@sna-sdk/core 0.5.0 → 0.6.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/dist/db/schema.js CHANGED
@@ -18,7 +18,8 @@ function getDb() {
18
18
  const BetterSqlite3 = loadBetterSqlite3();
19
19
  const dir = path.dirname(DB_PATH);
20
20
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
21
- _db = new BetterSqlite3(DB_PATH);
21
+ const nativeBinding = process.env.SNA_SQLITE_NATIVE_BINDING || void 0;
22
+ _db = nativeBinding ? new BetterSqlite3(DB_PATH, { nativeBinding }) : new BetterSqlite3(DB_PATH);
22
23
  _db.pragma("journal_mode = WAL");
23
24
  initSchema(_db);
24
25
  }
@@ -0,0 +1,172 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/electron/index.ts
31
+ var electron_exports = {};
32
+ __export(electron_exports, {
33
+ startSnaServer: () => startSnaServer
34
+ });
35
+ module.exports = __toCommonJS(electron_exports);
36
+
37
+ // ../../node_modules/.pnpm/tsup@8.5.1_jiti@2.6.1_postcss@8.5.8_tsx@4.21.0_typescript@5.9.3/node_modules/tsup/assets/cjs_shims.js
38
+ var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
39
+ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
40
+
41
+ // src/electron/index.ts
42
+ var import_child_process = require("child_process");
43
+ var import_url = require("url");
44
+ var import_fs = __toESM(require("fs"), 1);
45
+ var import_path = __toESM(require("path"), 1);
46
+ function resolveStandaloneScript() {
47
+ const selfPath = (0, import_url.fileURLToPath)(importMetaUrl);
48
+ let script = import_path.default.resolve(import_path.default.dirname(selfPath), "../server/standalone.js");
49
+ if (script.includes(".asar") && !script.includes(".asar.unpacked")) {
50
+ script = script.replace(/(\.asar)([/\\])/, ".asar.unpacked$2");
51
+ }
52
+ if (!import_fs.default.existsSync(script)) {
53
+ throw new Error(
54
+ `SNA standalone script not found: ${script}
55
+ Ensure "@sna-sdk/core" is listed in asarUnpack in your electron-builder config.`
56
+ );
57
+ }
58
+ return script;
59
+ }
60
+ function resolveNativeBinding(override) {
61
+ if (override) {
62
+ if (!import_fs.default.existsSync(override)) {
63
+ console.warn(`[sna] SNA nativeBinding override not found: ${override}`);
64
+ return void 0;
65
+ }
66
+ return override;
67
+ }
68
+ const BINDING_REL = import_path.default.join("better-sqlite3", "build", "Release", "better_sqlite3.node");
69
+ const resourcesPath = process.resourcesPath;
70
+ if (resourcesPath) {
71
+ const unpackedBase = import_path.default.join(resourcesPath, "app.asar.unpacked", "node_modules");
72
+ const candidates = [
73
+ import_path.default.join(unpackedBase, BINDING_REL),
74
+ // nested under @sna-sdk/core if hoisting differs
75
+ import_path.default.join(unpackedBase, "@sna-sdk", "core", "node_modules", BINDING_REL)
76
+ ];
77
+ for (const c of candidates) {
78
+ if (import_fs.default.existsSync(c)) return c;
79
+ }
80
+ }
81
+ const selfPath = (0, import_url.fileURLToPath)(importMetaUrl);
82
+ const local = import_path.default.resolve(import_path.default.dirname(selfPath), "../../node_modules", BINDING_REL);
83
+ if (import_fs.default.existsSync(local)) return local;
84
+ return void 0;
85
+ }
86
+ function buildNodePath() {
87
+ const resourcesPath = process.resourcesPath;
88
+ if (!resourcesPath) return void 0;
89
+ const unpacked = import_path.default.join(resourcesPath, "app.asar.unpacked", "node_modules");
90
+ if (!import_fs.default.existsSync(unpacked)) return void 0;
91
+ const existing = process.env.NODE_PATH;
92
+ return existing ? `${unpacked}${import_path.default.delimiter}${existing}` : unpacked;
93
+ }
94
+ async function startSnaServer(options) {
95
+ const port = options.port ?? 3099;
96
+ const cwd = options.cwd ?? import_path.default.dirname(options.dbPath);
97
+ const readyTimeout = options.readyTimeout ?? 15e3;
98
+ const { onLog } = options;
99
+ const standaloneScript = resolveStandaloneScript();
100
+ const nativeBinding = resolveNativeBinding(options.nativeBinding);
101
+ const nodePath = buildNodePath();
102
+ const env = {
103
+ ...process.env,
104
+ SNA_PORT: String(port),
105
+ SNA_DB_PATH: options.dbPath,
106
+ ...options.maxSessions != null ? { SNA_MAX_SESSIONS: String(options.maxSessions) } : {},
107
+ ...options.permissionMode ? { SNA_PERMISSION_MODE: options.permissionMode } : {},
108
+ ...options.model ? { SNA_MODEL: options.model } : {},
109
+ ...nativeBinding ? { SNA_SQLITE_NATIVE_BINDING: nativeBinding } : {},
110
+ ...nodePath ? { NODE_PATH: nodePath } : {},
111
+ // Consumer overrides last so they can always win
112
+ ...options.env ?? {}
113
+ };
114
+ const proc = (0, import_child_process.fork)(standaloneScript, [], {
115
+ cwd,
116
+ env,
117
+ stdio: "pipe"
118
+ });
119
+ let stdoutBuf = "";
120
+ let isReady = false;
121
+ const readyListeners = [];
122
+ proc.stdout?.on("data", (chunk) => {
123
+ stdoutBuf += chunk.toString();
124
+ const lines = stdoutBuf.split("\n");
125
+ stdoutBuf = lines.pop() ?? "";
126
+ for (const line of lines) {
127
+ if (onLog) onLog(line);
128
+ if (!isReady && line.includes("API server ready")) {
129
+ isReady = true;
130
+ readyListeners.splice(0).forEach((cb) => cb());
131
+ }
132
+ }
133
+ });
134
+ proc.stderr?.on("data", (chunk) => {
135
+ if (onLog) {
136
+ chunk.toString().split("\n").filter(Boolean).forEach(onLog);
137
+ }
138
+ });
139
+ await new Promise((resolve, reject) => {
140
+ if (isReady) return resolve();
141
+ const timer = setTimeout(() => {
142
+ reject(new Error(`SNA server did not become ready within ${readyTimeout}ms`));
143
+ }, readyTimeout);
144
+ readyListeners.push(() => {
145
+ clearTimeout(timer);
146
+ resolve();
147
+ });
148
+ proc.on("exit", (code) => {
149
+ if (!isReady) {
150
+ clearTimeout(timer);
151
+ reject(new Error(`SNA server process exited (code=${code ?? "null"}) before becoming ready`));
152
+ }
153
+ });
154
+ proc.on("error", (err) => {
155
+ if (!isReady) {
156
+ clearTimeout(timer);
157
+ reject(err);
158
+ }
159
+ });
160
+ });
161
+ return {
162
+ process: proc,
163
+ port,
164
+ stop() {
165
+ proc.kill("SIGTERM");
166
+ }
167
+ };
168
+ }
169
+ // Annotate the CommonJS export names for ESM import in node:
170
+ 0 && (module.exports = {
171
+ startSnaServer
172
+ });
@@ -0,0 +1,99 @@
1
+ import { ChildProcess } from 'child_process';
2
+
3
+ /**
4
+ * @sna-sdk/core/electron — Electron launcher API
5
+ *
6
+ * Provides startSnaServer() to launch the SNA standalone server as a forked
7
+ * child process from an Electron main process. Handles asar path resolution,
8
+ * native module binding detection, env construction, and ready detection
9
+ * automatically.
10
+ *
11
+ * @example
12
+ * const { startSnaServer } = require("@sna-sdk/core/electron");
13
+ *
14
+ * const sna = await startSnaServer({
15
+ * port: 3099,
16
+ * dbPath: path.join(app.getPath("userData"), "sna.db"),
17
+ * maxSessions: 20,
18
+ * permissionMode: "acceptEdits",
19
+ * onLog: (line) => console.log("[sna]", line),
20
+ * });
21
+ *
22
+ * // sna.process — ChildProcess ref
23
+ * // sna.port — actual port
24
+ * // sna.stop() — graceful shutdown
25
+ *
26
+ * @remarks
27
+ * **asarUnpack requirement**: for the fork to work, @sna-sdk/core must be
28
+ * outside the asar bundle. Add to your electron-builder config:
29
+ *
30
+ * asarUnpack: ["node_modules/@sna-sdk/core/**"]
31
+ *
32
+ * The better-sqlite3 native binding used by the forked process must be
33
+ * compiled for the system Node.js (not Electron). If your app uses
34
+ * electron-rebuild, set options.nativeBinding to a Node.js-compiled
35
+ * .node file, or let SNA manage its own native install via `sna api:up`.
36
+ */
37
+
38
+ interface SnaServerOptions {
39
+ /** Port for the SNA API server. Default: 3099 */
40
+ port?: number;
41
+ /** Absolute path to the SQLite database file. Required. */
42
+ dbPath: string;
43
+ /**
44
+ * Working directory for the server process.
45
+ * Default: dirname(dbPath)
46
+ */
47
+ cwd?: string;
48
+ /** Maximum concurrent agent sessions. Default: 5 */
49
+ maxSessions?: number;
50
+ /**
51
+ * Permission mode for Claude Code.
52
+ * Default: "acceptEdits"
53
+ */
54
+ permissionMode?: "acceptEdits" | "bypassPermissions" | "default";
55
+ /** Claude model to use. Default: SDK default (claude-sonnet-4-6) */
56
+ model?: string;
57
+ /**
58
+ * Explicit path to the better-sqlite3 native .node binding.
59
+ *
60
+ * When omitted, the launcher auto-detects from:
61
+ * 1. app.asar.unpacked/node_modules/better-sqlite3/build/Release/...
62
+ * 2. The SDK's local node_modules (dev / non-packaged)
63
+ *
64
+ * Set this if you have a custom Node.js-compiled binary at a known location.
65
+ */
66
+ nativeBinding?: string;
67
+ /**
68
+ * Extra env vars merged into the server process environment.
69
+ * These take precedence over the launcher's defaults.
70
+ */
71
+ env?: Record<string, string>;
72
+ /**
73
+ * How long to wait for the server to become ready, in milliseconds.
74
+ * Default: 15000 (15 seconds)
75
+ */
76
+ readyTimeout?: number;
77
+ /**
78
+ * Called with each log line emitted by the server process (stdout + stderr).
79
+ * Useful for forwarding to your app's logger.
80
+ */
81
+ onLog?: (line: string) => void;
82
+ }
83
+ interface SnaServerHandle {
84
+ /** The forked child process. */
85
+ process: ChildProcess;
86
+ /** The port the server is listening on. */
87
+ port: number;
88
+ /** Send SIGTERM to the server process for graceful shutdown. */
89
+ stop(): void;
90
+ }
91
+ /**
92
+ * Launch the SNA standalone API server in a forked child process.
93
+ *
94
+ * Returns a handle once the server is ready to accept requests.
95
+ * Throws if the server fails to start within `options.readyTimeout`.
96
+ */
97
+ declare function startSnaServer(options: SnaServerOptions): Promise<SnaServerHandle>;
98
+
99
+ export { type SnaServerHandle, type SnaServerOptions, startSnaServer };
@@ -0,0 +1,130 @@
1
+ import { fork } from "child_process";
2
+ import { fileURLToPath } from "url";
3
+ import fs from "fs";
4
+ import path from "path";
5
+ function resolveStandaloneScript() {
6
+ const selfPath = fileURLToPath(import.meta.url);
7
+ let script = path.resolve(path.dirname(selfPath), "../server/standalone.js");
8
+ if (script.includes(".asar") && !script.includes(".asar.unpacked")) {
9
+ script = script.replace(/(\.asar)([/\\])/, ".asar.unpacked$2");
10
+ }
11
+ if (!fs.existsSync(script)) {
12
+ throw new Error(
13
+ `SNA standalone script not found: ${script}
14
+ Ensure "@sna-sdk/core" is listed in asarUnpack in your electron-builder config.`
15
+ );
16
+ }
17
+ return script;
18
+ }
19
+ function resolveNativeBinding(override) {
20
+ if (override) {
21
+ if (!fs.existsSync(override)) {
22
+ console.warn(`[sna] SNA nativeBinding override not found: ${override}`);
23
+ return void 0;
24
+ }
25
+ return override;
26
+ }
27
+ const BINDING_REL = path.join("better-sqlite3", "build", "Release", "better_sqlite3.node");
28
+ const resourcesPath = process.resourcesPath;
29
+ if (resourcesPath) {
30
+ const unpackedBase = path.join(resourcesPath, "app.asar.unpacked", "node_modules");
31
+ const candidates = [
32
+ path.join(unpackedBase, BINDING_REL),
33
+ // nested under @sna-sdk/core if hoisting differs
34
+ path.join(unpackedBase, "@sna-sdk", "core", "node_modules", BINDING_REL)
35
+ ];
36
+ for (const c of candidates) {
37
+ if (fs.existsSync(c)) return c;
38
+ }
39
+ }
40
+ const selfPath = fileURLToPath(import.meta.url);
41
+ const local = path.resolve(path.dirname(selfPath), "../../node_modules", BINDING_REL);
42
+ if (fs.existsSync(local)) return local;
43
+ return void 0;
44
+ }
45
+ function buildNodePath() {
46
+ const resourcesPath = process.resourcesPath;
47
+ if (!resourcesPath) return void 0;
48
+ const unpacked = path.join(resourcesPath, "app.asar.unpacked", "node_modules");
49
+ if (!fs.existsSync(unpacked)) return void 0;
50
+ const existing = process.env.NODE_PATH;
51
+ return existing ? `${unpacked}${path.delimiter}${existing}` : unpacked;
52
+ }
53
+ async function startSnaServer(options) {
54
+ const port = options.port ?? 3099;
55
+ const cwd = options.cwd ?? path.dirname(options.dbPath);
56
+ const readyTimeout = options.readyTimeout ?? 15e3;
57
+ const { onLog } = options;
58
+ const standaloneScript = resolveStandaloneScript();
59
+ const nativeBinding = resolveNativeBinding(options.nativeBinding);
60
+ const nodePath = buildNodePath();
61
+ const env = {
62
+ ...process.env,
63
+ SNA_PORT: String(port),
64
+ SNA_DB_PATH: options.dbPath,
65
+ ...options.maxSessions != null ? { SNA_MAX_SESSIONS: String(options.maxSessions) } : {},
66
+ ...options.permissionMode ? { SNA_PERMISSION_MODE: options.permissionMode } : {},
67
+ ...options.model ? { SNA_MODEL: options.model } : {},
68
+ ...nativeBinding ? { SNA_SQLITE_NATIVE_BINDING: nativeBinding } : {},
69
+ ...nodePath ? { NODE_PATH: nodePath } : {},
70
+ // Consumer overrides last so they can always win
71
+ ...options.env ?? {}
72
+ };
73
+ const proc = fork(standaloneScript, [], {
74
+ cwd,
75
+ env,
76
+ stdio: "pipe"
77
+ });
78
+ let stdoutBuf = "";
79
+ let isReady = false;
80
+ const readyListeners = [];
81
+ proc.stdout?.on("data", (chunk) => {
82
+ stdoutBuf += chunk.toString();
83
+ const lines = stdoutBuf.split("\n");
84
+ stdoutBuf = lines.pop() ?? "";
85
+ for (const line of lines) {
86
+ if (onLog) onLog(line);
87
+ if (!isReady && line.includes("API server ready")) {
88
+ isReady = true;
89
+ readyListeners.splice(0).forEach((cb) => cb());
90
+ }
91
+ }
92
+ });
93
+ proc.stderr?.on("data", (chunk) => {
94
+ if (onLog) {
95
+ chunk.toString().split("\n").filter(Boolean).forEach(onLog);
96
+ }
97
+ });
98
+ await new Promise((resolve, reject) => {
99
+ if (isReady) return resolve();
100
+ const timer = setTimeout(() => {
101
+ reject(new Error(`SNA server did not become ready within ${readyTimeout}ms`));
102
+ }, readyTimeout);
103
+ readyListeners.push(() => {
104
+ clearTimeout(timer);
105
+ resolve();
106
+ });
107
+ proc.on("exit", (code) => {
108
+ if (!isReady) {
109
+ clearTimeout(timer);
110
+ reject(new Error(`SNA server process exited (code=${code ?? "null"}) before becoming ready`));
111
+ }
112
+ });
113
+ proc.on("error", (err) => {
114
+ if (!isReady) {
115
+ clearTimeout(timer);
116
+ reject(err);
117
+ }
118
+ });
119
+ });
120
+ return {
121
+ process: proc,
122
+ port,
123
+ stop() {
124
+ proc.kill("SIGTERM");
125
+ }
126
+ };
127
+ }
128
+ export {
129
+ startSnaServer
130
+ };
@@ -0,0 +1,172 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/node/index.ts
31
+ var node_exports = {};
32
+ __export(node_exports, {
33
+ startSnaServer: () => startSnaServer
34
+ });
35
+ module.exports = __toCommonJS(node_exports);
36
+
37
+ // ../../node_modules/.pnpm/tsup@8.5.1_jiti@2.6.1_postcss@8.5.8_tsx@4.21.0_typescript@5.9.3/node_modules/tsup/assets/cjs_shims.js
38
+ var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
39
+ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
40
+
41
+ // src/electron/index.ts
42
+ var import_child_process = require("child_process");
43
+ var import_url = require("url");
44
+ var import_fs = __toESM(require("fs"), 1);
45
+ var import_path = __toESM(require("path"), 1);
46
+ function resolveStandaloneScript() {
47
+ const selfPath = (0, import_url.fileURLToPath)(importMetaUrl);
48
+ let script = import_path.default.resolve(import_path.default.dirname(selfPath), "../server/standalone.js");
49
+ if (script.includes(".asar") && !script.includes(".asar.unpacked")) {
50
+ script = script.replace(/(\.asar)([/\\])/, ".asar.unpacked$2");
51
+ }
52
+ if (!import_fs.default.existsSync(script)) {
53
+ throw new Error(
54
+ `SNA standalone script not found: ${script}
55
+ Ensure "@sna-sdk/core" is listed in asarUnpack in your electron-builder config.`
56
+ );
57
+ }
58
+ return script;
59
+ }
60
+ function resolveNativeBinding(override) {
61
+ if (override) {
62
+ if (!import_fs.default.existsSync(override)) {
63
+ console.warn(`[sna] SNA nativeBinding override not found: ${override}`);
64
+ return void 0;
65
+ }
66
+ return override;
67
+ }
68
+ const BINDING_REL = import_path.default.join("better-sqlite3", "build", "Release", "better_sqlite3.node");
69
+ const resourcesPath = process.resourcesPath;
70
+ if (resourcesPath) {
71
+ const unpackedBase = import_path.default.join(resourcesPath, "app.asar.unpacked", "node_modules");
72
+ const candidates = [
73
+ import_path.default.join(unpackedBase, BINDING_REL),
74
+ // nested under @sna-sdk/core if hoisting differs
75
+ import_path.default.join(unpackedBase, "@sna-sdk", "core", "node_modules", BINDING_REL)
76
+ ];
77
+ for (const c of candidates) {
78
+ if (import_fs.default.existsSync(c)) return c;
79
+ }
80
+ }
81
+ const selfPath = (0, import_url.fileURLToPath)(importMetaUrl);
82
+ const local = import_path.default.resolve(import_path.default.dirname(selfPath), "../../node_modules", BINDING_REL);
83
+ if (import_fs.default.existsSync(local)) return local;
84
+ return void 0;
85
+ }
86
+ function buildNodePath() {
87
+ const resourcesPath = process.resourcesPath;
88
+ if (!resourcesPath) return void 0;
89
+ const unpacked = import_path.default.join(resourcesPath, "app.asar.unpacked", "node_modules");
90
+ if (!import_fs.default.existsSync(unpacked)) return void 0;
91
+ const existing = process.env.NODE_PATH;
92
+ return existing ? `${unpacked}${import_path.default.delimiter}${existing}` : unpacked;
93
+ }
94
+ async function startSnaServer(options) {
95
+ const port = options.port ?? 3099;
96
+ const cwd = options.cwd ?? import_path.default.dirname(options.dbPath);
97
+ const readyTimeout = options.readyTimeout ?? 15e3;
98
+ const { onLog } = options;
99
+ const standaloneScript = resolveStandaloneScript();
100
+ const nativeBinding = resolveNativeBinding(options.nativeBinding);
101
+ const nodePath = buildNodePath();
102
+ const env = {
103
+ ...process.env,
104
+ SNA_PORT: String(port),
105
+ SNA_DB_PATH: options.dbPath,
106
+ ...options.maxSessions != null ? { SNA_MAX_SESSIONS: String(options.maxSessions) } : {},
107
+ ...options.permissionMode ? { SNA_PERMISSION_MODE: options.permissionMode } : {},
108
+ ...options.model ? { SNA_MODEL: options.model } : {},
109
+ ...nativeBinding ? { SNA_SQLITE_NATIVE_BINDING: nativeBinding } : {},
110
+ ...nodePath ? { NODE_PATH: nodePath } : {},
111
+ // Consumer overrides last so they can always win
112
+ ...options.env ?? {}
113
+ };
114
+ const proc = (0, import_child_process.fork)(standaloneScript, [], {
115
+ cwd,
116
+ env,
117
+ stdio: "pipe"
118
+ });
119
+ let stdoutBuf = "";
120
+ let isReady = false;
121
+ const readyListeners = [];
122
+ proc.stdout?.on("data", (chunk) => {
123
+ stdoutBuf += chunk.toString();
124
+ const lines = stdoutBuf.split("\n");
125
+ stdoutBuf = lines.pop() ?? "";
126
+ for (const line of lines) {
127
+ if (onLog) onLog(line);
128
+ if (!isReady && line.includes("API server ready")) {
129
+ isReady = true;
130
+ readyListeners.splice(0).forEach((cb) => cb());
131
+ }
132
+ }
133
+ });
134
+ proc.stderr?.on("data", (chunk) => {
135
+ if (onLog) {
136
+ chunk.toString().split("\n").filter(Boolean).forEach(onLog);
137
+ }
138
+ });
139
+ await new Promise((resolve, reject) => {
140
+ if (isReady) return resolve();
141
+ const timer = setTimeout(() => {
142
+ reject(new Error(`SNA server did not become ready within ${readyTimeout}ms`));
143
+ }, readyTimeout);
144
+ readyListeners.push(() => {
145
+ clearTimeout(timer);
146
+ resolve();
147
+ });
148
+ proc.on("exit", (code) => {
149
+ if (!isReady) {
150
+ clearTimeout(timer);
151
+ reject(new Error(`SNA server process exited (code=${code ?? "null"}) before becoming ready`));
152
+ }
153
+ });
154
+ proc.on("error", (err) => {
155
+ if (!isReady) {
156
+ clearTimeout(timer);
157
+ reject(err);
158
+ }
159
+ });
160
+ });
161
+ return {
162
+ process: proc,
163
+ port,
164
+ stop() {
165
+ proc.kill("SIGTERM");
166
+ }
167
+ };
168
+ }
169
+ // Annotate the CommonJS export names for ESM import in node:
170
+ 0 && (module.exports = {
171
+ startSnaServer
172
+ });
@@ -0,0 +1,2 @@
1
+ export { SnaServerHandle, SnaServerOptions, startSnaServer } from '../electron/index.js';
2
+ import 'child_process';
@@ -0,0 +1,4 @@
1
+ import { startSnaServer } from "../electron/index.js";
2
+ export {
3
+ startSnaServer
4
+ };
@@ -31,7 +31,8 @@ function getDb() {
31
31
  const BetterSqlite3 = loadBetterSqlite3();
32
32
  const dir = path.dirname(DB_PATH);
33
33
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
34
- _db = new BetterSqlite3(DB_PATH);
34
+ const nativeBinding = process.env.SNA_SQLITE_NATIVE_BINDING || void 0;
35
+ _db = nativeBinding ? new BetterSqlite3(DB_PATH, { nativeBinding }) : new BetterSqlite3(DB_PATH);
35
36
  _db.pragma("journal_mode = WAL");
36
37
  initSchema(_db);
37
38
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sna-sdk/core",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "description": "Skills-Native Application runtime — server, providers, session management, database, and CLI",
5
5
  "type": "module",
6
6
  "bin": {
@@ -68,6 +68,20 @@
68
68
  "source": "./src/testing/mock-api.ts",
69
69
  "types": "./dist/testing/mock-api.d.ts",
70
70
  "default": "./dist/testing/mock-api.js"
71
+ },
72
+ "./electron": {
73
+ "source": "./src/electron/index.ts",
74
+ "types": "./dist/electron/index.d.ts",
75
+ "require": "./dist/electron/index.cjs",
76
+ "import": "./dist/electron/index.js",
77
+ "default": "./dist/electron/index.js"
78
+ },
79
+ "./node": {
80
+ "source": "./src/node/index.ts",
81
+ "types": "./dist/node/index.d.ts",
82
+ "require": "./dist/node/index.cjs",
83
+ "import": "./dist/node/index.js",
84
+ "default": "./dist/node/index.js"
71
85
  }
72
86
  },
73
87
  "engines": {