@cultured_computer/sight 0.8.3 → 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/dist/index.cjs CHANGED
@@ -13,6 +13,34 @@ var MAX_PENDING_RETRIES = 50;
13
13
  var SEND_TIMEOUT_MS = 15e3;
14
14
  var MAX_INFLIGHT = 64;
15
15
  var MAX_TURN_BODY_BYTES = 9e5;
16
+ var MAX_ACK_BODY_BYTES = 65536;
17
+ async function readAcknowledgement(response) {
18
+ if (!response.body) return {};
19
+ const reader = response.body.getReader();
20
+ const chunks = [];
21
+ let size = 0;
22
+ try {
23
+ while (true) {
24
+ const { done, value } = await reader.read();
25
+ if (done) break;
26
+ size += value.byteLength;
27
+ if (size > MAX_ACK_BODY_BYTES) throw new Error("acknowledgement exceeds 65536 bytes");
28
+ chunks.push(value);
29
+ }
30
+ const bytes = new Uint8Array(size);
31
+ let offset = 0;
32
+ for (const chunk of chunks) {
33
+ bytes.set(chunk, offset);
34
+ offset += chunk.byteLength;
35
+ }
36
+ const body = JSON.parse(new TextDecoder().decode(bytes));
37
+ return body !== null && typeof body === "object" && "pendingId" in body && typeof body.pendingId === "string" ? { pendingId: body.pendingId } : {};
38
+ } finally {
39
+ await reader.cancel().catch(() => {
40
+ });
41
+ reader.releaseLock();
42
+ }
43
+ }
16
44
  var IngestClient = class {
17
45
  apiKey;
18
46
  endpoint;
@@ -48,7 +76,7 @@ var IngestClient = class {
48
76
  * first drop prints one stderr warning, later ones log only with
49
77
  * `debug: true`.
50
78
  */
51
- async guardedFetch(url, init) {
79
+ async guardedFetch(url, init, consume) {
52
80
  if (this.inFlight >= MAX_INFLIGHT) {
53
81
  if (!this.shedAnnounced) {
54
82
  this.shedAnnounced = true;
@@ -59,9 +87,14 @@ var IngestClient = class {
59
87
  throw new Error(`${MAX_INFLIGHT} sends already in flight; this send was dropped`);
60
88
  }
61
89
  this.inFlight++;
90
+ let response;
62
91
  try {
63
- return await fetch(url, { ...init, signal: AbortSignal.timeout(SEND_TIMEOUT_MS) });
92
+ response = await fetch(url, { ...init, signal: AbortSignal.timeout(SEND_TIMEOUT_MS) });
93
+ await consume?.(response);
94
+ return response;
64
95
  } finally {
96
+ if (response?.body && !response.body.locked) await response.body.cancel().catch(() => {
97
+ });
65
98
  this.inFlight--;
66
99
  }
67
100
  }
@@ -72,8 +105,8 @@ var IngestClient = class {
72
105
  * the time is up is not guaranteed to be sent.
73
106
  */
74
107
  async drainInFlight(timeoutMs = SEND_TIMEOUT_MS) {
75
- const deadline = Date.now() + timeoutMs;
76
- while ((this.inFlight > 0 || this.pendingRetries > 0) && Date.now() < deadline) {
108
+ const deadline = performance.now() + timeoutMs;
109
+ while ((this.inFlight > 0 || this.pendingRetries > 0) && performance.now() < deadline) {
77
110
  await new Promise((r) => setTimeout(r, 50));
78
111
  }
79
112
  }
@@ -103,6 +136,18 @@ var IngestClient = class {
103
136
  "content-type": "application/json"
104
137
  },
105
138
  body
139
+ }, async (response2) => {
140
+ if (!response2.ok) return;
141
+ if (!this.firstCaptureAnnounced) {
142
+ this.firstCaptureAnnounced = true;
143
+ console.error(
144
+ `Sight: first session captured -> ${this.dashboardUrl}/sessions/${encodeURIComponent(turn.sessionExternalId)}`
145
+ );
146
+ }
147
+ if (this.debug) {
148
+ const ack = await readAcknowledgement(response2);
149
+ this.log(`[sight] ingest ok id=${ack.pendingId ?? "?"}`);
150
+ }
106
151
  });
107
152
  const response = await this.retryIfRateLimited(await send(), send);
108
153
  if (response === null) return;
@@ -111,16 +156,6 @@ var IngestClient = class {
111
156
  this.log(`[sight] ingest failed status=${response.status}`);
112
157
  return;
113
158
  }
114
- if (!this.firstCaptureAnnounced) {
115
- this.firstCaptureAnnounced = true;
116
- console.error(
117
- `Sight: first session captured -> ${this.dashboardUrl}/sessions/${encodeURIComponent(turn.sessionExternalId)}`
118
- );
119
- }
120
- if (this.debug) {
121
- const body2 = await response.json();
122
- this.log(`[sight] ingest ok id=${body2.pendingId ?? "?"}`);
123
- }
124
159
  } catch (err) {
125
160
  const msg = err instanceof Error ? err.message : String(err);
126
161
  this.log(`[sight] ingest error: ${msg}`);
@@ -1901,7 +1936,7 @@ function createIntegration(options) {
1901
1936
  call.contextSession = sessionFromContext(e["runtimeContext"]) ?? call.contextSession;
1902
1937
  const model = rec(e["model"]);
1903
1938
  const response = rec(e["response"]);
1904
- const performance = rec(e["performance"]);
1939
+ const performance2 = rec(e["performance"]);
1905
1940
  const content = Array.isArray(e["content"]) ? e["content"] : [];
1906
1941
  const toolNames = [];
1907
1942
  for (const part of content) {
@@ -1927,8 +1962,8 @@ function createIntegration(options) {
1927
1962
  finishReason,
1928
1963
  rawFinishReason: str(e["rawFinishReason"]),
1929
1964
  toolNames,
1930
- latencyMs: ms(performance?.["responseTimeMs"]) ?? (open ? Math.max(0, Date.now() - open.startedAt) : void 0),
1931
- firstTokenMs: ms(performance?.["timeToFirstOutputMs"]),
1965
+ latencyMs: ms(performance2?.["responseTimeMs"]) ?? (open ? Math.max(0, Date.now() - open.startedAt) : void 0),
1966
+ firstTokenMs: ms(performance2?.["timeToFirstOutputMs"]),
1932
1967
  // A stream that failed part way ends its step with this finish
1933
1968
  // reason; the events carry no error message for it.
1934
1969
  error: finishReason === "error" ? 'model call ended with finish reason "error"' : void 0,
@@ -3718,6 +3753,324 @@ var Probe = class {
3718
3753
  }
3719
3754
  };
3720
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;
3721
4074
  exports.Probe = Probe;
3722
4075
  exports.SPAN_INTERVAL_KINDS = SPAN_INTERVAL_KINDS;
3723
4076
  exports.SPAN_PAYLOAD_STATES = SPAN_PAYLOAD_STATES;
@@ -3731,6 +4084,7 @@ exports.SpanInputV2Schema = SpanInputV2Schema;
3731
4084
  exports.SpanIntervalSchema = SpanIntervalSchema;
3732
4085
  exports.SpanPayloadSchema = SpanPayloadSchema;
3733
4086
  exports.SpansBatchSchema = SpansBatchSchema;
4087
+ exports.createFieldClient = createFieldClient;
3734
4088
  exports.sightTelemetry = sightTelemetry;
3735
4089
  exports.wrapOpenAI = wrapOpenAI;
3736
4090
  //# sourceMappingURL=index.cjs.map