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