@cultured_computer/sight 0.8.4 → 0.10.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/dist/index.js CHANGED
@@ -2458,6 +2458,7 @@ var UserOutcomeSchema = z.object({
2458
2458
  /** Thumbs-up / thumbs-down widget value. */
2459
2459
  thumbs: z.enum(["up", "down"]).optional()
2460
2460
  });
2461
+ var REPLIES_BY = ["model", "person"];
2461
2462
  var TurnInputSchema = z.object({
2462
2463
  deploymentSlug: z.string().min(1),
2463
2464
  sessionExternalId: z.string().min(1),
@@ -2565,6 +2566,16 @@ var TurnInputSchema = z.object({
2565
2566
  * `metadata` key so it has a durable landing place.
2566
2567
  */
2567
2568
  clientContext: z.record(z.string(), z.unknown()).optional(),
2569
+ /**
2570
+ * Who writes the replies of this session: a model (the default) or a
2571
+ * person, as in a call between two people where one of them is the
2572
+ * agent. Session context like openedVia: it rides the first turn, the
2573
+ * worker writes it on the session at create (sessions.subject_type,
2574
+ * 'agent' or 'human') and ignores it on later turns. A session that
2575
+ * says a person replies carries no served model, and a judge run reads
2576
+ * that as a declaration, never as a model that went unrecorded.
2577
+ */
2578
+ repliesBy: z.enum(REPLIES_BY).optional(),
2568
2579
  payload: z.record(z.string(), z.unknown())
2569
2580
  });
2570
2581
  var SessionEndSchema2 = z.object({
@@ -3750,6 +3761,321 @@ var Probe = class {
3750
3761
  }
3751
3762
  };
3752
3763
 
3753
- export { Probe, SPAN_INTERVAL_KINDS, SPAN_PAYLOAD_STATES, SPAN_STATUSES, SPAN_TYPES, SPAN_V2_STATUSES, Probe as Sight, SpanInputSchema, SpanInputV1Schema, SpanInputV2Schema, SpanIntervalSchema, SpanPayloadSchema, SpansBatchSchema, sightTelemetry, wrapOpenAI };
3764
+ // src/field.ts
3765
+ var DEFAULT_FIELD_ENDPOINT = "https://api.cultured.computer";
3766
+ var FIELD_REFUSAL_CODES = [
3767
+ // The conversation and turn routes, and the rate limit.
3768
+ "invalid_body",
3769
+ "forbidden",
3770
+ "not_enabled",
3771
+ "no_such_profile",
3772
+ "no_such_endpoint",
3773
+ "no_such_conversation",
3774
+ "conversation_unknown",
3775
+ "archived",
3776
+ "revoked",
3777
+ "link_inactive",
3778
+ "conversation_conflict",
3779
+ "opening_forbidden",
3780
+ "opening_conflict",
3781
+ "runtime_forbidden",
3782
+ "invalid_reasoning_effort",
3783
+ "invalid_max_output_tokens",
3784
+ "invalid_reply_check",
3785
+ "conversation_ended",
3786
+ "no_live_version",
3787
+ "no_owner",
3788
+ "model_unavailable",
3789
+ "daily_cap",
3790
+ "link_session_cap",
3791
+ "rate_limited",
3792
+ "turn_cap",
3793
+ "stale_turn_index",
3794
+ "record_gap",
3795
+ "busy",
3796
+ "interrupted",
3797
+ "not_connected",
3798
+ "budget",
3799
+ "provider_error",
3800
+ "provider_timeout",
3801
+ "turn_failed",
3802
+ "request_unknown",
3803
+ "request_conflict",
3804
+ "request_pending",
3805
+ "request_interrupted",
3806
+ "replay_expired",
3807
+ // The profile put.
3808
+ "put_in_progress",
3809
+ "scene_live",
3810
+ "precondition_failed",
3811
+ "invalid_consent",
3812
+ "invalid_safeguards",
3813
+ "invalid_scrub",
3814
+ "invalid_fallback",
3815
+ "invalid_scene",
3816
+ // The profile read.
3817
+ "not_a_soul_md",
3818
+ "not_a_scene"
3819
+ ];
3820
+ var FIELD_REASONING_EFFORTS = ["none", "minimal", "low", "medium", "high", "xhigh", "max"];
3821
+ var FieldRefusal = class extends Error {
3822
+ name = "FieldRefusal";
3823
+ /** The HTTP status. */
3824
+ status;
3825
+ /**
3826
+ * The refusal's stable code, one of `FIELD_REFUSAL_CODES` from this
3827
+ * version; a newer API may answer a code this version does not list.
3828
+ * `null` when the answer carries none (401, a 403 for a missing
3829
+ * permission, 413, a 503 while the service drains).
3830
+ */
3831
+ code;
3832
+ /**
3833
+ * Why, when the answer says: the ended reason of a `conversation_ended`,
3834
+ * or the empty-completion reason of a `provider_error`. Otherwise null.
3835
+ */
3836
+ reason;
3837
+ /** `Retry-After` in seconds, when the answer carries one (429, 503, a busy put). */
3838
+ retryAfter;
3839
+ /** A failed turn still answers its notices; show them. Empty otherwise. */
3840
+ notices;
3841
+ /** A failed turn's frames, collected before it failed. Empty otherwise. */
3842
+ events;
3843
+ /** A failed turn's index, when the answer names one. */
3844
+ turnIndex;
3845
+ /** The answer's body as sent: parsed JSON, or the text when it is not JSON. */
3846
+ body;
3847
+ constructor(init) {
3848
+ super(init.message);
3849
+ this.status = init.status;
3850
+ this.code = init.code;
3851
+ this.reason = init.reason;
3852
+ this.retryAfter = init.retryAfter;
3853
+ this.notices = init.notices;
3854
+ this.events = init.events;
3855
+ this.turnIndex = init.turnIndex;
3856
+ this.body = init.body;
3857
+ }
3858
+ };
3859
+ function queryString(query) {
3860
+ const params = new URLSearchParams();
3861
+ for (const [key, value] of Object.entries(query)) {
3862
+ if (value !== void 0) params.append(key, String(value));
3863
+ }
3864
+ const text = params.toString();
3865
+ return text ? `?${text}` : "";
3866
+ }
3867
+ var segment = (value) => encodeURIComponent(value);
3868
+ function parseRetryAfter(value) {
3869
+ if (value === null) return null;
3870
+ const seconds = Number(value);
3871
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds : null;
3872
+ }
3873
+ function isRecord2(value) {
3874
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3875
+ }
3876
+ async function refusalOf(response) {
3877
+ const text = await response.text().catch(() => "");
3878
+ let body = text;
3879
+ try {
3880
+ body = text ? JSON.parse(text) : null;
3881
+ } catch {
3882
+ }
3883
+ const record = isRecord2(body) ? body : {};
3884
+ const events = Array.isArray(record["events"]) ? record["events"] : [];
3885
+ const errorFrame = events.find((frame) => isRecord2(frame) && frame.event === "error");
3886
+ const frameReason = errorFrame && isRecord2(errorFrame.data) ? errorFrame.data["reason"] : void 0;
3887
+ const reason = typeof record["reason"] === "string" ? record["reason"] : typeof frameReason === "string" ? frameReason : null;
3888
+ const sentence = typeof record["error"] === "string" ? record["error"] : null;
3889
+ return new FieldRefusal({
3890
+ status: response.status,
3891
+ message: sentence ?? `the Field API answered ${response.status}`,
3892
+ code: typeof record["code"] === "string" ? record["code"] : null,
3893
+ reason,
3894
+ retryAfter: parseRetryAfter(response.headers.get("retry-after")),
3895
+ notices: Array.isArray(record["notices"]) ? record["notices"] : [],
3896
+ events,
3897
+ turnIndex: typeof record["turnIndex"] === "number" ? record["turnIndex"] : null,
3898
+ body
3899
+ });
3900
+ }
3901
+ var KNOWN_FRAMES = /* @__PURE__ */ new Set(["run", "notice", "reads", "delta", "events", "done", "error"]);
3902
+ function frameOf(name, raw) {
3903
+ let data = raw;
3904
+ try {
3905
+ data = JSON.parse(raw);
3906
+ } catch {
3907
+ }
3908
+ if (KNOWN_FRAMES.has(name)) return { event: name, data };
3909
+ return { event: "other", name, data };
3910
+ }
3911
+ async function* readFrames(body) {
3912
+ const reader = body.getReader();
3913
+ const decoder = new TextDecoder();
3914
+ let buffer = "";
3915
+ let name = "";
3916
+ let data = [];
3917
+ try {
3918
+ while (true) {
3919
+ const { done, value } = await reader.read();
3920
+ buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });
3921
+ let newline;
3922
+ while ((newline = buffer.search(/\r\n|\r|\n/)) !== -1) {
3923
+ if (buffer[newline] === "\r" && newline === buffer.length - 1 && !done) break;
3924
+ const width = buffer.startsWith("\r\n", newline) ? 2 : 1;
3925
+ const line = buffer.slice(0, newline);
3926
+ buffer = buffer.slice(newline + width);
3927
+ if (line === "") {
3928
+ if (data.length > 0) yield frameOf(name || "message", data.join("\n"));
3929
+ name = "";
3930
+ data = [];
3931
+ continue;
3932
+ }
3933
+ if (line.startsWith(":")) continue;
3934
+ const colon = line.indexOf(":");
3935
+ const field = colon === -1 ? line : line.slice(0, colon);
3936
+ let content = colon === -1 ? "" : line.slice(colon + 1);
3937
+ if (content.startsWith(" ")) content = content.slice(1);
3938
+ if (field === "event") name = content;
3939
+ else if (field === "data") data.push(content);
3940
+ }
3941
+ if (done) return;
3942
+ }
3943
+ } finally {
3944
+ await reader.cancel().catch(() => {
3945
+ });
3946
+ reader.releaseLock();
3947
+ }
3948
+ }
3949
+ function runtimeBody(runtime) {
3950
+ const out = {};
3951
+ if (runtime.model !== void 0) out.model = runtime.model;
3952
+ if (runtime.temperature !== void 0) out.temperature = runtime.temperature;
3953
+ if (runtime.maxOutputTokens !== void 0) out.maxOutputTokens = runtime.maxOutputTokens;
3954
+ if (runtime.reasoningEffort !== void 0) out.reasoningEffort = runtime.reasoningEffort;
3955
+ return out;
3956
+ }
3957
+ function createFieldClient(options) {
3958
+ if (!options || typeof options.apiKey !== "string" || options.apiKey.trim() === "") {
3959
+ throw new TypeError("createFieldClient: apiKey is required (an App key; keep it on a server)");
3960
+ }
3961
+ const apiKey = options.apiKey;
3962
+ const endpoint = (options.endpoint ?? DEFAULT_FIELD_ENDPOINT).replace(/\/+$/, "");
3963
+ async function request(method, path, init) {
3964
+ const headers = { authorization: `Bearer ${apiKey}`, accept: init.accept, ...init.headers };
3965
+ if (init.contentType) headers["content-type"] = init.contentType;
3966
+ const response = await fetch(`${endpoint}${path}`, {
3967
+ method,
3968
+ headers,
3969
+ ...init.body !== void 0 ? { body: init.body } : {},
3970
+ ...init.signal ? { signal: init.signal } : {}
3971
+ });
3972
+ if (!response.ok) throw await refusalOf(response);
3973
+ return response;
3974
+ }
3975
+ async function json(response) {
3976
+ return await response.json();
3977
+ }
3978
+ function turnBody(input) {
3979
+ return JSON.stringify({
3980
+ conversation: input.conversation,
3981
+ message: input.message,
3982
+ ...input.resume ? { resume: { turnIndex: input.resume.turnIndex } } : {}
3983
+ });
3984
+ }
3985
+ return {
3986
+ profiles: {
3987
+ async put(name, soulMarkdown, put = {}) {
3988
+ const query = {
3989
+ model: put.model,
3990
+ temperature: put.temperature,
3991
+ maxOutputTokens: put.maxOutputTokens,
3992
+ reasoningEffort: put.reasoningEffort,
3993
+ fallback: put.fallback,
3994
+ consent: put.consent,
3995
+ safeguards: put.safeguards === void 0 ? void 0 : put.safeguards === "none" ? "none" : put.safeguards.join(","),
3996
+ scrub: put.scrub,
3997
+ idleMinutes: put.idleMinutes,
3998
+ turnsPerConversation: put.turnsPerConversation,
3999
+ conversationsPerDay: put.conversationsPerDay,
4000
+ dryRun: put.dryRun,
4001
+ force: put.force
4002
+ };
4003
+ const response = await request("PUT", `/v1/profiles/${segment(name)}${queryString(query)}`, {
4004
+ body: soulMarkdown,
4005
+ contentType: "text/markdown",
4006
+ accept: "application/json",
4007
+ ...put.ifMatch !== void 0 ? { headers: { "if-match": put.ifMatch } } : {},
4008
+ signal: put.signal
4009
+ });
4010
+ return { ...await json(response), etag: response.headers.get("etag") };
4011
+ },
4012
+ async get(name, get = {}) {
4013
+ const response = await request("GET", `/v1/profiles/${segment(name)}`, { accept: "application/json", signal: get.signal });
4014
+ return { ...await json(response), etag: response.headers.get("etag") };
4015
+ },
4016
+ async sessions(name, list = {}) {
4017
+ const query = {
4018
+ conversation: list.conversation,
4019
+ before: list.cursor,
4020
+ limit: list.limit,
4021
+ version: list.version,
4022
+ ended: list.ended
4023
+ };
4024
+ const response = await request("GET", `/v1/profiles/${segment(name)}/sessions${queryString(query)}`, {
4025
+ accept: "application/json",
4026
+ signal: list.signal
4027
+ });
4028
+ return json(response);
4029
+ }
4030
+ },
4031
+ conversations: {
4032
+ async start(profile, start) {
4033
+ const body = JSON.stringify({
4034
+ conversation: start.conversation,
4035
+ user: start.user,
4036
+ ...start.runtime !== void 0 ? { runtime: runtimeBody(start.runtime) } : {},
4037
+ ...start.opening !== void 0 ? { opening: start.opening } : {},
4038
+ ...start.seed !== void 0 ? { seed: start.seed } : {}
4039
+ });
4040
+ const response = await request("POST", `/v1/profiles/${segment(profile)}/conversations`, {
4041
+ body,
4042
+ contentType: "application/json",
4043
+ accept: "application/json",
4044
+ signal: start.signal
4045
+ });
4046
+ return json(response);
4047
+ }
4048
+ },
4049
+ turns: {
4050
+ async send(profile, turn) {
4051
+ const response = await request("POST", `/v1/profiles/${segment(profile)}/turns`, {
4052
+ body: turnBody(turn),
4053
+ contentType: "application/json",
4054
+ accept: "application/json",
4055
+ signal: turn.signal
4056
+ });
4057
+ return json(response);
4058
+ },
4059
+ async *stream(profile, turn) {
4060
+ const response = await request("POST", `/v1/profiles/${segment(profile)}/turns`, {
4061
+ body: turnBody(turn),
4062
+ contentType: "application/json",
4063
+ accept: "text/event-stream",
4064
+ signal: turn.signal
4065
+ });
4066
+ if (!response.body) return;
4067
+ yield* readFrames(response.body);
4068
+ }
4069
+ },
4070
+ sessions: {
4071
+ async get(id, get = {}) {
4072
+ const response = await request("GET", `/v1/sessions/${segment(id)}`, { accept: "application/json", signal: get.signal });
4073
+ return json(response);
4074
+ }
4075
+ }
4076
+ };
4077
+ }
4078
+
4079
+ export { DEFAULT_FIELD_ENDPOINT, FIELD_REASONING_EFFORTS, FIELD_REFUSAL_CODES, FieldRefusal, Probe, SPAN_INTERVAL_KINDS, SPAN_PAYLOAD_STATES, SPAN_STATUSES, SPAN_TYPES, SPAN_V2_STATUSES, Probe as Sight, SpanInputSchema, SpanInputV1Schema, SpanInputV2Schema, SpanIntervalSchema, SpanPayloadSchema, SpansBatchSchema, createFieldClient, sightTelemetry, wrapOpenAI };
3754
4080
  //# sourceMappingURL=index.js.map
3755
4081
  //# sourceMappingURL=index.js.map