reviewer-protocol 0.0.1 → 1.0.0-beta.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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,5 +1,136 @@
1
- # reviewer-protocol
1
+ # Reviewer Protocol
2
2
 
3
- Reviewer Protocol: the protocol, manifest format, and TypeScript SDK for connecting reviewer harnesses to review orchestrators.
3
+ The Reviewer Protocol connects a _reviewer_ — a coding-agent harness asked to review a change — to a _host_ that orchestrates reviews. A reviewer always runs as its own process, so it can be written in any language and stays isolated from the host.
4
4
 
5
- This package is a placeholder and is not yet published. See [reviewfixloop.com](https://reviewfixloop.com) for updates.
5
+ A harness connects in one of two ways:
6
+
7
+ | Kind | For | Connection |
8
+ | --------------- | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
9
+ | A: CLI wrapper | an existing harness | A declarative [manifest](#manifests) tells the host how to launch the vendor's CLI (or its ACP server) and how to map its output to protocol events. |
10
+ | B: native agent | a harness you develop | The harness speaks [ACP](https://agentclientprotocol.com) v1 with the [Reviewer Protocol extension](#acp-extension). |
11
+
12
+ This package holds the protocol's schemas ([zod](https://zod.dev)) and the functions a host and a manifest author share: manifest parsing and hashing, template rendering, and the output mapping.
13
+
14
+ ```sh
15
+ npm install reviewer-protocol
16
+ ```
17
+
18
+ ## Boundary
19
+
20
+ The host gives a reviewer the checkout's path (its working directory), a task prompt, the revision under review, a time limit, and the model and effort to use. The reviewer returns the [events](#events) below. A session takes several prompts in order (the review, reminders, verification of fixes); a harness that cannot continue a session receives each later prompt, made self-contained, in a new process.
21
+
22
+ The host decides timeouts, crashes and cancellations itself, since no vendor reports them reliably.
23
+
24
+ ## Events
25
+
26
+ | `type` | Fields | Purpose |
27
+ | ---------- | ------------------------------------------------------------------------------------------------ | ----------------------------------------- |
28
+ | `session` | `id`, `harness` (`name`, `version`), `model` | continuing the session, recording it |
29
+ | `progress` | `kind` (`message`, `thought`, `tool_start`, `tool_end`, `model_call`), `text` | the job's log, tool and model call counts |
30
+ | `usage` | `key`, `model`, `input`, `output`, `cacheRead`, `cacheWrite`, `reasoning`, `costUsd`, `servedBy` | usage totals |
31
+ | `log` | `level`, `text` | diagnostics kept on the user's machine |
32
+ | `turn_end` | `status`, `stopReason`, `text`, `failure`, `usageComplete` | the result of one prompt |
33
+
34
+ - A turn's usage is complete only when its process reported usage: a turn of a process that produced no `usage` event (the manifest maps none, or the harness died first), or one of whose reports held none of the declared token counts (unreported usage, not zero tokens), ends with `usageComplete: false`. The host decides this once the process has exited, with `ProcessMapper.usageUnreported`: a `turn_end` mapped from a line cannot know what the harness prints after it.
35
+ - A process reports its session once, however often the harness names it.
36
+ - Token counts have one meaning for every harness: `input` excludes cache reads and writes, `output` includes reasoning, and `reasoning` is the part of `output` spent on reasoning. Each `usage` event is a delta; `key` makes a report delivered twice count once.
37
+ - A `model_call` marks one request to the model. A harness whose output does not mark them emits none, so a session without `model_call` has an unknown number of model calls, not zero.
38
+ - Tokens are authoritative. `costUsd` is a reference value: few harnesses report it and some estimate it.
39
+ - `servedBy` counts the model calls each upstream provider served, by the name the endpoint gave it, for a harness that calls a gateway routing one model to several providers.
40
+ - `failure.kind` is one of `authentication`, `quota`, `rate_limit`, `overloaded`, `context_overflow`, `max_output`, `refusal`, `model_not_found`, `transport`, `harness_error`, `unknown`.
41
+
42
+ ## Manifests
43
+
44
+ A manifest is a JSONC file validated by a schema that rejects unknown keys. It holds no code:
45
+
46
+ - Templates substitute `{{var}}`, add arguments only when a variable has a value (`{ "when": "model", "args": [...] }`), expand a list (`{ "each": "writableDirs", "args": ["--add-dir", "{{item}}"] }`), and apply the `json` and `toml` filters (`{{writableDirs | toml}}`).
47
+ - A path the host acts on (`files`, `usageFile`) starts with `{{scratchDir}}/` and has no `..` segment; the host refuses a rendered path outside the scratch directory.
48
+ - Every `{{` opens a placeholder, so a template cannot hold a literal `{{`; `}}` elsewhere is literal text, as in JSON.
49
+ - The variables are `prompt`, `model`, `effort`, `sessionId`, `deadlineMinutes`, `logFile`, `scratchDir`, `tmpDir` (the temporary directory of a sandboxed launch), and `writableDirs`.
50
+ - Regular expressions must match in linear time: they are compiled with RE2, which has no backreferences or lookaround.
51
+ - The output mapping addresses a line's fields with JSON Pointers (RFC 6901).
52
+
53
+ ```jsonc
54
+ {
55
+ "schema": 1,
56
+ "id": "example",
57
+ "display": { "name": "Example" }, // shown to people; not part of the identity
58
+ "command": "example", // resolved on PATH: the user's own installation
59
+ "transport": {
60
+ "type": "jsonl",
61
+ "args": ["run", "--json", { "when": "model", "args": ["--model", "{{model}}"] }],
62
+ "resumeArgs": ["run", "--json", "--session", "{{sessionId}}"],
63
+ "stdin": "{{prompt}}",
64
+ "usage": { "mode": "delta" },
65
+ "events": [
66
+ { "match": { "/type": "start" }, "emit": { "type": "session", "id": { "from": "/id" } } },
67
+ {
68
+ "match": { "/type": "done" },
69
+ "emit": {
70
+ "type": "usage",
71
+ "input": { "from": "/tokens/input" },
72
+ "output": { "from": "/tokens/output" },
73
+ "cacheRead": { "from": "/tokens/cached" },
74
+ },
75
+ },
76
+ {
77
+ "match": { "/type": "done" },
78
+ "emit": { "type": "turn_end", "status": "completed", "text": { "from": "/text" } },
79
+ },
80
+ ],
81
+ },
82
+ "failures": [{ "pattern": "(?i)not logged in", "kind": "authentication" }],
83
+ }
84
+ ```
85
+
86
+ - `usage` declares how the harness counts tokens (`mode: "cumulative"` for running totals of the session, `inputIncludesCacheRead`, `inputIncludesCacheWrite`, `outputIncludesReasoning`), and the host normalizes them to the meaning above. `usageFile` names a JSON file to read the usage from when the output carries none (a manifest declares it or usage rules, not both): the host removes it before each launch, reads it once the process has exited, and reports the turn's `turn_end` after its usage, with `usageComplete: false` when the file is missing, unreadable, or holds none of the declared counts.
87
+ - A rule applies to a line that satisfies `match` (every JSON Pointer equals its value, or one of its values) and does not satisfy `unless`; with `each`, it emits one event per element of the named array that satisfies `itemMatch`.
88
+ - A process that ends without a mapped `turn_end` ends its turn by its exit status.
89
+ - `failures` classify a failure the harness did not classify itself. Each pattern is tried on the failure message followed by the end of standard error, and the match that starts latest decides.
90
+ - `"transport": { "type": "acp", ... }` launches the harness's ACP server instead; `"native": true` marks a kind B harness.
91
+ - `resolver` overrides the launch for a harness that is asked to fix what the reviewers found.
92
+ - `sandbox` lets a host run the harness in a sandbox that confines it to the working copy, its scratch and temporary directories, and the tools on PATH, gives it its own home directory, and lets it reach only the hosts allowed. `passEnv` names the variables of the user's environment passed in unchanged, `signInEnv` the ones passed likewise that the harness signs in with (a host leaves the harness out of a sandboxed run while none is set), both kept in a sandbox even where `env.unset` names them, `setEnv` sets variables in the sandbox alone, and `domains` lists the hosts the harness connects to (`*.` and a domain covers the hosts under it). A host refuses to sandbox a harness whose manifest has no `sandbox`.
93
+
94
+ A manifest can run arbitrary commands with the user's privileges, so a host shows the resolved arguments, the environment variables it sets and removes, the files it writes, the usage file it removes and reads, and what a sandboxed launch passes in and reaches (`resolveLaunch`) when a manifest is added and whenever its hash changes.
95
+
96
+ ### Identity
97
+
98
+ `manifestHash` is the SHA-256 of the validated manifest canonicalized by RFC 8785, without `display`. Formatting, comments and display wording never change it.
99
+
100
+ ## ACP extension
101
+
102
+ A kind B harness is an ACP v1 agent. ACP carries custom data only under `_meta`, so the extension lives under the key `reviewer-protocol/v1`:
103
+
104
+ | Where | Content |
105
+ | ------------------------------------------------------ | -------------------------------------------------------- |
106
+ | `agentCapabilities._meta` in the `initialize` response | `{ "version": 1 }`: the agent speaks the extension |
107
+ | `_meta` of the `session/new` request | `role`, `revision`, `deadlineMinutes`, `model`, `effort` |
108
+ | `_meta` of the `session/prompt` response | `usage`, `usageComplete`, `failure` |
109
+
110
+ The host creates one session per review (`session/new`), sends each prompt with `session/prompt`, and sends `session/cancel` at the time limit. It offers no `fs` or `terminal` capability, passes no MCP servers, and answers every permission request with an allow option: the agent uses its own tools in the checkout. It never calls `authenticate`: the agent signs in with what its user configured beforehand.
111
+
112
+ `acpMeta` and `readAcpMeta` build and read the extension's `_meta` in an agent written with the [ACP TypeScript SDK](https://www.npmjs.com/package/@agentclientprotocol/sdk):
113
+
114
+ ```ts
115
+ import { ACP_META_KEY, acpMeta, acpSessionMetaSchema, readAcpMeta } from 'reviewer-protocol';
116
+
117
+ // initialize
118
+ return { protocolVersion: 1, agentCapabilities: { _meta: acpMeta({ version: 1 }) } };
119
+ // session/new
120
+ const conditions = readAcpMeta(params._meta, acpSessionMetaSchema);
121
+ // session/prompt
122
+ return { stopReason: 'end_turn', _meta: acpMeta({ usage: { input: 1200, output: 340, cacheRead: 0 } }) };
123
+ ```
124
+
125
+ ## Versions and compatibility
126
+
127
+ The protocol is in beta: the `reviewer-protocol` package on npm has prereleases (`1.0.0-beta.<n>`) under the `beta` dist-tag, and a placeholder under `latest`. Until the first official release, the protocol and the manifest schema change incompatibly without raising their versions. The rules below apply from that release on.
128
+
129
+ - The protocol and the manifest schema each carry an integer major version (`REVIEWER_PROTOCOL_VERSION`, `MANIFEST_SCHEMA_VERSION`).
130
+ - Adding an optional field or a `failure.kind` to the protocol does not raise its major: a host ignores unknown fields and reads an unknown kind as `unknown`.
131
+ - The manifest schema rejects unknown keys, so adding a key raises its version. A host refuses a manifest newer than itself and asks to be updated.
132
+ - After a new major is released, the previous one stays supported for at least six months.
133
+
134
+ ## License
135
+
136
+ [Apache-2.0](LICENSE)
package/dist/acp.d.ts ADDED
@@ -0,0 +1,65 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * The Reviewer Protocol's extension of ACP (Agent Client Protocol) v1. ACP carries custom
4
+ * data only under `_meta`, so everything the protocol adds travels under this key: the
5
+ * agent advertises it in `initialize`, the host sends the session's conditions with
6
+ * `session/new`, and the agent reports each turn's usage and failure with its
7
+ * `session/prompt` response.
8
+ */
9
+ export declare const ACP_META_KEY = "reviewer-protocol/v1";
10
+ /** In `agentCapabilities._meta` of the `initialize` response: the agent speaks the extension. */
11
+ export declare const acpCapabilityMetaSchema: z.ZodObject<{
12
+ version: z.ZodLiteral<1>;
13
+ }, z.core.$strip>;
14
+ export type AcpCapabilityMeta = z.infer<typeof acpCapabilityMetaSchema>;
15
+ /** In `_meta` of the `session/new` request: what ACP itself has no field for. */
16
+ export declare const acpSessionMetaSchema: z.ZodObject<{
17
+ role: z.ZodEnum<{
18
+ resolver: "resolver";
19
+ reviewer: "reviewer";
20
+ }>;
21
+ revision: z.ZodString;
22
+ deadlineMinutes: z.ZodOptional<z.ZodNumber>;
23
+ model: z.ZodOptional<z.ZodString>;
24
+ effort: z.ZodOptional<z.ZodString>;
25
+ }, z.core.$strip>;
26
+ export type AcpSessionMeta = z.infer<typeof acpSessionMetaSchema>;
27
+ /**
28
+ * In `_meta` of the `session/prompt` response: the turn's usage in the protocol's unified
29
+ * meaning (see usageEventSchema) and, for a turn the agent could not finish, its failure.
30
+ */
31
+ export declare const acpTurnMetaSchema: z.ZodObject<{
32
+ usage: z.ZodOptional<z.ZodObject<{
33
+ model: z.ZodOptional<z.ZodString>;
34
+ input: z.ZodNumber;
35
+ output: z.ZodNumber;
36
+ cacheRead: z.ZodNumber;
37
+ cacheWrite: z.ZodOptional<z.ZodNumber>;
38
+ reasoning: z.ZodOptional<z.ZodNumber>;
39
+ costUsd: z.ZodOptional<z.ZodNumber>;
40
+ servedBy: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
41
+ }, z.core.$strip>>;
42
+ usageComplete: z.ZodOptional<z.ZodBoolean>;
43
+ failure: z.ZodOptional<z.ZodObject<{
44
+ kind: z.ZodCatch<z.ZodEnum<{
45
+ authentication: "authentication";
46
+ context_overflow: "context_overflow";
47
+ harness_error: "harness_error";
48
+ max_output: "max_output";
49
+ model_not_found: "model_not_found";
50
+ overloaded: "overloaded";
51
+ quota: "quota";
52
+ rate_limit: "rate_limit";
53
+ refusal: "refusal";
54
+ transport: "transport";
55
+ unknown: "unknown";
56
+ }>>;
57
+ message: z.ZodString;
58
+ retryAt: z.ZodOptional<z.ZodNumber>;
59
+ }, z.core.$strip>>;
60
+ }, z.core.$strip>;
61
+ export type AcpTurnMeta = z.infer<typeof acpTurnMetaSchema>;
62
+ /** The extension's part of an ACP `_meta` object, validated by `schema`; undefined when absent or malformed. */
63
+ export declare function readAcpMeta<Schema extends z.ZodType>(meta: unknown, schema: Schema): z.infer<Schema> | undefined;
64
+ /** An ACP `_meta` object carrying the extension's part. */
65
+ export declare function acpMeta<Value>(value: Value): Record<typeof ACP_META_KEY, Value>;
package/dist/acp.js ADDED
@@ -0,0 +1,43 @@
1
+ import { z } from 'zod';
2
+ import { failureSchema, usageEventSchema } from './events.js';
3
+ import { MANIFEST_ROLES } from './manifest.js';
4
+ /**
5
+ * The Reviewer Protocol's extension of ACP (Agent Client Protocol) v1. ACP carries custom
6
+ * data only under `_meta`, so everything the protocol adds travels under this key: the
7
+ * agent advertises it in `initialize`, the host sends the session's conditions with
8
+ * `session/new`, and the agent reports each turn's usage and failure with its
9
+ * `session/prompt` response.
10
+ */
11
+ export const ACP_META_KEY = 'reviewer-protocol/v1';
12
+ /** In `agentCapabilities._meta` of the `initialize` response: the agent speaks the extension. */
13
+ export const acpCapabilityMetaSchema = z.object({ version: z.literal(1) });
14
+ /** In `_meta` of the `session/new` request: what ACP itself has no field for. */
15
+ export const acpSessionMetaSchema = z.object({
16
+ role: z.enum(MANIFEST_ROLES),
17
+ /** The revision under review: a commit SHA. */
18
+ revision: z.string().min(1),
19
+ /** Minutes until the host cancels the session's turn. */
20
+ deadlineMinutes: z.number().positive().optional(),
21
+ model: z.string().min(1).optional(),
22
+ effort: z.string().min(1).optional(),
23
+ });
24
+ /**
25
+ * In `_meta` of the `session/prompt` response: the turn's usage in the protocol's unified
26
+ * meaning (see usageEventSchema) and, for a turn the agent could not finish, its failure.
27
+ */
28
+ export const acpTurnMetaSchema = z.object({
29
+ usage: usageEventSchema.omit({ type: true, key: true }).optional(),
30
+ usageComplete: z.boolean().optional(),
31
+ failure: failureSchema.optional(),
32
+ });
33
+ /** The extension's part of an ACP `_meta` object, validated by `schema`; undefined when absent or malformed. */
34
+ export function readAcpMeta(meta, schema) {
35
+ if (meta === null || typeof meta !== 'object')
36
+ return undefined;
37
+ const result = schema.safeParse(meta[ACP_META_KEY]);
38
+ return result.success ? result.data : undefined;
39
+ }
40
+ /** An ACP `_meta` object carrying the extension's part. */
41
+ export function acpMeta(value) {
42
+ return { [ACP_META_KEY]: value };
43
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Serializes a JSON value by RFC 8785 (JSON Canonicalization Scheme): object members sorted
3
+ * by their names' UTF-16 code units, no insignificant whitespace, and ECMAScript's number and
4
+ * string serialization. `Array.prototype.sort` without a comparator and `JSON.stringify` are
5
+ * exactly those orderings and serializations.
6
+ */
7
+ export declare function canonicalJson(value: unknown): string;
8
+ export declare function sha256Hex(text: string): Promise<string>;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Serializes a JSON value by RFC 8785 (JSON Canonicalization Scheme): object members sorted
3
+ * by their names' UTF-16 code units, no insignificant whitespace, and ECMAScript's number and
4
+ * string serialization. `Array.prototype.sort` without a comparator and `JSON.stringify` are
5
+ * exactly those orderings and serializations.
6
+ */
7
+ export function canonicalJson(value) {
8
+ if (value === null || typeof value !== 'object') {
9
+ if (typeof value === 'number' && !Number.isFinite(value))
10
+ throw new Error('JSON has no non-finite numbers');
11
+ const text = JSON.stringify(value);
12
+ if (text === undefined)
13
+ throw new Error(`not a JSON value: ${typeof value}`);
14
+ return text;
15
+ }
16
+ if (Array.isArray(value))
17
+ return `[${value.map((element) => canonicalJson(element)).join(',')}]`;
18
+ const members = Object.keys(value)
19
+ .toSorted()
20
+ .flatMap((name) => {
21
+ const member = value[name];
22
+ return member === undefined ? [] : [`${JSON.stringify(name)}:${canonicalJson(member)}`];
23
+ });
24
+ return `{${members.join(',')}}`;
25
+ }
26
+ export async function sha256Hex(text) {
27
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
28
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('');
29
+ }