@agentpolicyspecification/ollama 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/ollama
2
+
3
+ Ollama integration for the Agent Policy Specification (APS)
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @agentpolicyspecification/ollama
9
+ ```
10
+
11
+ ## License
12
+
13
+ Apache-2.0
@@ -0,0 +1,17 @@
1
+ import type { Ollama, ChatRequest, ChatResponse } from 'ollama';
2
+ import type { ApsEngine, Metadata } from '@agentpolicyspecification/core';
3
+ export interface ApsOllamaOptions {
4
+ engine: ApsEngine;
5
+ metadata?: Partial<Metadata>;
6
+ }
7
+ export type ApsOllamaClient = {
8
+ chat(request: ChatRequest & {
9
+ stream?: false;
10
+ }): Promise<ChatResponse>;
11
+ chat(request: ChatRequest & {
12
+ stream: true;
13
+ }): Promise<AsyncIterable<ChatResponse>>;
14
+ chat(request: ChatRequest): Promise<ChatResponse | AsyncIterable<ChatResponse>>;
15
+ };
16
+ export declare function withAps(ollama: Ollama, options: ApsOllamaOptions): ApsOllamaClient;
17
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,YAAY,EAA4B,MAAM,QAAQ,CAAC;AAC1F,OAAO,KAAK,EAAE,SAAS,EAAyB,QAAQ,EAAkC,MAAM,gCAAgC,CAAC;AAEjI,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,SAAS,CAAC;IAClB,QAAQ,CAAC,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC;CAC9B;AAED,MAAM,MAAM,eAAe,GAAG;IAC5B,IAAI,CAAC,OAAO,EAAE,WAAW,GAAG;QAAE,MAAM,CAAC,EAAE,KAAK,CAAA;KAAE,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC;IACvE,IAAI,CAAC,OAAO,EAAE,WAAW,GAAG;QAAE,MAAM,EAAE,IAAI,CAAA;KAAE,GAAG,OAAO,CAAC,aAAa,CAAC,YAAY,CAAC,CAAC,CAAC;IACpF,IAAI,CAAC,OAAO,EAAE,WAAW,GAAG,OAAO,CAAC,YAAY,GAAG,aAAa,CAAC,YAAY,CAAC,CAAC,CAAC;CACjF,CAAC;AAEF,wBAAgB,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,gBAAgB,GAAG,eAAe,CAsBlF"}
package/dist/index.js ADDED
@@ -0,0 +1,80 @@
1
+ export function withAps(ollama, options) {
2
+ return {
3
+ async chat(request) {
4
+ const messages = request.messages ?? [];
5
+ await options.engine.evaluateInput(toInputContext(messages, options));
6
+ if (request.stream === true) {
7
+ const stream = await ollama.chat({ ...request, stream: true });
8
+ return streamWithEval(stream, options);
9
+ }
10
+ const response = await ollama.chat({ ...request, stream: false });
11
+ await evaluateToolCalls(response, options);
12
+ if (response.message.content) {
13
+ await options.engine.evaluateOutput(toOutputContext(response.message.content, options));
14
+ }
15
+ return response;
16
+ },
17
+ };
18
+ }
19
+ async function evaluateToolCalls(response, options) {
20
+ const toolCalls = response.message.tool_calls ?? [];
21
+ console.log('evaluate tool calls:', toolCalls);
22
+ for (const toolCall of toolCalls) {
23
+ await options.engine.evaluateToolCall(toToolCallContext(toolCall, response.message.content, options));
24
+ }
25
+ }
26
+ async function* streamWithEval(stream, options) {
27
+ const textChunks = [];
28
+ let lastChunk;
29
+ for await (const chunk of stream) {
30
+ if (chunk.message.content) {
31
+ textChunks.push(chunk.message.content);
32
+ }
33
+ lastChunk = chunk;
34
+ yield chunk;
35
+ }
36
+ // Tool calls arrive in the final chunk
37
+ if (lastChunk) {
38
+ await evaluateToolCalls(lastChunk, options);
39
+ }
40
+ const text = textChunks.join('');
41
+ if (text) {
42
+ await options.engine.evaluateOutput(toOutputContext(text, options));
43
+ }
44
+ }
45
+ function toInputContext(messages, options) {
46
+ return {
47
+ messages: messages.map(toApsMessage),
48
+ metadata: getMetadata(options),
49
+ };
50
+ }
51
+ function toOutputContext(text, options) {
52
+ return {
53
+ response: { role: 'assistant', content: text },
54
+ metadata: getMetadata(options),
55
+ };
56
+ }
57
+ function toToolCallContext(toolCall, assistantContent, options) {
58
+ return {
59
+ tool_name: toolCall.function.name,
60
+ arguments: toolCall.function.arguments,
61
+ calling_message: { role: 'assistant', content: assistantContent },
62
+ metadata: getMetadata(options),
63
+ };
64
+ }
65
+ function toApsMessage(m) {
66
+ const role = m.role === 'user' || m.role === 'assistant' || m.role === 'system'
67
+ ? m.role
68
+ : 'user';
69
+ const content = typeof m.content === 'string' ? m.content : '';
70
+ return { role, content };
71
+ }
72
+ function getMetadata(options) {
73
+ return {
74
+ agent_id: options.metadata?.agent_id ?? 'unknown',
75
+ session_id: options.metadata?.session_id ?? 'unknown',
76
+ timestamp: new Date().toISOString(),
77
+ ...options.metadata,
78
+ };
79
+ }
80
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAcA,MAAM,UAAU,OAAO,CAAC,MAAc,EAAE,OAAyB;IAC/D,OAAO;QACL,KAAK,CAAC,IAAI,CAAC,OAAoB;YAC7B,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,EAAE,CAAC;YACxC,MAAM,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,cAAc,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAC;YAEtE,IAAI,OAAO,CAAC,MAAM,KAAK,IAAI,EAAE,CAAC;gBAC5B,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,IAAI,CAAC,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;gBAC/D,OAAO,cAAc,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;YACzC,CAAC;YAED,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,IAAI,CAAC,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;YAElE,MAAM,iBAAiB,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;YAE3C,IAAI,QAAQ,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;gBAC7B,MAAM,OAAO,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O,CAAC,QAAQ,EAAE,QAAQ,IAAI,SAAS;QACjD,UAAU,EAAE,OAAO,CAAC,QAAQ,EAAE,UAAU,IAAI,SAAS;QACrD,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;QACnC,GAAG,OAAO,CAAC,QAAQ;KACpB,CAAC;AACJ,CAAC"}
package/jest.config.js ADDED
@@ -0,0 +1,16 @@
1
+ export default {
2
+ preset: "ts-jest/presets/default-esm",
3
+ testEnvironment: "node",
4
+ testMatch: ["**/test/**/*.test.ts"],
5
+ transform: {
6
+ "^.+\\.tsx?$": [
7
+ "ts-jest",
8
+ {
9
+ useESM: true,
10
+ },
11
+ ],
12
+ },
13
+ moduleNameMapper: {
14
+ "^(\\.{1,2}/.*)\\.js$": "$1",
15
+ },
16
+ };
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@agentpolicyspecification/ollama",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "dependencies": {
8
+ "@agentpolicyspecification/core": "0.1.0"
9
+ },
10
+ "peerDependencies": {
11
+ "ollama": ">=0.5.0"
12
+ },
13
+ "devDependencies": {
14
+ "@jest/globals": "^29.5.0",
15
+ "@types/jest": "^29.5.0",
16
+ "@types/node": "^20.0.0",
17
+ "jest": "^29.5.0",
18
+ "ollama": "^0.5.0",
19
+ "ts-jest": "^29.1.0",
20
+ "typescript": "^5.4.0"
21
+ },
22
+ "author": "Pascal Wilbrink",
23
+ "license": "Apache-2.0",
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/agentpolicyspecification/aps-typescript.git",
27
+ "directory": "integrations/ollama"
28
+ },
29
+ "bugs": {
30
+ "url": "https://github.com/agentpolicyspecification/aps-typescript/issues"
31
+ },
32
+ "homepage": "https://github.com/agentpolicyspecification/aps-typescript/tree/main/integrations/ollama#readme",
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "scripts": {
37
+ "build": "tsc",
38
+ "test": "NODE_OPTIONS=--experimental-vm-modules jest --passWithNoTests"
39
+ }
40
+ }
package/src/index.ts ADDED
@@ -0,0 +1,115 @@
1
+ import type { Ollama, ChatRequest, ChatResponse, Message as OllamaMessage } from 'ollama';
2
+ import type { ApsEngine, InputContext, Message, Metadata, OutputContext, ToolCallContext } from '@agentpolicyspecification/core';
3
+
4
+ export interface ApsOllamaOptions {
5
+ engine: ApsEngine;
6
+ metadata?: Partial<Metadata>;
7
+ }
8
+
9
+ export type ApsOllamaClient = {
10
+ chat(request: ChatRequest & { stream?: false }): Promise<ChatResponse>;
11
+ chat(request: ChatRequest & { stream: true }): Promise<AsyncIterable<ChatResponse>>;
12
+ chat(request: ChatRequest): Promise<ChatResponse | AsyncIterable<ChatResponse>>;
13
+ };
14
+
15
+ export function withAps(ollama: Ollama, options: ApsOllamaOptions): ApsOllamaClient {
16
+ return {
17
+ async chat(request: ChatRequest): Promise<ChatResponse | AsyncIterable<ChatResponse>> {
18
+ const messages = request.messages ?? [];
19
+ await options.engine.evaluateInput(toInputContext(messages, options));
20
+
21
+ if (request.stream === true) {
22
+ const stream = await ollama.chat({ ...request, stream: true });
23
+ return streamWithEval(stream, options);
24
+ }
25
+
26
+ const response = await ollama.chat({ ...request, stream: false });
27
+
28
+ await evaluateToolCalls(response, options);
29
+
30
+ if (response.message.content) {
31
+ await options.engine.evaluateOutput(toOutputContext(response.message.content, options));
32
+ }
33
+
34
+ return response;
35
+ },
36
+ } as ApsOllamaClient;
37
+ }
38
+
39
+ async function evaluateToolCalls(response: ChatResponse, options: ApsOllamaOptions): Promise<void> {
40
+ const toolCalls = response.message.tool_calls ?? [];
41
+ console.log('evaluate tool calls:', toolCalls);
42
+ for (const toolCall of toolCalls) {
43
+ await options.engine.evaluateToolCall(toToolCallContext(toolCall, response.message.content, options));
44
+ }
45
+ }
46
+
47
+ async function* streamWithEval(
48
+ stream: AsyncIterable<ChatResponse>,
49
+ options: ApsOllamaOptions,
50
+ ): AsyncGenerator<ChatResponse> {
51
+ const textChunks: string[] = [];
52
+ let lastChunk: ChatResponse | undefined;
53
+
54
+ for await (const chunk of stream) {
55
+ if (chunk.message.content) {
56
+ textChunks.push(chunk.message.content);
57
+ }
58
+ lastChunk = chunk;
59
+ yield chunk;
60
+ }
61
+
62
+ // Tool calls arrive in the final chunk
63
+ if (lastChunk) {
64
+ await evaluateToolCalls(lastChunk, options);
65
+ }
66
+
67
+ const text = textChunks.join('');
68
+ if (text) {
69
+ await options.engine.evaluateOutput(toOutputContext(text, options));
70
+ }
71
+ }
72
+
73
+ function toInputContext(messages: OllamaMessage[], options: ApsOllamaOptions): InputContext {
74
+ return {
75
+ messages: messages.map(toApsMessage),
76
+ metadata: getMetadata(options),
77
+ };
78
+ }
79
+
80
+ function toOutputContext(text: string, options: ApsOllamaOptions): OutputContext {
81
+ return {
82
+ response: { role: 'assistant', content: text },
83
+ metadata: getMetadata(options),
84
+ };
85
+ }
86
+
87
+ function toToolCallContext(
88
+ toolCall: { function: { name: string; arguments: Record<string, unknown> } },
89
+ assistantContent: string,
90
+ options: ApsOllamaOptions,
91
+ ): ToolCallContext {
92
+ return {
93
+ tool_name: toolCall.function.name,
94
+ arguments: toolCall.function.arguments,
95
+ calling_message: { role: 'assistant', content: assistantContent },
96
+ metadata: getMetadata(options),
97
+ };
98
+ }
99
+
100
+ function toApsMessage(m: OllamaMessage): Message {
101
+ const role = m.role === 'user' || m.role === 'assistant' || m.role === 'system'
102
+ ? m.role
103
+ : 'user';
104
+ const content = typeof m.content === 'string' ? m.content : '';
105
+ return { role, content };
106
+ }
107
+
108
+ function getMetadata(options: ApsOllamaOptions): Metadata {
109
+ return {
110
+ agent_id: options.metadata?.agent_id ?? 'unknown',
111
+ session_id: options.metadata?.session_id ?? 'unknown',
112
+ timestamp: new Date().toISOString(),
113
+ ...options.metadata,
114
+ };
115
+ }
@@ -0,0 +1,193 @@
1
+ import { jest, describe, it, expect } from '@jest/globals';
2
+ import type { Ollama, ChatResponse } from 'ollama';
3
+ import { withAps } from '../src/index.js';
4
+ import { ApsEngine, PolicyDenialError } from '@agentpolicyspecification/core';
5
+ import type { InputContext, OutputContext, ToolCallContext, PolicyDecision, PolicySet } from '@agentpolicyspecification/core';
6
+
7
+ // ─── Helpers ─────────────────────────────────────────────────────────────────
8
+
9
+ const ALLOW_DECISION: PolicyDecision = { decision: 'allow' };
10
+ const DENY_DECISION: PolicyDecision = { decision: 'deny', reason: 'blocked by policy' };
11
+
12
+ function makeMockOllama(reply: string, toolCalls?: ChatResponse['message']['tool_calls']): { ollama: Ollama; chatSpy: ReturnType<typeof jest.fn> } {
13
+ const chatSpy = jest.fn<() => Promise<ChatResponse>>().mockResolvedValue({
14
+ message: { role: 'assistant', content: reply, tool_calls: toolCalls },
15
+ } as ChatResponse);
16
+ return { ollama: { chat: chatSpy } as unknown as Ollama, chatSpy };
17
+ }
18
+
19
+ function makeStreamingMockOllama(chunks: string[]): { ollama: Ollama; chatSpy: ReturnType<typeof jest.fn> } {
20
+ async function* gen(): AsyncGenerator<ChatResponse> {
21
+ for (const chunk of chunks) {
22
+ yield { message: { role: 'assistant', content: chunk } } as ChatResponse;
23
+ }
24
+ }
25
+ const chatSpy = jest.fn<() => Promise<AsyncGenerator<ChatResponse>>>().mockResolvedValue(gen());
26
+ return { ollama: { chat: chatSpy } as unknown as Ollama, chatSpy };
27
+ }
28
+
29
+ function makeEngine(policySet: PolicySet): ApsEngine {
30
+ return new ApsEngine({ policySet });
31
+ }
32
+
33
+ // ─── Tests ────────────────────────────────────────────────────────────────────
34
+
35
+ describe('withAps – non-streaming', () => {
36
+ it('passes through when all policies allow', async () => {
37
+ const { ollama } = makeMockOllama('Madrid');
38
+ const engine = makeEngine({
39
+ input: [{ id: 'allow-all', evaluate: () => ALLOW_DECISION }],
40
+ output: [{ id: 'allow-all', evaluate: () => ALLOW_DECISION }],
41
+ });
42
+
43
+ const client = withAps(ollama, { engine, metadata: { agent_id: 'test', session_id: 's1' } });
44
+ const response = await client.chat({ model: 'llama3', messages: [{ role: 'user', content: 'Capital of Spain?' }] });
45
+
46
+ expect(response.message.content).toBe('Madrid');
47
+ });
48
+
49
+ it('throws PolicyDenialError when input policy denies', async () => {
50
+ const { ollama, chatSpy } = makeMockOllama('Madrid');
51
+ const engine = makeEngine({
52
+ input: [{ id: 'no-pii', evaluate: () => DENY_DECISION }],
53
+ });
54
+
55
+ const client = withAps(ollama, { engine });
56
+ await expect(
57
+ client.chat({ model: 'llama3', messages: [{ role: 'user', content: 'My SSN is 123-45-6789' }] }),
58
+ ).rejects.toBeInstanceOf(PolicyDenialError);
59
+
60
+ expect(chatSpy).not.toHaveBeenCalled();
61
+ });
62
+
63
+ it('throws PolicyDenialError when output policy denies', async () => {
64
+ const { ollama } = makeMockOllama('secret information');
65
+ const engine = makeEngine({
66
+ input: [{ id: 'allow-all', evaluate: () => ALLOW_DECISION }],
67
+ output: [{ id: 'no-secrets', evaluate: () => DENY_DECISION }],
68
+ });
69
+
70
+ const client = withAps(ollama, { engine });
71
+ await expect(
72
+ client.chat({ model: 'llama3', messages: [{ role: 'user', content: 'Tell me something' }] }),
73
+ ).rejects.toBeInstanceOf(PolicyDenialError);
74
+ });
75
+
76
+ it('forwards metadata to engine context', async () => {
77
+ const inputEvaluate = jest.fn<(ctx: InputContext) => PolicyDecision>().mockReturnValue(ALLOW_DECISION);
78
+ const { ollama } = makeMockOllama('ok');
79
+ const engine = makeEngine({
80
+ input: [{ id: 'check-meta', evaluate: inputEvaluate as (ctx: InputContext) => PolicyDecision }],
81
+ });
82
+
83
+ const client = withAps(ollama, { engine, metadata: { agent_id: 'agent-1', session_id: 'sess-1' } });
84
+ await client.chat({ model: 'llama3', messages: [{ role: 'user', content: 'hi' }] });
85
+
86
+ const ctx = inputEvaluate.mock.calls[0]?.[0] as InputContext;
87
+ expect(ctx.metadata?.agent_id).toBe('agent-1');
88
+ expect(ctx.metadata?.session_id).toBe('sess-1');
89
+ });
90
+ });
91
+
92
+ describe('withAps – streaming', () => {
93
+ it('yields all chunks and evaluates output after stream ends', async () => {
94
+ const chunks = ['Hello', ', ', 'world!'];
95
+ const { ollama } = makeStreamingMockOllama(chunks);
96
+ const outputEvaluate = jest.fn<(ctx: OutputContext) => PolicyDecision>().mockReturnValue(ALLOW_DECISION);
97
+ const engine = makeEngine({
98
+ input: [{ id: 'allow-all', evaluate: () => ALLOW_DECISION }],
99
+ output: [{ id: 'check-output', evaluate: outputEvaluate as (ctx: OutputContext) => PolicyDecision }],
100
+ });
101
+
102
+ const client = withAps(ollama, { engine });
103
+ const stream = await client.chat({ model: 'llama3', messages: [{ role: 'user', content: 'hi' }], stream: true });
104
+
105
+ const received: string[] = [];
106
+ for await (const chunk of stream as AsyncIterable<ChatResponse>) {
107
+ received.push(chunk.message.content);
108
+ }
109
+
110
+ expect(received).toEqual(chunks);
111
+
112
+ const outputCtx = outputEvaluate.mock.calls[0]?.[0] as OutputContext;
113
+ expect(outputCtx.response?.content).toBe('Hello, world!');
114
+ });
115
+
116
+ it('throws PolicyDenialError when input policy denies (streaming)', async () => {
117
+ const { ollama, chatSpy } = makeStreamingMockOllama(['hi']);
118
+ const engine = makeEngine({
119
+ input: [{ id: 'deny-all', evaluate: () => DENY_DECISION }],
120
+ });
121
+
122
+ const client = withAps(ollama, { engine });
123
+ await expect(
124
+ client.chat({ model: 'llama3', messages: [{ role: 'user', content: 'hi' }], stream: true }),
125
+ ).rejects.toBeInstanceOf(PolicyDenialError);
126
+
127
+ expect(chatSpy).not.toHaveBeenCalled();
128
+ });
129
+ });
130
+
131
+ describe('withAps – tool calls', () => {
132
+ it('evaluates each tool call returned by the model', async () => {
133
+ const toolCalls = [
134
+ { function: { name: 'get_weather', arguments: { city: 'Madrid' } } },
135
+ { function: { name: 'search_web', arguments: { query: 'news' } } },
136
+ ];
137
+ const { ollama } = makeMockOllama('', toolCalls);
138
+ const toolEvaluate = jest.fn<(ctx: ToolCallContext) => PolicyDecision>().mockReturnValue(ALLOW_DECISION);
139
+ const engine = makeEngine({
140
+ input: [{ id: 'allow-all', evaluate: () => ALLOW_DECISION }],
141
+ tool_call: [{ id: 'check-tools', evaluate: toolEvaluate as (ctx: ToolCallContext) => PolicyDecision }],
142
+ });
143
+
144
+ const client = withAps(ollama, { engine });
145
+ await client.chat({ model: 'llama3', messages: [{ role: 'user', content: 'What is the weather?' }] });
146
+
147
+ expect(toolEvaluate).toHaveBeenCalledTimes(2);
148
+ const ctx0 = toolEvaluate.mock.calls[0]?.[0] as ToolCallContext;
149
+ expect(ctx0.tool_name).toBe('get_weather');
150
+ expect(ctx0.arguments).toEqual({ city: 'Madrid' });
151
+ const ctx1 = toolEvaluate.mock.calls[1]?.[0] as ToolCallContext;
152
+ expect(ctx1.tool_name).toBe('search_web');
153
+ });
154
+
155
+ it('throws PolicyDenialError when a tool call is denied', async () => {
156
+ const toolCalls = [{ function: { name: 'delete_file', arguments: { path: '/etc/passwd' } } }];
157
+ const { ollama } = makeMockOllama('', toolCalls);
158
+ const engine = makeEngine({
159
+ input: [{ id: 'allow-all', evaluate: () => ALLOW_DECISION }],
160
+ tool_call: [{ id: 'no-dangerous-tools', evaluate: () => DENY_DECISION }],
161
+ });
162
+
163
+ const client = withAps(ollama, { engine });
164
+ await expect(
165
+ client.chat({ model: 'llama3', messages: [{ role: 'user', content: 'Delete the file' }] }),
166
+ ).rejects.toBeInstanceOf(PolicyDenialError);
167
+ });
168
+
169
+ it('evaluates tool calls from the final chunk in streaming mode', async () => {
170
+ const toolCalls = [{ function: { name: 'get_weather', arguments: { city: 'Paris' } } }];
171
+ async function* gen(): AsyncGenerator<ChatResponse> {
172
+ yield { message: { role: 'assistant', content: 'Checking...' } } as ChatResponse;
173
+ yield { message: { role: 'assistant', content: '', tool_calls: toolCalls } } as unknown as ChatResponse;
174
+ }
175
+ const chatSpy = jest.fn<() => Promise<AsyncGenerator<ChatResponse>>>().mockResolvedValue(gen());
176
+ const ollama = { chat: chatSpy } as unknown as Ollama;
177
+
178
+ const toolEvaluate = jest.fn<(ctx: ToolCallContext) => PolicyDecision>().mockReturnValue(ALLOW_DECISION);
179
+ const engine = makeEngine({
180
+ input: [{ id: 'allow-all', evaluate: () => ALLOW_DECISION }],
181
+ tool_call: [{ id: 'check-tools', evaluate: toolEvaluate as (ctx: ToolCallContext) => PolicyDecision }],
182
+ });
183
+
184
+ const client = withAps(ollama, { engine });
185
+ const stream = await client.chat({ model: 'llama3', messages: [{ role: 'user', content: 'Weather?' }], stream: true });
186
+ for await (const _ of stream as AsyncIterable<ChatResponse>) { /* consume */ }
187
+
188
+ expect(toolEvaluate).toHaveBeenCalledTimes(1);
189
+ const ctx = toolEvaluate.mock.calls[0]?.[0] as ToolCallContext;
190
+ expect(ctx.tool_name).toBe('get_weather');
191
+ expect(ctx.arguments).toEqual({ city: 'Paris' });
192
+ });
193
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,18 @@
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
+ "esModuleInterop": true,
15
+ "skipLibCheck": true
16
+ },
17
+ "include": ["src/**/*"]
18
+ }