@agentpolicyspecification/http 0.1.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,187 @@
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 made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other transformations
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of discussing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or otherwise designated in writing by the copyright owner as
57
+ "Not a Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and included
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or any Contribution
81
+ embodied within the Work constitutes direct or contributory patent
82
+ infringement, then any patent licenses granted to You under this License
83
+ for that Work shall terminate as of the date such litigation is filed.
84
+
85
+ 4. Redistribution. You may reproduce and distribute copies of the
86
+ Work or Derivative Works thereof in any medium, with or without
87
+ modifications, and in Source or Object form, provided that You
88
+ meet the following conditions:
89
+
90
+ (a) You must give any other recipients of the Work or Derivative
91
+ Works a copy of this License; and
92
+
93
+ (b) You must cause any modified files to carry prominent notices
94
+ stating that You changed the files; and
95
+
96
+ (c) You must retain, in the Source form of any Derivative Works
97
+ that You distribute, all copyright, patent, trademark, and
98
+ attribution notices from the Source form of the Work,
99
+ excluding those notices that do not pertain to any part of
100
+ the Derivative Works; and
101
+
102
+ (d) If the Work includes a "NOTICE" text file as part of its
103
+ distribution, You must include a readable copy of the
104
+ attribution notices contained within such NOTICE file, in
105
+ at least one of the following places: within a NOTICE text
106
+ file distributed as part of the Derivative Works; within
107
+ the Source form or documentation, if provided along with the
108
+ Derivative Works; or, within a display generated by the
109
+ Derivative Works, if and wherever such third-party notices
110
+ normally appear. The contents of the NOTICE file are for
111
+ informational purposes only and do not modify the License.
112
+ You may add Your own attribution notices within Derivative
113
+ Works that You distribute, alongside or in addition to the
114
+ NOTICE text from the Work, provided that such additional
115
+ attribution notices cannot be construed as modifying the License.
116
+
117
+ You may add Your own license statement for Your modifications and
118
+ may provide additional grant of rights to use, copy, modify, merge,
119
+ publish, distribute, sublicense, and/or sell copies of the
120
+ Contribution, either on its own or as part of the Work.
121
+
122
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
123
+ any Contribution intentionally submitted for inclusion in the Work
124
+ by You to the Licensor shall be under the terms and conditions of
125
+ this License, without any additional terms or conditions.
126
+ Notwithstanding the above, nothing herein shall supersede or modify
127
+ the terms of any separate license agreement you may have executed
128
+ with Licensor regarding such Contributions.
129
+
130
+ 6. Trademarks. This License does not grant permission to use the trade
131
+ names, trademarks, service marks, or product names of the Licensor,
132
+ except as required for reasonable and customary use in describing the
133
+ origin of the Work and reproducing the content of the NOTICE file.
134
+
135
+ 7. Disclaimer of Warranty. Unless required by applicable law or
136
+ agreed to in writing, Licensor provides the Work (and each
137
+ Contributor provides its Contributions) on an "AS IS" BASIS,
138
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
139
+ implied, including, without limitation, any warranties or conditions
140
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
141
+ PARTICULAR PURPOSE. You are solely responsible for determining the
142
+ appropriateness of using or reproducing the Work and assume any
143
+ risks associated with Your exercise of permissions under this License.
144
+
145
+ 8. Limitation of Liability. In no event and under no legal theory,
146
+ whether in tort (including negligence), contract, or otherwise,
147
+ unless required by applicable law (such as deliberate and grossly
148
+ negligent acts) or agreed to in writing, shall any Contributor be
149
+ liable to You for damages, including any direct, indirect, special,
150
+ incidental, or exemplary damages of any character arising as a
151
+ result of this License or out of the use or inability to use the
152
+ Work (including but not limited to damages for loss of goodwill,
153
+ work stoppage, computer failure or malfunction, or all other
154
+ commercial damages or losses), even if such Contributor has been
155
+ advised of the possibility of such damages.
156
+
157
+ 9. Accepting Warranty or Liability. While redistributing the Work or
158
+ Derivative Works thereof, You may choose to offer, and charge a fee
159
+ for, acceptance of support, warranty, indemnity, or other liability
160
+ obligations and/or rights consistent with this License. However, in
161
+ accepting such obligations, You may offer only on behalf with
162
+ conditions fully consistent with this License.
163
+
164
+ END OF TERMS AND CONDITIONS
165
+
166
+ APPENDIX: How to apply the Apache License to your work.
167
+
168
+ To apply the Apache License to your work, attach the following
169
+ boilerplate notice, with the fields enclosed by brackets "[]"
170
+ replaced with your own identifying information. (Don't include
171
+ the brackets!) The text should be enclosed in the appropriate
172
+ comment syntax for the format in use. Please also include a
173
+ "NOTICE" file to clarify that the license applies to your work.
174
+
175
+ Copyright [yyyy] [name of copyright owner]
176
+
177
+ Licensed under the Apache License, Version 2.0 (the "License");
178
+ you may not use this file except in compliance with the License.
179
+ You may obtain a copy of the License at
180
+
181
+ http://www.apache.org/licenses/LICENSE-2.0
182
+
183
+ Unless required by applicable law or agreed to in writing, software
184
+ distributed under the License is distributed on an "AS IS" BASIS,
185
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
186
+ See the License for the specific language governing permissions and
187
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,13 @@
1
+ # @agentpolicyspecification/http
2
+
3
+ HTTP transport and client for the Agent Policy Specification (APS)
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @agentpolicyspecification/http
9
+ ```
10
+
11
+ ## License
12
+
13
+ Apache-2.0
@@ -0,0 +1,25 @@
1
+ import type { InputPolicy, OutputPolicy, ToolCallPolicy } from "@agentpolicyspecification/core";
2
+ import type { InputContext, OutputContext, PolicyDecision, ToolCallContext } from "@agentpolicyspecification/core";
3
+ export interface HttpClientOptions {
4
+ /** Base URL of the remote policy server, e.g. "http://localhost:3000" */
5
+ baseUrl: string;
6
+ }
7
+ export declare class HttpInputPolicy implements InputPolicy {
8
+ readonly id: string;
9
+ private readonly options;
10
+ constructor(id: string, options: HttpClientOptions);
11
+ evaluate(context: InputContext): Promise<PolicyDecision>;
12
+ }
13
+ export declare class HttpToolCallPolicy implements ToolCallPolicy {
14
+ readonly id: string;
15
+ private readonly options;
16
+ constructor(id: string, options: HttpClientOptions);
17
+ evaluate(context: ToolCallContext): Promise<PolicyDecision>;
18
+ }
19
+ export declare class HttpOutputPolicy implements OutputPolicy {
20
+ readonly id: string;
21
+ private readonly options;
22
+ constructor(id: string, options: HttpClientOptions);
23
+ evaluate(context: OutputContext): Promise<PolicyDecision>;
24
+ }
25
+ //# sourceMappingURL=http-policy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http-policy.d.ts","sourceRoot":"","sources":["../src/http-policy.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAChG,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AAGnH,MAAM,WAAW,iBAAiB;IAChC,yEAAyE;IACzE,OAAO,EAAE,MAAM,CAAC;CACjB;AA4CD,qBAAa,eAAgB,YAAW,WAAW;IAE/C,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB,OAAO,CAAC,QAAQ,CAAC,OAAO;gBADf,EAAE,EAAE,MAAM,EACF,OAAO,EAAE,iBAAiB;IAG7C,QAAQ,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,cAAc,CAAC;CAGzD;AAED,qBAAa,kBAAmB,YAAW,cAAc;IAErD,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB,OAAO,CAAC,QAAQ,CAAC,OAAO;gBADf,EAAE,EAAE,MAAM,EACF,OAAO,EAAE,iBAAiB;IAG7C,QAAQ,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,cAAc,CAAC;CAG5D;AAED,qBAAa,gBAAiB,YAAW,YAAY;IAEjD,QAAQ,CAAC,EAAE,EAAE,MAAM;IACnB,OAAO,CAAC,QAAQ,CAAC,OAAO;gBADf,EAAE,EAAE,MAAM,EACF,OAAO,EAAE,iBAAiB;IAG7C,QAAQ,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,cAAc,CAAC;CAG1D"}
@@ -0,0 +1,66 @@
1
+ import { PolicyEvaluationError } from "@agentpolicyspecification/core";
2
+ async function evaluate(id, options, context, interceptionPoint) {
3
+ const url = `${options.baseUrl}/aps/evaluate`;
4
+ let response;
5
+ try {
6
+ response = await fetch(url, {
7
+ method: "POST",
8
+ headers: { "Content-Type": "application/json" },
9
+ body: JSON.stringify({ policy_id: id, interception_point: interceptionPoint, context }),
10
+ });
11
+ }
12
+ catch (cause) {
13
+ throw new PolicyEvaluationError({ policy_id: id, interception_point: interceptionPoint, cause });
14
+ }
15
+ if (!response.ok) {
16
+ const text = await response.text().catch(() => "");
17
+ throw new PolicyEvaluationError({
18
+ policy_id: id,
19
+ interception_point: interceptionPoint,
20
+ cause: new Error(`Remote policy server returned HTTP ${response.status}: ${text}`),
21
+ });
22
+ }
23
+ let decision;
24
+ try {
25
+ decision = (await response.json());
26
+ }
27
+ catch (cause) {
28
+ throw new PolicyEvaluationError({ policy_id: id, interception_point: interceptionPoint, cause });
29
+ }
30
+ return decision;
31
+ }
32
+ // ─── Typed wrappers per interception point ────────────────────────────────────
33
+ export class HttpInputPolicy {
34
+ id;
35
+ options;
36
+ constructor(id, options) {
37
+ this.id = id;
38
+ this.options = options;
39
+ }
40
+ evaluate(context) {
41
+ return evaluate(this.id, this.options, context, "input");
42
+ }
43
+ }
44
+ export class HttpToolCallPolicy {
45
+ id;
46
+ options;
47
+ constructor(id, options) {
48
+ this.id = id;
49
+ this.options = options;
50
+ }
51
+ evaluate(context) {
52
+ return evaluate(this.id, this.options, context, "tool_call");
53
+ }
54
+ }
55
+ export class HttpOutputPolicy {
56
+ id;
57
+ options;
58
+ constructor(id, options) {
59
+ this.id = id;
60
+ this.options = options;
61
+ }
62
+ evaluate(context) {
63
+ return evaluate(this.id, this.options, context, "output");
64
+ }
65
+ }
66
+ //# sourceMappingURL=http-policy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http-policy.js","sourceRoot":"","sources":["../src/http-policy.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,qBAAqB,EAAE,MAAM,gCAAgC,CAAC;AASvE,KAAK,UAAU,QAAQ,CACrB,EAAU,EACV,OAA0B,EAC1B,OAAmB,EACnB,iBAAmD;IAEnD,MAAM,GAAG,GAAG,GAAG,OAAO,CAAC,OAAO,eAAe,CAAC;IAE9C,IAAI,QAAkB,CAAC;IACvB,IAAI,CAAC;QACH,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,EAAE;YAC1B,MAAM,EAAE,MAAM;YACd,OAAO,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE;YAC/C,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,SAAS,EAAE,EAAE,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,OAAO,EAAE,CAAC;SACxF,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,qBAAqB,CAAC,EAAE,SAAS,EAAE,EAAE,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,KAAK,EAAE,CAAC,CAAC;IACnG,CAAC;IAED,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;QACjB,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;QACnD,MAAM,IAAI,qBAAqB,CAAC;YAC9B,SAAS,EAAE,EAAE;YACb,kBAAkB,EAAE,iBAAiB;YACrC,KAAK,EAAE,IAAI,KAAK,CAAC,sCAAsC,QAAQ,CAAC,MAAM,KAAK,IAAI,EAAE,CAAC;SACnF,CAAC,CAAC;IACL,CAAC;IAED,IAAI,QAAwB,CAAC;IAC7B,IAAI,CAAC;QACH,QAAQ,GAAG,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAmB,CAAC;IACvD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,qBAAqB,CAAC,EAAE,SAAS,EAAE,EAAE,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,KAAK,EAAE,CAAC,CAAC;IACnG,CAAC;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,iFAAiF;AAEjF,MAAM,OAAO,eAAe;IAEf;IACQ;IAFnB,YACW,EAAU,EACF,OAA0B;QADlC,OAAE,GAAF,EAAE,CAAQ;QACF,YAAO,GAAP,OAAO,CAAmB;IAC1C,CAAC;IAEJ,QAAQ,CAAC,OAAqB;QAC5B,OAAO,QAAQ,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAC3D,CAAC;CACF;AAED,MAAM,OAAO,kBAAkB;IAElB;IACQ;IAFnB,YACW,EAAU,EACF,OAA0B;QADlC,OAAE,GAAF,EAAE,CAAQ;QACF,YAAO,GAAP,OAAO,CAAmB;IAC1C,CAAC;IAEJ,QAAQ,CAAC,OAAwB;QAC/B,OAAO,QAAQ,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,OAAO,EAAE,OAAO,EAAE,WAAW,CAAC,CAAC;IAC/D,CAAC;CACF;AAED,MAAM,OAAO,gBAAgB;IAEhB;IACQ;IAFnB,YACW,EAAU,EACF,OAA0B;QADlC,OAAE,GAAF,EAAE,CAAQ;QACF,YAAO,GAAP,OAAO,CAAmB;IAC1C,CAAC;IAEJ,QAAQ,CAAC,OAAsB;QAC7B,OAAO,QAAQ,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;IAC5D,CAAC;CACF"}
@@ -0,0 +1,3 @@
1
+ export { HttpInputPolicy, HttpToolCallPolicy, HttpOutputPolicy } from "./http-policy.js";
2
+ export type { HttpClientOptions } from "./http-policy.js";
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACzF,YAAY,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { HttpInputPolicy, HttpToolCallPolicy, HttpOutputPolicy } from "./http-policy.js";
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC"}
package/jest.config.js ADDED
@@ -0,0 +1,21 @@
1
+ export default {
2
+ preset: "ts-jest/presets/default-esm",
3
+ testEnvironment: "node",
4
+ testMatch: ["**/test/**/*.test.ts"],
5
+ collectCoverage: true,
6
+ coverageDirectory: "coverage",
7
+ coverageProvider: "v8",
8
+ collectCoverageFrom: ["src/**/*.ts"],
9
+ transform: {
10
+ "^.+\\.tsx?$": [
11
+ "ts-jest",
12
+ {
13
+ useESM: true,
14
+ tsconfig: "./tsconfig.test.json",
15
+ },
16
+ ],
17
+ },
18
+ moduleNameMapper: {
19
+ "^(\\.{1,2}/.*)\\.js$": "$1",
20
+ },
21
+ };
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@agentpolicyspecification/http",
3
+ "version": "0.1.0",
4
+ "description": "HTTP remote policy adapters for the Agent Policy Specification (APS)",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "type": "module",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/index.js",
11
+ "types": "./dist/index.d.ts"
12
+ }
13
+ },
14
+ "dependencies": {
15
+ "@agentpolicyspecification/core": "0.1.0"
16
+ },
17
+ "devDependencies": {
18
+ "@jest/globals": "^29.7.0",
19
+ "@types/jest": "^29.5.0",
20
+ "@types/node": "^20.0.0",
21
+ "jest": "^29.5.0",
22
+ "ts-jest": "^29.1.0",
23
+ "typescript": "^5.4.0"
24
+ },
25
+ "license": "Apache-2.0",
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/agentpolicyspecification/aps-typescript.git",
29
+ "directory": "packages/http"
30
+ },
31
+ "author": "Pascal Wilbrink",
32
+ "bugs": {
33
+ "url": "https://github.com/agentpolicyspecification/aps-typescript/issues"
34
+ },
35
+ "homepage": "https://github.com/agentpolicyspecification/aps-typescript/tree/main/packages/http#readme",
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "scripts": {
40
+ "build": "tsc",
41
+ "test": "NODE_OPTIONS=--experimental-vm-modules jest --passWithNoTests"
42
+ }
43
+ }
@@ -0,0 +1,83 @@
1
+ import type { InputPolicy, OutputPolicy, ToolCallPolicy } from "@agentpolicyspecification/core";
2
+ import type { InputContext, OutputContext, PolicyDecision, ToolCallContext } from "@agentpolicyspecification/core";
3
+ import { PolicyEvaluationError } from "@agentpolicyspecification/core";
4
+
5
+ export interface HttpClientOptions {
6
+ /** Base URL of the remote policy server, e.g. "http://localhost:3000" */
7
+ baseUrl: string;
8
+ }
9
+
10
+ type AnyContext = InputContext | ToolCallContext | OutputContext;
11
+
12
+ async function evaluate(
13
+ id: string,
14
+ options: HttpClientOptions,
15
+ context: AnyContext,
16
+ interceptionPoint: "input" | "tool_call" | "output"
17
+ ): Promise<PolicyDecision> {
18
+ const url = `${options.baseUrl}/aps/evaluate`;
19
+
20
+ let response: Response;
21
+ try {
22
+ response = await fetch(url, {
23
+ method: "POST",
24
+ headers: { "Content-Type": "application/json" },
25
+ body: JSON.stringify({ policy_id: id, interception_point: interceptionPoint, context }),
26
+ });
27
+ } catch (cause) {
28
+ throw new PolicyEvaluationError({ policy_id: id, interception_point: interceptionPoint, cause });
29
+ }
30
+
31
+ if (!response.ok) {
32
+ const text = await response.text().catch(() => "");
33
+ throw new PolicyEvaluationError({
34
+ policy_id: id,
35
+ interception_point: interceptionPoint,
36
+ cause: new Error(`Remote policy server returned HTTP ${response.status}: ${text}`),
37
+ });
38
+ }
39
+
40
+ let decision: PolicyDecision;
41
+ try {
42
+ decision = (await response.json()) as PolicyDecision;
43
+ } catch (cause) {
44
+ throw new PolicyEvaluationError({ policy_id: id, interception_point: interceptionPoint, cause });
45
+ }
46
+
47
+ return decision;
48
+ }
49
+
50
+ // ─── Typed wrappers per interception point ────────────────────────────────────
51
+
52
+ export class HttpInputPolicy implements InputPolicy {
53
+ constructor(
54
+ readonly id: string,
55
+ private readonly options: HttpClientOptions
56
+ ) {}
57
+
58
+ evaluate(context: InputContext): Promise<PolicyDecision> {
59
+ return evaluate(this.id, this.options, context, "input");
60
+ }
61
+ }
62
+
63
+ export class HttpToolCallPolicy implements ToolCallPolicy {
64
+ constructor(
65
+ readonly id: string,
66
+ private readonly options: HttpClientOptions
67
+ ) {}
68
+
69
+ evaluate(context: ToolCallContext): Promise<PolicyDecision> {
70
+ return evaluate(this.id, this.options, context, "tool_call");
71
+ }
72
+ }
73
+
74
+ export class HttpOutputPolicy implements OutputPolicy {
75
+ constructor(
76
+ readonly id: string,
77
+ private readonly options: HttpClientOptions
78
+ ) {}
79
+
80
+ evaluate(context: OutputContext): Promise<PolicyDecision> {
81
+ return evaluate(this.id, this.options, context, "output");
82
+ }
83
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { HttpInputPolicy, HttpToolCallPolicy, HttpOutputPolicy } from "./http-policy.js";
2
+ export type { HttpClientOptions } from "./http-policy.js";
@@ -0,0 +1,189 @@
1
+ import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
2
+ import { describe, it, expect, beforeAll, afterAll, beforeEach } from "@jest/globals";
3
+ import { ApsEngine, PolicyDenialError, PolicyEvaluationError } from "@agentpolicyspecification/core";
4
+ import { HttpInputPolicy, HttpToolCallPolicy, HttpOutputPolicy } from "../src/http-policy.js";
5
+ import type { InputContext, ToolCallContext, OutputContext, PolicyDecision } from "@agentpolicyspecification/core";
6
+
7
+ // ─── Mock server ──────────────────────────────────────────────────────────────
8
+
9
+ type Handler = (body: unknown) => { status: number; body: unknown };
10
+
11
+ let handler: Handler = () => ({ status: 200, body: { decision: "allow" } });
12
+
13
+ const server = createServer((req: IncomingMessage, res: ServerResponse) => {
14
+ let raw = "";
15
+ req.on("data", (chunk) => { raw += chunk; });
16
+ req.on("end", () => {
17
+ let parsed: unknown;
18
+ try { parsed = JSON.parse(raw); } catch { parsed = null; }
19
+ const { status, body } = handler(parsed);
20
+ res.writeHead(status, { "Content-Type": "application/json" });
21
+ res.end(JSON.stringify(body));
22
+ });
23
+ });
24
+
25
+ let baseUrl: string;
26
+
27
+ beforeAll(() => new Promise<void>((resolve) => server.listen(0, "127.0.0.1", () => {
28
+ const addr = server.address() as { port: number };
29
+ baseUrl = `http://127.0.0.1:${addr.port}`;
30
+ resolve();
31
+ })));
32
+
33
+ afterAll(() => new Promise<void>((resolve, reject) =>
34
+ server.close((err) => err ? reject(err) : resolve())
35
+ ));
36
+
37
+ beforeEach(() => {
38
+ handler = () => ({ status: 200, body: { decision: "allow" } });
39
+ });
40
+
41
+ // ─── Fixtures ─────────────────────────────────────────────────────────────────
42
+
43
+ function inputCtx(content: string): InputContext {
44
+ return {
45
+ messages: [{ role: "user", content }],
46
+ metadata: { agent_id: "a1", session_id: "s1", timestamp: "2026-01-01T00:00:00Z" },
47
+ };
48
+ }
49
+
50
+ function toolCallCtx(tool_name: string): ToolCallContext {
51
+ return {
52
+ tool_name,
53
+ arguments: {},
54
+ calling_message: { role: "assistant", content: "calling tool" },
55
+ metadata: { agent_id: "a1", session_id: "s1", timestamp: "2026-01-01T00:00:00Z" },
56
+ };
57
+ }
58
+
59
+ function outputCtx(content: string): OutputContext {
60
+ return {
61
+ response: { role: "assistant", content },
62
+ metadata: { agent_id: "a1", session_id: "s1", timestamp: "2026-01-01T00:00:00Z" },
63
+ };
64
+ }
65
+
66
+ // ─── HttpInputPolicy ──────────────────────────────────────────────────────────
67
+
68
+ describe("HttpInputPolicy", () => {
69
+ it("returns the decision from the remote server", async () => {
70
+ handler = () => ({ status: 200, body: { decision: "allow" } });
71
+ const policy = new HttpInputPolicy("test-input", { baseUrl });
72
+ const decision = await policy.evaluate(inputCtx("hello"));
73
+ expect(decision.decision).toBe("allow");
74
+ });
75
+
76
+ it("returns a deny decision with reason", async () => {
77
+ handler = () => ({ status: 200, body: { decision: "deny", reason: "Blocked content." } });
78
+ const policy = new HttpInputPolicy("test-input", { baseUrl });
79
+ const decision = await policy.evaluate(inputCtx("bad content")) as { decision: string; reason: string };
80
+ expect(decision.decision).toBe("deny");
81
+ expect(decision.reason).toBe("Blocked content.");
82
+ });
83
+
84
+ it("sends policy_id, interception_point and context in the request body", async () => {
85
+ let received: unknown;
86
+ handler = (body) => { received = body; return { status: 200, body: { decision: "allow" } }; };
87
+ const policy = new HttpInputPolicy("my-policy", { baseUrl });
88
+ await policy.evaluate(inputCtx("hello"));
89
+ expect(received).toMatchObject({
90
+ policy_id: "my-policy",
91
+ interception_point: "input",
92
+ context: { messages: [{ role: "user", content: "hello" }] },
93
+ });
94
+ });
95
+
96
+ it("throws PolicyEvaluationError on non-200 response", async () => {
97
+ handler = () => ({ status: 500, body: { error: "internal error" } });
98
+ const policy = new HttpInputPolicy("test-input", { baseUrl });
99
+ await expect(policy.evaluate(inputCtx("hello"))).rejects.toThrow(PolicyEvaluationError);
100
+ });
101
+
102
+ it("throws PolicyEvaluationError on invalid JSON response", async () => {
103
+ const server2 = createServer((_req, res) => {
104
+ res.writeHead(200, { "Content-Type": "application/json" });
105
+ res.end("not-json");
106
+ });
107
+ await new Promise<void>((resolve) => server2.listen(0, "127.0.0.1", resolve));
108
+ const { port } = server2.address() as { port: number };
109
+ const policy = new HttpInputPolicy("test-input", { baseUrl: `http://127.0.0.1:${port}` });
110
+ await expect(policy.evaluate(inputCtx("hello"))).rejects.toThrow(PolicyEvaluationError);
111
+ await new Promise<void>((resolve, reject) => server2.close((e) => e ? reject(e) : resolve()));
112
+ });
113
+
114
+ it("integrates with ApsEngine — passes when allowed", async () => {
115
+ handler = () => ({ status: 200, body: { decision: "allow" } });
116
+ const engine = new ApsEngine({ policySet: { input: [new HttpInputPolicy("p", { baseUrl })] } });
117
+ await expect(engine.evaluateInput(inputCtx("hello"))).resolves.toBeUndefined();
118
+ });
119
+
120
+ it("integrates with ApsEngine — throws PolicyDenialError when denied", async () => {
121
+ handler = () => ({ status: 200, body: { decision: "deny", reason: "Not allowed." } });
122
+ const engine = new ApsEngine({ policySet: { input: [new HttpInputPolicy("p", { baseUrl })] } });
123
+ await expect(engine.evaluateInput(inputCtx("hello"))).rejects.toThrow(PolicyDenialError);
124
+ });
125
+ });
126
+
127
+ // ─── HttpToolCallPolicy ───────────────────────────────────────────────────────
128
+
129
+ describe("HttpToolCallPolicy", () => {
130
+ it("returns the decision from the remote server", async () => {
131
+ handler = () => ({ status: 200, body: { decision: "allow" } });
132
+ const policy = new HttpToolCallPolicy("test-tool", { baseUrl });
133
+ const decision = await policy.evaluate(toolCallCtx("web_search"));
134
+ expect(decision.decision).toBe("allow");
135
+ });
136
+
137
+ it("sends interception_point as tool_call", async () => {
138
+ let received: unknown;
139
+ handler = (body) => { received = body; return { status: 200, body: { decision: "allow" } }; };
140
+ const policy = new HttpToolCallPolicy("test-tool", { baseUrl });
141
+ await policy.evaluate(toolCallCtx("web_search"));
142
+ expect(received).toMatchObject({ interception_point: "tool_call" });
143
+ });
144
+
145
+ it("returns a deny decision", async () => {
146
+ handler = () => ({ status: 200, body: { decision: "deny" } });
147
+ const policy = new HttpToolCallPolicy("test-tool", { baseUrl });
148
+ const decision = await policy.evaluate(toolCallCtx("delete_file"));
149
+ expect(decision.decision).toBe("deny");
150
+ });
151
+
152
+ it("throws PolicyEvaluationError on non-200 response", async () => {
153
+ handler = () => ({ status: 403, body: {} });
154
+ const policy = new HttpToolCallPolicy("test-tool", { baseUrl });
155
+ await expect(policy.evaluate(toolCallCtx("exec"))).rejects.toThrow(PolicyEvaluationError);
156
+ });
157
+ });
158
+
159
+ // ─── HttpOutputPolicy ─────────────────────────────────────────────────────────
160
+
161
+ describe("HttpOutputPolicy", () => {
162
+ it("returns the decision from the remote server", async () => {
163
+ handler = () => ({ status: 200, body: { decision: "allow" } });
164
+ const policy = new HttpOutputPolicy("test-output", { baseUrl });
165
+ const decision = await policy.evaluate(outputCtx("The weather is nice."));
166
+ expect(decision.decision).toBe("allow");
167
+ });
168
+
169
+ it("sends interception_point as output", async () => {
170
+ let received: unknown;
171
+ handler = (body) => { received = body; return { status: 200, body: { decision: "allow" } }; };
172
+ const policy = new HttpOutputPolicy("test-output", { baseUrl });
173
+ await policy.evaluate(outputCtx("hello"));
174
+ expect(received).toMatchObject({ interception_point: "output" });
175
+ });
176
+
177
+ it("returns a deny decision for blocked content", async () => {
178
+ handler = () => ({ status: 200, body: { decision: "deny", reason: "Blocked domain." } });
179
+ const policy = new HttpOutputPolicy("test-output", { baseUrl });
180
+ const decision = await policy.evaluate(outputCtx("Visit evil.example")) as PolicyDecision & { reason?: string };
181
+ expect(decision.decision).toBe("deny");
182
+ });
183
+
184
+ it("integrates with ApsEngine — throws PolicyDenialError when denied", async () => {
185
+ handler = () => ({ status: 200, body: { decision: "deny" } });
186
+ const engine = new ApsEngine({ policySet: { output: [new HttpOutputPolicy("p", { baseUrl })] } });
187
+ await expect(engine.evaluateOutput(outputCtx("blocked"))).rejects.toThrow(PolicyDenialError);
188
+ });
189
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,22 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "lib": ["ES2022"],
7
+ "outDir": "./dist",
8
+ "rootDir": "./src",
9
+ "declaration": true,
10
+ "declarationMap": true,
11
+ "sourceMap": true,
12
+ "strict": true,
13
+ "noUncheckedIndexedAccess": true,
14
+ "noImplicitOverride": true,
15
+ "exactOptionalPropertyTypes": true,
16
+ "forceConsistentCasingInFileNames": true,
17
+ "esModuleInterop": true,
18
+ "skipLibCheck": true
19
+ },
20
+ "include": ["src/**/*"],
21
+ "exclude": ["node_modules", "dist"]
22
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "rootDir": ".",
5
+ "outDir": "./dist-test",
6
+ "isolatedModules": true,
7
+ "types": ["jest"]
8
+ },
9
+ "include": ["src/**/*", "test/**/*"]
10
+ }