@lunora/solid 1.0.0-alpha.22 → 1.0.0-alpha.24

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.
@@ -0,0 +1,55 @@
1
+ import { createMemo } from 'solid-js';
2
+ import { createMutation } from './createMutation-LkrbhItI.mjs';
3
+ import { createSubscription } from './createSubscription-D3HbChGe.mjs';
4
+
5
+ const NO_MUTATION_REF = {
6
+ __lunoraRef: ""
7
+ };
8
+ const resolveMaybe = (value) => typeof value === "function" ? value() : value;
9
+ const createAgent = (options) => {
10
+ const {
11
+ api,
12
+ cancel: cancelReference,
13
+ run: runReference,
14
+ runArgs,
15
+ threadKey
16
+ } = options;
17
+ const runMutation = createMutation(runReference);
18
+ const cancelMutation = createMutation(cancelReference ?? NO_MUTATION_REF);
19
+ const {
20
+ data: threadData
21
+ } = createSubscription(api.agents.agentThread, () => {
22
+ return {
23
+ key: resolveMaybe(threadKey)
24
+ };
25
+ });
26
+ const thread = createMemo(() => threadData());
27
+ const status = createMemo(() => thread()?.status);
28
+ const run = async (input, arguments_) => {
29
+ await runMutation.mutate({
30
+ input,
31
+ threadKey: resolveMaybe(threadKey),
32
+ ...runArgs,
33
+ ...arguments_
34
+ });
35
+ };
36
+ const cancel = async () => {
37
+ const instanceId = thread()?.instanceId;
38
+ if (cancelReference === void 0 || instanceId === void 0) {
39
+ return;
40
+ }
41
+ await cancelMutation.mutate({
42
+ instanceId,
43
+ threadKey: resolveMaybe(threadKey)
44
+ });
45
+ };
46
+ return {
47
+ cancel,
48
+ pending: runMutation.pending,
49
+ run,
50
+ status,
51
+ thread
52
+ };
53
+ };
54
+
55
+ export { NO_MUTATION_REF, createAgent, resolveMaybe };
@@ -0,0 +1,150 @@
1
+ import { createSignal, createMemo } from 'solid-js';
2
+ import { resolveMaybe, NO_MUTATION_REF } from './createAgent-D7EZBeql.mjs';
3
+ import { createMutation } from './createMutation-LkrbhItI.mjs';
4
+ import { createStream } from './createStream-D9ONbGAw.mjs';
5
+ import { createSubscription } from './createSubscription-D3HbChGe.mjs';
6
+
7
+ const NO_STREAM_REF = {
8
+ __lunoraRef: ""
9
+ };
10
+ const reconcileOptimistic = (optimistic, durable) => {
11
+ const pool = durable.filter((message) => message.role === "user").map((message) => message.content);
12
+ return optimistic.filter((pending) => {
13
+ const index = pool.indexOf(pending.content);
14
+ if (index !== -1) {
15
+ pool.splice(index, 1);
16
+ return false;
17
+ }
18
+ return true;
19
+ });
20
+ };
21
+ const createAgentChat = (options) => {
22
+ const {
23
+ api,
24
+ cancel: cancelReference,
25
+ limit,
26
+ send: sendReference,
27
+ sendArgs,
28
+ stream: streamReference,
29
+ threadKey
30
+ } = options;
31
+ const {
32
+ data: history
33
+ } = createSubscription(api.agents.agentMessages, () => {
34
+ const key = resolveMaybe(threadKey);
35
+ return limit === void 0 ? {
36
+ key
37
+ } : {
38
+ key,
39
+ limit
40
+ };
41
+ });
42
+ const {
43
+ data: threadData
44
+ } = createSubscription(api.agents.agentThread, () => {
45
+ return {
46
+ key: resolveMaybe(threadKey)
47
+ };
48
+ });
49
+ const streamArguments = streamReference === void 0 ? "skip" : () => {
50
+ return {
51
+ key: resolveMaybe(threadKey)
52
+ };
53
+ };
54
+ const {
55
+ chunks
56
+ } = createStream(streamReference ?? NO_STREAM_REF, streamArguments);
57
+ const sendMutation = createMutation(sendReference);
58
+ const cancelMutation = createMutation(cancelReference ?? NO_MUTATION_REF);
59
+ const approvalMutation = createMutation(api.agents.agentResolveApproval);
60
+ const [optimistic, setOptimistic] = createSignal([]);
61
+ let nextId = 0;
62
+ const thread = createMemo(() => threadData());
63
+ const status = createMemo(() => thread()?.status);
64
+ const durable = createMemo(() => history() ?? []);
65
+ const messages = createMemo(() => {
66
+ const rows = durable();
67
+ const visible = reconcileOptimistic(optimistic(), rows);
68
+ if (visible.length === 0) {
69
+ return rows;
70
+ }
71
+ return [...rows, ...visible.map((pending, index) => {
72
+ return {
73
+ content: pending.content,
74
+ optimistic: true,
75
+ role: "user",
76
+ seq: rows.length + index
77
+ };
78
+ })];
79
+ });
80
+ const streamingText = createMemo(() => {
81
+ const key = resolveMaybe(threadKey);
82
+ const assistantCount = durable().filter((message) => message.role === "assistant").length;
83
+ return chunks().filter((event) => event.kind !== "progress" && event.threadKey === key && event.turn >= assistantCount).map((delta) => delta.text).join("");
84
+ });
85
+ const send = async (input, arguments_) => {
86
+ const id = nextId;
87
+ nextId += 1;
88
+ setOptimistic((previous) => [...reconcileOptimistic(previous, durable()), {
89
+ content: input,
90
+ id
91
+ }]);
92
+ await sendMutation.mutate({
93
+ input,
94
+ threadKey: resolveMaybe(threadKey),
95
+ ...sendArgs,
96
+ ...arguments_
97
+ });
98
+ };
99
+ const approve = async (toolCallId, note) => {
100
+ const instanceId = thread()?.instanceId;
101
+ if (instanceId === void 0) {
102
+ throw new Error("createAgentChat: cannot approve — no in-flight run (thread has no instanceId)");
103
+ }
104
+ await approvalMutation.mutate({
105
+ decision: "approve",
106
+ instanceId,
107
+ threadKey: resolveMaybe(threadKey),
108
+ toolCallId,
109
+ ...note === void 0 ? {} : {
110
+ note
111
+ }
112
+ });
113
+ };
114
+ const reject = async (toolCallId, note) => {
115
+ const instanceId = thread()?.instanceId;
116
+ if (instanceId === void 0) {
117
+ throw new Error("createAgentChat: cannot reject — no in-flight run (thread has no instanceId)");
118
+ }
119
+ await approvalMutation.mutate({
120
+ decision: "reject",
121
+ instanceId,
122
+ threadKey: resolveMaybe(threadKey),
123
+ toolCallId,
124
+ ...note === void 0 ? {} : {
125
+ note
126
+ }
127
+ });
128
+ };
129
+ const cancel = async () => {
130
+ const instanceId = thread()?.instanceId;
131
+ if (cancelReference === void 0 || instanceId === void 0) {
132
+ return;
133
+ }
134
+ await cancelMutation.mutate({
135
+ instanceId,
136
+ threadKey: resolveMaybe(threadKey)
137
+ });
138
+ };
139
+ return {
140
+ approve,
141
+ cancel,
142
+ messages,
143
+ reject,
144
+ send,
145
+ status,
146
+ streamingText
147
+ };
148
+ };
149
+
150
+ export { createAgentChat };
@@ -0,0 +1,21 @@
1
+ import { createMemo } from 'solid-js';
2
+ import { resolveMaybe } from './createAgent-D7EZBeql.mjs';
3
+ import { createSubscription } from './createSubscription-D3HbChGe.mjs';
4
+
5
+ const createAgentState = (options) => {
6
+ const {
7
+ data,
8
+ error
9
+ } = createSubscription(options.api.agents.agentState, () => {
10
+ return {
11
+ key: resolveMaybe(options.threadKey)
12
+ };
13
+ });
14
+ const state = createMemo(() => data());
15
+ return {
16
+ error,
17
+ state
18
+ };
19
+ };
20
+
21
+ export { createAgentState };
@@ -0,0 +1,99 @@
1
+ import { createMemo } from 'solid-js';
2
+ import { resolveMaybe } from './createAgent-D7EZBeql.mjs';
3
+ import { createStream } from './createStream-D9ONbGAw.mjs';
4
+ import { createSubscription } from './createSubscription-D3HbChGe.mjs';
5
+
6
+ const NO_STREAM_REF = {
7
+ __lunoraRef: ""
8
+ };
9
+ const EMPTY_MESSAGES = [];
10
+ const toDurableEvent = (message) => {
11
+ if (message.role === "assistant" && message.toolCalls) {
12
+ return message.toolCalls.map((call) => {
13
+ return {
14
+ input: call.input,
15
+ seq: message.seq,
16
+ toolCallId: call.id,
17
+ toolName: call.name,
18
+ type: "call"
19
+ };
20
+ });
21
+ }
22
+ if (message.role !== "tool") {
23
+ return void 0;
24
+ }
25
+ if (message.status === "awaiting_approval") {
26
+ return [{
27
+ seq: message.seq,
28
+ type: "awaiting-approval",
29
+ ...message.toolCallId === void 0 ? {} : {
30
+ toolCallId: message.toolCallId
31
+ },
32
+ ...message.toolName === void 0 ? {} : {
33
+ toolName: message.toolName
34
+ }
35
+ }];
36
+ }
37
+ return [{
38
+ output: message.content,
39
+ seq: message.seq,
40
+ type: "result",
41
+ ...message.status === "approved" || message.status === "rejected" ? {
42
+ status: message.status
43
+ } : {},
44
+ ...message.toolCallId === void 0 ? {} : {
45
+ toolCallId: message.toolCallId
46
+ },
47
+ ...message.toolName === void 0 ? {} : {
48
+ toolName: message.toolName
49
+ }
50
+ }];
51
+ };
52
+ const createAgentToolEvents = (options) => {
53
+ const {
54
+ api,
55
+ limit,
56
+ stream: streamReference,
57
+ threadKey
58
+ } = options;
59
+ const messagesArguments = () => {
60
+ const key = resolveMaybe(threadKey);
61
+ return limit === void 0 ? {
62
+ key
63
+ } : {
64
+ key,
65
+ limit
66
+ };
67
+ };
68
+ const {
69
+ data: history
70
+ } = createSubscription(api.agents.agentMessages, messagesArguments);
71
+ const streamArguments = streamReference === void 0 ? "skip" : () => {
72
+ return {
73
+ key: resolveMaybe(threadKey)
74
+ };
75
+ };
76
+ const {
77
+ chunks
78
+ } = createStream(streamReference ?? NO_STREAM_REF, streamArguments);
79
+ const events = createMemo(() => {
80
+ const key = resolveMaybe(threadKey);
81
+ const durable = history() ?? EMPTY_MESSAGES;
82
+ const derived = durable.flatMap((message) => toDurableEvent(message) ?? []);
83
+ for (const event of chunks()) {
84
+ if (event.kind === "progress" && event.threadKey === key) {
85
+ derived.push({
86
+ data: event.data,
87
+ toolCallId: event.toolCallId,
88
+ type: "progress"
89
+ });
90
+ }
91
+ }
92
+ return derived;
93
+ });
94
+ return {
95
+ events
96
+ };
97
+ };
98
+
99
+ export { createAgentToolEvents };
@@ -1,43 +1,7 @@
1
1
  import { createSignal, createEffect, on, onCleanup } from 'solid-js';
2
+ import { s as stableStringify } from './stable-key-CGp4e2Ux.mjs';
2
3
  import { useLunora } from './LunoraContext-C59PzHhN.mjs';
3
4
 
4
- const compareKeys = (a, b) => {
5
- if (a < b) {
6
- return -1;
7
- }
8
- return a > b ? 1 : 0;
9
- };
10
- const stableStringify = (value) => {
11
- if (value === void 0) {
12
- return "null";
13
- }
14
- if (typeof value === "bigint") {
15
- throw new TypeError("stableStringify: cannot use a bigint in a cache key (query/subscription/shape args) — pass it as a string");
16
- }
17
- if (value === null || typeof value !== "object") {
18
- return JSON.stringify(value);
19
- }
20
- if (Array.isArray(value)) {
21
- return `[${value.map((item) => stableStringify(item)).join(",")}]`;
22
- }
23
- const proto = Object.getPrototypeOf(value);
24
- if (proto !== null && proto !== Object.prototype) {
25
- const name = value.constructor?.name ?? "value";
26
- throw new TypeError(`stableStringify: cannot use a ${name} in a cache key (query/subscription/shape args) — only plain objects, arrays, and JSON primitives are supported`);
27
- }
28
- const record = value;
29
- const keys = Object.keys(record).toSorted(compareKeys);
30
- const parts = [];
31
- for (const key of keys) {
32
- const raw = record[key];
33
- if (raw === void 0) {
34
- continue;
35
- }
36
- parts.push(`${JSON.stringify(key)}:${stableStringify(raw)}`);
37
- }
38
- return `{${parts.join(",")}}`;
39
- };
40
-
41
5
  const FLAGS_EVAL_PATH = "__lunora_flags__:eval";
42
6
  const flagKind = (value) => {
43
7
  const kind = typeof value;
@@ -1,5 +1,6 @@
1
1
  import { initialPages, derivePaginationStatus, rebalance, applyLoadMore } from '@lunora/client/pagination';
2
2
  import { createMemo, createSignal, createEffect, on, onCleanup } from 'solid-js';
3
+ import { s as stableStringify } from './stable-key-CGp4e2Ux.mjs';
3
4
  import { useLunora } from './LunoraContext-C59PzHhN.mjs';
4
5
 
5
6
  const buildPageArgs = (page, baseArgs) => {
@@ -12,7 +13,7 @@ const buildPageArgs = (page, baseArgs) => {
12
13
  }
13
14
  };
14
15
  };
15
- const buildPageKey = (functionPath, pageArgs) => `${functionPath}::${JSON.stringify(pageArgs)}`;
16
+ const buildPageKey = (functionPath, pageArgs) => `${functionPath}::${stableStringify(pageArgs)}`;
16
17
  const createPaginatedCore = (function_, args, options) => {
17
18
  const client = useLunora();
18
19
  const {
@@ -32,6 +33,22 @@ const createPaginatedCore = (function_, args, options) => {
32
33
  });
33
34
  setPageResults(updated);
34
35
  };
36
+ const migrateResultsForRebalance = (oldPages, newPages, baseArgs) => {
37
+ const keyOf = (page) => buildPageKey(function_["__lunoraRef"], buildPageArgs(page, baseArgs));
38
+ for (const newPage of newPages) {
39
+ const newKey = keyOf(newPage);
40
+ if (resultsByKey.has(newKey)) {
41
+ continue;
42
+ }
43
+ const donor = oldPages.find((oldPage) => oldPage.lower === newPage.lower);
44
+ if (donor) {
45
+ const carried = resultsByKey.get(keyOf(donor));
46
+ if (carried) {
47
+ resultsByKey.set(newKey, carried);
48
+ }
49
+ }
50
+ }
51
+ };
35
52
  const syncSubscriptions = (currentPages, baseArgs) => {
36
53
  const wantedKeys = /* @__PURE__ */ new Set();
37
54
  for (const page of currentPages) {
@@ -42,6 +59,7 @@ const createPaginatedCore = (function_, args, options) => {
42
59
  unsub();
43
60
  activeSubs.delete(key);
44
61
  pendingPageKeys.delete(key);
62
+ resultsByKey.delete(key);
45
63
  }
46
64
  }
47
65
  for (const page of currentPages) {
@@ -60,8 +78,10 @@ const createPaginatedCore = (function_, args, options) => {
60
78
  }
61
79
  rebuildPageResults(pages(), currentArgs);
62
80
  if (pendingPageKeys.size === 0) {
63
- const next = rebalance(pages(), pageResults());
81
+ const latestPages = pages();
82
+ const next = rebalance(latestPages, pageResults());
64
83
  if (next) {
84
+ migrateResultsForRebalance(latestPages, next, currentArgs);
65
85
  setPages(next);
66
86
  }
67
87
  }
@@ -1,12 +1,19 @@
1
1
  import { createSignal, onMount, onCleanup } from 'solid-js';
2
2
  import { useLunora } from './LunoraContext-C59PzHhN.mjs';
3
3
 
4
- const makeSessionId = () => {
5
- if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
6
- return crypto.randomUUID();
4
+ const randomSessionId = (prefix = "sess") => {
5
+ if (typeof crypto !== "undefined") {
6
+ if (typeof crypto.randomUUID === "function") {
7
+ return crypto.randomUUID();
8
+ }
9
+ if (typeof crypto.getRandomValues === "function") {
10
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
11
+ return `${prefix}-${Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
12
+ }
7
13
  }
8
- return `sess-${Math.random().toString(36).slice(2)}-${String(Date.now())}`;
14
+ return `${prefix}-${Date.now().toString(36)}`;
9
15
  };
16
+
10
17
  const DEFAULT_INTERVAL_MS = 1e4;
11
18
  const createPresence = (roomId, options) => {
12
19
  const client = useLunora();
@@ -16,7 +23,7 @@ const createPresence = (roomId, options) => {
16
23
  listPresent,
17
24
  shardKey
18
25
  } = options;
19
- const sessionId = options.sessionId ?? makeSessionId();
26
+ const sessionId = options.sessionId ?? randomSessionId();
20
27
  const [present, setPresent] = createSignal(void 0);
21
28
  let latestData = options.data;
22
29
  const sendHeartbeat = () => {
@@ -0,0 +1,70 @@
1
+ import { createSignal, createEffect, on, onCleanup } from 'solid-js';
2
+ import { useLunora } from './LunoraContext-C59PzHhN.mjs';
3
+
4
+ const createStream = (function_, args, options = {}) => {
5
+ const client = useLunora();
6
+ const [chunks, setChunks] = createSignal([]);
7
+ const [error, setError] = createSignal(void 0);
8
+ const [status, setStatus] = createSignal("idle");
9
+ const resolveArgs = typeof args === "function" ? args : () => args;
10
+ let cancelCurrent;
11
+ const cancel = () => {
12
+ cancelCurrent?.();
13
+ };
14
+ createEffect(on(resolveArgs, (currentArgs) => {
15
+ setChunks(() => []);
16
+ setError(() => void 0);
17
+ if (currentArgs === "skip") {
18
+ setStatus("idle");
19
+ return;
20
+ }
21
+ setStatus("streaming");
22
+ let active = true;
23
+ const iterable = client.stream(function_, currentArgs, {
24
+ maxBuffer: options.maxBuffer,
25
+ shardKey: options.shardKey
26
+ });
27
+ const cancelIterable = () => {
28
+ iterable.cancel();
29
+ };
30
+ cancelCurrent = cancelIterable;
31
+ (async () => {
32
+ try {
33
+ for await (const chunk of iterable) {
34
+ if (!active) {
35
+ return;
36
+ }
37
+ setChunks((previous) => [...previous, chunk]);
38
+ }
39
+ if (active) {
40
+ setStatus("complete");
41
+ }
42
+ } catch (streamError) {
43
+ if (!active) {
44
+ return;
45
+ }
46
+ setError(() => streamError instanceof Error ? streamError : new Error(String(streamError)));
47
+ setStatus("error");
48
+ }
49
+ })().catch(() => {
50
+ });
51
+ onCleanup(() => {
52
+ active = false;
53
+ cancelIterable();
54
+ if (cancelCurrent === cancelIterable) {
55
+ cancelCurrent = void 0;
56
+ }
57
+ });
58
+ }));
59
+ onCleanup(() => {
60
+ cancel();
61
+ });
62
+ return {
63
+ cancel,
64
+ chunks,
65
+ error,
66
+ status
67
+ };
68
+ };
69
+
70
+ export { createStream };
@@ -1,4 +1,5 @@
1
1
  import { createQuerySubscription } from '@lunora/client/query';
2
+ import { LunoraError } from '@lunora/errors';
2
3
  import { createSignal, createEffect, on, onCleanup } from 'solid-js';
3
4
  import { useLunora } from './LunoraContext-C59PzHhN.mjs';
4
5
 
@@ -19,7 +20,8 @@ const createSubscription = (function_, args, options = {}) => {
19
20
  setError(() => void 0);
20
21
  },
21
22
  onError: (subscriptionError) => {
22
- setError(() => new Error(subscriptionError.message));
23
+ const normalized = subscriptionError.code ? new LunoraError(subscriptionError.code, subscriptionError.message) : new Error(subscriptionError.message);
24
+ setError(() => normalized);
23
25
  setData(() => void 0);
24
26
  },
25
27
  onReset: () => {