@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.js CHANGED
@@ -10,6 +10,34 @@ var MAX_PENDING_RETRIES = 50;
10
10
  var SEND_TIMEOUT_MS = 15e3;
11
11
  var MAX_INFLIGHT = 64;
12
12
  var MAX_TURN_BODY_BYTES = 9e5;
13
+ var MAX_ACK_BODY_BYTES = 65536;
14
+ async function readAcknowledgement(response) {
15
+ if (!response.body) return {};
16
+ const reader = response.body.getReader();
17
+ const chunks = [];
18
+ let size = 0;
19
+ try {
20
+ while (true) {
21
+ const { done, value } = await reader.read();
22
+ if (done) break;
23
+ size += value.byteLength;
24
+ if (size > MAX_ACK_BODY_BYTES) throw new Error("acknowledgement exceeds 65536 bytes");
25
+ chunks.push(value);
26
+ }
27
+ const bytes = new Uint8Array(size);
28
+ let offset = 0;
29
+ for (const chunk of chunks) {
30
+ bytes.set(chunk, offset);
31
+ offset += chunk.byteLength;
32
+ }
33
+ const body = JSON.parse(new TextDecoder().decode(bytes));
34
+ return body !== null && typeof body === "object" && "pendingId" in body && typeof body.pendingId === "string" ? { pendingId: body.pendingId } : {};
35
+ } finally {
36
+ await reader.cancel().catch(() => {
37
+ });
38
+ reader.releaseLock();
39
+ }
40
+ }
13
41
  var IngestClient = class {
14
42
  apiKey;
15
43
  endpoint;
@@ -45,7 +73,7 @@ var IngestClient = class {
45
73
  * first drop prints one stderr warning, later ones log only with
46
74
  * `debug: true`.
47
75
  */
48
- async guardedFetch(url, init) {
76
+ async guardedFetch(url, init, consume) {
49
77
  if (this.inFlight >= MAX_INFLIGHT) {
50
78
  if (!this.shedAnnounced) {
51
79
  this.shedAnnounced = true;
@@ -56,9 +84,14 @@ var IngestClient = class {
56
84
  throw new Error(`${MAX_INFLIGHT} sends already in flight; this send was dropped`);
57
85
  }
58
86
  this.inFlight++;
87
+ let response;
59
88
  try {
60
- return await fetch(url, { ...init, signal: AbortSignal.timeout(SEND_TIMEOUT_MS) });
89
+ response = await fetch(url, { ...init, signal: AbortSignal.timeout(SEND_TIMEOUT_MS) });
90
+ await consume?.(response);
91
+ return response;
61
92
  } finally {
93
+ if (response?.body && !response.body.locked) await response.body.cancel().catch(() => {
94
+ });
62
95
  this.inFlight--;
63
96
  }
64
97
  }
@@ -69,8 +102,8 @@ var IngestClient = class {
69
102
  * the time is up is not guaranteed to be sent.
70
103
  */
71
104
  async drainInFlight(timeoutMs = SEND_TIMEOUT_MS) {
72
- const deadline = Date.now() + timeoutMs;
73
- while ((this.inFlight > 0 || this.pendingRetries > 0) && Date.now() < deadline) {
105
+ const deadline = performance.now() + timeoutMs;
106
+ while ((this.inFlight > 0 || this.pendingRetries > 0) && performance.now() < deadline) {
74
107
  await new Promise((r) => setTimeout(r, 50));
75
108
  }
76
109
  }
@@ -100,6 +133,18 @@ var IngestClient = class {
100
133
  "content-type": "application/json"
101
134
  },
102
135
  body
136
+ }, async (response2) => {
137
+ if (!response2.ok) return;
138
+ if (!this.firstCaptureAnnounced) {
139
+ this.firstCaptureAnnounced = true;
140
+ console.error(
141
+ `Sight: first session captured -> ${this.dashboardUrl}/sessions/${encodeURIComponent(turn.sessionExternalId)}`
142
+ );
143
+ }
144
+ if (this.debug) {
145
+ const ack = await readAcknowledgement(response2);
146
+ this.log(`[sight] ingest ok id=${ack.pendingId ?? "?"}`);
147
+ }
103
148
  });
104
149
  const response = await this.retryIfRateLimited(await send(), send);
105
150
  if (response === null) return;
@@ -108,16 +153,6 @@ var IngestClient = class {
108
153
  this.log(`[sight] ingest failed status=${response.status}`);
109
154
  return;
110
155
  }
111
- if (!this.firstCaptureAnnounced) {
112
- this.firstCaptureAnnounced = true;
113
- console.error(
114
- `Sight: first session captured -> ${this.dashboardUrl}/sessions/${encodeURIComponent(turn.sessionExternalId)}`
115
- );
116
- }
117
- if (this.debug) {
118
- const body2 = await response.json();
119
- this.log(`[sight] ingest ok id=${body2.pendingId ?? "?"}`);
120
- }
121
156
  } catch (err) {
122
157
  const msg = err instanceof Error ? err.message : String(err);
123
158
  this.log(`[sight] ingest error: ${msg}`);
@@ -1898,7 +1933,7 @@ function createIntegration(options) {
1898
1933
  call.contextSession = sessionFromContext(e["runtimeContext"]) ?? call.contextSession;
1899
1934
  const model = rec(e["model"]);
1900
1935
  const response = rec(e["response"]);
1901
- const performance = rec(e["performance"]);
1936
+ const performance2 = rec(e["performance"]);
1902
1937
  const content = Array.isArray(e["content"]) ? e["content"] : [];
1903
1938
  const toolNames = [];
1904
1939
  for (const part of content) {
@@ -1924,8 +1959,8 @@ function createIntegration(options) {
1924
1959
  finishReason,
1925
1960
  rawFinishReason: str(e["rawFinishReason"]),
1926
1961
  toolNames,
1927
- latencyMs: ms(performance?.["responseTimeMs"]) ?? (open ? Math.max(0, Date.now() - open.startedAt) : void 0),
1928
- firstTokenMs: ms(performance?.["timeToFirstOutputMs"]),
1962
+ latencyMs: ms(performance2?.["responseTimeMs"]) ?? (open ? Math.max(0, Date.now() - open.startedAt) : void 0),
1963
+ firstTokenMs: ms(performance2?.["timeToFirstOutputMs"]),
1929
1964
  // A stream that failed part way ends its step with this finish
1930
1965
  // reason; the events carry no error message for it.
1931
1966
  error: finishReason === "error" ? 'model call ended with finish reason "error"' : void 0,
@@ -3715,6 +3750,320 @@ var Probe = class {
3715
3750
  }
3716
3751
  };
3717
3752
 
3718
- 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 };
3753
+ // src/field.ts
3754
+ var DEFAULT_FIELD_ENDPOINT = "https://api.cultured.computer";
3755
+ var FIELD_REFUSAL_CODES = [
3756
+ // The conversation and turn routes, and the rate limit.
3757
+ "invalid_body",
3758
+ "forbidden",
3759
+ "not_enabled",
3760
+ "no_such_profile",
3761
+ "no_such_endpoint",
3762
+ "no_such_conversation",
3763
+ "conversation_unknown",
3764
+ "archived",
3765
+ "revoked",
3766
+ "link_inactive",
3767
+ "conversation_conflict",
3768
+ "opening_forbidden",
3769
+ "opening_conflict",
3770
+ "runtime_forbidden",
3771
+ "invalid_reasoning_effort",
3772
+ "invalid_max_output_tokens",
3773
+ "conversation_ended",
3774
+ "no_live_version",
3775
+ "no_owner",
3776
+ "model_unavailable",
3777
+ "daily_cap",
3778
+ "link_session_cap",
3779
+ "rate_limited",
3780
+ "turn_cap",
3781
+ "stale_turn_index",
3782
+ "record_gap",
3783
+ "busy",
3784
+ "interrupted",
3785
+ "not_connected",
3786
+ "budget",
3787
+ "provider_error",
3788
+ "provider_timeout",
3789
+ "turn_failed",
3790
+ "request_unknown",
3791
+ "request_conflict",
3792
+ "request_pending",
3793
+ "request_interrupted",
3794
+ "replay_expired",
3795
+ // The profile put.
3796
+ "put_in_progress",
3797
+ "scene_live",
3798
+ "precondition_failed",
3799
+ "invalid_consent",
3800
+ "invalid_safeguards",
3801
+ "invalid_scrub",
3802
+ "invalid_fallback",
3803
+ "invalid_scene",
3804
+ // The profile read.
3805
+ "not_a_soul_md",
3806
+ "not_a_scene"
3807
+ ];
3808
+ var FIELD_REASONING_EFFORTS = ["none", "minimal", "low", "medium", "high", "xhigh", "max"];
3809
+ var FieldRefusal = class extends Error {
3810
+ name = "FieldRefusal";
3811
+ /** The HTTP status. */
3812
+ status;
3813
+ /**
3814
+ * The refusal's stable code, one of `FIELD_REFUSAL_CODES` from this
3815
+ * version; a newer API may answer a code this version does not list.
3816
+ * `null` when the answer carries none (401, a 403 for a missing
3817
+ * permission, 413, a 503 while the service drains).
3818
+ */
3819
+ code;
3820
+ /**
3821
+ * Why, when the answer says: the ended reason of a `conversation_ended`,
3822
+ * or the empty-completion reason of a `provider_error`. Otherwise null.
3823
+ */
3824
+ reason;
3825
+ /** `Retry-After` in seconds, when the answer carries one (429, 503, a busy put). */
3826
+ retryAfter;
3827
+ /** A failed turn still answers its notices; show them. Empty otherwise. */
3828
+ notices;
3829
+ /** A failed turn's frames, collected before it failed. Empty otherwise. */
3830
+ events;
3831
+ /** A failed turn's index, when the answer names one. */
3832
+ turnIndex;
3833
+ /** The answer's body as sent: parsed JSON, or the text when it is not JSON. */
3834
+ body;
3835
+ constructor(init) {
3836
+ super(init.message);
3837
+ this.status = init.status;
3838
+ this.code = init.code;
3839
+ this.reason = init.reason;
3840
+ this.retryAfter = init.retryAfter;
3841
+ this.notices = init.notices;
3842
+ this.events = init.events;
3843
+ this.turnIndex = init.turnIndex;
3844
+ this.body = init.body;
3845
+ }
3846
+ };
3847
+ function queryString(query) {
3848
+ const params = new URLSearchParams();
3849
+ for (const [key, value] of Object.entries(query)) {
3850
+ if (value !== void 0) params.append(key, String(value));
3851
+ }
3852
+ const text = params.toString();
3853
+ return text ? `?${text}` : "";
3854
+ }
3855
+ var segment = (value) => encodeURIComponent(value);
3856
+ function parseRetryAfter(value) {
3857
+ if (value === null) return null;
3858
+ const seconds = Number(value);
3859
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds : null;
3860
+ }
3861
+ function isRecord2(value) {
3862
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3863
+ }
3864
+ async function refusalOf(response) {
3865
+ const text = await response.text().catch(() => "");
3866
+ let body = text;
3867
+ try {
3868
+ body = text ? JSON.parse(text) : null;
3869
+ } catch {
3870
+ }
3871
+ const record = isRecord2(body) ? body : {};
3872
+ const events = Array.isArray(record["events"]) ? record["events"] : [];
3873
+ const errorFrame = events.find((frame) => isRecord2(frame) && frame.event === "error");
3874
+ const frameReason = errorFrame && isRecord2(errorFrame.data) ? errorFrame.data["reason"] : void 0;
3875
+ const reason = typeof record["reason"] === "string" ? record["reason"] : typeof frameReason === "string" ? frameReason : null;
3876
+ const sentence = typeof record["error"] === "string" ? record["error"] : null;
3877
+ return new FieldRefusal({
3878
+ status: response.status,
3879
+ message: sentence ?? `the Field API answered ${response.status}`,
3880
+ code: typeof record["code"] === "string" ? record["code"] : null,
3881
+ reason,
3882
+ retryAfter: parseRetryAfter(response.headers.get("retry-after")),
3883
+ notices: Array.isArray(record["notices"]) ? record["notices"] : [],
3884
+ events,
3885
+ turnIndex: typeof record["turnIndex"] === "number" ? record["turnIndex"] : null,
3886
+ body
3887
+ });
3888
+ }
3889
+ var KNOWN_FRAMES = /* @__PURE__ */ new Set(["run", "notice", "reads", "delta", "events", "done", "error"]);
3890
+ function frameOf(name, raw) {
3891
+ let data = raw;
3892
+ try {
3893
+ data = JSON.parse(raw);
3894
+ } catch {
3895
+ }
3896
+ if (KNOWN_FRAMES.has(name)) return { event: name, data };
3897
+ return { event: "other", name, data };
3898
+ }
3899
+ async function* readFrames(body) {
3900
+ const reader = body.getReader();
3901
+ const decoder = new TextDecoder();
3902
+ let buffer = "";
3903
+ let name = "";
3904
+ let data = [];
3905
+ try {
3906
+ while (true) {
3907
+ const { done, value } = await reader.read();
3908
+ buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });
3909
+ let newline;
3910
+ while ((newline = buffer.search(/\r\n|\r|\n/)) !== -1) {
3911
+ if (buffer[newline] === "\r" && newline === buffer.length - 1 && !done) break;
3912
+ const width = buffer.startsWith("\r\n", newline) ? 2 : 1;
3913
+ const line = buffer.slice(0, newline);
3914
+ buffer = buffer.slice(newline + width);
3915
+ if (line === "") {
3916
+ if (data.length > 0) yield frameOf(name || "message", data.join("\n"));
3917
+ name = "";
3918
+ data = [];
3919
+ continue;
3920
+ }
3921
+ if (line.startsWith(":")) continue;
3922
+ const colon = line.indexOf(":");
3923
+ const field = colon === -1 ? line : line.slice(0, colon);
3924
+ let content = colon === -1 ? "" : line.slice(colon + 1);
3925
+ if (content.startsWith(" ")) content = content.slice(1);
3926
+ if (field === "event") name = content;
3927
+ else if (field === "data") data.push(content);
3928
+ }
3929
+ if (done) return;
3930
+ }
3931
+ } finally {
3932
+ await reader.cancel().catch(() => {
3933
+ });
3934
+ reader.releaseLock();
3935
+ }
3936
+ }
3937
+ function runtimeBody(runtime) {
3938
+ const out = {};
3939
+ if (runtime.model !== void 0) out.model = runtime.model;
3940
+ if (runtime.temperature !== void 0) out.temperature = runtime.temperature;
3941
+ if (runtime.maxOutputTokens !== void 0) out.maxOutputTokens = runtime.maxOutputTokens;
3942
+ if (runtime.reasoningEffort !== void 0) out.reasoningEffort = runtime.reasoningEffort;
3943
+ return out;
3944
+ }
3945
+ function createFieldClient(options) {
3946
+ if (!options || typeof options.apiKey !== "string" || options.apiKey.trim() === "") {
3947
+ throw new TypeError("createFieldClient: apiKey is required (an App key; keep it on a server)");
3948
+ }
3949
+ const apiKey = options.apiKey;
3950
+ const endpoint = (options.endpoint ?? DEFAULT_FIELD_ENDPOINT).replace(/\/+$/, "");
3951
+ async function request(method, path, init) {
3952
+ const headers = { authorization: `Bearer ${apiKey}`, accept: init.accept, ...init.headers };
3953
+ if (init.contentType) headers["content-type"] = init.contentType;
3954
+ const response = await fetch(`${endpoint}${path}`, {
3955
+ method,
3956
+ headers,
3957
+ ...init.body !== void 0 ? { body: init.body } : {},
3958
+ ...init.signal ? { signal: init.signal } : {}
3959
+ });
3960
+ if (!response.ok) throw await refusalOf(response);
3961
+ return response;
3962
+ }
3963
+ async function json(response) {
3964
+ return await response.json();
3965
+ }
3966
+ function turnBody(input) {
3967
+ return JSON.stringify({
3968
+ conversation: input.conversation,
3969
+ message: input.message,
3970
+ ...input.resume ? { resume: { turnIndex: input.resume.turnIndex } } : {}
3971
+ });
3972
+ }
3973
+ return {
3974
+ profiles: {
3975
+ async put(name, soulMarkdown, put = {}) {
3976
+ const query = {
3977
+ model: put.model,
3978
+ temperature: put.temperature,
3979
+ maxOutputTokens: put.maxOutputTokens,
3980
+ reasoningEffort: put.reasoningEffort,
3981
+ fallback: put.fallback,
3982
+ consent: put.consent,
3983
+ safeguards: put.safeguards === void 0 ? void 0 : put.safeguards === "none" ? "none" : put.safeguards.join(","),
3984
+ scrub: put.scrub,
3985
+ idleMinutes: put.idleMinutes,
3986
+ turnsPerConversation: put.turnsPerConversation,
3987
+ conversationsPerDay: put.conversationsPerDay,
3988
+ dryRun: put.dryRun,
3989
+ force: put.force
3990
+ };
3991
+ const response = await request("PUT", `/v1/profiles/${segment(name)}${queryString(query)}`, {
3992
+ body: soulMarkdown,
3993
+ contentType: "text/markdown",
3994
+ accept: "application/json",
3995
+ ...put.ifMatch !== void 0 ? { headers: { "if-match": put.ifMatch } } : {},
3996
+ signal: put.signal
3997
+ });
3998
+ return { ...await json(response), etag: response.headers.get("etag") };
3999
+ },
4000
+ async get(name, get = {}) {
4001
+ const response = await request("GET", `/v1/profiles/${segment(name)}`, { accept: "application/json", signal: get.signal });
4002
+ return { ...await json(response), etag: response.headers.get("etag") };
4003
+ },
4004
+ async sessions(name, list = {}) {
4005
+ const query = {
4006
+ conversation: list.conversation,
4007
+ before: list.cursor,
4008
+ limit: list.limit,
4009
+ version: list.version,
4010
+ ended: list.ended
4011
+ };
4012
+ const response = await request("GET", `/v1/profiles/${segment(name)}/sessions${queryString(query)}`, {
4013
+ accept: "application/json",
4014
+ signal: list.signal
4015
+ });
4016
+ return json(response);
4017
+ }
4018
+ },
4019
+ conversations: {
4020
+ async start(profile, start) {
4021
+ const body = JSON.stringify({
4022
+ conversation: start.conversation,
4023
+ user: start.user,
4024
+ ...start.runtime !== void 0 ? { runtime: runtimeBody(start.runtime) } : {},
4025
+ ...start.opening !== void 0 ? { opening: start.opening } : {},
4026
+ ...start.seed !== void 0 ? { seed: start.seed } : {}
4027
+ });
4028
+ const response = await request("POST", `/v1/profiles/${segment(profile)}/conversations`, {
4029
+ body,
4030
+ contentType: "application/json",
4031
+ accept: "application/json",
4032
+ signal: start.signal
4033
+ });
4034
+ return json(response);
4035
+ }
4036
+ },
4037
+ turns: {
4038
+ async send(profile, turn) {
4039
+ const response = await request("POST", `/v1/profiles/${segment(profile)}/turns`, {
4040
+ body: turnBody(turn),
4041
+ contentType: "application/json",
4042
+ accept: "application/json",
4043
+ signal: turn.signal
4044
+ });
4045
+ return json(response);
4046
+ },
4047
+ async *stream(profile, turn) {
4048
+ const response = await request("POST", `/v1/profiles/${segment(profile)}/turns`, {
4049
+ body: turnBody(turn),
4050
+ contentType: "application/json",
4051
+ accept: "text/event-stream",
4052
+ signal: turn.signal
4053
+ });
4054
+ if (!response.body) return;
4055
+ yield* readFrames(response.body);
4056
+ }
4057
+ },
4058
+ sessions: {
4059
+ async get(id, get = {}) {
4060
+ const response = await request("GET", `/v1/sessions/${segment(id)}`, { accept: "application/json", signal: get.signal });
4061
+ return json(response);
4062
+ }
4063
+ }
4064
+ };
4065
+ }
4066
+
4067
+ 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 };
3719
4068
  //# sourceMappingURL=index.js.map
3720
4069
  //# sourceMappingURL=index.js.map