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

client.ts

1,066 lines36.8 KB

1// Browser-safe: this module has type-only imports from the rest of the
2// package, plus `media-ref`, `utils`, and `types`, which have no runtime
3// imports themselves. So no server code (adapters, stores, secrets) reaches a
4// client.
5import { isMediaRecord } from './media-ref'
6import { isRecord } from './utils'
7import type { ModelMessage } from '@tanstack/ai'
8import type {
9 LogRecord,
10 SessionIndexEntry,
11 SessionIndexPage,
12 SessionMember,
13} from '@tanstack/ai-persistence'
14import type { AgentInputOf } from './agents'
15import type {
16 AnyHarness,
17 HarnessAgentsOf,
18 HarnessToolInput,
19 HarnessToolsOf,
20 SessionMetadataOf,
21} from './define'
22import type { HostEvent } from './host'
23import type { HarnessErrorCode } from './protocol'
24import type { SessionDescription, SessionSnapshot } from './session/index'
25import type { SessionEntryChange } from './session-entry'
26import type {
27 BusyPolicy,
28 CancelOptions,
29 CommandOptions,
30 ConfigureOptions,
31 Cursor,
32 ForkPoint,
33 HarnessInput,
34 MediaRecord,
35 MediaUpload,
36 Receipt,
37 ResetOptions,
38 ResolveOptions,
39 SessionEvent,
40 UserInput,
41 WaitingInput,
42} from './types'
43​
44export {
45 MEDIA_URL_PREFIX,
46 kindOf,
47 mediaIdOf,
48 mediaOfMessage,
49 mediaPart,
50} from './media-ref'
51export { HARNESS_EVENTS } from './types'
52export type { ForkPoint, MediaKind, MediaRecord } from './types'
53export type { HarnessErrorCode } from './protocol'
54export type {
55 HostEvent,
56 HostSessionDeletedEvent,
57 HostSessionEvent,
58 HostStatusEvent,
59} from './host'
60​
61/**
62 * A `harness.error` frame that ended a stream of the client: `code` says
63 * what failed. `events()` and `hostEvents()` throw it. A `slow_consumer`
64 * error is not thrown: they connect again.
65 */
66export class HarnessProtocolError extends Error {
67 readonly code: HarnessErrorCode
68 constructor(code: HarnessErrorCode, message: string) {
69 super(message)
70 this.name = 'HarnessProtocolError'
71 this.code = code
72 }
74​
75/**
76 * The error of a `harness.error` frame. Undefined for another frame and
77 * for `slow_consumer`: the stream ends, and the client connects again.
78 */
79function protocolErrorOf(frame: unknown): HarnessProtocolError | undefined {
80 if (!isRecord(frame) || frame.type !== 'harness.error') return undefined
81 if (frame.code === 'slow_consumer') return undefined
82 const code =
83 typeof frame.code === 'string'
84 ? (frame.code as HarnessErrorCode)
85 : 'internal'
86 const message =
87 typeof frame.message === 'string' ? frame.message : 'Harness stream failed'
88 return new HarnessProtocolError(code, message)
90​
91export interface HarnessClientOptions {
92 /** The base URL of `createHarnessHandler`, for example `/api/harness`. */
93 url: string
94 threadId: string
95 /** Extra headers, for example `Authorization`. */
96 headers?: Record<string, string> | (() => Record<string, string>)
97 fetch?: typeof fetch
98 /**
99 * The first wait before a reconnect of `events()`. Default 1000 ms. Each
100 * failed try after it doubles the wait, up to 30 s, with a random part.
101 * A read from the server sets the wait back to this value.
102 */
103 reconnectDelayMs?: number
104 /**
105 * A connection of `events()` that gets no bytes for this long is dead,
106 * for example after a laptop sleeps or a NAT drops the mapping. The
107 * client closes it and connects again from its last cursor. Default
108 * 60 000 ms. Keep it larger than the `stream.heartbeatMs` of the server
109 * (default 20 000 ms), or the client reconnects in a loop.
110 */
111 idleTimeoutMs?: number
113​
114type StartArgs<TAgent> =
115 AgentInputOf<TAgent> extends undefined
116 ? [input?: undefined, options?: { detached?: boolean }]
117 : [input: AgentInputOf<TAgent>, options?: { detached?: boolean }]
118​
119/** `client.agents`: start an exposed agent, typed from the harness. */
120export type ClientAgentHandles<THarness> = {
121 [TAgent in HarnessAgentsOf<THarness> as TAgent['name']]: {
122 start: (...args: StartArgs<TAgent>) => Promise<Receipt>
123 }
125​
126/** The options of `HarnessClient.send`. */
127export type ClientSendOptions = {
128 inputId?: string
129 /**
130 * A W3C `traceparent` of the caller, sent as the `traceparent` header.
131 * The span of the turn on the server links it.
132 */
133 traceparent?: string
134} & (
135 | {
136 to?: undefined
137 mode?: 'prompt'
138 busy?: BusyPolicy
139 ephemeral?: ReadonlyArray<ModelMessage & { role: 'user' }>
140 /** `'operator'`: an operator reply. See `SendOptions.as`. */
141 as?: 'operator'
142 }
143 | {
144 to?: undefined
145 mode: 'steer' | 'followUp'
146 busy?: never
147 ephemeral?: never
148 as?: never
149 }
150 | {
151 to: string
152 mode?: 'steer' | 'followUp'
153 busy?: never
154 ephemeral?: never
155 as?: never
156 }
158​
159export interface HarnessClient<THarness extends AnyHarness> {
160 /**
161 * Send a message, as `session.send` does. `mode` is `'prompt'` (default),
162 * `'steer'` (join the running turn), or `'followUp'` (run after the
163 * current work). `to` sends it to an agent run; the harness must list the
164 * run's agent in `expose.agents`. `inputId` is an id you choose: a retry
165 * with the same id and message gets the first receipt and does not run
166 * again. `ephemeral` are messages for the model calls of a prompt only.
167 * `as: 'operator'` is the reply of an operator while a handoff to a
168 * person is open: no model runs. The sender needs the `operator` action.
169 */
170 send: (message: UserInput, options?: ClientSendOptions) => Promise<Receipt>
171 /**
172 * Start a turn from the stored transcript, with no new message. See
173 * `session.continueWithoutMessage`.
174 */
175 continueWithoutMessage: (options?: {
176 inputId?: string
177 ephemeral?: ReadonlyArray<ModelMessage & { role: 'user' }>
178 }) => Promise<Receipt>
179 /**
180 * Answer the waits of `snapshot().pendingWaits` that have an
181 * `interrupt`, as `session.resolve` does. The waits of the last turn (the
182 * approvals, the `question` tool calls, the client tools, and the
183 * sign-ins) go in one resume. A wait of a background agent run takes a
184 * resolve of its own. A wait with no interrupt takes `answer`.
185 *
186 * @example
187 * ```ts
188 * await client.resolve({ resume: [{ interruptId, status: 'resolved' }] })
189 * ```
190 */
191 resolve: (options: ResolveOptions) => Promise<Receipt>
192 /**
193 * Stop the operation `operationId`, or the running turn without it, as
194 * `session.cancel` does.
195 *
196 * @example
197 * ```ts
198 * await client.cancel({ operationId })
199 * ```
200 */
201 cancel: (options?: CancelOptions) => Promise<Receipt>
202 /**
203 * Cancel an input that waits (see `snapshot().waitingInputs`). An input
204 * that started is refused with `not_waiting`: use `cancel`.
205 *
206 * @example
207 * ```ts
208 * await client.cancelInput({ inputId })
209 * ```
210 */
211 cancelInput: (options: { inputId: string }) => Promise<Receipt>
212 /**
213 * Move an input that waits: `'steer'` joins the running turn, `'queue'`
214 * runs it as its own turn later.
215 */
216 changeInputDelivery: (change: {
217 inputId: string
218 delivery: WaitingInput['delivery']
219 }) => Promise<Receipt>
220 agents: ClientAgentHandles<THarness>
221 /**
222 * Answer a wait of `snapshot().pendingWaits` that no turn holds, as
223 * `session.answer` does: a `step.ask` wait of a command, a durable tool,
224 * or an agent run, an MCP question, or a `human` wait. The waits of the
225 * stopped turn take `resolve`.
226 */
227 answer: (answer: { questionId: string; value: unknown }) => Promise<Receipt>
228 /**
229 * Run the plugin command `name`. Its result arrives as a
230 * `harness.command.result` event.
231 *
232 * @example
233 * ```ts
234 * await client.runCommand({ name: 'mode', input: 'plan' })
235 * ```
236 */
237 runCommand: (options: CommandOptions) => Promise<Receipt>
238 /**
239 * Run a harness tool with no model turn, as `session.runTool` does. The
240 * harness must list it in `expose.tools`. `args` is typed from the
241 * tool's input schema.
242 *
243 * @example
244 * ```ts
245 * await client.runTool({ name: 'sync_inbox', args: { folder: 'INBOX' } })
246 * ```
247 */
248 runTool: <TName extends HarnessToolsOf<THarness>['name']>(options: {
249 name: TName
250 args?: HarnessToolInput<THarness, TName>
251 meta?: Record<string, unknown>
252 inputId?: string
253 }) => Promise<Receipt>
254 /**
255 * Add host records to the session log, as `session.appendRecords` does. The
256 * harness must list each record type in `expose.records`. With `inputId`,
257 * a second append with the same id is a duplicate and writes nothing.
258 *
259 * @example
260 * ```ts
261 * await client.appendRecords({ records: [{ type: 'app.signal', text: 'Saved.' }] })
262 * ```
263 */
264 appendRecords: (options: {
265 records: ReadonlyArray<LogRecord>
266 inputId?: string
267 }) => Promise<Receipt>
268 /** Change a session setting. */
269 setPluginSetting: (change: {
270 key: string
271 value: unknown
272 }) => Promise<Receipt>
273 /**
274 * Change the stored settings of the thread. See `session.updateThreadSettings`.
275 *
276 * @example
277 * ```ts
278 * await client.updateThreadSettings({ settings: { model: 'strong' } })
279 * ```
280 */
281 updateThreadSettings: (options: ConfigureOptions) => Promise<Receipt>
282 /**
283 * Start a fresh model context from the next turn. The model sees `note`
284 * first, when you give one. The transcript keeps every message.
285 *
286 * @example
287 * ```ts
288 * await client.reset({ note: 'The user wants a new plan.' })
289 * ```
290 */
291 reset: (options?: ResetOptions) => Promise<Receipt>
292 /**
293 * Go back to the message `messageId`, as `session.revert` does. The
294 * harness must list `'undo'` in `expose.commands`.
295 *
296 * @example
297 * ```ts
298 * await client.revert({ messageId })
299 * ```
300 */
301 revert: (options: { messageId: string }) => Promise<Receipt>
302 /** End the revert that stands, as `session.unrevert` does. */
303 unrevert: () => Promise<Receipt>
304 /**
305 * The session events from `from` (exclusive). Without `from`, the events
306 * start at the cursor of the snapshot: only new events come. Pass
307 * `from: '0'` to read the events from the start. Reconnects after a network
308 * error and resumes from the last cursor. Ends when `signal` aborts.
309 * `onConnection` reports `'open'` for each connection and `'reconnecting'`
310 * before each new try. When the log dropped the events after `from`, the
311 * first event is a `harness.gap` (`HARNESS_EVENTS.gap`): load the snapshot
312 * and the transcript again. A session view does this itself.
313 */
314 events: (options?: {
315 from?: Cursor
316 signal?: AbortSignal
317 onConnection?: (state: 'open' | 'reconnecting') => void
318 }) => AsyncIterable<SessionEvent>
319 /**
320 * The status changes and the session changes of all your sessions on the
321 * server (`host.events()`). First the current status of each open session.
322 * It ends when `signal` aborts or the server closes the stream. Call it
323 * again to reconnect: the current statuses come first again.
324 */
325 hostEvents: (options?: { signal?: AbortSignal }) => AsyncIterable<HostEvent>
326 snapshot: () => Promise<SessionSnapshot>
327 /** The saved messages of the thread. */
328 transcript: () => Promise<Array<ModelMessage>>
329 /**
330 * The saved messages of a child agent run of the thread, by its
331 * `subagentRunId` or by its `runId`. Empty for an unknown id. A child with
332 * no messages has one message with no content, with its card. See
333 * `session.agentTranscript`.
334 *
335 * @example
336 * ```ts
337 * const messages = await client.agentTranscript({ subagentRunId })
338 * ```
339 */
340 agentTranscript: (
341 run: { subagentRunId: string } | { runId: string },
342 ) => Promise<Array<ModelMessage>>
343 /**
344 * The commands, settings, and tools of the session. Only the commands in
345 * `expose.commands` and the config keys in `expose.config`.
346 */
347 describe: () => Promise<SessionDescription>
348 /**
349 * Store a file in the media store of the thread. Send the record in a
350 * prompt with `mediaPart(record)`. Throws when the handler refuses the
351 * file, for example `413` for a file over the size limit.
352 *
353 * @example
354 * ```ts
355 * const record = await client.putMedia({ body: file, mimeType: file.type, name: file.name })
356 * ```
357 */
358 putMedia: (
359 file: MediaUpload<Blob | ArrayBuffer | Uint8Array>,
360 ) => Promise<MediaRecord>
361 /**
362 * A signed URL for a media file, for `<img>`, `<audio>`, or `<video>`. It
363 * stops working at `expiresAt` (epoch milliseconds). Ask again for a new one.
364 *
365 * @example
366 * ```ts
367 * const { url } = await client.mediaUrl({ id: record.id })
368 * ```
369 */
370 mediaUrl: (options: {
371 id: string
372 }) => Promise<{ url?: string; expiresAt?: number }>
373 /**
374 * The bytes of the media file `id`.
375 *
376 * @example
377 * ```ts
378 * const bytes = await client.loadMedia({ id: record.id })
379 * ```
380 */
381 loadMedia: (options: { id: string }) => Promise<Uint8Array>
382 /**
383 * Your sessions on the server, as `host.sessions` has them for the
384 * user of the request.
385 *
386 * @example
387 * ```ts
388 * const page = await client.sessions.list({ limit: 20 })
389 * await client.sessions.rename({ threadId: 't-1', title: 'Trip plan' })
390 * await client.sessions.delete({ threadId: 't-1' })
391 * ```
392 */
393 sessions: HarnessClientSessions<THarness>
395​
396/** The sessions of the user of a `HarnessClient`. See `client.sessions`. */
397export interface HarnessClientSessions<THarness extends AnyHarness> {
398 /**
399 * One page of your sessions, newest first. Default: top-level sessions.
400 * Pass `parentThreadId` to get the child sessions of a thread, and the
401 * `cursor` of a page to get the next page. `search` keeps the sessions
402 * whose title contains the text, without case. `metadata` keeps the
403 * sessions with each exact metadata value. Archived sessions are left out
404 * unless `withArchived` is `true`.
405 */
406 list: (options?: {
407 limit?: number
408 cursor?: string
409 parentThreadId?: string
410 search?: string
411 metadata?: Record<string, string>
412 withArchived?: boolean
413 }) => Promise<
414 Omit<SessionIndexPage, 'entries'> & {
415 entries: Array<SessionIndexEntry<SessionMetadataOf<THarness>>>
416 }
417 >
418 /** Set the title of one of your sessions. Resolves to the changed entry. */
419 rename: (change: {
420 threadId: string
421 title: string
422 }) => Promise<SessionIndexEntry<SessionMetadataOf<THarness>>>
423 /**
424 * Archive one of your sessions: `list` leaves it out unless you pass
425 * `withArchived: true`. Resolves to the changed entry.
426 */
427 archive: (options: {
428 threadId: string
429 }) => Promise<SessionIndexEntry<SessionMetadataOf<THarness>>>
430 /** Undo `archive` on one of your sessions. Resolves to the changed entry. */
431 unarchive: (options: {
432 threadId: string
433 }) => Promise<SessionIndexEntry<SessionMetadataOf<THarness>>>
434 /**
435 * Change the `title`, `pinned`, or `metadata` of one of your sessions, for
436 * example the context items a user pinned in the composer. Each field you
437 * pass besides `threadId` replaces the stored one. The harness `metadataSchema` checks
438 * `metadata` on the server. Resolves to the changed entry.
439 */
440 update: (
441 change: { threadId: string } & SessionEntryChange<
442 SessionMetadataOf<THarness>
443 >,
444 ) => Promise<SessionIndexEntry<SessionMetadataOf<THarness>>>
445 /**
446 * Remove one of your sessions from the session index. The transcript and
447 * the other data of the thread stay on the server.
448 */
449 delete: (options: { threadId: string }) => Promise<void>
450 /**
451 * Copy one of your sessions into a new session, up to a message id.
452 * Resolves to the entry of the new session.
453 */
454 fork: (options: {
455 threadId: string
456 at: ForkPoint
457 }) => Promise<SessionIndexEntry<SessionMetadataOf<THarness>>>
458 /**
459 * Add the user `userId` to the members of one of your sessions with
460 * `role`, or change the role of a member. The server needs
461 * `access.rules.members`, and you need the `share` action. Resolves to
462 * the changed entry.
463 */
464 share: (change: {
465 threadId: string
466 userId: string
467 role: SessionMember['role']
468 }) => Promise<SessionIndexEntry<SessionMetadataOf<THarness>>>
469 /**
470 * Remove the user `userId` from the members of one of your sessions. The
471 * streams of that user close. Resolves to the changed entry.
472 */
473 unshare: (change: {
474 threadId: string
475 userId: string
476 }) => Promise<SessionIndexEntry<SessionMetadataOf<THarness>>>
478​
479/** The body of `POST sessions`. */
480type SessionChange =
481 | { op: 'rename'; threadId: string; title: string }
482 | ({ op: 'update'; threadId: string } & SessionEntryChange<unknown>)
483 | { op: 'delete' | 'archive' | 'unarchive'; threadId: string }
484 | ({ op: 'fork'; threadId: string } & ForkPoint)
485 | {
486 op: 'share'
487 threadId: string
488 userId: string
489 role: SessionMember['role']
490 }
491 | { op: 'unshare'; threadId: string; userId: string }
492​
493/** The longest wait before a reconnect of `events()`. */
494const MAX_RECONNECT_DELAY_MS = 30_000
495​
496/**
497 * The default `idleTimeoutMs`: 3 times the default `stream.heartbeatMs` of
498 * the server, so a live connection always sends bytes before it.
499 */
500const IDLE_TIMEOUT_MS = 60_000
501​
502/**
503 * The wait before reconnect number `attempt` (0 is the first): `base`
504 * doubled for each attempt, up to 30 s. A random part takes up to half of
505 * it away, so many clients do not reconnect at the same time.
506 */
507function reconnectDelay(base: number, attempt: number) {
508 const full = Math.min(MAX_RECONNECT_DELAY_MS, base * 2 ** attempt)
509 return full / 2 + (full / 2) * Math.random()
511​
512/** Run `stop` when `signal` aborts. Returns the function that removes it. */
513function whenAborted(signal: AbortSignal | undefined, stop: () => void) {
514 if (!signal) return () => {}
515 signal.addEventListener('abort', stop, { once: true })
516 return () => signal.removeEventListener('abort', stop)
518​
519/** Stop the read of an SSE body. Some fetch shims ignore the signal then. */
520function cancelReader(
521 reader: ReadableStreamDefaultReader<Uint8Array> | undefined,
522) {
523 reader?.cancel().catch(() => {})
525​
526/**
527 * An SSE parser that reads a stream as the SSE spec does. Give it the text
528 * as it comes. It returns the `data` of each event that the text ends.
529 *
530 * - A line ends with CR, LF, or CRLF, also when a CRLF is split across two
531 * reads.
532 * - The `data` lines of one event are joined with `\n`. One space after the
533 * colon is not part of the value.
534 * - A line that starts with `:` is a comment.
535 * - Only the new text is read. The part after the last line end is kept.
536 */
537function sseParser() {
538 let line = ''
539 let data: string | undefined
540 // The last text ended with CR. An LF at the start of the next text ends
541 // the same line, so it is skipped.
542 let afterCr = false
543 const endLine = (text: string, events: Array<string>) => {
544 if (text === '') {
545 if (data !== undefined) events.push(data)
546 data = undefined
547 return
548 }
549 if (text.startsWith(':')) return
550 const colon = text.indexOf(':')
551 const field = colon < 0 ? text : text.slice(0, colon)
552 // The client reads only `data`. `id`, `event`, and `retry` are left out.
553 if (field !== 'data') return
554 const raw = colon < 0 ? '' : text.slice(colon + 1)
555 const value = raw.startsWith(' ') ? raw.slice(1) : raw
556 data = data === undefined ? value : `${data}\n${value}`
557 }
558 return (text: string) => {
559 const events: Array<string> = []
560 let start = afterCr && text.startsWith('\n') ? 1 : 0
561 afterCr = false
562 const ends = /\r\n|\r|\n/g
563 ends.lastIndex = start
564 let match = ends.exec(text)
565 while (match) {
566 endLine(line + text.slice(start, match.index), events)
567 line = ''
568 start = match.index + match[0].length
569 afterCr = match[0] === '\r' && start === text.length
570 match = ends.exec(text)
571 }
572 line += text.slice(start)
573 return events
574 }
576​
577/**
578 * The `data` of each event of an SSE body, as parsed JSON. `onRead` runs
579 * for each chunk the server sends.
580 */
581async function* sseFrames(
582 reader: ReadableStreamDefaultReader<Uint8Array>,
583 onRead?: () => void,
584) {
585 const decoder = new TextDecoder()
586 const parse = sseParser()
587 try {
588 while (true) {
589 const { value, done } = await reader.read()
590 if (done) return
591 onRead?.()
592 const events = parse(decoder.decode(value, { stream: true }))
593 for (const data of events) {
594 // An event with an empty `data` has no frame.
595 if (data === '') continue
596 const frame: unknown = JSON.parse(data)
597 yield frame
598 }
599 }
600 } finally {
601 // A reader that stops early closes the connection, so the server stops.
602 cancelReader(reader)
603 }
605​
606// The answer of `GET media-url`: a signed path, relative to the base URL.
607function isSignedPath(
608 value: unknown,
609): value is { path: string; expiresAt: number } {
610 return (
611 typeof value === 'object' &&
612 value !== null &&
613 'path' in value &&
614 typeof value.path === 'string' &&
615 'expiresAt' in value &&
616 typeof value.expiresAt === 'number'
617 )
619​
620/**
621 * A client for a harness session served by `createHarnessHandler`. Pass the
622 * harness type for typed agents: `createHarnessClient<typeof studio>(...)`.
623 * Import the harness with `import type`, so it stays out of the bundle.
624 */
625export function createHarnessClient<THarness extends AnyHarness>(
626 options: HarnessClientOptions,
627): HarnessClient<THarness> {
628 const base = options.url.replace(/\/$/, '')
629 const doFetch = options.fetch ?? fetch
630 const idleTimeoutMs = options.idleTimeoutMs ?? IDLE_TIMEOUT_MS
631 const headers = () =>
632 typeof options.headers === 'function'
633 ? options.headers()
634 : (options.headers ?? {})
635​
636 // The handler answers a refusal with `{ error }`. Any other body falls
637 // back to the status text.
638 const failure = (action: string, response: Response, body: unknown) => {
639 const message =
640 typeof body === 'object' && body !== null && 'error' in body
641 ? String(body.error)
642 : response.statusText
643 return new Error(
644 `Harness ${action} failed (${response.status}): ${message}`,
645 )
646 }
647​
648 // The response when it is a success. Else it throws with the `{ error }`
649 // of the handler.
650 const checked = async (action: string, response: Response) => {
651 if (response.ok) return response
652 // A proxy can refuse a request with a page, not JSON.
653 const refusal: unknown = await response.json().catch(() => undefined)
654 throw failure(action, response, refusal)
655 }
656​
657 const send = async (
658 input: HarnessInput,
659 traceparent?: string,
660 ): Promise<Receipt> => {
661 // In `cancelInput` and `setDelivery`, `inputId` is the input to change.
662 const namesOther = input.op === 'cancelInput' || input.op === 'setDelivery'
663 // Each input gets an id, so a retry of the same request is the same
664 // input: the handler answers it with the first receipt.
665 const withId =
666 namesOther || input.inputId ? input : { ...input, inputId: newInputId() }
667 const response = await doFetch(`${base}/control`, {
668 method: 'POST',
669 headers: {
670 'Content-Type': 'application/json',
671 ...headers(),
672 ...(traceparent ? { traceparent } : {}),
673 },
674 body: JSON.stringify({ threadId: options.threadId, input: withId }),
675 })
676 const body: unknown = await (await checked('request', response)).json()
677 // The handler answers /control with a Receipt.
678 return body as Receipt
679 }
680​
681 const get = async (route: string, params: Record<string, string> = {}) => {
682 const query = new URLSearchParams({ threadId: options.threadId, ...params })
683 const response = await doFetch(`${base}/${route}?${query}`, {
684 headers: headers(),
685 })
686 if (!response.ok)
687 throw new Error(`Harness ${route} failed (${response.status})`)
688 return response
689 }
690​
691 const read = async <T>(route: string, params?: Record<string, string>) =>
692 // Each GET route answers with the type of the `HarnessClient` member
693 // that reads it. That member type sets `T`.
694 (await (await get(route, params)).json()) as T
695​
696 const putMedia = async ({
697 body,
698 mimeType,
699 name,
700 }: MediaUpload<Blob | ArrayBuffer | Uint8Array>) => {
701 const query = new URLSearchParams({
702 threadId: options.threadId,
703 name,
704 })
705 const response = await doFetch(`${base}/media?${query}`, {
706 method: 'POST',
707 headers: { 'Content-Type': mimeType, ...headers() },
708 // fetch refuses a view on a SharedArrayBuffer. ponytail: a Uint8Array
709 // is copied once; skip the copy when `body.buffer` is an ArrayBuffer
710 // if big uploads from bytes (not a Blob or File) ever matter.
711 body: body instanceof Uint8Array ? body.slice() : body,
712 })
713 await checked('upload', response)
714 const stored: unknown = await response.json()
715 if (!isMediaRecord(stored))
716 throw new Error('Harness upload failed: the answer is not a media record')
717 return stored
718 }
719​
720 const mediaUrl = async ({ id }: { id: string }) => {
721 const body: unknown = await (await get('media-url', { id })).json()
722 if (!isSignedPath(body))
723 throw new Error('Harness media-url failed: the answer has no signed path')
724 return { url: `${base}/${body.path}`, expiresAt: body.expiresAt }
725 }
726​
727 const loadMedia = async ({ id }: { id: string }) =>
728 new Uint8Array(await (await get('media', { id })).arrayBuffer())
729​
730 // `POST sessions`: rename, delete, fork, or share a session of this user.
731 const changeSession = async (change: SessionChange) =>
732 checked(
733 'sessions',
734 await doFetch(`${base}/sessions`, {
735 method: 'POST',
736 headers: { 'Content-Type': 'application/json', ...headers() },
737 body: JSON.stringify(change),
738 }),
739 )
740​
741 const sessionEntry = async (change: SessionChange) =>
742 // The handler answers each op but a delete with the entry.
743 // The server schema checked its metadata.
744 (await (await changeSession(change)).json()) as SessionIndexEntry<
745 SessionMetadataOf<THarness>
746 >
747​
748 async function* events(
749 eventOptions: {
750 from?: Cursor
751 signal?: AbortSignal
752 onConnection?: (state: 'open' | 'reconnecting') => void
753 } = {},
754 ) {
755 let cursor = eventOptions.from
756 const signal = eventOptions.signal
757 let reader: ReadableStreamDefaultReader<Uint8Array> | undefined
758 // Ends the wait before a reconnect.
759 let wake: (() => void) | undefined
760 // Closes a connection that sends nothing for `idleTimeoutMs`.
761 let idle: ReturnType<typeof setTimeout> | undefined
762 // One listener for all the connections: it stops the current read or
763 // the current wait.
764 const stopListening = whenAborted(signal, () => {
765 cancelReader(reader)
766 wake?.()
767 })
768 // The tries since the last read from the server, for the next wait.
769 let attempt = 0
770 // The error of a /snapshot answer with the wrong shape. It is not retried.
771 let badSnapshot: Error | undefined
772 try {
773 while (!signal?.aborted) {
774 try {
775 const query = new URLSearchParams({ threadId: options.threadId })
776 // No `from`: start at the head, so the stream does not send the
777 // whole history first. A thread with no entry has no events yet.
778 if (cursor === undefined) {
779 const head = await doFetch(`${base}/snapshot?${query}`, {
780 headers: headers(),
781 ...(signal ? { signal } : {}),
782 })
783 if (head.status === 404) cursor = '0'
784 else if (!head.ok) {
785 throw new Error(`Harness snapshot failed (${head.status})`)
786 } else {
787 const body: unknown = await head.json()
788 if (!isRecord(body) || typeof body.cursor !== 'string') {
789 // A retry gets the same answer, so stop the read.
790 badSnapshot = new Error(
791 `Harness snapshot has no string "cursor". Is ${base} a harness handler?`,
792 )
793 throw badSnapshot
794 }
795 cursor = body.cursor
796 }
797 }
798 if (cursor) query.set('from', cursor)
799 const response = await doFetch(`${base}/events?${query}`, {
800 headers: headers(),
801 ...(signal ? { signal } : {}),
802 })
803 if (!response.ok || !response.body) {
804 throw new Error(`Harness events failed (${response.status})`)
805 }
806 eventOptions.onConnection?.('open')
807 const connection = response.body.getReader()
808 reader = connection
809 // Each read, a ping too, shows that the connection is alive. A
810 // cancel ends the read, and the loop below connects again.
811 const isAlive = () => {
812 clearTimeout(idle)
813 idle = setTimeout(() => cancelReader(connection), idleTimeoutMs)
814 }
815 isAlive()
816 const frames = sseFrames(reader, () => {
817 attempt = 0
818 isAlive()
819 })
820 for await (const frame of frames) {
821 const failure = protocolErrorOf(frame)
822 if (failure) throw failure
823 if (
824 typeof frame === 'object' &&
825 frame !== null &&
826 'type' in frame &&
827 frame.type === 'harness.event' &&
828 'cursor' in frame &&
829 typeof frame.cursor === 'string'
830 ) {
831 cursor = frame.cursor
832 // The handler sends `{ type, cursor, operationId, event }`.
833 const { type: _type, ...entry } = frame as SessionEvent & {
834 type: string
835 }
836 yield entry
837 }
838 }
839 } catch (error) {
840 if (signal?.aborted) return
841 if (error === badSnapshot) throw error
842 if (error instanceof HarnessProtocolError) throw error
843 // A 404 means that the thread has no entry yet: a new chat, before
844 // its first message. Try again, the same as after a network error.
845 if (error instanceof Error && /\((401|403)\)/.test(error.message))
846 throw error
847 } finally {
848 clearTimeout(idle)
849 }
850 if (signal?.aborted) return
851 eventOptions.onConnection?.('reconnecting')
852 const wait = reconnectDelay(options.reconnectDelayMs ?? 1000, attempt)
853 attempt += 1
854 await new Promise<void>((resolve) => {
855 const timer = setTimeout(resolve, wait)
856 wake = () => {
857 clearTimeout(timer)
858 resolve()
859 }
860 })
861 wake = undefined
862 }
863 } finally {
864 stopListening()
865 }
866 }
867​
868 async function* hostEvents({ signal }: { signal?: AbortSignal } = {}) {
869 let reader: ReadableStreamDefaultReader<Uint8Array> | undefined
870 const stopListening = whenAborted(signal, () => cancelReader(reader))
871 try {
872 // A `slow_consumer` error ends the stream: connect again. The current
873 // statuses come first again.
874 let isSlow = true
875 while (isSlow && !signal?.aborted) {
876 isSlow = false
877 const response = await checked(
878 'host-events',
879 await doFetch(`${base}/host-events`, {
880 headers: headers(),
881 ...(signal ? { signal } : {}),
882 }),
883 )
884 if (!response.body)
885 throw new Error('Harness host-events failed: the answer has no body')
886 reader = response.body.getReader()
887 for await (const frame of sseFrames(reader)) {
888 // The handler sends `HostEvent` frames, and `harness.*` frames
889 // (the hello first, an error last) that are not host events.
890 const type = isRecord(frame) ? frame.type : undefined
891 if (type === 'harness.error') {
892 const failure = protocolErrorOf(frame)
893 if (failure) throw failure
894 isSlow = true
895 } else if (typeof type !== 'string' || !type.startsWith('harness.')) {
896 yield frame as HostEvent
897 }
898 }
899 }
900 } catch (error) {
901 if (signal?.aborted) return
902 throw error
903 } finally {
904 stopListening()
905 }
906 }
907​
908 const agents = new Proxy({} as ClientAgentHandles<THarness>, {
909 get: (_target, name) =>
910 typeof name === 'string'
911 ? {
912 start: (input?: unknown, startOptions?: { detached?: boolean }) =>
913 send({
914 op: 'agent',
915 agent: name,
916 input,
917 ...(startOptions?.detached ? { detached: true } : {}),
918 }),
919 }
920 : undefined,
921 })
922​
923 return {
924 send: (message, sendOptions) => {
925 const inputId = sendOptions?.inputId
926 ? { inputId: sendOptions.inputId }
927 : {}
928 if (sendOptions?.to !== undefined) {
929 return send({
930 op: 'agentMessage',
931 operationId: sendOptions.to,
932 message,
933 ...(sendOptions.mode ? { mode: sendOptions.mode } : {}),
934 ...inputId,
935 })
936 }
937 const mode = sendOptions?.mode ?? 'prompt'
938 const traceparent = sendOptions?.traceparent
939 if (mode !== 'prompt') {
940 return send({ op: mode, message, ...inputId }, traceparent)
941 }
942 return send(
943 {
944 op: 'prompt',
945 message,
946 ...(sendOptions?.busy ? { busy: sendOptions.busy } : {}),
947 ...(sendOptions?.ephemeral
948 ? { ephemeral: sendOptions.ephemeral }
949 : {}),
950 ...(sendOptions?.as ? { as: sendOptions.as } : {}),
951 ...inputId,
952 },
953 traceparent,
954 )
955 },
956 continueWithoutMessage: (continueOptions) =>
957 send({
958 op: 'continue',
959 ...(continueOptions?.inputId
960 ? { inputId: continueOptions.inputId }
961 : {}),
962 ...(continueOptions?.ephemeral
963 ? { ephemeral: continueOptions.ephemeral }
964 : {}),
965 }),
966 resolve: ({ resume, inputId }) =>
967 send({ op: 'resolve', resume, ...(inputId ? { inputId } : {}) }),
968 cancel: ({ operationId } = {}) =>
969 send({ op: 'cancel', ...(operationId ? { operationId } : {}) }),
970 cancelInput: ({ inputId }) => send({ op: 'cancelInput', inputId }),
971 changeInputDelivery: ({ inputId, delivery }) =>
972 send({ op: 'setDelivery', inputId, delivery }),
973 agents,
974 answer: ({ questionId, value }) =>
975 send({ op: 'answer', questionId, value }),
976 runCommand: ({ name, input }) => send({ op: 'command', name, input }),
977 runTool: ({ name, args, meta, inputId }) =>
978 send({
979 op: 'tool',
980 name,
981 ...(args !== undefined ? { args } : {}),
982 ...(meta ? { meta } : {}),
983 ...(inputId ? { inputId } : {}),
984 }),
985 appendRecords: ({ records, inputId }) =>
986 send({
987 op: 'append',
988 records: [...records],
989 ...(inputId ? { inputId } : {}),
990 }),
991 setPluginSetting: ({ key, value }) => send({ op: 'config', key, value }),
992 updateThreadSettings: ({ settings, inputId }) =>
993 send({ op: 'configure', settings, ...(inputId ? { inputId } : {}) }),
994 reset: ({ note, inputId } = {}) =>
995 send({
996 op: 'reset',
997 ...(note !== undefined ? { note } : {}),
998 ...(inputId ? { inputId } : {}),
999 }),
1000 revert: ({ messageId }) => send({ op: 'revert', messageId }),
1001 unrevert: () => send({ op: 'unrevert' }),
1002 events,
1003 hostEvents,
1004 snapshot: () => read('snapshot'),
1005 transcript: () => read('transcript'),
1006 agentTranscript: (run) =>
1007 read(
1008 'agent-transcript',
1009 'subagentRunId' in run
1010 ? { subagentRunId: run.subagentRunId }
1011 : { runId: run.runId },
1012 ),
1013 describe: () => read('describe'),
1014 putMedia,
1015 mediaUrl,
1016 loadMedia,
1017 sessions: {
1018 list: async ({
1019 limit,
1020 cursor,
1021 parentThreadId,
1022 search,
1023 metadata = {},
1024 withArchived,
1025 } = {}) => {
1026 const query = new URLSearchParams()
1027 if (limit !== undefined) query.set('limit', String(limit))
1028 if (cursor) query.set('cursor', cursor)
1029 if (parentThreadId) query.set('parentThreadId', parentThreadId)
1030 if (search) query.set('search', search)
1031 if (withArchived) query.set('withArchived', 'true')
1032 for (const [key, value] of Object.entries(metadata))
1033 query.set(`metadata.${key}`, value)
1034 const response = await checked(
1035 'sessions',
1036 await doFetch(`${base}/sessions?${query}`, { headers: headers() }),
1038 // The handler answers with one page of the session index.
1039 return (await response.json()) as Omit<SessionIndexPage, 'entries'> & {
1040 entries: Array<SessionIndexEntry<SessionMetadataOf<THarness>>>
1042 },
1043 rename: ({ threadId, title }) =>
1044 sessionEntry({ op: 'rename', threadId, title }),
1045 archive: ({ threadId }) => sessionEntry({ op: 'archive', threadId }),
1046 unarchive: ({ threadId }) => sessionEntry({ op: 'unarchive', threadId }),
1047 update: (change) => sessionEntry({ ...change, op: 'update' }),
1048 delete: async ({ threadId }) => {
1049 await changeSession({ op: 'delete', threadId })
1050 },
1051 fork: ({ threadId, at }) => sessionEntry({ op: 'fork', threadId, ...at }),
1052 share: ({ threadId, userId, role }) =>
1053 sessionEntry({ op: 'share', threadId, userId, role }),
1054 unshare: ({ threadId, userId }) =>
1055 sessionEntry({ op: 'unshare', threadId, userId }),
1056 },
1059​
1060// Browsers expose `crypto.randomUUID` only on HTTPS and localhost. The id
1061// only has to be unique, so plain HTTP falls back to random digits.
1062function newInputId(): string {
1063 return typeof crypto.randomUUID === 'function'
1064 ? crypto.randomUUID()
1065 : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}${Math.random().toString(36).slice(2)}`