Update existing types and rename structured output fields in SDK docs

This commit is contained in:
starptech 2026-05-21 13:26:38 +02:00
parent 13006d6d7c
commit 8d71e43508
33 changed files with 7610 additions and 3115 deletions

View file

@ -130,7 +130,7 @@ describe("StructuredOutput Integration", () => {
)
live(
"works with text outputFormat (default)",
"works with text format (default)",
() =>
Effect.gen(function* () {
const prompt = yield* SessionPrompt.Service
@ -168,7 +168,7 @@ describe("StructuredOutput Integration", () => {
)
live(
"stores outputFormat on user message",
"stores format on user message",
() =>
Effect.gen(function* () {
const prompt = yield* SessionPrompt.Service
@ -200,7 +200,7 @@ describe("StructuredOutput Integration", () => {
const messages = yield* sessions.messages({ sessionID: session.id })
const userMessage = messages.find((m) => m.info.role === "user")
// Verify outputFormat was stored on user message
// Verify format was stored on user message
expect(userMessage).toBeDefined()
if (userMessage?.info.role === "user") {
expect(userMessage.info.format).toBeDefined()

View file

@ -99,7 +99,7 @@ describe("structured-output.StructuredOutputError", () => {
})
describe("structured-output.UserMessage", () => {
test("user message accepts outputFormat", () => {
test("user message accepts format", () => {
const result = decodeUser({
id: MessageID.ascending(),
sessionID: SessionID.descending(),
@ -107,7 +107,7 @@ describe("structured-output.UserMessage", () => {
time: { created: Date.now() },
agent: "default",
model: { providerID: "anthropic", modelID: "claude-3" },
outputFormat: {
format: {
type: "json_schema",
schema: { type: "object" },
},
@ -115,7 +115,7 @@ describe("structured-output.UserMessage", () => {
expect(Exit.isSuccess(result)).toBe(true)
})
test("user message works without outputFormat (optional)", () => {
test("user message works without format (optional)", () => {
const result = decodeUser({
id: MessageID.ascending(),
sessionID: SessionID.descending(),

View file

@ -12,6 +12,33 @@ import { createClient } from "@hey-api/openapi-ts"
const opencode = path.resolve(dir, "../../opencode")
await $`bun dev generate > ${dir}/openapi.json`.cwd(opencode)
await Bun.write(path.join(dir, "openapi-legacy.json"), JSON.stringify(legacyOpenApi(await Bun.file("openapi.json").json())))
await createClient({
input: "./openapi-legacy.json",
output: {
path: "./src/gen",
tsConfigPath: path.join(dir, "tsconfig.json"),
clean: true,
},
plugins: [
{
name: "@hey-api/typescript",
exportFromIndex: false,
},
{
name: "@hey-api/sdk",
instance: "OpencodeClient",
exportFromIndex: false,
auth: false,
},
{
name: "@hey-api/client-fetch",
exportFromIndex: false,
baseUrl: "http://localhost:4096",
},
],
})
await createClient({
input: "./openapi.json",
@ -45,3 +72,27 @@ await $`bun prettier --write src/v2`
await $`rm -rf dist`
await $`bun tsc`
await $`rm openapi.json`
await $`rm openapi-legacy.json`
type OpenApiSpec = {
paths: Record<string, Record<string, { parameters?: Array<{ name: string; in: string }> }>>
}
function legacyOpenApi(input: OpenApiSpec) {
const spec = structuredClone(input)
spec.paths = Object.fromEntries(
Object.entries(spec.paths)
.filter(([route]) => route !== "/api" && !route.startsWith("/api/"))
.map(([route, item]) => [route.replaceAll("{sessionID}", "{id}"), renameLegacyPathParameters(item)]),
)
return spec
}
function renameLegacyPathParameters(item: OpenApiSpec["paths"][string]) {
for (const operation of Object.values(item)) {
for (const parameter of operation.parameters ?? []) {
if (parameter.in === "path" && parameter.name === "sessionID") parameter.name = "id"
}
}
return item
}

View file

@ -1,7 +1,7 @@
// This file is auto-generated by @hey-api/openapi-ts
import type { ClientOptions } from "./types.gen.js"
import { type Config, type ClientOptions as DefaultClientOptions, createClient, createConfig } from "./client/index.js"
import { type ClientOptions, type Config, createClient, createConfig } from "./client/index.js"
import type { ClientOptions as ClientOptions2 } from "./types.gen.js"
/**
* The `createClientConfig()` function will be called on client initialization
@ -11,12 +11,8 @@ import { type Config, type ClientOptions as DefaultClientOptions, createClient,
* `setConfig()`. This is useful for example if you're using Next.js
* to ensure your client always has the correct values.
*/
export type CreateClientConfig<T extends DefaultClientOptions = ClientOptions> = (
override?: Config<DefaultClientOptions & T>,
) => Config<Required<DefaultClientOptions> & T>
export type CreateClientConfig<T extends ClientOptions = ClientOptions2> = (
override?: Config<ClientOptions & T>,
) => Config<Required<ClientOptions> & T>
export const client = createClient(
createConfig<ClientOptions>({
baseUrl: "http://localhost:4096",
}),
)
export const client = createClient(createConfig<ClientOptions2>({ baseUrl: "http://localhost:4096" }))

View file

@ -1,6 +1,8 @@
// This file is auto-generated by @hey-api/openapi-ts
import { createSseClient } from "../core/serverSentEvents.gen.js"
import type { HttpMethod } from "../core/types.gen.js"
import { getValidRequestBody } from "../core/utils.gen.js"
import type { Client, Config, RequestOptions, ResolvedRequestOptions } from "./types.gen.js"
import {
buildUrl,
@ -49,12 +51,12 @@ export const createClient = (config: Config = {}): Client => {
await opts.requestValidator(opts)
}
if (opts.body && opts.bodySerializer) {
if (opts.body !== undefined && opts.bodySerializer) {
opts.serializedBody = opts.bodySerializer(opts.body)
}
// remove Content-Type header if body is empty to avoid sending invalid requests
if (opts.serializedBody === undefined || opts.serializedBody === "") {
if (opts.body === undefined || opts.serializedBody === "") {
opts.headers.delete("Content-Type")
}
@ -69,12 +71,12 @@ export const createClient = (config: Config = {}): Client => {
const requestInit: ReqInit = {
redirect: "follow",
...opts,
body: opts.serializedBody,
body: getValidRequestBody(opts),
}
let request = new Request(url, requestInit)
for (const fn of interceptors.request._fns) {
for (const fn of interceptors.request.fns) {
if (fn) {
request = await fn(request, opts)
}
@ -83,9 +85,37 @@ export const createClient = (config: Config = {}): Client => {
// fetch must be assigned here, otherwise it would throw the error:
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
const _fetch = opts.fetch!
let response = await _fetch(request)
let response: Response
for (const fn of interceptors.response._fns) {
try {
response = await _fetch(request)
} catch (error) {
// Handle fetch exceptions (AbortError, network errors, etc.)
let finalError = error
for (const fn of interceptors.error.fns) {
if (fn) {
finalError = (await fn(error, undefined as any, request, opts)) as unknown
}
}
finalError = finalError || ({} as unknown)
if (opts.throwOnError) {
throw finalError
}
// Return error response
return opts.responseStyle === "data"
? undefined
: {
error: finalError,
request,
response: undefined as any,
}
}
for (const fn of interceptors.response.fns) {
if (fn) {
response = await fn(response, request, opts)
}
@ -97,27 +127,51 @@ export const createClient = (config: Config = {}): Client => {
}
if (response.ok) {
const parseAs =
(opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json"
if (response.status === 204 || response.headers.get("Content-Length") === "0") {
let emptyData: any
switch (parseAs) {
case "arrayBuffer":
case "blob":
case "text":
emptyData = await response[parseAs]()
break
case "formData":
emptyData = new FormData()
break
case "stream":
emptyData = response.body
break
case "json":
default:
emptyData = {}
break
}
return opts.responseStyle === "data"
? {}
? emptyData
: {
data: {},
data: emptyData,
...result,
}
}
const parseAs =
(opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json"
let data: any
switch (parseAs) {
case "arrayBuffer":
case "blob":
case "formData":
case "json":
case "text":
data = await response[parseAs]()
break
case "json": {
// Some servers return 200 with no Content-Length and empty body.
// response.json() would throw; read as text and parse if non-empty.
const text = await response.text()
data = text ? JSON.parse(text) : {}
break
}
case "stream":
return opts.responseStyle === "data"
? response.body
@ -157,7 +211,7 @@ export const createClient = (config: Config = {}): Client => {
const error = jsonError ?? textError
let finalError = error
for (const fn of interceptors.error._fns) {
for (const fn of interceptors.error.fns) {
if (fn) {
finalError = (await fn(error, response, request, opts)) as string
}
@ -178,35 +232,54 @@ export const createClient = (config: Config = {}): Client => {
}
}
const makeMethod = (method: Required<Config>["method"]) => {
const fn = (options: RequestOptions) => request({ ...options, method })
fn.sse = async (options: RequestOptions) => {
const { opts, url } = await beforeRequest(options)
return createSseClient({
...opts,
body: opts.body as BodyInit | null | undefined,
headers: opts.headers as unknown as Record<string, string>,
method,
url,
})
}
return fn
const makeMethodFn = (method: Uppercase<HttpMethod>) => (options: RequestOptions) => request({ ...options, method })
const makeSseFn = (method: Uppercase<HttpMethod>) => async (options: RequestOptions) => {
const { opts, url } = await beforeRequest(options)
return createSseClient({
...opts,
body: opts.body as BodyInit | null | undefined,
headers: opts.headers as unknown as Record<string, string>,
method,
onRequest: async (url, init) => {
let request = new Request(url, init)
for (const fn of interceptors.request.fns) {
if (fn) {
request = await fn(request, opts)
}
}
return request
},
serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined,
url,
})
}
return {
buildUrl,
connect: makeMethod("CONNECT"),
delete: makeMethod("DELETE"),
get: makeMethod("GET"),
connect: makeMethodFn("CONNECT"),
delete: makeMethodFn("DELETE"),
get: makeMethodFn("GET"),
getConfig,
head: makeMethod("HEAD"),
head: makeMethodFn("HEAD"),
interceptors,
options: makeMethod("OPTIONS"),
patch: makeMethod("PATCH"),
post: makeMethod("POST"),
put: makeMethod("PUT"),
options: makeMethodFn("OPTIONS"),
patch: makeMethodFn("PATCH"),
post: makeMethodFn("POST"),
put: makeMethodFn("PUT"),
request,
setConfig,
trace: makeMethod("TRACE"),
sse: {
connect: makeSseFn("CONNECT"),
delete: makeSseFn("DELETE"),
get: makeSseFn("GET"),
head: makeSseFn("HEAD"),
options: makeSseFn("OPTIONS"),
patch: makeSseFn("PATCH"),
post: makeSseFn("POST"),
put: makeSseFn("PUT"),
trace: makeSseFn("TRACE"),
},
trace: makeMethodFn("TRACE"),
} as Client
}

View file

@ -8,6 +8,7 @@ export {
urlSearchParamsBodySerializer,
} from "../core/bodySerializer.gen.js"
export { buildClientParams } from "../core/params.gen.js"
export { serializeQueryKeyValue } from "../core/queryKeySerializer.gen.js"
export { createClient } from "./client.gen.js"
export type {
Client,
@ -15,7 +16,6 @@ export type {
Config,
CreateClientConfig,
Options,
OptionsLegacyParser,
RequestOptions,
RequestResult,
ResolvedRequestOptions,

View file

@ -20,7 +20,7 @@ export interface Config<T extends ClientOptions = ClientOptions>
*
* @default globalThis.fetch
*/
fetch?: (request: Request) => ReturnType<typeof fetch>
fetch?: typeof fetch
/**
* Please don't use the Fetch client for Next.js applications. The `next`
* options won't have any effect.
@ -128,7 +128,7 @@ export interface ClientOptions {
throwOnError?: boolean
}
type MethodFnBase = <
type MethodFn = <
TData = unknown,
TError = unknown,
ThrowOnError extends boolean = false,
@ -137,7 +137,7 @@ type MethodFnBase = <
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, "method">,
) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>
type MethodFnServerSentEvents = <
type SseFn = <
TData = unknown,
TError = unknown,
ThrowOnError extends boolean = false,
@ -146,10 +146,6 @@ type MethodFnServerSentEvents = <
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, "method">,
) => Promise<ServerSentEventsResult<TData, TError>>
type MethodFn = MethodFnBase & {
sse: MethodFnServerSentEvents
}
type RequestFn = <
TData = unknown,
TError = unknown,
@ -168,10 +164,10 @@ type BuildUrlFn = <
url: string
},
>(
options: Pick<TData, "url"> & Options<TData>,
options: TData & Options<TData>,
) => string
export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn> & {
export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn, SseFn> & {
interceptors: Middleware<Request, Response, unknown, ResolvedRequestOptions>
}
@ -203,20 +199,4 @@ export type Options<
TResponse = unknown,
TResponseStyle extends ResponseStyle = "fields",
> = OmitKeys<RequestOptions<TResponse, TResponseStyle, ThrowOnError>, "body" | "path" | "query" | "url"> &
Omit<TData, "url">
export type OptionsLegacyParser<
TData = unknown,
ThrowOnError extends boolean = boolean,
TResponseStyle extends ResponseStyle = "fields",
> = TData extends { body?: any }
? TData extends { headers?: any }
? OmitKeys<RequestOptions<unknown, TResponseStyle, ThrowOnError>, "body" | "headers" | "url"> & TData
: OmitKeys<RequestOptions<unknown, TResponseStyle, ThrowOnError>, "body" | "url"> &
TData &
Pick<RequestOptions<unknown, TResponseStyle, ThrowOnError>, "headers">
: TData extends { headers?: any }
? OmitKeys<RequestOptions<unknown, TResponseStyle, ThrowOnError>, "headers" | "url"> &
TData &
Pick<RequestOptions<unknown, TResponseStyle, ThrowOnError>, "body">
: OmitKeys<RequestOptions<unknown, TResponseStyle, ThrowOnError>, "url"> & TData
([TData] extends [never] ? unknown : Omit<TData, "url">)

View file

@ -7,7 +7,7 @@ import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam } fr
import { getUrl } from "../core/utils.gen.js"
import type { Client, ClientOptions, Config, RequestOptions } from "./types.gen.js"
export const createQuerySerializer = <T = unknown>({ allowReserved, array, object }: QuerySerializerOptions = {}) => {
export const createQuerySerializer = <T = unknown>({ parameters = {}, ...args }: QuerySerializerOptions = {}) => {
const querySerializer = (queryParams: T) => {
const search: string[] = []
if (queryParams && typeof queryParams === "object") {
@ -18,29 +18,31 @@ export const createQuerySerializer = <T = unknown>({ allowReserved, array, objec
continue
}
const options = parameters[name] || args
if (Array.isArray(value)) {
const serializedArray = serializeArrayParam({
allowReserved,
allowReserved: options.allowReserved,
explode: true,
name,
style: "form",
value,
...array,
...options.array,
})
if (serializedArray) search.push(serializedArray)
} else if (typeof value === "object") {
const serializedObject = serializeObjectParam({
allowReserved,
allowReserved: options.allowReserved,
explode: true,
name,
style: "deepObject",
value: value as Record<string, unknown>,
...object,
...options.object,
})
if (serializedObject) search.push(serializedObject)
} else {
const serializedPrimitive = serializePrimitiveParam({
allowReserved,
allowReserved: options.allowReserved,
name,
value: value as string,
})
@ -162,14 +164,22 @@ export const mergeConfigs = (a: Config, b: Config): Config => {
return config
}
const headersEntries = (headers: Headers): Array<[string, string]> => {
const entries: Array<[string, string]> = []
headers.forEach((value, key) => {
entries.push([key, value])
})
return entries
}
export const mergeHeaders = (...headers: Array<Required<Config>["headers"] | undefined>): Headers => {
const mergedHeaders = new Headers()
for (const header of headers) {
if (!header || typeof header !== "object") {
if (!header) {
continue
}
const iterator = header instanceof Headers ? header.entries() : Object.entries(header)
const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header)
for (const [key, value] of iterator) {
if (value === null) {
@ -200,61 +210,53 @@ type ReqInterceptor<Req, Options> = (request: Req, options: Options) => Req | Pr
type ResInterceptor<Res, Req, Options> = (response: Res, request: Req, options: Options) => Res | Promise<Res>
class Interceptors<Interceptor> {
_fns: (Interceptor | null)[]
fns: Array<Interceptor | null> = []
constructor() {
this._fns = []
clear(): void {
this.fns = []
}
clear() {
this._fns = []
eject(id: number | Interceptor): void {
const index = this.getInterceptorIndex(id)
if (this.fns[index]) {
this.fns[index] = null
}
}
exists(id: number | Interceptor): boolean {
const index = this.getInterceptorIndex(id)
return Boolean(this.fns[index])
}
getInterceptorIndex(id: number | Interceptor): number {
if (typeof id === "number") {
return this._fns[id] ? id : -1
} else {
return this._fns.indexOf(id)
return this.fns[id] ? id : -1
}
}
exists(id: number | Interceptor) {
const index = this.getInterceptorIndex(id)
return !!this._fns[index]
return this.fns.indexOf(id)
}
eject(id: number | Interceptor) {
update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false {
const index = this.getInterceptorIndex(id)
if (this._fns[index]) {
this._fns[index] = null
}
}
update(id: number | Interceptor, fn: Interceptor) {
const index = this.getInterceptorIndex(id)
if (this._fns[index]) {
this._fns[index] = fn
if (this.fns[index]) {
this.fns[index] = fn
return id
} else {
return false
}
return false
}
use(fn: Interceptor) {
this._fns = [...this._fns, fn]
return this._fns.length - 1
use(fn: Interceptor): number {
this.fns.push(fn)
return this.fns.length - 1
}
}
// `createInterceptors()` response, meant for external use as it does not
// expose internals
export interface Middleware<Req, Res, Err, Options> {
error: Pick<Interceptors<ErrInterceptor<Err, Res, Req, Options>>, "eject" | "use">
request: Pick<Interceptors<ReqInterceptor<Req, Options>>, "eject" | "use">
response: Pick<Interceptors<ResInterceptor<Res, Req, Options>>, "eject" | "use">
error: Interceptors<ErrInterceptor<Err, Res, Req, Options>>
request: Interceptors<ReqInterceptor<Req, Options>>
response: Interceptors<ResInterceptor<Res, Req, Options>>
}
// do not add `Middleware` as return type so we can use _fns internally
export const createInterceptors = <Req, Res, Err, Options>() => ({
export const createInterceptors = <Req, Res, Err, Options>(): Middleware<Req, Res, Err, Options> => ({
error: new Interceptors<ErrInterceptor<Err, Res, Req, Options>>(),
request: new Interceptors<ReqInterceptor<Req, Options>>(),
response: new Interceptors<ResInterceptor<Res, Req, Options>>(),

View file

@ -6,10 +6,18 @@ export type QuerySerializer = (query: Record<string, unknown>) => string
export type BodySerializer = (body: any) => any
export interface QuerySerializerOptions {
type QuerySerializerOptionsObject = {
allowReserved?: boolean
array?: SerializerOptions<ArrayStyle>
object?: SerializerOptions<ObjectStyle>
array?: Partial<SerializerOptions<ArrayStyle>>
object?: Partial<SerializerOptions<ObjectStyle>>
}
export type QuerySerializerOptions = QuerySerializerOptionsObject & {
/**
* Per-parameter serialization overrides. When provided, these settings
* override the global array/object settings for specific parameter names.
*/
parameters?: Record<string, QuerySerializerOptionsObject>
}
const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => {

View file

@ -23,6 +23,17 @@ export type Field =
key?: string
map?: string
}
| {
/**
* Field name. This is the name we want the user to see and use.
*/
key: string
/**
* Field mapped name. This is the name we want to use in the request.
* If `in` is omitted, `map` aliases `key` to the transport layer.
*/
map: Slot
}
export interface Fields {
allowExtra?: Partial<Record<Slot, boolean>>
@ -41,10 +52,14 @@ const extraPrefixes = Object.entries(extraPrefixesMap)
type KeyMap = Map<
string,
{
in: Slot
map?: string
}
| {
in: Slot
map?: string
}
| {
in?: never
map: Slot
}
>
const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => {
@ -60,6 +75,10 @@ const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => {
map: config.map,
})
}
} else if ("key" in config) {
map.set(config.key, {
map: config.map,
})
} else if (config.args) {
buildKeyMap(config.args, map)
}
@ -108,7 +127,9 @@ export const buildClientParams = (args: ReadonlyArray<unknown>, fields: FieldsCo
if (config.key) {
const field = map.get(config.key)!
const name = field.map || config.key
;(params[field.in] as Record<string, unknown>)[name] = arg
if (field.in) {
;(params[field.in] as Record<string, unknown>)[name] = arg
}
} else {
params.body = arg
}
@ -117,16 +138,20 @@ export const buildClientParams = (args: ReadonlyArray<unknown>, fields: FieldsCo
const field = map.get(key)
if (field) {
const name = field.map || key
;(params[field.in] as Record<string, unknown>)[name] = value
if (field.in) {
const name = field.map || key
;(params[field.in] as Record<string, unknown>)[name] = value
} else {
params[field.map] = value
}
} else {
const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix))
if (extra) {
const [prefix, slot] = extra
;(params[slot] as Record<string, unknown>)[key.slice(prefix.length)] = value
} else {
for (const [slot, allowed] of Object.entries(config.allowExtra ?? {})) {
} else if ("allowExtra" in config && config.allowExtra) {
for (const [slot, allowed] of Object.entries(config.allowExtra)) {
if (allowed) {
;(params[slot as Slot] as Record<string, unknown>)[key] = value
break

View file

@ -4,6 +4,17 @@ import type { Config } from "./types.gen.js"
export type ServerSentEventsOptions<TData = unknown> = Omit<RequestInit, "method"> &
Pick<Config, "method" | "responseTransformer" | "responseValidator"> & {
/**
* Fetch API implementation. You can use this option to provide a custom
* fetch instance.
*
* @default globalThis.fetch
*/
fetch?: typeof fetch
/**
* Implementing clients can call request interceptors inside this hook.
*/
onRequest?: (url: string, init: RequestInit) => Promise<Request>
/**
* Callback invoked when a network or parsing error occurs during streaming.
*
@ -21,6 +32,7 @@ export type ServerSentEventsOptions<TData = unknown> = Omit<RequestInit, "method
* @returns Nothing (void).
*/
onSseEvent?: (event: StreamEvent<TData>) => void
serializedBody?: RequestInit["body"]
/**
* Default retry delay in milliseconds.
*
@ -64,6 +76,7 @@ export type ServerSentEventsResult<TData = unknown, TReturn = void, TNext = unkn
}
export const createSseClient = <TData = unknown>({
onRequest,
onSseError,
onSseEvent,
responseTransformer,
@ -99,7 +112,21 @@ export const createSseClient = <TData = unknown>({
}
try {
const response = await fetch(url, { ...options, headers, signal })
const requestInit: RequestInit = {
redirect: "follow",
...options,
body: options.serializedBody,
headers,
signal,
}
let request = new Request(url, requestInit)
if (onRequest) {
request = await onRequest(url, requestInit)
}
// fetch must be assigned here, otherwise it would throw the error:
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
const _fetch = options.fetch ?? globalThis.fetch
const response = await _fetch(request)
if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`)
@ -111,7 +138,7 @@ export const createSseClient = <TData = unknown>({
const abortHandler = () => {
try {
void reader.cancel()
reader.cancel()
} catch {
// noop
}
@ -124,6 +151,8 @@ export const createSseClient = <TData = unknown>({
const { done, value } = await reader.read()
if (done) break
buffer += value
// Normalize line endings: CRLF -> LF, then CR -> LF
buffer = buffer.replace(/\r\n/g, "\n").replace(/\r/g, "\n")
const chunks = buffer.split("\n\n")
buffer = chunks.pop() ?? ""

View file

@ -3,24 +3,19 @@
import type { Auth, AuthToken } from "./auth.gen.js"
import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from "./bodySerializer.gen.js"
export interface Client<RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never> {
export type HttpMethod = "connect" | "delete" | "get" | "head" | "options" | "patch" | "post" | "put" | "trace"
export type Client<RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never> = {
/**
* Returns the final request URL.
*/
buildUrl: BuildUrlFn
connect: MethodFn
delete: MethodFn
get: MethodFn
getConfig: () => Config
head: MethodFn
options: MethodFn
patch: MethodFn
post: MethodFn
put: MethodFn
request: RequestFn
setConfig: (config: Config) => Config
trace: MethodFn
}
} & {
[K in HttpMethod]: MethodFn
} & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } })
export interface Config {
/**
@ -47,7 +42,7 @@ export interface Config {
*
* {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more}
*/
method?: "CONNECT" | "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT" | "TRACE"
method?: Uppercase<HttpMethod>
/**
* A function for serializing request query parameters. By default, arrays
* will be exploded in form style, objects will be exploded in deepObject

View file

@ -1,6 +1,6 @@
// This file is auto-generated by @hey-api/openapi-ts
import type { QuerySerializer } from "./bodySerializer.gen.js"
import type { BodySerializer, QuerySerializer } from "./bodySerializer.gen.js"
import {
type ArraySeparatorStyle,
serializeArrayParam,
@ -107,3 +107,31 @@ export const getUrl = ({
}
return url
}
export function getValidRequestBody(options: {
body?: unknown
bodySerializer?: BodySerializer | null
serializedBody?: unknown
}) {
const hasBody = options.body !== undefined
const isSerializedBody = hasBody && options.bodySerializer
if (isSerializedBody) {
if ("serializedBody" in options) {
const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ""
return hasSerializedBody ? options.serializedBody : null
}
// not all clients implement a serializedBody property (i.e. client-axios)
return options.body !== "" ? options.body : null
}
// plain/text body
if (hasBody) {
return options.body
}
// no body was provided
return undefined
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -148,7 +148,7 @@ const result = await client.session.prompt({
})
// Access the structured output
console.log(result.data.info.structured_output)
console.log(result.data.info.structured)
// { company: "Anthropic", founded: 2021, products: ["Claude", "Claude API"] }
```
@ -175,8 +175,8 @@ console.log(result.data.info.structured_output)
```typescript
if (result.data.info.error?.name === "StructuredOutputError") {
console.error("Failed to produce structured output:", result.data.info.error.message)
console.error("Attempts:", result.data.info.error.retries)
console.error("Failed to produce structured output:", result.data.info.error.data.message)
console.error("Attempts:", result.data.info.error.data.retries)
}
```
@ -313,7 +313,7 @@ const { providers, default: defaults } = await client.config.providers()
| `session.summarize({ path, body })` | تلخيص جلسة | يعيد `boolean` |
| `session.messages({ path })` | سرد الرسائل في جلسة | يعيد `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}[]` |
| `session.message({ path })` | جلب تفاصيل الرسالة | يعيد `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.prompt({ path, body })` | إرسال رسالة مطالبة | `body.noReply: true` يعيد UserMessage (للسياق فقط). الافتراضي يعيد <a href={typesUrl}><code>AssistantMessage</code></a> مع استجابة AI. يدعم `body.outputFormat` من أجل [المخرجات المنظمة](#المخرجات-المنظمة) |
| `session.prompt({ path, body })` | إرسال رسالة مطالبة | `body.noReply: true` يعيد UserMessage (للسياق فقط). الافتراضي يعيد <a href={typesUrl}><code>AssistantMessage</code></a> مع استجابة AI. يدعم `body.format` من أجل [المخرجات المنظمة](#المخرجات-المنظمة) |
| `session.command({ path, body })` | إرسال أمر إلى الجلسة | يعيد `{ info: `<a href={typesUrl}><code>AssistantMessage</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.shell({ path, body })` | تشغيل أمر shell | يعيد <a href={typesUrl}><code>AssistantMessage</code></a> |
| `session.revert({ path, body })` | التراجع عن رسالة | يعيد <a href={typesUrl}><code>Session</code></a> |

View file

@ -148,7 +148,7 @@ const result = await client.session.prompt({
})
// Access the structured output
console.log(result.data.info.structured_output)
console.log(result.data.info.structured)
// { company: "Anthropic", founded: 2021, products: ["Claude", "Claude API"] }
```
@ -175,8 +175,8 @@ Ako model ne uspije proizvesti validan strukturirani izlaz nakon svih ponovnih p
```typescript
if (result.data.info.error?.name === "StructuredOutputError") {
console.error("Failed to produce structured output:", result.data.info.error.message)
console.error("Attempts:", result.data.info.error.retries)
console.error("Failed to produce structured output:", result.data.info.error.data.message)
console.error("Attempts:", result.data.info.error.data.retries)
}
```
@ -313,7 +313,7 @@ const { providers, default: defaults } = await client.config.providers()
| `session.summarize({ path, body })` | Summarize session | Returns `boolean` |
| `session.messages({ path })` | List messages in a session | Returns `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}[]` |
| `session.message({ path })` | Get message details | Returns `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.prompt({ path, body })` | Send prompt message | `body.noReply: true` returns UserMessage (context only). Default returns <a href={typesUrl}><code>AssistantMessage</code></a> with AI response. Supports `body.outputFormat` for [structured output](#strukturirani-izlaz) |
| `session.prompt({ path, body })` | Send prompt message | `body.noReply: true` returns UserMessage (context only). Default returns <a href={typesUrl}><code>AssistantMessage</code></a> with AI response. Supports `body.format` for [structured output](#strukturirani-izlaz) |
| `session.command({ path, body })` | Send command to session | Returns `{ info: `<a href={typesUrl}><code>AssistantMessage</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.shell({ path, body })` | Run a shell command | Returns <a href={typesUrl}><code>AssistantMessage</code></a> |
| `session.revert({ path, body })` | Revert a message | Returns <a href={typesUrl}><code>Session</code></a> |

View file

@ -148,7 +148,7 @@ const result = await client.session.prompt({
})
// Access the structured output
console.log(result.data.info.structured_output)
console.log(result.data.info.structured)
// { company: "Anthropic", founded: 2021, products: ["Claude", "Claude API"] }
```
@ -175,8 +175,8 @@ Hvis modellen ikke formår at producere gyldigt struktureret output efter alle f
```typescript
if (result.data.info.error?.name === "StructuredOutputError") {
console.error("Failed to produce structured output:", result.data.info.error.message)
console.error("Attempts:", result.data.info.error.retries)
console.error("Failed to produce structured output:", result.data.info.error.data.message)
console.error("Attempts:", result.data.info.error.data.retries)
}
```
@ -313,7 +313,7 @@ const { providers, default: defaults } = await client.config.providers()
| `session.summarize({ path, body })` | Oppsummer sessionen | Returnerer `boolean` |
| `session.messages({ path })` | Liste meldinger i en session | Returnerer `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}[]` |
| `session.message({ path })` | Få meldingsdetaljer | Returnerer `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.prompt({ path, body })` | Send melding | `body.noReply: true` returnerer UserMessage (kun kontekst). Standard returnerer <a href={typesUrl}><code>AssistantMessage</code></a> med AI svar. Understøtter `body.outputFormat` for [struktureret output](#struktureret-output) |
| `session.prompt({ path, body })` | Send melding | `body.noReply: true` returnerer UserMessage (kun kontekst). Standard returnerer <a href={typesUrl}><code>AssistantMessage</code></a> med AI svar. Understøtter `body.format` for [struktureret output](#struktureret-output) |
| `session.command({ path, body })` | Send kommando til session | Returnerer `{ info: `<a href={typesUrl}><code>AssistantMessage</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.shell({ path, body })` | Kjør en shell-kommando | Returnerer <a href={typesUrl}><code>AssistantMessage</code></a> |
| `session.revert({ path, body })` | Tilbakestill en melding | Returnerer <a href={typesUrl}><code>Session</code></a> |

View file

@ -150,7 +150,7 @@ const result = await client.session.prompt({
})
// Zugriff auf die strukturierte Ausgabe
console.log(result.data.info.structured_output)
console.log(result.data.info.structured)
// { company: "Anthropic", founded: 2021, products: ["Claude", "Claude API"] }
```
@ -177,8 +177,8 @@ Wenn das Modell nach allen Wiederholungen keine valide strukturierte Ausgabe lie
```typescript
if (result.data.info.error?.name === "StructuredOutputError") {
console.error("Strukturierte Ausgabe fehlgeschlagen:", result.data.info.error.message)
console.error("Versuche:", result.data.info.error.retries)
console.error("Strukturierte Ausgabe fehlgeschlagen:", result.data.info.error.data.message)
console.error("Versuche:", result.data.info.error.data.retries)
}
```
@ -315,7 +315,7 @@ const { providers, default: defaults } = await client.config.providers()
| `session.summarize({ path, body })` | Fasst Session zusammen | Gibt `boolean` zurueck |
| `session.messages({ path })` | Listet Nachrichten einer Session | Gibt `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}[]` zurueck |
| `session.message({ path })` | Ruft Nachrichtendetails ab | Gibt `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` zurueck |
| `session.prompt({ path, body })` | Sendet Prompt-Nachricht | `body.noReply: true` gibt UserMessage (nur Kontext) zurueck. Standard gibt <a href={typesUrl}><code>AssistantMessage</code></a> mit AI-Antwort zurueck. Unterstuetzt `body.outputFormat` fuer [strukturierte Ausgabe](#structured-output) |
| `session.prompt({ path, body })` | Sendet Prompt-Nachricht | `body.noReply: true` gibt UserMessage (nur Kontext) zurueck. Standard gibt <a href={typesUrl}><code>AssistantMessage</code></a> mit AI-Antwort zurueck. Unterstuetzt `body.format` fuer [strukturierte Ausgabe](#structured-output) |
| `session.command({ path, body })` | Sendet Befehl an Session | Gibt `{ info: `<a href={typesUrl}><code>AssistantMessage</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` zurueck |
| `session.shell({ path, body })` | Fuehrt Shell-Befehl aus | Gibt <a href={typesUrl}><code>AssistantMessage</code></a> zurueck |
| `session.revert({ path, body })` | Setzt Nachricht zurueck | Gibt <a href={typesUrl}><code>Session</code></a> zurueck |

View file

@ -148,7 +148,7 @@ const result = await client.session.prompt({
})
// Access the structured output
console.log(result.data.info.structured_output)
console.log(result.data.info.structured)
// { company: "Anthropic", founded: 2021, products: ["Claude", "Claude API"] }
```
@ -175,8 +175,8 @@ Si el modelo no logra producir una salida estructurada válida después de todos
```typescript
if (result.data.info.error?.name === "StructuredOutputError") {
console.error("Failed to produce structured output:", result.data.info.error.message)
console.error("Attempts:", result.data.info.error.retries)
console.error("Failed to produce structured output:", result.data.info.error.data.message)
console.error("Attempts:", result.data.info.error.data.retries)
}
```
@ -313,7 +313,7 @@ const { providers, default: defaults } = await client.config.providers()
| `session.summarize({ path, body })` | Resumir sesión | Devuelve `boolean` |
| `session.messages({ path })` | Listar mensajes en una sesión | Devuelve `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}[]` |
| `session.message({ path })` | Obtener detalles del mensaje | Devuelve `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.prompt({ path, body })` | Enviar mensaje rápido | `body.noReply: true` devuelve UserMessage (solo contexto). El valor predeterminado devuelve <a href={typesUrl}><code>AssistantMessage</code></a> con respuesta de IA. Admite `body.outputFormat` para [salida estructurada](#salida-estructurada) |
| `session.prompt({ path, body })` | Enviar mensaje rápido | `body.noReply: true` devuelve UserMessage (solo contexto). El valor predeterminado devuelve <a href={typesUrl}><code>AssistantMessage</code></a> con respuesta de IA. Admite `body.format` para [salida estructurada](#salida-estructurada) |
| `session.command({ path, body })` | Enviar comando a la sesión | Devuelve `{ info: `<a href={typesUrl}><code>AssistantMessage</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.shell({ path, body })` | Ejecute un comando de shell | Devuelve <a href={typesUrl}><code>AssistantMessage</code></a> |
| `session.revert({ path, body })` | Revertir un mensaje | Devuelve <a href={typesUrl}><code>Session</code></a> |

View file

@ -148,7 +148,7 @@ const result = await client.session.prompt({
})
// Access the structured output
console.log(result.data.info.structured_output)
console.log(result.data.info.structured)
// { company: "Anthropic", founded: 2021, products: ["Claude", "Claude API"] }
```
@ -175,8 +175,8 @@ Si le modèle ne parvient pas à produire une sortie structurée valide après t
```typescript
if (result.data.info.error?.name === "StructuredOutputError") {
console.error("Failed to produce structured output:", result.data.info.error.message)
console.error("Attempts:", result.data.info.error.retries)
console.error("Failed to produce structured output:", result.data.info.error.data.message)
console.error("Attempts:", result.data.info.error.data.retries)
}
```
@ -313,7 +313,7 @@ const { providers, default: defaults } = await client.config.providers()
| `session.summarize({ path, body })` | Résumer la séance | Renvoie `boolean` |
| `session.messages({ path })` | Liste des messages dans une session | Renvoie `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}[]` |
| `session.message({ path })` | Obtenir les détails du message | Renvoie `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.prompt({ path, body })` | Envoyer un message d'invite | `body.noReply: true` renvoie UserMessage (contexte uniquement). La valeur par défaut renvoie <a href={typesUrl}><code>AssistantMessage</code></a> avec réponse IA. Prend en charge `body.outputFormat` pour [sortie structurée](#structured-output) |
| `session.prompt({ path, body })` | Envoyer un message d'invite | `body.noReply: true` renvoie UserMessage (contexte uniquement). La valeur par défaut renvoie <a href={typesUrl}><code>AssistantMessage</code></a> avec réponse IA. Prend en charge `body.format` pour [sortie structurée](#structured-output) |
| `session.command({ path, body })` | Envoyer la commande à la session | Renvoie `{ info: `<a href={typesUrl}><code>AssistantMessage</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.shell({ path, body })` | Exécuter une commande shell | Renvoie <a href={typesUrl}><code>AssistantMessage</code></a> |
| `session.revert({ path, body })` | Rétablir un message | Renvoie <a href={typesUrl}><code>Session</code></a> |

View file

@ -148,7 +148,7 @@ const result = await client.session.prompt({
})
// Access the structured output
console.log(result.data.info.structured_output)
console.log(result.data.info.structured)
// { company: "Anthropic", founded: 2021, products: ["Claude", "Claude API"] }
```
@ -175,8 +175,8 @@ Se il modello non riesce a produrre un output strutturato valido dopo tutti i te
```typescript
if (result.data.info.error?.name === "StructuredOutputError") {
console.error("Failed to produce structured output:", result.data.info.error.message)
console.error("Attempts:", result.data.info.error.retries)
console.error("Failed to produce structured output:", result.data.info.error.data.message)
console.error("Attempts:", result.data.info.error.data.retries)
}
```
@ -313,7 +313,7 @@ const { providers, default: defaults } = await client.config.providers()
| `session.summarize({ path, body })` | Riassume la sessione | Returns `boolean` |
| `session.messages({ path })` | Elenca i messaggi della sessione | Returns `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}[]` |
| `session.message({ path })` | Ottieni dettagli di un messaggio | Returns `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.prompt({ path, body })` | Invia un prompt | `body.noReply: true` returns UserMessage (solo contesto). Di default ritorna <a href={typesUrl}><code>AssistantMessage</code></a> con risposta AI. Supporta `body.outputFormat` per [output strutturato](#output-strutturato) |
| `session.prompt({ path, body })` | Invia un prompt | `body.noReply: true` returns UserMessage (solo contesto). Di default ritorna <a href={typesUrl}><code>AssistantMessage</code></a> con risposta AI. Supporta `body.format` per [output strutturato](#output-strutturato) |
| `session.command({ path, body })` | Invia un comando alla sessione | Returns `{ info: `<a href={typesUrl}><code>AssistantMessage</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.shell({ path, body })` | Esegue un comando shell | Returns <a href={typesUrl}><code>AssistantMessage</code></a> |
| `session.revert({ path, body })` | Ripristina un messaggio | Returns <a href={typesUrl}><code>Session</code></a> |

View file

@ -148,7 +148,7 @@ const result = await client.session.prompt({
})
// Access the structured output
console.log(result.data.info.structured_output)
console.log(result.data.info.structured)
// { company: "Anthropic", founded: 2021, products: ["Claude", "Claude API"] }
```
@ -175,8 +175,8 @@ console.log(result.data.info.structured_output)
```typescript
if (result.data.info.error?.name === "StructuredOutputError") {
console.error("Failed to produce structured output:", result.data.info.error.message)
console.error("Attempts:", result.data.info.error.retries)
console.error("Failed to produce structured output:", result.data.info.error.data.message)
console.error("Attempts:", result.data.info.error.data.retries)
}
```
@ -313,7 +313,7 @@ const { providers, default: defaults } = await client.config.providers()
| `session.summarize({ path, body })` | セッションを要約する | 戻り値 `boolean` |
| `session.messages({ path })` | セッション内のメッセージをリストする | 戻り値 `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}[]` |
| `session.message({ path })` | メッセージの詳細を取得する | 戻り値 `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.prompt({ path, body })` | プロンプトメッセージを送信する | `body.noReply: true` は UserMessage (コンテキストのみ) を返します。デフォルトでは、AI 応答を含む <a href={typesUrl}><code>AssistantMessage</code></a> を返します。[構造化出力](#構造化出力) のための `body.outputFormat` をサポートします。 |
| `session.prompt({ path, body })` | プロンプトメッセージを送信する | `body.noReply: true` は UserMessage (コンテキストのみ) を返します。デフォルトでは、AI 応答を含む <a href={typesUrl}><code>AssistantMessage</code></a> を返します。[構造化出力](#構造化出力) のための `body.format` をサポートします。 |
| `session.command({ path, body })` | コマンドをセッションに送信 | 戻り値 `{ info: `<a href={typesUrl}><code>AssistantMessage</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.shell({ path, body })` | シェルコマンドを実行する | 戻り値 <a href={typesUrl}><code>AssistantMessage</code></a> |
| `session.revert({ path, body })` | メッセージを元に戻す | 戻り値 <a href={typesUrl}><code>Session</code></a> |

View file

@ -148,7 +148,7 @@ const result = await client.session.prompt({
})
// Access the structured output
console.log(result.data.info.structured_output)
console.log(result.data.info.structured)
// { company: "Anthropic", founded: 2021, products: ["Claude", "Claude API"] }
```
@ -175,8 +175,8 @@ console.log(result.data.info.structured_output)
```typescript
if (result.data.info.error?.name === "StructuredOutputError") {
console.error("Failed to produce structured output:", result.data.info.error.message)
console.error("Attempts:", result.data.info.error.retries)
console.error("Failed to produce structured output:", result.data.info.error.data.message)
console.error("Attempts:", result.data.info.error.data.retries)
}
```
@ -313,7 +313,7 @@ const { providers, default: defaults } = await client.config.providers()
| `session.summarize({ path, body })` | 세션 요약 | 반품 `boolean` |
| `session.messages({ path })` | 세션의 메시지 목록 | `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part</code></a>`}[]` |
| `session.message({ path })` | 메시지 상세정보 | 반품 `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.prompt({ path, body })` | prompt 메시지 보내기 | `body.noReply: true`는 UserMessage(컨텍스트 전용)를 반환합니다. 기본값은 AI 응답과 함께 <a href={typesUrl}><code>AssistantMessage</code></a>를 반환합니다. [구조화된 출력](#구조화된-출력)을 위한 `body.outputFormat`을 지원합니다 |
| `session.prompt({ path, body })` | prompt 메시지 보내기 | `body.noReply: true`는 UserMessage(컨텍스트 전용)를 반환합니다. 기본값은 AI 응답과 함께 <a href={typesUrl}><code>AssistantMessage</code></a>를 반환합니다. [구조화된 출력](#구조화된-출력)을 위한 `body.format`을 지원합니다 |
| `session.command({ path, body })` | 세션으로 명령을 전송 | `{ info: `<a href={typesUrl}><code>AssistantMessage</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.shell({ path, body })` | shell 명령을 실행 | <a href={typesUrl}><code>AssistantMessage</code></a> |
| `session.revert({ path, body })` | 메시지 다시 변환 | <a href={typesUrl}><code>Session</code></a> |

View file

@ -148,7 +148,7 @@ const result = await client.session.prompt({
})
// Access the structured output
console.log(result.data.info.structured_output)
console.log(result.data.info.structured)
// { company: "Anthropic", founded: 2021, products: ["Claude", "Claude API"] }
```
@ -175,8 +175,8 @@ Hvis modellen ikke klarer å produsere gyldig strukturert utdata etter alle fors
```typescript
if (result.data.info.error?.name === "StructuredOutputError") {
console.error("Failed to produce structured output:", result.data.info.error.message)
console.error("Attempts:", result.data.info.error.retries)
console.error("Failed to produce structured output:", result.data.info.error.data.message)
console.error("Attempts:", result.data.info.error.data.retries)
}
```
@ -313,7 +313,7 @@ const { providers, default: defaults } = await client.config.providers()
| `session.summarize({ path, body })` | Oppsummer økten | Returnerer `boolean` |
| `session.messages({ path })` | List meldinger i en økt | Returnerer `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}[]` |
| `session.message({ path })` | Hent meldingsdetaljer | Returnerer `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.prompt({ path, body })` | Send melding | `body.noReply: true` returnerer UserMessage (kun kontekst). Standard returnerer <a href={typesUrl}><code>AssistantMessage</code></a> med AI svar. Støtter `body.outputFormat` for [strukturert utdata](#strukturert-utdata) |
| `session.prompt({ path, body })` | Send melding | `body.noReply: true` returnerer UserMessage (kun kontekst). Standard returnerer <a href={typesUrl}><code>AssistantMessage</code></a> med AI svar. Støtter `body.format` for [strukturert utdata](#strukturert-utdata) |
| `session.command({ path, body })` | Send kommando til økt | Returnerer `{ info: `<a href={typesUrl}><code>AssistantMessage</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.shell({ path, body })` | Kjør en shell-kommando | Returnerer <a href={typesUrl}><code>AssistantMessage</code></a> |
| `session.revert({ path, body })` | Tilbakestill en melding | Returnerer <a href={typesUrl}><code>Session</code></a> |

View file

@ -148,7 +148,7 @@ const result = await client.session.prompt({
})
// Access the structured output
console.log(result.data.info.structured_output)
console.log(result.data.info.structured)
// { company: "Anthropic", founded: 2021, products: ["Claude", "Claude API"] }
```
@ -175,8 +175,8 @@ Jeśli model nie wygeneruje prawidłowych ustrukturyzowanych danych wyjściowych
```typescript
if (result.data.info.error?.name === "StructuredOutputError") {
console.error("Failed to produce structured output:", result.data.info.error.message)
console.error("Attempts:", result.data.info.error.retries)
console.error("Failed to produce structured output:", result.data.info.error.data.message)
console.error("Attempts:", result.data.info.error.data.retries)
}
```

View file

@ -148,7 +148,7 @@ const result = await client.session.prompt({
})
// Acessar a saída estruturada
console.log(result.data.info.structured_output)
console.log(result.data.info.structured)
// { company: "Anthropic", founded: 2021, products: ["Claude", "Claude API"] }
```
@ -175,8 +175,8 @@ Se o modelo falhar em produzir uma saída estruturada válida após todas as ten
```typescript
if (result.data.info.error?.name === "StructuredOutputError") {
console.error("Failed to produce structured output:", result.data.info.error.message)
console.error("Attempts:", result.data.info.error.retries)
console.error("Failed to produce structured output:", result.data.info.error.data.message)
console.error("Attempts:", result.data.info.error.data.retries)
}
```
@ -313,7 +313,7 @@ const { providers, default: defaults } = await client.config.providers()
| `session.summarize({ path, body })` | Resumir sessão | Retorna `boolean` |
| `session.messages({ path })` | Listar mensagens em uma sessão | Retorna `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}[]` |
| `session.message({ path })` | Obter detalhes da mensagem | Retorna `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.prompt({ path, body })` | Enviar mensagem de prompt | `body.noReply: true` retorna UserMessage (apenas contexto). O padrão retorna <a href={typesUrl}><code>AssistantMessage</code></a> com resposta da AI. Suporta `body.outputFormat` para [saída estruturada](#saída-estruturada) |
| `session.prompt({ path, body })` | Enviar mensagem de prompt | `body.noReply: true` retorna UserMessage (apenas contexto). O padrão retorna <a href={typesUrl}><code>AssistantMessage</code></a> com resposta da AI. Suporta `body.format` para [saída estruturada](#saída-estruturada) |
| `session.command({ path, body })` | Enviar comando para a sessão | Retorna `{ info: `<a href={typesUrl}><code>AssistantMessage</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.shell({ path, body })` | Executar um comando shell | Retorna <a href={typesUrl}><code>AssistantMessage</code></a> |
| `session.revert({ path, body })` | Reverter uma mensagem | Retorna <a href={typesUrl}><code>Session</code></a> |

View file

@ -148,7 +148,7 @@ const result = await client.session.prompt({
})
// Access the structured output
console.log(result.data.info.structured_output)
console.log(result.data.info.structured)
// { company: "Anthropic", founded: 2021, products: ["Claude", "Claude API"] }
```
@ -175,8 +175,8 @@ console.log(result.data.info.structured_output)
```typescript
if (result.data.info.error?.name === "StructuredOutputError") {
console.error("Failed to produce structured output:", result.data.info.error.message)
console.error("Attempts:", result.data.info.error.retries)
console.error("Failed to produce structured output:", result.data.info.error.data.message)
console.error("Attempts:", result.data.info.error.data.retries)
}
```
@ -313,7 +313,7 @@ const { providers, default: defaults } = await client.config.providers()
| `session.summarize({ path, body })` | Summarize session | Returns `boolean` |
| `session.messages({ path })` | List messages in a session | Returns `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}[]` |
| `session.message({ path })` | Get message details | Returns `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.prompt({ path, body })` | Send prompt message | `body.noReply: true` возвращает UserMessage (только контекст). По умолчанию возвращает <a href={typesUrl}><code>AssistantMessage</code></a> с ответом ИИ. Поддерживает `body.outputFormat` для [структурированного вывода](#структурированный-вывод) |
| `session.prompt({ path, body })` | Send prompt message | `body.noReply: true` возвращает UserMessage (только контекст). По умолчанию возвращает <a href={typesUrl}><code>AssistantMessage</code></a> с ответом ИИ. Поддерживает `body.format` для [структурированного вывода](#структурированный-вывод) |
| `session.command({ path, body })` | Send command to session | Returns `{ info: `<a href={typesUrl}><code>AssistantMessage</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.shell({ path, body })` | Run a shell command | Returns <a href={typesUrl}><code>AssistantMessage</code></a> |
| `session.revert({ path, body })` | Revert a message | Returns <a href={typesUrl}><code>Session</code></a> |

View file

@ -148,7 +148,7 @@ const result = await client.session.prompt({
})
// Access the structured output
console.log(result.data.info.structured_output)
console.log(result.data.info.structured)
// { company: "Anthropic", founded: 2021, products: ["Claude", "Claude API"] }
```
@ -175,8 +175,8 @@ If the model fails to produce valid structured output after all retries, the res
```typescript
if (result.data.info.error?.name === "StructuredOutputError") {
console.error("Failed to produce structured output:", result.data.info.error.message)
console.error("Attempts:", result.data.info.error.retries)
console.error("Failed to produce structured output:", result.data.info.error.data.message)
console.error("Attempts:", result.data.info.error.data.retries)
}
```
@ -313,7 +313,7 @@ const { providers, default: defaults } = await client.config.providers()
| `session.summarize({ path, body })` | Summarize session | Returns `boolean` |
| `session.messages({ path })` | List messages in a session | Returns `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}[]` |
| `session.message({ path })` | Get message details | Returns `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.prompt({ path, body })` | Send prompt message | `body.noReply: true` returns UserMessage (context only). Default returns <a href={typesUrl}><code>AssistantMessage</code></a> with AI response. Supports `body.outputFormat` for [structured output](#structured-output) |
| `session.prompt({ path, body })` | Send prompt message | `body.noReply: true` returns UserMessage (context only). Default returns <a href={typesUrl}><code>AssistantMessage</code></a> with AI response. Supports `body.format` for [structured output](#structured-output) |
| `session.command({ path, body })` | Send command to session | Returns `{ info: `<a href={typesUrl}><code>AssistantMessage</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.shell({ path, body })` | Run a shell command | Returns <a href={typesUrl}><code>AssistantMessage</code></a> |
| `session.revert({ path, body })` | Revert a message | Returns <a href={typesUrl}><code>Session</code></a> |

View file

@ -148,7 +148,7 @@ const result = await client.session.prompt({
})
// Access the structured output
console.log(result.data.info.structured_output)
console.log(result.data.info.structured)
// { company: "Anthropic", founded: 2021, products: ["Claude", "Claude API"] }
```
@ -175,8 +175,8 @@ console.log(result.data.info.structured_output)
```typescript
if (result.data.info.error?.name === "StructuredOutputError") {
console.error("Failed to produce structured output:", result.data.info.error.message)
console.error("Attempts:", result.data.info.error.retries)
console.error("Failed to produce structured output:", result.data.info.error.data.message)
console.error("Attempts:", result.data.info.error.data.retries)
}
```
@ -313,7 +313,7 @@ const { providers, default: defaults } = await client.config.providers()
| `session.summarize({ path, body })` | สรุปเซสชัน | ส่งคืน `boolean` |
| `session.messages({ path })` | แสดงรายการข้อความในเซสชัน | ส่งคืน `{ info: `<a href={typesUrl}><code>ข้อความ</code></a>`, parts: `<a href={typesUrl}><code>ส่วน[]</code></a>`}[]` |
| `session.message({ path })` | รับรายละเอียดข้อความ | ส่งคืน `{ info: `<a href={typesUrl}><code>ข้อความ</code></a>`, parts: `<a href={typesUrl}><code>ส่วน[]</code></a>`}` |
| `session.prompt({ path, body })` | ส่งข้อความแจ้ง | `body.noReply: true` ส่งคืน UserMessage (บริบทเท่านั้น) ค่าเริ่มต้นส่งคืน <a href={typesUrl}><code>AssistantMessage</code></a> พร้อมการตอบสนองของ AI รองรับ `body.outputFormat` สำหรับ [ผลลัพธ์แบบมีโครงสร้าง](#ผลลัพธ์แบบมีโครงสร้าง) |
| `session.prompt({ path, body })` | ส่งข้อความแจ้ง | `body.noReply: true` ส่งคืน UserMessage (บริบทเท่านั้น) ค่าเริ่มต้นส่งคืน <a href={typesUrl}><code>AssistantMessage</code></a> พร้อมการตอบสนองของ AI รองรับ `body.format` สำหรับ [ผลลัพธ์แบบมีโครงสร้าง](#ผลลัพธ์แบบมีโครงสร้าง) |
| `session.command({ path, body })` | ส่งคำสั่งไปยังเซสชั่น | ส่งคืน `{ info: `<a href={typesUrl}><code>AssistantMessage</code></a>`, parts: `<a href={typesUrl}><code>ส่วน[]</code></a>`}` |
| `session.shell({ path, body })` | รันคำสั่ง shell | ส่งคืน <a href={typesUrl}><code>AssistantMessage</code></a> |
| `session.revert({ path, body })` | คืนค่าข้อความ | ส่งคืน <a href={typesUrl}><code>เซสชัน</code></a> |

View file

@ -148,7 +148,7 @@ const result = await client.session.prompt({
})
// Yapılandırılmış çıktıya erişin
console.log(result.data.info.structured_output)
console.log(result.data.info.structured)
// { company: "Anthropic", founded: 2021, products: ["Claude", "Claude API"] }
```
@ -175,8 +175,8 @@ Model, tüm yeniden denemelerden sonra geçerli bir yapılandırılmış çıkt
```typescript
if (result.data.info.error?.name === "StructuredOutputError") {
console.error("Yapılandırılmış çıktı üretilemedi:", result.data.info.error.message)
console.error("Denemeler:", result.data.info.error.retries)
console.error("Yapılandırılmış çıktı üretilemedi:", result.data.info.error.data.message)
console.error("Denemeler:", result.data.info.error.data.retries)
}
```
@ -313,7 +313,7 @@ const { providers, default: defaults } = await client.config.providers()
| `session.summarize({ path, body })` | Oturumu özetle | `boolean` döndürür |
| `session.messages({ path })` | Oturumdaki mesajları listele | `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}[]` döndürür |
| `session.message({ path })` | Mesaj ayrıntılarını al | `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` döndürür |
| `session.prompt({ path, body })` | İstem mesajı gönder | `body.noReply: true` UserMessage (yalnızca bağlam) döndürür. Varsayılan olarak AI yanıtıyla <a href={typesUrl}><code>AssistantMessage</code></a> döndürür. [yapılandırılmış çıktı](#yapılandırılmış-çıktı) için `body.outputFormat` destekler |
| `session.prompt({ path, body })` | İstem mesajı gönder | `body.noReply: true` UserMessage (yalnızca bağlam) döndürür. Varsayılan olarak AI yanıtıyla <a href={typesUrl}><code>AssistantMessage</code></a> döndürür. [yapılandırılmış çıktı](#yapılandırılmış-çıktı) için `body.format` destekler |
| `session.command({ path, body })` | Oturuma komut gönder | `{ info: `<a href={typesUrl}><code>AssistantMessage</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` döndürür |
| `session.shell({ path, body })` | Bir kabuk komutu çalıştır | <a href={typesUrl}><code>AssistantMessage</code></a> döndürür |
| `session.revert({ path, body })` | Bir mesajı geri al | <a href={typesUrl}><code>Session</code></a> döndürür |

View file

@ -148,7 +148,7 @@ const result = await client.session.prompt({
})
// Access the structured output
console.log(result.data.info.structured_output)
console.log(result.data.info.structured)
// { company: "Anthropic", founded: 2021, products: ["Claude", "Claude API"] }
```
@ -175,8 +175,8 @@ console.log(result.data.info.structured_output)
```typescript
if (result.data.info.error?.name === "StructuredOutputError") {
console.error("Failed to produce structured output:", result.data.info.error.message)
console.error("Attempts:", result.data.info.error.retries)
console.error("Failed to produce structured output:", result.data.info.error.data.message)
console.error("Attempts:", result.data.info.error.data.retries)
}
```
@ -313,7 +313,7 @@ const { providers, default: defaults } = await client.config.providers()
| `session.summarize({ path, body })` | 总结会话 | 返回 `boolean` |
| `session.messages({ path })` | 列出会话中的消息 | 返回 `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}[]` |
| `session.message({ path })` | 获取消息详情 | 返回 `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.prompt({ path, body })` | 发送提示词消息 | `body.noReply: true` 返回 UserMessage仅注入上下文。默认返回带有 AI 响应的 <a href={typesUrl}><code>AssistantMessage</code></a>。支持通过 `body.outputFormat` 使用[结构化输出](#结构化输出) |
| `session.prompt({ path, body })` | 发送提示词消息 | `body.noReply: true` 返回 UserMessage仅注入上下文。默认返回带有 AI 响应的 <a href={typesUrl}><code>AssistantMessage</code></a>。支持通过 `body.format` 使用[结构化输出](#结构化输出) |
| `session.command({ path, body })` | 向会话发送命令 | 返回 `{ info: `<a href={typesUrl}><code>AssistantMessage</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.shell({ path, body })` | 执行 shell 命令 | 返回 <a href={typesUrl}><code>AssistantMessage</code></a> |
| `session.revert({ path, body })` | 撤回消息 | 返回 <a href={typesUrl}><code>Session</code></a> |

View file

@ -148,7 +148,7 @@ const result = await client.session.prompt({
})
// Access the structured output
console.log(result.data.info.structured_output)
console.log(result.data.info.structured)
// { company: "Anthropic", founded: 2021, products: ["Claude", "Claude API"] }
```
@ -175,8 +175,8 @@ console.log(result.data.info.structured_output)
```typescript
if (result.data.info.error?.name === "StructuredOutputError") {
console.error("Failed to produce structured output:", result.data.info.error.message)
console.error("Attempts:", result.data.info.error.retries)
console.error("Failed to produce structured output:", result.data.info.error.data.message)
console.error("Attempts:", result.data.info.error.data.retries)
}
```
@ -313,7 +313,7 @@ const { providers, default: defaults } = await client.config.providers()
| `session.summarize({ path, body })` | 摘要工作階段 | 回傳 `boolean` |
| `session.messages({ path })` | 列出工作階段中的訊息 | 回傳 `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}[]` |
| `session.message({ path })` | 取得訊息詳情 | 回傳 `{ info: `<a href={typesUrl}><code>Message</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.prompt({ path, body })` | 傳送提示訊息 | `body.noReply: true` 回傳 UserMessage僅注入上下文。預設回傳帶有 AI 回應的 <a href={typesUrl}><code>AssistantMessage</code></a>。支援透過 `body.outputFormat` 使用[結構化輸出](#結構化輸出) |
| `session.prompt({ path, body })` | 傳送提示訊息 | `body.noReply: true` 回傳 UserMessage僅注入上下文。預設回傳帶有 AI 回應的 <a href={typesUrl}><code>AssistantMessage</code></a>。支援透過 `body.format` 使用[結構化輸出](#結構化輸出) |
| `session.command({ path, body })` | 向工作階段傳送指令 | 回傳 `{ info: `<a href={typesUrl}><code>AssistantMessage</code></a>`, parts: `<a href={typesUrl}><code>Part[]</code></a>`}` |
| `session.shell({ path, body })` | 執行 shell 指令 | 回傳 <a href={typesUrl}><code>AssistantMessage</code></a> |
| `session.revert({ path, body })` | 還原訊息 | 回傳 <a href={typesUrl}><code>Session</code></a> |