@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultrst-armada/kloks",
3
- "version": "2.2.3",
3
+ "version": "2.2.5",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public",
@@ -335,6 +335,16 @@
335
335
  "./functions/portable": {
336
336
  "types": "./packages/functions/dist/portable.d.ts",
337
337
  "import": "./packages/functions/dist/portable.js"
338
+ },
339
+ "./fod/quickjs-node": {
340
+ "types": "./packages/fod/dist/quickjs-node.d.ts",
341
+ "import": "./packages/fod/dist/quickjs-node.js",
342
+ "default": "./packages/fod/dist/quickjs-node.js"
343
+ },
344
+ "./backend/auth": {
345
+ "types": "./packages/backend/dist/auth/index.d.ts",
346
+ "import": "./packages/backend/dist/auth/index.js",
347
+ "default": "./packages/backend/dist/auth/index.js"
338
348
  }
339
349
  },
340
350
  "scripts": {
@@ -351,8 +361,10 @@
351
361
  "verify:package-exports": "node scripts/verify-package-exports.mjs"
352
362
  },
353
363
  "dependencies": {
354
- "@dinilmusick/gutts": "2.2.2",
364
+ "@dinilmusick/gutts": "2.2.3",
365
+ "@jitl/quickjs-wasmfile-release-sync": "0.32.0",
355
366
  "@webcontainer/api": "^1.6.4",
367
+ "quickjs-emscripten-core": "0.32.0",
356
368
  "ws": "^8.18.0",
357
369
  "zod": "^3.24.1",
358
370
  "zustand": "^5.0.15"
@@ -7,6 +7,7 @@ interface AikoTool {
7
7
  name: string;
8
8
  description?: string;
9
9
  inputSchema?: unknown;
10
+ validateInput?: (input: unknown) => readonly string[];
10
11
  execute: (input: unknown) => Promise<unknown>;
11
12
  sourceKind: AikoSourceKind;
12
13
  sourceId: string;
@@ -32,8 +33,31 @@ interface AikoCapability {
32
33
  sourceKind: AikoSourceKind;
33
34
  sourceId: string;
34
35
  inputSchema?: unknown;
36
+ validateInput?: (input: unknown) => readonly string[];
35
37
  execute: (input: unknown) => Promise<unknown>;
36
38
  }
39
+ type AikoNaturalLanguageCandidate = {
40
+ readonly status: 'inputs';
41
+ readonly input: unknown;
42
+ } | {
43
+ readonly status: 'clarification';
44
+ readonly question: string;
45
+ };
46
+ type AikoNaturalLanguageResult = {
47
+ readonly status: 'completed';
48
+ readonly output: unknown;
49
+ } | {
50
+ readonly status: 'clarification';
51
+ readonly question: string;
52
+ readonly issues?: readonly string[];
53
+ };
54
+ interface AikoNaturalLanguageTarget {
55
+ readonly name: string;
56
+ readonly description: string;
57
+ readonly inputSchema: unknown;
58
+ readonly intelligenceSpec: AikoIntelligenceSpec;
59
+ readonly intelligenceSpecId?: string;
60
+ }
37
61
  interface AikoKey {
38
62
  id: string;
39
63
  providerId: string;
@@ -75,18 +99,25 @@ interface AikoRuntimeOptions {
75
99
  capabilities: (() => Promise<AikoCapability[]> | AikoCapability[]) | AikoCapability[];
76
100
  resolver: AikoIntelligenceResolver;
77
101
  resolveNaturalLanguage?: (agent: AikoAgentDefinition, input: string) => Promise<unknown>;
102
+ parseNaturalLanguage?: (target: AikoNaturalLanguageTarget, input: string) => Promise<AikoNaturalLanguageCandidate>;
78
103
  keys: AikoKeyRuntime;
79
104
  }
80
105
 
81
106
  declare class AikoRuntime {
82
107
  private readonly options;
83
- private readonly agents;
108
+ private readonly customAgents;
84
109
  constructor(options: AikoRuntimeOptions);
85
110
  listCapabilities(): Promise<AikoCapability[]>;
86
111
  refreshAgents(): Promise<AikoAgentDefinition[]>;
87
112
  listAgents(): Promise<AikoAgentDefinition[]>;
88
113
  executeAgent(agentId: string, input: unknown): Promise<unknown>;
114
+ /** Parse conversational input against a trusted, server-side capability contract. */
115
+ executeAgentFromNaturalLanguage(agentId: string, input: string): Promise<AikoNaturalLanguageResult>;
116
+ private requireAgent;
89
117
  createCustomAgent(name: string, capabilityIds: string[], specId?: string): Promise<AikoAgentDefinition>;
118
+ private createCapabilityAgent;
119
+ private guardCapability;
120
+ private requireCurrentCapability;
90
121
  listKeys(): Promise<AikoKey[]>;
91
122
  getActiveKey(providerId: string): Promise<AikoKey | null>;
92
123
  rotateKey(providerId: string): Promise<AikoKey | null>;
@@ -102,4 +133,66 @@ declare class AikoRuntime {
102
133
  }): Promise<AikoKey>;
103
134
  }
104
135
 
105
- export { type AikoAgentDefinition, type AikoCapability, type AikoIntelligenceResolver, type AikoIntelligenceSpec, type AikoKey, type AikoKeyRuntime, AikoRuntime, type AikoRuntimeOptions, type AikoSourceKind, type AikoTool };
136
+ interface CentralAikoIntelligenceSpec {
137
+ readonly schemaVersion: 1;
138
+ readonly specId: string;
139
+ readonly version: string;
140
+ readonly spec: AikoIntelligenceSpec;
141
+ readonly routingPolicy: {
142
+ readonly prioritiseReasoning: boolean;
143
+ readonly prioritiseDeterminism: boolean;
144
+ readonly avoidPaidProviders: boolean;
145
+ };
146
+ }
147
+ interface CentralAikoIntelligenceOptions {
148
+ /** Configured by the consuming app's server from a trusted Aiko deployment. */
149
+ readonly origin: string;
150
+ /** Resolve the caller's current Luth session and workspace, never from an agent or workflow. */
151
+ readonly scope: () => Promise<{
152
+ workspaceId: string;
153
+ luthSession: string;
154
+ } | null>;
155
+ readonly send?: typeof globalThis.fetch;
156
+ }
157
+ /** A server-side resolver that checks the authority on every use, including after revocation. */
158
+ declare function createCentralAikoIntelligenceResolver(options: CentralAikoIntelligenceOptions): AikoIntelligenceResolver & {
159
+ resolve(specId?: string): Promise<CentralAikoIntelligenceSpec>;
160
+ };
161
+
162
+ type AikoDirectoryAgentKind = 'app' | 'endpoint' | 'workflow';
163
+ interface AikoDirectoryCaller {
164
+ readonly userId: string;
165
+ readonly appId: string;
166
+ readonly workspaceId: string;
167
+ }
168
+ interface AikoDirectoryEntry {
169
+ /** Immutable ID from the canonical Aiko runtime; aliases never replace it. */
170
+ readonly id: string;
171
+ readonly kind: AikoDirectoryAgentKind;
172
+ readonly sourceId: string;
173
+ /** Workspace alias when unique, otherwise the canonical name. */
174
+ readonly name: string;
175
+ readonly canonicalName: string;
176
+ readonly description: string;
177
+ readonly alias?: string;
178
+ }
179
+ interface AikoAgentDirectoryOptions {
180
+ /** Resolve the current caller from the server-side Luth session; never accept request-body identity. */
181
+ readonly resolveCaller: () => Promise<AikoDirectoryCaller | null> | AikoDirectoryCaller | null;
182
+ /** The canonical request-time Aiko registry projection. No directory catalog is persisted. */
183
+ readonly listAgents: () => Promise<readonly AikoAgentDefinition[]> | readonly AikoAgentDefinition[];
184
+ /** Must authorize the current caller against each current agent on every list request. */
185
+ readonly authorize: (caller: AikoDirectoryCaller, agent: AikoAgentDefinition) => Promise<boolean> | boolean;
186
+ /** Workspace-scoped display metadata only. It must never grant or imply agent access. */
187
+ readonly getWorkspaceAlias?: (workspaceId: string, stableAgentId: string) => Promise<string | null | undefined> | string | null | undefined;
188
+ }
189
+ /**
190
+ * A caller-scoped projection over the canonical Aiko runtime.
191
+ * Authorization is evaluated before aliases are read, and again on every list.
192
+ * The projection never persists an agent catalog or turns a display alias into authority.
193
+ */
194
+ declare function createAikoAgentDirectory(options: AikoAgentDirectoryOptions): {
195
+ list(): Promise<readonly AikoDirectoryEntry[]>;
196
+ };
197
+
198
+ export { type AikoAgentDefinition, type AikoAgentDirectoryOptions, type AikoCapability, type AikoDirectoryAgentKind, type AikoDirectoryCaller, type AikoDirectoryEntry, type AikoIntelligenceResolver, type AikoIntelligenceSpec, type AikoKey, type AikoKeyRuntime, type AikoNaturalLanguageCandidate, type AikoNaturalLanguageResult, type AikoNaturalLanguageTarget, AikoRuntime, type AikoRuntimeOptions, type AikoSourceKind, type AikoTool, type CentralAikoIntelligenceOptions, type CentralAikoIntelligenceSpec, createAikoAgentDirectory, createCentralAikoIntelligenceResolver };
@@ -1,67 +1,142 @@
1
1
  // src/runtime.ts
2
2
  var AikoRuntime = class {
3
- options;
4
- agents = /* @__PURE__ */ new Map();
5
3
  constructor(options) {
6
4
  this.options = options;
7
- for (const agent of options.customAgents ?? []) this.agents.set(agent.id, agent);
5
+ for (const agent of options.customAgents ?? []) this.customAgents.set(agent.id, agent);
8
6
  }
7
+ options;
8
+ customAgents = /* @__PURE__ */ new Map();
9
9
  async listCapabilities() {
10
- const caps = this.options.capabilities;
11
- return typeof caps === "function" ? await caps() : caps;
10
+ const { capabilities } = this.options;
11
+ return typeof capabilities === "function" ? await capabilities() : capabilities;
12
12
  }
13
13
  async refreshAgents() {
14
- const capabilities = await this.listCapabilities();
15
- const next = /* @__PURE__ */ new Map();
16
- for (const agent of this.agents.values()) {
17
- if (agent.custom || agent.sourceKind === "custom") next.set(agent.id, agent);
18
- }
19
- for (const capability of capabilities) {
20
- const tool = { id: capability.id, name: capability.name, description: capability.description, inputSchema: capability.inputSchema, execute: capability.execute, sourceKind: capability.sourceKind, sourceId: capability.sourceId };
21
- const resolved = await this.options.resolver.resolve(void 0, { tool });
22
- const agent = {
23
- schemaVersion: "1.0.0",
24
- id: "aiko-" + capability.sourceKind + "-" + capability.sourceId,
25
- name: capability.name + " Agent",
26
- description: capability.description ?? "Aiko agent for " + capability.name,
27
- agentType: capability.sourceKind === "endpoint" ? "ENDPOINT" : "TOOL",
28
- tool,
29
- intelligenceSpec: resolved.spec,
30
- intelligenceSpecId: resolved.specId,
31
- sourceKind: capability.sourceKind,
32
- sourceId: capability.sourceId
33
- };
34
- next.set(agent.id, agent);
14
+ const agents = new Map(this.customAgents);
15
+ for (const capability of await this.listCapabilities()) {
16
+ const agent = await this.createCapabilityAgent(capability);
17
+ if (agents.has(agent.id)) throw new Error("Duplicate Aiko agent ID: " + agent.id);
18
+ agents.set(agent.id, agent);
35
19
  }
36
- this.agents.clear();
37
- for (const agent of next.values()) this.agents.set(agent.id, agent);
38
- return [...this.agents.values()];
20
+ return [...agents.values()];
39
21
  }
40
22
  async listAgents() {
41
- return this.agents.size ? [...this.agents.values()] : this.refreshAgents();
23
+ return this.refreshAgents();
42
24
  }
43
25
  async executeAgent(agentId, input) {
44
- const agent = this.agents.get(agentId) ?? (await this.refreshAgents()).find((item) => item.id === agentId);
45
- if (!agent) throw new Error("Aiko agent not found: " + agentId);
26
+ const agent = await this.requireAgent(agentId);
46
27
  const resolvedInput = typeof input === "string" && this.options.resolveNaturalLanguage ? await this.options.resolveNaturalLanguage(agent, input) : input;
47
28
  return agent.tool.execute(resolvedInput);
48
29
  }
30
+ /** Parse conversational input against a trusted, server-side capability contract. */
31
+ async executeAgentFromNaturalLanguage(agentId, input) {
32
+ const parse = this.options.parseNaturalLanguage;
33
+ if (!parse) throw new Error("Typed natural-language input is unavailable.");
34
+ const agent = await this.requireAgent(agentId);
35
+ const { tool } = agent;
36
+ if (tool.inputSchema === void 0 || !tool.validateInput) {
37
+ throw new Error("This Aiko tool has no typed natural-language input contract.");
38
+ }
39
+ if (!input.trim()) return { status: "clarification", question: "What would you like to enter?" };
40
+ const candidate = await parse({
41
+ name: tool.name,
42
+ description: tool.description ?? agent.description,
43
+ inputSchema: tool.inputSchema,
44
+ intelligenceSpec: agent.intelligenceSpec,
45
+ intelligenceSpecId: agent.intelligenceSpecId
46
+ }, input);
47
+ if (candidate?.status === "clarification" && typeof candidate.question === "string" && candidate.question.trim()) {
48
+ return { status: "clarification", question: candidate.question.trim().slice(0, 500) };
49
+ }
50
+ if (candidate?.status !== "inputs" || !Object.hasOwn(candidate, "input")) {
51
+ return { status: "clarification", question: "Could you clarify the requested input?" };
52
+ }
53
+ const current = await this.requireCurrentCapability(tool);
54
+ if (current.inputSchema === void 0 || !current.validateInput) {
55
+ throw new Error("This Aiko tool has no typed natural-language input contract.");
56
+ }
57
+ const issues = current.validateInput(candidate.input);
58
+ if (issues.length) return { status: "clarification", question: "Could you supply the required input in the expected format?", issues };
59
+ return { status: "completed", output: await current.execute(candidate.input) };
60
+ }
61
+ async requireAgent(agentId) {
62
+ const saved = this.customAgents.get(agentId);
63
+ if (saved) {
64
+ if (!saved.intelligenceSpecId) return saved;
65
+ const current = await this.options.resolver.resolve(saved.intelligenceSpecId, { agent: saved, tool: saved.tool });
66
+ return { ...saved, intelligenceSpec: current.spec, intelligenceSpecId: current.specId ?? saved.intelligenceSpecId };
67
+ }
68
+ const agent = (await this.refreshAgents()).find((item) => item.id === agentId);
69
+ if (!agent) throw new Error("Aiko agent not found: " + agentId);
70
+ return agent;
71
+ }
49
72
  async createCustomAgent(name, capabilityIds, specId) {
50
- const capabilities = await this.listCapabilities();
51
- const allowed = capabilities.filter((item) => capabilityIds.includes(item.id));
52
- if (allowed.length === 0) throw new Error("A custom Aiko agent requires at least one permitted capability.");
73
+ const current = await this.listCapabilities();
74
+ const grants = new Set(capabilityIds);
75
+ if (!grants.size || [...grants].some((id) => current.filter((capability) => capability.id === id).length !== 1)) {
76
+ throw new Error("A custom Aiko agent requires permitted capabilities for every requested tool.");
77
+ }
78
+ const allowed = current.filter((capability) => grants.has(capability.id)).map((capability) => this.guardCapability(capability));
53
79
  const resolved = await this.options.resolver.resolve(specId, {});
54
- const tool = { id: "custom-" + name, name, description: "Custom Aiko capability set", execute: async (input) => {
55
- const request = input;
56
- if (!request?.toolId || !capabilityIds.includes(request.toolId)) throw new Error("Capability is not permitted for this custom agent.");
57
- const capability = allowed.find((item) => item.id === request.toolId);
58
- if (!capability) throw new Error("Capability not found.");
59
- return capability.execute(request.input);
60
- }, sourceKind: "custom", sourceId: name };
61
- const agent = { schemaVersion: "1.0.0", id: "aiko-custom-" + name.toLowerCase().replace(/\s+/g, "-"), name, description: "Custom Aiko agent", agentType: "AIKO", tool, intelligenceSpec: resolved.spec, intelligenceSpecId: resolved.specId, sourceKind: "custom", sourceId: name, allowedToolIds: capabilityIds, custom: true };
62
- this.agents.set(agent.id, agent);
80
+ const tool = {
81
+ id: "custom-" + name,
82
+ name,
83
+ description: "Custom Aiko capability set",
84
+ execute: async (input) => {
85
+ const request = input;
86
+ const capability = allowed.find((item) => item.id === request?.toolId);
87
+ if (!capability) throw new Error("Capability is not permitted for this custom agent.");
88
+ return capability.execute(request?.input);
89
+ },
90
+ sourceKind: "custom",
91
+ sourceId: name
92
+ };
93
+ const agent = {
94
+ schemaVersion: "1.0.0",
95
+ id: "aiko-custom-" + name.toLowerCase().replace(/\s+/g, "-"),
96
+ name,
97
+ description: "Custom Aiko agent",
98
+ agentType: "AIKO",
99
+ tool,
100
+ intelligenceSpec: resolved.spec,
101
+ intelligenceSpecId: resolved.specId ?? specId,
102
+ sourceKind: "custom",
103
+ sourceId: name,
104
+ allowedToolIds: [...grants],
105
+ custom: true
106
+ };
107
+ this.customAgents.set(agent.id, agent);
63
108
  return agent;
64
109
  }
110
+ async createCapabilityAgent(capability) {
111
+ const tool = this.guardCapability(capability);
112
+ const resolved = await this.options.resolver.resolve(void 0, { tool });
113
+ return {
114
+ schemaVersion: "1.0.0",
115
+ id: "aiko-" + tool.sourceKind + "-" + tool.sourceId,
116
+ name: tool.name + " Agent",
117
+ description: tool.description ?? "Aiko agent for " + tool.name,
118
+ agentType: tool.sourceKind === "endpoint" ? "ENDPOINT" : "TOOL",
119
+ tool,
120
+ intelligenceSpec: resolved.spec,
121
+ intelligenceSpecId: resolved.specId,
122
+ sourceKind: tool.sourceKind,
123
+ sourceId: tool.sourceId
124
+ };
125
+ }
126
+ guardCapability(capability) {
127
+ return {
128
+ ...capability,
129
+ execute: async (input) => (await this.requireCurrentCapability(capability)).execute(input)
130
+ };
131
+ }
132
+ async requireCurrentCapability({ id, sourceKind, sourceId }) {
133
+ const matches = (await this.listCapabilities()).filter((item) => item.id === id);
134
+ const [current] = matches;
135
+ if (matches.length !== 1 || current.sourceKind !== sourceKind || current.sourceId !== sourceId) {
136
+ throw new Error("Aiko capability is no longer permitted.");
137
+ }
138
+ return current;
139
+ }
65
140
  listKeys() {
66
141
  return this.options.keys.listKeys();
67
142
  }
@@ -79,6 +154,163 @@ var AikoRuntime = class {
79
154
  return this.options.keys.addKey(input);
80
155
  }
81
156
  };
157
+
158
+ // src/centralIntelligence.ts
159
+ async function contentVersion(content) {
160
+ const bytes = new TextEncoder().encode(JSON.stringify(content));
161
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
162
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
163
+ }
164
+ async function parseDocument(value, specId) {
165
+ const invalid = new Error("Central Aiko returned an invalid IntelligenceSpec.");
166
+ if (!value || typeof value !== "object") throw invalid;
167
+ const document = value;
168
+ const { spec, routingPolicy, version } = document;
169
+ if (document.schemaVersion !== 1 || document.specId !== specId || typeof version !== "string" || !/^[0-9a-f]{64}$/.test(version) || !spec || typeof spec !== "object" || Array.isArray(spec) || !Object.keys(spec).length || Object.values(spec).some((value2) => typeof value2 !== "number" || !Number.isFinite(value2)) || !routingPolicy || typeof routingPolicy.prioritiseReasoning !== "boolean" || typeof routingPolicy.prioritiseDeterminism !== "boolean" || typeof routingPolicy.avoidPaidProviders !== "boolean") {
170
+ throw invalid;
171
+ }
172
+ const content = {
173
+ schemaVersion: 1,
174
+ specId,
175
+ spec,
176
+ routingPolicy: {
177
+ prioritiseReasoning: routingPolicy.prioritiseReasoning,
178
+ prioritiseDeterminism: routingPolicy.prioritiseDeterminism,
179
+ avoidPaidProviders: routingPolicy.avoidPaidProviders
180
+ }
181
+ };
182
+ try {
183
+ if (await contentVersion(content) !== version) throw invalid;
184
+ } catch {
185
+ throw invalid;
186
+ }
187
+ return { ...content, version };
188
+ }
189
+ function createCentralAikoIntelligenceResolver(options) {
190
+ const url = new URL(options.origin);
191
+ if (url.protocol !== "https:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
192
+ throw new Error("Central Aiko requires an HTTPS origin.");
193
+ }
194
+ const send = options.send ?? globalThis.fetch;
195
+ return {
196
+ async resolve(specId = "preset-agent") {
197
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$/.test(specId)) {
198
+ throw new Error("Invalid IntelligenceSpec ID.");
199
+ }
200
+ const scope = await options.scope();
201
+ const workspace = scope?.workspaceId.trim();
202
+ if (!scope?.luthSession.trim() || !workspace || workspace === "." || workspace === ".." || workspace.includes("/")) {
203
+ throw new Error("A verified Luth session and workspace are required.");
204
+ }
205
+ const path = "/api/v1/workspaces/" + encodeURIComponent(workspace) + "/intelligence-specs/" + specId;
206
+ let response;
207
+ try {
208
+ response = await send(new URL(path, url.origin), {
209
+ headers: { authorization: "Bearer " + scope.luthSession, accept: "application/json" },
210
+ redirect: "error",
211
+ cache: "no-store",
212
+ signal: AbortSignal.timeout(5e3)
213
+ });
214
+ } catch {
215
+ throw new Error("Central Aiko is unavailable.");
216
+ }
217
+ if (response.status === 401 || response.status === 403) throw new Error("Central Aiko access was denied.");
218
+ if (response.status === 404) throw new Error("Central Aiko IntelligenceSpec was not found.");
219
+ if (!response.ok) throw new Error("Central Aiko is unavailable.");
220
+ const value = await response.json().catch(() => null);
221
+ return parseDocument(value, specId);
222
+ }
223
+ };
224
+ }
225
+
226
+ // src/agentDirectory.ts
227
+ function requiredText(value, field) {
228
+ if (typeof value !== "string" || !value.trim()) throw new Error("Aiko directory agent " + field + " is required.");
229
+ return value.trim();
230
+ }
231
+ function directoryKind(agent) {
232
+ if (agent.agentType === "ENDPOINT" || agent.sourceKind === "endpoint") return "endpoint";
233
+ if (agent.sourceKind === "fod-flow") return "workflow";
234
+ return "app";
235
+ }
236
+ function canonicalAgentName(agent, kind, sourceId) {
237
+ const name = typeof agent.name === "string" ? agent.name.trim() : "";
238
+ if (name) return name;
239
+ const prefix = kind === "endpoint" ? "Endpoint" : kind === "workflow" ? "Workflow" : "App";
240
+ return prefix + " " + sourceId;
241
+ }
242
+ function safeAlias(value) {
243
+ if (typeof value !== "string") return void 0;
244
+ const alias = value.trim();
245
+ if (!alias || alias.length > 80 || /[\u0000-\u001f\u007f]/.test(alias)) return void 0;
246
+ return alias;
247
+ }
248
+ function collisionKey(value) {
249
+ return value.normalize("NFKC").toLocaleLowerCase("en-US");
250
+ }
251
+ function createAikoAgentDirectory(options) {
252
+ return {
253
+ async list() {
254
+ const caller = await options.resolveCaller();
255
+ if (!caller) throw new Error("A verified Luth caller and active workspace are required.");
256
+ const trustedCaller = Object.freeze({
257
+ userId: requiredText(caller.userId, "caller user ID"),
258
+ appId: requiredText(caller.appId, "caller app ID"),
259
+ workspaceId: requiredText(caller.workspaceId, "caller workspace ID")
260
+ });
261
+ const agents = await options.listAgents();
262
+ if (!Array.isArray(agents)) throw new Error("The canonical Aiko registry returned an invalid agent collection.");
263
+ const seen = /* @__PURE__ */ new Set();
264
+ for (const agent of agents) {
265
+ const id = requiredText(agent?.id, "stable ID");
266
+ if (seen.has(id)) throw new Error("The canonical Aiko registry returned a duplicate agent ID: " + id);
267
+ seen.add(id);
268
+ requiredText(agent.sourceId, "source ID");
269
+ }
270
+ const authorized = (await Promise.all(agents.map(
271
+ async (agent) => await options.authorize(trustedCaller, agent) ? agent : null
272
+ ))).filter((agent) => agent !== null);
273
+ const candidates = await Promise.all(authorized.map(async (agent) => {
274
+ const kind = directoryKind(agent);
275
+ const sourceId = requiredText(agent.sourceId, "source ID");
276
+ const canonicalName = canonicalAgentName(agent, kind, sourceId);
277
+ let alias;
278
+ if (options.getWorkspaceAlias) {
279
+ try {
280
+ alias = safeAlias(await options.getWorkspaceAlias(trustedCaller.workspaceId, agent.id));
281
+ } catch {
282
+ alias = void 0;
283
+ }
284
+ }
285
+ return {
286
+ id: agent.id,
287
+ kind,
288
+ sourceId,
289
+ canonicalName,
290
+ description: typeof agent.description === "string" ? agent.description.trim() : "",
291
+ alias
292
+ };
293
+ }));
294
+ const names = candidates.map((candidate) => candidate.alias ?? candidate.canonicalName);
295
+ const counts = /* @__PURE__ */ new Map();
296
+ for (const name of names) counts.set(collisionKey(name), (counts.get(collisionKey(name)) ?? 0) + 1);
297
+ return Object.freeze(candidates.map((candidate) => {
298
+ const alias = candidate.alias && counts.get(collisionKey(candidate.alias)) === 1 ? candidate.alias : void 0;
299
+ return Object.freeze({
300
+ id: candidate.id,
301
+ kind: candidate.kind,
302
+ sourceId: candidate.sourceId,
303
+ canonicalName: candidate.canonicalName,
304
+ name: alias ?? candidate.canonicalName,
305
+ description: candidate.description,
306
+ ...alias ? { alias } : {}
307
+ });
308
+ }));
309
+ }
310
+ };
311
+ }
82
312
  export {
83
- AikoRuntime
313
+ AikoRuntime,
314
+ createAikoAgentDirectory,
315
+ createCentralAikoIntelligenceResolver
84
316
  };
@@ -8,7 +8,7 @@ import {
8
8
  inferenceExecutor,
9
9
  parseErrorJson,
10
10
  performInference
11
- } from "../chunk-GCTQY24J.js";
11
+ } from "../chunk-MK4ZRBFI.js";
12
12
  import "../chunk-MAMK4GDH.js";
13
13
  export {
14
14
  DeterministicEndpointExecutor,
@@ -7,9 +7,9 @@ import {
7
7
  endpointRefresher,
8
8
  modelCatalog,
9
9
  modelHealthService
10
- } from "../chunk-EREYT3WJ.js";
11
- import "../chunk-MAMK4GDH.js";
10
+ } from "../chunk-LMWXONZG.js";
12
11
  import "../chunk-P7H6TIEA.js";
12
+ import "../chunk-MAMK4GDH.js";
13
13
  import "../chunk-JSQZAFBU.js";
14
14
  export {
15
15
  EndpointRefresher,
@@ -6,11 +6,11 @@ import {
6
6
  failoverExecutionEngine,
7
7
  healthCheckService,
8
8
  metricsLogger
9
- } from "../chunk-LMAU62ZG.js";
9
+ } from "../chunk-PT6J6UEU.js";
10
+ import "../chunk-LMWXONZG.js";
11
+ import "../chunk-P7H6TIEA.js";
10
12
  import "../chunk-SLR6SIEU.js";
11
- import "../chunk-EREYT3WJ.js";
12
13
  import "../chunk-MAMK4GDH.js";
13
- import "../chunk-P7H6TIEA.js";
14
14
  import "../chunk-JSQZAFBU.js";
15
15
  export {
16
16
  FailoverExecutionEngine,
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Canonical application-side OAuth 2.1 backend-for-frontend (BFF).
3
+ *
4
+ * Luth is the single Better Auth authorization server. Applications never
5
+ * receive Luth bearer/refresh tokens in JavaScript or redirect URLs. The BFF
6
+ * owns PKCE, the code exchange, encrypted server-side tokens and an opaque,
7
+ * first-party HttpOnly session cookie. Mount the same handler in every app.
8
+ */
9
+ export interface OAuthBffDatabase {
10
+ query(statement: string, values: readonly unknown[]): Promise<{
11
+ rows: any[];
12
+ }>;
13
+ }
14
+ export interface OAuthBffConfig {
15
+ /** Luth's exact Better Auth issuer, including /api/auth. */
16
+ issuer: string;
17
+ /** Exact, administratively verified Luth OAuth client and callback binding. */
18
+ clientId: string;
19
+ clientSecret: string;
20
+ appId: string;
21
+ redirectUri: string;
22
+ /** Stable server-side secret, never serialized to a browser or log. */
23
+ encryptionSecret: string;
24
+ database: OAuthBffDatabase;
25
+ fetcher?: typeof fetch;
26
+ now?: () => number;
27
+ }
28
+ export interface OAuthBffUser {
29
+ id: string;
30
+ email: string;
31
+ name: string;
32
+ image?: string | null;
33
+ }
34
+ export interface OAuthBffSession {
35
+ authenticated: true;
36
+ user: OAuthBffUser;
37
+ session: {
38
+ id: string;
39
+ expiresAt: string;
40
+ };
41
+ }
42
+ /** The storage contract is in db/migrations/006_kloks_oidc_bff.sql. */
43
+ export declare function createOAuthBff(config: OAuthBffConfig): {
44
+ start: (request: Request) => Promise<Response>;
45
+ callback: (request: Request) => Promise<Response>;
46
+ getSession: (request: Request) => Promise<OAuthBffSession | null>;
47
+ session: (request: Request) => Promise<Response>;
48
+ signOut: (request: Request) => Promise<Response>;
49
+ handle: (request: Request) => Promise<Response | null>;
50
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,23 @@
1
+ export interface CanonicalApplicationAuthEnvironment {
2
+ APP_URL?: unknown;
3
+ SYSTEM_DATABASE_URL?: unknown;
4
+ SYSTEM_DATABASE_URL_2?: unknown;
5
+ SYSTEM_DATABASE_URL_3?: unknown;
6
+ LUTH_OAUTH_CLIENT_ID?: unknown;
7
+ LUTH_OAUTH_CLIENT_SECRET?: unknown;
8
+ LUTH_OAUTH_BFF_SECRET?: unknown;
9
+ [key: string]: unknown;
10
+ }
11
+ /**
12
+ * Single authoritative adapter from a verified application deployment to
13
+ * Kloks' OAuth 2.1 BFF. App code must supply its compile-time canonical app ID
14
+ * and trusted deployment bindings; never accept these from request JSON.
15
+ */
16
+ export declare function createCanonicalApplicationOAuthBff(request: Request, env: CanonicalApplicationAuthEnvironment, applicationId: string): {
17
+ start: (request: Request) => Promise<Response>;
18
+ callback: (request: Request) => Promise<Response>;
19
+ getSession: (request: Request) => Promise<import("./OidcBff.js").OAuthBffSession | null>;
20
+ session: (request: Request) => Promise<Response>;
21
+ signOut: (request: Request) => Promise<Response>;
22
+ handle: (request: Request) => Promise<Response | null>;
23
+ };
@@ -1,2 +1,4 @@
1
1
  export * from './CanonicalAuthClient.js';
2
2
  export * from './UnifiedAuthCore.js';
3
+ export * from './OidcBff.js';
4
+ export * from './OidcBffEnv.js';
@@ -1,4 +1,7 @@
1
- import "../chunk-JQKKMUCT.js";
1
+ import {
2
+ createCanonicalApplicationOAuthBff,
3
+ createOAuthBff
4
+ } from "../chunk-SEKPSCWP.js";
2
5
  import {
3
6
  LuthAuthClient,
4
7
  LuthAuthClient2,
@@ -16,8 +19,10 @@ export {
16
19
  LuthAuthClient2 as CanonicalAuthClient,
17
20
  LuthAuthClient,
18
21
  LuthAuthError,
22
+ createCanonicalApplicationOAuthBff,
19
23
  createLuthAuthClient2 as createCanonicalAuthClient,
20
24
  createLuthAuthClient,
25
+ createOAuthBff,
21
26
  loginSystemUser,
22
27
  resolveClientEnvironment,
23
28
  resolveClientOrigin,