@kehto/paja 0.25.1 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -34,7 +34,8 @@ var PAJA_SIMULATION_DOMAINS = [
34
34
  "dm",
35
35
  "fs",
36
36
  "cvm",
37
- "inc"
37
+ "inc",
38
+ "llm"
38
39
  ];
39
40
  var DEFAULT_RELAY_URLS = [
40
41
  "wss://relay.damus.io",
@@ -586,6 +587,17 @@ function renderPajaHtml(config) {
586
587
  .toggle { height: 24px; padding: 0 8px; color: var(--muted); }
587
588
  .toggle[data-enabled="true"] { color: var(--text); border-color: #5f724f; background: #24301f; }
588
589
  .toggle[data-enabled="false"] { color: #8d9187; border-color: #453536; background: #241d1d; }
590
+ .toggle[data-state="unconfigured"] { color: #e8d27a; border-color: #7a6a2a; background: #2d2814; }
591
+ .llm-form { display: grid; gap: 6px; min-width: 0; }
592
+ .llm-form label { display: grid; gap: 2px; color: var(--muted); font-size: 11px; }
593
+ .llm-form label.llm-check { grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 6px; }
594
+ .llm-form input:not([type="checkbox"]), .llm-form select { width: 100%; min-width: 0; padding: 0 8px; height: 24px; }
595
+ .llm-actions { display: flex; flex-wrap: wrap; gap: 6px; }
596
+ .llm-connections { margin: 0; padding: 0; list-style: none; display: grid; gap: 4px; }
597
+ .llm-connection { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 6px; padding: 4px 6px; border: 1px solid var(--line); border-radius: 4px; background: #0b0d0b; font-size: 11px; }
598
+ .llm-connection-label { min-width: 0; overflow-wrap: anywhere; color: var(--text); }
599
+ .llm-select-dialog select, .llm-vault-dialog input { width: 100%; min-width: 0; padding: 4px 8px; }
600
+ .llm-vault-dialog .config-error:empty { display: none; }
589
601
  .signer { color: var(--muted); word-break: break-all; font-size: 12px; }
590
602
  .signer-controls { display: grid; grid-template-columns: auto auto minmax(0, 1fr) auto; gap: 6px; }
591
603
  .signer-controls button[data-active="true"] { border-color: var(--accent); color: var(--text); background: #2a2a1d; }
@@ -647,6 +659,8 @@ function renderPajaHtml(config) {
647
659
  .dialog-actions { display: flex; justify-content: flex-end; flex-wrap: wrap; gap: 8px; }
648
660
  .confirmation-dialog { width: min(520px, calc(100% - 48px)); max-width: none; border: 0; padding: 0; background: transparent; color: var(--text); }
649
661
  .confirmation-dialog::backdrop { background: rgb(0 0 0 / 0.68); }
662
+ .llm-select-dialog, .llm-vault-dialog { width: min(520px, calc(100% - 48px)); max-width: none; border: 0; padding: 0; background: transparent; color: var(--text); }
663
+ .llm-select-dialog::backdrop, .llm-vault-dialog::backdrop { background: rgb(0 0 0 / 0.68); }
650
664
  .signer-consent { min-width: 0; margin: 0; padding: 10px; border: 1px solid var(--line); border-radius: 4px; display: grid; gap: 8px; }
651
665
  .signer-consent[hidden] { display: none; }
652
666
  .signer-consent legend { color: var(--accent); padding: 0 5px; }
@@ -746,6 +760,26 @@ function renderPajaHtml(config) {
746
760
  <div id="paja-resource-servers-status" role="status" aria-live="polite"></div>
747
761
  </form>
748
762
  </div></details>
763
+ <details class="section" id="paja-section-llm" data-paja-section="llm" open>
764
+ <summary class="section-title">Language models<span class="section-chevron" aria-hidden="true">\u203A</span></summary><div class="section-body">
765
+ <ul class="llm-connections" id="paja-llm-connections" aria-label="Configured model connections"></ul>
766
+ <form class="llm-form" id="paja-llm-form" autocomplete="off">
767
+ <label>Provider<select id="paja-llm-preset" aria-label="Provider preset"></select></label>
768
+ <label>Name<input id="paja-llm-name" type="text" required maxlength="64" spellcheck="false"></label>
769
+ <label>API base URL<input id="paja-llm-base-url" type="url" required spellcheck="false" placeholder="API root; presets fill this in"></label>
770
+ <label>Model<input id="paja-llm-model" type="text" required maxlength="200" spellcheck="false" list="paja-llm-model-examples"><datalist id="paja-llm-model-examples"></datalist></label>
771
+ <label>API key<input id="paja-llm-credential" type="password" autocomplete="off" spellcheck="false"></label>
772
+ <label class="llm-check"><input id="paja-llm-remember" type="checkbox"><span>Remember the key, encrypted with a vault password</span></label>
773
+ <label class="llm-check"><input id="paja-llm-images" type="checkbox"><span>Accepts image input</span></label>
774
+ <label class="llm-check"><input id="paja-llm-json" type="checkbox" checked><span>Supports JSON-object output</span></label>
775
+ <div class="llm-actions">
776
+ <button type="submit" id="paja-llm-save">Add connection</button>
777
+ <button type="button" id="paja-llm-vault-lock" hidden>Lock vault</button>
778
+ </div>
779
+ <p class="hint" id="paja-llm-status" role="status" aria-live="polite"></p>
780
+ </form>
781
+ <p class="hint">Keys go only to the connection's base URL and never to napplets. Every generation asks for your consent first (draft NAP-LLM).</p>
782
+ </div></details>
749
783
  <details class="section" id="paja-section-messages" data-paja-section="messages" open>
750
784
  <summary class="section-title">Messages<span class="section-chevron" aria-hidden="true">\u203A</span></summary><div class="section-body">
751
785
  <div class="log-tools">
@@ -770,6 +804,7 @@ function renderPajaHtml(config) {
770
804
  <div class="paja-notification-badges" id="paja-notification-badges" aria-label="Napplet notification badges"></div>
771
805
  <section class="paja-notification-center" id="paja-notification-center" aria-label="Napplet notifications" aria-live="polite"></section>
772
806
  ${renderConfirmationDialog()}
807
+ ${renderLlmDialogs()}
773
808
  ${renderConfigDialog()}
774
809
  ${renderIntentLinkDialog()}
775
810
  ${renderDuplicateDialog()}
@@ -821,6 +856,31 @@ function renderConfirmationDialog() {
821
856
  </div>
822
857
  </dialog>`;
823
858
  }
859
+ function renderLlmDialogs() {
860
+ return `<dialog class="llm-select-dialog" id="paja-llm-select-dialog" aria-labelledby="paja-llm-select-title" aria-describedby="paja-llm-select-copy">
861
+ <div class="dialog">
862
+ <div class="dialog-title" id="paja-llm-select-title">Choose a language model connection</div>
863
+ <div class="dialog-copy" id="paja-llm-select-copy"></div>
864
+ <select id="paja-llm-select-options" aria-label="Compatible connections" size="4"></select>
865
+ <div class="dialog-actions">
866
+ <button type="button" id="paja-llm-select-deny">Deny</button>
867
+ <button type="button" id="paja-llm-select-use">Use connection</button>
868
+ </div>
869
+ </div>
870
+ </dialog>
871
+ <dialog class="llm-vault-dialog" id="paja-llm-vault-dialog" aria-labelledby="paja-llm-vault-title" aria-describedby="paja-llm-vault-copy">
872
+ <div class="dialog">
873
+ <div class="dialog-title" id="paja-llm-vault-title">Unlock the credential vault</div>
874
+ <div class="dialog-copy" id="paja-llm-vault-copy"></div>
875
+ <input id="paja-llm-vault-password" type="password" autocomplete="off" aria-label="Vault password">
876
+ <div class="config-error" id="paja-llm-vault-error" role="alert"></div>
877
+ <div class="dialog-actions">
878
+ <button type="button" id="paja-llm-vault-cancel">Cancel</button>
879
+ <button type="button" id="paja-llm-vault-confirm">Unlock</button>
880
+ </div>
881
+ </div>
882
+ </dialog>`;
883
+ }
824
884
  function renderConfigDialog() {
825
885
  return `<dialog class="config-dialog" id="paja-config-dialog" aria-labelledby="paja-config-title" aria-describedby="paja-config-description">
826
886
  <div class="dialog">
@@ -1210,6 +1270,7 @@ var PAJA_UPSTREAM_WEB_DOMAINS = [
1210
1270
  "keys",
1211
1271
  "link",
1212
1272
  "lists",
1273
+ "llm",
1213
1274
  "media",
1214
1275
  "notify",
1215
1276
  "outbox",
@@ -1251,7 +1312,8 @@ var PAJA_ADVERTISED_DOMAINS = [
1251
1312
  "intent",
1252
1313
  "count",
1253
1314
  "dm",
1254
- "fs"
1315
+ "fs",
1316
+ "llm"
1255
1317
  ];
1256
1318
  var PAJA_REQUIRED_SERVICES = [
1257
1319
  "gamepad",
@@ -2004,6 +2066,386 @@ function normalizeServerTargetUrl(value) {
2004
2066
  return parsed.href;
2005
2067
  }
2006
2068
 
2069
+ // src/browser-llm-connections.ts
2070
+ import {
2071
+ LLM_PROVIDER_PRESETS,
2072
+ LlmServiceError,
2073
+ createHttpLlmProvider,
2074
+ countLlmImages
2075
+ } from "@kehto/services";
2076
+ var PAJA_LLM_CONNECTIONS_STORAGE_KEY = "kehto:paja:llm-connections:v1";
2077
+ var MAX_CONNECTIONS = 32;
2078
+ var PROTOCOLS = /* @__PURE__ */ new Set(["openai-chat", "anthropic-messages", "gemini"]);
2079
+ var CREDENTIAL_HEADERS = /* @__PURE__ */ new Set(["authorization-bearer", "api-key", "x-api-key", "x-goog-api-key"]);
2080
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
2081
+ function normalizePajaLlmBaseUrl(value) {
2082
+ let url;
2083
+ try {
2084
+ url = new URL(value.trim());
2085
+ } catch {
2086
+ throw new Error("Enter an absolute API base URL.");
2087
+ }
2088
+ if (url.username || url.password) throw new Error("The base URL must not embed credentials.");
2089
+ if (url.search || url.hash) throw new Error("The base URL must not include a query or fragment.");
2090
+ const loopback = LOOPBACK_HOSTS.has(url.hostname);
2091
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
2092
+ throw new Error("Use HTTPS, or HTTP only for a server on this machine (localhost / 127.0.0.1).");
2093
+ }
2094
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
2095
+ }
2096
+ function isRecord2(value) {
2097
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2098
+ }
2099
+ function normalizeRecord(input) {
2100
+ const text = (value) => typeof value === "string" ? value : "";
2101
+ const name = text(input.name).trim();
2102
+ const model = text(input.model).trim();
2103
+ const id = text(input.id);
2104
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(id)) throw new Error("Invalid connection id.");
2105
+ if (!name || name.length > 64) throw new Error("Enter a connection name of up to 64 characters.");
2106
+ if (!model || model.length > 200) throw new Error("Enter the exact provider model identifier.");
2107
+ const protocol = input.protocol;
2108
+ const credentialHeader = input.credentialHeader;
2109
+ const credentialStorage = input.credentialStorage;
2110
+ if (!PROTOCOLS.has(protocol)) throw new Error("Unknown provider protocol.");
2111
+ if (credentialHeader !== void 0 && !CREDENTIAL_HEADERS.has(credentialHeader)) throw new Error("Unknown credential header.");
2112
+ if (!["vault", "session", "none"].includes(credentialStorage)) throw new Error("Unknown credential storage.");
2113
+ const record = {
2114
+ id,
2115
+ name,
2116
+ presetId: text(input.presetId).slice(0, 64),
2117
+ protocol,
2118
+ baseUrl: normalizePajaLlmBaseUrl(text(input.baseUrl)),
2119
+ model,
2120
+ images: input.images === true,
2121
+ json: input.json === true,
2122
+ credentialStorage,
2123
+ ...credentialHeader ? { credentialHeader } : {}
2124
+ };
2125
+ return Object.freeze(record);
2126
+ }
2127
+ function readRecords(storage) {
2128
+ if (!storage) return [];
2129
+ try {
2130
+ const parsed = JSON.parse(storage.getItem(PAJA_LLM_CONNECTIONS_STORAGE_KEY) ?? "[]");
2131
+ if (!Array.isArray(parsed)) return [];
2132
+ const records = [];
2133
+ for (const entry of parsed) {
2134
+ if (!isRecord2(entry) || records.length >= MAX_CONNECTIONS) continue;
2135
+ try {
2136
+ records.push(normalizeRecord(entry));
2137
+ } catch {
2138
+ }
2139
+ }
2140
+ return records;
2141
+ } catch {
2142
+ return [];
2143
+ }
2144
+ }
2145
+ function storageOrNull() {
2146
+ try {
2147
+ return typeof localStorage === "undefined" ? null : localStorage;
2148
+ } catch {
2149
+ return null;
2150
+ }
2151
+ }
2152
+ function createPajaLlmConnectionStore(storage = storageOrNull()) {
2153
+ let records = readRecords(storage);
2154
+ const listeners = /* @__PURE__ */ new Set();
2155
+ const persist = () => {
2156
+ try {
2157
+ storage?.setItem(PAJA_LLM_CONNECTIONS_STORAGE_KEY, JSON.stringify(records));
2158
+ } catch {
2159
+ }
2160
+ for (const listener of listeners) listener();
2161
+ };
2162
+ return {
2163
+ list: () => records,
2164
+ get: (id) => records.find((record) => record.id === id),
2165
+ save(record) {
2166
+ const normalized = normalizeRecord({ ...record });
2167
+ const index = records.findIndex((entry) => entry.id === normalized.id);
2168
+ if (index === -1 && records.length >= MAX_CONNECTIONS) throw new Error(`Paja keeps at most ${MAX_CONNECTIONS} connections.`);
2169
+ records = index === -1 ? [...records, normalized] : records.map((entry, position) => position === index ? normalized : entry);
2170
+ persist();
2171
+ return normalized;
2172
+ },
2173
+ remove(id) {
2174
+ const next = records.filter((record) => record.id !== id);
2175
+ if (next.length === records.length) return false;
2176
+ records = next;
2177
+ persist();
2178
+ return true;
2179
+ },
2180
+ subscribe(listener) {
2181
+ listeners.add(listener);
2182
+ return () => listeners.delete(listener);
2183
+ }
2184
+ };
2185
+ }
2186
+ function describePajaLlmRoute(record) {
2187
+ const preset = LLM_PROVIDER_PRESETS.find((entry) => entry.id === record.presetId);
2188
+ const origin = new URL(record.baseUrl).origin;
2189
+ const label = preset && preset.id !== "custom" ? `${preset.label} at ${origin}` : origin;
2190
+ return `Paja (this browser) \u2192 ${label}`;
2191
+ }
2192
+ function toConnection(record) {
2193
+ return { id: record.id, name: record.name, model: record.model, route: describePajaLlmRoute(record), images: record.images, json: record.json };
2194
+ }
2195
+ function meets(record, requirements) {
2196
+ if (requirements.model !== void 0 && requirements.model !== record.model) return false;
2197
+ if (requirements.images === true && !record.images) return false;
2198
+ return !(requirements.json === true && !record.json);
2199
+ }
2200
+ function describeRequirements(requirements) {
2201
+ const parts = [
2202
+ requirements.model ? `model ${requirements.model}` : "any model",
2203
+ requirements.images ? "image input" : null,
2204
+ requirements.json ? "JSON output" : null
2205
+ ].filter((part) => part !== null);
2206
+ return parts.join(", ");
2207
+ }
2208
+ function countCharacters(request) {
2209
+ let total = 0;
2210
+ for (const message of request.messages) for (const part of message.content) total += part.type === "text" ? part.text.length : 0;
2211
+ return total;
2212
+ }
2213
+ function createPajaLlmHost(options) {
2214
+ const { store, vault, confirm, getIdentity } = options;
2215
+ const provider = options.provider ?? createHttpLlmProvider();
2216
+ async function ensureCredential(record) {
2217
+ if (record.credentialStorage === "none") return void 0;
2218
+ const existing = vault.getCredential(record.id);
2219
+ if (existing !== void 0) return existing;
2220
+ if (record.credentialStorage === "session") {
2221
+ options.openPanel();
2222
+ throw new LlmServiceError("unsupported", "This connection's API key was kept for one session only. Enter it again in Language models.");
2223
+ }
2224
+ if (!vault.isUnlocked()) {
2225
+ const unlocked = await options.requestUnlock();
2226
+ if (!unlocked) throw new LlmServiceError("user-cancelled", "The credential vault stayed locked.");
2227
+ }
2228
+ const credential = vault.getCredential(record.id);
2229
+ if (credential === void 0) {
2230
+ options.openPanel();
2231
+ throw new LlmServiceError("unsupported", "No API key is stored for this connection. Enter it again in Language models.");
2232
+ }
2233
+ return credential;
2234
+ }
2235
+ async function select(context, requirements) {
2236
+ const napplet = getIdentity(context.windowId);
2237
+ const candidates = store.list().filter((record) => meets(record, requirements));
2238
+ if (candidates.length === 0) {
2239
+ const configure = await confirm({ action: "llm-configure", windowId: context.windowId, napplet, requirements: describeRequirements(requirements), configured: store.list().length });
2240
+ if (!configure) return null;
2241
+ options.openPanel();
2242
+ throw new LlmServiceError("unsupported", "No compatible language model connection is configured yet. Add one in Paja's Language models panel, then select again.");
2243
+ }
2244
+ const chosen = await options.chooseConnection(candidates, { windowId: context.windowId, napplet, requirements });
2245
+ if (!chosen) return null;
2246
+ const current = store.get(chosen.id);
2247
+ return current && meets(current, requirements) ? toConnection(current) : null;
2248
+ }
2249
+ return {
2250
+ isConfigured: () => store.list().length > 0,
2251
+ select,
2252
+ describe(_context, connectionId) {
2253
+ const record = store.get(connectionId);
2254
+ return record ? toConnection(record) : null;
2255
+ },
2256
+ async authorize(context, connection, request) {
2257
+ const record = store.get(connection.id);
2258
+ if (!record) throw new LlmServiceError("selection-expired", "The selected connection was removed; select again.");
2259
+ await ensureCredential(record);
2260
+ return confirm({
2261
+ action: "llm",
2262
+ windowId: context.windowId,
2263
+ napplet: getIdentity(context.windowId),
2264
+ connection: record.name,
2265
+ model: record.model,
2266
+ route: describePajaLlmRoute(record),
2267
+ messages: request.messages.length,
2268
+ characters: countCharacters(request),
2269
+ images: countLlmImages(request.messages),
2270
+ format: request.format ?? "text",
2271
+ warning: "The prompt text and images below leave this device for the provider named in the route. Provider charges and retention follow that service's terms."
2272
+ });
2273
+ },
2274
+ async generate(_context, connection, request, hooks) {
2275
+ const record = store.get(connection.id);
2276
+ if (!record) throw new LlmServiceError("selection-expired", "The selected connection was removed; select again.");
2277
+ const credential = await ensureCredential(record);
2278
+ return provider({
2279
+ protocol: record.protocol,
2280
+ baseUrl: record.baseUrl,
2281
+ model: record.model,
2282
+ ...credential === void 0 ? {} : { credential },
2283
+ ...record.credentialHeader ? { credentialHeader: record.credentialHeader } : {}
2284
+ }, request, hooks.signal);
2285
+ },
2286
+ subscribe(listener) {
2287
+ const stopStore = store.subscribe(listener);
2288
+ const stopVault = vault.subscribe(listener);
2289
+ return () => {
2290
+ stopStore();
2291
+ stopVault();
2292
+ };
2293
+ }
2294
+ };
2295
+ }
2296
+
2297
+ // src/browser-llm-vault.ts
2298
+ var PAJA_LLM_VAULT_STORAGE_KEY = "kehto:paja:llm-vault:v1";
2299
+ var PAJA_LLM_VAULT_MIN_PASSWORD_LENGTH = 12;
2300
+ var VAULT_VERSION = 1;
2301
+ var KDF = "PBKDF2-SHA-256";
2302
+ var DEFAULT_ITERATIONS = 6e5;
2303
+ var SALT_BYTES = 16;
2304
+ var IV_BYTES = 12;
2305
+ function validatePajaLlmVaultPassword(password) {
2306
+ if (password.length < PAJA_LLM_VAULT_MIN_PASSWORD_LENGTH) return `Use at least ${PAJA_LLM_VAULT_MIN_PASSWORD_LENGTH} characters.`;
2307
+ if (new Set(password).size < 4) return "Use a password with more distinct characters.";
2308
+ return null;
2309
+ }
2310
+ function toBase64(bytes) {
2311
+ let binary = "";
2312
+ for (const byte of bytes) binary += String.fromCharCode(byte);
2313
+ return btoa(binary);
2314
+ }
2315
+ function fromBase64(value) {
2316
+ const binary = atob(value);
2317
+ const bytes = new Uint8Array(binary.length);
2318
+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
2319
+ return bytes;
2320
+ }
2321
+ function readDocument(storage) {
2322
+ if (!storage) return null;
2323
+ try {
2324
+ const raw = storage.getItem(PAJA_LLM_VAULT_STORAGE_KEY);
2325
+ if (raw === null) return null;
2326
+ const parsed = JSON.parse(raw);
2327
+ if (!parsed || typeof parsed !== "object") return null;
2328
+ const { version, kdf, iterations, salt, iv, ciphertext } = parsed;
2329
+ if (version !== VAULT_VERSION || kdf !== KDF) return null;
2330
+ if (typeof iterations !== "number" || typeof salt !== "string" || typeof iv !== "string" || typeof ciphertext !== "string") return null;
2331
+ return { version: VAULT_VERSION, kdf: KDF, iterations, salt, iv, ciphertext };
2332
+ } catch {
2333
+ return null;
2334
+ }
2335
+ }
2336
+ function defaultStorage() {
2337
+ try {
2338
+ return typeof localStorage === "undefined" ? null : localStorage;
2339
+ } catch {
2340
+ return null;
2341
+ }
2342
+ }
2343
+ function createPajaLlmVault(options = {}) {
2344
+ const storage = options.storage === void 0 ? defaultStorage() : options.storage;
2345
+ const crypto2 = options.crypto ?? globalThis.crypto;
2346
+ const iterations = options.iterations ?? DEFAULT_ITERATIONS;
2347
+ const session = /* @__PURE__ */ new Map();
2348
+ const listeners = /* @__PURE__ */ new Set();
2349
+ let key = null;
2350
+ let salt = null;
2351
+ let secrets = null;
2352
+ const notify = () => {
2353
+ for (const listener of listeners) listener();
2354
+ };
2355
+ async function deriveKey(password, saltBytes, rounds) {
2356
+ const material = await crypto2.subtle.importKey("raw", new TextEncoder().encode(password), "PBKDF2", false, ["deriveKey"]);
2357
+ return crypto2.subtle.deriveKey(
2358
+ { name: "PBKDF2", salt: saltBytes, iterations: rounds, hash: "SHA-256" },
2359
+ material,
2360
+ { name: "AES-GCM", length: 256 },
2361
+ false,
2362
+ ["encrypt", "decrypt"]
2363
+ );
2364
+ }
2365
+ async function persist() {
2366
+ if (!key || !salt || !secrets) throw new Error("vault is locked");
2367
+ const iv = crypto2.getRandomValues(new Uint8Array(IV_BYTES));
2368
+ const plaintext = new TextEncoder().encode(JSON.stringify(Object.fromEntries(secrets)));
2369
+ const ciphertext = await crypto2.subtle.encrypt({ name: "AES-GCM", iv }, key, plaintext);
2370
+ const document2 = { version: VAULT_VERSION, kdf: KDF, iterations, salt: toBase64(salt), iv: toBase64(iv), ciphertext: toBase64(new Uint8Array(ciphertext)) };
2371
+ try {
2372
+ storage?.setItem(PAJA_LLM_VAULT_STORAGE_KEY, JSON.stringify(document2));
2373
+ } catch {
2374
+ }
2375
+ }
2376
+ function lock() {
2377
+ key = null;
2378
+ salt = null;
2379
+ secrets = null;
2380
+ notify();
2381
+ }
2382
+ return {
2383
+ hasStoredSecrets: () => readDocument(storage) !== null,
2384
+ isUnlocked: () => key !== null && secrets !== null,
2385
+ async unlock(password) {
2386
+ const document2 = readDocument(storage);
2387
+ if (!document2) return false;
2388
+ try {
2389
+ const saltBytes = fromBase64(document2.salt);
2390
+ const candidate = await deriveKey(password, saltBytes, document2.iterations);
2391
+ const plaintext = await crypto2.subtle.decrypt({ name: "AES-GCM", iv: fromBase64(document2.iv) }, candidate, fromBase64(document2.ciphertext));
2392
+ const parsed = JSON.parse(new TextDecoder().decode(plaintext));
2393
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
2394
+ key = candidate;
2395
+ salt = saltBytes;
2396
+ secrets = new Map(Object.entries(parsed).filter((entry) => typeof entry[1] === "string"));
2397
+ notify();
2398
+ return true;
2399
+ } catch {
2400
+ return false;
2401
+ }
2402
+ },
2403
+ async create(password) {
2404
+ const problem = validatePajaLlmVaultPassword(password);
2405
+ if (problem) throw new Error(problem);
2406
+ const saltBytes = crypto2.getRandomValues(new Uint8Array(SALT_BYTES));
2407
+ key = await deriveKey(password, saltBytes, iterations);
2408
+ salt = saltBytes;
2409
+ secrets = /* @__PURE__ */ new Map();
2410
+ await persist();
2411
+ notify();
2412
+ },
2413
+ lock,
2414
+ getCredential: (connectionId) => secrets?.get(connectionId) ?? session.get(connectionId),
2415
+ async setCredential(connectionId, credential, tier) {
2416
+ if (tier === "session") {
2417
+ session.set(connectionId, credential);
2418
+ secrets?.delete(connectionId);
2419
+ if (secrets) await persist();
2420
+ return;
2421
+ }
2422
+ if (!secrets) throw new Error("Unlock the credential vault before remembering a key.");
2423
+ session.delete(connectionId);
2424
+ secrets.set(connectionId, credential);
2425
+ await persist();
2426
+ },
2427
+ async removeCredential(connectionId) {
2428
+ session.delete(connectionId);
2429
+ if (secrets?.has(connectionId)) {
2430
+ secrets.delete(connectionId);
2431
+ await persist();
2432
+ }
2433
+ },
2434
+ clear() {
2435
+ session.clear();
2436
+ try {
2437
+ storage?.removeItem(PAJA_LLM_VAULT_STORAGE_KEY);
2438
+ } catch {
2439
+ }
2440
+ lock();
2441
+ },
2442
+ subscribe(listener) {
2443
+ listeners.add(listener);
2444
+ return () => listeners.delete(listener);
2445
+ }
2446
+ };
2447
+ }
2448
+
2007
2449
  export {
2008
2450
  PajaSimulationError,
2009
2451
  PAJA_SIMULATION_DOMAINS,
@@ -2054,6 +2496,15 @@ export {
2054
2496
  PAJA_TARGET_CORS_HINT,
2055
2497
  classifyTargetCors,
2056
2498
  probeTargetCors,
2057
- startPajaServer
2499
+ startPajaServer,
2500
+ PAJA_LLM_CONNECTIONS_STORAGE_KEY,
2501
+ normalizePajaLlmBaseUrl,
2502
+ createPajaLlmConnectionStore,
2503
+ describePajaLlmRoute,
2504
+ createPajaLlmHost,
2505
+ PAJA_LLM_VAULT_STORAGE_KEY,
2506
+ PAJA_LLM_VAULT_MIN_PASSWORD_LENGTH,
2507
+ validatePajaLlmVaultPassword,
2508
+ createPajaLlmVault
2058
2509
  };
2059
- //# sourceMappingURL=chunk-FGY4IESF.js.map
2510
+ //# sourceMappingURL=chunk-EYSQOKVF.js.map