@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/mod.ts ADDED
@@ -0,0 +1,563 @@
1
+ import { trash } from '@yaks/process/trash'
2
+ import * as io from '@yaks/file/io'
3
+ import {
4
+ type ChildProcess,
5
+ command,
6
+ type CommandOptions,
7
+ } from '@yaks/process/command'
8
+ import { claudeDoc } from './vocab.js'
9
+ /**
10
+ * Claude Code as a one-turn @yaks/model implementation. The MCP server it
11
+ * hosts over the CLI's control channel only advertises tools: calls are
12
+ * returned to the harness, never executed here.
13
+ * Each request replays graph history; no Claude conversation is authoritative.
14
+ * @module
15
+ */
16
+ import {
17
+ acknowledged,
18
+ began,
19
+ type Item,
20
+ type Limit,
21
+ type Listed,
22
+ type Model,
23
+ ModelError,
24
+ type Reply,
25
+ type Request,
26
+ submitted,
27
+ type Usage,
28
+ } from '@yaks/model'
29
+ import { metered } from './limits.js'
30
+ import { stallMs, watchdog, watchedBody } from '@yaks/model/stall'
31
+ import { mark } from './mark.js'
32
+ import { offer } from './offer.js'
33
+
34
+ /** Host override, chiefly for deterministic CLI contract tests. */
35
+ export type Options = {
36
+ command?: string
37
+ args?: string[]
38
+ /** the account the CLI signs in with (@yaks/model `accountEid`), whose
39
+ * plan the limits a reply carries are of */
40
+ account?: string
41
+ clock?: Parameters<typeof watchdog>[1]
42
+ spawn?: (program: string, options: CommandOptions) => Child
43
+ }
44
+
45
+ /** CLI aliases are resolved by the installed Claude Code, not pinned releases. */
46
+ export let listing = (): Listed[] =>
47
+ ['haiku', 'sonnet', 'opus'].map((name) => ({
48
+ name,
49
+ label: `Claude Code ${name}`,
50
+ modalities: ['text'],
51
+ }))
52
+
53
+ /** Full graph history is data in one stream-json user message, not --resume:
54
+ * one text block per item, oldest first. The CLI marks the message's last
55
+ * block for the prompt cache, and the next step's message begins with the same
56
+ * blocks, so the cache finds this step's prefix there and only the items since
57
+ * are read anew. One string of the whole transcript differs from the last
58
+ * step's at its end, and the cache found none of it. */
59
+ export let input = (req: Request): string =>
60
+ JSON.stringify({
61
+ type: 'user',
62
+ message: {
63
+ role: 'user',
64
+ content: req.items.map((item) => ({
65
+ type: 'text',
66
+ text: JSON.stringify(item),
67
+ })),
68
+ },
69
+ }) + '\n'
70
+
71
+ /** The public text and tool requests of one completed assistant frame. The
72
+ * CLI lists the harness's tools as `mcp__harness__<name>`, while the
73
+ * transcript it replays names each call by its own name, so Claude asks for a
74
+ * tool by either; both are that tool. A call to anything else goes to the
75
+ * harness as asked, which answers it with a refusal the model reads, as it
76
+ * does every provider's. */
77
+ export let items = (message: Record<string, unknown>): Item[] => {
78
+ if (!Array.isArray(message.content)) {
79
+ throw new ModelError('claude_protocol', 'Missing assistant content')
80
+ }
81
+ return message.content.flatMap((p): Item[] => {
82
+ if (p.type == 'text') {
83
+ return [{ kind: 'assistant', text: p.text, id: String(message.id) }]
84
+ }
85
+ if (p.type == 'thinking' || p.type == 'redacted_thinking') return []
86
+ if (p.type == 'tool_use') {
87
+ let name = String(p.name).replace(/^mcp__harness__/, '')
88
+ return [{ kind: 'call', id: p.id, name, args: JSON.stringify(p.input) }]
89
+ }
90
+ throw new ModelError(
91
+ 'claude_protocol',
92
+ `Unsupported assistant content: ${p.type}`,
93
+ )
94
+ })
95
+ }
96
+
97
+ /** One line of the CLI's stream-json output. */
98
+ // deno-lint-ignore no-explicit-any
99
+ export type Frame = Record<string, any>
100
+
101
+ /** A reply's usage from the API's usage fields, which count cache reads and
102
+ * writes beside `input_tokens`; here they are parts of it. A write kept an
103
+ * hour is priced apart from one kept five minutes, so it is counted apart. */
104
+ let counted = (u: Frame): Usage => {
105
+ let cached = u.cache_read_input_tokens ?? 0
106
+ let wrote = u.cache_creation_input_tokens ?? 0
107
+ let hour = u.cache_creation?.ephemeral_1h_input_tokens
108
+ let input = (u.input_tokens ?? 0) + cached + wrote
109
+ let output = u.output_tokens ?? 0
110
+ return {
111
+ input_tokens: input,
112
+ output_tokens: output,
113
+ total_tokens: input + output,
114
+ cached_tokens: cached,
115
+ cache_write_tokens: wrote,
116
+ ...hour ? { cache_write_1h_tokens: hour } : {},
117
+ }
118
+ }
119
+
120
+ // The CLI's errors that pass: a 429 (`rate_limit`), whether a plan window is
121
+ // spent or the service is short of capacity, and a 5xx (`server_error`).
122
+ let PASSING = ['rate_limit', 'server_error']
123
+
124
+ // The longest a spent window defers a step: its owner may reset it early.
125
+ let RESET_WAIT = 60 * 60 * 1000
126
+
127
+ /**
128
+ * What an assistant frame's `error` comes to. One that passes is `busy`, as an
129
+ * API's 429 or 5xx is (@yaks/anthropic): asked again after a backoff, or, where
130
+ * a window the stream reported is spent, deferred until it resets, an hour at
131
+ * most, spending no attempt. Any other is the CLI's no, `claude`.
132
+ */
133
+ let refused = (
134
+ frame: Frame,
135
+ limits: Limit[],
136
+ now = Date.now(),
137
+ ): ModelError => {
138
+ let code = String(frame.error)
139
+ let content = frame.message?.content
140
+ let said = (Array.isArray(content) ? content : [])
141
+ .map((p: Frame) => p.text).filter(Boolean).join('\n') || code
142
+ let error = !PASSING.includes(code)
143
+ ? new ModelError('claude', said)
144
+ : new ModelError('busy', said, resets(limits, now))
145
+ return Object.assign(error, limits.length ? { limits } : {})
146
+ }
147
+
148
+ // How long until the last spent window resets, an hour at most, as a deferral;
149
+ // a plain retry where no reading says a window is spent.
150
+ let resets = (limits: Limit[], now: number) => {
151
+ let wait = Math.max(
152
+ 0,
153
+ ...limits.filter((l) => l.used >= 100 && l.resets)
154
+ .map((l) => Date.parse(l.resets!) - now),
155
+ )
156
+ return wait > 0 ? { after: Math.min(wait, RESET_WAIT), defer: true } : {}
157
+ }
158
+
159
+ /** What the frames of one turn came to. `terminal` says the CLI reported a
160
+ * successful result, which a turn ended by a call never reaches. */
161
+ export type Turn = {
162
+ reply?: Reply
163
+ session: string
164
+ terminal: boolean
165
+ /** each plan window's newest reading the stream gave (`rate_limit_event`) */
166
+ limits: Limit[]
167
+ }
168
+
169
+ /**
170
+ * Read one turn from the CLI's frames. Text reaches `onText` as its
171
+ * `stream_event` deltas arrive, at its place among the reply's assistant
172
+ * items; each completed assistant frame then adds its items to the reply and
173
+ * tells whatever of its text no delta carried, so the text told is always the
174
+ * reply's text. Usage is the count the message ended with, which its
175
+ * `message_delta` carries; an `assistant` frame holds the count it started
176
+ * with. A message that requests a call is read through its `message_delta`,
177
+ * which the CLI writes before it dispatches the call, and reading stops there.
178
+ * Otherwise it stops at the turn's `result`. The plan limits the stream
179
+ * reports on the way are kept with the turn, and with the failure where the
180
+ * turn ends in one.
181
+ */
182
+ export let read = async (
183
+ req: Request,
184
+ frames: AsyncIterable<Frame> | Iterable<Frame>,
185
+ ): Promise<Turn> => {
186
+ let turn: Turn = { session: '', terminal: false, limits: [] }
187
+ let id = ''
188
+ // Content block index to its place among the assistant items.
189
+ let place = new Map<number, number>()
190
+ let told: string[] = []
191
+ // The message's usage as last reported, newest fields winning.
192
+ let usage: Frame = {}
193
+ let tell = (index: number, text: string) => {
194
+ if (!text) return
195
+ told[index] = (told[index] ?? '') + text
196
+ req.onText?.({ index, id, text })
197
+ }
198
+ for await (let frame of frames) {
199
+ if (frame.session_id && !turn.session) {
200
+ turn.session = frame.session_id
201
+ await acknowledged(req, { claude: { session_id: turn.session } })
202
+ }
203
+ if (frame.type == 'rate_limit_event') {
204
+ let read = metered(frame.rate_limit_info ?? {})
205
+ turn.limits = [
206
+ ...turn.limits.filter((l) =>
207
+ !read.some((r) => r.window == l.window && r.per == l.per)
208
+ ),
209
+ ...read,
210
+ ]
211
+ }
212
+ if (frame.type == 'stream_event') {
213
+ let e = frame.event ?? {}
214
+ if (e.type == 'message_start') {
215
+ id = String(e.message?.id)
216
+ usage = { ...e.message?.usage }
217
+ }
218
+ if (e.type == 'message_delta') {
219
+ usage = { ...usage, ...e.usage }
220
+ if (turn.reply) turn.reply.usage = counted(usage)
221
+ if (turn.reply?.items.some((i) => i.kind == 'call')) break
222
+ }
223
+ if (e.type == 'content_block_start') {
224
+ began(req)
225
+ if (e.content_block?.type == 'text') place.set(e.index, place.size)
226
+ }
227
+ let at = place.get(e.index)
228
+ if (e.delta?.type == 'text_delta' && at != null) tell(at, e.delta.text)
229
+ }
230
+ if (frame.type == 'assistant') {
231
+ if (turn.reply && turn.reply.id != frame.message?.id) {
232
+ throw new ModelError('claude_protocol', 'More than one model turn')
233
+ }
234
+ if (frame.error) throw refused(frame, turn.limits)
235
+ began(req)
236
+ let message = frame.message
237
+ id = String(message.id)
238
+ let prior = turn.reply?.items ?? []
239
+ let output = items(message)
240
+ // The frame's count is the message's start: never below a later one.
241
+ usage = { ...message.usage, ...usage }
242
+ turn.reply = {
243
+ id,
244
+ model: message.model ?? req.model,
245
+ items: [...prior, ...output],
246
+ usage: counted(usage),
247
+ }
248
+ let at = prior.filter((i) => i.kind == 'assistant').length
249
+ for (let item of output) {
250
+ if (item.kind != 'assistant') continue
251
+ tell(at, item.text.slice(told[at]?.length ?? 0))
252
+ at++
253
+ }
254
+ }
255
+ if (frame.type == 'result') {
256
+ turn.terminal = true
257
+ if (frame.is_error || frame.subtype != 'success') {
258
+ throw Object.assign(
259
+ new ModelError('claude', JSON.stringify(frame)),
260
+ turn.limits.length ? { limits: turn.limits } : {},
261
+ )
262
+ }
263
+ break
264
+ }
265
+ }
266
+ return turn
267
+ }
268
+
269
+ /** The CLI's arguments for one model at one effort. A step's prompt and tools
270
+ * are not among them: they reach the process with the step (`opening`), so
271
+ * the process can start before its step is known. Built-ins, settings, hooks,
272
+ * slash commands and saved sessions are all off. */
273
+ export let argv = (model: string, effort?: string): string[] => [
274
+ '-p',
275
+ '--model',
276
+ model,
277
+ '--input-format',
278
+ 'stream-json',
279
+ '--output-format',
280
+ 'stream-json',
281
+ '--verbose',
282
+ '--include-partial-messages',
283
+ '--max-turns',
284
+ '1',
285
+ '--no-session-persistence',
286
+ '--tools',
287
+ '',
288
+ '--strict-mcp-config',
289
+ '--setting-sources',
290
+ '',
291
+ '--settings',
292
+ '{"disableAllHooks":true}',
293
+ '--disable-slash-commands',
294
+ '--permission-mode',
295
+ 'dontAsk',
296
+ '--allowedTools',
297
+ 'mcp__harness__*',
298
+ ...effort ? ['--effort', effort] : [],
299
+ ]
300
+
301
+ /** The control request that opens a step: its system prompt, and the harness
302
+ * as an SDK-hosted MCP server, which the CLI asks for its tools over the same
303
+ * stdin and stdout (`offer`). */
304
+ export let opening = (req: Request): string =>
305
+ JSON.stringify({
306
+ type: 'control_request',
307
+ request_id: crypto.randomUUID(),
308
+ request: {
309
+ subtype: 'initialize',
310
+ systemPrompt: [[
311
+ 'You are the model of a graph-native harness. The user message contains the authoritative transcript, one JSON item per block, oldest first.',
312
+ 'Continue that transcript, responding to its latest user or tool result. Prior assistant/call/result items are history, not new requests.',
313
+ 'Use only the offered harness MCP tools. The graph harness executes your calls after this turn. Do not simulate tool results.',
314
+ req.instructions ?? '',
315
+ ].join('\n\n')],
316
+ sdkMcpServers: ['harness'],
317
+ },
318
+ }) + '\n'
319
+
320
+ type Child = Pick<
321
+ ChildProcess,
322
+ | 'started'
323
+ | 'status'
324
+ | 'stdin'
325
+ | 'stdout'
326
+ | 'stderr'
327
+ | 'ref'
328
+ | 'unref'
329
+ | 'kill'
330
+ >
331
+ let spawn = (program: string, options: CommandOptions) =>
332
+ command(program, options).spawn()
333
+ /** A started CLI process and its empty working directory. */
334
+ type Proc = { child: Child; cwd: string; ended: boolean }
335
+
336
+ let start = async (opts: Options, model: string, effort?: string) => {
337
+ let cwd = await io.makeTempDir({ prefix: 'yak-claude-' })
338
+ let child = (opts.spawn ?? spawn)(opts.command ?? 'claude', {
339
+ args: [...opts.args ?? [], ...argv(model, effort)],
340
+ cwd,
341
+ stdin: 'piped',
342
+ stdout: 'piped',
343
+ stderr: 'piped',
344
+ env: {
345
+ CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1',
346
+ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1',
347
+ },
348
+ })
349
+ let proc: Proc = { child, cwd, ended: false }
350
+ let ended = () => {
351
+ proc.ended = true
352
+ }
353
+ child.status.then(ended, ended)
354
+ await child.started.catch(async (error) => {
355
+ await trash(cwd)
356
+ throw error
357
+ })
358
+ // A process waiting for its step never holds its host open; it ends when
359
+ // the host does, and its stdin with it.
360
+ child.unref()
361
+ return proc
362
+ }
363
+
364
+ let end = async (proc: Proc) => {
365
+ // Its exit is waited for, so it holds the host open until then.
366
+ proc.child.ref()
367
+ proc.child.kill('SIGKILL')
368
+ await proc.child.status.catch(() => {})
369
+ await trash(proc.cwd)
370
+ }
371
+
372
+ let lines = (stream: ReadableStream<Uint8Array<ArrayBuffer>>) => {
373
+ let buffer = ''
374
+ return stream.pipeThrough(new TextDecoderStream()).pipeThrough(
375
+ new TransformStream<string, string>({
376
+ transform(chunk, controller) {
377
+ buffer += chunk
378
+ let lines = buffer.split('\n')
379
+ buffer = lines.pop()!
380
+ for (let line of lines) if (line.trim()) controller.enqueue(line)
381
+ },
382
+ flush(controller) {
383
+ if (buffer.trim()) controller.enqueue(buffer)
384
+ },
385
+ }),
386
+ )
387
+ }
388
+
389
+ /**
390
+ * Claude Code answering model requests, one CLI process per step. Requires a
391
+ * signed-in local CLI. Each step takes a process started before it, for its
392
+ * model and effort, and starts the next step's while it waits on the model,
393
+ * so a step doesn't wait for the CLI to start. A process answers one step and
394
+ * is ended: nothing one step sends reaches another's reply.
395
+ */
396
+ export let claude = (opts: Options = {}): Model & AsyncDisposable => {
397
+ // The process the next step of each model and effort takes.
398
+ let spares = new Map<string, Promise<Proc | undefined>>()
399
+ let key = (req: Request) => JSON.stringify([req.model, req.effort ?? null])
400
+ let spare = (req: Request) => {
401
+ if (spares.has(key(req))) return
402
+ spares.set(
403
+ key(req),
404
+ start(opts, req.model, req.effort).catch(() => undefined),
405
+ )
406
+ }
407
+ let accounted = (limits: Limit[]): Limit[] =>
408
+ opts.account ? limits.map((l) => ({ ...l, account: opts.account })) : limits
409
+ let take = async (req: Request) => {
410
+ let held = spares.get(key(req))
411
+ spares.delete(key(req))
412
+ let proc = await held
413
+ if (proc && !proc.ended) return proc
414
+ if (proc) await end(proc)
415
+ return await start(opts, req.model, req.effort)
416
+ }
417
+ return Object.assign(async (req: Request): Promise<Reply> => {
418
+ if (req.questions) {
419
+ throw new ModelError(
420
+ 'questions',
421
+ 'Claude Code answers no typed questions',
422
+ )
423
+ }
424
+ if (
425
+ req.input || req.items.some((i) => 'bytes' in i) ||
426
+ req.modalities?.some((m) => m != 'text')
427
+ ) {
428
+ throw new ModelError(
429
+ 'claude_input',
430
+ 'Claude Code provider supports text and harness tools only',
431
+ )
432
+ }
433
+ req.signal?.throwIfAborted()
434
+ let tools = offer(req.tools)
435
+ let proc: Proc | undefined
436
+ let kill = () => proc?.child.kill('SIGKILL')
437
+ let dog = watchdog(stallMs(req), opts.clock, req.signal)
438
+ let signal = dog.signal
439
+ let stderr: Promise<string> | undefined
440
+ try {
441
+ await submitted(req)
442
+ signal?.throwIfAborted()
443
+ proc = await take(req)
444
+ let child = proc.child
445
+ child.ref()
446
+ signal?.addEventListener('abort', kill, { once: true })
447
+ signal?.throwIfAborted()
448
+ // Drain stderr concurrently to avoid a full pipe blocking stdout.
449
+ stderr = new Response(watchedBody(child.stderr, 0, undefined, signal))
450
+ .text().then((s) => s.slice(-8192))
451
+ stderr.catch(() => {})
452
+ let writer = child.stdin.getWriter()
453
+ let send = (line: string) => writer.write(new TextEncoder().encode(line))
454
+ await send(opening(req) + input(req))
455
+ spare(req)
456
+ let reader = lines(watchedBody(child.stdout, 0, undefined, signal))
457
+ .getReader()
458
+ // The turn's frames; the control channel is answered here.
459
+ let frames = async function* (): AsyncGenerator<Frame> {
460
+ try {
461
+ while (true) {
462
+ dog.kick()
463
+ let { value, done } = await reader.read()
464
+ if (done) return
465
+ let frame: Frame = JSON.parse(value!)
466
+ if (frame.type == 'control_response') {
467
+ if (frame.response?.subtype == 'error') {
468
+ throw new ModelError('claude_protocol', frame.response.error)
469
+ }
470
+ continue
471
+ }
472
+ if (frame.type != 'control_request') {
473
+ dog.rest()
474
+ yield frame
475
+ continue
476
+ }
477
+ let r = frame.request ?? {}
478
+ let mcp = r.subtype == 'mcp_message' && r.server_name == 'harness'
479
+ ? tools(r.message ?? {})
480
+ : undefined
481
+ // A call is never answered: the harness runs it.
482
+ if (mcp == undefined && r.message?.method == 'tools/call') continue
483
+ await send(
484
+ JSON.stringify({
485
+ type: 'control_response',
486
+ response: mcp
487
+ ? {
488
+ subtype: 'success',
489
+ request_id: frame.request_id,
490
+ response: { mcp_response: mcp },
491
+ }
492
+ : {
493
+ subtype: 'error',
494
+ request_id: frame.request_id,
495
+ error: `Unsupported control request: ${r.subtype}`,
496
+ },
497
+ }) + '\n',
498
+ )
499
+ }
500
+ } finally {
501
+ void reader.cancel().catch(() => {})
502
+ reader.releaseLock()
503
+ }
504
+ }
505
+ let { reply, session, terminal, limits } = await read(req, frames())
506
+ kill()
507
+ dog.kick()
508
+ signal?.throwIfAborted()
509
+ if (!reply || (!terminal && !reply.items.some((i) => i.kind == 'call'))) {
510
+ throw new ModelError(
511
+ 'claude_exit',
512
+ await stderr || 'Claude ended without a completed turn',
513
+ )
514
+ }
515
+ return Object.assign(reply, {
516
+ claudeSession: session,
517
+ ...limits.length ? { limits: accounted(limits) } : {},
518
+ })
519
+ } catch (error) {
520
+ kill()
521
+ if (dog.stalled()) {
522
+ throw new ModelError(
523
+ 'stalled',
524
+ `Claude Code stalled — ${signal?.reason}`,
525
+ {},
526
+ )
527
+ }
528
+ signal?.throwIfAborted()
529
+ if (error instanceof ModelError && error.limits) {
530
+ error.limits = accounted(error.limits)
531
+ }
532
+ let failed = await proc?.child.status.then(() => {}, (e) => e)
533
+ if (io.isNotFound(error) || io.isNotFound(failed)) {
534
+ throw new ModelError(
535
+ 'claude_missing',
536
+ 'Install and sign in to Claude Code on the harness host',
537
+ )
538
+ }
539
+ throw error
540
+ } finally {
541
+ try {
542
+ dog.kick()
543
+ if (proc) await end(proc)
544
+ await stderr?.catch(() => {})
545
+ } finally {
546
+ signal?.removeEventListener('abort', kill)
547
+ dog.close()
548
+ }
549
+ }
550
+ }, {
551
+ list: () => Promise.resolve(listing()),
552
+ info: (name: string) =>
553
+ Promise.resolve(listing().find((m) => m.name == name)),
554
+ mark,
555
+ vocab: claudeDoc,
556
+ /** Ends the processes waiting for steps. */
557
+ [Symbol.asyncDispose]: async () => {
558
+ let held = [...spares.values()]
559
+ spares.clear()
560
+ for (let proc of await Promise.all(held)) if (proc) await end(proc)
561
+ },
562
+ })
563
+ }
package/offer.js ADDED
@@ -0,0 +1,50 @@
1
+ /**
2
+ * A discovery-only MCP server the CLI reaches over its control channel
3
+ * (`mcp_message`): it answers `initialize`, `tools/list`, `ping` and
4
+ * notifications, and returns nothing for `tools/call`, which is never
5
+ * answered: the harness runs the call after the step, and the adapter ends
6
+ * the process when it sees one.
7
+ */ export let offer = (tools)=>(message)=>{
8
+ let reply = (result)=>({
9
+ jsonrpc: '2.0',
10
+ // A notification is answered with an empty result, as the CLI asks.
11
+ id: message.id ?? 0,
12
+ result
13
+ });
14
+ if (message.id == null) return reply({});
15
+ switch(message.method){
16
+ case 'initialize':
17
+ return reply({
18
+ protocolVersion: message.params?.protocolVersion,
19
+ capabilities: {
20
+ tools: {}
21
+ },
22
+ serverInfo: {
23
+ name: 'harness',
24
+ version: '1'
25
+ }
26
+ });
27
+ case 'tools/list':
28
+ return reply({
29
+ tools: tools.map((t)=>({
30
+ name: t.name,
31
+ description: t.description,
32
+ inputSchema: t.parameters
33
+ }))
34
+ });
35
+ case 'ping':
36
+ return reply({});
37
+ case 'tools/call':
38
+ return undefined;
39
+ default:
40
+ return {
41
+ jsonrpc: '2.0',
42
+ id: message.id,
43
+ error: {
44
+ code: -32601,
45
+ message: 'Method not found'
46
+ }
47
+ };
48
+ }
49
+ };
50
+ //# sourceMappingURL=offer.js.map
package/offer.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"offer.js","sources":["./offer.ts"],"names":[],"mappings":"AASA;;;;;;CAMC,GACD,OAAO,IAAI,QAAQ,CAAC,QACpB,CACE;IAEA,IAAI,QAAQ,CAAC,SAAoB,CAAC;QAChC,SAAS;QACT,oEAAoE;QACpE,IAAI,QAAQ,EAAE,IAAI;QAClB;MACF,CAAC;IACD,IAAI,QAAQ,EAAE,IAAI,MAAM,OAAO,MAAM,CAAC;IACtC,OAAQ,QAAQ,MAAM;MACpB,KAAK;QACH,OAAO,MAAM;UACX,iBAAiB,QAAQ,MAAM,EAAE;UACjC,cAAc;YAAE,OAAO,CAAC;UAAE;UAC1B,YAAY;YAAE,MAAM;YAAW,SAAS;UAAI;QAC9C;MACF,KAAK;QACH,OAAO,MAAM;UACX,OAAO,MAAM,GAAG,CAAC,CAAC,IAAM,CAAC;cACvB,MAAM,EAAE,IAAI;cACZ,aAAa,EAAE,WAAW;cAC1B,aAAa,EAAE,UAAU;YAC3B,CAAC;QACH;MACF,KAAK;QACH,OAAO,MAAM,CAAC;MAChB,KAAK;QACH,OAAO;MACT;QACE,OAAO;UACL,SAAS;UACT,IAAI,QAAQ,EAAE;UACd,OAAO;YAAE,MAAM,CAAC;YAAO,SAAS;UAAmB;QACrD;IACJ;EACF,EAAC"}
package/offer.ts ADDED
@@ -0,0 +1,54 @@
1
+ import type { Tool } from 'jsr:@yaks/model@0.2.36'
2
+
3
+ /** A JSON-RPC message the CLI sends its SDK-hosted MCP server. */
4
+ export type Message = {
5
+ id?: number | string
6
+ method?: string
7
+ params?: Record<string, unknown>
8
+ }
9
+
10
+ /**
11
+ * A discovery-only MCP server the CLI reaches over its control channel
12
+ * (`mcp_message`): it answers `initialize`, `tools/list`, `ping` and
13
+ * notifications, and returns nothing for `tools/call`, which is never
14
+ * answered: the harness runs the call after the step, and the adapter ends
15
+ * the process when it sees one.
16
+ */
17
+ export let offer = (tools: Tool[]) =>
18
+ (
19
+ message: Message,
20
+ ): Record<string, unknown> | undefined => {
21
+ let reply = (result: unknown) => ({
22
+ jsonrpc: '2.0',
23
+ // A notification is answered with an empty result, as the CLI asks.
24
+ id: message.id ?? 0,
25
+ result,
26
+ })
27
+ if (message.id == null) return reply({})
28
+ switch (message.method) {
29
+ case 'initialize':
30
+ return reply({
31
+ protocolVersion: message.params?.protocolVersion,
32
+ capabilities: { tools: {} },
33
+ serverInfo: { name: 'harness', version: '1' },
34
+ })
35
+ case 'tools/list':
36
+ return reply({
37
+ tools: tools.map((t) => ({
38
+ name: t.name,
39
+ description: t.description,
40
+ inputSchema: t.parameters,
41
+ })),
42
+ })
43
+ case 'ping':
44
+ return reply({})
45
+ case 'tools/call':
46
+ return undefined
47
+ default:
48
+ return {
49
+ jsonrpc: '2.0',
50
+ id: message.id,
51
+ error: { code: -32601, message: 'Method not found' },
52
+ }
53
+ }
54
+ }