@makinbakin/sdk 0.0.0-bootstrap.0 → 0.0.1-rc.2

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/utils/index.js CHANGED
@@ -1824,9 +1824,277 @@ function formatSize(bytes) {
1824
1824
  function isStale(timestamp, thresholdMs = 15 * 60 * 1000) {
1825
1825
  return Date.now() - new Date(timestamp).getTime() > thresholdMs;
1826
1826
  }
1827
+ // src/components/integrated-brainstorm/session.ts
1828
+ var ACTIVITY_CONTENT_MAX_CHARS = 500;
1829
+ var ACTIVITY_PREVIEW_MAX_CHARS = 2000;
1830
+ var ACTIVITY_METADATA_MAX_CHARS = 4000;
1831
+ var ACTIVITY_DATA_MAX_KEYS = 24;
1832
+ function brainstormThreadId(scope, entityId, agentId) {
1833
+ return [scope, entityId, agentId].map(threadIdPart).join(":");
1834
+ }
1835
+ function normalizeBrainstormActivityForStorage(activity) {
1836
+ const content = typeof activity.content === "string" ? truncate(activity.content.trim(), ACTIVITY_CONTENT_MAX_CHARS) : "";
1837
+ if (!content)
1838
+ return null;
1839
+ const data = normalizeActivityData(activity.data);
1840
+ return {
1841
+ kind: typeof activity.kind === "string" && activity.kind ? activity.kind : "runtime_status",
1842
+ content,
1843
+ ...data !== undefined ? { data } : {}
1844
+ };
1845
+ }
1846
+ function normalizeBrainstormActivityMessageForStorage(activity) {
1847
+ const normalized = normalizeBrainstormActivityForStorage(activity);
1848
+ if (!normalized)
1849
+ return null;
1850
+ return {
1851
+ role: "activity",
1852
+ kind: normalized.kind,
1853
+ content: normalized.content,
1854
+ ...normalized.data !== undefined ? { data: normalized.data } : {}
1855
+ };
1856
+ }
1857
+ function threadIdPart(value) {
1858
+ const trimmed = value.trim();
1859
+ return encodeURIComponent(trimmed || "default");
1860
+ }
1861
+ function normalizeActivityData(data) {
1862
+ if (data === undefined)
1863
+ return;
1864
+ if (!isRecord(data))
1865
+ return normalizeActivityValue(data, "value");
1866
+ const out = {};
1867
+ let count = 0;
1868
+ for (const [key, value] of Object.entries(data)) {
1869
+ if (count >= ACTIVITY_DATA_MAX_KEYS) {
1870
+ out.truncatedKeys = Object.keys(data).length - count;
1871
+ break;
1872
+ }
1873
+ out[key] = normalizeActivityValue(value, key);
1874
+ count += 1;
1875
+ }
1876
+ return out;
1877
+ }
1878
+ function normalizeActivityValue(value, key) {
1879
+ if (typeof value === "string") {
1880
+ const max = isPreviewKey(key) ? ACTIVITY_PREVIEW_MAX_CHARS : ACTIVITY_METADATA_MAX_CHARS;
1881
+ return truncate(value, max);
1882
+ }
1883
+ if (typeof value === "number" || typeof value === "boolean" || value === null)
1884
+ return value;
1885
+ if (value === undefined)
1886
+ return;
1887
+ return truncate(stringify(value), ACTIVITY_METADATA_MAX_CHARS);
1888
+ }
1889
+ function isPreviewKey(key) {
1890
+ return key === "inputPreview" || key === "argumentsPreview" || key === "outputPreview" || key === "resultPreview";
1891
+ }
1892
+ function stringify(value) {
1893
+ try {
1894
+ return JSON.stringify(value);
1895
+ } catch {
1896
+ return String(value);
1897
+ }
1898
+ }
1899
+ function truncate(value, maxChars) {
1900
+ if (value.length <= maxChars)
1901
+ return value;
1902
+ return `${value.slice(0, Math.max(0, maxChars - 3))}...`;
1903
+ }
1904
+ function isRecord(value) {
1905
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
1906
+ }
1907
+
1908
+ // src/components/integrated-brainstorm/activity.ts
1909
+ function newActivityId() {
1910
+ return `act-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
1911
+ }
1912
+ function runtimeChunkToBrainstormActivity(chunk) {
1913
+ if (chunk.type === "status") {
1914
+ return {
1915
+ kind: "runtime_status",
1916
+ content: chunk.content || "Agent status update",
1917
+ data: chunk.data
1918
+ };
1919
+ }
1920
+ if (chunk.type === "tool") {
1921
+ return {
1922
+ kind: "tool_call",
1923
+ content: chunk.content || "Tool call",
1924
+ data: chunk.data
1925
+ };
1926
+ }
1927
+ if (chunk.type === "error") {
1928
+ return {
1929
+ kind: "error",
1930
+ content: chunk.content || "Runtime stream error",
1931
+ data: chunk.data
1932
+ };
1933
+ }
1934
+ return null;
1935
+ }
1936
+ function brainstormActivityMessageFromCustom(name, data) {
1937
+ if (name !== "activity")
1938
+ return null;
1939
+ const payload = data && typeof data === "object" && "activity" in data ? data.activity : data;
1940
+ if (!payload || typeof payload !== "object")
1941
+ return null;
1942
+ const activity = payload;
1943
+ const content = typeof activity.content === "string" ? activity.content : "";
1944
+ if (!content)
1945
+ return null;
1946
+ const normalized = normalizeBrainstormActivityForStorage({
1947
+ kind: typeof activity.kind === "string" ? activity.kind : "runtime_status",
1948
+ content,
1949
+ data: activity.data
1950
+ });
1951
+ if (!normalized)
1952
+ return null;
1953
+ return {
1954
+ id: typeof activity.id === "string" ? activity.id : newActivityId(),
1955
+ role: "activity",
1956
+ kind: normalized.kind,
1957
+ content: normalized.content,
1958
+ ...normalized.data !== undefined ? { data: normalized.data } : {},
1959
+ timestamp: typeof activity.timestamp === "string" ? activity.timestamp : new Date().toISOString()
1960
+ };
1961
+ }
1962
+ function toBrainstormTimeline(agentId, input) {
1963
+ return [
1964
+ ...input.messages.map((message) => ({
1965
+ id: message.id,
1966
+ role: message.role === "user" ? "user" : "assistant",
1967
+ content: message.content,
1968
+ agentId: message.role === "user" ? undefined : agentId,
1969
+ timestamp: message.timestamp
1970
+ })),
1971
+ ...(input.activities ?? []).map((activity) => ({
1972
+ id: activity.id,
1973
+ role: "activity",
1974
+ kind: activity.kind,
1975
+ content: activity.content,
1976
+ data: activity.data,
1977
+ timestamp: activity.timestamp
1978
+ }))
1979
+ ].sort((a, b) => {
1980
+ const aTime = a.timestamp ? Date.parse(a.timestamp) : 0;
1981
+ const bTime = b.timestamp ? Date.parse(b.timestamp) : 0;
1982
+ return aTime - bTime;
1983
+ });
1984
+ }
1985
+ // src/components/integrated-brainstorm/sse.ts
1986
+ async function readBrainstormSseResponse(response, ctx, options = {}) {
1987
+ if (!response.ok || !response.body) {
1988
+ const text = await response.text().catch(() => "");
1989
+ throw new Error(text || `Server returned ${response.status}`);
1990
+ }
1991
+ const reader = response.body.getReader();
1992
+ const abort = () => {
1993
+ reader.cancel().catch(() => {});
1994
+ };
1995
+ ctx.signal.addEventListener("abort", abort, { once: true });
1996
+ const decoder = new TextDecoder;
1997
+ let buffer = "";
1998
+ let accumulated = "";
1999
+ let finalContent = "";
2000
+ const dispatch = (frame) => {
2001
+ if (frame.event === "token") {
2002
+ const text = textField(frame.data, "text");
2003
+ accumulated += text;
2004
+ ctx.onToken(text);
2005
+ return;
2006
+ }
2007
+ if (frame.event === "activity") {
2008
+ ctx.onCustom?.("activity", frame.data);
2009
+ return;
2010
+ }
2011
+ if (frame.event === "done") {
2012
+ finalContent = textField(frame.data, "content") || accumulated;
2013
+ return;
2014
+ }
2015
+ if (frame.event === "error") {
2016
+ throw new Error(textField(frame.data, "message") || "Unknown error");
2017
+ }
2018
+ if (options.onCustomEvent?.(frame.event, frame.data) === true)
2019
+ return;
2020
+ ctx.onCustom?.(frame.event, frame.data);
2021
+ };
2022
+ try {
2023
+ while (true) {
2024
+ if (ctx.signal.aborted)
2025
+ throw abortError();
2026
+ const { done, value } = await reader.read();
2027
+ if (done)
2028
+ break;
2029
+ buffer += decoder.decode(value, { stream: true });
2030
+ const parsed2 = drainSseFrames(buffer);
2031
+ buffer = parsed2.remainder;
2032
+ for (const frame of parsed2.frames)
2033
+ dispatch(frame);
2034
+ }
2035
+ buffer += decoder.decode();
2036
+ const parsed = drainSseFrames(buffer, true);
2037
+ for (const frame of parsed.frames)
2038
+ dispatch(frame);
2039
+ } finally {
2040
+ ctx.signal.removeEventListener("abort", abort);
2041
+ reader.releaseLock();
2042
+ }
2043
+ return { content: finalContent || accumulated };
2044
+ }
2045
+ function drainSseFrames(input, flush = false) {
2046
+ const parts = input.split(/\r?\n\r?\n/);
2047
+ const remainder = flush ? "" : parts.pop() ?? "";
2048
+ const frames = parts.map(parseSseFrame).filter((frame) => frame !== null);
2049
+ if (flush && parts.length === 0 && input.trim()) {
2050
+ const frame = parseSseFrame(input);
2051
+ if (frame)
2052
+ frames.push(frame);
2053
+ }
2054
+ return { frames, remainder };
2055
+ }
2056
+ function parseSseFrame(frame) {
2057
+ let event = "message";
2058
+ const dataLines = [];
2059
+ for (const rawLine of frame.split(/\r?\n/)) {
2060
+ const line = rawLine.trimEnd();
2061
+ if (line.startsWith("event:")) {
2062
+ event = line.slice("event:".length).trim();
2063
+ } else if (line.startsWith("data:")) {
2064
+ dataLines.push(line.slice("data:".length).trimStart());
2065
+ }
2066
+ }
2067
+ if (dataLines.length === 0)
2068
+ return null;
2069
+ const rawData = dataLines.join(`
2070
+ `);
2071
+ let data = rawData;
2072
+ try {
2073
+ data = JSON.parse(rawData);
2074
+ } catch {}
2075
+ return { event, data };
2076
+ }
2077
+ function textField(data, key) {
2078
+ if (!data || typeof data !== "object")
2079
+ return "";
2080
+ const value = data[key];
2081
+ return typeof value === "string" ? value : "";
2082
+ }
2083
+ function abortError() {
2084
+ const err = new Error("Aborted");
2085
+ err.name = "AbortError";
2086
+ return err;
2087
+ }
1827
2088
  export {
2089
+ toBrainstormTimeline,
2090
+ runtimeChunkToBrainstormActivity,
2091
+ readBrainstormSseResponse,
2092
+ normalizeBrainstormActivityMessageForStorage,
2093
+ normalizeBrainstormActivityForStorage,
1828
2094
  isStale,
1829
2095
  formatSize,
1830
2096
  formatAge,
1831
- cn
2097
+ cn,
2098
+ brainstormThreadId,
2099
+ brainstormActivityMessageFromCustom
1832
2100
  };