@restatedev/agents 0.3.0 → 0.4.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.
Files changed (136) hide show
  1. package/README.md +89 -49
  2. package/dist/calls.d.ts +29 -5
  3. package/dist/calls.d.ts.map +1 -1
  4. package/dist/calls.js +77 -10
  5. package/dist/calls.js.map +1 -1
  6. package/dist/claude/index.d.ts +36 -7
  7. package/dist/claude/index.d.ts.map +1 -1
  8. package/dist/claude/index.js +232 -151
  9. package/dist/claude/index.js.map +1 -1
  10. package/dist/client.d.ts +12 -3
  11. package/dist/client.d.ts.map +1 -1
  12. package/dist/client.js.map +1 -1
  13. package/dist/common.d.ts +151 -70
  14. package/dist/common.d.ts.map +1 -1
  15. package/dist/common.js +246 -204
  16. package/dist/common.js.map +1 -1
  17. package/dist/conversation.d.ts +466 -0
  18. package/dist/conversation.d.ts.map +1 -0
  19. package/dist/conversation.js +1247 -0
  20. package/dist/conversation.js.map +1 -0
  21. package/dist/deepseek/index.d.ts +38 -5
  22. package/dist/deepseek/index.d.ts.map +1 -1
  23. package/dist/deepseek/index.js +322 -106
  24. package/dist/deepseek/index.js.map +1 -1
  25. package/dist/deepseek/persistence.d.ts +9 -3
  26. package/dist/deepseek/persistence.d.ts.map +1 -1
  27. package/dist/deepseek/persistence.js +12 -6
  28. package/dist/deepseek/persistence.js.map +1 -1
  29. package/dist/index.d.ts +2 -2
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +2 -3
  32. package/dist/index.js.map +1 -1
  33. package/dist/langgraph/checkpointer.d.ts +16 -2
  34. package/dist/langgraph/checkpointer.d.ts.map +1 -1
  35. package/dist/langgraph/checkpointer.js +133 -26
  36. package/dist/langgraph/checkpointer.js.map +1 -1
  37. package/dist/langgraph/context.d.ts +10 -0
  38. package/dist/langgraph/context.d.ts.map +1 -0
  39. package/dist/langgraph/context.js +21 -0
  40. package/dist/langgraph/context.js.map +1 -0
  41. package/dist/langgraph/errors.d.ts +16 -0
  42. package/dist/langgraph/errors.d.ts.map +1 -0
  43. package/dist/langgraph/errors.js +30 -0
  44. package/dist/langgraph/errors.js.map +1 -0
  45. package/dist/langgraph/graph.d.ts +25 -0
  46. package/dist/langgraph/graph.d.ts.map +1 -0
  47. package/dist/langgraph/graph.js +346 -0
  48. package/dist/langgraph/graph.js.map +1 -0
  49. package/dist/langgraph/index.d.ts +65 -12
  50. package/dist/langgraph/index.d.ts.map +1 -1
  51. package/dist/langgraph/index.js +227 -171
  52. package/dist/langgraph/index.js.map +1 -1
  53. package/dist/langgraph/nodes.d.ts +70 -0
  54. package/dist/langgraph/nodes.d.ts.map +1 -0
  55. package/dist/langgraph/nodes.js +145 -0
  56. package/dist/langgraph/nodes.js.map +1 -0
  57. package/dist/messages.d.ts +18 -0
  58. package/dist/messages.d.ts.map +1 -0
  59. package/dist/messages.js +182 -0
  60. package/dist/messages.js.map +1 -0
  61. package/dist/object.d.ts +65 -23
  62. package/dist/object.d.ts.map +1 -1
  63. package/dist/object.js +121 -35
  64. package/dist/object.js.map +1 -1
  65. package/dist/output.d.ts +15 -7
  66. package/dist/output.d.ts.map +1 -1
  67. package/dist/output.js +44 -26
  68. package/dist/output.js.map +1 -1
  69. package/dist/pi/index.d.ts +39 -11
  70. package/dist/pi/index.d.ts.map +1 -1
  71. package/dist/pi/index.js +281 -77
  72. package/dist/pi/index.js.map +1 -1
  73. package/dist/pi/storage.d.ts +29 -4
  74. package/dist/pi/storage.d.ts.map +1 -1
  75. package/dist/pi/storage.js +18 -6
  76. package/dist/pi/storage.js.map +1 -1
  77. package/dist/signals.d.ts +74 -4
  78. package/dist/signals.d.ts.map +1 -1
  79. package/dist/signals.js +144 -15
  80. package/dist/signals.js.map +1 -1
  81. package/dist/steering.d.ts +31 -0
  82. package/dist/steering.d.ts.map +1 -0
  83. package/dist/steering.js +45 -0
  84. package/dist/steering.js.map +1 -0
  85. package/dist/tools.d.ts +28 -0
  86. package/dist/tools.d.ts.map +1 -1
  87. package/dist/tools.js +34 -5
  88. package/dist/tools.js.map +1 -1
  89. package/package.json +33 -37
  90. package/src/calls.ts +107 -15
  91. package/src/claude/README.md +41 -20
  92. package/src/claude/index.ts +266 -178
  93. package/src/client.ts +14 -3
  94. package/src/common.ts +317 -232
  95. package/src/conversation.ts +1527 -0
  96. package/src/deepseek/README.md +78 -11
  97. package/src/deepseek/index.ts +384 -137
  98. package/src/deepseek/persistence.ts +11 -8
  99. package/src/index.ts +13 -4
  100. package/src/langgraph/README.md +115 -25
  101. package/src/langgraph/checkpointer.ts +168 -28
  102. package/src/langgraph/context.ts +27 -0
  103. package/src/langgraph/errors.ts +26 -0
  104. package/src/langgraph/graph.ts +396 -0
  105. package/src/langgraph/index.ts +326 -181
  106. package/src/langgraph/nodes.ts +243 -0
  107. package/src/messages.ts +244 -0
  108. package/src/object.ts +167 -38
  109. package/src/output.ts +52 -31
  110. package/src/pi/README.md +18 -3
  111. package/src/pi/index.ts +346 -78
  112. package/src/pi/storage.ts +20 -7
  113. package/src/signals.ts +225 -19
  114. package/src/steering.ts +67 -0
  115. package/src/tools.ts +61 -8
  116. package/dist/claude/conversation.d.ts +0 -33
  117. package/dist/claude/conversation.d.ts.map +0 -1
  118. package/dist/claude/conversation.js +0 -95
  119. package/dist/claude/conversation.js.map +0 -1
  120. package/dist/log.d.ts +0 -29
  121. package/dist/log.d.ts.map +0 -1
  122. package/dist/log.js +0 -146
  123. package/dist/log.js.map +0 -1
  124. package/dist/opencode/db.d.ts +0 -40
  125. package/dist/opencode/db.d.ts.map +0 -1
  126. package/dist/opencode/db.js +0 -161
  127. package/dist/opencode/db.js.map +0 -1
  128. package/dist/opencode/index.d.ts +0 -100
  129. package/dist/opencode/index.d.ts.map +0 -1
  130. package/dist/opencode/index.js +0 -436
  131. package/dist/opencode/index.js.map +0 -1
  132. package/src/claude/conversation.ts +0 -114
  133. package/src/log.ts +0 -194
  134. package/src/opencode/README.md +0 -125
  135. package/src/opencode/db.ts +0 -223
  136. package/src/opencode/index.ts +0 -559
@@ -0,0 +1,243 @@
1
+ // Prebuilt LangGraph nodes that are Restate steps: wait for a signal, run a
2
+ // workflow, call or send to a handler, ask another agent. The Python SDK's
3
+ // restate/agents/langgraph/nodes.py.
4
+ //
5
+ // Add them to a graph of your own, as Restate's tools are added to an agent.
6
+ // Each reads its input from the graph's state, and writes what it gets back
7
+ // to the state field `output`:
8
+ //
9
+ // const graph = new StateGraph(State)
10
+ // .addNode('approve', nodes.waitForSignal('approval', { input: (s) => s.refund, output: 'approved' }))
11
+ // .addNode('ship', nodes.workflow(shipping, { input: (s) => s.order, output: 'receipt' }));
12
+ // const desk = langgraph.agent({ name: 'desk', graph });
13
+ //
14
+ // Or run the graph in a handler of your own, with its context as LangGraph's
15
+ // run context, its checkpoints in its database, and `durability: 'sync'`:
16
+ //
17
+ // const app = graph.compile({ checkpointer: new SqlCheckpointSaver(ctx.db) });
18
+ // await app.invoke(input, { configurable: { thread_id: 'refunds' }, context: ctx, durability: 'sync' });
19
+ //
20
+ // Each node does its step once. A crash runs a node again from the
21
+ // checkpoint it started from, which `durability: 'sync'` stored before the
22
+ // node ran, and LangGraph gives it the same task id there, so the node joins
23
+ // the workflow, the call, the agent's answer or the wait it started before
24
+ // rather than start another. A wait is listed by the agent's `pending` view,
25
+ // and its `signal` view resolves it.
26
+ import type * as restate from '@restatedev/sessions';
27
+ import type { LangGraphRunnableConfig } from '@langchain/langgraph';
28
+ import { signals, signalsOf } from '../signals.ts';
29
+ import { handlerContext } from './context.ts';
30
+
31
+ /** A LangGraph node: it takes the state and the run's config, and returns the state's update. */
32
+ // oxlint-disable-next-line typescript/no-explicit-any -- any graph's state
33
+ export type Node = (state: any, config: LangGraphRunnableConfig) => Promise<Record<string, unknown>>;
34
+
35
+ /** A service, virtual object or workflow, as its definition, of handlers `M`. */
36
+ type Target<M = unknown> =
37
+ | restate.ServiceDefinition<string, M>
38
+ | restate.VirtualObjectDefinition<string, M>
39
+ | restate.WorkflowDefinition<string, M>;
40
+
41
+ /** Whether a target is keyed: a virtual object (key) or a workflow (id). */
42
+ const keyed = (target: Target) => 'object' in target || 'workflow' in target;
43
+
44
+ /** A node's run: the agent's context, the node's name, and the key that is the same each time it runs again. */
45
+ interface Step {
46
+ ctx: restate.SessionContext;
47
+ node: string;
48
+ idempotencyKey: string;
49
+ }
50
+
51
+ /** LangGraph's keys, in a node's config, of its run's checkpointer, durability, and task id. */
52
+ const CHECKPOINTER = '__pregel_checkpointer';
53
+ const DURABILITY = '__pregel_durability';
54
+ const TASK_ID = '__pregel_task_id';
55
+
56
+ /** The run of a node of `kind`, from LangGraph's config. */
57
+ function stepOf(config: LangGraphRunnableConfig, kind: string): Step {
58
+ const ctx = handlerContext(config.context);
59
+ if (!ctx) {
60
+ throw new TypeError(
61
+ `nodes.${kind} runs in a graph that langgraph.agent({ graph }) runs, or that is invoked with the handler's ` +
62
+ 'context: invoke(input, { context: ctx })',
63
+ );
64
+ }
65
+ const configurable = (config.configurable ?? {}) as Record<string, unknown>;
66
+ if (!configurable[CHECKPOINTER]) {
67
+ throw new TypeError(
68
+ `nodes.${kind} runs in a graph with a checkpointer, so that a retried attempt resumes it: ` +
69
+ 'compile({ checkpointer: new SqlCheckpointSaver(ctx.db) })',
70
+ );
71
+ }
72
+ // Only 'sync' stores a step's checkpoint before its tasks run. Otherwise a crash before the save makes the resumed
73
+ // run create the checkpoint again, with a new id, and so new task ids: the step would be made twice.
74
+ const durability = (config as { durability?: unknown }).durability ?? configurable[DURABILITY];
75
+ if (durability !== 'sync') {
76
+ throw new TypeError(
77
+ `nodes.${kind} runs in a graph that stores each step's checkpoint before the step runs, so that a retried ` +
78
+ "attempt gets the same task ids: invoke(input, { durability: 'sync' })",
79
+ );
80
+ }
81
+ // The task's namespace holds its id, which LangGraph derives from the checkpoint the step started from: a node
82
+ // run again from that checkpoint gets the same one. It holds the subgraph's path too.
83
+ const namespace = String(configurable.checkpoint_ns || configurable[TASK_ID]);
84
+ const node = namespace.split('|').at(-1)!.split(':')[0]!;
85
+ return { ctx, node, idempotencyKey: `langgraph:${ctx.key}:${namespace}` };
86
+ }
87
+
88
+ /** The state's update that writes `value` to `output`, if given. */
89
+ const update = (output: string | undefined, value: unknown) => (output === undefined ? {} : { [output]: value });
90
+
91
+ /** As JSON, which Restate and the companion store: the state may hold class instances. */
92
+ const plain = (value: unknown): unknown => (value === undefined ? undefined : JSON.parse(JSON.stringify(value)));
93
+
94
+ /**
95
+ * A node that waits for the signal `name` to the agent, and writes its value
96
+ * to `output`: a person's approval, say, or another system's result. The
97
+ * graph waits without holding a process, for as long as it takes. The
98
+ * agent's `pending` view lists the wait, with `input`'s value, and its
99
+ * `signal` view resolves it:
100
+ *
101
+ * graph.addNode('approve', nodes.waitForSignal('approval', { input: (s) => s.refund, output: 'approved' }))
102
+ */
103
+ export const waitForSignal =
104
+ // oxlint-disable-next-line typescript/no-explicit-any -- any graph's state
105
+ (name: string, { output, input }: { output?: string; input?: (state: any) => unknown } = {}): Node =>
106
+ async (state, config) => {
107
+ const step = stepOf(config, 'waitForSignal');
108
+ // The wait's id starts with the invocation's (the same in each attempt), as the waits of tools do, so that a
109
+ // turn that ends without it (killed, say) has it closed: the companion closes the waits whose ids start with
110
+ // the turn's.
111
+ const id = `${step.ctx.request.id}:${step.idempotencyKey}`;
112
+ const shown = input === undefined ? {} : { input: plain(input(state)) };
113
+ const value = await step.ctx
114
+ .rpc(signals, signalsOf(step.ctx), { idempotencyKey: id })
115
+ .wait({ id, name, ...shown });
116
+ return update(output, value);
117
+ };
118
+
119
+ /** What a node that calls a handler takes. */
120
+ interface CallOptions {
121
+ /** The state field that gets the result; none to write nothing. */
122
+ output?: string;
123
+ /** The handler's input, from the state; none for a handler that takes none. */
124
+ // oxlint-disable-next-line typescript/no-explicit-any -- any graph's state
125
+ input?: (state: any) => unknown;
126
+ /** The key to call, from the state: for a virtual object's or a workflow's handler, and only for those. */
127
+ // oxlint-disable-next-line typescript/no-explicit-any -- any graph's state
128
+ key?: (state: any) => string;
129
+ }
130
+
131
+ /** Throw a `TypeError` if `key` is given for a target that is not keyed, or the other way around. */
132
+ function checkKey(target: Target, key: unknown) {
133
+ if (keyed(target) !== (key !== undefined)) {
134
+ throw new TypeError(
135
+ `${target.name} ${keyed(target) ? 'is' : 'is not'} keyed: ${keyed(target) ? 'pass' : 'drop'} key`,
136
+ );
137
+ }
138
+ }
139
+
140
+ /**
141
+ * A node that calls `handler` of `target` (a service, virtual object or
142
+ * workflow), and writes its result to `output`:
143
+ *
144
+ * graph.addNode('status', nodes.call(orders, 'status', { input: (s) => s.order, key: (s) => s.customer, output: 'status' }))
145
+ */
146
+ export const call = <M>(target: Target<M>, handler: keyof M & string, options: CallOptions = {}): Node => {
147
+ checkKey(target, options.key);
148
+ return async (state, config) => {
149
+ const { ctx, idempotencyKey } = stepOf(config, 'call');
150
+ const result = await ctx.rpc({
151
+ service: target.name,
152
+ handler,
153
+ key: options.key?.(state),
154
+ input: plain(options.input?.(state)),
155
+ idempotencyKey,
156
+ });
157
+ return update(options.output, result);
158
+ };
159
+ };
160
+
161
+ /**
162
+ * A node that sends to `handler` of `target`, without waiting for it to run,
163
+ * after `delay` if given (such as `{ days: 1 }`). It writes nothing:
164
+ *
165
+ * graph.addNode('remind', nodes.send(checkins, 'remind', { input: (s) => s.checkin, delay: { days: 1 } }))
166
+ */
167
+ export const send = <M>(
168
+ target: Target<M>,
169
+ handler: keyof M & string,
170
+ options: Omit<CallOptions, 'output'> & { delay?: restate.Duration } = {},
171
+ ): Node => {
172
+ checkKey(target, options.key);
173
+ return async (state, config) => {
174
+ const { ctx, idempotencyKey } = stepOf(config, 'send');
175
+ ctx.send({
176
+ service: target.name,
177
+ handler,
178
+ key: options.key?.(state),
179
+ input: plain(options.input?.(state)),
180
+ delay: options.delay,
181
+ idempotencyKey,
182
+ });
183
+ return {};
184
+ };
185
+ };
186
+
187
+ /**
188
+ * A node that runs the workflow `target` (its `run` handler) to the end, and
189
+ * writes its result to `output`. The workflow's id is `key`'s, or one of the
190
+ * node's own, made of the agent's key and the node's task:
191
+ *
192
+ * graph.addNode('ship', nodes.workflow(shipping, { input: (s) => s.order, output: 'receipt' }))
193
+ */
194
+ export const workflow =
195
+ (target: restate.WorkflowDefinition<string, { run: unknown }>, { output, input, key }: CallOptions = {}): Node =>
196
+ async (state, config) => {
197
+ const { ctx, idempotencyKey } = stepOf(config, 'workflow');
198
+ const result = await ctx.rpc({
199
+ service: target.name,
200
+ handler: 'run',
201
+ key: key?.(state) ?? idempotencyKey,
202
+ input: plain(input?.(state)),
203
+ idempotencyKey,
204
+ });
205
+ return update(output, result);
206
+ };
207
+
208
+ /**
209
+ * A node that sends a message to another agent (or any virtual object with
210
+ * a handler that takes text), and writes its answer to `output`. The message
211
+ * goes to the agent's key `<this key>.<node name>` unless `key` gives one, so
212
+ * each run of the graph continues the same conversation with it:
213
+ *
214
+ * graph.addNode('research', nodes.subagent(researcher, { message: (s) => s.question, output: 'findings' }))
215
+ */
216
+ export const subagent =
217
+ <M>(
218
+ agent: restate.VirtualObjectDefinition<string, M>,
219
+ {
220
+ message,
221
+ output,
222
+ key,
223
+ handler = 'chat',
224
+ }: {
225
+ // oxlint-disable-next-line typescript/no-explicit-any -- any graph's state
226
+ message: (state: any) => string;
227
+ output?: string;
228
+ // oxlint-disable-next-line typescript/no-explicit-any -- any graph's state
229
+ key?: (state: any) => string;
230
+ handler?: string;
231
+ },
232
+ ): Node =>
233
+ async (state, config) => {
234
+ const { ctx, node, idempotencyKey } = stepOf(config, 'subagent');
235
+ const answer = await ctx.rpc({
236
+ service: agent.name,
237
+ handler,
238
+ key: key?.(state) ?? `${ctx.key}.${node}`,
239
+ input: message(state),
240
+ idempotencyKey,
241
+ });
242
+ return update(output, answer);
243
+ };
@@ -0,0 +1,244 @@
1
+ // The conversation as clients read it: the `messages` view's pages, rendered
2
+ // from the conversation's rows (conversation.ts), as the Python SDK's
3
+ // `_messages.py`.
4
+ //
5
+ // A message is what a person sees: the user's text, or the assistant's text
6
+ // and tool calls, each call with its output once it has one. It is made of
7
+ // rows of the conversation: the row that starts it (whose position is the
8
+ // message's id), and the rows that add to it (a tool call's result comes
9
+ // later, in a row of its own). A message changes when a row is added to it,
10
+ // so its `seq` is the latest of its rows', and a client that follows the
11
+ // conversation from a cursor gets each message again whenever it changes.
12
+ //
13
+ // A turn's prompt always starts a message, and the rows of its trajectory
14
+ // only add to messages of their own turn. So the messages from any turn on
15
+ // are rendered from the rows of both tables from that turn's position on, in
16
+ // order, and a page reads only the rows it needs.
17
+ //
18
+ // The summary view is each turn's message of the user and its answer, from
19
+ // the turns' rows, and the messages steered to the turn that it took, under
20
+ // the ids they have in the full view.
21
+ import type { DatabaseReader, ViewContext } from '@restatedev/sessions';
22
+ import { type ChatMessage, ITEMS, type Messages, type MessagesRequest, type Part } from './common.ts';
23
+ import { failed, type Items, lastOf, loadItem, SCHEMA, startOf, STEERED, STEPS, TURNS } from './conversation.ts';
24
+
25
+ /** A message as rendered, with when it last changed. */
26
+ interface Rendered {
27
+ id: number;
28
+ role: ChatMessage['role'];
29
+ parts: Part[];
30
+ /** The latest `seq` of its rows. */
31
+ seq: number;
32
+ }
33
+
34
+ /** The conversation's `rows` (`n`, `seq`, `item`, in order) as messages, without the empty ones. */
35
+ function render<I>(items: Items<I>, rows: unknown[][]): Rendered[] {
36
+ const messages: Rendered[] = [];
37
+ /** Each tool call's message, by the call's id. */
38
+ const at = new Map<string, Rendered>();
39
+ for (const [n, seq, stored] of rows) {
40
+ const position = Number(n);
41
+ const changed = Number(seq);
42
+ const { said, calls = [], results = [] } = items.read(loadItem(items, String(stored)));
43
+ if (said) {
44
+ const [role, text] = said;
45
+ messages.push({ id: position, role: role === 'user' ? 'user' : 'assistant', parts: [], seq: changed });
46
+ if (text.trim()) messages.at(-1)!.parts.push({ type: 'text', text });
47
+ }
48
+ for (const call of calls) {
49
+ if (messages.at(-1)?.role !== 'assistant') {
50
+ messages.push({ id: position, role: 'assistant', parts: [], seq: changed });
51
+ }
52
+ const message = messages.at(-1)!;
53
+ message.parts.push({ type: 'tool', id: call.id, name: call.name, input: call.input });
54
+ message.seq = changed;
55
+ at.set(call.id, message);
56
+ }
57
+ for (const result of results) {
58
+ const answered = at.get(result.id);
59
+ if (!answered) continue;
60
+ const error = failed(result);
61
+ answered.parts = answered.parts.map((part) =>
62
+ part.type === 'tool' && part.id === result.id
63
+ ? { ...part, output: result.output, ...(error ? { error: true as const } : {}) }
64
+ : part,
65
+ );
66
+ answered.seq = changed;
67
+ }
68
+ }
69
+ return messages.filter((message) => message.parts.length > 0);
70
+ }
71
+
72
+ const chat = ({ id, role, parts }: Rendered): ChatMessage => ({ id, role, parts });
73
+
74
+ /** The latest `limit` of `messages`: none for a limit of 0 (`slice(-0)` would be all of them). */
75
+ const latestOf = (messages: Rendered[], limit: number) => (limit > 0 ? messages.slice(-limit) : []);
76
+
77
+ /**
78
+ * A page of the conversation in `db`, whose items are `items`'. With a
79
+ * `cursor`: the messages that changed since it, in the order they changed,
80
+ * and the cursor to read on from. Without: the latest `limit` messages (or
81
+ * the latest before id `before`), oldest first, and the cursor to follow the
82
+ * conversation from. `view: 'summary'` gives each turn's message and answer.
83
+ */
84
+ export async function page<I>(db: DatabaseReader, items: Items<I>, request: MessagesRequest = {}): Promise<Messages> {
85
+ const { limit = 50, before, cursor, view } = request;
86
+ await SCHEMA.ensure(db);
87
+ const start = await startOf(db);
88
+ const summary = view === 'summary';
89
+ const result =
90
+ cursor === undefined
91
+ ? await (summary ? summaryLatest : latest)(db, items, before, limit)
92
+ : await (summary ? summarySince : since)(db, items, cursor, limit);
93
+ return start.n ? { ...result, first: start.n } : result;
94
+ }
95
+
96
+ /**
97
+ * The rows (`n`, `seq`, `item`) of the transcript and the trajectories from
98
+ * position `first` on, before position `until` if given, in order.
99
+ */
100
+ async function rowsFrom(db: DatabaseReader, first: number, until = Number.MAX_SAFE_INTEGER) {
101
+ const range = 'WHERE n >= ? AND n < ? ORDER BY n';
102
+ const turns = await db.values(`SELECT n, seq, item FROM ${TURNS} ${range}`, [first, until]);
103
+ const steps = await db.values(`SELECT n, seq, item FROM ${STEPS} ${range}`, [first, until]);
104
+ return [...turns, ...steps].toSorted((a, b) => Number(a[0]) - Number(b[0]));
105
+ }
106
+
107
+ /** Whether the conversation has a turn before a position: a page that starts there has more before it. */
108
+ const EARLIER = `SELECT EXISTS (SELECT 1 FROM ${TURNS} WHERE n < ?)`;
109
+
110
+ /** The first value of the first row of `sql`. */
111
+ const one = async (db: DatabaseReader, sql: string, params: unknown[]) =>
112
+ (await db.values(sql, params as never))[0]?.[0];
113
+
114
+ /** The cursor of the conversation as it is now. */
115
+ async function now(db: DatabaseReader) {
116
+ const start = await startOf(db);
117
+ const [, seq] = await lastOf(db);
118
+ return Math.max(start.seq, seq);
119
+ }
120
+
121
+ /** The messages that changed since `cursor`, rendered from the turn of the earliest change on. */
122
+ async function since<I>(db: DatabaseReader, items: Items<I>, cursor: number, limit: number): Promise<Messages> {
123
+ const prompt = await one(db, `SELECT MIN(n) FROM ${TURNS} WHERE seq > ?`, [cursor]);
124
+ const step = await one(db, `SELECT MIN(turn) FROM ${STEPS} WHERE seq > ?`, [cursor]);
125
+ const changed = [prompt, step].filter((n) => n !== null && n !== undefined).map(Number);
126
+ if (changed.length === 0) return { messages: [], more: false, cursor };
127
+ const messages = render(items, await rowsFrom(db, Math.min(...changed)))
128
+ .filter((m) => m.seq > cursor)
129
+ .toSorted((a, b) => a.seq - b.seq);
130
+ const shown = messages.slice(0, limit);
131
+ return { messages: shown.map(chat), more: messages.length > limit, cursor: shown.at(-1)?.seq ?? cursor };
132
+ }
133
+
134
+ /**
135
+ * The latest `limit` messages before id `before`, rendered from enough turns
136
+ * back to hold them: each turn starts with a message, so the rows from the
137
+ * `limit + 1`-th latest turn before `before` on hold more than `limit`. And
138
+ * to no later than the turn `before` is in: a turn's rows add only to its
139
+ * own messages, so the turns from `before` on change none before it.
140
+ */
141
+ async function latest<I>(
142
+ db: DatabaseReader,
143
+ items: Items<I>,
144
+ before: number | undefined,
145
+ limit: number,
146
+ ): Promise<Messages> {
147
+ const end = before ?? Number.MAX_SAFE_INTEGER;
148
+ const first = await one(
149
+ db,
150
+ `SELECT COALESCE((SELECT n FROM ${TURNS} WHERE n < ? ORDER BY n DESC LIMIT 1 OFFSET ?), (SELECT MIN(n) FROM ${TURNS}))`,
151
+ [end, limit],
152
+ );
153
+ const cursor = await now(db);
154
+ if (first === null || first === undefined) return { messages: [], more: false, cursor };
155
+ const until = before === undefined ? undefined : await one(db, `SELECT MIN(n) FROM ${TURNS} WHERE n >= ?`, [end]);
156
+ const rows = await rowsFrom(db, Number(first), until === null || until === undefined ? undefined : Number(until));
157
+ const messages = render(items, rows).filter((m) => m.id < end);
158
+ const earlier = await one(db, EARLIER, [first]);
159
+ return {
160
+ messages: latestOf(messages, limit).map(chat),
161
+ more: messages.length > limit || Boolean(Number(earlier)),
162
+ cursor,
163
+ };
164
+ }
165
+
166
+ /** The columns of a turn the summary view reads. */
167
+ const TURN = `SELECT n, seq, item, answer, answered_at, answered_seq FROM ${TURNS}`;
168
+
169
+ /** The messages steered to turns that took them (`n`, `seq`, `item`): messages of the user, which the summary shows too. */
170
+ const STEERS = `SELECT st.n, s.seq, s.item FROM ${STEERED} st JOIN ${STEPS} s ON s.n = st.n`;
171
+
172
+ /**
173
+ * Turns' rows ({@link TURN}'s columns) as their user's messages and answers,
174
+ * with the messages steered to them (`steered`, {@link STEERS}'s columns),
175
+ * in order: the answer's message has the id it has in the full view (the
176
+ * turn's last message of the assistant), and the `seq` it was stored with;
177
+ * so does a steered message.
178
+ */
179
+ function summarized<I>(items: Items<I>, rows: unknown[][], steered: unknown[][] = []): Rendered[] {
180
+ const messages: Rendered[] = [];
181
+ const user = (n: unknown, seq: unknown, stored: unknown): Rendered => {
182
+ const text = items.read(loadItem(items, String(stored))).said?.[1] ?? '';
183
+ return { id: Number(n), role: 'user', parts: text.trim() ? [{ type: 'text', text }] : [], seq: Number(seq) };
184
+ };
185
+ for (const [n, seq, stored, answer, answeredAt, answeredSeq] of rows) {
186
+ messages.push(user(n, seq, stored));
187
+ if (answer !== null && answer !== undefined && answeredAt !== null && answeredAt !== undefined) {
188
+ const answered = typeof answer === 'string' ? answer : JSON.stringify(answer);
189
+ messages.push({
190
+ id: Number(answeredAt),
191
+ role: 'assistant',
192
+ parts: answered.trim() ? [{ type: 'text', text: answered }] : [],
193
+ seq: Number(answeredSeq),
194
+ });
195
+ }
196
+ }
197
+ for (const [n, seq, stored] of steered) messages.push(user(n, seq, stored));
198
+ return messages.filter((message) => message.parts.length > 0).toSorted((a, b) => a.id - b.id);
199
+ }
200
+
201
+ /** The user's messages and answers stored since `cursor`, in the order they were. */
202
+ async function summarySince<I>(db: DatabaseReader, items: Items<I>, cursor: number, limit: number): Promise<Messages> {
203
+ const asked = await db.values(`${TURN} WHERE seq > ?`, [cursor]);
204
+ const answered = await db.values(`${TURN} WHERE answered_seq > ?`, [cursor]);
205
+ const steered = await db.values(`${STEERS} WHERE s.seq > ?`, [cursor]);
206
+ const rows = new Map([...asked, ...answered].map((row) => [Number(row[0]), row]));
207
+ const messages = summarized(items, [...rows.values()], steered)
208
+ .filter((m) => m.seq > cursor)
209
+ .toSorted((a, b) => a.seq - b.seq);
210
+ const shown = messages.slice(0, limit);
211
+ return { messages: shown.map(chat), more: messages.length > limit, cursor: shown.at(-1)?.seq ?? cursor };
212
+ }
213
+
214
+ /** The latest `limit` user's messages and answers before id `before`: from as many turns, at most. */
215
+ async function summaryLatest<I>(
216
+ db: DatabaseReader,
217
+ items: Items<I>,
218
+ before: number | undefined,
219
+ limit: number,
220
+ ): Promise<Messages> {
221
+ const end = before ?? Number.MAX_SAFE_INTEGER;
222
+ const rows = await db.values(`${TURN} WHERE n < ? ORDER BY n DESC LIMIT ?`, [end, limit]);
223
+ const cursor = await now(db);
224
+ const first = rows.length > 0 ? Number(rows.at(-1)![0]) : end;
225
+ const steered = await db.values(`${STEERS} WHERE st.n >= ? AND st.n < ? ORDER BY st.n`, [first, end]);
226
+ const messages = summarized(items, rows.toReversed(), steered).filter((m) => m.id < end);
227
+ const earlier = await one(db, EARLIER, [first]);
228
+ return {
229
+ messages: latestOf(messages, limit).map(chat),
230
+ more: messages.length > limit || Boolean(Number(earlier)),
231
+ cursor,
232
+ };
233
+ }
234
+
235
+ /**
236
+ * The `messages` view of an agent whose framework keeps the conversation of
237
+ * turns, with its `items`: `sessionObject` finds them on it, and gives the
238
+ * agent `settle` and `compact`, and `clear` that keeps the ids going.
239
+ */
240
+ export const conversationView = <I>(items: Items<I>) =>
241
+ ITEMS.on(
242
+ async (ctx: ViewContext, request?: MessagesRequest): Promise<Messages> => page(ctx.db, items, request ?? {}),
243
+ items,
244
+ );