@odyssey365/cli 0.2.5 → 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,232 @@
1
+ /**
2
+ * 브리지가 부르는 서버 MCP 도구(설계 §15.3)와 대화 미디어 올리기 · 내려받기.
3
+ *
4
+ * 도구 이름 · 입력은 계약 그대로다 — 서버(functions_v2)가 정본. 결과는 structuredContent(없으면 텍스트 JSON)를 쓴다.
5
+ */
6
+ import { createReadStream, openSync, readSync, closeSync, statSync, mkdirSync, writeFileSync } from 'node:fs';
7
+ import { basename, extname, join } from 'node:path';
8
+ import { execFileSync } from 'node:child_process';
9
+ import { mkdtempSync, existsSync, rmSync } from 'node:fs';
10
+ import { tmpdir } from 'node:os';
11
+ import { AgentMediaPolicy, paths, safeName } from './store.js';
12
+ export class ToolError extends Error {
13
+ tool;
14
+ constructor(tool, message) {
15
+ super(`${tool}: ${message}`);
16
+ this.tool = tool;
17
+ this.name = 'ToolError';
18
+ }
19
+ }
20
+ /** 도구 결과에서 객체를 꺼낸다. isError 면 던진다. */
21
+ export async function call(client, tool, args) {
22
+ const r = (await client.callTool(tool, args));
23
+ const text = (r?.content ?? []).filter((c) => c.type === 'text' || c.text).map((c) => c.text ?? '').join('\n');
24
+ if (r?.isError)
25
+ throw new ToolError(tool, text.replace(/^오류:\s*/, '') || '도구 오류');
26
+ if (r?.structuredContent && typeof r.structuredContent === 'object')
27
+ return r.structuredContent;
28
+ try {
29
+ return JSON.parse(text);
30
+ }
31
+ catch {
32
+ return {};
33
+ }
34
+ }
35
+ // ── 미디어 ──
36
+ const MIME = {
37
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp',
38
+ '.heic': 'image/heic', '.bmp': 'image/bmp', // SVG 는 서버가 받지 않는다(스크립트를 품을 수 있다)
39
+ '.mp4': 'video/mp4', '.mov': 'video/quicktime', '.webm': 'video/webm', '.m4v': 'video/x-m4v', '.mkv': 'video/x-matroska', '.avi': 'video/x-msvideo',
40
+ };
41
+ export const MEDIA_EXTS = Object.keys(MIME);
42
+ export function mimeOf(path) {
43
+ return MIME[extname(path).toLowerCase()] ?? null;
44
+ }
45
+ export function extOfMime(mime) {
46
+ const hit = Object.entries(MIME).find(([, m]) => m === mime);
47
+ return hit ? hit[0] : '.bin';
48
+ }
49
+ export function mediaLimit(mime) {
50
+ return mime.startsWith('video/') ? AgentMediaPolicy.videoMaxBytes : AgentMediaPolicy.imageMaxBytes;
51
+ }
52
+ /** GCS 이어 올리기 세션 URI 인가(`upload_id=` · `uploadType=resumable`). 아니면 PUT 서명 URL 로 본다. */
53
+ export function isResumableSession(url) {
54
+ return /[?&]upload_id=/.test(url) || /[?&]uploadType=resumable/.test(url);
55
+ }
56
+ const CHUNK = 32 * 256 * 1024; // 8MiB — GCS 이어 올리기는 256KiB 배수여야 한다
57
+ /**
58
+ * 파일 하나를 서버가 준 URL 로 올린다. 두 꼴을 다 받는다(서버가 어느 쪽을 줄지 아직 모른다):
59
+ * - PUT 서명 URL(V4 signed): PUT 본문 = 파일(스트림), Content-Type = mime
60
+ * - 이어 올리기 세션 URI: 8MiB 조각으로 PUT + Content-Range, 308 이면 Range 를 보고 이어 간다
61
+ */
62
+ export async function uploadFile(target, filePath, mime, fetchFn = fetch) {
63
+ const size = statSync(filePath).size;
64
+ if (isResumableSession(target.uploadUrl)) {
65
+ let offset = 0;
66
+ const fd = openSync(filePath, 'r');
67
+ try {
68
+ if (size === 0) {
69
+ const res = await fetchFn(target.uploadUrl, { method: 'PUT', headers: { 'Content-Length': '0', 'Content-Range': 'bytes */0', ...target.headers }, body: new Uint8Array(0) });
70
+ if (!res.ok)
71
+ throw new Error(`올리기 실패(${res.status})`);
72
+ return;
73
+ }
74
+ while (offset < size) {
75
+ const len = Math.min(CHUNK, size - offset);
76
+ const buf = Buffer.alloc(len);
77
+ readSync(fd, buf, 0, len, offset);
78
+ const end = offset + len - 1;
79
+ let res;
80
+ try {
81
+ res = await fetchFn(target.uploadUrl, {
82
+ method: 'PUT',
83
+ headers: { 'Content-Length': String(len), 'Content-Range': `bytes ${offset}-${end}/${size}`, ...target.headers },
84
+ body: new Uint8Array(buf),
85
+ });
86
+ }
87
+ catch (e) {
88
+ // 조각을 보내다 끊겼다 — 서버가 받은 만큼을 물어 그 뒤부터(한 번만; 또 끊기면 던져 outbox 가 다시).
89
+ res = await fetchFn(target.uploadUrl, { method: 'PUT', headers: { 'Content-Length': '0', 'Content-Range': `bytes */${size}` }, body: new Uint8Array(0) });
90
+ if (res.status !== 308 && !res.ok)
91
+ throw e;
92
+ }
93
+ if (res.status === 308) {
94
+ const range = res.headers.get('range'); // bytes=0-12345
95
+ const m = range ? /bytes=0-(\d+)/.exec(range) : null;
96
+ offset = m ? Number(m[1]) + 1 : offset; // Range 가 없으면 아무것도 안 받았다 — 같은 조각을 다시
97
+ if (!m)
98
+ await new Promise((r) => setTimeout(r, 500));
99
+ continue;
100
+ }
101
+ if (res.ok)
102
+ return; // 마지막 조각 — 200/201
103
+ throw new Error(`올리기 실패(${res.status}) ${await res.text().catch(() => '')}`.trim());
104
+ }
105
+ }
106
+ finally {
107
+ closeSync(fd);
108
+ }
109
+ return;
110
+ }
111
+ const stream = createReadStream(filePath);
112
+ let streamError = null;
113
+ stream.on('error', (e) => {
114
+ streamError = e; // 읽다 사라진 파일 — 처리 안 된 오류로 데몬이 죽지 않게
115
+ });
116
+ let res;
117
+ try {
118
+ res = await fetchFn(target.uploadUrl, {
119
+ method: target.method ?? 'PUT',
120
+ headers: { 'Content-Type': mime, 'Content-Length': String(size), ...target.headers },
121
+ body: stream,
122
+ duplex: 'half',
123
+ });
124
+ }
125
+ finally {
126
+ stream.destroy();
127
+ }
128
+ if (streamError)
129
+ throw streamError;
130
+ if (!res.ok)
131
+ throw new Error(`올리기 실패(${res.status}) ${(await res.text().catch(() => '')).slice(0, 200)}`.trim());
132
+ }
133
+ /** agent_media_upload_url → 올리기 → agent_media_complete. 큰 파일은 tooLarge 로 돌려준다(부르는 쪽이 한 줄로 알린다). */
134
+ export async function uploadMedia(client, bridgeId, sessionUid, filePath, direction = 'fromAgent', fetchFn) {
135
+ const mime = mimeOf(filePath) ?? 'application/octet-stream';
136
+ const bytes = statSync(filePath).size;
137
+ const fileName = basename(filePath);
138
+ // 한도 검사는 서버가 한다 — 넘으면 {tooLarge, mediaId}(자리표시 메타)를 준다. 0바이트는 서버가 받지 않는다.
139
+ if (bytes === 0)
140
+ return { tooLarge: false, fileName, bytes };
141
+ const r = await call(client, 'agent_media_upload_url', { bridgeId, sessionUid, fileName, mime, bytes, direction });
142
+ if (r.tooLarge)
143
+ return { tooLarge: true, fileName, bytes, ...(r.mediaId ? { mediaId: r.mediaId } : {}) };
144
+ if (!r.mediaId || !r.uploadUrl)
145
+ throw new ToolError('agent_media_upload_url', '올리기 주소가 없다');
146
+ await uploadFile({ uploadUrl: r.uploadUrl, ...(r.method ? { method: r.method } : {}), ...(r.headers ? { headers: r.headers } : {}) }, filePath, mime, fetchFn);
147
+ // 영상이면 첫 장면(포스터)을 만들어 함께 올린다 — 앱은 누르기 전엔 영상을 받지 않으니 포스터가 없으면 빈 칸이다(261122 E2E).
148
+ const posterPath = mime.startsWith('video/') ? await uploadPoster(client, bridgeId, sessionUid, filePath, r.mediaId, fetchFn).catch(() => null) : null;
149
+ await call(client, 'agent_media_complete', { bridgeId, sessionUid, mediaId: r.mediaId, ...(posterPath ? { posterPath } : {}) });
150
+ return { mediaId: r.mediaId, fileName, bytes };
151
+ }
152
+ /** 영상의 첫 장면 PNG/JPG — ffmpeg 가 있으면 그것으로, 없으면 macOS 기본 QuickLook(qlmanage). 못 만들면 null. */
153
+ export function makePoster(videoPath) {
154
+ const dir = mkdtempSync(join(tmpdir(), 'odyssey-poster-'));
155
+ const cleanup = () => rmSync(dir, { recursive: true, force: true });
156
+ try {
157
+ const out = join(dir, 'poster.jpg');
158
+ execFileSync('ffmpeg', ['-y', '-loglevel', 'error', '-ss', '0.5', '-i', videoPath, '-frames:v', '1', '-vf', 'scale=720:-2', out], { timeout: 20_000, stdio: 'ignore' });
159
+ if (existsSync(out))
160
+ return { path: out, cleanup };
161
+ }
162
+ catch {
163
+ // ffmpeg 없음 → 아래로
164
+ }
165
+ if (process.platform === 'darwin') {
166
+ try {
167
+ execFileSync('qlmanage', ['-t', '-s', '720', '-o', dir, videoPath], { timeout: 20_000, stdio: 'ignore' });
168
+ const out = join(dir, `${basename(videoPath)}.png`);
169
+ if (existsSync(out))
170
+ return { path: out, cleanup };
171
+ }
172
+ catch {
173
+ // 썸네일 실패 — 포스터 없이
174
+ }
175
+ }
176
+ cleanup();
177
+ return null;
178
+ }
179
+ async function uploadPoster(client, bridgeId, sessionUid, videoPath, videoMediaId, fetchFn) {
180
+ const poster = makePoster(videoPath);
181
+ if (!poster)
182
+ return null;
183
+ try {
184
+ const mime = mimeOf(poster.path) ?? 'image/png';
185
+ const bytes = statSync(poster.path).size;
186
+ const p = await call(client, 'agent_media_upload_url', { bridgeId, sessionUid, fileName: basename(poster.path), mime, bytes, direction: 'fromAgent', posterOf: videoMediaId });
187
+ if (p.tooLarge || !p.uploadUrl || !p.storagePath)
188
+ return null;
189
+ await uploadFile({ uploadUrl: p.uploadUrl, ...(p.method ? { method: p.method } : {}), ...(p.headers ? { headers: p.headers } : {}) }, poster.path, mime, fetchFn);
190
+ return p.storagePath;
191
+ }
192
+ finally {
193
+ poster.cleanup();
194
+ }
195
+ }
196
+ /** 앱이 보낸 미디어 하나를 `~/.odyssey/agent/media/<세션>/` 에 받는다 → 로컬 경로. */
197
+ export async function downloadMedia(client, bridgeId, sessionUid, ref, server) {
198
+ const r = await call(client, 'agent_media_download_url', {
199
+ bridgeId,
200
+ sessionUid,
201
+ ...(ref.mediaId ? { mediaId: ref.mediaId } : { storagePath: ref.storagePath }),
202
+ });
203
+ const url = r.url ?? r.downloadUrl;
204
+ if (!url)
205
+ throw new ToolError('agent_media_download_url', '읽기 주소가 없다');
206
+ const dir = paths.media(sessionUid);
207
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
208
+ const tail = (ref.storagePath ?? ref.mediaId ?? 'media').split('/').pop() ?? 'media';
209
+ let name = safeName(r.fileName ?? tail);
210
+ if (!extname(name))
211
+ name += extOfMime(r.mime);
212
+ const target = join(dir, name);
213
+ const res = await fetch(url, { signal: AbortSignal.timeout(10 * 60_000) }).catch((e) => {
214
+ throw new Error(`내려받기 실패: ${e.message} (${server})`);
215
+ });
216
+ if (!res.ok)
217
+ throw new Error(`내려받기 실패(${res.status})`);
218
+ writeFileSync(target, Buffer.from(await res.arrayBuffer()), { mode: 0o600 });
219
+ // 앱이 보낸 영상은 앱이 포스터를 못 만든다(썸네일 도구 없음) — 여기서 만들어 그 말풍선에 붙인다. 실패해도 턴은 그대로.
220
+ const mediaId = r.mediaId ?? ref.mediaId;
221
+ if (mediaId && (r.mime ?? mimeOf(target) ?? '').startsWith('video/')) {
222
+ try {
223
+ const posterPath = await uploadPoster(client, bridgeId, sessionUid, target, mediaId);
224
+ if (posterPath)
225
+ await call(client, 'agent_media_complete', { bridgeId, sessionUid, mediaId, posterPath });
226
+ }
227
+ catch {
228
+ // 포스터 없이도 영상은 넘어간다
229
+ }
230
+ }
231
+ return target;
232
+ }