@cultured_computer/sight 0.8.4 → 0.9.0

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/CHANGELOG.md CHANGED
@@ -5,6 +5,32 @@ reconstructed from the repository: the `sdk-v*` release tags (dates are tag
5
5
  dates) and the commits between them. Where the history does not say what a
6
6
  version changed for SDK users, the entry says "see git history".
7
7
 
8
+ ## 0.9.0 (2026-10-16)
9
+
10
+ - New: the serving client. `createFieldClient({ apiKey, endpoint? })`
11
+ calls the Field API: `profiles.put`, `profiles.get`, `profiles.sessions`,
12
+ `conversations.start`, `turns.send` (JSON), `turns.stream` (the turn's
13
+ server-sent frames as an async iterator: `run`, `notice`, `reads`,
14
+ `delta`, `events`, `done`, `error`) and `sessions.get`. It uses the
15
+ global `fetch`, adds no dependency, keeps no state and never retries.
16
+ - The runtime record: `model`, `temperature`, `maxOutputTokens` and
17
+ `reasoningEffort` (including `none`) as `profiles.put` options, and as
18
+ `runtime` on `conversations.start` to choose them for one conversation
19
+ (a key with `profiles:write` only; `runtime_forbidden` otherwise). The
20
+ profile read's `maxOutputTokensSource` and `reasoningEffortSource`, and
21
+ the `run` frame's `maxOutputTokens` and `override`, are typed. These
22
+ need the Field's served runtime record deployed.
23
+ - Every refused request throws a `FieldRefusal` with `status`, `code`,
24
+ `reason` (the ended reason, or `empty_completion` and
25
+ `empty_completion_length` on a `provider_error`), `retryAfter`, and a
26
+ failed turn's `notices`, `events` and `turnIndex`.
27
+ `FIELD_REFUSAL_CODES` lists the codes.
28
+ - Capture is unchanged: `Sight` and every other export behave as in
29
+ 0.8.4, and the request a capture sends is pinned byte for byte by a
30
+ test.
31
+ - 0.8.4 never reached the registry (its publish failed), so 0.9.0 is the
32
+ first npm release carrying 0.8.4's changes, listed below.
33
+
8
34
  ## 0.8.4 (2026-10-13)
9
35
 
10
36
  - Capture slots and drain now include consuming or cancelling the HTTP
package/README.md CHANGED
@@ -5,6 +5,9 @@ makes inside a session as one turn (the person's message, the reply, model,
5
5
  tokens, latency) and sends it to the Sight API without changing or delaying
6
6
  the response.
7
7
 
8
+ It also carries a serving client for the Field API, which serves a
9
+ `SOUL.md` profile for you: see [Serve a profile](#serve-a-profile).
10
+
8
11
  Full documentation: https://sight.cultured.computer/docs
9
12
 
10
13
  ## Requirements
@@ -188,11 +191,210 @@ environment variables. Secrets are read from the environment, never from a flag.
188
191
 
189
192
  Every flag: [CLI](https://sight.cultured.computer/docs/cli).
190
193
 
191
- ## Serving a profile
194
+ ## Serve a profile
195
+
196
+ The serving client puts a `SOUL.md` at a name on the Field API, serves it
197
+ turn by turn and reads its record. It is separate from capture: it takes
198
+ its own key and shares no state with `Sight`. It uses the global `fetch`,
199
+ keeps nothing between calls and never retries a request.
200
+
201
+ ### Setup
202
+
203
+ - An App key (it carries `studio:serve` and `profiles:write`), set as
204
+ `SIGHT_APP_KEY`. Keep it on a server: it can rewrite the profile.
205
+ - The project's OpenRouter key, connected once with an Admin key. See call 1
206
+ of [Quickstart: serve a profile](https://sight.cultured.computer/docs/serve-a-soul-md),
207
+ or `sight openrouter connect`.
208
+ - The host is `https://api.cultured.computer`, the same as capture; set
209
+ `endpoint` only for a staging API.
210
+
211
+ ### Quickstart
212
+
213
+ ```ts
214
+ import { createFieldClient } from "@cultured_computer/sight";
215
+
216
+ const field = createFieldClient({ apiKey: process.env.SIGHT_APP_KEY! });
217
+ await field.profiles.put("listener", soulMarkdown);
218
+ await field.conversations.start("listener", { conversation: "conv-001", user: "user-481" });
219
+ const { reply, notices } = await field.turns.send("listener", { conversation: "conv-001", message: "Hi" });
220
+ ```
221
+
222
+ Show `notices` to the person before the reply: they are fixed platform
223
+ texts (an AI disclosure, a crisis referral), sent only by a profile with a
224
+ safeguard switched on.
225
+
226
+ To stream the reply, iterate the turn's frames:
227
+
228
+ ```ts
229
+ for await (const frame of field.turns.stream("listener", { conversation: "conv-001", message: "Hi" })) {
230
+ if (frame.event === "notice") showNotice(frame.data.text);
231
+ if (frame.event === "delta") write(frame.data.text);
232
+ if (frame.event === "error") console.error(frame.data.code, frame.data.reason);
233
+ }
234
+ ```
235
+
236
+ The frames come in order: `run`, then any `notice` and `reads` before the
237
+ first `delta`, the `delta`s, `events`, and last `done` or `error`. A frame
238
+ this version does not know arrives as `other`, with its `name`.
239
+
240
+ | Method | Route | Answers |
241
+ | --- | --- | --- |
242
+ | `profiles.put(name, soulMarkdown, options?)` | `PUT /v1/profiles/{name}` | `outcome`, `changed`, the version, the `runtime`, `refused` (parts of the file left out; check it after every put), `etag` |
243
+ | `profiles.get(name)` | `GET /v1/profiles/{name}` | The live version, the `runtime`, limits, safeguards, the connection, `etag` |
244
+ | `profiles.sessions(name, { conversation?, cursor?, limit?, version?, ended? })` | `GET /v1/profiles/{name}/sessions` | One page of sessions, newest first; pass `nextBefore` as `cursor` for the next |
245
+ | `conversations.start(profile, { conversation, user, runtime?, opening?, seed? })` | `POST /v1/profiles/{name}/conversations` | `runId`, `sessionId`, `record` |
246
+ | `turns.send(profile, { conversation, message, resume? })` | `POST /v1/profiles/{name}/turns`, JSON | `reply`, `notices`, `events`, `turnIndex` |
247
+ | `turns.stream(profile, { conversation, message, resume? })` | The same route, server-sent events | The frames, as an async iterator |
248
+ | `sessions.get(id)` | `GET /v1/sessions/{id}` | The session and its turns: each turn's `message`, then the `reply` it prompted |
249
+
250
+ Every method takes an optional `signal` (an `AbortSignal`). The client sets
251
+ no timeout of its own; the Field bounds a reply at 90 seconds.
252
+
253
+ ### The runtime record
192
254
 
193
- - The Field API serves a profile on the same host, `https://api.cultured.computer`, with keys from the same API Keys page.
194
- - This package has no client and no CLI verbs for it.
195
- - Docs: [Serve a SOUL.md](https://sight.cultured.computer/docs/serve-a-soul-md).
255
+ What the reply call is sent. A profile sets it; a conversation can
256
+ override it.
257
+
258
+ | Setting | What it does | Default |
259
+ | --- | --- | --- |
260
+ | `model` | The OpenRouter model id that writes the reply, `vendor/model`. It must have an active route in the model catalogue. | None: the file or the put must name one. |
261
+ | `temperature` | Sampling temperature, 0 to 2. Left out of the request where the model's route takes none. | 0.7 |
262
+ | `maxOutputTokens` | The reply's output budget, in tokens: an integer from 256 to the model's catalogue `max_completion_tokens` (16,384 when it states none). A reasoning model's reasoning tokens count inside it, with the answer. | The smaller of 16,384 and the model's catalogue `max_completion_tokens`; 4,096 when the catalogue says nothing of the model |
263
+ | `reasoningEffort` | `none`, `minimal`, `low`, `medium`, `high`, `xhigh` or `max`. Sent only where the model's catalogue entry lists that effort; elsewhere left out. `none` asks for no reasoning. | `low` where the catalogue lists it, else the lowest effort it lists; nothing when it lists none |
264
+
265
+ - On a profile: write them in the `SOUL.md` frontmatter, or pass them to
266
+ `profiles.put` (the options override the file for that put). A changed
267
+ `reasoningEffort` or `maxOutputTokens` saves a new version.
268
+ `maxOutputTokens` in the frontmatter and as a put option.
269
+ - `profiles.get` answers what the replies are sent with, under `runtime`.
270
+ `maxOutputTokens` and `reasoningEffort` (`null` when nothing is
271
+ asked), each with its source, `maxOutputTokensSource` and
272
+ `reasoningEffortSource`: `profile` when the live version names it,
273
+ `default` for the house default.
274
+ - Each turn's `run` frame, and each turn of `sessions.get` under `sent`,
275
+ say what the call actually sent.
276
+
277
+ Every model the Field serves reasons by default, so a setting you leave
278
+ out is not "off": it is the house default above, per model.
279
+
280
+ Reasoning tokens count inside `maxOutputTokens`. A reasoning model at a
281
+ high effort with a small limit can spend the whole limit reasoning and
282
+ write no reply; that turn fails with `empty_completion_length` (below).
283
+ Reasoning before the first visible token also counts against the
284
+ 15-second first-token deadline.
285
+
286
+ ### Choosing a model per conversation
287
+
288
+ ```ts
289
+ await field.conversations.start("listener", {
290
+ conversation: "conv-002",
291
+ user: "user-481",
292
+ runtime: { model: "anthropic/claude-opus-5", reasoningEffort: "none", maxOutputTokens: 1024 },
293
+ });
294
+ ```
295
+
296
+ - `runtime` overrides the profile's settings for that one conversation;
297
+ a key left out keeps the profile's value.
298
+ - Only a key holding `profiles:write` (the App key) may send it; any
299
+ other key is refused with `runtime_forbidden`.
300
+ - `model` must have an active route in the catalogue (`model_unavailable`
301
+ otherwise); `maxOutputTokens` must be in that model's range and
302
+ `reasoningEffort` one of the efforts (`invalid_max_output_tokens`,
303
+ `invalid_reasoning_effort`). A refused start starts nothing.
304
+ - It is stored with the conversation and every turn uses it. A repeated
305
+ start of the same conversation must send the same `runtime`
306
+ (`opening_conflict` otherwise). Each turn's `run` frame names it as
307
+ `override`.
308
+ - The profile's file, its `## When` sentences and its safeguards are the
309
+ same for every conversation; only the runtime record changes.
310
+
311
+ ### Handling `empty_completion`
312
+
313
+ A model that finishes a turn with no reply text is a `provider_error`
314
+ (`502`) with a `reason`:
315
+
316
+ | `reason` | What happened | What to do |
317
+ | --- | --- | --- |
318
+ | `empty_completion` | The model answered nothing | The next message can be sent as usual. To change the model, start the next conversation with another `runtime.model`. |
319
+ | `empty_completion_length` | The output limit ended the call before any reply text: a reasoning model spent `maxOutputTokens` reasoning | Raise `maxOutputTokens`, or lower `reasoningEffort` |
320
+
321
+ A profile with a `fallback` model has that model answer such a turn
322
+ first. The turn index has moved; do not resend the same message as a new
323
+ turn without deciding to.
324
+
325
+ ```ts
326
+ import { FieldRefusal } from "@cultured_computer/sight";
327
+
328
+ try {
329
+ const { reply } = await field.turns.send("listener", { conversation, message });
330
+ } catch (error) {
331
+ if (error instanceof FieldRefusal && error.code === "provider_error" && error.reason === "empty_completion_length") {
332
+ // The limit was spent reasoning: start the next conversation with a larger maxOutputTokens.
333
+ }
334
+ throw error;
335
+ }
336
+ ```
337
+
338
+ In a stream the same failure is the `error` frame, with `code` and
339
+ `reason`; it ends the stream.
340
+
341
+ ### Refusals
342
+
343
+ Every answer that is not a `2xx` throws a `FieldRefusal`:
344
+
345
+ | Property | What it is |
346
+ | --- | --- |
347
+ | `status` | The HTTP status |
348
+ | `code` | The stable code (below), or `null` when the answer has none (`401`, a `403` for a missing permission, `413`) |
349
+ | `reason` | The `conversation_ended` reason (`idle`, `turn_cap`, `floor`, `failed`, `ended`), or the `provider_error` reason, or `null` |
350
+ | `retryAfter` | `Retry-After` in seconds, or `null` |
351
+ | `notices`, `events`, `turnIndex` | A failed turn's notices (show them), frames and index |
352
+ | `body` | The answer as sent |
353
+
354
+ Branch on `code`, never on the message. `FIELD_REFUSAL_CODES` lists every
355
+ code this version knows; a newer API may answer one it does not list.
356
+
357
+ | Code | Status | What to do |
358
+ | --- | --- | --- |
359
+ | `invalid_body` | `400` | Fix the body; `body.detail` names the fields |
360
+ | `no_owner` | `400` | The project has no owner. Ask us. |
361
+ | `forbidden` | `403` | A rehearsal link was used at a profile address. Use the App key. |
362
+ | `opening_forbidden` | `403` | An `opening` needs a key with `profiles:write` |
363
+ | `runtime_forbidden` | `403` | A `runtime` override needs a key with `profiles:write` |
364
+ | `no_such_profile`, `no_such_endpoint` | `404` | Check the name; put the profile first |
365
+ | `no_such_conversation` | `404` | Start the conversation before sending a turn |
366
+ | `conversation_unknown` | `409` | The conversation has not started |
367
+ | `conversation_conflict` | `409` | This conversation id was started with another `user`. Use a new id. |
368
+ | `opening_conflict` | `409` | This id was started with another `opening`, `seed` or `runtime`. Send the same ones, or use a new id. |
369
+ | `conversation_ended` | `409` | The id is spent; `reason` says why. Start a new conversation under a new id. |
370
+ | `turn_cap` | `409` | The conversation reached its turn cap. Start a new one. |
371
+ | `stale_turn_index` | `409` | `resume.turnIndex` is not the next turn; use the `turnIndex` in the answer |
372
+ | `busy` | `409` | A reply is in progress on this conversation. Wait, then send. |
373
+ | `interrupted`, `record_gap` | `409` | The conversation cannot continue. Start a new one. |
374
+ | `no_live_version` | `409` | Put the file |
375
+ | `model_unavailable` | `409` | The profile's model, or the start's `runtime.model`, has no active route in the catalogue. Name a model it carries. |
376
+ | `not_connected` | `409` | Connect the project's OpenRouter key |
377
+ | `budget` | `409` | The monthly budget is reached. Connect again with a larger budget. |
378
+ | `put_in_progress` | `409` | Another put of this profile is running. Retry after `retryAfter`. |
379
+ | `scene_live` | `409` | The profile serves a stepped scene. Put with `force: true` to replace it. |
380
+ | `request_conflict`, `request_pending`, `request_interrupted` | `409` | Logical turn requests only; not sent by this client |
381
+ | `not_a_soul_md`, `not_a_scene` | `406` | Profile read in another format; not sent by this client |
382
+ | `archived`, `revoked`, `link_inactive` | `410` | It does not come back |
383
+ | `request_unknown`, `replay_expired` | `404`, `410` | Logical turn requests only; not sent by this client |
384
+ | `precondition_failed` | `412` | `ifMatch` no longer names the live version. Read the profile, then put. |
385
+ | `invalid_consent`, `invalid_safeguards`, `invalid_scrub`, `invalid_fallback`, `invalid_scene`, `invalid_reasoning_effort` | `422` | Fix that setting (on a put, or a start's `runtime`); `body.accepted` lists the words. Nothing was stored. |
386
+ | `invalid_max_output_tokens` | `422` | `maxOutputTokens` (on a put, or a start's `runtime`) is not an integer in the model's range; `body.accepted` is `{ min, max }`. Nothing was stored. |
387
+ | `daily_cap` | `429` | The day's conversations are used up (UTC) |
388
+ | `link_session_cap` | `429` | A rehearsal link's session limit; not sent by this client |
389
+ | `rate_limited` | `429` | Wait `retryAfter` seconds, then retry |
390
+ | `turn_failed` | `500` | The turn broke and the conversation is closed. Start a new one. |
391
+ | `provider_error` | `502` | The provider or the model failed; see `reason` above |
392
+ | `provider_timeout` | `504` | A reply deadline passed. The next turn can be sent at once. |
393
+ | `not_enabled` | `503` | Serving is not enabled for the project. Ask us. |
394
+
395
+ Every route, body and refusal:
396
+ [Profile reference](https://sight.cultured.computer/docs/serve-a-profile-reference)
397
+ and [SDK reference](https://sight.cultured.computer/docs/sdk-reference#serve-a-profile).
196
398
 
197
399
  ## Troubleshooting
198
400
 
package/dist/index.cjs CHANGED
@@ -3753,6 +3753,324 @@ var Probe = class {
3753
3753
  }
3754
3754
  };
3755
3755
 
3756
+ // src/field.ts
3757
+ var DEFAULT_FIELD_ENDPOINT = "https://api.cultured.computer";
3758
+ var FIELD_REFUSAL_CODES = [
3759
+ // The conversation and turn routes, and the rate limit.
3760
+ "invalid_body",
3761
+ "forbidden",
3762
+ "not_enabled",
3763
+ "no_such_profile",
3764
+ "no_such_endpoint",
3765
+ "no_such_conversation",
3766
+ "conversation_unknown",
3767
+ "archived",
3768
+ "revoked",
3769
+ "link_inactive",
3770
+ "conversation_conflict",
3771
+ "opening_forbidden",
3772
+ "opening_conflict",
3773
+ "runtime_forbidden",
3774
+ "invalid_reasoning_effort",
3775
+ "invalid_max_output_tokens",
3776
+ "conversation_ended",
3777
+ "no_live_version",
3778
+ "no_owner",
3779
+ "model_unavailable",
3780
+ "daily_cap",
3781
+ "link_session_cap",
3782
+ "rate_limited",
3783
+ "turn_cap",
3784
+ "stale_turn_index",
3785
+ "record_gap",
3786
+ "busy",
3787
+ "interrupted",
3788
+ "not_connected",
3789
+ "budget",
3790
+ "provider_error",
3791
+ "provider_timeout",
3792
+ "turn_failed",
3793
+ "request_unknown",
3794
+ "request_conflict",
3795
+ "request_pending",
3796
+ "request_interrupted",
3797
+ "replay_expired",
3798
+ // The profile put.
3799
+ "put_in_progress",
3800
+ "scene_live",
3801
+ "precondition_failed",
3802
+ "invalid_consent",
3803
+ "invalid_safeguards",
3804
+ "invalid_scrub",
3805
+ "invalid_fallback",
3806
+ "invalid_scene",
3807
+ // The profile read.
3808
+ "not_a_soul_md",
3809
+ "not_a_scene"
3810
+ ];
3811
+ var FIELD_REASONING_EFFORTS = ["none", "minimal", "low", "medium", "high", "xhigh", "max"];
3812
+ var FieldRefusal = class extends Error {
3813
+ name = "FieldRefusal";
3814
+ /** The HTTP status. */
3815
+ status;
3816
+ /**
3817
+ * The refusal's stable code, one of `FIELD_REFUSAL_CODES` from this
3818
+ * version; a newer API may answer a code this version does not list.
3819
+ * `null` when the answer carries none (401, a 403 for a missing
3820
+ * permission, 413, a 503 while the service drains).
3821
+ */
3822
+ code;
3823
+ /**
3824
+ * Why, when the answer says: the ended reason of a `conversation_ended`,
3825
+ * or the empty-completion reason of a `provider_error`. Otherwise null.
3826
+ */
3827
+ reason;
3828
+ /** `Retry-After` in seconds, when the answer carries one (429, 503, a busy put). */
3829
+ retryAfter;
3830
+ /** A failed turn still answers its notices; show them. Empty otherwise. */
3831
+ notices;
3832
+ /** A failed turn's frames, collected before it failed. Empty otherwise. */
3833
+ events;
3834
+ /** A failed turn's index, when the answer names one. */
3835
+ turnIndex;
3836
+ /** The answer's body as sent: parsed JSON, or the text when it is not JSON. */
3837
+ body;
3838
+ constructor(init) {
3839
+ super(init.message);
3840
+ this.status = init.status;
3841
+ this.code = init.code;
3842
+ this.reason = init.reason;
3843
+ this.retryAfter = init.retryAfter;
3844
+ this.notices = init.notices;
3845
+ this.events = init.events;
3846
+ this.turnIndex = init.turnIndex;
3847
+ this.body = init.body;
3848
+ }
3849
+ };
3850
+ function queryString(query) {
3851
+ const params = new URLSearchParams();
3852
+ for (const [key, value] of Object.entries(query)) {
3853
+ if (value !== void 0) params.append(key, String(value));
3854
+ }
3855
+ const text = params.toString();
3856
+ return text ? `?${text}` : "";
3857
+ }
3858
+ var segment = (value) => encodeURIComponent(value);
3859
+ function parseRetryAfter(value) {
3860
+ if (value === null) return null;
3861
+ const seconds = Number(value);
3862
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds : null;
3863
+ }
3864
+ function isRecord2(value) {
3865
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3866
+ }
3867
+ async function refusalOf(response) {
3868
+ const text = await response.text().catch(() => "");
3869
+ let body = text;
3870
+ try {
3871
+ body = text ? JSON.parse(text) : null;
3872
+ } catch {
3873
+ }
3874
+ const record = isRecord2(body) ? body : {};
3875
+ const events = Array.isArray(record["events"]) ? record["events"] : [];
3876
+ const errorFrame = events.find((frame) => isRecord2(frame) && frame.event === "error");
3877
+ const frameReason = errorFrame && isRecord2(errorFrame.data) ? errorFrame.data["reason"] : void 0;
3878
+ const reason = typeof record["reason"] === "string" ? record["reason"] : typeof frameReason === "string" ? frameReason : null;
3879
+ const sentence = typeof record["error"] === "string" ? record["error"] : null;
3880
+ return new FieldRefusal({
3881
+ status: response.status,
3882
+ message: sentence ?? `the Field API answered ${response.status}`,
3883
+ code: typeof record["code"] === "string" ? record["code"] : null,
3884
+ reason,
3885
+ retryAfter: parseRetryAfter(response.headers.get("retry-after")),
3886
+ notices: Array.isArray(record["notices"]) ? record["notices"] : [],
3887
+ events,
3888
+ turnIndex: typeof record["turnIndex"] === "number" ? record["turnIndex"] : null,
3889
+ body
3890
+ });
3891
+ }
3892
+ var KNOWN_FRAMES = /* @__PURE__ */ new Set(["run", "notice", "reads", "delta", "events", "done", "error"]);
3893
+ function frameOf(name, raw) {
3894
+ let data = raw;
3895
+ try {
3896
+ data = JSON.parse(raw);
3897
+ } catch {
3898
+ }
3899
+ if (KNOWN_FRAMES.has(name)) return { event: name, data };
3900
+ return { event: "other", name, data };
3901
+ }
3902
+ async function* readFrames(body) {
3903
+ const reader = body.getReader();
3904
+ const decoder = new TextDecoder();
3905
+ let buffer = "";
3906
+ let name = "";
3907
+ let data = [];
3908
+ try {
3909
+ while (true) {
3910
+ const { done, value } = await reader.read();
3911
+ buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });
3912
+ let newline;
3913
+ while ((newline = buffer.search(/\r\n|\r|\n/)) !== -1) {
3914
+ if (buffer[newline] === "\r" && newline === buffer.length - 1 && !done) break;
3915
+ const width = buffer.startsWith("\r\n", newline) ? 2 : 1;
3916
+ const line = buffer.slice(0, newline);
3917
+ buffer = buffer.slice(newline + width);
3918
+ if (line === "") {
3919
+ if (data.length > 0) yield frameOf(name || "message", data.join("\n"));
3920
+ name = "";
3921
+ data = [];
3922
+ continue;
3923
+ }
3924
+ if (line.startsWith(":")) continue;
3925
+ const colon = line.indexOf(":");
3926
+ const field = colon === -1 ? line : line.slice(0, colon);
3927
+ let content = colon === -1 ? "" : line.slice(colon + 1);
3928
+ if (content.startsWith(" ")) content = content.slice(1);
3929
+ if (field === "event") name = content;
3930
+ else if (field === "data") data.push(content);
3931
+ }
3932
+ if (done) return;
3933
+ }
3934
+ } finally {
3935
+ await reader.cancel().catch(() => {
3936
+ });
3937
+ reader.releaseLock();
3938
+ }
3939
+ }
3940
+ function runtimeBody(runtime) {
3941
+ const out = {};
3942
+ if (runtime.model !== void 0) out.model = runtime.model;
3943
+ if (runtime.temperature !== void 0) out.temperature = runtime.temperature;
3944
+ if (runtime.maxOutputTokens !== void 0) out.maxOutputTokens = runtime.maxOutputTokens;
3945
+ if (runtime.reasoningEffort !== void 0) out.reasoningEffort = runtime.reasoningEffort;
3946
+ return out;
3947
+ }
3948
+ function createFieldClient(options) {
3949
+ if (!options || typeof options.apiKey !== "string" || options.apiKey.trim() === "") {
3950
+ throw new TypeError("createFieldClient: apiKey is required (an App key; keep it on a server)");
3951
+ }
3952
+ const apiKey = options.apiKey;
3953
+ const endpoint = (options.endpoint ?? DEFAULT_FIELD_ENDPOINT).replace(/\/+$/, "");
3954
+ async function request(method, path, init) {
3955
+ const headers = { authorization: `Bearer ${apiKey}`, accept: init.accept, ...init.headers };
3956
+ if (init.contentType) headers["content-type"] = init.contentType;
3957
+ const response = await fetch(`${endpoint}${path}`, {
3958
+ method,
3959
+ headers,
3960
+ ...init.body !== void 0 ? { body: init.body } : {},
3961
+ ...init.signal ? { signal: init.signal } : {}
3962
+ });
3963
+ if (!response.ok) throw await refusalOf(response);
3964
+ return response;
3965
+ }
3966
+ async function json(response) {
3967
+ return await response.json();
3968
+ }
3969
+ function turnBody(input) {
3970
+ return JSON.stringify({
3971
+ conversation: input.conversation,
3972
+ message: input.message,
3973
+ ...input.resume ? { resume: { turnIndex: input.resume.turnIndex } } : {}
3974
+ });
3975
+ }
3976
+ return {
3977
+ profiles: {
3978
+ async put(name, soulMarkdown, put = {}) {
3979
+ const query = {
3980
+ model: put.model,
3981
+ temperature: put.temperature,
3982
+ maxOutputTokens: put.maxOutputTokens,
3983
+ reasoningEffort: put.reasoningEffort,
3984
+ fallback: put.fallback,
3985
+ consent: put.consent,
3986
+ safeguards: put.safeguards === void 0 ? void 0 : put.safeguards === "none" ? "none" : put.safeguards.join(","),
3987
+ scrub: put.scrub,
3988
+ idleMinutes: put.idleMinutes,
3989
+ turnsPerConversation: put.turnsPerConversation,
3990
+ conversationsPerDay: put.conversationsPerDay,
3991
+ dryRun: put.dryRun,
3992
+ force: put.force
3993
+ };
3994
+ const response = await request("PUT", `/v1/profiles/${segment(name)}${queryString(query)}`, {
3995
+ body: soulMarkdown,
3996
+ contentType: "text/markdown",
3997
+ accept: "application/json",
3998
+ ...put.ifMatch !== void 0 ? { headers: { "if-match": put.ifMatch } } : {},
3999
+ signal: put.signal
4000
+ });
4001
+ return { ...await json(response), etag: response.headers.get("etag") };
4002
+ },
4003
+ async get(name, get = {}) {
4004
+ const response = await request("GET", `/v1/profiles/${segment(name)}`, { accept: "application/json", signal: get.signal });
4005
+ return { ...await json(response), etag: response.headers.get("etag") };
4006
+ },
4007
+ async sessions(name, list = {}) {
4008
+ const query = {
4009
+ conversation: list.conversation,
4010
+ before: list.cursor,
4011
+ limit: list.limit,
4012
+ version: list.version,
4013
+ ended: list.ended
4014
+ };
4015
+ const response = await request("GET", `/v1/profiles/${segment(name)}/sessions${queryString(query)}`, {
4016
+ accept: "application/json",
4017
+ signal: list.signal
4018
+ });
4019
+ return json(response);
4020
+ }
4021
+ },
4022
+ conversations: {
4023
+ async start(profile, start) {
4024
+ const body = JSON.stringify({
4025
+ conversation: start.conversation,
4026
+ user: start.user,
4027
+ ...start.runtime !== void 0 ? { runtime: runtimeBody(start.runtime) } : {},
4028
+ ...start.opening !== void 0 ? { opening: start.opening } : {},
4029
+ ...start.seed !== void 0 ? { seed: start.seed } : {}
4030
+ });
4031
+ const response = await request("POST", `/v1/profiles/${segment(profile)}/conversations`, {
4032
+ body,
4033
+ contentType: "application/json",
4034
+ accept: "application/json",
4035
+ signal: start.signal
4036
+ });
4037
+ return json(response);
4038
+ }
4039
+ },
4040
+ turns: {
4041
+ async send(profile, turn) {
4042
+ const response = await request("POST", `/v1/profiles/${segment(profile)}/turns`, {
4043
+ body: turnBody(turn),
4044
+ contentType: "application/json",
4045
+ accept: "application/json",
4046
+ signal: turn.signal
4047
+ });
4048
+ return json(response);
4049
+ },
4050
+ async *stream(profile, turn) {
4051
+ const response = await request("POST", `/v1/profiles/${segment(profile)}/turns`, {
4052
+ body: turnBody(turn),
4053
+ contentType: "application/json",
4054
+ accept: "text/event-stream",
4055
+ signal: turn.signal
4056
+ });
4057
+ if (!response.body) return;
4058
+ yield* readFrames(response.body);
4059
+ }
4060
+ },
4061
+ sessions: {
4062
+ async get(id, get = {}) {
4063
+ const response = await request("GET", `/v1/sessions/${segment(id)}`, { accept: "application/json", signal: get.signal });
4064
+ return json(response);
4065
+ }
4066
+ }
4067
+ };
4068
+ }
4069
+
4070
+ exports.DEFAULT_FIELD_ENDPOINT = DEFAULT_FIELD_ENDPOINT;
4071
+ exports.FIELD_REASONING_EFFORTS = FIELD_REASONING_EFFORTS;
4072
+ exports.FIELD_REFUSAL_CODES = FIELD_REFUSAL_CODES;
4073
+ exports.FieldRefusal = FieldRefusal;
3756
4074
  exports.Probe = Probe;
3757
4075
  exports.SPAN_INTERVAL_KINDS = SPAN_INTERVAL_KINDS;
3758
4076
  exports.SPAN_PAYLOAD_STATES = SPAN_PAYLOAD_STATES;
@@ -3766,6 +4084,7 @@ exports.SpanInputV2Schema = SpanInputV2Schema;
3766
4084
  exports.SpanIntervalSchema = SpanIntervalSchema;
3767
4085
  exports.SpanPayloadSchema = SpanPayloadSchema;
3768
4086
  exports.SpansBatchSchema = SpansBatchSchema;
4087
+ exports.createFieldClient = createFieldClient;
3769
4088
  exports.sightTelemetry = sightTelemetry;
3770
4089
  exports.wrapOpenAI = wrapOpenAI;
3771
4090
  //# sourceMappingURL=index.cjs.map