@clearideas/agent-runtime-server 0.0.0-stage → 0.9.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Clear Ideas Incorporated
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,8 @@
1
+ Clear Ideas Agent Runtime
2
+ Copyright 2026 Clear Ideas Incorporated
3
+
4
+ Clear Ideas is a trademark of Clear Ideas Incorporated.
5
+
6
+ The documentation site includes @clearideas/analytics 1.16.11, distributed
7
+ under the MIT License. Its license text is available at
8
+ docs/public/assets/analytics/LICENSE.clearideas-analytics.txt.
package/README.md CHANGED
@@ -1,3 +1,45 @@
1
- # Temporary Holding Version
1
+ # @clearideas/agent-runtime-server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An OpenAI-compatible HTTP server for Agent Runtime manifests. Each served
4
+ manifest appears as a model on `/v1/models`; a chat front end or SDK sends an
5
+ ordinary `/v1/chat/completions` request, and the server runs the whole
6
+ manifest and returns its reply, streamed or not.
7
+
8
+ ```sh
9
+ # One manifest
10
+ npx agent-runtime serve ./support-chat.agent.yaml --config ./runtime.yaml --port 8000
11
+
12
+ # Several, from agent-runtime.server.yaml in the working directory
13
+ npx agent-runtime serve
14
+ ```
15
+
16
+ The server is a host. Requests select a served model and supply a
17
+ conversation or operator-mapped variables; they never supply manifests,
18
+ configuration, tools, or provider options. Manifests that declare `messages`
19
+ receive the chat as conversation turns, and a conversation ledger continues
20
+ each conversation from the runtime's own signed, compacted history. Only the
21
+ run's final output is ever streamed as content.
22
+
23
+ To embed the server in an application:
24
+
25
+ ```ts
26
+ import {
27
+ AgentServer,
28
+ createFetchHandler,
29
+ listen,
30
+ loadServerConfig,
31
+ } from "@clearideas/agent-runtime-server";
32
+
33
+ const server = await AgentServer.create({
34
+ loaded: await loadServerConfig("./agent-runtime.server.yaml"),
35
+ });
36
+ const listening = await listen(server); // node:http
37
+ // or: const handler = createFetchHandler(server); // Request → Response
38
+ ```
39
+
40
+ The package also exports the host composition shared by every Agent Runtime
41
+ host (`composeHostRuntime`, `hostRuntimeDependencies`, `loadHostRuntime`).
42
+
43
+ See [Serve agents over an OpenAI-compatible API](https://agent-runtime.clearideas.com/serving).
44
+
45
+ Requires Node.js 22.20.0 or newer.
@@ -0,0 +1,19 @@
1
+ export interface AdmissionOptions {
2
+ maxConcurrentRuns: number;
3
+ maxQueuedRequests: number;
4
+ queueTimeoutMs: number;
5
+ }
6
+ export interface AdmissionSnapshot {
7
+ active: number;
8
+ queued: number;
9
+ }
10
+ export declare class AdmissionController {
11
+ #private;
12
+ constructor(options: AdmissionOptions);
13
+ get snapshot(): AdmissionSnapshot;
14
+ /**
15
+ * Wait for a slot. Resolves with a release function that must be called
16
+ * exactly once when the run ends.
17
+ */
18
+ acquire(principal: string, limit: number | undefined, signal?: AbortSignal): Promise<() => void>;
19
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Admission control: a global and a per-principal limit on concurrent runs,
3
+ * with a bounded first-in, first-out queue. Requests beyond the queue, or
4
+ * that wait longer than the queue timeout, are refused with 429.
5
+ */
6
+ import { ServerError } from "./errors.js";
7
+ export class AdmissionController {
8
+ #options;
9
+ #activeByPrincipal = new Map();
10
+ #queue = [];
11
+ #active = 0;
12
+ constructor(options) {
13
+ this.#options = options;
14
+ }
15
+ get snapshot() {
16
+ return { active: this.#active, queued: this.#queue.length };
17
+ }
18
+ /**
19
+ * Wait for a slot. Resolves with a release function that must be called
20
+ * exactly once when the run ends.
21
+ */
22
+ acquire(principal, limit, signal) {
23
+ if (signal?.aborted)
24
+ return Promise.reject(signal.reason);
25
+ if (this.#canRun(principal, limit)) {
26
+ return Promise.resolve(this.#take(principal));
27
+ }
28
+ if (this.#queue.length >= this.#options.maxQueuedRequests) {
29
+ return Promise.reject(this.#busy("The server is at capacity; retry shortly."));
30
+ }
31
+ return new Promise((resolve, reject) => {
32
+ const timer = setTimeout(() => {
33
+ this.#remove(waiter);
34
+ reject(this.#busy("Timed out waiting for capacity; retry shortly."));
35
+ }, this.#options.queueTimeoutMs);
36
+ timer.unref?.();
37
+ const onAbort = () => {
38
+ this.#remove(waiter);
39
+ reject(signal?.reason instanceof Error
40
+ ? signal.reason
41
+ : new Error("Request aborted while queued."));
42
+ };
43
+ const waiter = {
44
+ principal,
45
+ limit,
46
+ resolve,
47
+ reject,
48
+ cleanup: () => {
49
+ clearTimeout(timer);
50
+ signal?.removeEventListener("abort", onAbort);
51
+ },
52
+ };
53
+ signal?.addEventListener("abort", onAbort, { once: true });
54
+ this.#queue.push(waiter);
55
+ });
56
+ }
57
+ #busy(message) {
58
+ return new ServerError(429, "rate_limit_exceeded", message, {
59
+ retryAfter: 1,
60
+ });
61
+ }
62
+ #canRun(principal, limit) {
63
+ if (this.#active >= this.#options.maxConcurrentRuns)
64
+ return false;
65
+ return (limit === undefined ||
66
+ (this.#activeByPrincipal.get(principal) ?? 0) < limit);
67
+ }
68
+ #take(principal) {
69
+ this.#active += 1;
70
+ this.#activeByPrincipal.set(principal, (this.#activeByPrincipal.get(principal) ?? 0) + 1);
71
+ let released = false;
72
+ return () => {
73
+ if (released)
74
+ return;
75
+ released = true;
76
+ this.#active -= 1;
77
+ const remaining = (this.#activeByPrincipal.get(principal) ?? 1) - 1;
78
+ if (remaining <= 0)
79
+ this.#activeByPrincipal.delete(principal);
80
+ else
81
+ this.#activeByPrincipal.set(principal, remaining);
82
+ this.#drain();
83
+ };
84
+ }
85
+ #remove(waiter) {
86
+ waiter.cleanup();
87
+ const index = this.#queue.indexOf(waiter);
88
+ if (index >= 0)
89
+ this.#queue.splice(index, 1);
90
+ }
91
+ /** Admit the oldest waiters that fit; a waiter blocked by its own limit does not block others. */
92
+ #drain() {
93
+ for (let index = 0; index < this.#queue.length;) {
94
+ if (this.#active >= this.#options.maxConcurrentRuns)
95
+ return;
96
+ const waiter = this.#queue[index];
97
+ if (!this.#canRun(waiter.principal, waiter.limit)) {
98
+ index += 1;
99
+ continue;
100
+ }
101
+ this.#queue.splice(index, 1);
102
+ waiter.cleanup();
103
+ waiter.resolve(this.#take(waiter.principal));
104
+ }
105
+ }
106
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Which step's text may stream as the reply.
3
+ *
4
+ * The reply is the run's final output. A step's text may stream live only
5
+ * when that step's output is certain to be the reply: it is a candidate for
6
+ * the final output, no earlier candidate produced output, and every later
7
+ * step that could contribute to the final output will provably be skipped.
8
+ * Everything else streams only once the run has committed its output.
9
+ */
10
+ import type { AgentManifest, AgentStep, VariableState } from "@clearideas/agent-runtime-contracts";
11
+ import type { ConditionEvaluator, StepExecutor } from "@clearideas/agent-runtime-core";
12
+ export type StreamMode = "auto" | "live" | "committed";
13
+ /** A top-level step whose output can become the reply. */
14
+ export interface AnswerCandidate {
15
+ stepId: string;
16
+ index: number;
17
+ /** A prompt step without structured output or tools: its text deltas are its output. */
18
+ streamable: boolean;
19
+ }
20
+ export interface AnswerPlan {
21
+ /** Top-level steps whose output can be the reply. */
22
+ candidates: AnswerCandidate[];
23
+ /** True when steps mark includeInFinalOutput; otherwise the last completed step is the reply. */
24
+ explicit: boolean;
25
+ /** Per-step state projections change output selection; never stream live. */
26
+ projected: boolean;
27
+ }
28
+ /** Computed once per served model at startup. */
29
+ export declare const planAnswer: (manifest: AgentManifest) => AnswerPlan;
30
+ /** Whether a condition reads a variable, directly or through a template. */
31
+ export declare const conditionReads: (expression: string, key: string) => boolean;
32
+ /**
33
+ * Decide, as a candidate step starts, whether its text can stream live.
34
+ * `variables` are the step's own input variables, which later `when`
35
+ * conditions are evaluated against.
36
+ */
37
+ export declare const canStreamLive: (input: {
38
+ manifest: AgentManifest;
39
+ plan: AnswerPlan;
40
+ mode: StreamMode;
41
+ step: AgentStep;
42
+ variables: Readonly<VariableState>;
43
+ /** Candidates that already completed in this run. */
44
+ completedCandidates: ReadonlySet<string>;
45
+ evaluator: ConditionEvaluator;
46
+ }) => Promise<boolean>;
47
+ /**
48
+ * Wrap a step executor so the server learns, before a top-level step runs,
49
+ * which step it is and with which variables.
50
+ */
51
+ export declare const observeStepStarts: (executor: StepExecutor, onStart: (step: AgentStep, variables: Readonly<VariableState>) => void | Promise<void>) => StepExecutor;
package/dist/answer.js ADDED
@@ -0,0 +1,100 @@
1
+ const usesStateProjection = (manifest) => {
2
+ const runtime = manifest.extensions?.agentRuntime;
3
+ return (runtime != null &&
4
+ typeof runtime === "object" &&
5
+ !Array.isArray(runtime) &&
6
+ runtime.stateProjection ===
7
+ "step-output-state-v1");
8
+ };
9
+ const isStreamable = (step) => step.type === "prompt" &&
10
+ step.outputSchema === undefined &&
11
+ (step.tools?.length ?? 0) === 0;
12
+ /** Computed once per served model at startup. */
13
+ export const planAnswer = (manifest) => {
14
+ const explicit = manifest.steps.some((step) => step.includeInFinalOutput === true);
15
+ const candidates = manifest.steps.flatMap((step, index) => !explicit || step.includeInFinalOutput === true
16
+ ? [{ stepId: step.id, index, streamable: isStreamable(step) }]
17
+ : []);
18
+ return { candidates, explicit, projected: usesStateProjection(manifest) };
19
+ };
20
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
21
+ /** Whether a condition reads a variable, directly or through a template. */
22
+ export const conditionReads = (expression, key) => {
23
+ const escaped = escapeRegExp(key);
24
+ return (new RegExp(String.raw `\{\{\s*${escaped}(?:\.|\s*\}\})`, "iu").test(expression) ||
25
+ new RegExp(String.raw `(^|[^A-Za-z0-9_.-])${escaped}(?=$|\.|[^A-Za-z0-9_.-])`, "iu").test(expression));
26
+ };
27
+ /** Variables a step writes, or undefined when they cannot be known statically. */
28
+ const knownWrites = (step) => {
29
+ if (step.type !== "prompt")
30
+ return undefined;
31
+ return step.outputVariable ? [step.outputVariable] : [];
32
+ };
33
+ /**
34
+ * Decide, as a candidate step starts, whether its text can stream live.
35
+ * `variables` are the step's own input variables, which later `when`
36
+ * conditions are evaluated against.
37
+ */
38
+ export const canStreamLive = async (input) => {
39
+ const { manifest, plan, step } = input;
40
+ if (input.mode === "committed" || plan.projected)
41
+ return false;
42
+ const candidate = plan.candidates.find((entry) => entry.stepId === step.id);
43
+ if (!candidate?.streamable)
44
+ return false;
45
+ // An earlier candidate's output would be part of the final output too.
46
+ if (plan.explicit && input.completedCandidates.size > 0)
47
+ return false;
48
+ if (input.mode === "live")
49
+ return true;
50
+ const contributes = new Set(plan.candidates.map((entry) => entry.stepId));
51
+ const written = new Set(knownWrites(step) ?? []);
52
+ let writesKnown = true;
53
+ for (const later of manifest.steps.slice(candidate.index + 1)) {
54
+ if (!plan.explicit || contributes.has(later.id)) {
55
+ // This step could add to or replace the reply; prove it is skipped.
56
+ const condition = later.when?.trim();
57
+ if (!condition || !writesKnown)
58
+ return false;
59
+ if (conditionReads(condition, "messages"))
60
+ return false;
61
+ for (const key of written) {
62
+ if (conditionReads(condition, key))
63
+ return false;
64
+ }
65
+ let runs;
66
+ try {
67
+ runs = await input.evaluator.evaluate(condition, input.variables);
68
+ }
69
+ catch {
70
+ return false;
71
+ }
72
+ if (runs)
73
+ return false;
74
+ continue;
75
+ }
76
+ const writes = knownWrites(later);
77
+ if (writes === undefined)
78
+ writesKnown = false;
79
+ else
80
+ for (const key of writes)
81
+ written.add(key);
82
+ }
83
+ return true;
84
+ };
85
+ /**
86
+ * Wrap a step executor so the server learns, before a top-level step runs,
87
+ * which step it is and with which variables.
88
+ */
89
+ export const observeStepStarts = (executor, onStart) => ({
90
+ type: executor.type,
91
+ ...(executor.preflight
92
+ ? { preflight: executor.preflight.bind(executor) }
93
+ : {}),
94
+ execute: async (context) => {
95
+ if (context.stepPath === context.step.id) {
96
+ await onStart(context.step, context.variables);
97
+ }
98
+ return executor.execute(context);
99
+ },
100
+ });
package/dist/auth.d.ts ADDED
@@ -0,0 +1,49 @@
1
+ import type { ApiKeyConfig } from "./config.js";
2
+ /** An authenticated caller. */
3
+ export interface Principal {
4
+ /** Stable id used in logs, metrics, and the conversation scope. Never the credential. */
5
+ id: string;
6
+ /** Served model names the caller may use, or "*" for all. */
7
+ models: "*" | ReadonlySet<string>;
8
+ /** Overrides the derived conversation scope (`key:<id>`). */
9
+ scope?: string;
10
+ maxConcurrentRuns?: number;
11
+ maxTotalTokensPerRequest?: number;
12
+ }
13
+ /** What an `authenticate` hook receives. */
14
+ export interface AuthenticationRequest {
15
+ method: string;
16
+ path: string;
17
+ headers: Readonly<Record<string, string | string[] | undefined>>;
18
+ }
19
+ /** A principal returned by a host `authenticate` hook. */
20
+ export interface HostPrincipal {
21
+ id: string;
22
+ models?: "*" | string[];
23
+ scope?: string;
24
+ maxConcurrentRuns?: number;
25
+ maxTotalTokensPerRequest?: number;
26
+ }
27
+ /**
28
+ * Host authentication hook, exported as `authenticate` by the runtime
29
+ * module. Return a principal to accept the request, `undefined` to decline
30
+ * (the server then reports the request as unauthenticated), or throw to
31
+ * reject it.
32
+ */
33
+ export type AuthenticateHook = (request: AuthenticationRequest) => HostPrincipal | undefined | Promise<HostPrincipal | undefined>;
34
+ export declare const ANONYMOUS_PRINCIPAL: Principal;
35
+ export interface AuthenticatorOptions {
36
+ keys: readonly ApiKeyConfig[];
37
+ environment?: Readonly<Record<string, string | undefined>>;
38
+ hook?: AuthenticateHook;
39
+ /** Accept requests without credentials when no key or hook is configured. */
40
+ allowAnonymous: boolean;
41
+ }
42
+ export declare class Authenticator {
43
+ #private;
44
+ constructor(options: AuthenticatorOptions);
45
+ /** True when requests are accepted without a credential. */
46
+ get anonymous(): boolean;
47
+ authenticate(request: AuthenticationRequest): Promise<Principal>;
48
+ }
49
+ export declare const principalCanUse: (principal: Principal, model: string) => boolean;
package/dist/auth.js ADDED
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Authentication: API keys issued by the operator, and an optional host
3
+ * hook for other credentials. The result is a principal whose id scopes
4
+ * conversations and whose models limit what it may call.
5
+ */
6
+ import { createHash, timingSafeEqual } from "node:crypto";
7
+ import { ServerError } from "./errors.js";
8
+ const sha256 = (value) => createHash("sha256").update(value, "utf8").digest();
9
+ const principalFromKey = (key) => ({
10
+ id: key.id,
11
+ models: key.models === "*" ? "*" : new Set(key.models),
12
+ ...(key.maxConcurrentRuns != null
13
+ ? { maxConcurrentRuns: key.maxConcurrentRuns }
14
+ : {}),
15
+ ...(key.maxTotalTokensPerRequest != null
16
+ ? { maxTotalTokensPerRequest: key.maxTotalTokensPerRequest }
17
+ : {}),
18
+ });
19
+ export const ANONYMOUS_PRINCIPAL = { id: "anonymous", models: "*" };
20
+ export class Authenticator {
21
+ #keys;
22
+ #hook;
23
+ #allowAnonymous;
24
+ constructor(options) {
25
+ const environment = options.environment ?? process.env;
26
+ this.#keys = options.keys.map((key) => {
27
+ if ("env" in key.key) {
28
+ const value = environment[key.key.env];
29
+ if (!value) {
30
+ throw new Error(`API key ${key.id} reads environment variable ${key.key.env}, which is not set.`);
31
+ }
32
+ return { digest: sha256(value), principal: principalFromKey(key) };
33
+ }
34
+ return {
35
+ digest: Buffer.from(key.key.sha256, "hex"),
36
+ principal: principalFromKey(key),
37
+ };
38
+ });
39
+ this.#hook = options.hook;
40
+ this.#allowAnonymous = options.allowAnonymous;
41
+ }
42
+ /** True when requests are accepted without a credential. */
43
+ get anonymous() {
44
+ return this.#allowAnonymous && this.#keys.length === 0 && !this.#hook;
45
+ }
46
+ async authenticate(request) {
47
+ if (this.anonymous)
48
+ return ANONYMOUS_PRINCIPAL;
49
+ const header = request.headers.authorization;
50
+ const value = Array.isArray(header) ? header[0] : header;
51
+ const match = value ? /^Bearer\s+(.+)$/iu.exec(value.trim()) : null;
52
+ const presented = match?.[1]?.trim();
53
+ if (presented) {
54
+ const digest = sha256(presented);
55
+ let found;
56
+ // Compare against every key so timing does not reveal which matched.
57
+ for (const key of this.#keys) {
58
+ if (timingSafeEqual(digest, key.digest))
59
+ found ??= key.principal;
60
+ }
61
+ if (found)
62
+ return found;
63
+ }
64
+ if (this.#hook) {
65
+ const principal = await this.#hook(request);
66
+ if (principal) {
67
+ if (!principal.id || typeof principal.id !== "string")
68
+ throw new Error("authenticate must return a principal with an id.");
69
+ return {
70
+ id: principal.id,
71
+ models: principal.models === undefined || principal.models === "*"
72
+ ? "*"
73
+ : new Set(principal.models),
74
+ ...(principal.scope ? { scope: principal.scope } : {}),
75
+ ...(principal.maxConcurrentRuns != null
76
+ ? { maxConcurrentRuns: principal.maxConcurrentRuns }
77
+ : {}),
78
+ ...(principal.maxTotalTokensPerRequest != null
79
+ ? { maxTotalTokensPerRequest: principal.maxTotalTokensPerRequest }
80
+ : {}),
81
+ };
82
+ }
83
+ }
84
+ throw new ServerError(401, "invalid_api_key", presented
85
+ ? "Incorrect API key provided."
86
+ : "Missing API key. Send it as an Authorization: Bearer header.", { type: "authentication_error" });
87
+ }
88
+ }
89
+ export const principalCanUse = (principal, model) => principal.models === "*" || principal.models.has(model);