@kana-ai/edgar-provider-claude 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +88 -2
- package/dist/src/claude/agent.d.ts +7 -0
- package/dist/src/claude/agent.js +112 -0
- package/dist/src/claude/options.d.ts +12 -0
- package/dist/src/claude/options.js +105 -0
- package/dist/src/claude/tools.d.ts +26 -0
- package/dist/src/claude/tools.js +38 -0
- package/dist/src/main.d.ts +2 -0
- package/dist/src/main.js +37 -0
- package/dist/src/outcome/failures.d.ts +48 -0
- package/dist/src/outcome/failures.js +57 -0
- package/dist/src/outcome/reader.d.ts +23 -0
- package/dist/src/outcome/reader.js +149 -0
- package/package.json +39 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Kana.ai
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|
package/README.md
CHANGED
|
@@ -1,3 +1,89 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @kana-ai/edgar-provider-claude
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The process that runs Claude sessions for the EDGAR engine. The engine starts one per run, sends JSON-RPC 2.0 requests on stdin, one per line, and reads answers, `tool.request` requests and `session.event` notifications on stdout. The runtime writes its log to stderr. The messages are in `@kana-ai/edgar-contracts/schemas/json/provider.schema.json`.
|
|
4
|
+
|
|
5
|
+
Each session is one Claude Agent SDK `query()` (`@anthropic-ai/claude-agent-sdk` 0.3.319, which runs Claude Code 2.1.319). The model never runs a tool itself: the SDK's built-in tools are off, and the role's tools are an in-process MCP server whose handlers ask the engine through `tool.request` and give the model the engine's outcome.
|
|
6
|
+
|
|
7
|
+
## The contract
|
|
8
|
+
|
|
9
|
+
| Method | Direction | What it does |
|
|
10
|
+
| ---------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
11
|
+
| `hello` | engine to runtime | `{contract: 1}`; answers `{contract, provider: "claude", sdk_version}` |
|
|
12
|
+
| `session.start` | engine to runtime | `{session_id, model, instructions, skills, tools, limits, cwd, credential, resume?}`; answers `{handle}`, the SDK session id |
|
|
13
|
+
| `session.send` | engine to runtime | `{handle, message}`; answers `{}` and starts one turn, which ends with a `result` event. A second send before that is `busy` |
|
|
14
|
+
| `session.cancel` | engine to runtime | `{handle}`; stops the session and answers `{cancelled}`. A running turn ends `cancelled`. The handle can still be resumed |
|
|
15
|
+
| `shutdown` | engine to runtime | cancels every session, answers `null` and exits 0 |
|
|
16
|
+
| `tool.request` | runtime to engine | `{handle, call_id, tool, input}`; the engine answers `{outcome}`, and `done.output` is what the model reads. A refusal with an `ErrorCode` reaches the model as `refused` |
|
|
17
|
+
| `session.event` | runtime to engine | `{handle, event}`, where `event` is `message`, `usage` (the session's running totals, before each `result`), `limit` (the subscription limit), `result` (the turn's outcome) or `error` (the session stopped between turns) |
|
|
18
|
+
|
|
19
|
+
- A new session gets a new handle. `resume: {handle, fork: false}` continues that session under the same handle. `resume: {handle, fork: true}` starts a new handle from its history.
|
|
20
|
+
- `model` is the vendor's model id from `[providers.claude] model` in `edgar.toml`, sent to the SDK as `model`. With no such key, the engine sends the role's `model`, which is `claude`: the runtime then sends no model, and the SDK uses its default model.
|
|
21
|
+
- A turn ends `done` with what the model passed to `edgar__result` once the engine accepted it. A role without `edgar__result` ends `done` with the turn's last text.
|
|
22
|
+
- A role's `effort` is the SDK's `effort`. A role with no `effort` runs at the default of the model.
|
|
23
|
+
- `limits.max_turns` is the SDK's `maxTurns`. `limits.context_tokens` sets `CLAUDE_CODE_AUTO_COMPACT_WINDOW`. `limits.max_tokens` counts each model call's input and output tokens once, and stops the session `token_budget` when the total passes it.
|
|
24
|
+
- One mapping table in `src/outcome/failures.ts` turns the SDK's errors into outcome kinds, and keeps the raw code in `cause` (`assistant:<code>`, `status:<HTTP status>`, `terminal:<reason>`, `result:<subtype>`). A 429 with a known reset time is `rate_limited` with `retry_after`; a 429 without one, a 5xx, a 529 and a lost process are temporary; a 401, a 403 and a login failure are `unauthenticated`. A code the table does not know is `provider_unavailable`.
|
|
25
|
+
- Each SDK `rate_limit_event` becomes a `limit` event of the source `claude`: `remaining` is `0` when the status is `rejected`, `resets_at` is `resetsAt` in milliseconds, and `window` is the `rateLimitType`, such as `five_hour`. The engine stores it on the `claude` row of the `limits` table and does not start an agent stage of a Claude role while that row is used up. The `utilization` share is not read.
|
|
26
|
+
- A line over 4 MiB is refused with `runtime_payload_too_large`. The runtime exits after `--idle-seconds` (default 300) with no turn running, and cancels each open session before it exits.
|
|
27
|
+
|
|
28
|
+
## What the runtime and the CLI may reach
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
env -i PATH="$PATH" HOME=<per-run folder> \
|
|
32
|
+
node --disable-proto=throw --permission --allow-child-process \
|
|
33
|
+
--allow-fs-read=<apps/provider-claude> --allow-fs-read=<packages/sdk> \
|
|
34
|
+
--allow-fs-read=<node_modules/.pnpm> \
|
|
35
|
+
apps/provider-claude/src/main.ts --idle-seconds 300
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
- The runtime starts with `PATH` and `HOME` only. No credential is in its environment: each arrives in `session.start`.
|
|
39
|
+
- The SDK starts the Claude CLI as a child with an environment of `PATH`, `HOME` and exactly one credential: `CLAUDE_CODE_OAUTH_TOKEN` for `oauth`, `ANTHROPIC_API_KEY` for `api_key`. The engine's fallback API key comes as an `api_key` credential too, so it reaches the CLI as `ANTHROPIC_API_KEY`. The CLI uses an `ANTHROPIC_AUTH_TOKEN` or an API key over an OAuth token when it has both, so it never gets two.
|
|
40
|
+
- The `cli` credential carries no value: the child gets `PATH`, `HOME` set to `--cli-home` (the `HOME` of the user who runs `edgar start`), and `USER` and `LOGNAME` set to that user's account name from the system. It uses the sign-in of `claude auth login` that it finds there. On macOS that sign-in is in the keychain under `USER`, so the CLI is not signed in without it. The role's tools are the engine's, so they still run in the run's sandbox.
|
|
41
|
+
- An `unauthenticated` outcome's message names its fix: `claude auth login` or `ANTHROPIC_API_KEY` for the `cli` credential, else the secret of the credential it ran on.
|
|
42
|
+
- The SDK finds the CLI itself: it resolves `@anthropic-ai/claude-agent-sdk-<platform>-<arch>/claude` (or `-musl` on musl Linux) from its own package, which pnpm installs as an optional dependency for the current machine only. So `pathToClaudeCodeExecutable` is not set. A container needs the package of its own platform.
|
|
43
|
+
- An API error that the CLI tags `unknown` maps by its HTTP status: a 400 is a permanent `invalid`, and a 401 or 403 is a permanent `unauthenticated`, with the vendor's text as the message. For example, a key that is not scoped to a workspace gives 400, and the engine does not retry it.
|
|
44
|
+
- The CLI loads no settings file, no `CLAUDE.md` and no other MCP server (`settingSources: []`, `strictMcpConfig: true`), and stores its sessions under `HOME/.claude`. A resume needs the same `HOME`.
|
|
45
|
+
- `--allow-child-process` is needed to start the CLI. The CLI is a native program, so Node's permission model does not limit it. Its only tools are the engine's.
|
|
46
|
+
|
|
47
|
+
## Shortcuts
|
|
48
|
+
|
|
49
|
+
- The engine sends each tool's schema as one plain object, with no condition or branch keyword. The schema passes through Zod's `fromJSONSchema`, and the provider gives the resulting object to the in-process MCP server as it is. It does not use the SDK's `tool()`, because `tool()` takes a raw shape that the server wraps in `z.object`, which removes every key the shape does not name. So an open schema such as `{"type":"object"}` keeps every key, `additionalProperties: false` refuses an extra key, and a missing required key is an error answer to the model. The engine validates each call again. Upgrade when the SDK takes a JSON Schema directly.
|
|
50
|
+
- `canUseTool` is the allow-list: the role's tools are not in `allowedTools`, so the CLI asks `canUseTool` for each call, and it allows only `mcp__edgar__<tool>` for a listed tool. `tools: []` turns the built-in tools off and `disallowedTools` removes them by name as well.
|
|
51
|
+
- `max_tokens` is checked after each model call, so one call can pass it.
|
|
52
|
+
- `skills` holds the name and the description of each skill of the role, and no text of a skill. The system prompt lists them after the instructions under `# Skills`, one line for each, and says that `edgar__skill` loads one. A role with no skill gets no list.
|
|
53
|
+
- The `error` event's `session_gone` is in the contract, but the runtime cannot tell it yet: a resume of a session the CLI does not have ends `runtime_crashed`.
|
|
54
|
+
- `rate_limit_event.resetsAt` is read as Unix seconds. The SDK's types do not say which unit it is.
|
|
55
|
+
|
|
56
|
+
## Check the credential path
|
|
57
|
+
|
|
58
|
+
This check confirms that the Agent SDK runs a session on one person's OAuth token. It calls the Anthropic API once, with one short turn and no tools. Run it from the repository root in `zsh` or `bash` after `pnpm install`. Get a token with `claude setup-token`. Do not write the token into a file.
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
read -rs TOKEN # paste the token, then press Enter
|
|
62
|
+
WORK=$(mktemp -d) && mkdir "$WORK/home" && mkfifo "$WORK/in"
|
|
63
|
+
env -i PATH="$PATH" HOME="$WORK/home" node apps/provider-claude/src/main.ts \
|
|
64
|
+
< "$WORK/in" > "$WORK/out" 2> "$WORK/log" &
|
|
65
|
+
exec 3> "$WORK/in"
|
|
66
|
+
printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"hello","params":{"contract":1}}' >&3
|
|
67
|
+
printf '{"jsonrpc":"2.0","id":2,"method":"session.start","params":{"session_id":"c5","model":"claude-opus-5-5","instructions":"Answer with one word.","skills":[],"tools":[],"limits":{"max_turns":1},"cwd":"%s","credential":{"kind":"oauth","value":"%s"}}}\n' "$WORK" "$TOKEN" >&3
|
|
68
|
+
until grep -q '"handle"' "$WORK/out"; do sleep 1; done
|
|
69
|
+
HANDLE=$(grep -o '"handle":"[^"]*"' "$WORK/out" | head -1 | cut -d'"' -f4)
|
|
70
|
+
printf '{"jsonrpc":"2.0","id":3,"method":"session.send","params":{"handle":"%s","message":"Say hello."}}\n' "$HANDLE" >&3
|
|
71
|
+
until grep -q '"type":"result"' "$WORK/out"; do sleep 1; done
|
|
72
|
+
printf '%s\n' '{"jsonrpc":"2.0","id":4,"method":"shutdown","params":{}}' >&3
|
|
73
|
+
exec 3>&-; wait; unset TOKEN
|
|
74
|
+
cat "$WORK/out"; cat "$WORK/log"
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
A pass prints, in `$WORK/out`, these lines in order:
|
|
78
|
+
|
|
79
|
+
1. `{"jsonrpc":"2.0","id":1,"result":{"contract":1,"provider":"claude","sdk_version":"0.3.319"}}`
|
|
80
|
+
2. `{"jsonrpc":"2.0","id":2,"result":{"handle":"<uuid>"}}`
|
|
81
|
+
3. `{"jsonrpc":"2.0","id":3,"result":{}}`
|
|
82
|
+
4. a `session.event` with `"type":"message"` and the model's word
|
|
83
|
+
5. a `session.event` with `"type":"usage"` and token counts above 0
|
|
84
|
+
6. a `session.event` with `"type":"result"` and `"outcome":{"outcome":"done","output":"<the word>"}`
|
|
85
|
+
7. `{"jsonrpc":"2.0","id":4,"result":null}`
|
|
86
|
+
|
|
87
|
+
`$WORK/log` has one line `session <uuid>: Claude Code 2.1.319, credential oauth, tools <list>`. The credential is the `kind` that `session.start` sent, never its value. The tool list must be empty. A fail is a `result` with `"outcome":"permanent_failure","kind":"unauthenticated"`, or no `result` line at all, with the reason in `$WORK/log`.
|
|
88
|
+
|
|
89
|
+
Report: the date, pass or fail, the `result` line, and the `$WORK/log` line. Neither file holds the token. Then delete the folder with `rm -r "$WORK"`. To see that the token, not another login, decided the result, run the check once more with a wrong token: it must end `unauthenticated`.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type SDKSystemMessage } from "@anthropic-ai/claude-agent-sdk";
|
|
2
|
+
import type { SessionStartParams } from "@kana-ai/edgar-contracts/provider";
|
|
3
|
+
import { type Agent } from "@kana-ai/edgar-sdk/provider";
|
|
4
|
+
/** The log line of a session's start: the CLI version, the kind of credential and the tools, never the credential's value. */
|
|
5
|
+
export declare const startLine: (handle: string, spec: SessionStartParams, init: Pick<SDKSystemMessage, "claude_code_version" | "tools">) => string;
|
|
6
|
+
/** The real agent over `query()`, with the `HOME` the Claude CLI signed in under; it spawns the CLI, so it has no unit test and stays thin. */
|
|
7
|
+
export declare const claude: (cliHome: string | undefined) => Agent;
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { query } from "@anthropic-ai/claude-agent-sdk";
|
|
2
|
+
import { failedSession } from "@kana-ai/edgar-sdk/provider";
|
|
3
|
+
import { sessionOptions } from "#claude/options";
|
|
4
|
+
import { RESULT_TOOL, engineTools } from "#claude/tools";
|
|
5
|
+
import { Reader } from "#outcome/reader";
|
|
6
|
+
function errorEvent(failure) {
|
|
7
|
+
return {
|
|
8
|
+
type: "error",
|
|
9
|
+
kind: failure.kind,
|
|
10
|
+
message: failure.message,
|
|
11
|
+
...(failure.cause === undefined ? {} : { cause: failure.cause }),
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
class Inbox {
|
|
15
|
+
#items = [];
|
|
16
|
+
#wake;
|
|
17
|
+
#closed = false;
|
|
18
|
+
push(text) {
|
|
19
|
+
this.#items.push({
|
|
20
|
+
type: "user",
|
|
21
|
+
message: { role: "user", content: text },
|
|
22
|
+
parent_tool_use_id: null,
|
|
23
|
+
});
|
|
24
|
+
this.#wake?.();
|
|
25
|
+
}
|
|
26
|
+
close() {
|
|
27
|
+
this.#closed = true;
|
|
28
|
+
this.#wake?.();
|
|
29
|
+
}
|
|
30
|
+
async *[Symbol.asyncIterator]() {
|
|
31
|
+
for (;;) {
|
|
32
|
+
const next = this.#items.shift();
|
|
33
|
+
if (next !== undefined)
|
|
34
|
+
yield next;
|
|
35
|
+
else if (this.#closed)
|
|
36
|
+
return;
|
|
37
|
+
else
|
|
38
|
+
await new Promise((resolve) => (this.#wake = resolve));
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** The log line of a session's start: the CLI version, the kind of credential and the tools, never the credential's value. */
|
|
43
|
+
export const startLine = (handle, spec, init) => `session ${handle}: Claude Code ${init.claude_code_version}, credential ${spec.credential.kind}, tools ${init.tools.join(" ")}`;
|
|
44
|
+
/** The real agent over `query()`, with the `HOME` the Claude CLI signed in under; it spawns the CLI, so it has no unit test and stays thin. */
|
|
45
|
+
export const claude = (cliHome) => ({
|
|
46
|
+
start(spec, handle, bind) {
|
|
47
|
+
const hooks = bind(handle);
|
|
48
|
+
const reader = new Reader(spec);
|
|
49
|
+
const tools = engineTools(spec.tools, async (name, input) => {
|
|
50
|
+
const outcome = await hooks.toolRequest(name, input);
|
|
51
|
+
if (name === RESULT_TOOL && outcome.outcome === "done")
|
|
52
|
+
reader.capture(input);
|
|
53
|
+
return outcome;
|
|
54
|
+
});
|
|
55
|
+
if (!tools.ok)
|
|
56
|
+
return Promise.resolve({
|
|
57
|
+
handle,
|
|
58
|
+
session: failedSession(hooks, { type: "error", kind: "refused", message: tools.error }),
|
|
59
|
+
});
|
|
60
|
+
const abort = new AbortController();
|
|
61
|
+
const inbox = new Inbox();
|
|
62
|
+
const options = sessionOptions(spec, handle, tools.value, abort, cliHome);
|
|
63
|
+
let turn = false;
|
|
64
|
+
let stop;
|
|
65
|
+
const finish = (thrown) => {
|
|
66
|
+
if (turn)
|
|
67
|
+
hooks.event({ type: "result", outcome: reader.stopped(stop ?? { thrown }) });
|
|
68
|
+
else if (stop === undefined)
|
|
69
|
+
hooks.event(errorEvent(reader.ended({ thrown })));
|
|
70
|
+
};
|
|
71
|
+
const run = (async () => {
|
|
72
|
+
try {
|
|
73
|
+
for await (const message of query({ prompt: inbox, options })) {
|
|
74
|
+
if (message.type === "system" && message.subtype === "init")
|
|
75
|
+
hooks.log(startLine(handle, spec, message));
|
|
76
|
+
for (const event of reader.read(message)) {
|
|
77
|
+
if (event.type === "result")
|
|
78
|
+
turn = false;
|
|
79
|
+
hooks.event(event);
|
|
80
|
+
}
|
|
81
|
+
if (stop === undefined && reader.overBudget) {
|
|
82
|
+
stop = "token_budget";
|
|
83
|
+
abort.abort();
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
finish(undefined);
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
finish(error);
|
|
90
|
+
}
|
|
91
|
+
finally {
|
|
92
|
+
inbox.close();
|
|
93
|
+
hooks.closed();
|
|
94
|
+
}
|
|
95
|
+
})();
|
|
96
|
+
return Promise.resolve({
|
|
97
|
+
handle,
|
|
98
|
+
session: {
|
|
99
|
+
send(message) {
|
|
100
|
+
turn = true;
|
|
101
|
+
inbox.push(message);
|
|
102
|
+
},
|
|
103
|
+
async cancel() {
|
|
104
|
+
stop ??= "cancelled";
|
|
105
|
+
abort.abort();
|
|
106
|
+
inbox.close();
|
|
107
|
+
await run;
|
|
108
|
+
},
|
|
109
|
+
},
|
|
110
|
+
});
|
|
111
|
+
},
|
|
112
|
+
});
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Options } from "@anthropic-ai/claude-agent-sdk";
|
|
2
|
+
import type { SessionStartParams } from "@kana-ai/edgar-contracts/provider";
|
|
3
|
+
import { type EngineTool } from "#claude/tools";
|
|
4
|
+
/** Built-in tools of the Claude CLI, removed as well as turned off by `tools: []`. */
|
|
5
|
+
export declare const BUILT_IN_TOOLS: readonly ["Agent", "Task", "Bash", "BashOutput", "KillShell", "Read", "Write", "Edit", "MultiEdit", "Glob", "Grep", "NotebookEdit", "TodoWrite", "WebFetch", "WebSearch", "Skill", "AskUserQuestion", "EnterPlanMode", "ExitPlanMode", "TaskCreate", "TaskGet", "TaskUpdate", "TaskList", "TaskStop", "Workflow", "Monitor", "CronCreate", "CronDelete", "CronList", "EnterWorktree", "ExitWorktree", "ListMcpResourcesTool", "ReadMcpResourceTool"];
|
|
6
|
+
/** The environment variable that carries each kind of credential with a value; the CLI process gets exactly one. */
|
|
7
|
+
export declare const CREDENTIAL_VARIABLES: {
|
|
8
|
+
readonly oauth: "CLAUDE_CODE_OAUTH_TOKEN";
|
|
9
|
+
readonly api_key: "ANTHROPIC_API_KEY";
|
|
10
|
+
};
|
|
11
|
+
/** The `query()` options of one session: the model id when the engine sends one, no built-in tool, the engine's tools only, one credential, or for the `cli` credential none, the `HOME` the Claude CLI signed in under and the `USER` and `LOGNAME` whose keychain holds that sign-in. */
|
|
12
|
+
export declare function sessionOptions(spec: SessionStartParams, handle: string, tools: readonly EngineTool[], abort: AbortController, cliHome: string | undefined, base?: NodeJS.ProcessEnv): Options;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk";
|
|
2
|
+
import { userInfo } from "node:os";
|
|
3
|
+
import { skillList } from "@kana-ai/edgar-sdk/provider";
|
|
4
|
+
import { attempt, unwrapOr } from "@kana-ai/edgar-sdk/result";
|
|
5
|
+
import { SERVER, mcpName } from "#claude/tools";
|
|
6
|
+
/** Built-in tools of the Claude CLI, removed as well as turned off by `tools: []`. */
|
|
7
|
+
export const BUILT_IN_TOOLS = [
|
|
8
|
+
"Agent",
|
|
9
|
+
"Task",
|
|
10
|
+
"Bash",
|
|
11
|
+
"BashOutput",
|
|
12
|
+
"KillShell",
|
|
13
|
+
"Read",
|
|
14
|
+
"Write",
|
|
15
|
+
"Edit",
|
|
16
|
+
"MultiEdit",
|
|
17
|
+
"Glob",
|
|
18
|
+
"Grep",
|
|
19
|
+
"NotebookEdit",
|
|
20
|
+
"TodoWrite",
|
|
21
|
+
"WebFetch",
|
|
22
|
+
"WebSearch",
|
|
23
|
+
"Skill",
|
|
24
|
+
"AskUserQuestion",
|
|
25
|
+
"EnterPlanMode",
|
|
26
|
+
"ExitPlanMode",
|
|
27
|
+
"TaskCreate",
|
|
28
|
+
"TaskGet",
|
|
29
|
+
"TaskUpdate",
|
|
30
|
+
"TaskList",
|
|
31
|
+
"TaskStop",
|
|
32
|
+
"Workflow",
|
|
33
|
+
"Monitor",
|
|
34
|
+
"CronCreate",
|
|
35
|
+
"CronDelete",
|
|
36
|
+
"CronList",
|
|
37
|
+
"EnterWorktree",
|
|
38
|
+
"ExitWorktree",
|
|
39
|
+
"ListMcpResourcesTool",
|
|
40
|
+
"ReadMcpResourceTool",
|
|
41
|
+
];
|
|
42
|
+
/** The environment variable that carries each kind of credential with a value; the CLI process gets exactly one. */
|
|
43
|
+
export const CREDENTIAL_VARIABLES = {
|
|
44
|
+
oauth: "CLAUDE_CODE_OAUTH_TOKEN",
|
|
45
|
+
api_key: "ANTHROPIC_API_KEY",
|
|
46
|
+
};
|
|
47
|
+
/** The model a role names when it picks this provider and no model id: the session sends no model, so the vendor's default applies. */
|
|
48
|
+
const PROVIDER_NAME = "claude";
|
|
49
|
+
/** The `query()` options of one session: the model id when the engine sends one, no built-in tool, the engine's tools only, one credential, or for the `cli` credential none, the `HOME` the Claude CLI signed in under and the `USER` and `LOGNAME` whose keychain holds that sign-in. */
|
|
50
|
+
export function sessionOptions(spec, handle, tools, abort, cliHome, base = process.env) {
|
|
51
|
+
const allowed = new Set(spec.tools.map((t) => mcpName(t.name)));
|
|
52
|
+
const canUseTool = (name, input) => Promise.resolve(allowed.has(name)
|
|
53
|
+
? { behavior: "allow", updatedInput: input }
|
|
54
|
+
: { behavior: "deny", message: `${name} is not a tool of this role` });
|
|
55
|
+
return {
|
|
56
|
+
...(spec.model === PROVIDER_NAME ? {} : { model: spec.model }),
|
|
57
|
+
...(spec.effort === undefined ? {} : { effort: spec.effort }),
|
|
58
|
+
cwd: spec.cwd,
|
|
59
|
+
systemPrompt: [spec.instructions, skillList(spec.skills)]
|
|
60
|
+
.filter((part) => part.length > 0)
|
|
61
|
+
.join("\n\n"),
|
|
62
|
+
tools: [],
|
|
63
|
+
disallowedTools: [...BUILT_IN_TOOLS],
|
|
64
|
+
mcpServers: { [SERVER]: createSdkMcpServer({ name: SERVER, tools: [...tools] }) },
|
|
65
|
+
strictMcpConfig: true,
|
|
66
|
+
settingSources: [],
|
|
67
|
+
permissionMode: "default",
|
|
68
|
+
canUseTool,
|
|
69
|
+
env: environment(spec, base, cliHome),
|
|
70
|
+
abortController: abort,
|
|
71
|
+
...(spec.limits.max_turns === undefined ? {} : { maxTurns: spec.limits.max_turns }),
|
|
72
|
+
...resumeOptions(spec.resume, handle),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
function resumeOptions(resume, handle) {
|
|
76
|
+
if (resume === undefined)
|
|
77
|
+
return { sessionId: handle };
|
|
78
|
+
return resume.fork
|
|
79
|
+
? { resume: resume.handle, forkSession: true, sessionId: handle }
|
|
80
|
+
: { resume: resume.handle };
|
|
81
|
+
}
|
|
82
|
+
/** The user whose macOS keychain holds the CLI's sign-in: the process's own account, or `USER` when the system has no name for it, such as a container uid. */
|
|
83
|
+
function signedInUser(base) {
|
|
84
|
+
return unwrapOr(attempt(() => userInfo().username, () => undefined), base["USER"]);
|
|
85
|
+
}
|
|
86
|
+
function environment(spec, base, cliHome) {
|
|
87
|
+
const env = {};
|
|
88
|
+
const credential = spec.credential;
|
|
89
|
+
if (credential.kind !== "cli")
|
|
90
|
+
env[CREDENTIAL_VARIABLES[credential.kind]] = credential.value;
|
|
91
|
+
const path = base["PATH"];
|
|
92
|
+
if (path !== undefined)
|
|
93
|
+
env["PATH"] = path;
|
|
94
|
+
const home = credential.kind === "cli" ? cliHome : base["HOME"];
|
|
95
|
+
if (home !== undefined)
|
|
96
|
+
env["HOME"] = home;
|
|
97
|
+
const user = credential.kind === "cli" ? signedInUser(base) : undefined;
|
|
98
|
+
if (user !== undefined) {
|
|
99
|
+
env["USER"] = user;
|
|
100
|
+
env["LOGNAME"] = user;
|
|
101
|
+
}
|
|
102
|
+
if (spec.limits.context_tokens !== undefined)
|
|
103
|
+
env["CLAUDE_CODE_AUTO_COMPACT_WINDOW"] = String(spec.limits.context_tokens);
|
|
104
|
+
return env;
|
|
105
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
|
|
2
|
+
import type { ProviderTool } from "@kana-ai/edgar-contracts/provider";
|
|
3
|
+
import type { Outcome } from "@kana-ai/edgar-sdk";
|
|
4
|
+
import { type Result } from "@kana-ai/edgar-sdk/result";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
/** The name of the in-process MCP server that holds the engine's tools. */
|
|
7
|
+
export declare const SERVER = "edgar";
|
|
8
|
+
/** The engine tool through which a role returns its result. */
|
|
9
|
+
export declare const RESULT_TOOL = "edgar__result";
|
|
10
|
+
/** The name the model sees for an engine tool. */
|
|
11
|
+
export declare function mcpName(name: string): string;
|
|
12
|
+
/**
|
|
13
|
+
* One engine tool as the SDK's in-process MCP tool. Its input schema is the object Zod reads from the JSON Schema, so
|
|
14
|
+
* the MCP server keeps every key the JSON Schema allows; the SDK's `tool()` takes only a raw shape, which the server
|
|
15
|
+
* rebuilds with `z.object` and so strips each key it does not name.
|
|
16
|
+
*/
|
|
17
|
+
export interface EngineTool {
|
|
18
|
+
readonly name: string;
|
|
19
|
+
readonly description: string;
|
|
20
|
+
readonly inputSchema: z.ZodObject;
|
|
21
|
+
readonly handler: (input: unknown, extra: unknown) => Promise<CallToolResult>;
|
|
22
|
+
}
|
|
23
|
+
/** The engine's tools as MCP tools whose handlers ask the engine and give the model its outcome. */
|
|
24
|
+
export declare function engineTools(specs: readonly ProviderTool[], ask: (tool: string, input: unknown) => Promise<Outcome>): Result<EngineTool[], string>;
|
|
25
|
+
/** What the model reads: `done.output` as text, any other outcome as an error with its kind. */
|
|
26
|
+
export declare function toolResult(outcome: Outcome): CallToolResult;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { attempt, err, ok } from "@kana-ai/edgar-sdk/result";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
/** The name of the in-process MCP server that holds the engine's tools. */
|
|
4
|
+
export const SERVER = "edgar";
|
|
5
|
+
/** The engine tool through which a role returns its result. */
|
|
6
|
+
export const RESULT_TOOL = "edgar__result";
|
|
7
|
+
/** The name the model sees for an engine tool. */
|
|
8
|
+
export function mcpName(name) {
|
|
9
|
+
return `mcp__${SERVER}__${name}`;
|
|
10
|
+
}
|
|
11
|
+
/** The engine's tools as MCP tools whose handlers ask the engine and give the model its outcome. */
|
|
12
|
+
export function engineTools(specs, ask) {
|
|
13
|
+
const tools = [];
|
|
14
|
+
for (const spec of specs) {
|
|
15
|
+
const inputSchema = objectSchema(spec.input_schema);
|
|
16
|
+
if (inputSchema === undefined)
|
|
17
|
+
return err(`${spec.name}: input_schema is not a JSON Schema object`);
|
|
18
|
+
tools.push({
|
|
19
|
+
name: spec.name,
|
|
20
|
+
description: spec.description,
|
|
21
|
+
inputSchema,
|
|
22
|
+
handler: async (input) => toolResult(await ask(spec.name, input)),
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
return ok(tools);
|
|
26
|
+
}
|
|
27
|
+
function objectSchema(schema) {
|
|
28
|
+
const parsed = attempt(() => z.fromJSONSchema(schema), () => undefined);
|
|
29
|
+
return parsed.ok && parsed.value instanceof z.ZodObject ? parsed.value : undefined;
|
|
30
|
+
}
|
|
31
|
+
/** What the model reads: `done.output` as text, any other outcome as an error with its kind. */
|
|
32
|
+
export function toolResult(outcome) {
|
|
33
|
+
if (outcome.outcome === "done") {
|
|
34
|
+
const text = typeof outcome.output === "string" ? outcome.output : JSON.stringify(outcome.output);
|
|
35
|
+
return { content: [{ type: "text", text }] };
|
|
36
|
+
}
|
|
37
|
+
return { isError: true, content: [{ type: "text", text: JSON.stringify(outcome) }] };
|
|
38
|
+
}
|
package/dist/src/main.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { parseArgs } from "node:util";
|
|
4
|
+
import { claude } from "#claude/agent";
|
|
5
|
+
import { serve } from "@kana-ai/edgar-sdk/provider";
|
|
6
|
+
const log = (line) => {
|
|
7
|
+
process.stderr.write(`${line}\n`);
|
|
8
|
+
};
|
|
9
|
+
const { values } = parseArgs({
|
|
10
|
+
options: {
|
|
11
|
+
"idle-seconds": { type: "string", default: "300" },
|
|
12
|
+
"cli-home": { type: "string" },
|
|
13
|
+
},
|
|
14
|
+
});
|
|
15
|
+
const idleSeconds = Number(values["idle-seconds"]);
|
|
16
|
+
if (!Number.isInteger(idleSeconds) || idleSeconds < 1) {
|
|
17
|
+
log("usage: edgar-provider-claude [--idle-seconds <positive integer>] [--cli-home <dir>]");
|
|
18
|
+
process.exit(2);
|
|
19
|
+
}
|
|
20
|
+
const manifest = JSON.parse(await readFile(new URL("package.json", import.meta.resolve("@anthropic-ai/claude-agent-sdk")), "utf8"));
|
|
21
|
+
const version = typeof manifest === "object" && manifest !== null && "version" in manifest
|
|
22
|
+
? manifest.version
|
|
23
|
+
: undefined;
|
|
24
|
+
if (typeof version !== "string") {
|
|
25
|
+
log("refusing to start: the Claude Agent SDK has no readable package.json");
|
|
26
|
+
process.exit(1);
|
|
27
|
+
}
|
|
28
|
+
await serve({
|
|
29
|
+
input: process.stdin,
|
|
30
|
+
output: process.stdout,
|
|
31
|
+
log,
|
|
32
|
+
agent: claude(values["cli-home"]),
|
|
33
|
+
provider: "claude",
|
|
34
|
+
sdkVersion: version,
|
|
35
|
+
idleSeconds,
|
|
36
|
+
exit: (code) => process.exit(code),
|
|
37
|
+
});
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { FailureKind } from "@kana-ai/edgar-sdk";
|
|
2
|
+
/** The outcome kinds a Claude session can end with. */
|
|
3
|
+
export type Kind = Extract<FailureKind, "provider_unavailable" | "rate_limited" | "runtime_crashed" | "unauthenticated" | "context_exhausted" | "token_budget" | "cancelled" | "invalid" | "not_found" | "refused">;
|
|
4
|
+
/** The kind of a vendor code this table does not know. */
|
|
5
|
+
export declare const UNEXPECTED: Kind;
|
|
6
|
+
/** The error codes on an assistant message. */
|
|
7
|
+
export declare const ASSISTANT_ERRORS: {
|
|
8
|
+
readonly authentication_failed: "unauthenticated";
|
|
9
|
+
readonly oauth_org_not_allowed: "unauthenticated";
|
|
10
|
+
readonly account_on_hold: "unauthenticated";
|
|
11
|
+
readonly verification_required: "unauthenticated";
|
|
12
|
+
readonly cloud_credential_error: "unauthenticated";
|
|
13
|
+
readonly billing_error: "provider_unavailable";
|
|
14
|
+
readonly rate_limit: "rate_limited";
|
|
15
|
+
readonly overloaded: "provider_unavailable";
|
|
16
|
+
readonly server_error: "provider_unavailable";
|
|
17
|
+
readonly invalid_request: "invalid";
|
|
18
|
+
readonly model_not_found: "not_found";
|
|
19
|
+
readonly max_output_tokens: "token_budget";
|
|
20
|
+
readonly unknown: "provider_unavailable";
|
|
21
|
+
};
|
|
22
|
+
/** The error subtypes of a result message. */
|
|
23
|
+
export declare const RESULT_ERRORS: {
|
|
24
|
+
readonly error_max_turns: "token_budget";
|
|
25
|
+
readonly error_max_budget_usd: "token_budget";
|
|
26
|
+
readonly error_max_structured_output_retries: "invalid";
|
|
27
|
+
readonly error_during_execution: "runtime_crashed";
|
|
28
|
+
};
|
|
29
|
+
/** The terminal reasons that name a kind; the others fall through to the subtype. */
|
|
30
|
+
export declare const TERMINAL_REASONS: {
|
|
31
|
+
readonly prompt_too_long: "context_exhausted";
|
|
32
|
+
readonly blocking_limit: "context_exhausted";
|
|
33
|
+
readonly max_turns: "token_budget";
|
|
34
|
+
readonly budget_exhausted: "token_budget";
|
|
35
|
+
readonly aborted_streaming: "cancelled";
|
|
36
|
+
readonly aborted_tools: "cancelled";
|
|
37
|
+
readonly model_error: "provider_unavailable";
|
|
38
|
+
readonly malformed_tool_use_exhausted: "invalid";
|
|
39
|
+
readonly structured_output_retry_exhausted: "invalid";
|
|
40
|
+
};
|
|
41
|
+
/** The kind of an HTTP status from the Messages API. */
|
|
42
|
+
export declare function statusKind(status: number): Kind;
|
|
43
|
+
/** The assistant error table by code. */
|
|
44
|
+
export declare const assistantKinds: ReadonlyMap<string, Kind>;
|
|
45
|
+
/** The result subtype table by subtype. */
|
|
46
|
+
export declare const resultKinds: ReadonlyMap<string, Kind>;
|
|
47
|
+
/** The terminal reason table by reason. */
|
|
48
|
+
export declare const terminalKinds: ReadonlyMap<string, Kind>;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/** The kind of a vendor code this table does not know. */
|
|
2
|
+
export const UNEXPECTED = "provider_unavailable";
|
|
3
|
+
/** The error codes on an assistant message. */
|
|
4
|
+
export const ASSISTANT_ERRORS = {
|
|
5
|
+
authentication_failed: "unauthenticated",
|
|
6
|
+
oauth_org_not_allowed: "unauthenticated",
|
|
7
|
+
account_on_hold: "unauthenticated",
|
|
8
|
+
verification_required: "unauthenticated",
|
|
9
|
+
cloud_credential_error: "unauthenticated",
|
|
10
|
+
billing_error: "provider_unavailable",
|
|
11
|
+
rate_limit: "rate_limited",
|
|
12
|
+
overloaded: "provider_unavailable",
|
|
13
|
+
server_error: "provider_unavailable",
|
|
14
|
+
invalid_request: "invalid",
|
|
15
|
+
model_not_found: "not_found",
|
|
16
|
+
max_output_tokens: "token_budget",
|
|
17
|
+
unknown: UNEXPECTED,
|
|
18
|
+
};
|
|
19
|
+
/** The error subtypes of a result message. */
|
|
20
|
+
export const RESULT_ERRORS = {
|
|
21
|
+
error_max_turns: "token_budget",
|
|
22
|
+
error_max_budget_usd: "token_budget",
|
|
23
|
+
error_max_structured_output_retries: "invalid",
|
|
24
|
+
error_during_execution: "runtime_crashed",
|
|
25
|
+
};
|
|
26
|
+
/** The terminal reasons that name a kind; the others fall through to the subtype. */
|
|
27
|
+
export const TERMINAL_REASONS = {
|
|
28
|
+
prompt_too_long: "context_exhausted",
|
|
29
|
+
blocking_limit: "context_exhausted",
|
|
30
|
+
max_turns: "token_budget",
|
|
31
|
+
budget_exhausted: "token_budget",
|
|
32
|
+
aborted_streaming: "cancelled",
|
|
33
|
+
aborted_tools: "cancelled",
|
|
34
|
+
model_error: "provider_unavailable",
|
|
35
|
+
malformed_tool_use_exhausted: "invalid",
|
|
36
|
+
structured_output_retry_exhausted: "invalid",
|
|
37
|
+
};
|
|
38
|
+
/** The kind of an HTTP status from the Messages API. */
|
|
39
|
+
export function statusKind(status) {
|
|
40
|
+
if (status === 401 || status === 403)
|
|
41
|
+
return "unauthenticated";
|
|
42
|
+
if (status === 429)
|
|
43
|
+
return "rate_limited";
|
|
44
|
+
if (status === 404)
|
|
45
|
+
return "not_found";
|
|
46
|
+
if (status === 400 || status === 413)
|
|
47
|
+
return "invalid";
|
|
48
|
+
if (status === 408 || status >= 500)
|
|
49
|
+
return "provider_unavailable";
|
|
50
|
+
return UNEXPECTED;
|
|
51
|
+
}
|
|
52
|
+
/** The assistant error table by code. */
|
|
53
|
+
export const assistantKinds = new Map(Object.entries(ASSISTANT_ERRORS));
|
|
54
|
+
/** The result subtype table by subtype. */
|
|
55
|
+
export const resultKinds = new Map(Object.entries(RESULT_ERRORS));
|
|
56
|
+
/** The terminal reason table by reason. */
|
|
57
|
+
export const terminalKinds = new Map(Object.entries(TERMINAL_REASONS));
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { SDKMessage } from "@anthropic-ai/claude-agent-sdk";
|
|
2
|
+
import type { SessionEvent, SessionStartParams } from "@kana-ai/edgar-contracts/provider";
|
|
3
|
+
import { type Failure, type Outcome } from "@kana-ai/edgar-sdk";
|
|
4
|
+
/** Why a session stopped before its turn's result. */
|
|
5
|
+
type Stop = "cancelled" | "token_budget" | {
|
|
6
|
+
readonly thrown: unknown;
|
|
7
|
+
};
|
|
8
|
+
/** Reads one session's SDK messages into session events, keeping the turn's facts for the mapping table. */
|
|
9
|
+
export declare class Reader {
|
|
10
|
+
#private;
|
|
11
|
+
constructor(spec: SessionStartParams, now?: () => number);
|
|
12
|
+
/** Keeps what the model passed to `edgar__result` once the engine accepted it. */
|
|
13
|
+
capture(output: unknown): void;
|
|
14
|
+
/** True once the session spent more input and output tokens than `limits.max_tokens`. */
|
|
15
|
+
get overBudget(): boolean;
|
|
16
|
+
/** The events one SDK message gives. */
|
|
17
|
+
read(message: SDKMessage): SessionEvent[];
|
|
18
|
+
/** The outcome of a turn that stopped before its result: the result that the engine accepted when the stop is `token_budget`, else the failure of `ended`. */
|
|
19
|
+
stopped(stop: Stop): Outcome;
|
|
20
|
+
/** The failure of a session that stopped before a turn's result. */
|
|
21
|
+
ended(stop: Stop): Failure;
|
|
22
|
+
}
|
|
23
|
+
export {};
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { done, isTemporary, permanentFailure, temporaryFailure, } from "@kana-ai/edgar-sdk";
|
|
2
|
+
import { CREDENTIAL_VARIABLES } from "#claude/options";
|
|
3
|
+
import { RESULT_TOOL } from "#claude/tools";
|
|
4
|
+
import { UNEXPECTED, assistantKinds, resultKinds, statusKind, terminalKinds, } from "#outcome/failures";
|
|
5
|
+
/** Reads one session's SDK messages into session events, keeping the turn's facts for the mapping table. */
|
|
6
|
+
export class Reader {
|
|
7
|
+
#expectsResult;
|
|
8
|
+
#maxTokens;
|
|
9
|
+
#now;
|
|
10
|
+
#fix;
|
|
11
|
+
#spent = new Map();
|
|
12
|
+
#captured;
|
|
13
|
+
#assistantError;
|
|
14
|
+
#resetsAt;
|
|
15
|
+
constructor(spec, now = Date.now) {
|
|
16
|
+
this.#expectsResult = spec.tools.some((t) => t.name === RESULT_TOOL);
|
|
17
|
+
this.#maxTokens = spec.limits.max_tokens;
|
|
18
|
+
this.#now = now;
|
|
19
|
+
this.#fix =
|
|
20
|
+
spec.credential.kind === "cli"
|
|
21
|
+
? "sign in with `claude auth login`, or set `ANTHROPIC_API_KEY` in the project's `[secrets]`"
|
|
22
|
+
: `set a valid \`${CREDENTIAL_VARIABLES[spec.credential.kind]}\` in the project's \`[secrets]\``;
|
|
23
|
+
}
|
|
24
|
+
/** Keeps what the model passed to `edgar__result` once the engine accepted it. */
|
|
25
|
+
capture(output) {
|
|
26
|
+
this.#captured = { value: output };
|
|
27
|
+
}
|
|
28
|
+
/** True once the session spent more input and output tokens than `limits.max_tokens`. */
|
|
29
|
+
get overBudget() {
|
|
30
|
+
if (this.#maxTokens === undefined)
|
|
31
|
+
return false;
|
|
32
|
+
let total = 0;
|
|
33
|
+
for (const tokens of this.#spent.values())
|
|
34
|
+
total += tokens;
|
|
35
|
+
return total > this.#maxTokens;
|
|
36
|
+
}
|
|
37
|
+
/** The events one SDK message gives. */
|
|
38
|
+
read(message) {
|
|
39
|
+
if (message.type === "assistant") {
|
|
40
|
+
const usage = message.message.usage;
|
|
41
|
+
this.#spent.set(message.message.id, usage.input_tokens + usage.output_tokens);
|
|
42
|
+
if (message.error !== undefined)
|
|
43
|
+
this.#assistantError = message.error;
|
|
44
|
+
if (message.parent_tool_use_id !== null)
|
|
45
|
+
return [];
|
|
46
|
+
const text = message.message.content
|
|
47
|
+
.flatMap((block) => (block.type === "text" ? [block.text] : []))
|
|
48
|
+
.join("");
|
|
49
|
+
return text.length === 0 ? [] : [{ type: "message", role: "assistant", text }];
|
|
50
|
+
}
|
|
51
|
+
if (message.type === "rate_limit_event") {
|
|
52
|
+
if (message.rate_limit_info.status === "rejected")
|
|
53
|
+
this.#resetsAt = message.rate_limit_info.resetsAt;
|
|
54
|
+
return [limitEvent(message.rate_limit_info)];
|
|
55
|
+
}
|
|
56
|
+
if (message.type !== "result")
|
|
57
|
+
return [];
|
|
58
|
+
const events = [
|
|
59
|
+
usageEvent(message),
|
|
60
|
+
{ type: "result", outcome: this.#outcome(message) },
|
|
61
|
+
];
|
|
62
|
+
this.#captured = undefined;
|
|
63
|
+
this.#assistantError = undefined;
|
|
64
|
+
return events;
|
|
65
|
+
}
|
|
66
|
+
/** The outcome of a turn that stopped before its result: the result that the engine accepted when the stop is `token_budget`, else the failure of `ended`. */
|
|
67
|
+
stopped(stop) {
|
|
68
|
+
if (stop === "token_budget" && this.#captured !== undefined)
|
|
69
|
+
return done(this.#captured.value);
|
|
70
|
+
return this.ended(stop);
|
|
71
|
+
}
|
|
72
|
+
/** The failure of a session that stopped before a turn's result. */
|
|
73
|
+
ended(stop) {
|
|
74
|
+
if (stop === "cancelled")
|
|
75
|
+
return this.#failure("cancelled", "the session was cancelled", "edgar:cancelled");
|
|
76
|
+
if (stop === "token_budget")
|
|
77
|
+
return this.#failure("token_budget", "the session spent its max_tokens", "edgar:max_tokens");
|
|
78
|
+
return this.#failure("runtime_crashed", stop.thrown instanceof Error ? stop.thrown.message : "the Claude process ended", "edgar:thrown");
|
|
79
|
+
}
|
|
80
|
+
/** The outcome of a turn's result: a named assistant error first, then the API's HTTP status, because the CLI tags an API error it does not name, such as a 400 for a key outside a workspace, `unknown`. */
|
|
81
|
+
#outcome(result) {
|
|
82
|
+
if (result.subtype === "success" && !result.is_error) {
|
|
83
|
+
if (result.stop_reason === "refusal")
|
|
84
|
+
return this.#failure("refused", result.result, "stop:refusal");
|
|
85
|
+
if (!this.#expectsResult)
|
|
86
|
+
return done(result.result);
|
|
87
|
+
if (this.#captured !== undefined)
|
|
88
|
+
return done(this.#captured.value);
|
|
89
|
+
return this.#failure("invalid", `the turn ended without ${RESULT_TOOL}`, "edgar:no_result");
|
|
90
|
+
}
|
|
91
|
+
const message = result.subtype === "success" ? result.result : result.errors.join("; ");
|
|
92
|
+
const status = result.subtype === "success" ? result.api_error_status : undefined;
|
|
93
|
+
const assistant = this.#assistantError;
|
|
94
|
+
if (assistant !== undefined && !(assistant === "unknown" && typeof status === "number"))
|
|
95
|
+
return this.#failure(assistantKinds.get(assistant) ?? UNEXPECTED, message, `assistant:${assistant}`);
|
|
96
|
+
if (typeof status === "number")
|
|
97
|
+
return this.#failure(statusKind(status), message, `status:${status}`);
|
|
98
|
+
const reason = result.terminal_reason;
|
|
99
|
+
const terminal = reason === undefined ? undefined : terminalKinds.get(reason);
|
|
100
|
+
if (terminal !== undefined)
|
|
101
|
+
return this.#failure(terminal, message, `terminal:${reason}`);
|
|
102
|
+
return this.#failure(resultKinds.get(result.subtype) ?? UNEXPECTED, message, `result:${result.subtype}`);
|
|
103
|
+
}
|
|
104
|
+
/** A failure; an `unauthenticated` one names the sign-in or the secret that fixes it. */
|
|
105
|
+
#failure(kind, text, cause) {
|
|
106
|
+
const message = kind === "unauthenticated" ? `${text.replace(/\.$/, "")}; ${this.#fix}.` : text;
|
|
107
|
+
if (kind === "rate_limited") {
|
|
108
|
+
if (this.#resetsAt === undefined)
|
|
109
|
+
return temporaryFailure("provider_unavailable", message, { cause });
|
|
110
|
+
const retryAfterSeconds = Math.max(0, Math.ceil(this.#resetsAt - this.#now() / 1000));
|
|
111
|
+
return temporaryFailure("rate_limited", message, { cause, retryAfterSeconds });
|
|
112
|
+
}
|
|
113
|
+
return isTemporary(kind)
|
|
114
|
+
? temporaryFailure(kind, message, { cause })
|
|
115
|
+
: permanentFailure(kind, message, { cause });
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/** The subscription limit a `rate_limit_event` reports: used up when `rejected`, with its window and its reset in Unix seconds. */
|
|
119
|
+
function limitEvent(info) {
|
|
120
|
+
return {
|
|
121
|
+
type: "limit",
|
|
122
|
+
limit: {
|
|
123
|
+
source: "claude",
|
|
124
|
+
...(info.status === "rejected" ? { remaining: 0 } : {}),
|
|
125
|
+
...(info.resetsAt === undefined ? {} : { resets_at: Math.round(info.resetsAt * 1000) }),
|
|
126
|
+
...(info.rateLimitType === undefined ? {} : { window: info.rateLimitType }),
|
|
127
|
+
},
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
function usageEvent(result) {
|
|
131
|
+
let input = 0;
|
|
132
|
+
let output = 0;
|
|
133
|
+
let read = 0;
|
|
134
|
+
let write = 0;
|
|
135
|
+
for (const model of Object.values(result.modelUsage)) {
|
|
136
|
+
input += model.inputTokens;
|
|
137
|
+
output += model.outputTokens;
|
|
138
|
+
read += model.cacheReadInputTokens;
|
|
139
|
+
write += model.cacheCreationInputTokens;
|
|
140
|
+
}
|
|
141
|
+
return {
|
|
142
|
+
type: "usage",
|
|
143
|
+
input_tokens: input,
|
|
144
|
+
output_tokens: output,
|
|
145
|
+
cache_read_tokens: read,
|
|
146
|
+
cache_write_tokens: write,
|
|
147
|
+
cost_usd: result.total_cost_usd,
|
|
148
|
+
};
|
|
149
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kana-ai/edgar-provider-claude",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "The process that runs Claude sessions for the EDGAR engine through the Claude Agent SDK, over JSON-RPC on stdio.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/kana-ai/edgar",
|
|
9
|
+
"directory": "apps/provider-claude"
|
|
10
|
+
},
|
|
11
|
+
"bin": {
|
|
12
|
+
"edgar-provider-claude": "./dist/src/main.js"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist/src"
|
|
16
|
+
],
|
|
17
|
+
"type": "module",
|
|
18
|
+
"imports": {
|
|
19
|
+
"#*": "./dist/src/*.js"
|
|
20
|
+
},
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"@anthropic-ai/claude-agent-sdk": "0.3.319",
|
|
23
|
+
"@kana-ai/edgar-contracts": "0.1.0",
|
|
24
|
+
"@kana-ai/edgar-sdk": "0.1.0",
|
|
25
|
+
"zod": "4.6.7"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"@anthropic-ai/sdk": "1.6.0",
|
|
29
|
+
"@modelcontextprotocol/sdk": "1.32.2",
|
|
30
|
+
"@types/node": "24.19.2",
|
|
31
|
+
"oxfmt": "0.76.0",
|
|
32
|
+
"oxlint": "1.91.0",
|
|
33
|
+
"oxlint-tsgolint": "7.0.2005",
|
|
34
|
+
"typescript": "7.0.2"
|
|
35
|
+
},
|
|
36
|
+
"scripts": {
|
|
37
|
+
"check-types": "tsc --noEmit",
|
|
38
|
+
"lint": "oxlint --type-aware --deny-warnings",
|
|
39
|
+
"format:check": "oxfmt --check",
|
|
40
|
+
"test": "node --test"
|
|
41
|
+
}
|
|
6
42
|
}
|