@dicamo/flint-ai-bridge 1.0.0 → 1.0.1

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/README.md CHANGED
@@ -2,12 +2,12 @@
2
2
 
3
3
  FLiNT CMS와 내 PC에 설치된 Claude Code 또는 Codex를 연결하는 도구입니다.
4
4
 
5
- Claude Code를 통한 AI 대화와 CMS 읽기 전용 조회를 지원합니다. Codex는 설치 상태 확인만 지원하며, 채팅 실행은 아직 지원하지 않습니다.
5
+ Claude Code를 통한 AI 대화와 CMS 읽기 전용 조회를 지원합니다. Claude Code·Codex·Gemini CLI의 설치 상태와 버전을 자동으로 확인합니다. 현재 CMS 채팅 실행은 Claude Code만 지원하며, Codex와 Gemini는 준비 중으로 표시합니다.
6
6
 
7
7
  ## 준비 사항
8
8
 
9
9
  - Node.js 22 이상
10
- - Claude Code **2.1.285** 설치 및 구독 계정 로그인(현재 채팅 실행 검증 버전)
10
+ - Claude Code **2.1.285 또는 2.1.286** 설치 및 구독 계정 로그인(현재 채팅 실행 검증 버전)
11
11
  - FLiNT CMS 계정과 AI 어시스턴트 사용 권한
12
12
  - 관리자가 안내한 CMS 주소와 서버 주소
13
13
 
@@ -38,10 +38,10 @@ npx @dicamo/flint-ai-bridge@latest configure \
38
38
  ### 2. 브리지 실행
39
39
 
40
40
  ```sh
41
- npx @dicamo/flint-ai-bridge@1.0.0 serve --enable-chat
41
+ npx @dicamo/flint-ai-bridge@1.0.1 start --enable-chat
42
42
  ```
43
43
 
44
- 연결하는 동안 터미널을 열어 두세요. macOS에서는 PC 승인 창으로 연결할 수 있으며, 터미널의 6자리 코드는 대체 연결 수단입니다.
44
+ 실행 완료 후 터미널을 닫아도 브리지는 백그라운드에서 계속 동작합니다. macOS에서는 PC 승인 창으로 연결할 수 있으며, 터미널의 6자리 코드는 대체 연결 수단입니다.
45
45
 
46
46
  ### 3. CMS에서 연결
47
47
 
@@ -54,7 +54,7 @@ npx @dicamo/flint-ai-bridge@1.0.0 serve --enable-chat
54
54
 
55
55
  ## CMS 데이터 질문하기
56
56
 
57
- 위의 `serve --enable-chat` 명령으로 실행하면 CMS에서 채팅을 사용할 수 있습니다. 이 옵션을 생략하면 연결 및 계정 인증만 활성화됩니다.
57
+ 위의 `start --enable-chat` 명령으로 실행하면 CMS에서 채팅을 사용할 수 있습니다. 이 옵션을 생략하면 연결 및 계정 인증만 활성화됩니다.
58
58
 
59
59
  회사·매장·단말·미디어·씬·사용자·로그인 이력·자동화·앱·휴무일·3D 맵과 대시보드/미디어 재생 통계를 질문할 수 있습니다. 예를 들어 “최근 등록된 단말 10대”, “오프라인 단말은 총 몇 대?”, “이번 주 미디어 재생 통계”를 물어보세요.
60
60
 
@@ -64,7 +64,14 @@ npx @dicamo/flint-ai-bridge@1.0.0 serve --enable-chat
64
64
 
65
65
  자동 재연결과 브라우저 연결 정보 저장은 하지 않습니다. 연결이 끊기면 브리지를 실행하고 CMS에서 **다시 찾기 → 이 PC에 연결**을 눌러 다시 승인하세요. 승인 창은 60초 후 만료됩니다.
66
66
 
67
- 브리지를 종료하려면 터미널에서 `Ctrl+C`를 누르세요.
67
+ 실행 상태 확인과 종료:
68
+
69
+ ```sh
70
+ npx @dicamo/flint-ai-bridge@1.0.1 status
71
+ npx @dicamo/flint-ai-bridge@1.0.1 stop
72
+ ```
73
+
74
+ PC 재시작 후에는 `start --enable-chat`을 다시 실행하세요. 자동 로그인 실행은 등록하지 않습니다. 실행 오류와 대체 연결 코드는 `~/.flint-ai-bridge/bridge.log`에서 확인할 수 있습니다. 터미널에 직접 로그를 보려면 `serve --enable-chat`으로 실행하고 `Ctrl+C`로 종료할 수 있습니다.
68
75
 
69
76
  현재 CMS와의 연결을 해제하려면 Flint AI의 **페어링 해제**를 누르세요.
70
77
  이 PC의 모든 CMS 연결을 해제하려면 다음 명령을 실행하세요.
package/dist/cli.js CHANGED
@@ -6,20 +6,156 @@ import {
6
6
  RESOURCES
7
7
  } from "./chunk-QMPCIDA7.js";
8
8
 
9
+ // src/cli.ts
10
+ import { fileURLToPath as fileURLToPath2 } from "url";
11
+
12
+ // src/background.ts
13
+ import { createServer } from "http";
14
+ import { randomBytes, timingSafeEqual } from "crypto";
15
+ import { spawn } from "child_process";
16
+ import { chmod, mkdir, open, readFile, rename, unlink } from "fs/promises";
17
+ import { join } from "path";
18
+ import { z } from "zod";
19
+ var runtimeSchema = z.object({ port: z.number().int().min(1).max(65535), token: z.string().regex(/^[a-f0-9]{64}$/), pid: z.number().int().positive() });
20
+ async function control(directory, action) {
21
+ const runtime = runtimeSchema.parse(JSON.parse(await readFile(join(directory, "runtime.json"), "utf8")));
22
+ const res = await fetch(`http://127.0.0.1:${runtime.port}/${action}`, { method: "POST", headers: { Authorization: `Bearer ${runtime.token}` }, redirect: "error", signal: AbortSignal.timeout(2e3) });
23
+ if (!res.ok) throw new Error("Bridge control request failed");
24
+ return z.object({ running: z.boolean(), port: z.number().optional(), chat: z.boolean().optional(), pid: z.number().optional() }).parse(await res.json());
25
+ }
26
+ async function backgroundStatus(directory) {
27
+ try {
28
+ return await control(directory, "status");
29
+ } catch {
30
+ try {
31
+ await readFile(join(directory, "instance.lock"));
32
+ return { running: false, unavailable: true };
33
+ } catch {
34
+ return { running: false };
35
+ }
36
+ }
37
+ }
38
+ async function stopBackground(directory) {
39
+ const state = await backgroundStatus(directory);
40
+ if (state.unavailable) throw new Error("Bridge control is unavailable but an instance lock exists. Check bridge.log and the running bridge; no process was killed.");
41
+ if (!state.running) return false;
42
+ await control(directory, "stop");
43
+ for (let i = 0; i < 100; i++) {
44
+ try {
45
+ await readFile(join(directory, "instance.lock"));
46
+ } catch (error) {
47
+ if (error.code === "ENOENT") return true;
48
+ throw error;
49
+ }
50
+ await new Promise((resolve2) => setTimeout(resolve2, 100));
51
+ }
52
+ throw new Error("Bridge is still shutting down. Check status before starting again.");
53
+ }
54
+ async function serveControl(directory, status, shutdown) {
55
+ const token = randomBytes(32).toString("hex");
56
+ const runtimePath = join(directory, "runtime.json");
57
+ const server = createServer((req, res) => {
58
+ const address2 = server.address();
59
+ const port = address2 && typeof address2 !== "string" ? address2.port : 0;
60
+ const supplied = Buffer.from(req.headers.authorization ?? ""), expected = Buffer.from(`Bearer ${token}`);
61
+ if (req.method !== "POST" || req.headers.origin || req.headers.host !== `127.0.0.1:${port}` || supplied.length !== expected.length || !timingSafeEqual(supplied, expected) || !["/status", "/stop"].includes(req.url ?? "")) {
62
+ res.writeHead(403).end();
63
+ return;
64
+ }
65
+ res.setHeader("Content-Type", "application/json");
66
+ res.setHeader("Cache-Control", "no-store");
67
+ res.end(JSON.stringify({ running: true, ...status, pid: process.pid }));
68
+ if (req.url === "/stop") void shutdown().catch(() => {
69
+ process.exitCode = 1;
70
+ });
71
+ });
72
+ await new Promise((resolve2, reject) => {
73
+ server.once("error", reject);
74
+ server.listen(0, "127.0.0.1", resolve2);
75
+ });
76
+ const address = server.address();
77
+ if (!address || typeof address === "string") throw new Error("Control startup failed");
78
+ const temporary = join(directory, `runtime-${token}.tmp`);
79
+ try {
80
+ await mkdir(directory, { recursive: true, mode: 448 });
81
+ const file = await open(temporary, "wx", 384);
82
+ try {
83
+ await file.writeFile(JSON.stringify({ port: address.port, token, pid: process.pid }));
84
+ } finally {
85
+ await file.close();
86
+ }
87
+ await rename(temporary, runtimePath);
88
+ } catch (error) {
89
+ server.close();
90
+ await unlink(temporary).catch(() => {
91
+ });
92
+ throw error;
93
+ }
94
+ return async () => {
95
+ await new Promise((resolve2) => {
96
+ server.close(() => resolve2());
97
+ server.closeIdleConnections();
98
+ });
99
+ try {
100
+ const current = JSON.parse(await readFile(runtimePath, "utf8"));
101
+ if (current.token === token) await unlink(runtimePath);
102
+ } catch (error) {
103
+ if (error.code !== "ENOENT") throw error;
104
+ }
105
+ };
106
+ }
107
+ async function startBackground(directory, entry, chat) {
108
+ const previous = await backgroundStatus(directory);
109
+ if (previous.running) {
110
+ if (chat && !previous.chat) throw new Error("Bridge is running without chat. Run stop, then start --enable-chat.");
111
+ return previous;
112
+ }
113
+ await mkdir(directory, { recursive: true, mode: 448 });
114
+ const log = await open(join(directory, "bridge.log"), "a", 384);
115
+ await chmod(join(directory, "bridge.log"), 384);
116
+ try {
117
+ const child = spawn(process.execPath, [entry, "serve", "--data-dir", directory, ...chat ? ["--enable-chat"] : []], { detached: true, stdio: ["ignore", log.fd, log.fd, "ipc"], windowsHide: true });
118
+ return await new Promise((resolve2, reject) => {
119
+ const timer = setTimeout(() => {
120
+ child.kill();
121
+ finish(new Error(`Bridge startup timed out. Check ${join(directory, "bridge.log")}`));
122
+ }, 3e4);
123
+ let done = false;
124
+ const finish = (error, state) => {
125
+ if (done) return;
126
+ done = true;
127
+ clearTimeout(timer);
128
+ if (child.connected) child.disconnect();
129
+ child.unref();
130
+ if (error) reject(error);
131
+ else resolve2(state);
132
+ };
133
+ child.once("error", (error) => finish(error));
134
+ child.once("exit", () => finish(new Error(`Bridge startup failed. Check ${join(directory, "bridge.log")}`)));
135
+ child.on("message", (message) => {
136
+ const result = z.object({ type: z.literal("bridge.ready"), port: z.number(), chat: z.boolean() }).safeParse(message);
137
+ if (result.success) finish(void 0, { running: true, port: result.data.port, chat: result.data.chat, pid: child.pid });
138
+ });
139
+ });
140
+ } finally {
141
+ await log.close();
142
+ }
143
+ }
144
+
9
145
  // src/cli.ts
10
146
  import { homedir } from "os";
11
- import { join as join2, resolve } from "path";
147
+ import { join as join3, resolve } from "path";
12
148
  import { parseArgs } from "util";
13
149
  import { watchFile, unwatchFile } from "fs";
14
- import { access, writeFile as writeFile3, mkdir as mkdir2, unlink as unlink2 } from "fs/promises";
150
+ import { access, writeFile as writeFile3, mkdir as mkdir3, unlink as unlink3 } from "fs/promises";
15
151
 
16
152
  // src/instance.ts
17
- import { open, readFile, unlink } from "fs/promises";
153
+ import { open as open2, readFile as readFile2, unlink as unlink2 } from "fs/promises";
18
154
  import { randomUUID } from "crypto";
19
155
  async function acquireInstance(path) {
20
156
  const nonce = randomUUID();
21
157
  try {
22
- const handle = await open(path, "wx", 384);
158
+ const handle = await open2(path, "wx", 384);
23
159
  try {
24
160
  await handle.writeFile(JSON.stringify({ pid: process.pid, nonce }));
25
161
  } finally {
@@ -31,7 +167,7 @@ async function acquireInstance(path) {
31
167
  }
32
168
  return async () => {
33
169
  try {
34
- if (JSON.parse(await readFile(path, "utf8")).nonce === nonce) await unlink(path);
170
+ if (JSON.parse(await readFile2(path, "utf8")).nonce === nonce) await unlink2(path);
35
171
  } catch (error) {
36
172
  if (error.code !== "ENOENT") throw error;
37
173
  }
@@ -42,19 +178,19 @@ async function acquireInstance(path) {
42
178
  import { createInterface } from "readline";
43
179
 
44
180
  // src/config.ts
45
- import { mkdir, readFile as readFile2, rename, writeFile, chmod, lstat } from "fs/promises";
181
+ import { mkdir as mkdir2, readFile as readFile3, rename as rename2, writeFile, chmod as chmod2, lstat } from "fs/promises";
46
182
  import { dirname } from "path";
47
183
  import { randomUUID as randomUUID2 } from "crypto";
48
- import { z } from "zod";
49
- var origin = z.string().url().refine((value) => {
184
+ import { z as z2 } from "zod";
185
+ var origin = z2.string().url().refine((value) => {
50
186
  const u = new URL(value);
51
187
  return u.origin === value && (u.protocol === "https:" || u.protocol === "http:" && ["localhost", "127.0.0.1"].includes(u.hostname));
52
188
  }, "Use an exact HTTPS origin, or HTTP loopback for development");
53
- var schema = z.object({
54
- version: z.literal(1),
55
- hostId: z.string().uuid(),
56
- servers: z.array(z.object({ id: z.string().regex(/^[a-z0-9-]{1,64}$/), url: origin, origins: z.array(origin).min(1) }).strict()).max(32),
57
- pairings: z.array(z.object({ id: z.string().uuid(), origin, tokenHash: z.string().regex(/^[a-f0-9]{64}$/), expiresAt: z.number().int().positive() }).strict()).max(100)
189
+ var schema = z2.object({
190
+ version: z2.literal(1),
191
+ hostId: z2.string().uuid(),
192
+ servers: z2.array(z2.object({ id: z2.string().regex(/^[a-z0-9-]{1,64}$/), url: origin, origins: z2.array(origin).min(1) }).strict()).max(32),
193
+ pairings: z2.array(z2.object({ id: z2.string().uuid(), origin, tokenHash: z2.string().regex(/^[a-f0-9]{64}$/), expiresAt: z2.number().int().positive() }).strict()).max(100)
58
194
  }).strict();
59
195
  function parseConfig(raw) {
60
196
  const config = schema.parse(raw);
@@ -66,7 +202,7 @@ function parseConfig(raw) {
66
202
  async function readConfig(path) {
67
203
  try {
68
204
  if ((await lstat(path)).isSymbolicLink()) throw new Error("Config symlinks are not supported");
69
- return parseConfig(JSON.parse(await readFile2(path, "utf8")));
205
+ return parseConfig(JSON.parse(await readFile3(path, "utf8")));
70
206
  } catch (error) {
71
207
  if (error.code !== "ENOENT") throw error;
72
208
  return { version: 1, hostId: randomUUID2(), servers: [], pairings: [] };
@@ -75,37 +211,37 @@ async function readConfig(path) {
75
211
  async function saveConfig(path, config) {
76
212
  parseConfig(config);
77
213
  const dir = dirname(path);
78
- await mkdir(dir, { recursive: true, mode: 448 });
214
+ await mkdir2(dir, { recursive: true, mode: 448 });
79
215
  if ((await lstat(dir)).isSymbolicLink()) throw new Error("Config directory symlinks are not supported");
80
216
  if (process.platform !== "win32" && ((await lstat(dir)).mode & 63) !== 0) {
81
217
  throw new Error("Use a dedicated private data directory (mode 0700)");
82
218
  }
83
219
  const temp = `${path}.${randomUUID2()}.tmp`;
84
220
  await writeFile(temp, JSON.stringify(config, null, 2) + "\n", { mode: 384, flag: "wx" });
85
- await rename(temp, path);
86
- await chmod(path, 384);
221
+ await rename2(temp, path);
222
+ await chmod2(path, 384);
87
223
  }
88
224
 
89
225
  // src/cmsTurn.ts
90
226
  import { mkdtemp, writeFile as writeFile2, rm } from "fs/promises";
91
- import { join } from "path";
227
+ import { join as join2 } from "path";
92
228
  import { fileURLToPath } from "url";
93
- import { z as z7 } from "zod";
229
+ import { z as z8 } from "zod";
94
230
 
95
231
  // src/cmsMcp.ts
96
- import { createServer } from "http";
97
- import { randomBytes as randomBytes2, timingSafeEqual as timingSafeEqual2 } from "crypto";
98
- import { z as z5 } from "zod";
232
+ import { createServer as createServer2 } from "http";
233
+ import { randomBytes as randomBytes3, timingSafeEqual as timingSafeEqual3 } from "crypto";
234
+ import { z as z6 } from "zod";
99
235
 
100
236
  // src/cmsTools.ts
101
- import { z as z4 } from "zod";
237
+ import { z as z5 } from "zod";
102
238
 
103
239
  // src/auth.ts
104
240
  import { randomUUID as randomUUID4 } from "crypto";
105
- import { z as z2 } from "zod";
241
+ import { z as z3 } from "zod";
106
242
 
107
243
  // src/security.ts
108
- import { createHash, randomInt, randomBytes, randomUUID as randomUUID3, timingSafeEqual } from "crypto";
244
+ import { createHash, randomInt, randomBytes as randomBytes2, randomUUID as randomUUID3, timingSafeEqual as timingSafeEqual2 } from "crypto";
109
245
  var BridgeError = class extends Error {
110
246
  constructor(code) {
111
247
  super(code);
@@ -140,7 +276,7 @@ var Pairing = class {
140
276
  if (now < this.nextAttempt) throw new BridgeError("rate_limited");
141
277
  this.nextAttempt = now + 1e3;
142
278
  if (!this.codeHash || now >= this.expiresAt) throw new BridgeError("pair_expired");
143
- if (!timingSafeEqual(Buffer.from(hash(code), "hex"), Buffer.from(this.codeHash, "hex"))) {
279
+ if (!timingSafeEqual2(Buffer.from(hash(code), "hex"), Buffer.from(this.codeHash, "hex"))) {
144
280
  if (++this.failures >= 5) {
145
281
  this.codeHash = "";
146
282
  this.lockedUntil = now + 6e4;
@@ -154,7 +290,7 @@ var Pairing = class {
154
290
  /** Call only after explicit local approval or a successful code exchange. */
155
291
  grant(origin2) {
156
292
  const now = this.now();
157
- const bridgeToken = randomBytes(32).toString("base64url");
293
+ const bridgeToken = randomBytes2(32).toString("base64url");
158
294
  const pairing = { id: randomUUID3(), origin: origin2, tokenHash: hash(bridgeToken), expiresAt: now + 30 * 864e5 };
159
295
  this.config.pairings = this.config.pairings.filter((p) => p.expiresAt > now);
160
296
  if (this.config.pairings.length >= 100) throw new BridgeError("pair_locked");
@@ -163,20 +299,20 @@ var Pairing = class {
163
299
  }
164
300
  authenticate(token, origin2) {
165
301
  const tokenHash = hash(token);
166
- return this.config.pairings.find((p) => p.origin === origin2 && p.expiresAt > this.now() && timingSafeEqual(Buffer.from(p.tokenHash, "hex"), Buffer.from(tokenHash, "hex")));
302
+ return this.config.pairings.find((p) => p.origin === origin2 && p.expiresAt > this.now() && timingSafeEqual2(Buffer.from(p.tokenHash, "hex"), Buffer.from(tokenHash, "hex")));
167
303
  }
168
304
  };
169
305
 
170
306
  // src/auth.ts
171
- var scopeSchema = z2.object({
172
- company_id: z2.number().int().nullable(),
173
- company_ids: z2.array(z2.number().int()).nullable(),
174
- store_ids: z2.array(z2.number().int()).nullable(),
175
- super_user: z2.boolean().nullable(),
176
- is_owner: z2.boolean().optional(),
177
- include_descendants: z2.boolean().nullable().optional()
307
+ var scopeSchema = z3.object({
308
+ company_id: z3.number().int().nullable(),
309
+ company_ids: z3.array(z3.number().int()).nullable(),
310
+ store_ids: z3.array(z3.number().int()).nullable(),
311
+ super_user: z3.boolean().nullable(),
312
+ is_owner: z3.boolean().optional(),
313
+ include_descendants: z3.boolean().nullable().optional()
178
314
  });
179
- var claimSchema = z2.array(z2.object({ name: z2.string() }));
315
+ var claimSchema = z3.array(z3.object({ name: z3.string() }));
180
316
  function permissionsRevision(user) {
181
317
  const scope = scopeSchema.parse(user.scope);
182
318
  if (scope.company_ids !== null) scope.company_ids = [...new Set(scope.company_ids)].sort((a, b) => a - b);
@@ -207,11 +343,11 @@ var verifySupabase = async ({ url, anonKey, accessToken }) => {
207
343
  return JSON.parse(body);
208
344
  };
209
345
  try {
210
- const user = z2.object({ id: z2.string().uuid(), app_metadata: z2.object({ is_owner: z2.boolean().optional() }).passthrough().optional() }).parse(await get("/auth/v1/user"));
211
- const payload = z2.object({ exp: z2.number() }).parse(JSON.parse(Buffer.from(accessToken.split(".")[1] ?? "", "base64url").toString()));
346
+ const user = z3.object({ id: z3.string().uuid(), app_metadata: z3.object({ is_owner: z3.boolean().optional() }).passthrough().optional() }).parse(await get("/auth/v1/user"));
347
+ const payload = z3.object({ exp: z3.number() }).parse(JSON.parse(Buffer.from(accessToken.split(".")[1] ?? "", "base64url").toString()));
212
348
  if (payload.exp * 1e3 <= Date.now()) throw new BridgeError("auth_invalid");
213
349
  const claims = claimSchema.parse(await get("/rest/v1/rpc/load_my_claim_names", true)).map((r) => r.name);
214
- const scopes = z2.array(scopeSchema).length(1).parse(await get("/rest/v1/rpc/get_my_scope", true));
350
+ const scopes = z3.array(scopeSchema).length(1).parse(await get("/rest/v1/rpc/get_my_scope", true));
215
351
  const scope = { ...scopes[0], ...user.app_metadata?.is_owner === true ? { is_owner: true } : scopes[0].is_owner !== void 0 ? { is_owner: false } : {} };
216
352
  if (!scope.is_owner && !claims.includes(AI_CLAIM)) throw new BridgeError("auth_forbidden");
217
353
  return { userId: user.id, scope, claims, expiresAt: payload.exp * 1e3 };
@@ -246,7 +382,7 @@ async function authenticate(options) {
246
382
  }
247
383
 
248
384
  // src/cmsCatalog.ts
249
- import { z as z3 } from "zod";
385
+ import { z as z4 } from "zod";
250
386
  var dataset = (name, label, resource, table, fields, scope, order = ["id"]) => ({ name, label, resource, table, fields: fields.split(","), ...scope, order });
251
387
  var CMS_DATASETS = [
252
388
  dataset("devices", "\uB2E8\uB9D0 \uC0C1\uC138 \uC815\uBCF4", "devices", "v_devices", "id,name,company_id,store_id,online,created_at,updated_at,keep_alive,width,height,network,cpu_usage,memory_usage,service_version,service_version_code,player_app_version,player_app_version_code,supported_32bit_abis,supported_64bit_abis,density,ip,mac,ssid,ssaid,vpn_status,remote_count,uptime,runtime,screen_on,foreground_app,battery,os_time", { company: "company_id", store: "store_id" }),
@@ -273,28 +409,28 @@ var CMS_DATASETS = [
273
409
  dataset("device_online_daily", "\uB2E8\uB9D0 \uC77C\uBCC4 \uAC00\uB3D9 \uD1B5\uACC4", "devices", "v_device_online_daily", "device_id,day,online_seconds,outage_count", { parent: { dataset: "devices", field: "device_id" } }, ["day", "device_id"]),
274
410
  dataset("device_online_sessions", "\uB2E8\uB9D0 \uC811\uC18D \uC774\uB825", "devices", "v_device_online_sessions", "device_id,online,started_at,ended_at", { parent: { dataset: "devices", field: "device_id" } }, ["started_at", "device_id"])
275
411
  ];
276
- var queryArgs = z3.object({
277
- dataset: z3.string().min(1).max(80),
278
- fields: z3.array(z3.string().max(80)).min(1).max(50).optional(),
279
- filters: z3.array(z3.object({ field: z3.string().max(80), op: z3.enum(["eq", "neq", "gt", "gte", "lt", "lte", "ilike", "is"]), value: z3.union([z3.string().max(500), z3.number().finite(), z3.boolean(), z3.null()]) }).strict()).max(12).default([]),
280
- order: z3.array(z3.object({ field: z3.string().max(80), direction: z3.enum(["asc", "desc"]) }).strict()).max(3).default([]),
281
- limit: z3.number().int().min(1).max(50).default(20),
282
- offset: z3.number().int().min(0).max(1e5).default(0),
283
- countOnly: z3.boolean().default(false)
412
+ var queryArgs = z4.object({
413
+ dataset: z4.string().min(1).max(80),
414
+ fields: z4.array(z4.string().max(80)).min(1).max(50).optional(),
415
+ filters: z4.array(z4.object({ field: z4.string().max(80), op: z4.enum(["eq", "neq", "gt", "gte", "lt", "lte", "ilike", "is"]), value: z4.union([z4.string().max(500), z4.number().finite(), z4.boolean(), z4.null()]) }).strict()).max(12).default([]),
416
+ order: z4.array(z4.object({ field: z4.string().max(80), direction: z4.enum(["asc", "desc"]) }).strict()).max(3).default([]),
417
+ limit: z4.number().int().min(1).max(50).default(20),
418
+ offset: z4.number().int().min(0).max(1e5).default(0),
419
+ countOnly: z4.boolean().default(false)
284
420
  }).strict();
285
421
  var CATALOG_TOOLS = [
286
422
  { name: "describe_cms_queries", description: "\uD604\uC7AC \uAD8C\uD55C\uC73C\uB85C \uC870\uD68C \uAC00\uB2A5\uD55C CMS \uB370\uC774\uD130\uC14B\uACFC \uD544\uB4DC, \uD544\uD130 \uBC0F \uBD80\uBAA8 ID \uC870\uAC74\uC744 \uD655\uC778\uD569\uB2C8\uB2E4. \uC9C8\uBB38\uC5D0 \uD544\uC694\uD55C \uC815\uBCF4\uAC00 \uAE30\uBCF8 \uB2E8\uB9D0 \uB3C4\uAD6C\uC5D0 \uC5C6\uC73C\uBA74 \uC774 \uB3C4\uAD6C\uB97C \uBA3C\uC800 \uC0AC\uC6A9\uD558\uC138\uC694.", inputSchema: { type: "object", properties: {}, additionalProperties: false } },
287
423
  { name: "query_cms", description: "CMS \uB370\uC774\uD130 \uC870\uD68C \uBC0F \uC815\uD655\uD55C \uAC1C\uC218 \uC9D1\uACC4. describe_cms_queries\uC758 \uB370\uC774\uD130\uC14B/\uD544\uB4DC\uB9CC \uC0AC\uC6A9\uD569\uB2C8\uB2E4. \uB0A0\uC9DC\uB294 ISO \uD615\uC2DD, \uC774\uB984 \uAC80\uC0C9\uC740 ilike\uC640 * \uD328\uD134, \uCD5C\uADFC \uB4F1\uB85D\uC740 created_at desc. filters\uB294 AND, countOnly\uB294 \uAC19\uC740 \uD544\uD130\uC758 \uC804\uCCB4 \uAC1C\uC218\uB9CC \uBC18\uD658\uD569\uB2C8\uB2E4. hasMore\uC774\uBA74 \uC77C\uBD80 \uACB0\uACFC\uC774\uBA70 nextOffset\uC73C\uB85C \uACC4\uC18D \uC870\uD68C\uD569\uB2C8\uB2E4.", inputSchema: { type: "object", properties: { dataset: { type: "string" }, fields: { type: "array", items: { type: "string" } }, filters: { type: "array", items: { type: "object", properties: { field: { type: "string" }, op: { type: "string", enum: ["eq", "neq", "gt", "gte", "lt", "lte", "ilike", "is"] }, value: { type: ["string", "number", "boolean", "null"] } }, required: ["field", "op", "value"], additionalProperties: false } }, order: { type: "array", items: { type: "object", properties: { field: { type: "string" }, direction: { type: "string", enum: ["asc", "desc"] } }, required: ["field", "direction"], additionalProperties: false } }, limit: { type: "integer", minimum: 1, maximum: 50 }, offset: { type: "integer", minimum: 0, maximum: 1e5 }, countOnly: { type: "boolean" } }, required: ["dataset"], additionalProperties: false } }
288
424
  ].map((tool) => ({ ...tool, annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false } }));
289
- var reportArgs = z3.object({ report: z3.enum(["dashboard", "media_log"]), companyIds: z3.array(z3.number().int().nonnegative()).min(1).max(100).optional(), storeId: z3.number().int().nonnegative().optional(), days: z3.number().int().min(1).max(90).default(7) }).strict();
425
+ var reportArgs = z4.object({ report: z4.enum(["dashboard", "media_log"]), companyIds: z4.array(z4.number().int().nonnegative()).min(1).max(100).optional(), storeId: z4.number().int().nonnegative().optional(), days: z4.number().int().min(1).max(90).default(7) }).strict();
290
426
  var REPORT_TOOL = { name: "get_cms_report", description: "\uB300\uC2DC\uBCF4\uB4DC(\uB2E8\uB9D0 \uAC00\uB3D9 \uCD94\uC774\xB7\uBBF8\uB514\uC5B4\xB7\uC52C \uC9D1\uACC4) \uB610\uB294 \uBBF8\uB514\uC5B4 \uC7AC\uC0DD \uD1B5\uACC4\uB97C \uC870\uD68C\uD569\uB2C8\uB2E4. \uD68C\uC0AC ID\uB97C \uC9C0\uC815\uD574 \uBC94\uC704\uB97C \uC881\uD790 \uC218 \uC788\uC2B5\uB2C8\uB2E4. \uB9E4\uC7A5 \uC81C\uD55C \uACC4\uC815\uC740 \uC811\uADFC \uAC00\uB2A5\uD55C storeId \uD558\uB098\uB97C \uC9C0\uC815\uD558\uC138\uC694. \uD1B5\uACC4 RPC\uAC00 \uC124\uCE58\uB41C \uC11C\uBC84\uC5D0\uC11C \uC0AC\uC6A9 \uAC00\uB2A5\uD569\uB2C8\uB2E4.", inputSchema: { type: "object", properties: { report: { type: "string", enum: ["dashboard", "media_log"] }, companyIds: { type: "array", items: { type: "integer", minimum: 0 }, minItems: 1, maxItems: 100 }, storeId: { type: "integer", minimum: 0 }, days: { type: "integer", minimum: 1, maximum: 90 } }, required: ["report"], additionalProperties: false }, annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false } };
291
427
 
292
428
  // src/cmsTools.ts
293
- var id = z4.number().int().nonnegative().safe();
294
- var deviceId = z4.string().min(1).max(256).regex(/^[^\u0000-\u001f\u007f]+$/);
295
- var companySchema = z4.object({ id, name: z4.string().max(500), parent_id: id.nullable() });
296
- var deviceSchema = z4.object({ id: deviceId, name: z4.string().max(500).nullable(), company_id: id.nullable(), store_id: id.nullable(), online: z4.boolean(), created_at: z4.string().max(100).nullable(), keep_alive: z4.string().max(100).nullable(), service_version: z4.string().max(100).nullable().optional(), player_app_version: z4.string().max(100).nullable().optional() });
297
- var listArgs = z4.object({ companyId: id.optional(), storeId: id.optional(), online: z4.boolean().optional(), limit: z4.number().int().min(1).max(50).default(20), afterId: deviceId.optional(), sort: z4.enum(["id", "newest"]).default("id"), offset: z4.number().int().min(0).max(1e5).default(0) }).strict().refine((input) => input.sort === "newest" ? !input.afterId : input.offset === 0, { message: "newest uses offset; id uses afterId" });
429
+ var id = z5.number().int().nonnegative().safe();
430
+ var deviceId = z5.string().min(1).max(256).regex(/^[^\u0000-\u001f\u007f]+$/);
431
+ var companySchema = z5.object({ id, name: z5.string().max(500), parent_id: id.nullable() });
432
+ var deviceSchema = z5.object({ id: deviceId, name: z5.string().max(500).nullable(), company_id: id.nullable(), store_id: id.nullable(), online: z5.boolean(), created_at: z5.string().max(100).nullable(), keep_alive: z5.string().max(100).nullable(), service_version: z5.string().max(100).nullable().optional(), player_app_version: z5.string().max(100).nullable().optional() });
433
+ var listArgs = z5.object({ companyId: id.optional(), storeId: id.optional(), online: z5.boolean().optional(), limit: z5.number().int().min(1).max(50).default(20), afterId: deviceId.optional(), sort: z5.enum(["id", "newest"]).default("id"), offset: z5.number().int().min(0).max(1e5).default(0) }).strict().refine((input) => input.sort === "newest" ? !input.afterId : input.offset === 0, { message: "newest uses offset; id uses afterId" });
298
434
  var LEGACY_TOOLS = [
299
435
  { name: "list_devices", description: "\uD604\uC7AC \uC0AC\uC6A9\uC790\uAC00 \uBCFC \uC218 \uC788\uB294 \uC2E4\uC81C \uB2E8\uB9D0\uC758 \uC774\uB984, \uB4F1\uB85D\uC77C(created_at), \uC628\uB77C\uC778 \uC0C1\uD0DC\uC640 \uB9C8\uC9C0\uB9C9 \uC5F0\uACB0 \uC2DC\uAC01\uC744 \uC870\uD68C\uD569\uB2C8\uB2E4. \uCD5C\uADFC \uB4F1\uB85D \uB2E8\uB9D0\uC740 sort=newest\uB85C \uC870\uD68C\uD558\uC138\uC694(\uB4F1\uB85D\uC77C \uB0B4\uB9BC\uCC28\uC21C, \uBBF8\uC0C1\uC740 \uB9C8\uC9C0\uB9C9). \uC774\uB54C \uB2E4\uC74C \uD398\uC774\uC9C0\uB294 nextOffset\uC744 offset\uC73C\uB85C \uC804\uB2EC\uD569\uB2C8\uB2E4. \uAE30\uBCF8 ID\uC21C \uB2E4\uC74C \uD398\uC774\uC9C0\uB294 nextAfterId\uB97C afterId\uB85C \uC804\uB2EC\uD569\uB2C8\uB2E4. hasMore=true\uBA74 \uC804\uCCB4 \uC9D1\uACC4\uAC00 \uC544\uB2D9\uB2C8\uB2E4. ID \uD06C\uAE30\uB098 \uBC84\uC804\uC73C\uB85C \uB4F1\uB85D\uC77C\uC744 \uCD94\uCE21\uD558\uC9C0 \uB9C8\uC138\uC694.", inputSchema: { type: "object", properties: { companyId: { type: "integer", minimum: 0 }, storeId: { type: "integer", minimum: 0 }, online: { type: "boolean" }, limit: { type: "integer", minimum: 1, maximum: 50 }, afterId: { type: "string", minLength: 1, maxLength: 256 }, sort: { type: "string", enum: ["id", "newest"] }, offset: { type: "integer", minimum: 0, maximum: 1e5 } }, additionalProperties: false } },
300
436
  { name: "get_device_status", description: "\uC811\uADFC \uAC00\uB2A5\uD55C \uC2E4\uC81C \uB2E8\uB9D0 \uD55C \uB300\uC758 \uB4F1\uB85D\uC77C(created_at)\uACFC \uC0C1\uD0DC\uB97C \uC870\uD68C\uD569\uB2C8\uB2E4.", inputSchema: { type: "object", properties: { deviceId: { type: "string", minLength: 1, maxLength: 256 } }, required: ["deviceId"], additionalProperties: false } },
@@ -345,7 +481,7 @@ var CmsReadTools = class {
345
481
  return allowed;
346
482
  }
347
483
  if (user.scope.include_descendants === false || !allowed.size) return allowed;
348
- const companies = z4.array(companySchema).max(999).parse(await this.read("companies", new URLSearchParams({ select: "id,name,parent_id", limit: "1001", order: "id.asc" })));
484
+ const companies = z5.array(companySchema).max(999).parse(await this.read("companies", new URLSearchParams({ select: "id,name,parent_id", limit: "1001", order: "id.asc" })));
349
485
  let changed = true;
350
486
  while (changed) {
351
487
  changed = false;
@@ -364,7 +500,7 @@ var CmsReadTools = class {
364
500
  let companyIds = input.companyIds ?? (allowed !== null ? [...allowed] : null);
365
501
  if (companyIds?.some((id2) => allowed !== null && !allowed.has(id2))) throw new Error("cms_scope_forbidden");
366
502
  if (companyIds === null) {
367
- const rows = z4.array(companySchema).max(999).parse(await this.read("companies", new URLSearchParams({ select: "id,name,parent_id", limit: "1001", order: "id.asc" })));
503
+ const rows = z5.array(companySchema).max(999).parse(await this.read("companies", new URLSearchParams({ select: "id,name,parent_id", limit: "1001", order: "id.asc" })));
368
504
  companyIds = rows.map((row) => row.id);
369
505
  }
370
506
  const stores = user.scope.super_user || user.scope.is_owner ? null : user.scope.store_ids;
@@ -409,7 +545,7 @@ var CmsReadTools = class {
409
545
  query.append(f.field, `${f.op}.${String(f.value)}`);
410
546
  }
411
547
  const page = await this.readPage(d.table, query, true);
412
- const rows = z4.array(z4.record(z4.string(), z4.unknown())).max(input.countOnly ? 0 : input.limit + 1).parse(page.rows);
548
+ const rows = z5.array(z5.record(z5.string(), z5.unknown())).max(input.countOnly ? 0 : input.limit + 1).parse(page.rows);
413
549
  for (const row of rows) {
414
550
  this.assertRowScope(d, row, allowed, stores);
415
551
  if (parentCheck && String(row.id) !== String(input.filters.find((f) => f.field === "id" && f.op === "eq")?.value)) throw new Error("cms_filter_violation");
@@ -428,7 +564,7 @@ var CmsReadTools = class {
428
564
  const o = this.options;
429
565
  o.assertActive();
430
566
  if (!CMS_TOOLS.some((tool) => tool.name === name)) throw new Error("cms_unknown_tool");
431
- const parsed = name === "get_cms_report" ? reportArgs.parse(args) : name === "query_cms" ? queryArgs.parse(args) : name === "list_devices" ? listArgs.parse(args) : name === "get_device_status" ? z4.object({ deviceId }).strict().parse(args) : z4.object({}).strict().parse(args);
567
+ const parsed = name === "get_cms_report" ? reportArgs.parse(args) : name === "query_cms" ? queryArgs.parse(args) : name === "list_devices" ? listArgs.parse(args) : name === "get_device_status" ? z5.object({ deviceId }).strict().parse(args) : z5.object({}).strict().parse(args);
432
568
  const user = await (o.verify ?? verifySupabase)(o.credentials);
433
569
  o.assertActive();
434
570
  if (user.userId !== o.userId || user.expiresAt <= Date.now() || !user.scope.is_owner && !user.claims.includes("enable:ai.assistant")) throw new Error("cms_auth_changed");
@@ -445,7 +581,7 @@ var CmsReadTools = class {
445
581
  if (!allowed.size) return { companies: [], hasMore: false };
446
582
  query2.set("id", `in.(${[...allowed].join(",")})`);
447
583
  }
448
- const rows2 = z4.array(companySchema).max(999).parse(await this.read("companies", query2));
584
+ const rows2 = z5.array(companySchema).max(999).parse(await this.read("companies", query2));
449
585
  if (allowed !== null && rows2.some((row) => !allowed.has(row.id))) throw new Error("cms_scope_violation");
450
586
  return { companies: rows2, hasMore: false };
451
587
  }
@@ -463,7 +599,7 @@ var CmsReadTools = class {
463
599
  if (input.storeId !== void 0) query.set("store_id", `eq.${input.storeId}`);
464
600
  else if (stores !== null) query.set("store_id", `in.(${stores.join(",")})`);
465
601
  if (input.online !== void 0) query.set("online", `eq.${input.online}`);
466
- const rows = z4.array(deviceSchema).max(limit + 1).parse(await this.read("v_devices", query));
602
+ const rows = z5.array(deviceSchema).max(limit + 1).parse(await this.read("v_devices", query));
467
603
  if (rows.some((row) => allowed !== null && (row.company_id === null || !allowed.has(row.company_id)) || stores !== null && (row.store_id === null || !stores.includes(row.store_id)))) throw new Error("cms_scope_violation");
468
604
  if (rows.some((row) => input.deviceId !== void 0 && row.id !== input.deviceId || input.companyId !== void 0 && row.company_id !== input.companyId || input.storeId !== void 0 && row.store_id !== input.storeId || input.online !== void 0 && row.online !== input.online)) throw new Error("cms_filter_violation");
469
605
  return { devices: rows.slice(0, limit), hasMore: rows.length > limit, nextAfterId: rows.length > limit && input.sort !== "newest" ? rows[limit - 1].id : null, nextOffset: rows.length > limit && input.sort === "newest" ? input.offset + limit : null };
@@ -472,16 +608,16 @@ var CmsReadTools = class {
472
608
 
473
609
  // src/cmsMcp.ts
474
610
  async function startCmsMcp(options) {
475
- const token = randomBytes2(32).toString("hex");
611
+ const token = randomBytes3(32).toString("hex");
476
612
  const service = new CmsReadTools(options);
477
613
  const tools = CMS_TOOLS.filter((t) => toolResource(t.name) === null || options.resources.includes(toolResource(t.name)));
478
614
  let pending = 0, calls = 0;
479
- const server = createServer(async (req, res) => {
615
+ const server = createServer2(async (req, res) => {
480
616
  const address2 = server.address();
481
617
  const port = address2 && typeof address2 !== "string" ? address2.port : 0;
482
618
  const supplied = Buffer.from(req.headers.authorization ?? "");
483
619
  const expected = Buffer.from(`Bearer ${token}`);
484
- if (req.url !== "/mcp" || req.method !== "POST" || req.headers.origin || req.headers.host !== `127.0.0.1:${port}` || supplied.length !== expected.length || !timingSafeEqual2(supplied, expected)) {
620
+ if (req.url !== "/mcp" || req.method !== "POST" || req.headers.origin || req.headers.host !== `127.0.0.1:${port}` || supplied.length !== expected.length || !timingSafeEqual3(supplied, expected)) {
485
621
  res.writeHead(403).end();
486
622
  return;
487
623
  }
@@ -500,7 +636,7 @@ async function startCmsMcp(options) {
500
636
  body += chunk;
501
637
  if (Buffer.byteLength(body) > 65536) throw new Error("large_request");
502
638
  }
503
- const input = z5.object({ jsonrpc: z5.literal("2.0"), id: z5.union([z5.string().max(200), z5.number().finite()]).optional(), method: z5.string().max(100), params: z5.unknown().optional() }).strict().parse(JSON.parse(body));
639
+ const input = z6.object({ jsonrpc: z6.literal("2.0"), id: z6.union([z6.string().max(200), z6.number().finite()]).optional(), method: z6.string().max(100), params: z6.unknown().optional() }).strict().parse(JSON.parse(body));
504
640
  if (input.id === void 0) {
505
641
  res.writeHead(204).end();
506
642
  return;
@@ -508,13 +644,13 @@ async function startCmsMcp(options) {
508
644
  requestId = input.id;
509
645
  let result;
510
646
  if (input.method === "initialize") {
511
- const params = z5.object({ protocolVersion: z5.string().max(30) }).passthrough().parse(input.params);
647
+ const params = z6.object({ protocolVersion: z6.string().max(30) }).passthrough().parse(input.params);
512
648
  result = { protocolVersion: params.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: "flint-cms", version: "1.0.0" } };
513
649
  } else if (input.method === "tools/list") result = { tools };
514
650
  else if (input.method === "ping") result = {};
515
651
  else if (input.method === "tools/call") {
516
652
  if (++calls > 64) throw new Error("tool_limit");
517
- const args = z5.object({ name: z5.string(), arguments: z5.unknown().optional(), _meta: z5.record(z5.string(), z5.unknown()).optional() }).strict().parse(input.params);
653
+ const args = z6.object({ name: z6.string(), arguments: z6.unknown().optional(), _meta: z6.record(z6.string(), z6.unknown()).optional() }).strict().parse(input.params);
518
654
  if (!tools.some((tool) => tool.name === args.name)) throw new Error("tool_forbidden");
519
655
  const label = { list_devices: "\uB2E8\uB9D0 \uBAA9\uB85D", get_device_status: "\uB2E8\uB9D0 \uC0C1\uD0DC", list_companies: "\uD68C\uC0AC \uBAA9\uB85D", describe_cms_queries: "\uC870\uD68C \uAE30\uB2A5", query_cms: "CMS \uB370\uC774\uD130", get_cms_report: "CMS \uD1B5\uACC4" }[args.name];
520
656
  options.onActivity?.(`${label} \uC870\uD68C \uC911\u2026`);
@@ -528,7 +664,7 @@ async function startCmsMcp(options) {
528
664
  options.onActivity?.(`${label} \uC870\uD68C \uC2E4\uD328`);
529
665
  const code = error instanceof Error ? error.message : "";
530
666
  const permission = ["cms_auth_changed", "cms_permissions_changed", "cms_tool_forbidden", "cms_scope_forbidden", "cms_scope_violation", "auth_forbidden"].includes(code);
531
- const message = code === "cms_parent_required" ? "\uC774 \uC870\uD68C\uC5D0\uB294 \uBD80\uBAA8 ID\uC758 eq \uD544\uD130\uAC00 \uD544\uC694\uD569\uB2C8\uB2E4. describe_cms_queries\uC5D0\uC11C requiredFilter\uB97C \uD655\uC778\uD558\uC138\uC694." : ["cms_invalid_field", "cms_invalid_filter", "cms_unknown_dataset"].includes(code) ? "\uC870\uD68C \uB370\uC774\uD130\uC14B \uB610\uB294 \uD544\uB4DC\uAC00 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4. describe_cms_queries\uB97C \uD655\uC778\uD558\uC138\uC694." : error instanceof z5.ZodError ? "CMS \uC751\uB2F5 \uD615\uC2DD \uB610\uB294 \uB3C4\uAD6C \uC778\uC790\uB97C \uBE0C\uB9AC\uC9C0\uAC00 \uCC98\uB9AC\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4. \uAD8C\uD55C \uBD80\uC871\uC73C\uB85C \uB2E8\uC815\uD558\uC9C0 \uB9C8\uC138\uC694." : permission ? "\uD604\uC7AC \uC778\uC99D \uB610\uB294 \uC870\uD68C \uBC94\uC704 \uAC80\uC99D\uC744 \uD1B5\uACFC\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4." : "CMS \uC870\uD68C \uCC98\uB9AC \uC911 \uC624\uB958\uAC00 \uBC1C\uC0DD\uD588\uC2B5\uB2C8\uB2E4. \uC774 \uC624\uB958\uB9CC\uC73C\uB85C \uAD8C\uD55C \uBD80\uC871\uC744 \uD310\uB2E8\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.";
667
+ const message = code === "cms_parent_required" ? "\uC774 \uC870\uD68C\uC5D0\uB294 \uBD80\uBAA8 ID\uC758 eq \uD544\uD130\uAC00 \uD544\uC694\uD569\uB2C8\uB2E4. describe_cms_queries\uC5D0\uC11C requiredFilter\uB97C \uD655\uC778\uD558\uC138\uC694." : ["cms_invalid_field", "cms_invalid_filter", "cms_unknown_dataset"].includes(code) ? "\uC870\uD68C \uB370\uC774\uD130\uC14B \uB610\uB294 \uD544\uB4DC\uAC00 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4. describe_cms_queries\uB97C \uD655\uC778\uD558\uC138\uC694." : error instanceof z6.ZodError ? "CMS \uC751\uB2F5 \uD615\uC2DD \uB610\uB294 \uB3C4\uAD6C \uC778\uC790\uB97C \uBE0C\uB9AC\uC9C0\uAC00 \uCC98\uB9AC\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4. \uAD8C\uD55C \uBD80\uC871\uC73C\uB85C \uB2E8\uC815\uD558\uC9C0 \uB9C8\uC138\uC694." : permission ? "\uD604\uC7AC \uC778\uC99D \uB610\uB294 \uC870\uD68C \uBC94\uC704 \uAC80\uC99D\uC744 \uD1B5\uACFC\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4." : "CMS \uC870\uD68C \uCC98\uB9AC \uC911 \uC624\uB958\uAC00 \uBC1C\uC0DD\uD588\uC2B5\uB2C8\uB2E4. \uC774 \uC624\uB958\uB9CC\uC73C\uB85C \uAD8C\uD55C \uBD80\uC871\uC744 \uD310\uB2E8\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.";
532
668
  result = { isError: true, content: [{ type: "text", text: message + " \uC870\uD68C \uACB0\uACFC\uB97C \uCD94\uCE21\uD558\uC9C0 \uB9C8\uC138\uC694." }] };
533
669
  }
534
670
  } else {
@@ -556,13 +692,13 @@ async function startCmsMcp(options) {
556
692
  }
557
693
 
558
694
  // src/runner.ts
559
- import { spawn } from "child_process";
695
+ import { spawn as spawn2 } from "child_process";
560
696
  async function runJsonProcess(options) {
561
697
  if (process.platform === "win32") throw new Error("runner_platform_unverified");
562
698
  if (options.signal?.aborted) throw new Error("runner_cancelled");
563
699
  const maxBytes = options.maxBytes ?? 8 * 1024 * 1024;
564
700
  await new Promise((resolve2, reject) => {
565
- const child = spawn(options.command, options.args, {
701
+ const child = spawn2(options.command, options.args, {
566
702
  cwd: options.cwd,
567
703
  env: options.env,
568
704
  detached: true,
@@ -631,20 +767,20 @@ async function runJsonProcess(options) {
631
767
  }
632
768
 
633
769
  // src/usage.ts
634
- import { z as z6 } from "zod";
635
- var count = z6.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).nullable();
636
- var turnUsageSchema = z6.object({
637
- model_key: z6.string().min(1).max(200),
638
- provider: z6.enum(["claude", "codex"]),
639
- cli_version: z6.string().min(1).max(50),
640
- normalizer_version: z6.literal(1),
770
+ import { z as z7 } from "zod";
771
+ var count = z7.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).nullable();
772
+ var turnUsageSchema = z7.object({
773
+ model_key: z7.string().min(1).max(200),
774
+ provider: z7.enum(["claude", "codex"]),
775
+ cli_version: z7.string().min(1).max(50),
776
+ normalizer_version: z7.literal(1),
641
777
  input_tokens: count,
642
778
  output_tokens: count,
643
779
  cache_read_tokens: count,
644
780
  cache_write_tokens: count,
645
781
  reasoning_tokens: count,
646
- usage_status: z6.enum(["complete", "partial", "unavailable"]),
647
- source_scope: z6.literal("turn")
782
+ usage_status: z7.enum(["complete", "partial", "unavailable"]),
783
+ source_scope: z7.literal("turn")
648
784
  }).strict();
649
785
  var rawCount = (value) => count.safeParse(value).success ? value : null;
650
786
  var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
@@ -724,8 +860,8 @@ async function runTurnProcess(options) {
724
860
  }
725
861
 
726
862
  // src/cmsTurn.ts
727
- var dbTurn = z7.object({ id: z7.string().uuid(), session_id: z7.string().uuid(), host_id: z7.string().uuid(), cli: z7.literal("claude"), status: z7.literal("running"), bridge_stream_id: z7.string().uuid(), prompt: z7.string().min(1).max(32e3), lease_expires_at: z7.string() });
728
- function createCmsExecutor(dataDir) {
863
+ var dbTurn = z8.object({ id: z8.string().uuid(), session_id: z8.string().uuid(), host_id: z8.string().uuid(), cli: z8.literal("claude"), status: z8.literal("running"), bridge_stream_id: z8.string().uuid(), prompt: z8.string().min(1).max(32e3), lease_expires_at: z8.string() });
864
+ function createCmsExecutor(dataDir, cliVersion = "2.1.285") {
729
865
  return async (request) => {
730
866
  const controller = new AbortController();
731
867
  const signal = AbortSignal.any([request.signal, controller.signal]);
@@ -758,29 +894,29 @@ function createCmsExecutor(dataDir) {
758
894
  const user = await verifySupabase(request.credentials);
759
895
  active();
760
896
  if (user.userId !== request.auth.userId || permissionsRevision(user) !== request.auth.permissionsRevision) throw new Error("cms_permissions_changed");
761
- const sessions = z7.array(z7.object({ id: z7.string().uuid(), user_id: z7.string().uuid(), mode: z7.literal("cms"), permissions_revision: z7.string() })).length(1).parse(await read("chat_sessions", new URLSearchParams({ select: "id,user_id,mode,permissions_revision", id: `eq.${request.sessionId}` })));
897
+ const sessions = z8.array(z8.object({ id: z8.string().uuid(), user_id: z8.string().uuid(), mode: z8.literal("cms"), permissions_revision: z8.string() })).length(1).parse(await read("chat_sessions", new URLSearchParams({ select: "id,user_id,mode,permissions_revision", id: `eq.${request.sessionId}` })));
762
898
  if (sessions[0].user_id !== user.userId || sessions[0].permissions_revision !== request.auth.permissionsRevision) throw new Error("cms_session_scope_changed");
763
899
  const checkLease = async () => {
764
- const rows = z7.array(dbTurn).length(1).parse(await read("chat_turns", new URLSearchParams({ select: "id,session_id,host_id,cli,status,bridge_stream_id,prompt,lease_expires_at", id: `eq.${request.turnId}` })));
900
+ const rows = z8.array(dbTurn).length(1).parse(await read("chat_turns", new URLSearchParams({ select: "id,session_id,host_id,cli,status,bridge_stream_id,prompt,lease_expires_at", id: `eq.${request.turnId}` })));
765
901
  const turn2 = rows[0];
766
902
  if (turn2.bridge_stream_id !== request.streamId || turn2.session_id !== request.sessionId || turn2.host_id !== request.hostId || Date.parse(turn2.lease_expires_at) - Date.now() <= 15e3 || !Number.isFinite(Date.parse(turn2.lease_expires_at))) throw new Error("cms_lease_lost");
767
903
  return turn2;
768
904
  };
769
905
  const turn = await checkLease();
770
- const messages = z7.array(z7.object({ role: z7.enum(["user", "assistant"]), content: z7.string(), turn_id: z7.string().uuid(), chat_turns: z7.object({ status: z7.literal("completed") }) })).max(20).parse(await read("chat_messages", new URLSearchParams({ select: "role,content,turn_id,chat_turns!inner(status)", "chat_turns.status": "eq.completed", session_id: `eq.${request.sessionId}`, order: "message_seq.desc", limit: "20" }), 2 * 1024 * 1024));
906
+ const messages = z8.array(z8.object({ role: z8.enum(["user", "assistant"]), content: z8.string(), turn_id: z8.string().uuid(), chat_turns: z8.object({ status: z8.literal("completed") }) })).max(20).parse(await read("chat_messages", new URLSearchParams({ select: "role,content,turn_id,chat_turns!inner(status)", "chat_turns.status": "eq.completed", session_id: `eq.${request.sessionId}`, order: "message_seq.desc", limit: "20" }), 2 * 1024 * 1024));
771
907
  let remaining = 32e3;
772
908
  const history = messages.filter((m) => m.turn_id !== request.turnId).map((m) => {
773
909
  const content = remaining > 0 ? m.content.slice(-remaining) : "";
774
910
  remaining = Math.max(0, remaining - content.length);
775
911
  return { role: m.role, content: remaining === 0 && content.length === 0 ? "" : content };
776
912
  }).filter((m) => m.content).reverse();
777
- const dir = await mkdtemp(join(dataDir, "turn-"));
913
+ const dir = await mkdtemp(join2(dataDir, "turn-"));
778
914
  let broker;
779
915
  let poll;
780
916
  let checking = false;
781
917
  try {
782
918
  broker = await startCmsMcp({ credentials: request.credentials, userId: user.userId, permissionsRevision: request.auth.permissionsRevision, resources: request.auth.accessibleResources, assertActive: active, signal, onActivity: request.onActivity });
783
- const config = join(dir, "mcp.json");
919
+ const config = join2(dir, "mcp.json");
784
920
  await writeFile2(config, JSON.stringify({ mcpServers: { "flint-cms": { command: process.execPath, args: [fileURLToPath(new URL("./mcpCli.js", import.meta.url))], env: { FLINT_MCP_ENDPOINT: broker.url, FLINT_MCP_TOKEN: broker.token } } } }), { mode: 384 });
785
921
  poll = setInterval(() => {
786
922
  if (checking) return;
@@ -793,7 +929,7 @@ function createCmsExecutor(dataDir) {
793
929
  const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => /^(PATH|HOME|USER|LOGNAME|TMPDIR|LANG|LC_ALL|SHELL)$/.test(key)));
794
930
  let content = "";
795
931
  const allowed = new Set(broker.toolNames);
796
- const result = await runTurnProcess({ provider: "claude", cliVersion: "2.1.285", command: "claude", args, cwd: dir, env, signal, timeoutMs: 6e5, input: JSON.stringify({ previousConversation: history, userRequest: turn.prompt }), onEvent(event) {
932
+ const result = await runTurnProcess({ provider: "claude", cliVersion, command: "claude", args, cwd: dir, env, signal, timeoutMs: 6e5, input: JSON.stringify({ previousConversation: history, userRequest: turn.prompt }), onEvent(event) {
797
933
  active();
798
934
  const e = event;
799
935
  if (e.type === "system" && e.subtype === "init" && (!Array.isArray(e.tools) || e.tools.some((tool) => typeof tool !== "string" || !allowed.has(tool)))) throw new Error("cms_unexpected_tool");
@@ -823,7 +959,7 @@ import { promisify } from "util";
823
959
  var exec = promisify(execFile);
824
960
  var runCommand = (cli, args) => exec(cli, args, { timeout: 5e3, maxBuffer: 8192, windowsHide: true });
825
961
  async function detectClis(run2 = runCommand) {
826
- return Promise.all(["claude", "codex"].map(async (id2) => {
962
+ return Promise.all(["claude", "codex", "gemini"].map(async (id2) => {
827
963
  let version;
828
964
  try {
829
965
  const { stdout } = await run2(id2, ["--version"]);
@@ -832,6 +968,7 @@ async function detectClis(run2 = runCommand) {
832
968
  return { id: id2, installed: false, version: null, authStatus: "unknown", cmsReady: false, reason: "not_installed" };
833
969
  }
834
970
  let authStatus = "unknown";
971
+ if (id2 === "gemini") return { id: id2, installed: true, version, authStatus, cmsReady: false, reason: "isolation_not_verified" };
835
972
  try {
836
973
  const { stdout, stderr } = await run2(id2, id2 === "claude" ? ["auth", "status", "--json"] : ["login", "status"]);
837
974
  if (id2 === "claude") {
@@ -875,31 +1012,31 @@ async function requestLocalApproval(origin2, signal) {
875
1012
  }
876
1013
 
877
1014
  // src/server.ts
878
- import { createServer as createServer2 } from "http";
1015
+ import { createServer as createServer3 } from "http";
879
1016
  import { isDeepStrictEqual } from "util";
880
1017
  import { randomUUID as randomUUID5 } from "crypto";
881
1018
  import { WebSocketServer, WebSocket } from "ws";
882
- import { z as z8 } from "zod";
883
- var envelope = { v: z8.literal(1), requestId: z8.string().uuid() };
884
- var turnFields = { ...envelope, authContextId: z8.string().uuid(), turnId: z8.string().uuid() };
885
- var requestSchema = z8.discriminatedUnion("type", [
886
- z8.object({ ...envelope, type: z8.literal("hello"), bridgeToken: z8.string().max(128).optional() }).strict(),
887
- z8.object({ ...envelope, type: z8.literal("pair.request") }).strict(),
888
- z8.object({ ...envelope, type: z8.literal("pair"), code: z8.string().regex(/^\d{6}$/) }).strict(),
889
- z8.object({
1019
+ import { z as z9 } from "zod";
1020
+ var envelope = { v: z9.literal(1), requestId: z9.string().uuid() };
1021
+ var turnFields = { ...envelope, authContextId: z9.string().uuid(), turnId: z9.string().uuid() };
1022
+ var requestSchema = z9.discriminatedUnion("type", [
1023
+ z9.object({ ...envelope, type: z9.literal("hello"), bridgeToken: z9.string().max(128).optional() }).strict(),
1024
+ z9.object({ ...envelope, type: z9.literal("pair.request") }).strict(),
1025
+ z9.object({ ...envelope, type: z9.literal("pair"), code: z9.string().regex(/^\d{6}$/) }).strict(),
1026
+ z9.object({
890
1027
  ...envelope,
891
- type: z8.literal("auth.update"),
892
- authContextId: z8.string().uuid().optional(),
893
- supabaseUrl: z8.string().url().max(512),
894
- anonKey: z8.string().min(1).max(8192),
895
- accessToken: z8.string().min(1).max(16384),
896
- accessibleResources: z8.array(z8.string().max(64)).max(32)
1028
+ type: z9.literal("auth.update"),
1029
+ authContextId: z9.string().uuid().optional(),
1030
+ supabaseUrl: z9.string().url().max(512),
1031
+ anonKey: z9.string().min(1).max(8192),
1032
+ accessToken: z9.string().min(1).max(16384),
1033
+ accessibleResources: z9.array(z9.string().max(64)).max(32)
897
1034
  }).strict(),
898
- z8.object({ ...envelope, type: z8.literal("auth.clear"), authContextId: z8.string().uuid() }).strict(),
899
- z8.object({ ...turnFields, type: z8.literal("turn.start"), sessionId: z8.string().uuid() }).strict(),
900
- z8.object({ ...turnFields, type: z8.literal("turn.cancel") }).strict(),
901
- z8.object({ ...turnFields, type: z8.literal("turn.ack") }).strict(),
902
- ...["status", "unpair"].map((type) => z8.object({ ...envelope, type: z8.literal(type) }).strict())
1035
+ z9.object({ ...envelope, type: z9.literal("auth.clear"), authContextId: z9.string().uuid() }).strict(),
1036
+ z9.object({ ...turnFields, type: z9.literal("turn.start"), sessionId: z9.string().uuid() }).strict(),
1037
+ z9.object({ ...turnFields, type: z9.literal("turn.cancel") }).strict(),
1038
+ z9.object({ ...turnFields, type: z9.literal("turn.ack") }).strict(),
1039
+ ...["status", "unpair"].map((type) => z9.object({ ...envelope, type: z9.literal(type) }).strict())
903
1040
  ]);
904
1041
  async function startBridge(options) {
905
1042
  const { config } = options;
@@ -912,7 +1049,7 @@ async function startBridge(options) {
912
1049
  const detect = options.detect ?? detectClis;
913
1050
  let clis = await detect();
914
1051
  let lastDetection = Date.now();
915
- const http = createServer2((_req, res) => {
1052
+ const http = createServer3((_req, res) => {
916
1053
  res.writeHead(404, { "Cache-Control": "no-store" });
917
1054
  res.end();
918
1055
  });
@@ -990,7 +1127,7 @@ async function startBridge(options) {
990
1127
  if (!result.success) {
991
1128
  const input = parsed;
992
1129
  const code = input?.v !== 1 ? "version_unsupported" : input?.type === "turn.start" ? "preflight_required" : "invalid_request";
993
- send(peer, { type: "request.error", code, message: code }, typeof input?.requestId === "string" && z8.string().uuid().safeParse(input.requestId).success ? input.requestId : void 0);
1130
+ send(peer, { type: "request.error", code, message: code }, typeof input?.requestId === "string" && z9.string().uuid().safeParse(input.requestId).success ? input.requestId : void 0);
994
1131
  peer.pending--;
995
1132
  return;
996
1133
  }
@@ -1006,7 +1143,7 @@ async function startBridge(options) {
1006
1143
  if (request.bridgeToken) throw new BridgeError("pair_required");
1007
1144
  reply({
1008
1145
  type: "hello.ok",
1009
- bridgeVersion: "1.0.0",
1146
+ bridgeVersion: "1.0.1",
1010
1147
  hostId: config.hostId,
1011
1148
  streamId,
1012
1149
  connectionId: peer.id,
@@ -1133,7 +1270,7 @@ async function startBridge(options) {
1133
1270
  const query = new URLSearchParams({ select: "result_payload", id: `eq.${turn.id}`, session_id: `eq.${turn.sessionId}` });
1134
1271
  const result2 = await fetch(`${server.url}/rest/v1/chat_turns?${query}`, { headers: { "Accept-Profile": "ai", apikey: auth.anonKey, Authorization: `Bearer ${auth.accessToken}` }, redirect: "error", signal: AbortSignal.timeout(8e3) });
1135
1272
  if (!result2.ok) throw new BridgeError("turn_failed");
1136
- const rows = z8.array(z8.object({ result_payload: z8.unknown() })).length(1).parse(await result2.json());
1273
+ const rows = z9.array(z9.object({ result_payload: z9.unknown() })).length(1).parse(await result2.json());
1137
1274
  if (!isDeepStrictEqual(rows[0].result_payload, turn.result)) throw new BridgeError("turn_failed");
1138
1275
  peer.turn = void 0;
1139
1276
  reply({ type: "turn.acked", turnId: request.turnId });
@@ -1256,19 +1393,39 @@ async function main() {
1256
1393
  help: { type: "boolean", short: "h" }
1257
1394
  } });
1258
1395
  if (values.help) {
1259
- console.log(`flint-ai-bridge [serve|configure|unpair] [--data-dir <dedicated directory>]
1396
+ console.log(`flint-ai-bridge [start|status|stop|serve|configure|unpair] [--data-dir <dedicated directory>]
1260
1397
  configure --id <server-id> --server <https-origin> --origin <cms-origin>
1398
+ start --enable-chat: run in the background; terminal can be closed.
1399
+ status: show background status. stop: stop the bridge.
1261
1400
  serve: loopback connection and pairing. --enable-chat opts into Claude CMS chat after SQL/claim preparation.
1262
1401
  While serving, type "pair" to issue a new five-minute pairing code.`);
1263
1402
  return;
1264
1403
  }
1265
- const path = join2(resolve(values["data-dir"] ?? join2(homedir(), ".flint-ai-bridge")), "config.json");
1266
- const directory = resolve(values["data-dir"] ?? join2(homedir(), ".flint-ai-bridge"));
1267
- const lockPath = join2(directory, "instance.lock");
1268
- const revokePath = join2(directory, "revoke.request");
1404
+ const path = join3(resolve(values["data-dir"] ?? join3(homedir(), ".flint-ai-bridge")), "config.json");
1405
+ const directory = resolve(values["data-dir"] ?? join3(homedir(), ".flint-ai-bridge"));
1406
+ const lockPath = join3(directory, "instance.lock");
1407
+ const revokePath = join3(directory, "revoke.request");
1269
1408
  const running = await access(lockPath).then(() => true, () => false);
1409
+ const command = positionals[0] ?? "serve";
1410
+ if (command === "status") {
1411
+ const state = await backgroundStatus(directory);
1412
+ console.log(state.running ? `Bridge running: ws://127.0.0.1:${state.port} (chat ${state.chat ? "enabled" : "disabled"})` : state.unavailable ? "Bridge status unavailable: an instance lock exists. Check bridge.log." : "Bridge is stopped.");
1413
+ return;
1414
+ }
1415
+ if (command === "stop") {
1416
+ console.log(await stopBackground(directory) ? "Bridge stopped." : "Bridge is already stopped.");
1417
+ return;
1418
+ }
1270
1419
  const config = await readConfig(path);
1271
- switch (positionals[0] ?? "serve") {
1420
+ if (command === "start") {
1421
+ if (!config.servers.length) throw new Error("No registered server. Run configure first; see --help.");
1422
+ const state = await startBackground(directory, fileURLToPath2(import.meta.url), !!values["enable-chat"]);
1423
+ console.log(`Bridge running in background: ws://127.0.0.1:${state.port}
1424
+ You can close this terminal. Use status or stop to manage it.
1425
+ Log: ${join3(directory, "bridge.log")}`);
1426
+ return;
1427
+ }
1428
+ switch (command) {
1272
1429
  case "configure": {
1273
1430
  if (running) throw new Error("Stop the running bridge before changing registered servers.");
1274
1431
  if (!values.id || !values.server || !values.origin) throw new Error("configure requires --id, --server and --origin");
@@ -1296,7 +1453,7 @@ While serving, type "pair" to issue a new five-minute pairing code.`);
1296
1453
  throw new Error("Unknown command. Use --help.");
1297
1454
  }
1298
1455
  if (!config.servers.length) throw new Error("No registered server. Run configure first; see --help.");
1299
- await mkdir2(directory, { recursive: true, mode: 448 });
1456
+ await mkdir3(directory, { recursive: true, mode: 448 });
1300
1457
  const release = await acquireInstance(lockPath);
1301
1458
  try {
1302
1459
  config.pairings = [];
@@ -1310,8 +1467,8 @@ While serving, type "pair" to issue a new five-minute pairing code.`);
1310
1467
  let execute;
1311
1468
  if (values["enable-chat"]) {
1312
1469
  const claude = (await detectClis()).find((c) => c.id === "claude");
1313
- if (claude?.version !== "2.1.285" || claude.authStatus !== "subscription") throw new Error("Chat requires Claude 2.1.285 subscription login");
1314
- execute = createCmsExecutor(directory);
1470
+ if (["2.1.285", "2.1.286"].includes(claude?.version ?? "") && claude?.authStatus === "subscription") execute = createCmsExecutor(directory, claude.version);
1471
+ else console.warn(`CMS chat unavailable: Claude 2.1.285 or 2.1.286 subscription login required (detected: ${claude?.version ?? "not installed"}, ${claude?.authStatus ?? "unknown"}). Bridge discovery remains available.`);
1315
1472
  }
1316
1473
  const bridge = await startBridge({ config, persist, execute, approve: process.platform === "darwin" ? requestLocalApproval : void 0 });
1317
1474
  const issue = () => {
@@ -1324,8 +1481,8 @@ While serving, type "pair" to issue a new five-minute pairing code.`);
1324
1481
  console.log(`FLiNT AI bridge: ws://127.0.0.1:${bridge.port}
1325
1482
  ${execute ? "CMS chat enabled; server claim and SQL preflight required per turn." : "Chat disabled: isolation and database preflight verification required."}`);
1326
1483
  issue();
1327
- const input = createInterface({ input: process.stdin });
1328
- input.on("line", (line) => {
1484
+ const input = process.connected ? void 0 : createInterface({ input: process.stdin });
1485
+ input?.on("line", (line) => {
1329
1486
  if (line.trim() === "pair") issue();
1330
1487
  });
1331
1488
  let revoking = false;
@@ -1337,7 +1494,7 @@ ${execute ? "CMS chat enabled; server claim and SQL preflight required per turn.
1337
1494
  config.pairings = [];
1338
1495
  bridge.revoke();
1339
1496
  await persist();
1340
- await unlink2(revokePath);
1497
+ await unlink3(revokePath);
1341
1498
  console.log("All pairings revoked.");
1342
1499
  } catch (error) {
1343
1500
  if (error.code !== "ENOENT") console.error("Revocation persistence failed; retrying.");
@@ -1350,16 +1507,25 @@ ${execute ? "CMS chat enabled; server claim and SQL preflight required per turn.
1350
1507
  });
1351
1508
  await revoke();
1352
1509
  let stopping = false;
1510
+ let closeControl;
1353
1511
  const shutdown = async () => {
1354
1512
  if (stopping) return;
1355
1513
  stopping = true;
1356
1514
  unwatchFile(revokePath);
1357
- input.close();
1515
+ input?.close();
1358
1516
  await bridge.close();
1359
1517
  await saving.catch(() => {
1360
1518
  });
1519
+ await closeControl?.();
1361
1520
  await release();
1362
1521
  };
1522
+ try {
1523
+ closeControl = await serveControl(directory, { port: bridge.port, chat: !!execute }, shutdown);
1524
+ } catch (error) {
1525
+ await shutdown();
1526
+ throw error;
1527
+ }
1528
+ if (process.connected) process.send?.({ type: "bridge.ready", port: bridge.port, chat: !!execute });
1363
1529
  process.once("SIGINT", () => {
1364
1530
  void shutdown();
1365
1531
  });
@@ -14,9 +14,9 @@ declare const turnUsageSchema: z.ZodObject<{
14
14
  cache_write_tokens: z.ZodNullable<z.ZodNumber>;
15
15
  reasoning_tokens: z.ZodNullable<z.ZodNumber>;
16
16
  usage_status: z.ZodEnum<{
17
+ unavailable: "unavailable";
17
18
  complete: "complete";
18
19
  partial: "partial";
19
- unavailable: "unavailable";
20
20
  }>;
21
21
  source_scope: z.ZodLiteral<"turn">;
22
22
  }, z.core.$strict>;
@@ -30,7 +30,7 @@ declare const MAX_MESSAGE_BYTES: number;
30
30
  declare const RESOURCES: readonly ["companies", "devices", "studio", "media", "dashboard", "users", "users.login_history", "automations", "holidays", "app_store", "alterra", "media_log"];
31
31
  type Resource = typeof RESOURCES[number];
32
32
  type CliInfo = {
33
- id: 'claude' | 'codex';
33
+ id: 'claude' | 'codex' | 'gemini';
34
34
  installed: boolean;
35
35
  version: string | null;
36
36
  authStatus: 'subscription' | 'api_key' | 'logged_out' | 'unknown';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dicamo/flint-ai-bridge",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "Local CLI connection bridge for FLiNT CMS",
5
5
  "type": "module",
6
6
  "bin": {