@peac/adapter-openai-compatible 0.11.2

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,190 @@
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
+ Copyright 2025-2026 PEAC Protocol Contributors
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,81 @@
1
+ # @peac/adapter-openai-compatible
2
+
3
+ OpenAI-compatible chat completion adapter for PEAC interaction evidence.
4
+
5
+ Maps OpenAI-compatible chat completion responses into PEAC `InteractionEvidenceV01` using a **hash-first model** (DD-138): no raw prompt or completion text is stored in receipts. Only SHA-256 digests, model identifiers, token counts, and timing metadata are recorded.
6
+
7
+ Works with any OpenAI-compatible provider (OpenAI, Anthropic Messages API via adapter, Ollama, vLLM, Together, etc.) without importing their SDKs.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pnpm add @peac/adapter-openai-compatible
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```typescript
18
+ import { fromChatCompletion } from '@peac/adapter-openai-compatible';
19
+
20
+ // After making an OpenAI-compatible API call:
21
+ const evidence = await fromChatCompletion({
22
+ messages: [
23
+ { role: 'system', content: 'You are a helpful assistant.' },
24
+ { role: 'user', content: 'What is 2+2?' },
25
+ ],
26
+ completion: {
27
+ id: 'chatcmpl-abc123',
28
+ object: 'chat.completion',
29
+ created: 1709251200,
30
+ model: 'gpt-4',
31
+ choices: [
32
+ {
33
+ index: 0,
34
+ message: { role: 'assistant', content: 'The answer is 4.' },
35
+ finish_reason: 'stop',
36
+ },
37
+ ],
38
+ usage: { prompt_tokens: 20, completion_tokens: 5, total_tokens: 25 },
39
+ },
40
+ provider: 'openai', // optional
41
+ });
42
+
43
+ // evidence.input.digest -> SHA-256 of messages (no raw text)
44
+ // evidence.output.digest -> SHA-256 of output (no raw text)
45
+ // evidence.extensions -> model, usage, finish_reason
46
+ ```
47
+
48
+ ## Hash-First Model
49
+
50
+ Per DD-138, this adapter records only:
51
+
52
+ | Field | Content |
53
+ | --------------- | --------------------------------------- |
54
+ | `input.digest` | SHA-256 of canonicalized messages array |
55
+ | `output.digest` | SHA-256 of concatenated output content |
56
+ | `executor` | Platform identifier and model name |
57
+ | `extensions` | Model ID, token counts, finish reason |
58
+
59
+ Raw prompt and completion text never appear in the evidence structure.
60
+
61
+ ## Streaming
62
+
63
+ Streaming support (`fromChatCompletionStream`) is explicitly deferred to v0.11.3.
64
+
65
+ ## API
66
+
67
+ ### `fromChatCompletion(params): Promise<InferenceEvidence>`
68
+
69
+ Maps a chat completion response to interaction evidence.
70
+
71
+ ### `hashMessages(messages): Promise<string>`
72
+
73
+ SHA-256 hash of a messages array. Returns `sha256:<hex64>`.
74
+
75
+ ### `hashOutput(content): Promise<string>`
76
+
77
+ SHA-256 hash of output text. Returns `sha256:<hex64>`.
78
+
79
+ ## License
80
+
81
+ Apache-2.0
@@ -0,0 +1,22 @@
1
+ /**
2
+ * WebCrypto utility for SHA-256 hashing (DD-138).
3
+ *
4
+ * Portable: uses globalThis.crypto.subtle (Node 19+, browsers, Deno, Bun)
5
+ * with fallback to node:crypto webcrypto for Node >=16.
6
+ *
7
+ * Minimum supported runtime: Node.js 16+ (with webcrypto).
8
+ * Recommended: Node.js 22+ (globalThis.crypto.subtle is always available).
9
+ */
10
+ type Subtle = typeof globalThis.crypto.subtle;
11
+ /**
12
+ * Get the SubtleCrypto implementation for the current runtime.
13
+ *
14
+ * Tries globalThis.crypto.subtle first (available in Node 19+, all modern
15
+ * browsers, Deno, Bun, Cloudflare Workers). Falls back to node:crypto
16
+ * webcrypto for Node >=16.
17
+ *
18
+ * @throws {Error} if no WebCrypto implementation is available
19
+ */
20
+ export declare function getSubtle(): Subtle;
21
+ export {};
22
+ //# sourceMappingURL=crypto.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["../src/crypto.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,KAAK,MAAM,GAAG,OAAO,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC;AAM9C;;;;;;;;GAQG;AACH,wBAAgB,SAAS,IAAI,MAAM,CAiBlC"}
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Evidence mapping for OpenAI-compatible chat completions (DD-138).
3
+ *
4
+ * Maps a ChatCompletion into InteractionEvidenceV01 using the hash-first
5
+ * model: SHA-256 digests of messages and output, plaintext metadata only.
6
+ */
7
+ import type { InferenceReceiptParams } from './types.js';
8
+ /** Well-known interaction kind for chat completions. */
9
+ export declare const INFERENCE_KIND = "inference.chat_completion";
10
+ /** Extension key for inference metadata. */
11
+ export declare const INFERENCE_EXTENSION_KEY = "org.peacprotocol/inference@0.1";
12
+ /** Interaction evidence structure (matches InteractionEvidenceV01 from @peac/schema). */
13
+ export interface InferenceEvidence {
14
+ interaction_id: string;
15
+ kind: typeof INFERENCE_KIND;
16
+ executor: {
17
+ platform: string;
18
+ version?: string;
19
+ };
20
+ started_at: string;
21
+ completed_at?: string;
22
+ duration_ms?: number;
23
+ input: {
24
+ digest: {
25
+ alg: 'sha-256';
26
+ value: string;
27
+ bytes: number;
28
+ };
29
+ redaction: 'hash_only';
30
+ };
31
+ output: {
32
+ digest: {
33
+ alg: 'sha-256';
34
+ value: string;
35
+ bytes: number;
36
+ };
37
+ redaction: 'hash_only';
38
+ };
39
+ result: {
40
+ status: 'ok' | 'error';
41
+ };
42
+ extensions: Record<string, unknown>;
43
+ }
44
+ /**
45
+ * Create interaction evidence from an OpenAI-compatible chat completion.
46
+ *
47
+ * Hash-first model (DD-138): no raw prompt or completion text is stored.
48
+ * Only SHA-256 digests, model ID, token counts, and timing are recorded.
49
+ *
50
+ * @param params - Messages, completion response, and optional provider
51
+ * @returns InteractionEvidenceV01-compatible object
52
+ */
53
+ export declare function fromChatCompletion(params: InferenceReceiptParams): Promise<InferenceEvidence>;
54
+ //# sourceMappingURL=evidence.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"evidence.d.ts","sourceRoot":"","sources":["../src/evidence.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAA+B,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAOtF,wDAAwD;AACxD,eAAO,MAAM,cAAc,8BAA8B,CAAC;AAE1D,4CAA4C;AAC5C,eAAO,MAAM,uBAAuB,mCAAmC,CAAC;AAMxE,yFAAyF;AACzF,MAAM,WAAW,iBAAiB;IAChC,cAAc,EAAE,MAAM,CAAC;IACvB,IAAI,EAAE,OAAO,cAAc,CAAC;IAC5B,QAAQ,EAAE;QACR,QAAQ,EAAE,MAAM,CAAC;QACjB,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB,CAAC;IACF,UAAU,EAAE,MAAM,CAAC;IACnB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,KAAK,EAAE;QACL,MAAM,EAAE;YACN,GAAG,EAAE,SAAS,CAAC;YACf,KAAK,EAAE,MAAM,CAAC;YACd,KAAK,EAAE,MAAM,CAAC;SACf,CAAC;QACF,SAAS,EAAE,WAAW,CAAC;KACxB,CAAC;IACF,MAAM,EAAE;QACN,MAAM,EAAE;YACN,GAAG,EAAE,SAAS,CAAC;YACf,KAAK,EAAE,MAAM,CAAC;YACd,KAAK,EAAE,MAAM,CAAC;SACf,CAAC;QACF,SAAS,EAAE,WAAW,CAAC;KACxB,CAAC;IACF,MAAM,EAAE;QACN,MAAM,EAAE,IAAI,GAAG,OAAO,CAAC;KACxB,CAAC;IACF,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACrC;AAqBD;;;;;;;;GAQG;AACH,wBAAsB,kBAAkB,CACtC,MAAM,EAAE,sBAAsB,GAC7B,OAAO,CAAC,iBAAiB,CAAC,CAoE5B"}
package/dist/hash.d.ts ADDED
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Hash-first evidence model for OpenAI-compatible completions (DD-138).
3
+ *
4
+ * SHA-256 digests of messages and output.
5
+ * No raw prompt or completion text is stored in receipts.
6
+ *
7
+ * Canonicalization: deterministic key-sorted JSON serialization.
8
+ * Object keys are sorted lexicographically at every nesting level,
9
+ * then serialized via JSON.stringify. This is NOT RFC 8785 JCS
10
+ * (which has additional requirements for numeric handling); it is
11
+ * sufficient for ChatMessage objects whose fields are strings,
12
+ * booleans, nulls, and arrays of the same.
13
+ *
14
+ * Input constraints enforced by canonicalize():
15
+ * - Allowed: string, number, boolean, null, plain object, array
16
+ * - Rejected: Date, RegExp, Map, Set, Function, Symbol, BigInt, undefined
17
+ * (at any nesting level)
18
+ */
19
+ import type { ChatMessage } from './types.js';
20
+ /**
21
+ * Hash an array of chat messages.
22
+ *
23
+ * Applies deterministic key-sorted JSON serialization (sorted keys at
24
+ * every nesting level), then computes SHA-256. Returns `sha256:<hex64>`.
25
+ *
26
+ * @param messages - The chat messages to hash
27
+ * @returns `sha256:<hex64>` digest string
28
+ * @throws {TypeError} if messages contain non-JSON-safe types
29
+ */
30
+ export declare function hashMessages(messages: ChatMessage[]): Promise<string>;
31
+ /**
32
+ * Compute the byte size of a messages array (canonical JSON).
33
+ *
34
+ * @throws {TypeError} if messages contain non-JSON-safe types
35
+ */
36
+ export declare function messagesBytes(messages: ChatMessage[]): number;
37
+ /**
38
+ * Hash chat completion output text.
39
+ *
40
+ * Computes SHA-256 of the output content string.
41
+ * Returns `sha256:<hex64>`.
42
+ *
43
+ * @param content - The output text to hash (concatenated choice contents)
44
+ * @returns `sha256:<hex64>` digest string
45
+ */
46
+ export declare function hashOutput(content: string): Promise<string>;
47
+ /**
48
+ * Compute the byte size of output content.
49
+ */
50
+ export declare function outputBytes(content: string): number;
51
+ //# sourceMappingURL=hash.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hash.d.ts","sourceRoot":"","sources":["../src/hash.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAGH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAuG9C;;;;;;;;;GASG;AACH,wBAAsB,YAAY,CAAC,QAAQ,EAAE,WAAW,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAG3E;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,QAAQ,EAAE,WAAW,EAAE,GAAG,MAAM,CAG7D;AAED;;;;;;;;GAQG;AACH,wBAAsB,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAEjE;AAED;;GAEG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAEnD"}
package/dist/index.cjs ADDED
@@ -0,0 +1,165 @@
1
+ 'use strict';
2
+
3
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
+ }) : x)(function(x) {
6
+ if (typeof require !== "undefined") return require.apply(this, arguments);
7
+ throw Error('Dynamic require of "' + x + '" is not supported');
8
+ });
9
+
10
+ // src/crypto.ts
11
+ function getSubtle() {
12
+ const subtle = globalThis?.crypto?.subtle;
13
+ if (subtle) return subtle;
14
+ try {
15
+ const nodeCrypto = __require("crypto");
16
+ return nodeCrypto.webcrypto.subtle;
17
+ } catch {
18
+ throw new Error(
19
+ "No WebCrypto implementation available. Requires Node.js >=16, or a runtime with globalThis.crypto.subtle."
20
+ );
21
+ }
22
+ }
23
+
24
+ // src/hash.ts
25
+ var encoder = new TextEncoder();
26
+ async function sha256(input) {
27
+ const data = encoder.encode(input);
28
+ const subtle = getSubtle();
29
+ const buf = await subtle.digest("SHA-256", data);
30
+ const hex = Array.from(new Uint8Array(buf)).map((b) => b.toString(16).padStart(2, "0")).join("");
31
+ return `sha256:${hex}`;
32
+ }
33
+ function canonicalize(value) {
34
+ if (value === null) return value;
35
+ if (value === void 0) {
36
+ throw new TypeError("canonicalize: undefined is not allowed; use null instead");
37
+ }
38
+ const t = typeof value;
39
+ if (t === "string" || t === "number" || t === "boolean") {
40
+ return value;
41
+ }
42
+ if (t === "bigint") {
43
+ throw new TypeError("canonicalize: BigInt is not JSON-serializable");
44
+ }
45
+ if (t === "symbol") {
46
+ throw new TypeError("canonicalize: Symbol is not JSON-serializable");
47
+ }
48
+ if (t === "function") {
49
+ throw new TypeError("canonicalize: Function is not JSON-serializable");
50
+ }
51
+ if (Array.isArray(value)) {
52
+ return value.map(canonicalize);
53
+ }
54
+ if (value instanceof Date) {
55
+ throw new TypeError("canonicalize: Date objects are not allowed; use ISO 8601 strings");
56
+ }
57
+ if (value instanceof RegExp) {
58
+ throw new TypeError("canonicalize: RegExp objects are not JSON-serializable");
59
+ }
60
+ if (value instanceof Map || value instanceof Set) {
61
+ throw new TypeError(
62
+ "canonicalize: Map/Set are not JSON-serializable; use plain objects/arrays"
63
+ );
64
+ }
65
+ if (t === "object") {
66
+ const sorted = {};
67
+ for (const key of Object.keys(value).sort()) {
68
+ sorted[key] = canonicalize(value[key]);
69
+ }
70
+ return sorted;
71
+ }
72
+ throw new TypeError(`canonicalize: unsupported type "${t}"`);
73
+ }
74
+ async function hashMessages(messages) {
75
+ const canonical = JSON.stringify(canonicalize(messages));
76
+ return sha256(canonical);
77
+ }
78
+ function messagesBytes(messages) {
79
+ const canonical = JSON.stringify(canonicalize(messages));
80
+ return encoder.encode(canonical).byteLength;
81
+ }
82
+ async function hashOutput(content) {
83
+ return sha256(content);
84
+ }
85
+ function outputBytes(content) {
86
+ return encoder.encode(content).byteLength;
87
+ }
88
+
89
+ // src/evidence.ts
90
+ var INFERENCE_KIND = "inference.chat_completion";
91
+ var INFERENCE_EXTENSION_KEY = "org.peacprotocol/inference@0.1";
92
+ function concatOutputContent(completion) {
93
+ return completion.choices.map((c) => c.message.content ?? "").join("");
94
+ }
95
+ function primaryFinishReason(completion) {
96
+ if (completion.choices.length === 0) return null;
97
+ return completion.choices[0].finish_reason;
98
+ }
99
+ async function fromChatCompletion(params) {
100
+ const { messages, completion, provider } = params;
101
+ const outputContent = concatOutputContent(completion);
102
+ const [inputHash, outputHash] = await Promise.all([
103
+ hashMessages(messages),
104
+ hashOutput(outputContent)
105
+ ]);
106
+ const inputValue = inputHash.slice("sha256:".length);
107
+ const outputValue = outputHash.slice("sha256:".length);
108
+ const platform = provider ? `openai-compatible:${provider}` : "openai-compatible";
109
+ const inferenceExt = {
110
+ model: completion.model,
111
+ finish_reason: primaryFinishReason(completion)
112
+ };
113
+ if (completion.usage) {
114
+ inferenceExt.usage = {
115
+ prompt_tokens: completion.usage.prompt_tokens,
116
+ completion_tokens: completion.usage.completion_tokens,
117
+ total_tokens: completion.usage.total_tokens
118
+ };
119
+ }
120
+ const finishReason = primaryFinishReason(completion);
121
+ const resultStatus = finishReason === "error" || completion.choices.length === 0 ? "error" : "ok";
122
+ const evidence = {
123
+ interaction_id: completion.id,
124
+ kind: INFERENCE_KIND,
125
+ executor: {
126
+ platform,
127
+ version: completion.model
128
+ },
129
+ started_at: new Date(completion.created * 1e3).toISOString(),
130
+ input: {
131
+ digest: {
132
+ alg: "sha-256",
133
+ value: inputValue,
134
+ bytes: messagesBytes(messages)
135
+ },
136
+ redaction: "hash_only"
137
+ },
138
+ output: {
139
+ digest: {
140
+ alg: "sha-256",
141
+ value: outputValue,
142
+ bytes: outputBytes(outputContent)
143
+ },
144
+ redaction: "hash_only"
145
+ },
146
+ result: {
147
+ status: resultStatus
148
+ },
149
+ extensions: {
150
+ [INFERENCE_EXTENSION_KEY]: inferenceExt
151
+ }
152
+ };
153
+ return evidence;
154
+ }
155
+
156
+ exports.INFERENCE_EXTENSION_KEY = INFERENCE_EXTENSION_KEY;
157
+ exports.INFERENCE_KIND = INFERENCE_KIND;
158
+ exports.fromChatCompletion = fromChatCompletion;
159
+ exports.getSubtle = getSubtle;
160
+ exports.hashMessages = hashMessages;
161
+ exports.hashOutput = hashOutput;
162
+ exports.messagesBytes = messagesBytes;
163
+ exports.outputBytes = outputBytes;
164
+ //# sourceMappingURL=index.cjs.map
165
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/crypto.ts","../src/hash.ts","../src/evidence.ts"],"names":[],"mappings":";;;;;;;;;;AA0BO,SAAS,SAAA,GAAoB;AAElC,EAAA,MAAM,MAAA,GAAS,YAAY,MAAA,EAAQ,MAAA;AACnC,EAAA,IAA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ACV;AAAA,IACA,UAAA,EAAY;AAAA,MACV,CAAC,uBAAuB,GAAG;AAAA;AAC7B,GACF;AAEA,EAAA,OAAO,QAAA;AACT","file":"index.cjs","sourcesContent":["/**\n * WebCrypto utility for SHA-256 hashing (DD-138).\n *\n * Portable: uses globalThis.crypto.subtle (Node 19+, browsers, Deno, Bun)\n * with fallback to node:crypto webcrypto for Node >=16.\n *\n * Minimum supported runtime: Node.js 16+ (with webcrypto).\n * Recommended: Node.js 22+ (globalThis.crypto.subtle is always available).\n */\n\n// Use typeof to avoid DOM lib dependency for the SubtleCrypto type\ntype Subtle = typeof globalThis.crypto.subtle;\n\n// ---------------------------------------------------------------------------\n// WebCrypto resolution\n// ---------------------------------------------------------------------------\n\n/**\n * Get the SubtleCrypto implementation for the current runtime.\n *\n * Tries globalThis.crypto.subtle first (available in Node 19+, all modern\n * browsers, Deno, Bun, Cloudflare Workers). Falls back to node:crypto\n * webcrypto for Node >=16.\n *\n * @throws {Error} if no WebCrypto implementation is available\n */\nexport function getSubtle(): Subtle {\n // Prefer globalThis.crypto.subtle (Node 19+, all modern browsers)\n const subtle = globalThis?.crypto?.subtle;\n if (subtle) return subtle;\n\n // Node.js fallback for older versions (>=16)\n try {\n const nodeCrypto = require('node:crypto') as {\n webcrypto: { subtle: Subtle };\n };\n return nodeCrypto.webcrypto.subtle;\n } catch {\n throw new Error(\n 'No WebCrypto implementation available. ' +\n 'Requires Node.js >=16, or a runtime with globalThis.crypto.subtle.'\n );\n }\n}\n","/**\n * Hash-first evidence model for OpenAI-compatible completions (DD-138).\n *\n * SHA-256 digests of messages and output.\n * No raw prompt or completion text is stored in receipts.\n *\n * Canonicalization: deterministic key-sorted JSON serialization.\n * Object keys are sorted lexicographically at every nesting level,\n * then serialized via JSON.stringify. This is NOT RFC 8785 JCS\n * (which has additional requirements for numeric handling); it is\n * sufficient for ChatMessage objects whose fields are strings,\n * booleans, nulls, and arrays of the same.\n *\n * Input constraints enforced by canonicalize():\n * - Allowed: string, number, boolean, null, plain object, array\n * - Rejected: Date, RegExp, Map, Set, Function, Symbol, BigInt, undefined\n * (at any nesting level)\n */\n\nimport { getSubtle } from './crypto.js';\nimport type { ChatMessage } from './types.js';\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst encoder = new TextEncoder();\n\n/**\n * SHA-256 hash a string, return `sha256:<hex64>`.\n *\n * Uses getSubtle() for portable WebCrypto access\n * (Node 19+ globalThis.crypto.subtle, fallback to node:crypto webcrypto).\n */\nasync function sha256(input: string): Promise<string> {\n const data = encoder.encode(input);\n const subtle = getSubtle();\n const buf = await subtle.digest('SHA-256', data);\n const hex = Array.from(new Uint8Array(buf))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n return `sha256:${hex}`;\n}\n\n// ---------------------------------------------------------------------------\n// Canonicalization\n// ---------------------------------------------------------------------------\n\n/**\n * Recursively sort object keys for deterministic serialization.\n *\n * This produces a stable JSON representation by sorting object keys\n * lexicographically at every nesting level. Arrays preserve order.\n *\n * Note: this is deterministic key-sorted JSON, not RFC 8785 JCS.\n * Suitable for ChatMessage fields (strings, nulls, arrays, booleans).\n *\n * Input constraints: only JSON-safe types are accepted (string, number,\n * boolean, null, plain object, array). Date, RegExp, Map, Set, Function,\n * Symbol, BigInt, and undefined are rejected with a TypeError.\n *\n * @throws {TypeError} if input contains non-JSON-safe types\n */\nfunction canonicalize(value: unknown): unknown {\n if (value === null) return value;\n\n if (value === undefined) {\n throw new TypeError('canonicalize: undefined is not allowed; use null instead');\n }\n\n const t = typeof value;\n\n // Primitives: string, number, boolean pass through\n if (t === 'string' || t === 'number' || t === 'boolean') {\n return value;\n }\n\n // Reject non-JSON-safe primitives\n if (t === 'bigint') {\n throw new TypeError('canonicalize: BigInt is not JSON-serializable');\n }\n if (t === 'symbol') {\n throw new TypeError('canonicalize: Symbol is not JSON-serializable');\n }\n if (t === 'function') {\n throw new TypeError('canonicalize: Function is not JSON-serializable');\n }\n\n // Object types\n if (Array.isArray(value)) {\n return value.map(canonicalize);\n }\n\n // Reject non-plain objects (Date, RegExp, Map, Set, etc.)\n if (value instanceof Date) {\n throw new TypeError('canonicalize: Date objects are not allowed; use ISO 8601 strings');\n }\n if (value instanceof RegExp) {\n throw new TypeError('canonicalize: RegExp objects are not JSON-serializable');\n }\n if (value instanceof Map || value instanceof Set) {\n throw new TypeError(\n 'canonicalize: Map/Set are not JSON-serializable; use plain objects/arrays'\n );\n }\n\n // Plain object: sort keys recursively\n if (t === 'object') {\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(value as Record<string, unknown>).sort()) {\n sorted[key] = canonicalize((value as Record<string, unknown>)[key]);\n }\n return sorted;\n }\n\n // Catch-all for any other unexpected type\n throw new TypeError(`canonicalize: unsupported type \"${t}\"`);\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Hash an array of chat messages.\n *\n * Applies deterministic key-sorted JSON serialization (sorted keys at\n * every nesting level), then computes SHA-256. Returns `sha256:<hex64>`.\n *\n * @param messages - The chat messages to hash\n * @returns `sha256:<hex64>` digest string\n * @throws {TypeError} if messages contain non-JSON-safe types\n */\nexport async function hashMessages(messages: ChatMessage[]): Promise<string> {\n const canonical = JSON.stringify(canonicalize(messages));\n return sha256(canonical);\n}\n\n/**\n * Compute the byte size of a messages array (canonical JSON).\n *\n * @throws {TypeError} if messages contain non-JSON-safe types\n */\nexport function messagesBytes(messages: ChatMessage[]): number {\n const canonical = JSON.stringify(canonicalize(messages));\n return encoder.encode(canonical).byteLength;\n}\n\n/**\n * Hash chat completion output text.\n *\n * Computes SHA-256 of the output content string.\n * Returns `sha256:<hex64>`.\n *\n * @param content - The output text to hash (concatenated choice contents)\n * @returns `sha256:<hex64>` digest string\n */\nexport async function hashOutput(content: string): Promise<string> {\n return sha256(content);\n}\n\n/**\n * Compute the byte size of output content.\n */\nexport function outputBytes(content: string): number {\n return encoder.encode(content).byteLength;\n}\n","/**\n * Evidence mapping for OpenAI-compatible chat completions (DD-138).\n *\n * Maps a ChatCompletion into InteractionEvidenceV01 using the hash-first\n * model: SHA-256 digests of messages and output, plaintext metadata only.\n */\n\nimport type { ChatCompletion, ChatMessage, InferenceReceiptParams } from './types.js';\nimport { hashMessages, hashOutput, messagesBytes, outputBytes } from './hash.js';\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/** Well-known interaction kind for chat completions. */\nexport const INFERENCE_KIND = 'inference.chat_completion';\n\n/** Extension key for inference metadata. */\nexport const INFERENCE_EXTENSION_KEY = 'org.peacprotocol/inference@0.1';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Interaction evidence structure (matches InteractionEvidenceV01 from @peac/schema). */\nexport interface InferenceEvidence {\n interaction_id: string;\n kind: typeof INFERENCE_KIND;\n executor: {\n platform: string;\n version?: string;\n };\n started_at: string;\n completed_at?: string;\n duration_ms?: number;\n input: {\n digest: {\n alg: 'sha-256';\n value: string;\n bytes: number;\n };\n redaction: 'hash_only';\n };\n output: {\n digest: {\n alg: 'sha-256';\n value: string;\n bytes: number;\n };\n redaction: 'hash_only';\n };\n result: {\n status: 'ok' | 'error';\n };\n extensions: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Concatenate all choice message contents into a single string. */\nfunction concatOutputContent(completion: ChatCompletion): string {\n return completion.choices.map((c) => c.message.content ?? '').join('');\n}\n\n/** Extract finish_reason from the first choice (if any). */\nfunction primaryFinishReason(completion: ChatCompletion): string | null {\n if (completion.choices.length === 0) return null;\n return completion.choices[0].finish_reason;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Create interaction evidence from an OpenAI-compatible chat completion.\n *\n * Hash-first model (DD-138): no raw prompt or completion text is stored.\n * Only SHA-256 digests, model ID, token counts, and timing are recorded.\n *\n * @param params - Messages, completion response, and optional provider\n * @returns InteractionEvidenceV01-compatible object\n */\nexport async function fromChatCompletion(\n params: InferenceReceiptParams\n): Promise<InferenceEvidence> {\n const { messages, completion, provider } = params;\n\n // Hash inputs and outputs\n const outputContent = concatOutputContent(completion);\n const [inputHash, outputHash] = await Promise.all([\n hashMessages(messages),\n hashOutput(outputContent),\n ]);\n\n // Extract the hex value (strip `sha256:` prefix for digest.value)\n const inputValue = inputHash.slice('sha256:'.length);\n const outputValue = outputHash.slice('sha256:'.length);\n\n // Build platform identifier\n const platform = provider ? `openai-compatible:${provider}` : 'openai-compatible';\n\n // Build inference extension metadata\n const inferenceExt: Record<string, unknown> = {\n model: completion.model,\n finish_reason: primaryFinishReason(completion),\n };\n if (completion.usage) {\n inferenceExt.usage = {\n prompt_tokens: completion.usage.prompt_tokens,\n completion_tokens: completion.usage.completion_tokens,\n total_tokens: completion.usage.total_tokens,\n };\n }\n\n // Determine result status from finish_reason\n const finishReason = primaryFinishReason(completion);\n const resultStatus: 'ok' | 'error' =\n finishReason === 'error' || completion.choices.length === 0 ? 'error' : 'ok';\n\n const evidence: InferenceEvidence = {\n interaction_id: completion.id,\n kind: INFERENCE_KIND,\n executor: {\n platform,\n version: completion.model,\n },\n started_at: new Date(completion.created * 1000).toISOString(),\n input: {\n digest: {\n alg: 'sha-256',\n value: inputValue,\n bytes: messagesBytes(messages),\n },\n redaction: 'hash_only',\n },\n output: {\n digest: {\n alg: 'sha-256',\n value: outputValue,\n bytes: outputBytes(outputContent),\n },\n redaction: 'hash_only',\n },\n result: {\n status: resultStatus,\n },\n extensions: {\n [INFERENCE_EXTENSION_KEY]: inferenceExt,\n },\n };\n\n return evidence;\n}\n"]}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @peac/adapter-openai-compatible
3
+ *
4
+ * OpenAI-compatible chat completion adapter for PEAC interaction evidence.
5
+ * Hash-first model (DD-138): no raw prompt or completion text in receipts.
6
+ *
7
+ * Works with any OpenAI-compatible provider (OpenAI, Anthropic via adapter,
8
+ * Ollama, vLLM, Together, etc.) without importing their SDKs.
9
+ *
10
+ * @packageDocumentation
11
+ */
12
+ export type { ChatRole, ChatMessage, ChatUsage, ChatChoice, ChatCompletion, InferenceReceiptParams, } from './types.js';
13
+ export { getSubtle } from './crypto.js';
14
+ export { hashMessages, hashOutput, messagesBytes, outputBytes } from './hash.js';
15
+ export { fromChatCompletion, INFERENCE_KIND, INFERENCE_EXTENSION_KEY } from './evidence.js';
16
+ export type { InferenceEvidence } from './evidence.js';
17
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,YAAY,EACV,QAAQ,EACR,WAAW,EACX,SAAS,EACT,UAAU,EACV,cAAc,EACd,sBAAsB,GACvB,MAAM,YAAY,CAAC;AAGpB,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAGxC,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAGjF,OAAO,EAAE,kBAAkB,EAAE,cAAc,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAC;AAC5F,YAAY,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC"}
package/dist/index.mjs ADDED
@@ -0,0 +1,156 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
8
+ // src/crypto.ts
9
+ function getSubtle() {
10
+ const subtle = globalThis?.crypto?.subtle;
11
+ if (subtle) return subtle;
12
+ try {
13
+ const nodeCrypto = __require("crypto");
14
+ return nodeCrypto.webcrypto.subtle;
15
+ } catch {
16
+ throw new Error(
17
+ "No WebCrypto implementation available. Requires Node.js >=16, or a runtime with globalThis.crypto.subtle."
18
+ );
19
+ }
20
+ }
21
+
22
+ // src/hash.ts
23
+ var encoder = new TextEncoder();
24
+ async function sha256(input) {
25
+ const data = encoder.encode(input);
26
+ const subtle = getSubtle();
27
+ const buf = await subtle.digest("SHA-256", data);
28
+ const hex = Array.from(new Uint8Array(buf)).map((b) => b.toString(16).padStart(2, "0")).join("");
29
+ return `sha256:${hex}`;
30
+ }
31
+ function canonicalize(value) {
32
+ if (value === null) return value;
33
+ if (value === void 0) {
34
+ throw new TypeError("canonicalize: undefined is not allowed; use null instead");
35
+ }
36
+ const t = typeof value;
37
+ if (t === "string" || t === "number" || t === "boolean") {
38
+ return value;
39
+ }
40
+ if (t === "bigint") {
41
+ throw new TypeError("canonicalize: BigInt is not JSON-serializable");
42
+ }
43
+ if (t === "symbol") {
44
+ throw new TypeError("canonicalize: Symbol is not JSON-serializable");
45
+ }
46
+ if (t === "function") {
47
+ throw new TypeError("canonicalize: Function is not JSON-serializable");
48
+ }
49
+ if (Array.isArray(value)) {
50
+ return value.map(canonicalize);
51
+ }
52
+ if (value instanceof Date) {
53
+ throw new TypeError("canonicalize: Date objects are not allowed; use ISO 8601 strings");
54
+ }
55
+ if (value instanceof RegExp) {
56
+ throw new TypeError("canonicalize: RegExp objects are not JSON-serializable");
57
+ }
58
+ if (value instanceof Map || value instanceof Set) {
59
+ throw new TypeError(
60
+ "canonicalize: Map/Set are not JSON-serializable; use plain objects/arrays"
61
+ );
62
+ }
63
+ if (t === "object") {
64
+ const sorted = {};
65
+ for (const key of Object.keys(value).sort()) {
66
+ sorted[key] = canonicalize(value[key]);
67
+ }
68
+ return sorted;
69
+ }
70
+ throw new TypeError(`canonicalize: unsupported type "${t}"`);
71
+ }
72
+ async function hashMessages(messages) {
73
+ const canonical = JSON.stringify(canonicalize(messages));
74
+ return sha256(canonical);
75
+ }
76
+ function messagesBytes(messages) {
77
+ const canonical = JSON.stringify(canonicalize(messages));
78
+ return encoder.encode(canonical).byteLength;
79
+ }
80
+ async function hashOutput(content) {
81
+ return sha256(content);
82
+ }
83
+ function outputBytes(content) {
84
+ return encoder.encode(content).byteLength;
85
+ }
86
+
87
+ // src/evidence.ts
88
+ var INFERENCE_KIND = "inference.chat_completion";
89
+ var INFERENCE_EXTENSION_KEY = "org.peacprotocol/inference@0.1";
90
+ function concatOutputContent(completion) {
91
+ return completion.choices.map((c) => c.message.content ?? "").join("");
92
+ }
93
+ function primaryFinishReason(completion) {
94
+ if (completion.choices.length === 0) return null;
95
+ return completion.choices[0].finish_reason;
96
+ }
97
+ async function fromChatCompletion(params) {
98
+ const { messages, completion, provider } = params;
99
+ const outputContent = concatOutputContent(completion);
100
+ const [inputHash, outputHash] = await Promise.all([
101
+ hashMessages(messages),
102
+ hashOutput(outputContent)
103
+ ]);
104
+ const inputValue = inputHash.slice("sha256:".length);
105
+ const outputValue = outputHash.slice("sha256:".length);
106
+ const platform = provider ? `openai-compatible:${provider}` : "openai-compatible";
107
+ const inferenceExt = {
108
+ model: completion.model,
109
+ finish_reason: primaryFinishReason(completion)
110
+ };
111
+ if (completion.usage) {
112
+ inferenceExt.usage = {
113
+ prompt_tokens: completion.usage.prompt_tokens,
114
+ completion_tokens: completion.usage.completion_tokens,
115
+ total_tokens: completion.usage.total_tokens
116
+ };
117
+ }
118
+ const finishReason = primaryFinishReason(completion);
119
+ const resultStatus = finishReason === "error" || completion.choices.length === 0 ? "error" : "ok";
120
+ const evidence = {
121
+ interaction_id: completion.id,
122
+ kind: INFERENCE_KIND,
123
+ executor: {
124
+ platform,
125
+ version: completion.model
126
+ },
127
+ started_at: new Date(completion.created * 1e3).toISOString(),
128
+ input: {
129
+ digest: {
130
+ alg: "sha-256",
131
+ value: inputValue,
132
+ bytes: messagesBytes(messages)
133
+ },
134
+ redaction: "hash_only"
135
+ },
136
+ output: {
137
+ digest: {
138
+ alg: "sha-256",
139
+ value: outputValue,
140
+ bytes: outputBytes(outputContent)
141
+ },
142
+ redaction: "hash_only"
143
+ },
144
+ result: {
145
+ status: resultStatus
146
+ },
147
+ extensions: {
148
+ [INFERENCE_EXTENSION_KEY]: inferenceExt
149
+ }
150
+ };
151
+ return evidence;
152
+ }
153
+
154
+ export { INFERENCE_EXTENSION_KEY, INFERENCE_KIND, fromChatCompletion, getSubtle, hashMessages, hashOutput, messagesBytes, outputBytes };
155
+ //# sourceMappingURL=index.mjs.map
156
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/crypto.ts","../src/hash.ts","../src/evidence.ts"],"names":[],"mappings":";;;;;;;;AA0BO,SAAS,SAAA,GAAoB;AAElC,EAAA,MAAM,MAAA,GAAS,YAAY,MAAA,EAAQ,MAAA;AACnC,EAAA,IAAI,QAAQ,OAAO,MAAA;AAGnB,EAAA,IAAI;AACF,IAAA,MAAM,UAAA,GAAa,UAAQ,QAAa,CAAA;AAGxC,IAAA,OAAO,WAAW,SAAA,CAAU,MAAA;AAAA,EAC9B,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KAEF;AAAA,EACF;AACF;;;ACjBA,IAAM,OAAA,GAAU,IAAI,WAAA,EAAY;AAQhC,eAAe,OAAO,KAAA,EAAgC;AACpD,EAAA,MAAM,IAAA,GAAO,OAAA,CAAQ,MAAA,CAAO,KAAK,CAAA;AACjC,EAAA,MAAM,SAAS,SAAA,EAAU;AACzB,EAAA,MAAM,GAAA,GAAM,MAAM,MAAA,CAAO,MAAA,CAAO,WAAW,IAAI,CAAA;AAC/C,EAAA,MAAM,GAAA,GAAM,MAAM,IAAA,CAAK,IAAI,WAAW,GAAG,CAAC,EACvC,GAAA,CAAI,CAAC,MAAM,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,QAAA,CAAS,GAAG,GAAG,CAAC,CAAA,CAC1C,IAAA,CAAK,EAAE,CAAA;AACV,EAAA,OAAO,UAAU,GAAG,CAAA,CAAA;AACtB;AAqBA,SAAS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OAAA,GAAU,GAAI,EAAE,WAAA,EAAY;AAAA,IAC5D,KAAA,EAAO;AAAA,MACL,MAAA,EAAQ;AAAA,QACN,GAAA,EAAK,SAAA;AAAA,QACL,KAAA,EAAO,UAAA;AAAA,QACP,KAAA,EAAO,cAAc,QAAQ;AAAA,OAC/B;AAAA,MACA,SAAA,EAAW;AAAA,KACb;AAAA,IACA,MAAA,EAAQ;AAAA,MACN,MAAA,EAAQ;AAAA,QACN,GAAA,EAAK,SAAA;AAAA,QACL,KAAA,EAAO,WAAA;AAAA,QACP,KAAA,EAAO,YAAY,aAAa;AAAA,OAClC;AAAA,MACA,SAAA,EAAW;AAAA,KACb;AAAA,IACA,MAAA,EAAQ;AAAA,MACN,MAAA,EAAQ;AAAA,KACV;AAAA,IACA,UAAA,EAAY;AAAA,MACV,CAAC,uBAAuB,GAAG;AAAA;AAC7B,GACF;AAEA,EAAA,OAAO,QAAA;AACT","file":"index.mjs","sourcesContent":["/**\n * WebCrypto utility for SHA-256 hashing (DD-138).\n *\n * Portable: uses globalThis.crypto.subtle (Node 19+, browsers, Deno, Bun)\n * with fallback to node:crypto webcrypto for Node >=16.\n *\n * Minimum supported runtime: Node.js 16+ (with webcrypto).\n * Recommended: Node.js 22+ (globalThis.crypto.subtle is always available).\n */\n\n// Use typeof to avoid DOM lib dependency for the SubtleCrypto type\ntype Subtle = typeof globalThis.crypto.subtle;\n\n// ---------------------------------------------------------------------------\n// WebCrypto resolution\n// ---------------------------------------------------------------------------\n\n/**\n * Get the SubtleCrypto implementation for the current runtime.\n *\n * Tries globalThis.crypto.subtle first (available in Node 19+, all modern\n * browsers, Deno, Bun, Cloudflare Workers). Falls back to node:crypto\n * webcrypto for Node >=16.\n *\n * @throws {Error} if no WebCrypto implementation is available\n */\nexport function getSubtle(): Subtle {\n // Prefer globalThis.crypto.subtle (Node 19+, all modern browsers)\n const subtle = globalThis?.crypto?.subtle;\n if (subtle) return subtle;\n\n // Node.js fallback for older versions (>=16)\n try {\n const nodeCrypto = require('node:crypto') as {\n webcrypto: { subtle: Subtle };\n };\n return nodeCrypto.webcrypto.subtle;\n } catch {\n throw new Error(\n 'No WebCrypto implementation available. ' +\n 'Requires Node.js >=16, or a runtime with globalThis.crypto.subtle.'\n );\n }\n}\n","/**\n * Hash-first evidence model for OpenAI-compatible completions (DD-138).\n *\n * SHA-256 digests of messages and output.\n * No raw prompt or completion text is stored in receipts.\n *\n * Canonicalization: deterministic key-sorted JSON serialization.\n * Object keys are sorted lexicographically at every nesting level,\n * then serialized via JSON.stringify. This is NOT RFC 8785 JCS\n * (which has additional requirements for numeric handling); it is\n * sufficient for ChatMessage objects whose fields are strings,\n * booleans, nulls, and arrays of the same.\n *\n * Input constraints enforced by canonicalize():\n * - Allowed: string, number, boolean, null, plain object, array\n * - Rejected: Date, RegExp, Map, Set, Function, Symbol, BigInt, undefined\n * (at any nesting level)\n */\n\nimport { getSubtle } from './crypto.js';\nimport type { ChatMessage } from './types.js';\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst encoder = new TextEncoder();\n\n/**\n * SHA-256 hash a string, return `sha256:<hex64>`.\n *\n * Uses getSubtle() for portable WebCrypto access\n * (Node 19+ globalThis.crypto.subtle, fallback to node:crypto webcrypto).\n */\nasync function sha256(input: string): Promise<string> {\n const data = encoder.encode(input);\n const subtle = getSubtle();\n const buf = await subtle.digest('SHA-256', data);\n const hex = Array.from(new Uint8Array(buf))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n return `sha256:${hex}`;\n}\n\n// ---------------------------------------------------------------------------\n// Canonicalization\n// ---------------------------------------------------------------------------\n\n/**\n * Recursively sort object keys for deterministic serialization.\n *\n * This produces a stable JSON representation by sorting object keys\n * lexicographically at every nesting level. Arrays preserve order.\n *\n * Note: this is deterministic key-sorted JSON, not RFC 8785 JCS.\n * Suitable for ChatMessage fields (strings, nulls, arrays, booleans).\n *\n * Input constraints: only JSON-safe types are accepted (string, number,\n * boolean, null, plain object, array). Date, RegExp, Map, Set, Function,\n * Symbol, BigInt, and undefined are rejected with a TypeError.\n *\n * @throws {TypeError} if input contains non-JSON-safe types\n */\nfunction canonicalize(value: unknown): unknown {\n if (value === null) return value;\n\n if (value === undefined) {\n throw new TypeError('canonicalize: undefined is not allowed; use null instead');\n }\n\n const t = typeof value;\n\n // Primitives: string, number, boolean pass through\n if (t === 'string' || t === 'number' || t === 'boolean') {\n return value;\n }\n\n // Reject non-JSON-safe primitives\n if (t === 'bigint') {\n throw new TypeError('canonicalize: BigInt is not JSON-serializable');\n }\n if (t === 'symbol') {\n throw new TypeError('canonicalize: Symbol is not JSON-serializable');\n }\n if (t === 'function') {\n throw new TypeError('canonicalize: Function is not JSON-serializable');\n }\n\n // Object types\n if (Array.isArray(value)) {\n return value.map(canonicalize);\n }\n\n // Reject non-plain objects (Date, RegExp, Map, Set, etc.)\n if (value instanceof Date) {\n throw new TypeError('canonicalize: Date objects are not allowed; use ISO 8601 strings');\n }\n if (value instanceof RegExp) {\n throw new TypeError('canonicalize: RegExp objects are not JSON-serializable');\n }\n if (value instanceof Map || value instanceof Set) {\n throw new TypeError(\n 'canonicalize: Map/Set are not JSON-serializable; use plain objects/arrays'\n );\n }\n\n // Plain object: sort keys recursively\n if (t === 'object') {\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(value as Record<string, unknown>).sort()) {\n sorted[key] = canonicalize((value as Record<string, unknown>)[key]);\n }\n return sorted;\n }\n\n // Catch-all for any other unexpected type\n throw new TypeError(`canonicalize: unsupported type \"${t}\"`);\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Hash an array of chat messages.\n *\n * Applies deterministic key-sorted JSON serialization (sorted keys at\n * every nesting level), then computes SHA-256. Returns `sha256:<hex64>`.\n *\n * @param messages - The chat messages to hash\n * @returns `sha256:<hex64>` digest string\n * @throws {TypeError} if messages contain non-JSON-safe types\n */\nexport async function hashMessages(messages: ChatMessage[]): Promise<string> {\n const canonical = JSON.stringify(canonicalize(messages));\n return sha256(canonical);\n}\n\n/**\n * Compute the byte size of a messages array (canonical JSON).\n *\n * @throws {TypeError} if messages contain non-JSON-safe types\n */\nexport function messagesBytes(messages: ChatMessage[]): number {\n const canonical = JSON.stringify(canonicalize(messages));\n return encoder.encode(canonical).byteLength;\n}\n\n/**\n * Hash chat completion output text.\n *\n * Computes SHA-256 of the output content string.\n * Returns `sha256:<hex64>`.\n *\n * @param content - The output text to hash (concatenated choice contents)\n * @returns `sha256:<hex64>` digest string\n */\nexport async function hashOutput(content: string): Promise<string> {\n return sha256(content);\n}\n\n/**\n * Compute the byte size of output content.\n */\nexport function outputBytes(content: string): number {\n return encoder.encode(content).byteLength;\n}\n","/**\n * Evidence mapping for OpenAI-compatible chat completions (DD-138).\n *\n * Maps a ChatCompletion into InteractionEvidenceV01 using the hash-first\n * model: SHA-256 digests of messages and output, plaintext metadata only.\n */\n\nimport type { ChatCompletion, ChatMessage, InferenceReceiptParams } from './types.js';\nimport { hashMessages, hashOutput, messagesBytes, outputBytes } from './hash.js';\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/** Well-known interaction kind for chat completions. */\nexport const INFERENCE_KIND = 'inference.chat_completion';\n\n/** Extension key for inference metadata. */\nexport const INFERENCE_EXTENSION_KEY = 'org.peacprotocol/inference@0.1';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Interaction evidence structure (matches InteractionEvidenceV01 from @peac/schema). */\nexport interface InferenceEvidence {\n interaction_id: string;\n kind: typeof INFERENCE_KIND;\n executor: {\n platform: string;\n version?: string;\n };\n started_at: string;\n completed_at?: string;\n duration_ms?: number;\n input: {\n digest: {\n alg: 'sha-256';\n value: string;\n bytes: number;\n };\n redaction: 'hash_only';\n };\n output: {\n digest: {\n alg: 'sha-256';\n value: string;\n bytes: number;\n };\n redaction: 'hash_only';\n };\n result: {\n status: 'ok' | 'error';\n };\n extensions: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Concatenate all choice message contents into a single string. */\nfunction concatOutputContent(completion: ChatCompletion): string {\n return completion.choices.map((c) => c.message.content ?? '').join('');\n}\n\n/** Extract finish_reason from the first choice (if any). */\nfunction primaryFinishReason(completion: ChatCompletion): string | null {\n if (completion.choices.length === 0) return null;\n return completion.choices[0].finish_reason;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Create interaction evidence from an OpenAI-compatible chat completion.\n *\n * Hash-first model (DD-138): no raw prompt or completion text is stored.\n * Only SHA-256 digests, model ID, token counts, and timing are recorded.\n *\n * @param params - Messages, completion response, and optional provider\n * @returns InteractionEvidenceV01-compatible object\n */\nexport async function fromChatCompletion(\n params: InferenceReceiptParams\n): Promise<InferenceEvidence> {\n const { messages, completion, provider } = params;\n\n // Hash inputs and outputs\n const outputContent = concatOutputContent(completion);\n const [inputHash, outputHash] = await Promise.all([\n hashMessages(messages),\n hashOutput(outputContent),\n ]);\n\n // Extract the hex value (strip `sha256:` prefix for digest.value)\n const inputValue = inputHash.slice('sha256:'.length);\n const outputValue = outputHash.slice('sha256:'.length);\n\n // Build platform identifier\n const platform = provider ? `openai-compatible:${provider}` : 'openai-compatible';\n\n // Build inference extension metadata\n const inferenceExt: Record<string, unknown> = {\n model: completion.model,\n finish_reason: primaryFinishReason(completion),\n };\n if (completion.usage) {\n inferenceExt.usage = {\n prompt_tokens: completion.usage.prompt_tokens,\n completion_tokens: completion.usage.completion_tokens,\n total_tokens: completion.usage.total_tokens,\n };\n }\n\n // Determine result status from finish_reason\n const finishReason = primaryFinishReason(completion);\n const resultStatus: 'ok' | 'error' =\n finishReason === 'error' || completion.choices.length === 0 ? 'error' : 'ok';\n\n const evidence: InferenceEvidence = {\n interaction_id: completion.id,\n kind: INFERENCE_KIND,\n executor: {\n platform,\n version: completion.model,\n },\n started_at: new Date(completion.created * 1000).toISOString(),\n input: {\n digest: {\n alg: 'sha-256',\n value: inputValue,\n bytes: messagesBytes(messages),\n },\n redaction: 'hash_only',\n },\n output: {\n digest: {\n alg: 'sha-256',\n value: outputValue,\n bytes: outputBytes(outputContent),\n },\n redaction: 'hash_only',\n },\n result: {\n status: resultStatus,\n },\n extensions: {\n [INFERENCE_EXTENSION_KEY]: inferenceExt,\n },\n };\n\n return evidence;\n}\n"]}
@@ -0,0 +1,48 @@
1
+ /**
2
+ * OpenAI-compatible Chat Completion Types (DD-138)
3
+ *
4
+ * Self-contained minimal types matching the OpenAI chat completion API shape.
5
+ * Works with any OpenAI-compatible provider (OpenAI, Anthropic via adapter,
6
+ * Ollama, vLLM, Together, etc.) without importing their SDKs.
7
+ */
8
+ /** Chat message role */
9
+ export type ChatRole = 'system' | 'user' | 'assistant' | 'tool' | 'function';
10
+ /** Chat message */
11
+ export interface ChatMessage {
12
+ role: ChatRole;
13
+ content: string | null;
14
+ name?: string;
15
+ tool_calls?: unknown[];
16
+ tool_call_id?: string;
17
+ }
18
+ /** Token usage statistics */
19
+ export interface ChatUsage {
20
+ prompt_tokens: number;
21
+ completion_tokens: number;
22
+ total_tokens: number;
23
+ }
24
+ /** Completion choice */
25
+ export interface ChatChoice {
26
+ index: number;
27
+ message: ChatMessage;
28
+ finish_reason: string | null;
29
+ }
30
+ /** Chat completion response */
31
+ export interface ChatCompletion {
32
+ id: string;
33
+ object: string;
34
+ created: number;
35
+ model: string;
36
+ choices: ChatChoice[];
37
+ usage?: ChatUsage;
38
+ }
39
+ /** Parameters for creating interaction evidence from a chat completion */
40
+ export interface InferenceReceiptParams {
41
+ /** The chat messages sent as input */
42
+ messages: ChatMessage[];
43
+ /** The completion response */
44
+ completion: ChatCompletion;
45
+ /** Optional provider identifier (e.g., 'openai', 'anthropic', 'ollama') */
46
+ provider?: string;
47
+ }
48
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAMH,wBAAwB;AACxB,MAAM,MAAM,QAAQ,GAAG,QAAQ,GAAG,MAAM,GAAG,WAAW,GAAG,MAAM,GAAG,UAAU,CAAC;AAE7E,mBAAmB;AACnB,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,QAAQ,CAAC;IACf,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,UAAU,CAAC,EAAE,OAAO,EAAE,CAAC;IACvB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAMD,6BAA6B;AAC7B,MAAM,WAAW,SAAS;IACxB,aAAa,EAAE,MAAM,CAAC;IACtB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,YAAY,EAAE,MAAM,CAAC;CACtB;AAED,wBAAwB;AACxB,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,WAAW,CAAC;IACrB,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;CAC9B;AAED,+BAA+B;AAC/B,MAAM,WAAW,cAAc;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,UAAU,EAAE,CAAC;IACtB,KAAK,CAAC,EAAE,SAAS,CAAC;CACnB;AAMD,0EAA0E;AAC1E,MAAM,WAAW,sBAAsB;IACrC,sCAAsC;IACtC,QAAQ,EAAE,WAAW,EAAE,CAAC;IACxB,8BAA8B;IAC9B,UAAU,EAAE,cAAc,CAAC;IAC3B,2EAA2E;IAC3E,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB"}
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@peac/adapter-openai-compatible",
3
+ "version": "0.11.2",
4
+ "description": "OpenAI-compatible chat completion adapter for PEAC interaction evidence (hash-first)",
5
+ "main": "dist/index.cjs",
6
+ "types": "dist/index.d.ts",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/peacprotocol/peac.git",
10
+ "directory": "packages/adapters/openai-compatible"
11
+ },
12
+ "author": "jithinraj <7850727+jithinraj@users.noreply.github.com>",
13
+ "license": "Apache-2.0",
14
+ "bugs": {
15
+ "url": "https://github.com/peacprotocol/peac/issues"
16
+ },
17
+ "homepage": "https://github.com/peacprotocol/peac#readme",
18
+ "files": [
19
+ "dist",
20
+ "README.md"
21
+ ],
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "dependencies": {
26
+ "@peac/kernel": "0.11.2",
27
+ "@peac/schema": "0.11.2"
28
+ },
29
+ "devDependencies": {
30
+ "@types/node": "^22.19.11",
31
+ "typescript": "^5.3.3",
32
+ "vitest": "^4.0.0",
33
+ "tsup": "^8.0.0"
34
+ },
35
+ "exports": {
36
+ ".": {
37
+ "types": "./dist/index.d.ts",
38
+ "import": "./dist/index.mjs",
39
+ "require": "./dist/index.cjs",
40
+ "default": "./dist/index.mjs"
41
+ },
42
+ "./package.json": "./package.json"
43
+ },
44
+ "scripts": {
45
+ "prebuild": "rm -rf dist",
46
+ "build": "pnpm run build:js && pnpm run build:types",
47
+ "test": "vitest run",
48
+ "test:watch": "vitest",
49
+ "clean": "rm -rf dist",
50
+ "build:js": "tsup",
51
+ "build:types": "rm -f dist/.tsbuildinfo && tsc && rm -f dist/.tsbuildinfo"
52
+ }
53
+ }