@ultrst-armada/kloks 2.2.3 → 2.2.5

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.
Files changed (55) hide show
  1. package/package.json +14 -2
  2. package/packages/aiko/dist/index.d.ts +95 -2
  3. package/packages/aiko/dist/index.js +277 -45
  4. package/packages/backend/dist/ai-inference/index.js +1 -1
  5. package/packages/backend/dist/ai-inference/inferenceExecutor.test.d.ts +1 -0
  6. package/packages/backend/dist/ai-models/index.js +2 -2
  7. package/packages/backend/dist/ai-routing/index.js +3 -3
  8. package/packages/backend/dist/auth/OidcBff.d.ts +50 -0
  9. package/packages/backend/dist/auth/OidcBff.test.d.ts +1 -0
  10. package/packages/backend/dist/auth/OidcBffEnv.d.ts +23 -0
  11. package/packages/backend/dist/auth/index.d.ts +2 -0
  12. package/packages/backend/dist/auth/index.js +6 -1
  13. package/packages/backend/dist/{chunk-RFPGUJAZ.js → chunk-26NAKO4V.js} +7 -7
  14. package/packages/backend/dist/{chunk-NIP22V2G.js → chunk-E2I7D52V.js} +22 -1
  15. package/packages/backend/dist/{chunk-5E6JRFUH.js → chunk-HX5TN27Y.js} +294 -4
  16. package/packages/backend/dist/{chunk-GCTQY24J.js → chunk-MK4ZRBFI.js} +7 -6
  17. package/packages/backend/dist/{chunk-LMAU62ZG.js → chunk-PT6J6UEU.js} +4 -4
  18. package/packages/backend/dist/chunk-SEKPSCWP.js +350 -0
  19. package/packages/backend/dist/{chunk-N7OUR5R5.js → chunk-YDGW7PXM.js} +1 -1
  20. package/packages/backend/dist/client/index.js +2 -2
  21. package/packages/backend/dist/connectivity/FrontendSession.d.ts +1 -0
  22. package/packages/backend/dist/connectivity/FrontendSession.dispose.test.d.ts +1 -0
  23. package/packages/backend/dist/connectivity/HTTPTransport.d.ts +1 -0
  24. package/packages/backend/dist/connectivity/HTTPTransport.operation.test.d.ts +1 -0
  25. package/packages/backend/dist/connectivity/InProcessExecutor.session.test.d.ts +1 -0
  26. package/packages/backend/dist/connectivity/RemoteExecutor.error.test.d.ts +1 -0
  27. package/packages/backend/dist/connectivity/facadeInvocation.adversarial_replay.test.d.ts +1 -0
  28. package/packages/backend/dist/connectivity/facadeInvocation.d.ts +101 -0
  29. package/packages/backend/dist/connectivity/facadeInvocation.oneUseLuthContract.test.d.ts +1 -0
  30. package/packages/backend/dist/connectivity/facadeInvocation.test.d.ts +1 -0
  31. package/packages/backend/dist/connectivity/index.d.ts +2 -0
  32. package/packages/backend/dist/connectivity/index.js +8 -4
  33. package/packages/backend/dist/index.js +7 -3
  34. package/packages/backend/dist/krnl-ai-services.js +6 -6
  35. package/packages/backend/dist/node.js +34 -25
  36. package/packages/backend/package.json +1 -1
  37. package/packages/client/dist/auth.d.ts +1 -1
  38. package/packages/client/dist/auth.js +5 -1
  39. package/packages/client/dist/{chunk-ATLIA7AJ.js → chunk-WYC7RG32.js} +5 -1
  40. package/packages/client/dist/index.d.ts +1 -1
  41. package/packages/client/dist/index.js +5 -1
  42. package/packages/client/package.json +1 -1
  43. package/packages/fod/dist/chunk-Q4OLPORH.js +111 -0
  44. package/packages/fod/dist/chunk-SMWRWNEW.js +81 -0
  45. package/packages/fod/dist/index.d.ts +12 -95
  46. package/packages/fod/dist/index.js +34 -11
  47. package/packages/fod/dist/quickJsAdapter-BRj8ixha.d.ts +34 -0
  48. package/packages/fod/dist/quickjs-node.d.ts +6 -0
  49. package/packages/fod/dist/quickjs-node.js +73 -0
  50. package/packages/fod/dist/quickjs-worker.d.ts +8 -0
  51. package/packages/fod/dist/quickjs-worker.js +51 -0
  52. package/packages/fod/dist/smallScript-wzJ-VayJ.d.ts +130 -0
  53. package/packages/fod/package.json +11 -3
  54. package/packages/backend/dist/chunk-JQKKMUCT.js +0 -0
  55. package/packages/backend/dist/{chunk-EREYT3WJ.js → chunk-LMWXONZG.js} +3 -3
@@ -1,21 +1,21 @@
1
1
  import {
2
2
  failoverExecutionEngine
3
- } from "./chunk-LMAU62ZG.js";
3
+ } from "./chunk-PT6J6UEU.js";
4
4
  import {
5
- aiProviderService
6
- } from "./chunk-SLR6SIEU.js";
5
+ modelCatalog
6
+ } from "./chunk-LMWXONZG.js";
7
7
  import {
8
8
  toolManagerService
9
9
  } from "./chunk-U4HUGPRH.js";
10
10
  import {
11
11
  inferenceExecutor
12
- } from "./chunk-GCTQY24J.js";
13
- import {
14
- modelCatalog
15
- } from "./chunk-EREYT3WJ.js";
12
+ } from "./chunk-MK4ZRBFI.js";
16
13
  import {
17
14
  keyStore
18
15
  } from "./chunk-P7H6TIEA.js";
16
+ import {
17
+ aiProviderService
18
+ } from "./chunk-SLR6SIEU.js";
19
19
 
20
20
  // src/krnl-ai-services.ts
21
21
  import {
@@ -268,7 +268,14 @@ var HTTPTransport = class {
268
268
  isConnected() {
269
269
  return this.connected;
270
270
  }
271
+ operationEndpoint(operation) {
272
+ if (typeof operation !== "string" || !operation || operation.trim() !== operation || /[\/\\?#%\x00-\x1f\x7f]/.test(operation) || operation.split(".").some((segment) => !segment || segment.trim() !== segment)) {
273
+ throw new Error("[HTTPTransport] Invalid remote operation identifier.");
274
+ }
275
+ return `${this.baseUrl}/api/${operation.split(".").map(encodeURIComponent).join("/")}`;
276
+ }
271
277
  async request(message) {
278
+ const endpoint = this.operationEndpoint(message.operation);
272
279
  const controller = new AbortController();
273
280
  const timer = setTimeout(() => controller.abort(), this.timeoutMs);
274
281
  const headers = {
@@ -279,7 +286,6 @@ var HTTPTransport = class {
279
286
  if (message.sessionId) headers["x-session-id"] = message.sessionId;
280
287
  if (message.correlationId) headers["x-correlation-id"] = message.correlationId;
281
288
  try {
282
- const endpoint = `${this.baseUrl}/api/${message.operation.replace(/\./g, "/")}`;
283
289
  const res = await fetch(endpoint, {
284
290
  method: message.type === "QUERY" ? "POST" : "POST",
285
291
  headers,
@@ -657,6 +663,7 @@ var FrontendSession = class {
657
663
  callbackRegistry;
658
664
  sequenceTracker;
659
665
  subscriptions = /* @__PURE__ */ new Set();
666
+ disposed = false;
660
667
  constructor(options = {}) {
661
668
  this.sessionId = options.sessionId || `session-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
662
669
  this.credentials = { ...options.credentials || {} };
@@ -665,6 +672,7 @@ var FrontendSession = class {
665
672
  this.sequenceTracker = options.sequenceTracker || new SequenceTracker();
666
673
  }
667
674
  setCredential(key, value) {
675
+ if (this.disposed) throw new Error("[FrontendSession] Cannot update a disposed session.");
668
676
  this.credentials[key] = value;
669
677
  return this;
670
678
  }
@@ -675,6 +683,7 @@ var FrontendSession = class {
675
683
  return { ...this.credentials };
676
684
  }
677
685
  grantCapability(capability) {
686
+ if (this.disposed) throw new Error("[FrontendSession] Cannot update a disposed session.");
678
687
  this.capabilities.add(capability);
679
688
  return this;
680
689
  }
@@ -682,6 +691,14 @@ var FrontendSession = class {
682
691
  return this.capabilities.has(capability) || this.capabilities.has("*");
683
692
  }
684
693
  trackSubscription(cleanup) {
694
+ if (this.disposed) {
695
+ try {
696
+ cleanup();
697
+ } catch {
698
+ }
699
+ return () => {
700
+ };
701
+ }
685
702
  this.subscriptions.add(cleanup);
686
703
  return () => {
687
704
  this.subscriptions.delete(cleanup);
@@ -698,6 +715,10 @@ var FrontendSession = class {
698
715
  this.subscriptions.clear();
699
716
  }
700
717
  dispose() {
718
+ if (this.disposed) return;
719
+ this.disposed = true;
720
+ this.credentials = {};
721
+ this.capabilities.clear();
701
722
  this.clearSubscriptions();
702
723
  this.callbackRegistry.clear();
703
724
  this.sequenceTracker.reset();
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  CallbackRegistry,
3
3
  EventBus
4
- } from "./chunk-NIP22V2G.js";
4
+ } from "./chunk-E2I7D52V.js";
5
5
 
6
6
  // src/connectivity/BackendContract.ts
7
7
  function createEmptyContract(version = "1.0.0") {
@@ -676,6 +676,9 @@ var InProcessExecutor = class {
676
676
  }
677
677
  async delegate(delegation) {
678
678
  if (delegation.callbackHandle) {
679
+ if (typeof delegation.sessionId !== "string" || !delegation.sessionId.trim()) {
680
+ throw new Error("[InProcessExecutor] Delegated callback requires caller session identity.");
681
+ }
679
682
  return await this.callbackRegistry.invoke(
680
683
  delegation.callbackHandle,
681
684
  [delegation.payload],
@@ -716,9 +719,9 @@ var RemoteExecutor = class {
716
719
  initCallbackListener() {
717
720
  this.transport.onMessage(async (msg) => {
718
721
  if (msg.type === "CALLBACK_REQUEST" && msg.payload) {
719
- const { handle, args } = msg.payload;
722
+ const { handle: handle2, args } = msg.payload;
720
723
  try {
721
- const result = await this.callbackRegistry.invoke(handle, args, this.sessionId);
724
+ const result = await this.callbackRegistry.invoke(handle2, args, this.sessionId);
722
725
  await this.transport.send({
723
726
  id: `cb-res-${Date.now()}`,
724
727
  type: "CALLBACK_RESULT",
@@ -783,11 +786,17 @@ var RemoteExecutor = class {
783
786
  async delegate(delegation) {
784
787
  const msg = this.prepareMessage("COMMAND", `${delegation.target}.${delegation.operation}`, delegation);
785
788
  const res = await this.transport.request(msg);
789
+ if (res.type === "ERROR") {
790
+ throw new Error(res.error?.message || `Delegation "${delegation.target}.${delegation.operation}" failed.`);
791
+ }
786
792
  return res.payload;
787
793
  }
788
794
  async submitJob(job) {
789
795
  const msg = this.prepareMessage("JOB_SUBMIT", `jobs.submit`, job);
790
796
  const res = await this.transport.request(msg);
797
+ if (res.type === "ERROR") {
798
+ throw new Error(res.error?.message || "Remote job submission failed.");
799
+ }
791
800
  return res.payload;
792
801
  }
793
802
  getSessionId() {
@@ -801,6 +810,285 @@ var RemoteExecutor = class {
801
810
  }
802
811
  };
803
812
 
813
+ // src/connectivity/facadeInvocation.ts
814
+ var FacadeInvocationDenied = class extends Error {
815
+ constructor(code, status = 403) {
816
+ super(code);
817
+ this.code = code;
818
+ this.status = status;
819
+ this.name = "FacadeInvocationDenied";
820
+ }
821
+ code;
822
+ status;
823
+ };
824
+ var handle = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
825
+ var validId = (value) => typeof value === "string" && handle.test(value) && !value.includes("..") && !value.includes("__proto__") && !value.includes("constructor") && !value.includes("prototype");
826
+ var own = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
827
+ var fail = (code, status = 403) => {
828
+ throw new FacadeInvocationDenied(code, status);
829
+ };
830
+ function assertInvocation(request) {
831
+ if (!request || typeof request !== "object" || Array.isArray(request)) fail("MALFORMED_HANDLE", 400);
832
+ if (Object.keys(request).some((key) => !["operationId", "version", "targetWorkspaceId", "invocationId", "input"].includes(key))) fail("UNTRUSTED_CLAIMS", 400);
833
+ if (![request.operationId, request.version, request.targetWorkspaceId, request.invocationId].every(validId)) fail("MALFORMED_HANDLE", 400);
834
+ if (!own(request, "input")) fail("MALFORMED_INPUT", 400);
835
+ }
836
+ function assertDescriptor(operation) {
837
+ if (!operation || !validId(operation.id) || !validId(operation.version) || !validId(operation.targetWorkspaceId) || typeof operation.name !== "string" || operation.name.length > 160) return false;
838
+ if (operation.kind === "static") return validId(operation.serviceId) && validId(operation.serviceOperation);
839
+ return operation.kind === "workflow" && validId(operation.workflowId);
840
+ }
841
+ function sameCallerIdentity(before, after) {
842
+ return before.principalId === after.principalId && before.sessionId === after.sessionId && before.sourceAppId === after.sourceAppId && before.sourceWorkspaceId === after.sourceWorkspaceId && before.audience === after.audience && before.invoker.kind === after.invoker.kind && before.invoker.id === after.invoker.id && before.depth === after.depth && before.chain.length === after.chain.length && before.chain.every((id, index) => id === after.chain[index]);
843
+ }
844
+ function sameDispatchReference(before, after) {
845
+ return before.id === after.id && before.version === after.version && before.targetWorkspaceId === after.targetWorkspaceId && before.kind === after.kind && (before.kind === "workflow" ? before.workflowId === after.workflowId : before.serviceId === after.serviceId && before.serviceOperation === after.serviceOperation);
846
+ }
847
+ function parseJson(body) {
848
+ return body.json().catch(() => fail("MALFORMED_JSON", 400));
849
+ }
850
+ function createFacadeInvocationBoundary(options) {
851
+ if (!validId(options.targetAppId)) throw new Error("Invalid target application identity");
852
+ for (const name of [
853
+ "verifyLuthCredential",
854
+ "revalidateLuthCaller",
855
+ "listCurrentOperations",
856
+ "authorize",
857
+ "deploymentEligible",
858
+ "consumeInvocation",
859
+ "invokePublishedWorkflow",
860
+ "delegateCredential"
861
+ ]) {
862
+ if (typeof options[name] !== "function") throw new Error(`Missing required facade authority: ${name}`);
863
+ }
864
+ async function callerFor(credential) {
865
+ if (!credential || typeof credential !== "string") fail("AUTH_REQUIRED", 401);
866
+ const caller = await options.verifyLuthCredential(credential, options.targetAppId);
867
+ if (!caller || !validId(caller.principalId) || !validId(caller.sourceAppId) || !validId(caller.sourceWorkspaceId) || !validId(caller.sessionId) || caller.audience !== options.targetAppId || !validId(caller.invoker?.id) || !["user", "app-agent", "endpoint-agent", "workflow-agent"].includes(caller.invoker.kind) || !Array.isArray(caller.chain) || caller.chain.length < 1 || caller.chain.some((id) => !validId(id)) || !Number.isSafeInteger(caller.depth) || caller.depth < 0 || !Number.isSafeInteger(caller.maxDepth) || caller.maxDepth < 1 || !Number.isSafeInteger(caller.remainingCalls) || caller.remainingCalls < 1 || !Number.isFinite(caller.deadlineAt) || !Number.isFinite(caller.expiresAt) || caller.expiresAt <= Date.now()) fail("AUTH_INVALID", 401);
868
+ if (caller.chain.includes(options.targetAppId) && caller.chain.at(-1) !== options.targetAppId) fail("APP_CYCLE");
869
+ if (caller.depth >= caller.maxDepth) fail("DEPTH_EXCEEDED", 429);
870
+ if (Date.now() >= caller.deadlineAt) fail("DEADLINE_EXCEEDED", 408);
871
+ return caller;
872
+ }
873
+ async function discover(credential, workspaceId, transport) {
874
+ const caller = await callerFor(credential);
875
+ if (!validId(workspaceId)) fail("INVALID_WORKSPACE", 400);
876
+ const rows = await options.listCurrentOperations(workspaceId);
877
+ const visible = [];
878
+ for (const op of rows) {
879
+ if (!assertDescriptor(op) || op.targetWorkspaceId !== workspaceId) continue;
880
+ const decision = { caller, operation: op, transport };
881
+ if (!await options.deploymentEligible(decision) || !await options.authorize(decision, "discover")) continue;
882
+ visible.push({ id: op.id, version: op.version, name: op.name, kind: op.kind, targetWorkspaceId: op.targetWorkspaceId });
883
+ }
884
+ return visible;
885
+ }
886
+ async function invoke(credential, request, transport, parentSignal) {
887
+ assertInvocation(request);
888
+ const verified = await callerFor(credential);
889
+ const caller = {
890
+ ...verified,
891
+ invoker: { ...verified.invoker },
892
+ chain: [...verified.chain]
893
+ };
894
+ const current = await options.listCurrentOperations(request.targetWorkspaceId);
895
+ const operation = current.find((op) => assertDescriptor(op) && op.id === request.operationId && op.targetWorkspaceId === request.targetWorkspaceId && op.version === request.version);
896
+ if (!operation) fail("OPERATION_UNAVAILABLE", 404);
897
+ const decision = { caller, operation, transport };
898
+ if (!await options.deploymentEligible(decision)) fail("DEPLOYMENT_UNAVAILABLE", 503);
899
+ if (!await options.authorize(decision, "invoke", request.input)) fail("ACCESS_DENIED");
900
+ if (!await options.consumeInvocation(caller, request.invocationId)) fail("REPLAY_OR_BUDGET_EXHAUSTED", 409);
901
+ const controller = new AbortController();
902
+ const deadline = Math.min(caller.deadlineAt, caller.expiresAt, Date.now() + 3e4);
903
+ const remaining = deadline - Date.now();
904
+ if (remaining <= 0) fail("DEADLINE_EXCEEDED", 408);
905
+ const abort = () => controller.abort();
906
+ parentSignal?.addEventListener("abort", abort, { once: true });
907
+ if (parentSignal?.aborted) controller.abort();
908
+ let timer;
909
+ let timedOut = false;
910
+ const abortError = () => new FacadeInvocationDenied(timedOut ? "DEADLINE_EXCEEDED" : "CANCELLED", 408);
911
+ try {
912
+ const stopped = new Promise((_, reject) => {
913
+ controller.signal.addEventListener("abort", () => reject(abortError()), { once: true });
914
+ timer = setTimeout(() => {
915
+ timedOut = true;
916
+ controller.abort();
917
+ }, remaining);
918
+ if (controller.signal.aborted) reject(abortError());
919
+ });
920
+ const work = async () => {
921
+ if (operation.kind === "workflow") {
922
+ return options.invokePublishedWorkflow({ workspaceId: operation.targetWorkspaceId, workflowId: operation.workflowId, version: operation.version }, request.input, controller.signal);
923
+ }
924
+ const services = options.facade.services;
925
+ if (!own(services, operation.serviceId)) fail("OPERATION_UNAVAILABLE", 404);
926
+ const service = services[operation.serviceId];
927
+ if (typeof service?.execute !== "function") fail("OPERATION_UNAVAILABLE", 404);
928
+ return service.execute(operation.serviceOperation, request.input, { signal: controller.signal, transport });
929
+ };
930
+ const output = await Promise.race([work(), stopped]);
931
+ const currentCaller = await options.revalidateLuthCaller(caller, options.targetAppId);
932
+ if (!currentCaller || !currentCaller.invoker || !Array.isArray(currentCaller.chain) || !Number.isFinite(currentCaller.expiresAt) || currentCaller.expiresAt <= Date.now() || !Number.isFinite(currentCaller.deadlineAt) || currentCaller.deadlineAt <= Date.now() || currentCaller.audience !== options.targetAppId) fail("AUTH_INVALID", 401);
933
+ if (!sameCallerIdentity(caller, currentCaller)) fail("CALLER_CHANGED", 401);
934
+ const currentOperations = await options.listCurrentOperations(request.targetWorkspaceId);
935
+ if (!currentOperations.some((op) => assertDescriptor(op) && sameDispatchReference(operation, op))) {
936
+ fail("OPERATION_REVOKED", 403);
937
+ }
938
+ const currentDecision = { caller: currentCaller, operation, transport };
939
+ if (!await options.deploymentEligible(currentDecision)) fail("DEPLOYMENT_UNAVAILABLE", 503);
940
+ if (!await options.authorize(currentDecision, "output", output)) fail("ACCESS_REVOKED");
941
+ if (controller.signal.aborted) throw abortError();
942
+ return { output, replyTo: { ...currentCaller.invoker }, invocationId: request.invocationId };
943
+ } finally {
944
+ if (timer) clearTimeout(timer);
945
+ parentSignal?.removeEventListener("abort", abort);
946
+ controller.abort();
947
+ }
948
+ }
949
+ async function delegate(credential, targetAppId, request, dispatch, signal) {
950
+ assertInvocation(request);
951
+ const caller = await callerFor(credential);
952
+ if (!validId(targetAppId)) fail("INVALID_TARGET", 400);
953
+ if (caller.chain.includes(targetAppId) && caller.chain.at(-1) !== targetAppId) fail("APP_CYCLE");
954
+ if (caller.depth + 1 >= caller.maxDepth || caller.remainingCalls <= 1) fail("BUDGET_EXCEEDED", 429);
955
+ const controller = new AbortController();
956
+ let timer;
957
+ let timedOut = false;
958
+ const abortError = () => new FacadeInvocationDenied(timedOut ? "DEADLINE_EXCEEDED" : "CANCELLED", 408);
959
+ const abort = () => controller.abort();
960
+ signal?.addEventListener("abort", abort, { once: true });
961
+ if (signal?.aborted) controller.abort();
962
+ try {
963
+ const remaining = Math.min(caller.deadlineAt, caller.expiresAt, Date.now() + 3e4) - Date.now();
964
+ if (remaining <= 0) fail("DEADLINE_EXCEEDED", 408);
965
+ const stopped = new Promise((_, reject) => {
966
+ controller.signal.addEventListener("abort", () => reject(abortError()), { once: true });
967
+ timer = setTimeout(() => {
968
+ timedOut = true;
969
+ controller.abort();
970
+ }, remaining);
971
+ if (controller.signal.aborted) reject(abortError());
972
+ });
973
+ const forward = async () => {
974
+ if (controller.signal.aborted) throw abortError();
975
+ const delegated = await options.delegateCredential(caller, targetAppId, request.invocationId, controller.signal);
976
+ if (controller.signal.aborted) throw abortError();
977
+ if (!delegated) fail("DELEGATION_DENIED");
978
+ return dispatch(delegated, request, controller.signal);
979
+ };
980
+ return await Promise.race([forward(), stopped]);
981
+ } finally {
982
+ if (timer) clearTimeout(timer);
983
+ signal?.removeEventListener("abort", abort);
984
+ controller.abort();
985
+ }
986
+ }
987
+ const bearer = (request) => {
988
+ const value = request.headers.get("Authorization");
989
+ const match = /^Bearer ([^\s]+)$/.exec(value ?? "");
990
+ if (!match) fail("AUTH_REQUIRED", 401);
991
+ return match[1];
992
+ };
993
+ const errorResponse = (error) => {
994
+ const denied = error instanceof FacadeInvocationDenied ? error : new FacadeInvocationDenied("INTERNAL_ERROR", 500);
995
+ return Response.json({ error: denied.code }, { status: denied.status, headers: { "Cache-Control": "no-store" } });
996
+ };
997
+ async function http(request) {
998
+ try {
999
+ const path = new URL(request.url).pathname;
1000
+ const credential = bearer(request);
1001
+ if (path === "/api/crossapp/operations" && request.method === "GET") {
1002
+ return Response.json({ operations: await discover(credential, new URL(request.url).searchParams.get("workspace") ?? "", "http") }, { headers: { "Cache-Control": "no-store" } });
1003
+ }
1004
+ if (path === "/api/crossapp/invoke" && request.method === "POST") {
1005
+ return Response.json(await invoke(credential, await parseJson(request), "http", request.signal), { headers: { "Cache-Control": "no-store" } });
1006
+ }
1007
+ return errorResponse(new FacadeInvocationDenied("NOT_FOUND", 404));
1008
+ } catch (error) {
1009
+ return errorResponse(error);
1010
+ }
1011
+ }
1012
+ async function mcp(request) {
1013
+ let id = null;
1014
+ try {
1015
+ const credential = bearer(request);
1016
+ const body = await parseJson(request);
1017
+ if (!body || typeof body !== "object" || Array.isArray(body) || body.jsonrpc !== "2.0" || typeof body.method !== "string") fail("INVALID_MCP_REQUEST", 400);
1018
+ id = body.id ?? null;
1019
+ if (body.method !== "tools/list" && body.method !== "tools/call") await callerFor(credential);
1020
+ if (body.method === "notifications/initialized" && body.id === void 0) {
1021
+ return new Response(null, { status: 202 });
1022
+ }
1023
+ if (body.id === void 0 || typeof body.id !== "string" && typeof body.id !== "number") {
1024
+ fail("INVALID_MCP_REQUEST", 400);
1025
+ }
1026
+ if (body.method === "initialize") {
1027
+ return Response.json({ jsonrpc: "2.0", id, result: {
1028
+ protocolVersion: "2025-06-18",
1029
+ capabilities: { tools: { listChanged: false } },
1030
+ serverInfo: { name: "kloks-backend-facade", version: "1.0.0" }
1031
+ } }, { headers: { "Cache-Control": "no-store" } });
1032
+ }
1033
+ if (body.method === "tools/list") {
1034
+ const workspace = body.params?.workspaceId;
1035
+ if (typeof workspace !== "string") throw new FacadeInvocationDenied("INVALID_WORKSPACE", 400);
1036
+ const operations = await discover(credential, workspace, "mcp");
1037
+ return Response.json({ jsonrpc: "2.0", id, result: { tools: operations.map((op) => ({
1038
+ name: op.id,
1039
+ description: op.name,
1040
+ inputSchema: {
1041
+ type: "object",
1042
+ properties: {
1043
+ version: { type: "string", const: op.version },
1044
+ targetWorkspaceId: { type: "string", const: op.targetWorkspaceId },
1045
+ invocationId: { type: "string", minLength: 1, maxLength: 128 },
1046
+ input: {}
1047
+ },
1048
+ required: ["version", "targetWorkspaceId", "invocationId", "input"],
1049
+ additionalProperties: false
1050
+ },
1051
+ _meta: { version: op.version, targetWorkspaceId: op.targetWorkspaceId }
1052
+ })) } }, { headers: { "Cache-Control": "no-store" } });
1053
+ }
1054
+ if (body.method === "tools/call") {
1055
+ const params = body.params;
1056
+ let invocation;
1057
+ if (typeof params?.name === "string") {
1058
+ const args = params.arguments;
1059
+ if (!args || typeof args !== "object" || Array.isArray(args) || Object.keys(args).some((key) => !["version", "targetWorkspaceId", "invocationId", "input"].includes(key)) || own(params, "invocation")) fail("INVALID_MCP_REQUEST", 400);
1060
+ const values = args;
1061
+ invocation = {
1062
+ operationId: params.name,
1063
+ version: values.version,
1064
+ targetWorkspaceId: values.targetWorkspaceId,
1065
+ invocationId: values.invocationId,
1066
+ input: values.input
1067
+ };
1068
+ } else {
1069
+ invocation = params?.invocation;
1070
+ }
1071
+ const result = await invoke(credential, invocation, "mcp", request.signal);
1072
+ const output = result.output ?? null;
1073
+ const structuredContent = output && typeof output === "object" && !Array.isArray(output) ? output : { value: output };
1074
+ return Response.json({ jsonrpc: "2.0", id, result: {
1075
+ content: [{ type: "text", text: JSON.stringify(output) }],
1076
+ structuredContent,
1077
+ isError: false
1078
+ } }, { headers: { "Cache-Control": "no-store" } });
1079
+ }
1080
+ return Response.json({ jsonrpc: "2.0", id, error: { code: -32601, message: "Method not found" } }, { status: 404 });
1081
+ } catch (error) {
1082
+ const denied = error instanceof FacadeInvocationDenied ? error : new FacadeInvocationDenied("INTERNAL_ERROR", 500);
1083
+ return Response.json(
1084
+ { jsonrpc: "2.0", id, error: { code: denied.status, message: denied.code } },
1085
+ { status: denied.status, headers: { "Cache-Control": "no-store" } }
1086
+ );
1087
+ }
1088
+ }
1089
+ return { discover, invoke, delegate, http, mcp };
1090
+ }
1091
+
804
1092
  export {
805
1093
  createEmptyContract,
806
1094
  BackendRegistry,
@@ -812,5 +1100,7 @@ export {
812
1100
  HealthMonitor,
813
1101
  LoadBalancer,
814
1102
  InProcessExecutor,
815
- RemoteExecutor
1103
+ RemoteExecutor,
1104
+ FacadeInvocationDenied,
1105
+ createFacadeInvocationBoundary
816
1106
  };
@@ -77,7 +77,7 @@ var PROVIDER_BASE_URLS = {
77
77
  };
78
78
  async function executeGoogleInference(modelId, apiKey, prompt, options) {
79
79
  const normModel = modelId.startsWith("models/") ? modelId.replace("models/", "") : modelId;
80
- const url = `https://generativelanguage.googleapis.com/v1beta/models/${normModel}:generateContent?key=${apiKey}`;
80
+ const url = `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(normModel)}:generateContent`;
81
81
  const reqBody = {
82
82
  contents: [{ parts: [{ text: prompt }] }]
83
83
  };
@@ -92,7 +92,7 @@ async function executeGoogleInference(modelId, apiKey, prompt, options) {
92
92
  }
93
93
  const res = await fetch(url, {
94
94
  method: "POST",
95
- headers: { "Content-Type": "application/json" },
95
+ headers: { "Content-Type": "application/json", "x-goog-api-key": apiKey.trim() },
96
96
  body: JSON.stringify(reqBody),
97
97
  signal: options?.signal
98
98
  });
@@ -118,15 +118,16 @@ async function executeGoogleInference(modelId, apiKey, prompt, options) {
118
118
  async function performInference(providerId, modelId, apiKey, prompt, options) {
119
119
  const start = Date.now();
120
120
  const normModel = modelId.startsWith("models/") ? modelId.replace("models/", "") : modelId;
121
+ if (!apiKey || !apiKey.trim()) {
122
+ throw new Error(`[${providerId.toUpperCase()} AUTH]: Missing API key for ${providerId}`);
123
+ }
121
124
  if (providerId === "google") {
122
125
  const res2 = await executeGoogleInference(normModel, apiKey, prompt, options);
123
126
  res2.durationMs = Date.now() - start;
124
127
  return res2;
125
128
  }
126
- if (!apiKey || apiKey.trim().length === 0) {
127
- throw new Error(`[${providerId.toUpperCase()} AUTH]: Missing API key for ${providerId}`);
128
- }
129
- const baseUrl = PROVIDER_BASE_URLS[providerId] || "https://api.groq.com/openai/v1";
129
+ const baseUrl = Object.hasOwn(PROVIDER_BASE_URLS, providerId) ? PROVIDER_BASE_URLS[providerId] : void 0;
130
+ if (!baseUrl) throw new Error(`Unsupported AI inference provider: ${providerId}`);
130
131
  const reqBody = {
131
132
  model: normModel,
132
133
  messages: options?.messages || [{ role: "user", content: prompt }],
@@ -1,13 +1,13 @@
1
- import {
2
- aiProviderService
3
- } from "./chunk-SLR6SIEU.js";
4
1
  import {
5
2
  modelCatalog,
6
3
  modelHealthService
7
- } from "./chunk-EREYT3WJ.js";
4
+ } from "./chunk-LMWXONZG.js";
8
5
  import {
9
6
  keyStore
10
7
  } from "./chunk-P7H6TIEA.js";
8
+ import {
9
+ aiProviderService
10
+ } from "./chunk-SLR6SIEU.js";
11
11
 
12
12
  // src/ai-routing/metricsLogger.ts
13
13
  var MetricsLogger = class {