@yaks/claude 0.0.0-stage → 0.2.36

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 2026 Jeff Peterson
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,3 +1,123 @@
1
- # Temporary Holding Version
1
+ # @yaks/claude
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A native harness `Model` backed by the owner's signed-in `claude -p`. This is
4
+ not the outside-agent adapter in `@yaks/spawn`: the harness owns execution,
5
+ permissions, machine routing, calls, results and the transcript.
6
+
7
+ Compose `@yaks/claude` alongside `@yaks/harness` to declare its reply metadata,
8
+ then choose the provider and a Claude Code model alias or full name:
9
+
10
+ ```sh
11
+ yak session new 'Read the task graph' --provider claude --model haiku
12
+ ```
13
+
14
+ The harness host needs the `claude` executable and subscription sign-in. Model
15
+ and provider selection remain graph rows (`@yaks/model`); `list()` advertises
16
+ `haiku`, `sonnet`, `opus`, resolved by the installed CLI. No default model,
17
+ release, context window or API price is invented here. A full model name can
18
+ also be requested and confirmed by the normal provider resolver.
19
+
20
+ ## One turn, one owner of tools
21
+
22
+ Each step is answered by its own CLI process in an empty temporary directory,
23
+ which reads stream-json input and writes stream-json output. The step's explicit
24
+ system prompt arrives in the process's `initialize` control request, and the
25
+ graph history as JSON transcript data in one user message. Settings sources,
26
+ hooks, slash commands, auto-memory and nonessential traffic are disabled.
27
+ `--tools ''` disables built-ins. The harness is an SDK-hosted MCP server
28
+ (`sdkMcpServers`): the CLI asks it for its tools over the same stdin and stdout,
29
+ and it advertises exactly the request's tool definitions. It **never executes a
30
+ tool**: a `tools/call` is never answered. On the completed assistant tool-use
31
+ frame the adapter kills the child, returning neutral calls to the harness, whose
32
+ ordinary loop persists and executes them. A call names its tool bare
33
+ (`graph_query`) or as the CLI lists it (`mcp__harness__graph_query`); a call to
34
+ a tool the step did not offer reaches the harness as asked, and the harness
35
+ answers it with a refusal the model can read and recover from. `--max-turns 1`
36
+ also bounds the CLI's loop. Text-only completion must end in a successful
37
+ result. `--include-partial-messages` makes the CLI send text as it is written,
38
+ and each piece reaches the request's `onText` as it arrives; the completed frame
39
+ tells only what no piece carried. There are no retries within this adapter;
40
+ durable submission/acknowledgement uses the same model callbacks as the HTTP
41
+ providers. A message the CLI ends with `error: "rate_limit"` or `"server_error"`
42
+ (a 429 or a 5xx) is `busy` and passes, as an API's is: the session asks again
43
+ after a backoff, and where the stream said a plan window is spent, defers until
44
+ it resets, an hour at most. Any other error is the CLI's no (`claude`).
45
+
46
+ The graph records each ask, assistant text, requested call, harness result, CLI
47
+ session/message ids and reported token usage: input, output, what was read from
48
+ the prompt cache and what was written to it, a write kept an hour counted apart
49
+ since it lists at more. The reply names the release its alias resolved to, and
50
+ the request is weighed at that release's price (@yaks/session `ask.served`).
51
+ Claude's displayed dollar estimate is not a subscription charge and is not
52
+ recorded as a paid API bill. Cancellation kills the child and trashes its
53
+ directory.
54
+
55
+ ## A process started before its step
56
+
57
+ The CLI takes 0.3–0.6 s to start, before it reads its input. Nothing of a step
58
+ is in its arguments except the model and effort, so each step takes a process
59
+ already started for them and, once its own input is sent, starts the one the
60
+ next step takes. A process answers one step and is then killed: one step's input
61
+ never reaches another's reply. A waiting process doesn't hold its host open
62
+ (`unref`); it reads end-of-file and exits when the host does. Each holds about
63
+ 190 MB while it waits, one for each model and effort asked for. The model is
64
+ `AsyncDisposable`, which ends the waiting ones.
65
+
66
+ The CLI pipes use the same idle watchdog as HTTP model streams. A gap in
67
+ progress ends the child process and reports a retryable `stalled` model error.
68
+ The default is five minutes, and `provider{stall_timeout}` sets the provider's
69
+ own limit in seconds.
70
+
71
+ Through `/model/step` on this box, one-word `haiku` steps 3 s apart reached
72
+ first text in 612–2015 ms (median 876) this way, and 858–2949 ms (median 1145)
73
+ with a process started per step. workers/yak/README.md has the rest of an
74
+ Operator step's time.
75
+
76
+ ## When the cache goes cold
77
+
78
+ The CLI chooses how long the prompt cache keeps a prefix, and a reply names no
79
+ expiry. `mark(reply, cache)` writes
80
+ `claude{response_id, session_id, cache_expires_at}`: the expiry is the request's
81
+ start plus the lifetime its provider row records, `provider{cache_retention}` in
82
+ seconds ([@yaks/model](../model/README.md), "Cached-prefix expiry"). Where the
83
+ row records none the expiry is null, which every reader takes as cold.
84
+
85
+ Measured on 2026-11-11 with Claude Code 2.1.322 signed in to a subscription, on
86
+ `fable` and `haiku`: a 35,000-token prefix nobody else had sent was written
87
+ once, then sent again with one more block after its own gap. After 4, 6 and 55
88
+ minutes all of it was read from the cache; after 65 minutes none was, and it was
89
+ written again. Every write was reported as `ephemeral_1h_input_tokens`. So the
90
+ `claude` provider row on this box records `cache_retention: 3600`.
91
+
92
+ ## What is not graph-native
93
+
94
+ `claude` owns subscription authentication, transport/init diagnostics, internal
95
+ prompt additions, thinking and token/cache accounting. Its private state cannot
96
+ be exported into the neutral `Model` interface. We retain reported token usage,
97
+ not hidden thinking or CLI diagnostic traffic. The CLI is a host integration,
98
+ not a session machine; it has no task checkout and its built-ins cannot work on
99
+ one. Like other process integrations this is not an OS security sandbox.
100
+
101
+ We deliberately do **not** use `--resume`. A resumed CLI conversation would own
102
+ context, compaction, instructions and tool results outside the graph. Instead,
103
+ the graph history is replayed as data on every ask (not native Anthropic
104
+ assistant/tool-result wire blocks), for a single source of truth. Each item is
105
+ its own text block of the one user message, so the next ask's message begins
106
+ with this one's and the prompt cache holds all but the items since. Sent as one
107
+ string, the whole transcript missed the cache on every ask: a second ask on a
108
+ 27K-token transcript wrote 27,741 tokens to the cache, and as blocks it writes
109
+ 614 and reads 34,857. `--no-session-persistence` prevents saved CLI conversation
110
+ threads. CLI aliases may change with Claude Code. `--bare` cannot be used for
111
+ this subscription-backed path: its help explicitly disables OAuth. Images, typed
112
+ questions and model-native inputs fail explicitly before spending.
113
+
114
+ A `native` marker on harness-created/delegated transcripts distinguishes them
115
+ from unmarked managed Claude sessions. Spawn ignores the former; the native
116
+ provider leaves the latter alone, including existing heal fixers. The spawn
117
+ adapter remains for outside Claude agents, their built-in tools and saved
118
+ threads. Moving heal requires changing its opener/machine/persona preparation
119
+ and process-based concurrency accounting; it is not switched by this package.
120
+
121
+ Tested against Claude Code 2.1.322. Tests hand `read` the CLI's frames in
122
+ process, never a paid Claude invocation. A live probe should use `--model haiku`
123
+ and stay short.
@@ -0,0 +1,28 @@
1
+ import type { Limit } from "@yaks/model";
2
+ type Info = Record<string, unknown>;
3
+ /**
4
+ * The readings in a `rate_limit_event`'s `rate_limit_info`: each window's
5
+ * fraction used and when it resets (`unifiedWindows`), whatever the status;
6
+ * where an older CLI sends none, the one window the event is about, which
7
+ * says how much is used only past a warning.
8
+ *
9
+ * ```ts
10
+ * import { metered } from './limits.ts'
11
+ * import { equal } from '@yaks/testing'
12
+ *
13
+ * let week = { utilization: 0.25, resetsAt: 1794913200 }
14
+ * equal(metered({ status: 'allowed', unifiedWindows: { seven_day: week } }), [
15
+ * { provider: 'claude', window: 10080, used: 25, resets: '2026-11-17T11:00:00.000Z' },
16
+ * ])
17
+ * equal(metered({ rateLimitType: 'five_hour', utilization: 0.9 }), [
18
+ * { provider: 'claude', window: 300, used: 90 },
19
+ * ])
20
+ * equal(metered({ status: 'allowed', rateLimitType: 'five_hour' }), [])
21
+ * // The model's own weekly cap is a second limit beside the week.
22
+ * let cap = { utilization: 0.06, resetsAt: 1794913200 }
23
+ * equal(metered({ unifiedWindows: { seven_day: week, seven_day_overage_included: cap } })[1], {
24
+ * provider: 'claude', window: 10080, per: 'model', used: 6, resets: '2026-11-17T11:00:00.000Z',
25
+ * })
26
+ * ```
27
+ */ export declare let metered: (info: Info) => Limit[];
28
+ //# sourceMappingURL=limits.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"limits.d.ts","sources":["../limits.ts"],"names":[],"mappings":"AAIA,cAAc,KAAK,2BAAgC;KAW9C,OAAO,OAAO,MAAM,EAAE,OAAO;AASlC;;;;;;;;;;;;;;;;;;;;;;;;CAwBC,GACD,OAAO,YAAI,UAAW,MAAM,SAAO,QAgBlC"}
package/_dist/mod.d.ts ADDED
@@ -0,0 +1,67 @@
1
+ import { type ChildProcess, type CommandOptions } from "@yaks/process/command";
2
+ /**
3
+ * Claude Code as a one-turn @yaks/model implementation. The MCP server it
4
+ * hosts over the CLI's control channel only advertises tools: calls are
5
+ * returned to the harness, never executed here.
6
+ * Each request replays graph history; no Claude conversation is authoritative.
7
+ * @module
8
+ */ import { type Item, type Limit, type Listed, type Model, type Reply, type Request } from "@yaks/model";
9
+ import { watchdog } from "@yaks/model/stall";
10
+ /** Host override, chiefly for deterministic CLI contract tests. */ export type Options = {
11
+ command?: string;
12
+ args?: string[];
13
+ /** the account the CLI signs in with (@yaks/model `accountEid`), whose
14
+ * plan the limits a reply carries are of */ account?: string;
15
+ clock?: Parameters<typeof watchdog>[1];
16
+ spawn?: (program: string, options: CommandOptions) => Child;
17
+ };
18
+ /** CLI aliases are resolved by the installed Claude Code, not pinned releases. */ export declare let listing: () => Listed[];
19
+ /** Full graph history is data in one stream-json user message, not --resume:
20
+ * one text block per item, oldest first. The CLI marks the message's last
21
+ * block for the prompt cache, and the next step's message begins with the same
22
+ * blocks, so the cache finds this step's prefix there and only the items since
23
+ * are read anew. One string of the whole transcript differs from the last
24
+ * step's at its end, and the cache found none of it. */ export declare let input: (req: Request) => string;
25
+ /** The public text and tool requests of one completed assistant frame. The
26
+ * CLI lists the harness's tools as `mcp__harness__<name>`, while the
27
+ * transcript it replays names each call by its own name, so Claude asks for a
28
+ * tool by either; both are that tool. A call to anything else goes to the
29
+ * harness as asked, which answers it with a refusal the model reads, as it
30
+ * does every provider's. */ export declare let items: (message: Record<string, unknown>) => Item[];
31
+ /** One line of the CLI's stream-json output. */ export type Frame = Record<string, any>;
32
+ /** What the frames of one turn came to. `terminal` says the CLI reported a
33
+ * successful result, which a turn ended by a call never reaches. */ export type Turn = {
34
+ reply?: Reply;
35
+ session: string;
36
+ terminal: boolean;
37
+ /** each plan window's newest reading the stream gave (`rate_limit_event`) */ limits: Limit[];
38
+ };
39
+ /**
40
+ * Read one turn from the CLI's frames. Text reaches `onText` as its
41
+ * `stream_event` deltas arrive, at its place among the reply's assistant
42
+ * items; each completed assistant frame then adds its items to the reply and
43
+ * tells whatever of its text no delta carried, so the text told is always the
44
+ * reply's text. Usage is the count the message ended with, which its
45
+ * `message_delta` carries; an `assistant` frame holds the count it started
46
+ * with. A message that requests a call is read through its `message_delta`,
47
+ * which the CLI writes before it dispatches the call, and reading stops there.
48
+ * Otherwise it stops at the turn's `result`. The plan limits the stream
49
+ * reports on the way are kept with the turn, and with the failure where the
50
+ * turn ends in one.
51
+ */ export declare let read: (req: Request, frames: AsyncIterable<Frame> | Iterable<Frame>) => Promise<Turn>;
52
+ /** The CLI's arguments for one model at one effort. A step's prompt and tools
53
+ * are not among them: they reach the process with the step (`opening`), so
54
+ * the process can start before its step is known. Built-ins, settings, hooks,
55
+ * slash commands and saved sessions are all off. */ export declare let argv: (model: string, effort?: string) => string[];
56
+ /** The control request that opens a step: its system prompt, and the harness
57
+ * as an SDK-hosted MCP server, which the CLI asks for its tools over the same
58
+ * stdin and stdout (`offer`). */ export declare let opening: (req: Request) => string;
59
+ type Child = Pick<ChildProcess, 'started' | 'status' | 'stdin' | 'stdout' | 'stderr' | 'ref' | 'unref' | 'kill'>;
60
+ /**
61
+ * Claude Code answering model requests, one CLI process per step. Requires a
62
+ * signed-in local CLI. Each step takes a process started before it, for its
63
+ * model and effort, and starts the next step's while it waits on the model,
64
+ * so a step doesn't wait for the CLI to start. A process answers one step and
65
+ * is ended: nothing one step sends reaches another's reply.
66
+ */ export declare let claude: (opts?: Options) => Model & AsyncDisposable;
67
+ //# sourceMappingURL=mod.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.d.ts","sources":["../mod.ts"],"names":[],"mappings":"AAEA,SACE,KAAK,YAAY,EAEjB,KAAK,cAAc,qCACoB;AAEzC;;;;;;CAMC,GACD,SAGE,KAAK,IAAI,EACT,KAAK,KAAK,EACV,KAAK,MAAM,EACX,KAAK,KAAK,EAEV,KAAK,KAAK,EACV,KAAK,OAAO,2BAGiB;AAE/B,SAAkB,QAAQ,iCAAmD;AAI7E,iEAAiE,GACjE,YAAY;EACV,UAAU,MAAM;EAChB,OAAO,MAAM;EACb;4CAC0C,GAC1C,UAAU,MAAM;EAChB,QAAQ,kBAAkB,UAAU;EACpC,SAAS,SAAS,MAAM,EAAE,SAAS,mBAAmB;;AAGxD,gFAAgF,GAChF,OAAO,YAAI,eAAc,SAKpB;AAEL;;;;;sDAKsD,GACtD,OAAO,YAAI,QAAS,KAAK,YAAU,MAAM,CAU9B;AAEX;;;;;0BAK0B,GAC1B,OAAO,YAAI,QAAS,SAAS,OAAO,MAAM,EAAE,OAAO,MAAI,OAkBtD;AAED,8CAA8C,GAE9C,YAAY,QAAQ,OAAO,MAAM,EAAE,GAAG;AA4DtC;kEACkE,GAClE,YAAY;EACV,QAAQ;EACR,SAAS,MAAM;EACf,UAAU,OAAO;EACjB,2EAA2E,GAC3E,QAAQ;;AAGV;;;;;;;;;;;;CAYC,GACD,OAAO,YAAI,OACT,KAAK,SACL,QAAQ,cAAc,SAAS,SAAS,WACvC,QAAQ,MAkFV;AAED;;;kDAGkD,GAClD,OAAO,YAAI,OAAQ,OAAO,MAAM,EAAE,SAAS,MAAM,KAAG,MAAM,GA0BzD;AAED;;+BAE+B,GAC/B,OAAO,YAAI,UAAW,KAAK,YAAU,MAAM,CAchC;KAEN,QAAQ,KACX,cACE,YACA,WACA,UACA,WACA,WACA,QACA,UACA;AA4DJ;;;;;;CAMC,GACD,OAAO,YAAI,SAAU,OAAM,YAAe,QAAQ,gBAuKjD"}
@@ -0,0 +1,4 @@
1
+ import { type Lent, type Model } from "@yaks/model";
2
+ import type { Options } from "./mod.js";
3
+ /** `claude`, the local Claude Code CLI. */ export declare let providers: (lent: Lent, options?: Options) => Record<string, Model>;
4
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sources":["../provider.ts"],"names":[],"mappings":"AAOA,SAIE,KAAK,IAAI,EACT,KAAK,KAAK,2BACmB;AAE/B,cAAc,OAAO,mBAAkB;AAGvC,yCAAyC,GACzC,OAAO,YAAI,YACT,MAAM,MACN,UAAS,YACR,OAAO,MAAM,EAAE,OAgBjB"}
@@ -0,0 +1,4 @@
1
+ import type { VocabDoc } from "@yaks/vocab";
2
+ export declare let claudeDoc: VocabDoc;
3
+ export declare let docs: VocabDoc[];
4
+ //# sourceMappingURL=vocab.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vocab.d.ts","sources":["../vocab.ts"],"names":[],"mappings":"AAAA,cAAc,QAAQ,2BAAgC;AAEtD,OAAO,YAAI,WAAW,SAAc;AACpC,OAAO,YAAI,MAAM,WAAwB"}
package/cli_fixture.ts ADDED
@@ -0,0 +1,92 @@
1
+ // A stand-in for `claude -p` in stream-json mode, for mod_test.ts. It appends
2
+ // `boot <pid>` to the file its first argument names when it starts, lists its
3
+ // tools over the control channel when a step opens, and answers each user
4
+ // message with one text block: what this process has seen, as JSON. A message
5
+ // saying `please call` is answered with a call of its first tool, which it then
6
+ // dispatches and waits on, as the CLI does.
7
+
8
+ let log = Deno.args[0]
9
+ await Deno.writeTextFile(log, `boot ${Deno.pid}\n`, { append: true })
10
+ let encoder = new TextEncoder()
11
+ let emit = (frame: unknown) => {
12
+ Deno.stdout.writeSync(encoder.encode(JSON.stringify(frame) + '\n'))
13
+ }
14
+ let pending = new Map<string, (response: unknown) => void>()
15
+ let ask = (message: unknown) => {
16
+ let id = crypto.randomUUID()
17
+ emit({
18
+ type: 'control_request',
19
+ request_id: id,
20
+ request: { subtype: 'mcp_message', server_name: 'harness', message },
21
+ })
22
+ return new Promise<unknown>((resolve) => pending.set(id, resolve))
23
+ }
24
+ let seen: { prompt?: string; tools: string[]; users: unknown[] } = {
25
+ tools: [],
26
+ users: [],
27
+ }
28
+ let opened = async (
29
+ frame: { request_id: string; request: { systemPrompt: string[] } },
30
+ ) => {
31
+ seen.prompt = frame.request.systemPrompt.join('')
32
+ await ask({ jsonrpc: '2.0', id: 0, method: 'initialize', params: {} })
33
+ let listed = await ask({ jsonrpc: '2.0', id: 1, method: 'tools/list' }) as {
34
+ mcp_response: { result: { tools: { name: string }[] } }
35
+ }
36
+ seen.tools = listed.mcp_response.result.tools.map((t) => t.name)
37
+ emit({
38
+ type: 'control_response',
39
+ response: { subtype: 'success', request_id: frame.request_id },
40
+ })
41
+ }
42
+ let answer = (text: string) => {
43
+ let message = { id: `message-${Deno.pid}`, model: 'fixture', usage: {} }
44
+ emit({ type: 'system', subtype: 'init', session_id: `session-${Deno.pid}` })
45
+ emit({
46
+ type: 'stream_event',
47
+ event: { type: 'message_start', message },
48
+ })
49
+ if (text.includes('please call')) {
50
+ let call = {
51
+ type: 'tool_use',
52
+ id: 'call-1',
53
+ name: `mcp__harness__${seen.tools[0]}`,
54
+ input: {},
55
+ }
56
+ emit({ type: 'assistant', message: { ...message, content: [call] } })
57
+ ask({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: {} })
58
+ emit({ type: 'stream_event', event: { type: 'message_delta', usage: {} } })
59
+ return
60
+ }
61
+ let content = [{
62
+ type: 'text',
63
+ text: JSON.stringify({ pid: Deno.pid, ...seen }),
64
+ }]
65
+ emit({ type: 'assistant', message: { ...message, content } })
66
+ emit({ type: 'stream_event', event: { type: 'message_delta', usage: {} } })
67
+ emit({ type: 'result', subtype: 'success' })
68
+ }
69
+ // A step's message is answered once its opening has listed the tools, which
70
+ // needs the host's answers from this same stdin.
71
+ let open = Promise.resolve()
72
+ let buffer = ''
73
+ for await (
74
+ let chunk of Deno.stdin.readable.pipeThrough(new TextDecoderStream())
75
+ ) {
76
+ buffer += chunk
77
+ let lines = buffer.split('\n')
78
+ buffer = lines.pop()!
79
+ for (let line of lines.filter((l) => l.trim())) {
80
+ let frame = JSON.parse(line)
81
+ if (frame.type == 'control_response') {
82
+ pending.get(frame.response.request_id)?.(frame.response.response)
83
+ }
84
+ if (frame.request?.subtype == 'initialize') open = opened(frame)
85
+ if (frame.type == 'user') {
86
+ seen.users.push(
87
+ ...frame.message.content.map((b: { text: string }) => b.text),
88
+ )
89
+ open = open.then(() => answer(line))
90
+ }
91
+ }
92
+ }
package/deno.json ADDED
@@ -0,0 +1 @@
1
+ {"publish":{"exclude":["**/*_test.ts"]},"name":"@yaks/claude","version":"0.2.36","license":"Apache-2.0","description":"Claude Code print mode as a one-turn model; the graph harness alone executes tools.","exports":{".":"./mod.ts","./vocab":"./vocab.ts","./limits":"./limits.ts","./provider":"./provider.ts"},"imports":{"@yaks/claude":"./mod.ts","@yaks/claude/vocab":"./vocab.ts","@yaks/claude/limits":"./limits.ts","@yaks/claude/provider":"./provider.ts"}}
package/limits.js ADDED
@@ -0,0 +1,68 @@
1
+ // Claude's plan limits, as the CLI's stream reports them. Its own module
2
+ // (`@yaks/claude/limits`) so a reader of the stream's lines (@yaks/session)
3
+ // reads them as the model does, without loading the model.
4
+ // Claude's plan windows a reading is kept of, in minutes. The week has a
5
+ // second limit, `seven_day_overage_included`, which only a Fable request's
6
+ // stream reports: the plan's weekly cap on that model.
7
+ let WINDOWS = {
8
+ five_hour: {
9
+ window: 300
10
+ },
11
+ seven_day: {
12
+ window: 10080
13
+ },
14
+ seven_day_overage_included: {
15
+ window: 10080,
16
+ per: 'model'
17
+ }
18
+ };
19
+ let obj = (v)=>v && typeof v == 'object' && !Array.isArray(v) ? v : {};
20
+ let count = (v)=>{
21
+ if (v == null) return undefined;
22
+ let n = Number(v);
23
+ return Number.isFinite(n) ? n : undefined;
24
+ };
25
+ /**
26
+ * The readings in a `rate_limit_event`'s `rate_limit_info`: each window's
27
+ * fraction used and when it resets (`unifiedWindows`), whatever the status;
28
+ * where an older CLI sends none, the one window the event is about, which
29
+ * says how much is used only past a warning.
30
+ *
31
+ * ```ts
32
+ * import { metered } from './limits.ts'
33
+ * import { equal } from '@yaks/testing'
34
+ *
35
+ * let week = { utilization: 0.25, resetsAt: 1794913200 }
36
+ * equal(metered({ status: 'allowed', unifiedWindows: { seven_day: week } }), [
37
+ * { provider: 'claude', window: 10080, used: 25, resets: '2026-11-17T11:00:00.000Z' },
38
+ * ])
39
+ * equal(metered({ rateLimitType: 'five_hour', utilization: 0.9 }), [
40
+ * { provider: 'claude', window: 300, used: 90 },
41
+ * ])
42
+ * equal(metered({ status: 'allowed', rateLimitType: 'five_hour' }), [])
43
+ * // The model's own weekly cap is a second limit beside the week.
44
+ * let cap = { utilization: 0.06, resetsAt: 1794913200 }
45
+ * equal(metered({ unifiedWindows: { seven_day: week, seven_day_overage_included: cap } })[1], {
46
+ * provider: 'claude', window: 10080, per: 'model', used: 6, resets: '2026-11-17T11:00:00.000Z',
47
+ * })
48
+ * ```
49
+ */ export let metered = (info)=>{
50
+ let each = obj(info.unifiedWindows);
51
+ let windows = Object.keys(each).length ? each : {
52
+ [String(info.rateLimitType ?? '')]: info
53
+ };
54
+ return Object.entries(WINDOWS).flatMap(([name, limit])=>{
55
+ let w = obj(windows[name]);
56
+ return count(w.utilization) == null ? [] : [
57
+ {
58
+ provider: 'claude',
59
+ ...limit,
60
+ used: Math.round(Number(w.utilization) * 100),
61
+ ...count(w.resetsAt) == null ? {} : {
62
+ resets: new Date(Number(w.resetsAt) * 1000).toISOString()
63
+ }
64
+ }
65
+ ];
66
+ });
67
+ };
68
+ //# sourceMappingURL=limits.js.map
package/limits.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"limits.js","sources":["./limits.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,4EAA4E;AAC5E,2DAA2D;AAI3D,yEAAyE;AACzE,2EAA2E;AAC3E,uDAAuD;AACvD,IAAI,UAAyD;EAC3D,WAAW;IAAE,QAAQ;EAAI;EACzB,WAAW;IAAE,QAAQ;EAAM;EAC3B,4BAA4B;IAAE,QAAQ;IAAO,KAAK;EAAQ;AAC5D;AAGA,IAAI,MAAM,CAAC,IACT,KAAK,OAAO,KAAK,YAAY,CAAC,MAAM,OAAO,CAAC,KAAK,IAAY,CAAC;AAChE,IAAI,QAAQ,CAAC;EACX,IAAI,KAAK,MAAM,OAAO;EACtB,IAAI,IAAI,OAAO;EACf,OAAO,OAAO,QAAQ,CAAC,KAAK,IAAI;AAClC;AAEA;;;;;;;;;;;;;;;;;;;;;;;;CAwBC,GACD,OAAO,IAAI,UAAU,CAAC;EACpB,IAAI,OAAO,IAAI,KAAK,cAAc;EAClC,IAAI,UAAU,OAAO,IAAI,CAAC,MAAM,MAAM,GAClC,OACA;IAAE,CAAC,OAAO,KAAK,aAAa,IAAI,IAAI,EAAE;EAAK;EAC/C,OAAO,OAAO,OAAO,CAAC,SAAS,OAAO,CAAC,CAAC,CAAC,MAAM,MAAM;IACnD,IAAI,IAAI,IAAI,OAAO,CAAC,KAAK;IACzB,OAAO,MAAM,EAAE,WAAW,KAAK,OAAO,EAAE,GAAG;MAAC;QAC1C,UAAU;QACV,GAAG,KAAK;QACR,MAAM,KAAK,KAAK,CAAC,OAAO,EAAE,WAAW,IAAI;QACzC,GAAG,MAAM,EAAE,QAAQ,KAAK,OACpB,CAAC,IACD;UAAE,QAAQ,IAAI,KAAK,OAAO,EAAE,QAAQ,IAAI,MAAM,WAAW;QAAG,CAAC;MACnE;KAAE;EACJ;AACF,EAAC"}