@100xprompt/sdk 0.1.130 → 0.1.132

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -46,7 +46,9 @@ await client.session.prompt({
46
46
  server.close()
47
47
  ```
48
48
 
49
- `create100XPrompt()` spawns `100xprompt serve` on `127.0.0.1:4096` and returns a typed client pointed at it.
49
+ `create100XPrompt()` spawns `100xprompt serve` on `127.0.0.1` and returns a typed client pointed at it. The server takes port 4096 when it is free and any free port otherwise; pass `port` to pin one.
50
+
51
+ The server requires a token on every request, on loopback too. `create100XPromptServer` picks a random one (or takes `token`), hands it to the server, and returns it as `server.token`; the client `create100XPrompt()` returns already sends it.
50
52
 
51
53
  ## Server and client separately
52
54
 
@@ -54,7 +56,10 @@ server.close()
54
56
  import { create100XPromptServer, create100XPromptClient } from "@100xprompt/sdk"
55
57
 
56
58
  const server = await create100XPromptServer({ port: 4096 })
57
- const client = create100XPromptClient({ baseUrl: server.url })
59
+ const client = create100XPromptClient({
60
+ baseUrl: server.url,
61
+ headers: { Authorization: `Bearer ${server.token}` },
62
+ })
58
63
 
59
64
  // ... use the client ...
60
65
 
@@ -63,14 +68,14 @@ server.close()
63
68
 
64
69
  ## Connect to an existing server
65
70
 
66
- If a `100xprompt serve` instance is already running — locally or remotely — skip the spawn and point the client at it:
71
+ If a `100xprompt serve` instance is already running — locally or remotely — skip the spawn and point the client at it. `serve` prints the token it requires; set `HUNDREDXPROMPT_SERVER_TOKEN` before starting it to choose the token yourself.
67
72
 
68
73
  ```ts
69
74
  import { create100XPromptClient } from "@100xprompt/sdk/client"
70
75
 
71
76
  const client = create100XPromptClient({
72
77
  baseUrl: "https://your-host.example.com",
73
- headers: { Authorization: `Bearer ${process.env.HUNDREDXPROMPT_TOKEN}` },
78
+ headers: { Authorization: `Bearer ${process.env.HUNDREDXPROMPT_SERVER_TOKEN}` },
74
79
  })
75
80
  ```
76
81
 
package/dist/client.d.ts CHANGED
@@ -1,12 +1,186 @@
1
1
  export * from "./gen/types.gen.js";
2
2
  import { type Config } from "./gen/client/types.gen.js";
3
- import { X100PromptClient as _X100PromptClient, Revert, Oauth, Resource, Control } from "./gen/sdk.gen.js";
3
+ import type { ServerSentEventsResult } from "./gen/core/serverSentEvents.gen.js";
4
+ import type { EventSubscribeResponses } from "./gen/types.gen.js";
5
+ import type { AssistantMessage, Part } from "./gen/types.gen.js";
6
+ import { X100PromptClient as _X100PromptClient, Event as _EventClient, Session as _SessionClient, type Options, Revert, Oauth, Resource, Control } from "./gen/sdk.gen.js";
4
7
  import { type Client } from "./gen/client/index.js";
8
+ /**
9
+ * Options `event.subscribe()` takes on top of the generated SSE options.
10
+ * All durations are milliseconds, like the generated `sseDefaultRetryDelay`.
11
+ */
12
+ export interface X100PromptEventStreamOptions {
13
+ /**
14
+ * A connection that delivers no bytes for this long is treated as dead,
15
+ * dropped and replaced. The server writes a heartbeat every 30 s, so any
16
+ * healthy connection beats this; a half-open one (a laptop that slept, a
17
+ * NAT that forgot the flow) would otherwise sit silent forever.
18
+ * Default 45 000; 0 turns the check off.
19
+ */
20
+ sseLivenessTimeout?: number;
21
+ /**
22
+ * Stop reconnecting after this long without a successful connection; the
23
+ * stream then ends (after `onSseError`). Default 600 000 (10 min); 0 never
24
+ * gives up. `sseMaxRetryAttempts` caps the same run of failures by count.
25
+ */
26
+ sseMaxRetryDuration?: number;
27
+ /** Replaces `setTimeout` for the reconnect backoff (tests). */
28
+ sseSleepFn?: (ms: number) => Promise<void>;
29
+ }
30
+ /**
31
+ * The server refused the event stream with a status that retrying cannot fix
32
+ * (401, 403, 404). Thrown out of the stream's iterator, after `onSseError`.
33
+ */
34
+ export declare class EventStreamRejectedError extends Error {
35
+ readonly status: number;
36
+ readonly url: string;
37
+ name: string;
38
+ constructor(status: number, url: string);
39
+ }
40
+ /**
41
+ * `event.subscribe()` that stays subscribed.
42
+ *
43
+ * The generated SSE client ends its stream for good when the server closes the
44
+ * connection cleanly (a restart, the server's own write-stall guard, a proxy
45
+ * reaping an idle stream), never resets its backoff after a connection that
46
+ * worked, and has no liveness check at all, so a half-open connection is
47
+ * silent forever. Every long-lived consumer had to wrap it (the TUI did); an
48
+ * integrator who did not simply stopped hearing `permission.asked`.
49
+ *
50
+ * Here one generated subscription is ONE connection (`sseMaxRetryAttempts: 1`,
51
+ * so it never sleeps or retries on its own) and this loop owns reconnecting:
52
+ * after any end that the caller's `signal` did not ask for, it reconnects with
53
+ * `Last-Event-ID` (so the server replays what was missed, or sends
54
+ * `server.reset` when it can't — the id is opaque, `<epoch>:<seq>`, and an id
55
+ * from before a server restart or instance rebuild is always answered with a
56
+ * reset, never read as a position in the new stream), backs off exponentially with ±25 % jitter
57
+ * from `sseDefaultRetryDelay`, starts again from that base delay once a
58
+ * connection succeeds, and gives up on 401/403/404 (throws) or after
59
+ * `sseMaxRetryDuration` / `sseMaxRetryAttempts` of failures (ends).
60
+ * `onSseError` hears every drop, clean closes included, so a caller can show
61
+ * "reconnecting".
62
+ */
63
+ declare class EventClient extends _EventClient {
64
+ subscribe<ThrowOnError extends boolean = false>(parameters?: {
65
+ directory?: string;
66
+ }, options?: Options<never, ThrowOnError> & X100PromptEventStreamOptions): Promise<ServerSentEventsResult<EventSubscribeResponses, unknown>>;
67
+ }
68
+ /**
69
+ * The `format` a prompt can carry (`session.prompt`, `session.promptAsync`,
70
+ * `session.promptStructured`): the turn's final answer is a JSON value
71
+ * matching `schema`.
72
+ *
73
+ * How it runs on the server, on every provider: the model is given a
74
+ * `structured_output` tool whose parameters are the schema, each call is
75
+ * validated against the WHOLE schema (types and unions, required,
76
+ * additionalProperties, enum/const, min/max bounds, pattern, format, items and
77
+ * tuples, anyOf/oneOf/allOf, local `$ref`), and a mismatch goes back to the
78
+ * model naming each field to fix. A turn that ends without a valid value is
79
+ * reminded, up to `retries` corrections (default 3, at most 5) in all, and
80
+ * then fails with a `StructuredOutputError` on the assistant message instead
81
+ * of returning prose. The validated value is `info.structured` on the
82
+ * assistant message: in `session.prompt`'s answer, and in the
83
+ * `message.updated` events a `promptAsync` caller reads. A schema the server
84
+ * cannot use is a 400.
85
+ */
86
+ export interface StructuredOutputFormat {
87
+ type: "json_schema";
88
+ /** A JSON Schema object. A root that is not an object (an array, a union) works too. */
89
+ schema: Record<string, unknown>;
90
+ /** Short name of the answer's format, shown to the model. */
91
+ name?: string;
92
+ /** Corrections before the turn fails (default 3, capped at 5). */
93
+ retries?: number;
94
+ }
95
+ /** The answer of a structured prompt: the validated value, typed as the caller says. */
96
+ export interface StructuredPromptResult<T> {
97
+ structured: T;
98
+ info: AssistantMessage;
99
+ parts: Array<Part>;
100
+ }
101
+ /**
102
+ * `session.promptStructured` got no validated value: the model never
103
+ * delivered one through its retries (`error.name === "StructuredOutputError"`),
104
+ * the turn failed for another reason (a provider error, an abort), or the
105
+ * request was refused (`status` 400: a schema the server cannot use).
106
+ */
107
+ export declare class StructuredOutputFailedError extends Error {
108
+ readonly detail: {
109
+ /** The server's error, `{ name, data }`, when it gave one. */
110
+ error?: {
111
+ name?: string;
112
+ data?: unknown;
113
+ };
114
+ /** The turn's last assistant message, when the turn produced one. */
115
+ info?: AssistantMessage;
116
+ parts?: Array<Part>;
117
+ /** HTTP status of a refused request. */
118
+ status?: number;
119
+ /**
120
+ * The transport failure, when the request itself failed: e.g. a
121
+ * ResponseTruncatedError, after which the turn may still have run (read
122
+ * the session's messages back rather than retrying blind).
123
+ */
124
+ cause?: unknown;
125
+ };
126
+ name: string;
127
+ constructor(message: string, detail?: {
128
+ /** The server's error, `{ name, data }`, when it gave one. */
129
+ error?: {
130
+ name?: string;
131
+ data?: unknown;
132
+ };
133
+ /** The turn's last assistant message, when the turn produced one. */
134
+ info?: AssistantMessage;
135
+ parts?: Array<Part>;
136
+ /** HTTP status of a refused request. */
137
+ status?: number;
138
+ /**
139
+ * The transport failure, when the request itself failed: e.g. a
140
+ * ResponseTruncatedError, after which the turn may still have run (read
141
+ * the session's messages back rather than retrying blind).
142
+ */
143
+ cause?: unknown;
144
+ });
145
+ }
146
+ type PromptParameters = Parameters<_SessionClient["prompt"]>[0];
147
+ declare class SessionClient extends _SessionClient {
148
+ /**
149
+ * Send a prompt whose answer is a JSON value matching `format.schema`, and
150
+ * wait for it. Resolves only with a value the server validated against the
151
+ * whole schema; anything else (no answer, a refused request, a transport
152
+ * failure: see `detail`) throws `StructuredOutputFailedError`. `T` is
153
+ * the caller's word for the schema's type (no schema-to-type inference).
154
+ *
155
+ * Works against any server that knows `format`, whether or not this SDK's
156
+ * generated types have caught up: the body is sent as given.
157
+ *
158
+ * @example
159
+ * const { structured } = await client.session.promptStructured<{ title: string; severity: "low" | "high" }>({
160
+ * sessionID,
161
+ * parts: [{ type: "text", text: "Triage the crash in logs/today.txt" }],
162
+ * format: {
163
+ * type: "json_schema",
164
+ * schema: {
165
+ * type: "object",
166
+ * properties: { title: { type: "string" }, severity: { enum: ["low", "high"] } },
167
+ * required: ["title", "severity"],
168
+ * additionalProperties: false,
169
+ * },
170
+ * },
171
+ * })
172
+ */
173
+ promptStructured<T = unknown>(parameters: Omit<PromptParameters, "format"> & {
174
+ format: StructuredOutputFormat;
175
+ }, options?: Omit<Options<never, false>, "throwOnError">): Promise<StructuredPromptResult<T>>;
176
+ }
5
177
  export declare class X100PromptClient extends _X100PromptClient {
6
178
  revert: Revert;
7
179
  oauth: Oauth;
8
180
  resource: Resource;
9
181
  control: Control;
182
+ event: EventClient;
183
+ session: SessionClient;
10
184
  constructor(args?: {
11
185
  client?: Client;
12
186
  key?: string;
@@ -20,7 +194,7 @@ export { type Config as X100PromptClientConfig, Revert, Oauth, Resource, Control
20
194
  * straight into the frame and corrupts it.
21
195
  */
22
196
  export interface X100PromptClientDiagnostic {
23
- /** A 2xx response whose body was empty or truncated; a default was returned. */
197
+ /** A 2xx response whose body was empty; a default was returned. */
24
198
  kind: "empty-response-body";
25
199
  /** Human-readable, already formatted for a log line. */
26
200
  message: string;
@@ -35,6 +209,31 @@ export interface X100PromptClientDiagnostic {
35
209
  cause: Error;
36
210
  }
37
211
  export type X100PromptClientDiagnosticHandler = (diagnostic: X100PromptClientDiagnostic) => void;
212
+ /**
213
+ * A 2xx response whose body broke off before it was complete: the connection
214
+ * died mid-body (a proxy idle timeout, a server restart, Node's 300 s
215
+ * `bodyTimeout` on a long `session.prompt()`). The request DID run, so the
216
+ * result is lost, not absent; read it back (e.g. `session.messages()`) rather
217
+ * than retrying blind. For turns that can run for minutes, `prompt_async` plus
218
+ * the event stream's `session.idle` never holds a response open at all.
219
+ */
220
+ export declare class ResponseTruncatedError extends Error {
221
+ readonly url: string;
222
+ readonly status: number;
223
+ name: string;
224
+ constructor(url: string, status: number, options: {
225
+ cause: unknown;
226
+ });
227
+ }
228
+ /** A response body that arrived whole but is not the JSON its content type promised. */
229
+ export declare class ResponseParseError extends Error {
230
+ readonly url: string;
231
+ readonly status: number;
232
+ name: string;
233
+ constructor(url: string, status: number, parseAs: string, options: {
234
+ cause: unknown;
235
+ });
236
+ }
38
237
  /**
39
238
  * Install the process-wide sink for client diagnostics, for hosts that build
40
239
  * clients in several places (the CLI wires this to its file logger once at
package/dist/client.js CHANGED
@@ -1,6 +1,254 @@
1
1
  export * from "./gen/types.gen.js";
2
2
  import { createClient } from "./gen/client/client.gen.js";
3
- import { X100PromptClient as _X100PromptClient, Revert, Oauth, Resource, Control, } from "./gen/sdk.gen.js";
3
+ import { mergeHeaders } from "./gen/client/utils.gen.js";
4
+ import { X100PromptClient as _X100PromptClient, Event as _EventClient, Session as _SessionClient, Revert, Oauth, Resource, Control, } from "./gen/sdk.gen.js";
5
+ /**
6
+ * The server refused the event stream with a status that retrying cannot fix
7
+ * (401, 403, 404). Thrown out of the stream's iterator, after `onSseError`.
8
+ */
9
+ export class EventStreamRejectedError extends Error {
10
+ status;
11
+ url;
12
+ name = "EventStreamRejectedError";
13
+ constructor(status, url) {
14
+ super(`the server refused the event stream from ${url} (status ${status}); not reconnecting`);
15
+ this.status = status;
16
+ this.url = url;
17
+ }
18
+ }
19
+ /** Statuses a reconnect cannot fix: bad credentials, no access, no such route. */
20
+ const PERMANENT_EVENT_STREAM_STATUS = new Set([401, 403, 404]);
21
+ const DEFAULT_LIVENESS_TIMEOUT = 45_000;
22
+ const DEFAULT_MAX_RETRY_DURATION = 600_000;
23
+ /**
24
+ * `event.subscribe()` that stays subscribed.
25
+ *
26
+ * The generated SSE client ends its stream for good when the server closes the
27
+ * connection cleanly (a restart, the server's own write-stall guard, a proxy
28
+ * reaping an idle stream), never resets its backoff after a connection that
29
+ * worked, and has no liveness check at all, so a half-open connection is
30
+ * silent forever. Every long-lived consumer had to wrap it (the TUI did); an
31
+ * integrator who did not simply stopped hearing `permission.asked`.
32
+ *
33
+ * Here one generated subscription is ONE connection (`sseMaxRetryAttempts: 1`,
34
+ * so it never sleeps or retries on its own) and this loop owns reconnecting:
35
+ * after any end that the caller's `signal` did not ask for, it reconnects with
36
+ * `Last-Event-ID` (so the server replays what was missed, or sends
37
+ * `server.reset` when it can't — the id is opaque, `<epoch>:<seq>`, and an id
38
+ * from before a server restart or instance rebuild is always answered with a
39
+ * reset, never read as a position in the new stream), backs off exponentially with ±25 % jitter
40
+ * from `sseDefaultRetryDelay`, starts again from that base delay once a
41
+ * connection succeeds, and gives up on 401/403/404 (throws) or after
42
+ * `sseMaxRetryDuration` / `sseMaxRetryAttempts` of failures (ends).
43
+ * `onSseError` hears every drop, clean closes included, so a caller can show
44
+ * "reconnecting".
45
+ */
46
+ class EventClient extends _EventClient {
47
+ subscribe(parameters, options) {
48
+ const connect = (once) => super.subscribe(parameters, once);
49
+ const caller = options?.signal ?? undefined;
50
+ const baseFetch = options?.fetch ?? this.client.getConfig().fetch ?? globalThis.fetch;
51
+ const sleep = options?.sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
52
+ const baseDelay = options?.sseDefaultRetryDelay ?? 3000;
53
+ const maxDelay = options?.sseMaxRetryDelay ?? 30_000;
54
+ const maxFailures = options?.sseMaxRetryAttempts;
55
+ const liveness = options?.sseLivenessTimeout ?? DEFAULT_LIVENESS_TIMEOUT;
56
+ const giveUpAfter = options?.sseMaxRetryDuration ?? DEFAULT_MAX_RETRY_DURATION;
57
+ async function* stream() {
58
+ let lastEventID;
59
+ // Reconnects since the last connection that worked (drives the backoff),
60
+ // and of those, the attempts that never got a response (drives giving up).
61
+ let attempts = 0;
62
+ let failures = 0;
63
+ let failingSince;
64
+ while (!caller?.aborted) {
65
+ const attempt = new AbortController();
66
+ const forward = () => attempt.abort(caller?.reason);
67
+ caller?.addEventListener("abort", forward, { once: true });
68
+ let status;
69
+ let url = "";
70
+ let connected = false;
71
+ let silent = false;
72
+ let failure;
73
+ let timer;
74
+ // Any byte counts, heartbeats included: a big frame arriving slowly
75
+ // is still a live connection.
76
+ const touch = () => {
77
+ if (!liveness)
78
+ return;
79
+ if (timer)
80
+ clearTimeout(timer);
81
+ timer = setTimeout(() => {
82
+ silent = true;
83
+ attempt.abort();
84
+ }, liveness);
85
+ };
86
+ const fetchOnce = async (request) => {
87
+ url = request.url;
88
+ const response = await baseFetch(request);
89
+ status = response.status;
90
+ if (!response.ok || !response.body)
91
+ return response;
92
+ connected = true;
93
+ touch();
94
+ const body = response.body.pipeThrough(new TransformStream({
95
+ transform(chunk, controller) {
96
+ touch();
97
+ controller.enqueue(chunk);
98
+ },
99
+ }));
100
+ return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
101
+ };
102
+ try {
103
+ const result = await connect({
104
+ ...options,
105
+ ...(lastEventID !== undefined
106
+ ? { headers: mergeHeaders(options?.headers, { "Last-Event-ID": lastEventID }) }
107
+ : {}),
108
+ signal: attempt.signal,
109
+ fetch: fetchOnce,
110
+ sseMaxRetryAttempts: 1,
111
+ onSseError: (error) => {
112
+ failure = error;
113
+ },
114
+ onSseEvent: (event) => {
115
+ if (event.id !== undefined)
116
+ lastEventID = event.id;
117
+ options?.onSseEvent?.(event);
118
+ },
119
+ });
120
+ for await (const event of result.stream)
121
+ yield event;
122
+ }
123
+ catch (error) {
124
+ failure = error;
125
+ }
126
+ finally {
127
+ if (timer)
128
+ clearTimeout(timer);
129
+ caller?.removeEventListener("abort", forward);
130
+ // Also the path a consumer's `break` takes: close this connection
131
+ // instead of leaving its body unread on the socket.
132
+ attempt.abort();
133
+ }
134
+ if (caller?.aborted)
135
+ return;
136
+ if (status !== undefined && PERMANENT_EVENT_STREAM_STATUS.has(status)) {
137
+ const rejected = new EventStreamRejectedError(status, url);
138
+ options?.onSseError?.(rejected);
139
+ throw rejected;
140
+ }
141
+ options?.onSseError?.(silent
142
+ ? new Error(`event stream sent nothing for ${liveness} ms; reconnecting`)
143
+ : (failure ?? new Error("event stream closed by the server; reconnecting")));
144
+ if (connected) {
145
+ attempts = 0;
146
+ failures = 0;
147
+ failingSince = undefined;
148
+ }
149
+ else {
150
+ failures++;
151
+ failingSince ??= Date.now();
152
+ }
153
+ if (maxFailures !== undefined && failures >= maxFailures)
154
+ return;
155
+ if (giveUpAfter > 0 && failingSince !== undefined && Date.now() - failingSince >= giveUpAfter)
156
+ return;
157
+ attempts++;
158
+ const backoff = Math.min(baseDelay * 2 ** (attempts - 1), maxDelay);
159
+ const delay = backoff + backoff * 0.25 * (2 * Math.random() - 1);
160
+ // An abort during the wait ends the stream now, not after the delay.
161
+ await new Promise((resolve) => {
162
+ if (caller?.aborted)
163
+ return resolve();
164
+ const done = () => {
165
+ caller?.removeEventListener("abort", done);
166
+ resolve();
167
+ };
168
+ caller?.addEventListener("abort", done, { once: true });
169
+ sleep(delay).then(done, done);
170
+ });
171
+ }
172
+ }
173
+ return Promise.resolve({ stream: stream() });
174
+ }
175
+ }
176
+ /**
177
+ * `session.promptStructured` got no validated value: the model never
178
+ * delivered one through its retries (`error.name === "StructuredOutputError"`),
179
+ * the turn failed for another reason (a provider error, an abort), or the
180
+ * request was refused (`status` 400: a schema the server cannot use).
181
+ */
182
+ export class StructuredOutputFailedError extends Error {
183
+ detail;
184
+ name = "StructuredOutputFailedError";
185
+ constructor(message, detail = {}) {
186
+ super(message, detail.cause !== undefined ? { cause: detail.cause } : undefined);
187
+ this.detail = detail;
188
+ }
189
+ }
190
+ class SessionClient extends _SessionClient {
191
+ /**
192
+ * Send a prompt whose answer is a JSON value matching `format.schema`, and
193
+ * wait for it. Resolves only with a value the server validated against the
194
+ * whole schema; anything else (no answer, a refused request, a transport
195
+ * failure: see `detail`) throws `StructuredOutputFailedError`. `T` is
196
+ * the caller's word for the schema's type (no schema-to-type inference).
197
+ *
198
+ * Works against any server that knows `format`, whether or not this SDK's
199
+ * generated types have caught up: the body is sent as given.
200
+ *
201
+ * @example
202
+ * const { structured } = await client.session.promptStructured<{ title: string; severity: "low" | "high" }>({
203
+ * sessionID,
204
+ * parts: [{ type: "text", text: "Triage the crash in logs/today.txt" }],
205
+ * format: {
206
+ * type: "json_schema",
207
+ * schema: {
208
+ * type: "object",
209
+ * properties: { title: { type: "string" }, severity: { enum: ["low", "high"] } },
210
+ * required: ["title", "severity"],
211
+ * additionalProperties: false,
212
+ * },
213
+ * },
214
+ * })
215
+ */
216
+ async promptStructured(parameters, options) {
217
+ const { sessionID, directory, ...body } = parameters;
218
+ const result = await this.client
219
+ .post({
220
+ url: "/session/{sessionID}/message",
221
+ ...options,
222
+ path: { sessionID },
223
+ ...(directory !== undefined ? { query: { directory } } : {}),
224
+ body,
225
+ headers: { "Content-Type": "application/json", ...options?.headers },
226
+ })
227
+ .catch((cause) => {
228
+ // One error type for every way of getting no answer, as documented.
229
+ throw new StructuredOutputFailedError(`the structured prompt failed in transport: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
230
+ });
231
+ // No response at all: the client hands a failed fetch back as `error`.
232
+ if (result.error !== undefined && !result.response) {
233
+ const cause = result.error;
234
+ throw new StructuredOutputFailedError(`the structured prompt failed in transport: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
235
+ }
236
+ if (result.error !== undefined) {
237
+ const error = result.error;
238
+ throw new StructuredOutputFailedError(`the structured prompt was refused (status ${result.response?.status}): ${error.data?.message ?? error.message ?? JSON.stringify(error)}`, { error, status: result.response?.status });
239
+ }
240
+ // The route answers 200 even for a turn that never reached an assistant
241
+ // message (`{}`, or `{ error }`): see the server's /message handler.
242
+ const data = (result.data ?? {});
243
+ const info = data.info;
244
+ const parts = data.parts ?? [];
245
+ if (info && info.structured !== undefined && !info.error)
246
+ return { structured: info.structured, info, parts };
247
+ const error = info?.error ?? data.error;
248
+ const reason = error?.data?.message ?? error?.name;
249
+ throw new StructuredOutputFailedError(reason ? `no structured answer: ${reason}` : "no structured answer: the turn ended without one", { error, info, parts });
250
+ }
251
+ }
4
252
  export class X100PromptClient extends _X100PromptClient {
5
253
  revert;
6
254
  oauth;
@@ -8,6 +256,8 @@ export class X100PromptClient extends _X100PromptClient {
8
256
  control;
9
257
  constructor(args) {
10
258
  super(args);
259
+ this.event = new EventClient({ client: this.client });
260
+ this.session = new SessionClient({ client: this.client });
11
261
  this.revert = new Revert(args);
12
262
  this.oauth = new Oauth(args);
13
263
  this.resource = new Resource(args);
@@ -18,6 +268,35 @@ export class X100PromptClient extends _X100PromptClient {
18
268
  }
19
269
  }
20
270
  export { Revert, Oauth, Resource, Control };
271
+ /**
272
+ * A 2xx response whose body broke off before it was complete: the connection
273
+ * died mid-body (a proxy idle timeout, a server restart, Node's 300 s
274
+ * `bodyTimeout` on a long `session.prompt()`). The request DID run, so the
275
+ * result is lost, not absent; read it back (e.g. `session.messages()`) rather
276
+ * than retrying blind. For turns that can run for minutes, `prompt_async` plus
277
+ * the event stream's `session.idle` never holds a response open at all.
278
+ */
279
+ export class ResponseTruncatedError extends Error {
280
+ url;
281
+ status;
282
+ name = "ResponseTruncatedError";
283
+ constructor(url, status, options) {
284
+ super(`the response body from ${url} (status ${status}) was cut off: ${options.cause instanceof Error ? options.cause.message : String(options.cause)}`, options);
285
+ this.url = url;
286
+ this.status = status;
287
+ }
288
+ }
289
+ /** A response body that arrived whole but is not the JSON its content type promised. */
290
+ export class ResponseParseError extends Error {
291
+ url;
292
+ status;
293
+ name = "ResponseParseError";
294
+ constructor(url, status, parseAs, options) {
295
+ super(`Failed to parse ${parseAs} from ${url} (status ${status}): ${options.cause instanceof Error ? options.cause.message : String(options.cause)}`, options);
296
+ this.url = url;
297
+ this.status = status;
298
+ }
299
+ }
21
300
  let defaultDiagnosticHandler;
22
301
  /**
23
302
  * Install the process-wide sink for client diagnostics, for hosts that build
@@ -55,45 +334,52 @@ export function create100XPromptClient(config) {
55
334
  // worker). The Request always knows where it was going.
56
335
  const requestUrl = request.url;
57
336
  const response = await originalFetch(request);
58
- const wrapParser = (parser, parseType) => {
59
- return async () => {
60
- try {
61
- return await parser();
337
+ // The body is read as text first, so a failure is always attributable:
338
+ // reading it failed (the transport), or it arrived and does not parse.
339
+ // Telling them apart by error message used to lump undici's `terminated`
340
+ // (Node: the socket died mid-body) in with an empty body, so a
341
+ // `session.prompt()` whose long-poll was cut off resolved `{}` on Node,
342
+ // while Bun, wording the same failure differently, threw.
343
+ const readBody = async (parseAs) => {
344
+ let text;
345
+ try {
346
+ text = await response.text();
347
+ }
348
+ catch (e) {
349
+ // Case 1: Request was intentionally aborted — surface a clean AbortError
350
+ if (signal?.aborted) {
351
+ const abortError = new Error("The operation was aborted");
352
+ abortError.name = "AbortError";
353
+ throw abortError;
62
354
  }
63
- catch (e) {
64
- if (e instanceof Error &&
65
- (e.message.includes("Unexpected end of JSON input") ||
66
- e.message.includes("terminated") ||
67
- e.message.includes("JSON"))) {
68
- // Case 1: Request was intentionally aborted — surface a clean AbortError
69
- if (signal?.aborted) {
70
- const abortError = new Error("The operation was aborted");
71
- abortError.name = "AbortError";
72
- throw abortError;
73
- }
74
- // Case 2: Server returned empty/truncated body on a success response
75
- // Return safe defaults instead of crashing
76
- if (response.ok) {
77
- const parseAs = parseType === "text" ? "text" : "json";
78
- report({
79
- kind: "empty-response-body",
80
- message: `empty or malformed response body from ${requestUrl} (status ${response.status}); ` +
81
- `returning empty ${parseAs === "text" ? "string" : "object"}`,
82
- url: requestUrl,
83
- status: response.status,
84
- parseAs,
85
- cause: e,
86
- });
87
- return parseAs === "text" ? "" : {};
88
- }
89
- // Case 3: Error response with unparseable body — wrap with context
90
- const wrappedError = new Error(`Failed to parse ${parseType ?? "response"} from ${requestUrl} (status ${response.status}): ${e.message}`);
91
- wrappedError.name = "ResponseParseError";
92
- throw wrappedError;
93
- }
94
- throw e;
355
+ // Case 2: the body broke off. On a success the request ran and its
356
+ // result is gone, which must not read as an empty answer.
357
+ if (response.ok)
358
+ throw new ResponseTruncatedError(requestUrl, response.status, { cause: e });
359
+ throw new ResponseParseError(requestUrl, response.status, parseAs, { cause: e });
360
+ }
361
+ if (parseAs === "text")
362
+ return text;
363
+ try {
364
+ return JSON.parse(text);
365
+ }
366
+ catch (e) {
367
+ // Case 3: a success with an EMPTY body (the TUI's worker bridge builds
368
+ // such responses) — return a safe default instead of crashing.
369
+ if (response.ok && text.trim() === "") {
370
+ report({
371
+ kind: "empty-response-body",
372
+ message: `empty response body from ${requestUrl} (status ${response.status}); returning empty object`,
373
+ url: requestUrl,
374
+ status: response.status,
375
+ parseAs,
376
+ cause: e instanceof Error ? e : new Error(String(e)),
377
+ });
378
+ return {};
95
379
  }
96
- };
380
+ // Case 4: a body that arrived whole and is not JSON — wrap with context
381
+ throw new ResponseParseError(requestUrl, response.status, parseAs, { cause: e });
382
+ }
97
383
  };
98
384
  // Proxy the response to wrap json() and text()
99
385
  return new Proxy(response, {
@@ -103,13 +389,11 @@ export function create100XPromptClient(config) {
103
389
  // of the empty string a hand-built Response reports.
104
390
  if (prop === "url" && !target.url)
105
391
  return requestUrl;
392
+ if (prop === "json" || prop === "text")
393
+ return () => readBody(prop);
106
394
  const value = target[prop];
107
- if (typeof value === "function") {
108
- if (prop === "json" || prop === "text") {
109
- return wrapParser(value.bind(target), prop);
110
- }
395
+ if (typeof value === "function")
111
396
  return value.bind(target);
112
- }
113
397
  return value;
114
398
  },
115
399
  });
@@ -1,5 +1,5 @@
1
1
  import { type Client, type Options as Options2, type TDataShape } from "./client/index.js";
2
- import type { AgentPartInput, AppAgentsResponses, AppLogErrors, AppLogResponses, Auth as Auth2, AuthSetErrors, AuthSetResponses, CommandListResponses, Config as Config2, ConfigGetResponses, ConfigProvidersResponses, ConfigUpdateErrors, ConfigUpdateResponses, EventSubscribeResponses, EventTuiCommandExecute, EventTuiPromptAppend, EventTuiSessionSelect, EventTuiToastShow, ExperimentalResourceListResponses, FileListResponses, FilePartInput, FilePartSource, FileReadResponses, FileStatusResponses, FindFilesResponses, FindSymbolsResponses, FindTextResponses, FormatterStatusResponses, GlobalDisposeResponses, GlobalEventResponses, GlobalHealthResponses, InstanceDisposeResponses, LspStatusResponses, McpAddErrors, McpAddResponses, McpAuthAuthenticateErrors, McpAuthAuthenticateResponses, McpAuthCallbackErrors, McpAuthCallbackResponses, McpAuthRemoveErrors, McpAuthRemoveResponses, McpAuthStartErrors, McpAuthStartResponses, McpConnectErrors, McpConnectResponses, McpDisconnectResponses, McpLocalConfig, McpRemoteConfig, McpStatusResponses, Part as Part2, PartDeleteErrors, PartDeleteResponses, PartUpdateErrors, PartUpdateResponses, PathGetResponses, PermissionListResponses, PermissionMode, PermissionReplyErrors, PermissionReplyResponses, PermissionRespondErrors, PermissionRespondResponses, PermissionRuleset, PluginDiscoverResponses, PluginErrorsResponses, PluginInstalledResponses, PluginInstallErrors, PluginInstallNamedErrors, PluginInstallNamedResponses, PluginInstallResponses, PluginMarketplaceAddResponses, PluginMarketplaceRemoveResponses, PluginMarketplacesResponses, PluginReloadResponses, PluginRemoveResponses, PluginSetEnabledResponses, ProjectCurrentResponses, ProjectListResponses, ProjectUpdateErrors, ProjectUpdateResponses, ProviderAuthResponses, ProviderListResponses, ProviderOauthAuthorizeErrors, ProviderOauthAuthorizeResponses, ProviderOauthCallbackErrors, ProviderOauthCallbackResponses, PtyConnectErrors, PtyConnectResponses, PtyCreateErrors, PtyCreateResponses, PtyGetErrors, PtyGetResponses, PtyListResponses, PtyRemoveErrors, PtyRemoveResponses, PtyUpdateErrors, PtyUpdateResponses, QuestionAnswer, QuestionListResponses, QuestionRejectErrors, QuestionRejectResponses, QuestionReplyErrors, QuestionReplyResponses, RemoteBridgeConnectResponses, RemoteBridgeDevicesResponses, RemoteBridgeEnrollResponses, RemoteBridgeRevokeResponses, SessionAbortErrors, SessionAbortResponses, SessionChildrenErrors, SessionChildrenResponses, SessionCommandErrors, SessionCommandResponses, SessionCreateErrors, SessionCreateResponses, SessionDeleteErrors, SessionDeleteResponses, SessionDiffErrors, SessionDiffResponses, SessionFeedbackErrors, SessionFeedbackResponses, SessionForkResponses, SessionGetErrors, SessionGetResponses, SessionInitErrors, SessionInitResponses, SessionListResponses, SessionMessageErrors, SessionMessageResponses, SessionMessagesErrors, SessionMessagesResponses, SessionPromptAsyncErrors, SessionPromptAsyncResponses, SessionPromptErrors, SessionPromptResponses, SessionRevertErrors, SessionRevertPreviewErrors, SessionRevertPreviewResponses, SessionRevertResponses, SessionShareErrors, SessionShareResponses, SessionShellErrors, SessionShellResponses, SessionStatusErrors, SessionStatusResponses, SessionSummarizeErrors, SessionSummarizeResponses, SessionTodoErrors, SessionTodoResponses, SessionUnrevertErrors, SessionUnrevertResponses, SessionUnshareErrors, SessionUnshareResponses, SessionUpdateErrors, SessionUpdateResponses, SubtaskPartInput, TextPartInput, ToolIdsErrors, ToolIdsResponses, ToolListErrors, ToolListResponses, TrustAlwaysResponses, TrustOnceResponses, TrustStatusResponses, TuiAppendPromptErrors, TuiAppendPromptResponses, TuiClearPromptResponses, TuiControlNextResponses, TuiControlResponseResponses, TuiExecuteCommandErrors, TuiExecuteCommandResponses, TuiOpenHelpResponses, TuiOpenModelsResponses, TuiOpenSessionsResponses, TuiOpenThemesResponses, TuiPublishErrors, TuiPublishResponses, TuiSelectSessionErrors, TuiSelectSessionResponses, TuiShowToastResponses, TuiSubmitPromptResponses, VcsGetResponses, WorktreeCreateErrors, WorktreeCreateInput, WorktreeCreateResponses, WorktreeListResponses } from "./types.gen.js";
2
+ import type { AgentPartInput, AppAgentsResponses, AppLogErrors, AppLogResponses, Auth as Auth2, AuthSetErrors, AuthSetResponses, CommandListResponses, Config as Config2, ConfigGetResponses, ConfigProvidersResponses, ConfigUpdateErrors, ConfigUpdateResponses, EventSubscribeResponses, EventTuiCommandExecute, EventTuiPromptAppend, EventTuiSessionSelect, EventTuiToastShow, ExperimentalResourceListResponses, FileListResponses, FilePartInput, FilePartSource, FileReadResponses, FileStatusResponses, FindFilesResponses, FindSymbolsResponses, FindTextResponses, FormatterStatusResponses, GlobalDisposeResponses, GlobalEventResponses, GlobalHealthResponses, InstanceDisposeResponses, LspStatusResponses, McpAddErrors, McpAddResponses, McpAuthAuthenticateErrors, McpAuthAuthenticateResponses, McpAuthCallbackErrors, McpAuthCallbackResponses, McpAuthRemoveErrors, McpAuthRemoveResponses, McpAuthStartErrors, McpAuthStartResponses, McpConnectErrors, McpConnectResponses, McpDisconnectResponses, McpLocalConfig, McpRemoteConfig, McpStatusResponses, OutputFormat, Part as Part2, PartDeleteErrors, PartDeleteResponses, PartUpdateErrors, PartUpdateResponses, PathGetResponses, PermissionListResponses, PermissionMode, PermissionReplyErrors, PermissionReplyResponses, PermissionRespondErrors, PermissionRespondResponses, PermissionRuleset, PluginDiscoverResponses, PluginErrorsResponses, PluginInstalledResponses, PluginInstallErrors, PluginInstallNamedErrors, PluginInstallNamedResponses, PluginInstallResponses, PluginMarketplaceAddResponses, PluginMarketplaceRemoveResponses, PluginMarketplacesResponses, PluginReloadResponses, PluginRemoveResponses, PluginSetEnabledResponses, ProjectCurrentResponses, ProjectListResponses, ProjectUpdateErrors, ProjectUpdateResponses, ProviderAuthResponses, ProviderListResponses, ProviderOauthAuthorizeErrors, ProviderOauthAuthorizeResponses, ProviderOauthCallbackErrors, ProviderOauthCallbackResponses, PtyConnectErrors, PtyConnectResponses, PtyCreateErrors, PtyCreateResponses, PtyGetErrors, PtyGetResponses, PtyListResponses, PtyRemoveErrors, PtyRemoveResponses, PtyUpdateErrors, PtyUpdateResponses, QuestionAnswer, QuestionListResponses, QuestionRejectErrors, QuestionRejectResponses, QuestionReplyErrors, QuestionReplyResponses, RemoteBridgeConnectResponses, RemoteBridgeDevicesResponses, RemoteBridgeEnrollResponses, RemoteBridgeRevokeResponses, SessionAbortErrors, SessionAbortResponses, SessionChildrenErrors, SessionChildrenResponses, SessionCommandErrors, SessionCommandResponses, SessionCreateErrors, SessionCreateResponses, SessionDeleteErrors, SessionDeleteResponses, SessionDiffErrors, SessionDiffResponses, SessionFeedbackErrors, SessionFeedbackResponses, SessionForkResponses, SessionGetErrors, SessionGetResponses, SessionInitErrors, SessionInitResponses, SessionListResponses, SessionMessageErrors, SessionMessageResponses, SessionMessagesErrors, SessionMessagesResponses, SessionPromptAsyncErrors, SessionPromptAsyncResponses, SessionPromptErrors, SessionPromptResponses, SessionRevertErrors, SessionRevertPreviewErrors, SessionRevertPreviewResponses, SessionRevertResponses, SessionShareErrors, SessionShareResponses, SessionShellErrors, SessionShellResponses, SessionStatusErrors, SessionStatusResponses, SessionSummarizeErrors, SessionSummarizeResponses, SessionTodoErrors, SessionTodoResponses, SessionUnrevertErrors, SessionUnrevertResponses, SessionUnshareErrors, SessionUnshareResponses, SessionUpdateErrors, SessionUpdateResponses, SubtaskPartInput, TextPartInput, ToolIdsErrors, ToolIdsResponses, ToolListErrors, ToolListResponses, TrustAlwaysResponses, TrustOnceResponses, TrustStatusResponses, TuiAppendPromptErrors, TuiAppendPromptResponses, TuiClearPromptResponses, TuiControlNextResponses, TuiControlResponseResponses, TuiExecuteCommandErrors, TuiExecuteCommandResponses, TuiOpenHelpResponses, TuiOpenModelsResponses, TuiOpenSessionsResponses, TuiOpenThemesResponses, TuiPublishErrors, TuiPublishResponses, TuiSelectSessionErrors, TuiSelectSessionResponses, TuiShowToastResponses, TuiSubmitPromptResponses, VcsGetResponses, WorktreeCreateErrors, WorktreeCreateInput, WorktreeCreateResponses, WorktreeListResponses } from "./types.gen.js";
3
3
  export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean> = Options2<TData, ThrowOnError> & {
4
4
  /**
5
5
  * You can provide a client instance returned by `createClient()` instead of
@@ -571,6 +571,7 @@ export declare class Session extends HeyApiClient {
571
571
  system?: string;
572
572
  systemOverride?: string;
573
573
  variant?: string;
574
+ format?: OutputFormat;
574
575
  kairos?: boolean;
575
576
  terminalFocus?: boolean;
576
577
  parts?: Array<TextPartInput | FilePartInput | AgentPartInput | SubtaskPartInput>;
@@ -606,6 +607,7 @@ export declare class Session extends HeyApiClient {
606
607
  system?: string;
607
608
  systemOverride?: string;
608
609
  variant?: string;
610
+ format?: OutputFormat;
609
611
  kairos?: boolean;
610
612
  terminalFocus?: boolean;
611
613
  parts?: Array<TextPartInput | FilePartInput | AgentPartInput | SubtaskPartInput>;
@@ -1125,6 +1125,7 @@ export class Session extends HeyApiClient {
1125
1125
  { in: "body", key: "system" },
1126
1126
  { in: "body", key: "systemOverride" },
1127
1127
  { in: "body", key: "variant" },
1128
+ { in: "body", key: "format" },
1128
1129
  { in: "body", key: "kairos" },
1129
1130
  { in: "body", key: "terminalFocus" },
1130
1131
  { in: "body", key: "parts" },
@@ -1182,6 +1183,7 @@ export class Session extends HeyApiClient {
1182
1183
  { in: "body", key: "system" },
1183
1184
  { in: "body", key: "systemOverride" },
1184
1185
  { in: "body", key: "variant" },
1186
+ { in: "body", key: "format" },
1185
1187
  { in: "body", key: "kairos" },
1186
1188
  { in: "body", key: "terminalFocus" },
1187
1189
  { in: "body", key: "parts" },
@@ -212,6 +212,23 @@ export type FileDiff = {
212
212
  additions: number;
213
213
  deletions: number;
214
214
  };
215
+ export type OutputFormat = {
216
+ type: "json_schema";
217
+ /**
218
+ * JSON Schema the final answer must match
219
+ */
220
+ schema: {
221
+ [key: string]: unknown;
222
+ };
223
+ /**
224
+ * Short name of the answer's format, shown to the model
225
+ */
226
+ name?: string;
227
+ /**
228
+ * Corrections allowed before the turn fails with StructuredOutputError (default 3, capped at 5)
229
+ */
230
+ retries?: number;
231
+ };
215
232
  export type UserMessage = {
216
233
  id: string;
217
234
  sessionID: string;
@@ -235,6 +252,7 @@ export type UserMessage = {
235
252
  [key: string]: boolean;
236
253
  };
237
254
  variant?: string;
255
+ format?: OutputFormat;
238
256
  };
239
257
  export type ProviderAuthError = {
240
258
  name: "ProviderAuthError";
@@ -276,6 +294,13 @@ export type ApiError = {
276
294
  };
277
295
  };
278
296
  };
297
+ export type StructuredOutputError = {
298
+ name: "StructuredOutputError";
299
+ data: {
300
+ message: string;
301
+ retries: number;
302
+ };
303
+ };
279
304
  export type AssistantMessage = {
280
305
  id: string;
281
306
  sessionID: string;
@@ -284,7 +309,7 @@ export type AssistantMessage = {
284
309
  created: number;
285
310
  completed?: number;
286
311
  };
287
- error?: ProviderAuthError | UnknownError | MessageOutputLengthError | MessageAbortedError | ApiError;
312
+ error?: ProviderAuthError | UnknownError | MessageOutputLengthError | MessageAbortedError | ApiError | StructuredOutputError;
288
313
  parentID: string;
289
314
  modelID: string;
290
315
  providerID: string;
@@ -297,8 +322,17 @@ export type AssistantMessage = {
297
322
  summary?: boolean;
298
323
  cost: number;
299
324
  tokens: {
325
+ /**
326
+ * Prompt tokens neither read from nor written to the prompt cache.
327
+ */
300
328
  input: number;
329
+ /**
330
+ * Generated tokens that are not reasoning: billed output is output + reasoning. Steps recorded by older versions on OpenAI-compatible providers may still include the reasoning here.
331
+ */
301
332
  output: number;
333
+ /**
334
+ * Reasoning (thinking) tokens, billed as output. 0 where the provider reports none.
335
+ */
302
336
  reasoning: number;
303
337
  cache: {
304
338
  read: number;
@@ -306,6 +340,7 @@ export type AssistantMessage = {
306
340
  };
307
341
  };
308
342
  finish?: string;
343
+ structured?: unknown;
309
344
  };
310
345
  export type Message = UserMessage | AssistantMessage;
311
346
  export type EventMessageUpdated = {
@@ -478,8 +513,17 @@ export type StepFinishPart = {
478
513
  upstream?: string;
479
514
  cost: number;
480
515
  tokens: {
516
+ /**
517
+ * Prompt tokens neither read from nor written to the prompt cache.
518
+ */
481
519
  input: number;
520
+ /**
521
+ * Generated tokens that are not reasoning: billed output is output + reasoning. Steps recorded by older versions on OpenAI-compatible providers may still include the reasoning here.
522
+ */
482
523
  output: number;
524
+ /**
525
+ * Reasoning (thinking) tokens, billed as output. 0 where the provider reports none.
526
+ */
483
527
  reasoning: number;
484
528
  cache: {
485
529
  read: number;
@@ -920,6 +964,31 @@ export type EventAgentLimitReached = {
920
964
  activeThreads: number;
921
965
  };
922
966
  };
967
+ /**
968
+ * Deprecated: no consumer reads this event. The notification queue is an internal hand-off — a queued notification reaches the user as part of the next assistant turn, observable through `message.part.updated`. No direct replacement. Scheduled for removal in the next major; still emitted until then.
969
+ *
970
+ * @deprecated
971
+ */
972
+ export type EventSessionNotificationQueued = {
973
+ type: "session.notification.queued";
974
+ properties: {
975
+ sessionID: string;
976
+ taskID: string;
977
+ priority: "now" | "next" | "later";
978
+ };
979
+ };
980
+ /**
981
+ * Deprecated: no consumer reads this event. The notification queue is an internal hand-off — a queued notification reaches the user as part of the next assistant turn, observable through `message.part.updated`. No direct replacement. Scheduled for removal in the next major; still emitted until then.
982
+ *
983
+ * @deprecated
984
+ */
985
+ export type EventSessionNotificationDrained = {
986
+ type: "session.notification.drained";
987
+ properties: {
988
+ sessionID: string;
989
+ count: number;
990
+ };
991
+ };
923
992
  export type EventTaskCreated = {
924
993
  type: "task.created";
925
994
  properties: {
@@ -1090,31 +1159,6 @@ export type EventAgentCoordinatorDispatchUpdated = {
1090
1159
  status: "running" | "completed" | "failed" | "stopped";
1091
1160
  };
1092
1161
  };
1093
- /**
1094
- * Deprecated: no consumer reads this event. The notification queue is an internal hand-off — a queued notification reaches the user as part of the next assistant turn, observable through `message.part.updated`. No direct replacement. Scheduled for removal in the next major; still emitted until then.
1095
- *
1096
- * @deprecated
1097
- */
1098
- export type EventSessionNotificationQueued = {
1099
- type: "session.notification.queued";
1100
- properties: {
1101
- sessionID: string;
1102
- taskID: string;
1103
- priority: "now" | "next" | "later";
1104
- };
1105
- };
1106
- /**
1107
- * Deprecated: no consumer reads this event. The notification queue is an internal hand-off — a queued notification reaches the user as part of the next assistant turn, observable through `message.part.updated`. No direct replacement. Scheduled for removal in the next major; still emitted until then.
1108
- *
1109
- * @deprecated
1110
- */
1111
- export type EventSessionNotificationDrained = {
1112
- type: "session.notification.drained";
1113
- properties: {
1114
- sessionID: string;
1115
- count: number;
1116
- };
1117
- };
1118
1162
  /**
1119
1163
  * Deprecated: no consumer reads this event. It carries a short progress label for a batch of tool calls, and it was always intended for clients rather than the TUI — but nothing has ever consumed it. The same information is derivable from the `message.part.updated` tool parts. Scheduled for removal in the next major unless a consumer is written first; still emitted until then.
1120
1164
  *
@@ -1251,7 +1295,7 @@ export type EventSessionError = {
1251
1295
  type: "session.error";
1252
1296
  properties: {
1253
1297
  sessionID?: string;
1254
- error?: ProviderAuthError | UnknownError | MessageOutputLengthError | MessageAbortedError | ApiError;
1298
+ error?: ProviderAuthError | UnknownError | MessageOutputLengthError | MessageAbortedError | ApiError | StructuredOutputError;
1255
1299
  };
1256
1300
  };
1257
1301
  export type EventSessionVerificationVerdict = {
@@ -1400,7 +1444,7 @@ export type EventSwarmMailboxMessage = {
1400
1444
  time: number;
1401
1445
  };
1402
1446
  };
1403
- export type Event = EventFlagRefreshed | EventInstallationUpdated | EventInstallationUpdateAvailable | EventProjectUpdated | EventConfigManagedPolicyChanged | EventFileWatcherUpdated | EventConfigChanged | EventScheduleCreated | EventScheduleUpdated | EventScheduleRemoved | EventScheduleFired | EventLspClientDiagnostics | EventLspUpdated | EventMessageUpdated | EventMessageRemoved | EventMessagePartUpdated | EventMessagePartRemoved | EventPermissionAsked | EventPermissionReplied | EventMemoryExtractionCompleted | EventMemoryConsolidationCompleted | EventMemoryRecallCompleted | EventQuestionAsked | EventQuestionReplied | EventQuestionRejected | EventSessionStatus | EventSessionIdle | EventMcpToolsChanged | EventMcpStatusChanged | EventTodoUpdated | EventSessionCompacted | EventSessionCompactionFailed | EventCommandExecuted | EventAgentThreadCreated | EventAgentThreadCompleted | EventAgentThreadInterrupted | EventAgentThreadError | EventAgentLimitReached | EventTaskCreated | EventTaskUpdated | EventTaskRemoved | EventTaskActivated | EventTaskBackgrounded | EventTaskDeactivated | EventAgentWorkitemUpdated | EventAgentCoordinatorEnabled | EventAgentCoordinatorDisabled | EventAgentCoordinatorDispatched | EventAgentCoordinatorDispatchUpdated | EventSessionNotificationQueued | EventSessionNotificationDrained | EventSessionToolSummary | EventSessionBudgetCompleted | EventSessionPromptSuggestion | EventFileEdited | EventAgentTeamCreated | EventAgentTeamDeleted | EventSessionCreated | EventSessionUpdated | EventSessionDeleted | EventSessionDiff | EventSessionError | EventSessionVerificationVerdict | EventVcsBranchUpdated | EventTuiPromptAppend | EventTuiCommandExecute | EventTuiToastShow | EventTuiSessionSelect | EventPtyCreated | EventPtyUpdated | EventPtyExited | EventPtyDeleted | EventServerConnected | EventServerInstanceDisposed | EventGlobalDisposed | EventSwarmMessageReceived | EventSwarmMailboxMessage;
1447
+ export type Event = EventFlagRefreshed | EventInstallationUpdated | EventInstallationUpdateAvailable | EventProjectUpdated | EventConfigManagedPolicyChanged | EventFileWatcherUpdated | EventConfigChanged | EventScheduleCreated | EventScheduleUpdated | EventScheduleRemoved | EventScheduleFired | EventLspClientDiagnostics | EventLspUpdated | EventMessageUpdated | EventMessageRemoved | EventMessagePartUpdated | EventMessagePartRemoved | EventPermissionAsked | EventPermissionReplied | EventMemoryExtractionCompleted | EventMemoryConsolidationCompleted | EventMemoryRecallCompleted | EventQuestionAsked | EventQuestionReplied | EventQuestionRejected | EventSessionStatus | EventSessionIdle | EventMcpToolsChanged | EventMcpStatusChanged | EventTodoUpdated | EventSessionCompacted | EventSessionCompactionFailed | EventCommandExecuted | EventAgentThreadCreated | EventAgentThreadCompleted | EventAgentThreadInterrupted | EventAgentThreadError | EventAgentLimitReached | EventSessionNotificationQueued | EventSessionNotificationDrained | EventTaskCreated | EventTaskUpdated | EventTaskRemoved | EventTaskActivated | EventTaskBackgrounded | EventTaskDeactivated | EventAgentWorkitemUpdated | EventAgentCoordinatorEnabled | EventAgentCoordinatorDisabled | EventAgentCoordinatorDispatched | EventAgentCoordinatorDispatchUpdated | EventSessionToolSummary | EventSessionBudgetCompleted | EventSessionPromptSuggestion | EventFileEdited | EventAgentTeamCreated | EventAgentTeamDeleted | EventSessionCreated | EventSessionUpdated | EventSessionDeleted | EventSessionDiff | EventSessionError | EventSessionVerificationVerdict | EventVcsBranchUpdated | EventTuiPromptAppend | EventTuiCommandExecute | EventTuiToastShow | EventTuiSessionSelect | EventPtyCreated | EventPtyUpdated | EventPtyExited | EventPtyDeleted | EventServerConnected | EventServerInstanceDisposed | EventGlobalDisposed | EventSwarmMessageReceived | EventSwarmMailboxMessage;
1404
1448
  export type GlobalEvent = {
1405
1449
  directory: string;
1406
1450
  payload: Event;
@@ -1965,7 +2009,7 @@ export type AgentConfig = {
1965
2009
  */
1966
2010
  color?: string;
1967
2011
  /**
1968
- * Maximum number of agentic iterations before forcing text-only response
2012
+ * Maximum model steps per user turn. The last one runs without tools and asks the model to summarize; then the turn ends. Unset: no limit, except 200 for a subagent.
1969
2013
  */
1970
2014
  steps?: number;
1971
2015
  /**
@@ -2250,7 +2294,7 @@ export type Config = {
2250
2294
  hooks?: {
2251
2295
  [key: string]: Array<{
2252
2296
  /**
2253
- * Regex matched against the tool name (PreToolUse/PostToolUse only)
2297
+ * Which events of this kind the entry runs for, matched against the event's subject: the tool name (PreToolUse, PostToolUse, PostToolUseFailure), the permission (PermissionRequest), the file path (FileChanged, FileEdited, LspDiagnostics), the error class (StopFailure), the MCP server (Elicitation), the trigger (Setup). Omitted, "" or "*": every event, including those with no subject. Names joined by "|" ("Bash", "edit|write"): an exact, case-insensitive list; Claude Code tool names work, and a file path matches by its basename. Anything else is an unanchored regex ("^mcp__github__", "\\.ts$"); a matcher never selects an event that has no subject.
2254
2298
  */
2255
2299
  matcher?: string;
2256
2300
  hooks: Array<{
@@ -2613,7 +2657,7 @@ export type Config = {
2613
2657
  */
2614
2658
  cache?: {
2615
2659
  /**
2616
- * Prompt-cache lifetime for Anthropic-family models. "1h" (default) keeps the cached prefix alive across long pauses — writes cost 2x base but the prefix is reused instead of re-written every turn, a net win for long interactive/agentic sessions. "5m" writes cheapest (1.25x base input). No effect on non-Anthropic providers.
2660
+ * Prompt-cache lifetime for Anthropic-family models. "1h" (default) keeps the cached prefix alive across long pauses — writes cost 2x base but the prefix is reused instead of re-written every turn, a net win for long interactive/agentic sessions. "5m" writes cheapest (1.25x base input). Read at the first request of a session and kept for that session while the process (or daemon) runs: a restart reads it again. No effect on non-Anthropic providers.
2617
2661
  */
2618
2662
  ttl?: "5m" | "1h";
2619
2663
  };
@@ -4358,6 +4402,7 @@ export type SessionPromptData = {
4358
4402
  */
4359
4403
  systemOverride?: string;
4360
4404
  variant?: string;
4405
+ format?: OutputFormat;
4361
4406
  /**
4362
4407
  * Run this session in kairos (background tick) mode: registers the sleep tool and the kairos prompt discipline. Sticky until explicitly set to false
4363
4408
  */
@@ -4537,6 +4582,7 @@ export type SessionPromptAsyncData = {
4537
4582
  */
4538
4583
  systemOverride?: string;
4539
4584
  variant?: string;
4585
+ format?: OutputFormat;
4540
4586
  /**
4541
4587
  * Run this session in kairos (background tick) mode: registers the sleep tool and the kairos prompt discipline. Sticky until explicitly set to false
4542
4588
  */
@@ -4567,6 +4613,10 @@ export type SessionPromptAsyncErrors = {
4567
4613
  * Not found
4568
4614
  */
4569
4615
  404: NotFoundError;
4616
+ /**
4617
+ * Conflict: the session is running in another process
4618
+ */
4619
+ 409: UnknownError;
4570
4620
  };
4571
4621
  export type SessionPromptAsyncError = SessionPromptAsyncErrors[keyof SessionPromptAsyncErrors];
4572
4622
  export type SessionPromptAsyncResponses = {
package/dist/index.d.ts CHANGED
@@ -5,6 +5,7 @@ export declare function create100XPrompt(options?: ServerOptions): Promise<{
5
5
  client: import("./client.js").X100PromptClient;
6
6
  server: {
7
7
  url: string;
8
+ token: string;
8
9
  close(): void;
9
10
  };
10
11
  }>;
package/dist/index.js CHANGED
@@ -8,6 +8,7 @@ export async function create100XPrompt(options) {
8
8
  });
9
9
  const client = create100XPromptClient({
10
10
  baseUrl: server.url,
11
+ headers: { authorization: `Bearer ${server.token}` },
11
12
  });
12
13
  return {
13
14
  client,
package/dist/server.d.ts CHANGED
@@ -5,6 +5,8 @@ export type ServerOptions = {
5
5
  signal?: AbortSignal;
6
6
  timeout?: number;
7
7
  config?: Config;
8
+ /** The token the server will require on every request. Default: a fresh random one. */
9
+ token?: string;
8
10
  };
9
11
  export type TuiOptions = {
10
12
  project?: string;
@@ -16,6 +18,8 @@ export type TuiOptions = {
16
18
  };
17
19
  export declare function create100XPromptServer(options?: ServerOptions): Promise<{
18
20
  url: string;
21
+ /** Send as `Authorization: Bearer <token>`; create100XPrompt's client does. */
22
+ token: string;
19
23
  close(): void;
20
24
  }>;
21
25
  export declare function create100XPromptTui(options?: TuiOptions): {
package/dist/server.js CHANGED
@@ -1,18 +1,25 @@
1
1
  import { spawn } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
2
3
  export async function create100XPromptServer(options) {
3
4
  options = Object.assign({
4
5
  hostname: "127.0.0.1",
5
- port: 4096,
6
+ // 0 lets the server take 4096 when it is free and any free port
7
+ // otherwise, so two SDK users on one machine don't collide.
8
+ port: 0,
6
9
  timeout: 5000,
7
10
  }, options ?? {});
8
11
  const args = [`serve`, `--hostname=${options.hostname}`, `--port=${options.port}`];
9
12
  if (options.config?.logLevel)
10
13
  args.push(`--log-level=${options.config.logLevel}`);
14
+ // The server requires a token on every request, loopback included. Chosen
15
+ // here and handed over in the environment, which the server clears once read.
16
+ const token = options.token || randomBytes(32).toString("hex");
11
17
  const proc = spawn(`100xprompt`, args, {
12
18
  signal: options.signal,
13
19
  env: {
14
20
  ...process.env,
15
21
  HUNDREDXPROMPT_CONFIG_CONTENT: JSON.stringify(options.config ?? {}),
22
+ HUNDREDXPROMPT_SERVER_TOKEN: token,
16
23
  },
17
24
  });
18
25
  const url = await new Promise((resolve, reject) => {
@@ -59,6 +66,8 @@ export async function create100XPromptServer(options) {
59
66
  });
60
67
  return {
61
68
  url,
69
+ /** Send as `Authorization: Bearer <token>`; create100XPrompt's client does. */
70
+ token,
62
71
  close() {
63
72
  proc.kill();
64
73
  },
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@100xprompt/sdk",
4
- "version": "0.1.130",
4
+ "version": "0.1.132",
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE",
7
7
  "description": "TypeScript SDK for 100XPrompt — a fully-typed client plus server/TUI launchers for the open source AI coding agent.",