Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

protocol.ts

737 lines24.6 KB

1import { convertSchemaToJsonSchema } from '@tanstack/ai'
2import { AccessDeniedError } from './access'
3import { parseTraceparent } from './observability'
4import { isRecord } from './utils'
5import { createInputId, errorText } from './session/helpers'
6import { storeInlineMedia } from './inline-media'
7import { SessionImpl } from './session/harness-session'
8import { mediaIdOf } from './media-ref'
9import type { ModelMessage, StreamChunk } from '@tanstack/ai'
10import type { AnyAgent } from './agents'
11import type { AnyHarness } from './define'
12import type { InlineMediaContext } from './inline-media'
13import type { HarnessSession, SessionSnapshot } from './session/index'
14import type { AgentRunStartOptions } from './session/types'
15import type {
16 Cursor,
17 HarnessInput,
18 Operation,
19 HarnessUser,
20 Receipt,
21 UserInput,
22} from './types'
23​
24/** The session-tier protocol version. Sent in `subscribe` and `hello`. */
25export const HARNESS_PROTOCOL_VERSION = 2
26​
27/** What failed, in a `harness.error` frame. */
28export type HarnessErrorCode =
29 | 'unauthorized'
30 | 'forbidden'
31 | 'invalid_frame'
32 | 'unsupported_version'
33 | 'slow_consumer'
34 | 'internal'
35​
36/** Client to host. */
37export type ControlFrame =
38 | { type: 'harness.subscribe'; threadId: string; from?: Cursor; v?: number }
39 | {
40 type: 'harness.input'
41 requestId: string
42 input: HarnessInput
43 /** A W3C `traceparent` of the caller. An invalid value is dropped. */
44 traceparent?: string
45 }
46 | { type: 'harness.snapshot' }
47​
48/** Host to client. */
49export type HostFrame =
50 | { type: 'harness.hello'; v: number; threadId: string }
51 | {
52 type: 'harness.receipt'
53 requestId: string
54 status: Receipt['status']
55 inputId?: string
56 operationId?: string
57 reason?: string
58 }
59 | {
60 type: 'harness.event'
61 cursor: Cursor
62 /** The thread of the event: the thread, or a child thread of its tree. */
63 threadId: string
64 operationId: string
65 event: StreamChunk
66 }
67 | { type: 'harness.snapshot'; snapshot: SessionSnapshot }
68 | {
69 type: 'harness.error'
70 /** A short reason, for people. Read `code` in code. */
71 message: string
72 code: HarnessErrorCode
73 /**
74 * The `requestId` of the frame or the request that failed. A frame or
75 * a request with no id gets an id from the server.
76 */
77 requestId: string
78 }
79 /** A heartbeat. It keeps idle connections open. Ignore it. */
80 | { type: 'harness.ping' }
81​
82const INPUT_OPS = new Set([
83 'prompt',
84 'steer',
85 'followUp',
86 'continue',
87 'resolve',
88 'agent',
89 'cancel',
90 'background',
91 'cancelInput',
92 'setDelivery',
93 'command',
94 'answer',
95 'config',
96 'tool',
97 'append',
98 'configure',
99 'reset',
100 'revert',
101 'unrevert',
102 'agentMessage',
103])
104​
105const PART_TYPES = new Set(['text', 'image', 'audio', 'video', 'document'])
106​
107/**
108 * True for a content part with the fields the harness reads: a string
109 * `content` for text, else a `source` with a string `type` and `value`, and
110 * a string `mimeType` for a `data` source.
111 */
112function isContentPart(value: unknown) {
113 if (!isRecord(value) || typeof value.type !== 'string') return false
114 if (!PART_TYPES.has(value.type)) return false
115 if (value.type === 'text') return typeof value.content === 'string'
116 const { source } = value
117 if (!isRecord(source) || typeof source.type !== 'string') return false
118 if (typeof source.value !== 'string') return false
119 return source.type !== 'data' || typeof source.mimeType === 'string'
121​
122/** True for a string, or an array of content parts. */
123function isMessageContent(value: unknown) {
124 return (
125 typeof value === 'string' ||
126 (Array.isArray(value) && value.every(isContentPart))
127 )
129​
130/** Check the shape of a client input. Throws with a short reason. */
131export function parseHarnessInput(value: unknown): HarnessInput {
132 if (
133 !isRecord(value) ||
134 typeof value.op !== 'string' ||
135 !INPUT_OPS.has(value.op)
136 ) {
137 throw new Error('Invalid input: expected { op } with a known op.')
138 }
139 const needsMessage =
140 value.op === 'prompt' ||
141 value.op === 'steer' ||
142 value.op === 'followUp' ||
143 value.op === 'agentMessage'
144 if (needsMessage && !isMessageContent(value.message)) {
145 throw new Error(
146 `Invalid input: ${value.op} needs a message: text, or content parts.`,
147 )
148 }
149 if (
150 value.op === 'prompt' &&
151 value.as !== undefined &&
152 value.as !== 'operator'
153 ) {
154 throw new Error("Invalid input: the as of prompt must be 'operator'.")
155 }
156 if (value.op === 'resolve' && !Array.isArray(value.resume)) {
157 throw new Error('Invalid input: resolve needs a resume array.')
158 }
159 if (value.op === 'agent' && typeof value.agent !== 'string') {
160 throw new Error('Invalid input: agent needs an agent name.')
161 }
162 if (value.op === 'agentMessage' && typeof value.operationId !== 'string') {
163 throw new Error('Invalid input: agentMessage needs an operationId.')
164 }
165 if (
166 value.op === 'agentMessage' &&
167 value.mode !== undefined &&
168 value.mode !== 'steer' &&
169 value.mode !== 'followUp'
170 ) {
171 throw new Error(
172 "Invalid input: the mode of agentMessage must be 'steer' or 'followUp'.",
173 )
174 }
175 if (value.op === 'command' && typeof value.name !== 'string') {
176 throw new Error('Invalid input: command needs a name.')
177 }
178 if (value.op === 'answer' && typeof value.questionId !== 'string') {
179 throw new Error('Invalid input: answer needs a questionId.')
180 }
181 if (value.op === 'config' && typeof value.key !== 'string') {
182 throw new Error('Invalid input: config needs a key.')
183 }
184 if (value.op === 'tool' && typeof value.name !== 'string') {
185 throw new Error('Invalid input: tool needs a name.')
186 }
187 const isRecords =
188 Array.isArray(value.records) &&
189 value.records.length > 0 &&
190 value.records.every(
191 (record) => isRecord(record) && typeof record.type === 'string',
192 )
193 if (value.op === 'append' && !isRecords) {
194 throw new Error(
195 'Invalid input: append needs records, each with a string type.',
196 )
197 }
198 const namesInput = value.op === 'cancelInput' || value.op === 'setDelivery'
199 if (namesInput && typeof value.inputId !== 'string') {
200 throw new Error(`Invalid input: ${value.op} needs an inputId.`)
201 }
202 const isDelivery = value.delivery === 'steer' || value.delivery === 'queue'
203 if (value.op === 'setDelivery' && !isDelivery) {
204 throw new Error("Invalid input: setDelivery needs 'steer' or 'queue'.")
205 }
206 // The session checks each field, and answers a bad one with a receipt.
207 if (value.op === 'configure' && !isRecord(value.settings)) {
208 throw new Error('Invalid input: configure needs a settings object.')
209 }
210 if (
211 value.op === 'reset' &&
212 value.note !== undefined &&
213 typeof value.note !== 'string'
214 ) {
215 throw new Error('Invalid input: the note of reset must be a string.')
216 }
217 if (value.op === 'revert' && typeof value.messageId !== 'string') {
218 throw new Error('Invalid input: revert needs a messageId.')
219 }
220 if (
221 value.op === 'background' &&
222 value.toolCallId !== undefined &&
223 typeof value.toolCallId !== 'string'
224 ) {
225 throw new Error(
226 'Invalid input: the toolCallId of background must be a string.',
227 )
228 }
229 if (value.inputId !== undefined && typeof value.inputId !== 'string') {
230 throw new Error('Invalid input: inputId must be a string.')
231 }
232 // A client sends user messages only. An assistant or tool message from a
233 // client could fake an answer or a tool result in the model context.
234 const isUserMessage = (message: unknown) =>
235 isRecord(message) &&
236 message.role === 'user' &&
237 (message.content === null || isMessageContent(message.content))
238 if (
239 (value.op === 'prompt' || value.op === 'continue') &&
240 value.ephemeral !== undefined &&
241 !(Array.isArray(value.ephemeral) && value.ephemeral.every(isUserMessage))
242 ) {
243 throw new Error(
244 'Invalid input: ephemeral must be an array of user messages.',
245 )
246 }
247 // Only the harness marks a wake follow-up. A client cannot.
248 if (value.op === 'followUp' && 'wake' in value) {
249 const { wake: _wake, ...input } = value
250 return input as HarnessInput
251 }
252 // The checks above cover every field the session reads.
253 return value as HarnessInput
255​
256/** Parse one text frame from a client. Throws with a short reason. */
257export function parseControlFrame(data: string): ControlFrame {
258 const value: unknown = JSON.parse(data)
259 if (!isRecord(value)) throw new Error('Invalid frame.')
260 if (
261 value.type === 'harness.subscribe' &&
262 typeof value.threadId === 'string'
263 ) {
264 if (value.v !== undefined && typeof value.v !== 'number') {
265 throw new Error('Invalid frame: v must be a number.')
266 }
267 return {
268 type: 'harness.subscribe',
269 threadId: value.threadId,
270 ...(typeof value.from === 'string' ? { from: value.from } : {}),
271 ...(value.v === undefined ? {} : { v: value.v }),
272 }
273 }
274 if (value.type === 'harness.input' && typeof value.requestId === 'string') {
275 return {
276 type: 'harness.input',
277 requestId: value.requestId,
278 input: parseHarnessInput(value.input),
279 // As the W3C rules say, an invalid `traceparent` is dropped.
280 ...(typeof value.traceparent === 'string' &&
281 parseTraceparent(value.traceparent)
282 ? { traceparent: value.traceparent }
283 : {}),
284 }
285 }
286 if (value.type === 'harness.snapshot') return { type: 'harness.snapshot' }
287 throw new Error('Invalid frame: unknown type.')
289​
290/**
291 * Apply a client input to a session. A client can run, or send messages to,
292 * only the agents in `expose.agents`. It can run only the commands in
293 * `expose.commands` and the tools in `expose.tools`, and change only the
294 * settings in `expose.settings` and the config keys in `expose.config`.
295 * Resolves to the receipt. `user` is who sent the input, from the
296 * login of the request, never from the input itself. A chat input runs with
297 * its credentials. Rejects with `AccessDeniedError` when the host refuses
298 * the input.
299 *
300 * Media in a message, or in an `ephemeral` message, is checked first, as
301 * `storeInlineMedia` does: inline bytes go to the media store and the part
302 * becomes a `harness-media:` reference. An external URL needs
303 * `media.externalUrls`. A refused part gives a rejected receipt with the
304 * reason, for example `media_too_large`. An input with an `inputId` that the
305 * session has already sends the stored message again, so a retry stores no
306 * media.
307 *
308 * @example
309 * ```ts
310 * const receipt = await applyInput({ harness, session, input, user })
311 * ```
312 */
313export async function applyInput({
314 harness,
315 session,
316 input,
317 user,
318 traceparent,
319}: {
320 harness: AnyHarness
321 session: HarnessSession
322 input: HarnessInput
323 user?: HarnessUser
324 /** A W3C `traceparent` of the caller, for a message to the session. */
325 traceparent?: string
326}): Promise<Receipt> {
327 // The log keeps who sent each input, for every input kind.
328 const asUser = user ? { user } : {}
329 const traced = traceparent === undefined ? {} : { traceparent }
330 const id = {
331 ...(input.inputId === undefined ? {} : { inputId: input.inputId }),
332 ...asUser,
333 }
334 const sent = {
335 ...id,
336 ...('context' in input && input.context !== undefined
337 ? { context: input.context }
338 : {}),
339 }
340 const notExposed: Receipt = {
341 inputId: input.inputId ?? '',
342 status: 'rejected',
343 reason: 'not_exposed',
344 }
345 const refused = (reason: string) => {
346 const receipt: Receipt = {
347 inputId: input.inputId ?? '',
348 status: 'rejected',
349 reason,
350 }
351 return receipt
352 }
353 const media: InlineMediaContext = {
354 options: harness.media,
355 putMedia: (upload) => session.putMedia(upload),
356 }
357 /** `message` with its inline media stored. A retry stores none again. */
358 const checkedMessage = async (message: UserInput) => {
359 const retry = retriedMessage(session, input.inputId, message)
360 if (retry !== undefined) return { content: retry, isRetry: true }
361 if (typeof message === 'string') return { content: message }
362 const checked = await storeInlineMedia(message, media)
363 return 'refused' in checked ? checked : { content: checked.parts }
364 }
365 switch (input.op) {
366 case 'prompt': {
367 const message = await checkedMessage(input.message)
368 if ('refused' in message) return refused(message.refused)
369 // A retry drops its ephemeral messages, as `session.send` does.
370 const ephemeral = message.isRetry
371 ? { options: {} }
372 : await checkedEphemeral(input.ephemeral, media)
373 if ('refused' in ephemeral) return refused(ephemeral.refused)
374 return turnReceipt(
375 session.send(message.content, {
376 ...(input.busy ? { busy: input.busy } : {}),
377 ...ephemeral.options,
378 // The host checks the `operator` action of the sender.
379 ...(input.as ? { as: input.as } : {}),
380 ...sent,
381 ...traced,
382 }),
383 )
384 }
385 case 'continue': {
386 const ephemeral = await checkedEphemeral(input.ephemeral, media)
387 if ('refused' in ephemeral) return refused(ephemeral.refused)
388 return turnReceipt(
389 session.continueWithoutMessage({ ...ephemeral.options, ...sent }),
390 )
391 }
392 case 'steer':
393 case 'followUp': {
394 const message = await checkedMessage(input.message)
395 if ('refused' in message) return refused(message.refused)
396 return turnReceipt(
397 session.send(message.content, { ...sent, ...traced, mode: input.op }),
398 )
399 }
400 case 'resolve':
401 return session.resolve({ resume: input.resume, ...id })
402 case 'cancel':
403 return session.cancel({ operationId: input.operationId, ...asUser })
404 // It runs no new code, so it needs no `expose` entry, like `cancel`. It
405 // stores no input, so there is no sender to keep.
406 case 'background':
407 return session.moveToolCallToBackground(
408 input.toolCallId !== undefined ? { toolCallId: input.toolCallId } : {},
409 )
410 case 'cancelInput':
411 return session.cancelInput({ inputId: input.inputId, ...asUser })
412 case 'setDelivery':
413 return session.changeInputDelivery({
414 inputId: input.inputId,
415 delivery: input.delivery,
416 ...asUser,
417 })
418 case 'command': {
419 // A command can change the session, for example `/mode bypass`.
420 if (!(harness.expose?.commands ?? []).includes(input.name)) {
421 return notExposed
422 }
423 // The client's id makes a resent command a duplicate, so it runs once.
424 const inputId = input.inputId ?? createInputId()
425 const operation = session.runCommand({
426 name: input.name,
427 input: input.input,
428 inputId,
429 ...asUser,
430 })
431 // ponytail: a command has no receipt, so it is accepted at once. A
432 // command that the host refuses fails with a `RUN_ERROR` event.
433 operation.then(
434 () => {},
435 () => {},
436 )
437 return { inputId, status: 'accepted', operationId: operation.id }
438 }
439 case 'answer':
440 return session.answer({
441 questionId: input.questionId,
442 value: input.value,
443 ...asUser,
444 })
445 case 'config':
446 if (!(harness.expose?.config ?? []).includes(input.key)) {
447 return notExposed
448 }
449 return session.setPluginSetting({
450 key: input.key,
451 value: input.value,
452 ...asUser,
453 })
454 case 'tool': {
455 if (!(harness.expose?.tools ?? []).includes(input.name)) {
456 return notExposed
457 }
458 return turnReceipt(
459 session.runTool({
460 name: input.name,
461 args: input.args,
462 ...(input.meta ? { meta: input.meta } : {}),
463 ...id,
464 }),
465 )
466 }
467 case 'append': {
468 // A client adds only the exposed types, and only to this thread.
469 const types: ReadonlyArray<string> = harness.expose?.records ?? []
470 const isExposed = input.records.every(
471 (record) => types.includes(record.type) && !('thread' in record),
472 )
473 if (!isExposed) return notExposed
474 // The client's id makes a resent append a duplicate that writes
475 // nothing.
476 try {
477 return await session.appendRecords({
478 records: input.records,
479 ...(input.inputId !== undefined ? { inputId: input.inputId } : {}),
480 ...asUser,
481 })
482 } catch (error) {
483 const inputId = input.inputId ?? createInputId()
484 return { inputId, status: 'rejected', reason: errorText(error) }
485 }
486 }
487 case 'configure': {
488 // A client changes only the settings the harness exposes.
489 const exposed: ReadonlyArray<string> = harness.expose?.settings ?? []
490 const isExposed = Object.keys(input.settings).every((key) =>
491 exposed.includes(key),
492 )
493 if (!isExposed) return notExposed
494 return session.updateThreadSettings({ settings: input.settings, ...id })
495 }
496 case 'reset':
497 return session.reset({ note: input.note, ...id })
498 // A revert puts files back, as `/undo` does.
499 case 'revert':
500 case 'unrevert':
501 if (!(harness.expose?.commands ?? []).includes('undo')) return notExposed
502 return input.op === 'revert'
503 ? session.revert({ messageId: input.messageId })
504 : session.unrevert()
505 case 'agent': {
506 const exposed = (harness.expose?.agents ?? []).includes(input.agent)
507 if (!exposed) {
508 return { inputId: '', status: 'rejected', reason: 'not_exposed' }
509 }
510 const handle = session.agent(input.agent)
511 if (!handle) {
512 return { inputId: '', status: 'rejected', reason: 'unknown_agent' }
513 }
514 // The run is the client's: its credentials and keys are theirs.
515 // ponytail: accepted at once, as a command. A run that the host
516 // refuses fails with a `RUN_ERROR` event.
517 // The client's id makes a resent start a duplicate, so the agent runs
518 // once.
519 const inputId = input.inputId ?? createInputId()
520 const options: AgentRunStartOptions = {
521 startTurnWhenDone: input.detached === true,
522 inputId,
523 ...asUser,
524 }
525 const operation = handle.start(input.input, options)
526 return { inputId, status: 'accepted', operationId: operation.id }
527 }
528 case 'agentMessage': {
529 const run = session.agentRun(input.operationId)
530 if (!run) {
531 return {
532 inputId: input.inputId ?? '',
533 status: 'rejected',
534 reason: 'not_running',
535 }
536 }
537 // Only a run of an exposed agent takes messages from a client.
538 const exposed: ReadonlyArray<string> = harness.expose?.agents ?? []
539 if (!exposed.includes(run.agent ?? '')) {
540 return {
541 inputId: input.inputId ?? '',
542 status: 'rejected',
543 reason: 'not_exposed',
544 }
545 }
546 const message = await checkedMessage(input.message)
547 if ('refused' in message) return refused(message.refused)
548 return turnReceipt(
549 session.send(message.content, {
550 to: input.operationId,
551 ...id,
552 ...(input.mode ? { mode: input.mode } : {}),
553 }),
554 )
555 }
556 }
558​
559/**
560 * `message` as a retry of the input `inputId` that `session` has in its log,
561 * or `undefined` for a new input. A part at the place of a stored
562 * `harness-media:` part, of the same type, becomes the stored part. So a
563 * retry stores no media again, and the duplicate check of the session
564 * matches. A retry that differs in another way gets `conflict`. Its parts are
565 * not checked or stored: the session refuses it before it runs.
566 */
567// ponytail: a retry with other inline bytes of the same type matches too.
568// The first input stands.
569export function retriedMessage(
570 session: HarnessSession,
571 inputId: string | undefined,
572 message: UserInput,
573): UserInput | undefined {
574 if (inputId === undefined || !(session instanceof SessionImpl)) {
575 return undefined
576 }
577 const known = session.knownMessage(inputId)
578 if (known === undefined) return undefined
579 if (typeof message === 'string' || typeof known === 'string') return message
580 return message.map((part, index) => {
581 const stored = known[index]
582 const isStoredMedia =
583 stored?.type === part.type && mediaIdOf(stored) !== undefined
584 return isStoredMedia ? stored : part
585 })
587​
588/**
589 * The `ephemeral` option of a turn, with the inline media of each message
590 * stored, or why a part was refused. No messages give no option.
591 */
592async function checkedEphemeral(
593 messages: ReadonlyArray<ModelMessage & { role: 'user' }> | undefined,
594 media: InlineMediaContext,
595) {
596 if (!messages) return { options: {} }
597 const ephemeral: Array<ModelMessage & { role: 'user' }> = []
598 for (const message of messages) {
599 if (!Array.isArray(message.content)) {
600 ephemeral.push(message)
601 continue
602 }
603 const checked = await storeInlineMedia(message.content, media)
604 if ('refused' in checked) return checked
605 ephemeral.push({ ...message, content: checked.parts })
606 }
607 return { options: { ephemeral } }
609​
610/**
611 * The receipt of a turn that a client started. Nobody may await the turn,
612 * so its failure is handled here. A turn that the host refused throws its
613 * `AccessDeniedError`, as the other inputs do, so a transport answers 403.
614 */
615export async function turnReceipt(operation: Operation<unknown>) {
616 const failure = operation.then(
617 () => undefined,
618 (error: unknown) => error,
619 )
620 const receipt = await operation.receipt
621 if (receipt.status !== 'rejected') return receipt
622 // A refused input fails its operation at once.
623 const error = await failure
624 if (error instanceof AccessDeniedError) throw error
625 return receipt
627​
628/**
629 * What `describe` sends a client: only the commands in `expose.commands` and
630 * the config keys in `expose.config`, so a UI shows only what `applyInput`
631 * lets through. Server code reads the full `session.describe()`.
632 */
633export function describeForClient(
634 harness: AnyHarness,
635 session: HarnessSession,
636) {
637 const description = session.describe()
638 const commands: ReadonlyArray<string> = harness.expose?.commands ?? []
639 const config: ReadonlyArray<string> = harness.expose?.config ?? []
640 return {
641 ...description,
642 commands: description.commands.filter(({ name }) =>
643 commands.includes(name),
644 ),
645 config: description.config.filter(({ key }) => config.includes(key)),
646 }
648​
649/**
650 * The AG-UI capabilities document of a harness. Pass `socket: true` when the
651 * app also serves `handleHarnessSocket`, so `transport.websocket` tells
652 * clients that they can use a WebSocket. Default `false`.
653 *
654 * @example
655 * ```ts
656 * const capabilities = capabilitiesOf(assistant, { socket: true })
657 * ```
658 */
659export function capabilitiesOf(
660 harness: AnyHarness,
661 { socket = false }: { socket?: boolean } = {},
662) {
663 const exposed = new Set<string>(harness.expose?.agents ?? [])
664 const subagents: ReadonlyArray<AnyAgent> = harness.subagents?.agents ?? []
665 const agents: ReadonlyArray<AnyAgent> = [
666 ...(harness.agents ?? []),
667 ...subagents,
668 ]
669 return {
670 identity: { name: harness.name, type: 'tanstack-ai-harness' },
671 transport: { streaming: true, websocket: socket },
672 tools: {
673 supported: true,
674 items: (harness.tools ?? []).map((tool) => ({
675 name: tool.name,
676 description: tool.description,
677 exposed: (harness.expose?.tools ?? []).includes(tool.name),
678 })),
679 },
680 multiAgent: {
681 supported: agents.length > 0,
682 subagents: subagents.map((agent) => ({
683 name: agent.name,
684 description: agent.description,
685 })),
686 },
687 humanInTheLoop: { supported: true, interrupts: true },
688 custom: {
689 tanstack: {
690 protocol: HARNESS_PROTOCOL_VERSION,
691 agents: agents
692 .filter((agent) => exposed.has(agent.name))
693 .map((agent) => ({
694 name: agent.name,
695 description: agent.description,
696 ...(agent.produces ? { produces: agent.produces } : {}),
697 ...(agent.inputSchema
698 ? { inputSchema: convertSchemaToJsonSchema(agent.inputSchema) }
699 : {}),
700 })),
701 },
702 },
703 }
705​
706/**
707 * The `unsupported_version` error of a `harness.subscribe` frame or a
708 * `?v=` query that asks for a version other than
709 * {@link HARNESS_PROTOCOL_VERSION}. No version asks for the current one.
710 * Send the error frame, then close the stream.
711 */
712export function versionError(requested: number | undefined) {
713 if (requested === undefined || requested === HARNESS_PROTOCOL_VERSION) {
714 return undefined
715 }
716 return {
717 message: `Protocol version ${requested} is not supported. This host speaks version ${HARNESS_PROTOCOL_VERSION}.`,
718 code: 'unsupported_version' as const,
719 }
721​
722/**
723 * The `requestId` of the raw text of a client frame, or `undefined`. It
724 * reads only that field, so the error frame of a frame that fails the full
725 * parse (for example, with a bad `input`) still names its request. It never
726 * throws.
727 */
728export function requestIdOf(data: string): string | undefined {
729 try {
730 const value: unknown = JSON.parse(data)
731 return isRecord(value) && typeof value.requestId === 'string'
732 ? value.requestId
733 : undefined
734 } catch {
735 return undefined
736 }