@dicamo/flint-ai-bridge 1.0.8 → 1.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -14,12 +14,84 @@ import { fileURLToPath as fileURLToPath2 } from "url";
14
14
  import { createServer } from "http";
15
15
  import { randomBytes, timingSafeEqual } from "crypto";
16
16
  import { spawn } from "child_process";
17
- import { chmod, mkdir, open, readFile, rename, unlink } from "fs/promises";
17
+ import { chmod, mkdir, open as open2, readFile as readFile2, rename, unlink as unlink2 } from "fs/promises";
18
18
  import { join } from "path";
19
19
  import { z } from "zod";
20
+
21
+ // src/instance.ts
22
+ import { open, readFile, unlink } from "fs/promises";
23
+ import { randomUUID } from "crypto";
24
+ var LOCK_EXISTS = "Bridge instance lock exists. Stop the existing bridge; remove instance.lock only after confirming it is stopped.";
25
+ function isStale(raw) {
26
+ let pid;
27
+ try {
28
+ pid = JSON.parse(raw).pid;
29
+ } catch {
30
+ return false;
31
+ }
32
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return false;
33
+ try {
34
+ process.kill(pid, 0);
35
+ return false;
36
+ } catch (error) {
37
+ return error.code === "ESRCH";
38
+ }
39
+ }
40
+ async function readLock(path) {
41
+ try {
42
+ return await readFile(path, "utf8");
43
+ } catch (error) {
44
+ if (error.code === "ENOENT") return void 0;
45
+ throw error;
46
+ }
47
+ }
48
+ async function instanceLocked(path) {
49
+ const raw = await readLock(path);
50
+ return raw !== void 0 && !isStale(raw);
51
+ }
52
+ async function removeStaleLock(path) {
53
+ const raw = await readLock(path);
54
+ if (raw === void 0) return true;
55
+ if (!isStale(raw)) return false;
56
+ if (await readLock(path) !== raw) return false;
57
+ try {
58
+ await unlink(path);
59
+ } catch (error) {
60
+ if (error.code !== "ENOENT") throw error;
61
+ }
62
+ console.log(`Removed stale instance lock (PID ${JSON.parse(raw).pid} is not running).`);
63
+ return true;
64
+ }
65
+ async function acquireInstance(path) {
66
+ const nonce = randomUUID();
67
+ for (let attempt = 0; ; attempt++) {
68
+ try {
69
+ const handle = await open(path, "wx", 384);
70
+ try {
71
+ await handle.writeFile(JSON.stringify({ pid: process.pid, nonce }));
72
+ } finally {
73
+ await handle.close();
74
+ }
75
+ break;
76
+ } catch (error) {
77
+ if (error.code !== "EEXIST") throw error;
78
+ if (attempt === 0 && await removeStaleLock(path)) continue;
79
+ throw new Error(LOCK_EXISTS);
80
+ }
81
+ }
82
+ return async () => {
83
+ try {
84
+ if (JSON.parse(await readFile(path, "utf8")).nonce === nonce) await unlink(path);
85
+ } catch (error) {
86
+ if (error.code !== "ENOENT") throw error;
87
+ }
88
+ };
89
+ }
90
+
91
+ // src/background.ts
20
92
  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() });
21
93
  async function control(directory, action) {
22
- const runtime = runtimeSchema.parse(JSON.parse(await readFile(join(directory, "runtime.json"), "utf8")));
94
+ const runtime = runtimeSchema.parse(JSON.parse(await readFile2(join(directory, "runtime.json"), "utf8")));
23
95
  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) });
24
96
  if (!res.ok) throw new Error("Bridge control request failed");
25
97
  return z.object({ running: z.boolean(), port: z.number().optional(), chat: z.boolean().optional(), chatReason: z.string().max(512).optional(), pid: z.number().optional() }).parse(await res.json());
@@ -29,10 +101,9 @@ async function backgroundStatus(directory) {
29
101
  return await control(directory, "status");
30
102
  } catch {
31
103
  try {
32
- await readFile(join(directory, "instance.lock"));
33
- return { running: false, unavailable: true };
104
+ return await instanceLocked(join(directory, "instance.lock")) ? { running: false, unavailable: true } : { running: false };
34
105
  } catch {
35
- return { running: false };
106
+ return { running: false, unavailable: true };
36
107
  }
37
108
  }
38
109
  }
@@ -42,12 +113,7 @@ async function stopBackground(directory) {
42
113
  if (!state.running) return false;
43
114
  await control(directory, "stop");
44
115
  for (let i = 0; i < 100; i++) {
45
- try {
46
- await readFile(join(directory, "instance.lock"));
47
- } catch (error) {
48
- if (error.code === "ENOENT") return true;
49
- throw error;
50
- }
116
+ if (!await instanceLocked(join(directory, "instance.lock"))) return true;
51
117
  await new Promise((resolve2) => setTimeout(resolve2, 100));
52
118
  }
53
119
  throw new Error("Bridge is still shutting down. Check status before starting again.");
@@ -79,7 +145,7 @@ async function serveControl(directory, status, shutdown) {
79
145
  const temporary = join(directory, `runtime-${token}.tmp`);
80
146
  try {
81
147
  await mkdir(directory, { recursive: true, mode: 448 });
82
- const file = await open(temporary, "wx", 384);
148
+ const file = await open2(temporary, "wx", 384);
83
149
  try {
84
150
  await file.writeFile(JSON.stringify({ port: address.port, token, pid: process.pid }));
85
151
  } finally {
@@ -88,7 +154,7 @@ async function serveControl(directory, status, shutdown) {
88
154
  await rename(temporary, runtimePath);
89
155
  } catch (error) {
90
156
  server.close();
91
- await unlink(temporary).catch(() => {
157
+ await unlink2(temporary).catch(() => {
92
158
  });
93
159
  throw error;
94
160
  }
@@ -98,8 +164,8 @@ async function serveControl(directory, status, shutdown) {
98
164
  server.closeIdleConnections();
99
165
  });
100
166
  try {
101
- const current = JSON.parse(await readFile(runtimePath, "utf8"));
102
- if (current.token === token) await unlink(runtimePath);
167
+ const current = JSON.parse(await readFile2(runtimePath, "utf8"));
168
+ if (current.token === token) await unlink2(runtimePath);
103
169
  } catch (error) {
104
170
  if (error.code !== "ENOENT") throw error;
105
171
  }
@@ -112,7 +178,7 @@ async function startBackground(directory, entry, chat) {
112
178
  return previous;
113
179
  }
114
180
  await mkdir(directory, { recursive: true, mode: 448 });
115
- const log = await open(join(directory, "bridge.log"), "a", 384);
181
+ const log = await open2(join(directory, "bridge.log"), "a", 384);
116
182
  await chmod(join(directory, "bridge.log"), 384);
117
183
  try {
118
184
  const child = spawn(process.execPath, [entry, "serve", "--data-dir", directory, ...chat ? ["--enable-chat"] : []], { detached: true, stdio: ["ignore", log.fd, log.fd, "ipc"], windowsHide: true });
@@ -149,33 +215,6 @@ import { join as join4, resolve } from "path";
149
215
  import { parseArgs } from "util";
150
216
  import { watchFile, unwatchFile } from "fs";
151
217
  import { access, writeFile as writeFile4, mkdir as mkdir3, unlink as unlink3 } from "fs/promises";
152
-
153
- // src/instance.ts
154
- import { open as open2, readFile as readFile2, unlink as unlink2 } from "fs/promises";
155
- import { randomUUID } from "crypto";
156
- async function acquireInstance(path) {
157
- const nonce = randomUUID();
158
- try {
159
- const handle = await open2(path, "wx", 384);
160
- try {
161
- await handle.writeFile(JSON.stringify({ pid: process.pid, nonce }));
162
- } finally {
163
- await handle.close();
164
- }
165
- } catch (error) {
166
- if (error.code === "EEXIST") throw new Error("Bridge instance lock exists. Stop the existing bridge; remove instance.lock only after confirming it is stopped.");
167
- throw error;
168
- }
169
- return async () => {
170
- try {
171
- if (JSON.parse(await readFile2(path, "utf8")).nonce === nonce) await unlink2(path);
172
- } catch (error) {
173
- if (error.code !== "ENOENT") throw error;
174
- }
175
- };
176
- }
177
-
178
- // src/cli.ts
179
218
  import { createInterface } from "readline";
180
219
 
181
220
  // src/config.ts
@@ -1251,7 +1290,7 @@ async function startBridge(options) {
1251
1290
  if (request.bridgeToken) throw new BridgeError("pair_required");
1252
1291
  reply({
1253
1292
  type: "hello.ok",
1254
- bridgeVersion: "1.0.8",
1293
+ bridgeVersion: "1.0.9",
1255
1294
  hostId: config.hostId,
1256
1295
  streamId,
1257
1296
  connectionId: peer.id,
@@ -1513,7 +1552,7 @@ While serving, type "pair" to issue a new five-minute pairing code.`);
1513
1552
  const directory = resolve(values["data-dir"] ?? join4(homedir(), ".flint-ai-bridge"));
1514
1553
  const lockPath = join4(directory, "instance.lock");
1515
1554
  const revokePath = join4(directory, "revoke.request");
1516
- const running = await access(lockPath).then(() => true, () => false);
1555
+ const running = await instanceLocked(lockPath);
1517
1556
  const command = positionals[0] ?? "serve";
1518
1557
  if (command === "status") {
1519
1558
  const state = await backgroundStatus(directory);
@@ -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";
18
17
  complete: "complete";
19
18
  partial: "partial";
19
+ unavailable: "unavailable";
20
20
  }>;
21
21
  source_scope: z.ZodLiteral<"turn">;
22
22
  }, z.core.$strict>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dicamo/flint-ai-bridge",
3
- "version": "1.0.8",
3
+ "version": "1.0.9",
4
4
  "description": "Local CLI connection bridge for FLiNT CMS",
5
5
  "type": "module",
6
6
  "bin": {