@jeffusion/bungee-core 5.23.2 → 5.24.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.
@@ -14772,6 +14772,22 @@ var require_winston_daily_rotate_file = __commonJS(function(exports, module) {
14772
14772
 
14773
14773
  // src/plugin-state/worker.ts
14774
14774
  import { Database as Database2 } from "bun:sqlite";
14775
+ import { AsyncLocalStorage } from "async_hooks";
14776
+
14777
+ // src/plugin-state/operations.ts
14778
+ var reads = new Set(["get", "readStrict", "keys", "list", "receipt", "status", "inspect", "query", "current", "version", "read", "oldestSequence", "latestSequence", "prunedThrough", "checkpoint", "maintenanceStatus", "pendingRecoveryRequests", "recoveryScanComplete", "journalNamespaces", "atomicView", "executorProofPage", "executorHasPending", "probe"]);
14779
+ var creators = new Set(["durable", "storage", "secret", "communication", "event", "snapshot", "journal"]);
14780
+ function stateMethodClass(target, method, args) {
14781
+ if (method === "close")
14782
+ return "close";
14783
+ if (method === "releaseCapability" || method === "secretRevoke" || target === "source" && method === "release" || target === "host" && method === "release")
14784
+ return "cleanup";
14785
+ if (target === "host" && (method === "open" || creators.has(method)))
14786
+ return "resource";
14787
+ if (target === "host" && method === "storageOperation")
14788
+ return ["get", "readStrict", "keys"].includes(args[1]) ? "read" : "write";
14789
+ return reads.has(method) ? "read" : "write";
14790
+ }
14775
14791
 
14776
14792
  // src/plugin-durable-state.ts
14777
14793
  var PLUGIN_DURABLE_STATE_SCHEMA_SQL = `
@@ -19392,6 +19408,106 @@ function initializePluginStateDatabase(db, plan = PLUGIN_STATE_MIGRATIONS) {
19392
19408
  }).immediate();
19393
19409
  }
19394
19410
 
19411
+ // src/plugin-state/executor-proof-store.ts
19412
+ import { createHash as createHash5 } from "crypto";
19413
+
19414
+ // src/supervision/process-lifetime-guard.ts
19415
+ import { dirname, join, resolve } from "path";
19416
+ var PROCESS_LIFETIME_GUARD_DOMAIN = "bungee-local-flock";
19417
+ function parseProcessLifetimeGuardFacts(value) {
19418
+ if (typeof value !== "object" || value === null || Array.isArray(value))
19419
+ throw new Error("process lifetime guard facts are malformed");
19420
+ const facts = value;
19421
+ const keys = ["schema", "identity", "process_instance_id", "path", "device", "inode", "host_boot_id", "domain"];
19422
+ if (Object.keys(facts).length !== keys.length || keys.some((key) => !Object.hasOwn(facts, key)) || facts.schema !== "bungee-process-lifetime-guard-v1" || facts.domain !== PROCESS_LIFETIME_GUARD_DOMAIN || typeof facts.identity !== "string" || !isLowercaseUuid(facts.identity) || typeof facts.process_instance_id !== "string" || !isLowercaseUuid(facts.process_instance_id) || typeof facts.path !== "string" || facts.path !== resolve(facts.path) || typeof facts.device !== "string" || !/^\d+$/.test(facts.device) || typeof facts.inode !== "string" || !/^[1-9]\d*$/.test(facts.inode) || typeof facts.host_boot_id !== "string" || !/^(linux:[0-9a-f-]{36}|darwin:\d+:\d+)$/.test(facts.host_boot_id)) {
19423
+ throw new Error("process lifetime guard facts are malformed");
19424
+ }
19425
+ return Object.freeze({ ...facts });
19426
+ }
19427
+ function parseHeldProcessLifetimeGuardFacts(value) {
19428
+ if (typeof value !== "object" || value === null || value.held !== true)
19429
+ throw new Error("process lifetime guard held acknowledgement is malformed");
19430
+ const { held: _held, ...body } = value;
19431
+ return Object.freeze({ ...parseProcessLifetimeGuardFacts(body), held: true });
19432
+ }
19433
+ var inheritedDescriptors = new Map;
19434
+
19435
+ // src/plugin-services/peer-executor-proof.ts
19436
+ var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
19437
+ var MARKER = new RegExp(`^${UUID}$`);
19438
+ var BOOT = new RegExp(`^(?:linux:${UUID}|win32:${UUID}|darwin:[0-9]+:[0-9]+)$`);
19439
+ var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
19440
+ var text = (value, max) => typeof value === "string" && value.length > 0 && value.length <= max;
19441
+ function decodePluginExecutorProof(value) {
19442
+ if (!object(value) || Object.keys(value).length !== 5 || !object(value.source) || !object(value.physical) || typeof value.retired !== "boolean" || !Object.hasOwn(value, "guard"))
19443
+ return null;
19444
+ const { source, physical, boot } = value;
19445
+ if (Object.keys(source).length !== 4 || source.process !== "control" || !text(source.instance, 128) || !text(source.catalog, 256) || !Number.isSafeInteger(source.generation) || source.generation < 1 || Object.keys(physical).length !== 4 || !Number.isSafeInteger(physical.pid) || physical.pid <= 0 || !text(physical.startToken, 256) || !text(physical.executable, 4096) || !text(physical.processInstanceId, 36) || !MARKER.test(physical.processInstanceId) || typeof boot !== "string" || !BOOT.test(boot))
19446
+ return null;
19447
+ let guard;
19448
+ try {
19449
+ guard = value.guard === null ? null : parseHeldProcessLifetimeGuardFacts(value.guard);
19450
+ } catch {
19451
+ return null;
19452
+ }
19453
+ if (guard !== null && guard.process_instance_id !== physical.processInstanceId)
19454
+ return null;
19455
+ return Object.freeze({
19456
+ source: Object.freeze({ process: "control", instance: source.instance, catalog: source.catalog, generation: source.generation }),
19457
+ physical: Object.freeze({ pid: physical.pid, startToken: physical.startToken, executable: physical.executable, processInstanceId: physical.processInstanceId }),
19458
+ boot,
19459
+ guard,
19460
+ retired: value.retired
19461
+ });
19462
+ }
19463
+
19464
+ // src/plugin-state/executor-proof-store.ts
19465
+ function retireExecutorProof(db, communication, id, expected) {
19466
+ const proof = decodePluginExecutorProof(expected);
19467
+ if (proof === null || createHash5("sha256").update(JSON.stringify([proof.source.process, proof.source.instance, proof.source.catalog, proof.source.generation])).digest("hex") !== id)
19468
+ throw new Error("executor_proof_invalid");
19469
+ db.transaction(() => {
19470
+ const store = communication.forNamespace("host:rpc:executors");
19471
+ const record = store.get(id);
19472
+ const current = record === null ? null : decodePluginExecutorProof(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(record.payload)));
19473
+ if (current === null || JSON.stringify({ ...current, retired: false }) !== JSON.stringify({ ...proof, retired: false }))
19474
+ throw new Error("executor_proof_changed");
19475
+ if (current.retired)
19476
+ return;
19477
+ store.ack(id);
19478
+ store.put(id, new TextEncoder().encode(JSON.stringify({ ...current, retired: true })), { required: true });
19479
+ }).immediate();
19480
+ }
19481
+ function prepareExecutorProofPage(db, communication, after) {
19482
+ if (typeof after !== "string" || after.length > 128)
19483
+ throw new Error("runtime_upgrade_cursor_invalid");
19484
+ return db.transaction(() => {
19485
+ const rows = db.query("SELECT key FROM plugin_communication_records WHERE namespace='host:rpc:executors' AND key>? ORDER BY key LIMIT 128").all(after);
19486
+ const store = communication.forNamespace("host:rpc:executors");
19487
+ let converted = 0;
19488
+ for (const row of rows) {
19489
+ const record = store.get(row.key);
19490
+ if (record === null)
19491
+ throw new Error("runtime_upgrade_record_missing");
19492
+ const raw = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(record.payload));
19493
+ if (decodePluginExecutorProof(raw) !== null)
19494
+ continue;
19495
+ if (!raw || typeof raw !== "object" || Array.isArray(raw) || Object.keys(raw).sort().join() !== "boot,physical,source")
19496
+ throw new Error("runtime_upgrade_proof_invalid");
19497
+ const proof = decodePluginExecutorProof({ ...raw, guard: null, retired: false });
19498
+ if (proof === null)
19499
+ throw new Error("runtime_upgrade_proof_invalid");
19500
+ const key = createHash5("sha256").update(JSON.stringify([proof.source.process, proof.source.instance, proof.source.catalog, proof.source.generation])).digest("hex");
19501
+ if (key !== row.key)
19502
+ throw new Error("runtime_upgrade_identity_mismatch");
19503
+ store.ack(row.key);
19504
+ store.put(row.key, new TextEncoder().encode(JSON.stringify(proof)), { required: true });
19505
+ converted++;
19506
+ }
19507
+ return { scanned: rows.length, converted, last_key: rows.at(-1)?.key ?? null };
19508
+ }).immediate();
19509
+ }
19510
+
19395
19511
  // src/plugin-state/worker.ts
19396
19512
  var db;
19397
19513
  var durable;
@@ -19403,25 +19519,33 @@ var handles = new Map;
19403
19519
  var durableNamespaces = new Map;
19404
19520
  var sources = new Map;
19405
19521
  var callbacks = new Map;
19522
+ var requests = new Map;
19523
+ var context = new AsyncLocalStorage;
19524
+ var closing = false;
19525
+ var offline = false;
19526
+ var drain = null;
19406
19527
  var nextCallback = 0;
19407
19528
  var callbackCapacity = 128;
19529
+ function physical(id) {
19530
+ const active = requests.get(id);
19531
+ if (!active?.responded || [...callbacks.values()].some((c) => c.requestId === id))
19532
+ return;
19533
+ requests.delete(id);
19534
+ self.postMessage({ type: "physical-settled", id });
19535
+ if (requests.size === 0 && callbacks.size === 0)
19536
+ drain?.();
19537
+ }
19408
19538
  function callback(token, method, args) {
19539
+ const request = context.getStore();
19540
+ if (!request || closing || Date.now() >= request.deadlineAt)
19541
+ return Promise.reject(new CommandJournalError("unknown"));
19409
19542
  if (callbacks.size >= callbackCapacity)
19410
19543
  return Promise.reject(new CommandJournalError("overloaded"));
19411
19544
  const id = ++nextCallback;
19412
19545
  return new Promise((resolve, reject) => {
19413
- const timer = setTimeout(() => {
19414
- callbacks.delete(id);
19415
- reject(new CommandJournalError("unknown"));
19416
- }, 30000);
19417
- callbacks.set(id, { resolve: (value) => {
19418
- clearTimeout(timer);
19419
- resolve(value);
19420
- }, reject: (error) => {
19421
- clearTimeout(timer);
19422
- reject(error);
19423
- } });
19424
- self.postMessage({ type: "callback", id, token, method, args });
19546
+ const timer = setTimeout(() => reject(new CommandJournalError("unknown")), Math.max(0, request.deadlineAt - Date.now()));
19547
+ callbacks.set(id, { requestId: request.id, resolve, reject, timer });
19548
+ self.postMessage({ type: "callback", id, requestId: request.id, deadlineAt: request.deadlineAt, token, method, args });
19425
19549
  });
19426
19550
  }
19427
19551
  function bind(value) {
@@ -19524,6 +19648,7 @@ async function dispatch(request) {
19524
19648
  if (db)
19525
19649
  throw new Error("plugin_state_already_open");
19526
19650
  const [path, options] = args;
19651
+ offline = options.offline === true;
19527
19652
  db = new Database2(path, { create: options.initialize === true, strict: true });
19528
19653
  db.exec("PRAGMA foreign_keys=ON; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000;");
19529
19654
  if (options.initialize !== true && db.query("PRAGMA user_version").get().user_version === 0)
@@ -19543,6 +19668,13 @@ async function dispatch(request) {
19543
19668
  if (!db)
19544
19669
  throw new Error("plugin_state_not_open");
19545
19670
  if (target === "host") {
19671
+ if (method === "retireExecutorProof")
19672
+ return retireExecutorProof(db, communication, args[0], args[1]);
19673
+ if (method === "prepareExecutorProofPage") {
19674
+ if (!offline)
19675
+ throw new Error("runtime_upgrade_requires_offline_session");
19676
+ return prepareExecutorProofPage(db, communication, args[0]);
19677
+ }
19546
19678
  if (method === "durable") {
19547
19679
  const id = bind(durable.forStorageNamespace(args[0]));
19548
19680
  durableNamespaces.set(id, args[0]);
@@ -19626,9 +19758,16 @@ async function dispatch(request) {
19626
19758
  });
19627
19759
  }).deferred();
19628
19760
  }
19761
+ if (method === "probe")
19762
+ return { database: db.query("SELECT 1 AS ok").get(), requests: requests.size, callbacks: callbacks.size, handles: handles.size, sources: sources.size };
19629
19763
  if (method === "close") {
19764
+ if (requests.size || callbacks.size)
19765
+ await new Promise((resolve) => {
19766
+ drain = resolve;
19767
+ });
19768
+ drain = null;
19630
19769
  for (const s of sources.values())
19631
- s.release?.();
19770
+ await s.release?.();
19632
19771
  sources.clear();
19633
19772
  handles.clear();
19634
19773
  kvStores.clear();
@@ -19650,7 +19789,7 @@ async function dispatch(request) {
19650
19789
  if (method === "read")
19651
19790
  return value.read(args[1], args[2]);
19652
19791
  if (method === "release") {
19653
- value.release?.();
19792
+ await value.release?.();
19654
19793
  sources.delete(args[0]);
19655
19794
  return;
19656
19795
  }
@@ -19697,16 +19836,39 @@ self.onmessage = (event) => {
19697
19836
  if (!pending)
19698
19837
  return;
19699
19838
  callbacks.delete(message.id);
19839
+ clearTimeout(pending.timer);
19700
19840
  if (message.error)
19701
19841
  pending.reject(new Error(message.error));
19702
19842
  else
19703
19843
  pending.resolve(message.value);
19844
+ physical(pending.requestId);
19704
19845
  return;
19705
19846
  }
19706
19847
  if (message.type !== "request")
19707
19848
  return;
19708
- dispatch(message).then((value) => self.postMessage({ type: "response", id: message.id, value }), (error) => {
19709
- self.postMessage({ type: "response", id: message.id, error: { name: error?.name ?? "Error", message: error?.message ?? "plugin_state_failure", code: error?.code, operationId: error?.operationId } });
19849
+ const kind = stateMethodClass(message.target, message.method, message.args);
19850
+ if (closing && kind !== "cleanup" && message.method !== "probe") {
19851
+ self.postMessage({ type: "response", id: message.id, error: { name: "Error", message: "plugin_state_closing" } });
19852
+ self.postMessage({ type: "physical-settled", id: message.id });
19853
+ return;
19854
+ }
19855
+ if (kind === "close")
19856
+ closing = true;
19857
+ else
19858
+ requests.set(message.id, { request: message, responded: false });
19859
+ context.run(message, () => dispatch(message)).then((value) => {
19860
+ self.postMessage({ type: "response", id: message.id, physical: ![...callbacks.values()].some((c) => c.requestId === message.id), value });
19861
+ }, (error) => {
19862
+ self.postMessage({ type: "response", id: message.id, physical: ![...callbacks.values()].some((c) => c.requestId === message.id), error: { name: error?.name ?? "Error", message: error?.message ?? "plugin_state_failure", code: error?.code, operationId: error?.operationId } });
19863
+ }).finally(() => {
19864
+ if (kind === "close")
19865
+ self.postMessage({ type: "physical-settled", id: message.id });
19866
+ else {
19867
+ const active = requests.get(message.id);
19868
+ if (active)
19869
+ active.responded = true;
19870
+ physical(message.id);
19871
+ }
19710
19872
  });
19711
19873
  };
19712
19874
  self.postMessage({ type: "ready" });
@@ -1439,10 +1439,12 @@ var CODEX_RESPONSES_ORIGINATOR = "codex-tui";
1439
1439
  // plugins/chatgpt-oauth/server/adapter.ts
1440
1440
  var CHAT_COMPLETIONS_PATH = "/v1/chat/completions";
1441
1441
  var RESPONSES_PATH = "/responses";
1442
+ var SEARCH_PATH = "/alpha/search";
1442
1443
  var SIWC_RESPONSES_PATH = "/v1/responses";
1443
1444
  var MODELS_PATH = "/v1/models";
1444
1445
  var CODEX_RESPONSES_PATH = "/backend-api/codex/responses";
1445
1446
  var CODEX_MODELS_PATH = "/backend-api/codex/models";
1447
+ var CODEX_SEARCH_PATH = "/backend-api/codex/alpha/search";
1446
1448
  function isResponsesRequest(url) {
1447
1449
  return url.pathname === RESPONSES_PATH;
1448
1450
  }
@@ -1879,6 +1881,10 @@ class ChatgptOauthAdapter {
1879
1881
  }));
1880
1882
  return context;
1881
1883
  }
1884
+ if (context.method.toUpperCase() === "POST" && context.url.pathname === SEARCH_PATH) {
1885
+ context.url.pathname = CODEX_SEARCH_PATH;
1886
+ return context;
1887
+ }
1882
1888
  if (context.url.pathname === CODEX_RESPONSES_PATH) {
1883
1889
  setCodexRoutingHint(context.headers, context.body);
1884
1890
  enforceCodexResponsesLite(context);
@@ -2128,4 +2134,4 @@ export {
2128
2134
  server_default as default
2129
2135
  };
2130
2136
 
2131
- //# debugId=E48A263F3FBDCAF664756E2164756E21
2137
+ //# debugId=76D0FF2CAF8435B164756E2164756E21