@restatedev/agents 0.11.1 → 0.12.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 (218) hide show
  1. package/README.md +189 -808
  2. package/dist/pi/factory.d.ts +73 -0
  3. package/dist/pi/factory.d.ts.map +1 -0
  4. package/dist/pi/factory.js +145 -0
  5. package/dist/pi/factory.js.map +1 -0
  6. package/dist/pi/index.d.ts +5 -129
  7. package/dist/pi/index.d.ts.map +1 -1
  8. package/dist/pi/index.js +31 -571
  9. package/dist/pi/index.js.map +1 -1
  10. package/dist/pi/keepalive.d.ts +3 -16
  11. package/dist/pi/keepalive.d.ts.map +1 -1
  12. package/dist/pi/keepalive.js +38 -41
  13. package/dist/pi/keepalive.js.map +1 -1
  14. package/dist/pi/left.d.ts +16 -0
  15. package/dist/pi/left.d.ts.map +1 -0
  16. package/dist/pi/left.js +23 -0
  17. package/dist/pi/left.js.map +1 -0
  18. package/dist/pi/storage.d.ts +19 -76
  19. package/dist/pi/storage.d.ts.map +1 -1
  20. package/dist/pi/storage.js +50 -368
  21. package/dist/pi/storage.js.map +1 -1
  22. package/dist/pi/tools.d.ts +12 -0
  23. package/dist/pi/tools.d.ts.map +1 -0
  24. package/dist/pi/tools.js +70 -0
  25. package/dist/pi/tools.js.map +1 -0
  26. package/package.json +11 -254
  27. package/src/pi/factory.ts +231 -0
  28. package/src/pi/index.ts +31 -759
  29. package/src/pi/keepalive.ts +46 -56
  30. package/src/pi/left.ts +52 -0
  31. package/src/pi/storage.ts +75 -409
  32. package/src/pi/tools.ts +78 -0
  33. package/dist/agentlib/agent.d.ts +0 -32
  34. package/dist/agentlib/agent.d.ts.map +0 -1
  35. package/dist/agentlib/agent.js +0 -174
  36. package/dist/agentlib/agent.js.map +0 -1
  37. package/dist/agentlib/index.d.ts +0 -5
  38. package/dist/agentlib/index.d.ts.map +0 -1
  39. package/dist/agentlib/index.js +0 -15
  40. package/dist/agentlib/index.js.map +0 -1
  41. package/dist/agentlib/messages.d.ts +0 -39
  42. package/dist/agentlib/messages.d.ts.map +0 -1
  43. package/dist/agentlib/messages.js +0 -177
  44. package/dist/agentlib/messages.js.map +0 -1
  45. package/dist/agentlib/model.d.ts +0 -31
  46. package/dist/agentlib/model.d.ts.map +0 -1
  47. package/dist/agentlib/model.js +0 -140
  48. package/dist/agentlib/model.js.map +0 -1
  49. package/dist/agentlib/options.d.ts +0 -58
  50. package/dist/agentlib/options.d.ts.map +0 -1
  51. package/dist/agentlib/options.js +0 -2
  52. package/dist/agentlib/options.js.map +0 -1
  53. package/dist/agentlib/runtime.d.ts +0 -37
  54. package/dist/agentlib/runtime.d.ts.map +0 -1
  55. package/dist/agentlib/runtime.js +0 -216
  56. package/dist/agentlib/runtime.js.map +0 -1
  57. package/dist/agentlib/state.d.ts +0 -114
  58. package/dist/agentlib/state.d.ts.map +0 -1
  59. package/dist/agentlib/state.js +0 -52
  60. package/dist/agentlib/state.js.map +0 -1
  61. package/dist/agentlib/steering.d.ts +0 -23
  62. package/dist/agentlib/steering.d.ts.map +0 -1
  63. package/dist/agentlib/steering.js +0 -48
  64. package/dist/agentlib/steering.js.map +0 -1
  65. package/dist/agentlib/tools.d.ts +0 -33
  66. package/dist/agentlib/tools.d.ts.map +0 -1
  67. package/dist/agentlib/tools.js +0 -245
  68. package/dist/agentlib/tools.js.map +0 -1
  69. package/dist/agentlib/turn.d.ts +0 -82
  70. package/dist/agentlib/turn.d.ts.map +0 -1
  71. package/dist/agentlib/turn.js +0 -253
  72. package/dist/agentlib/turn.js.map +0 -1
  73. package/dist/calls.d.ts +0 -90
  74. package/dist/calls.d.ts.map +0 -1
  75. package/dist/calls.js +0 -235
  76. package/dist/calls.js.map +0 -1
  77. package/dist/claude/index.d.ts +0 -106
  78. package/dist/claude/index.d.ts.map +0 -1
  79. package/dist/claude/index.js +0 -386
  80. package/dist/claude/index.js.map +0 -1
  81. package/dist/client.d.ts +0 -90
  82. package/dist/client.d.ts.map +0 -1
  83. package/dist/client.js +0 -88
  84. package/dist/client.js.map +0 -1
  85. package/dist/common.d.ts +0 -410
  86. package/dist/common.d.ts.map +0 -1
  87. package/dist/common.js +0 -563
  88. package/dist/common.js.map +0 -1
  89. package/dist/companion.d.ts +0 -286
  90. package/dist/companion.d.ts.map +0 -1
  91. package/dist/companion.js +0 -463
  92. package/dist/companion.js.map +0 -1
  93. package/dist/conversation.d.ts +0 -576
  94. package/dist/conversation.d.ts.map +0 -1
  95. package/dist/conversation.js +0 -1476
  96. package/dist/conversation.js.map +0 -1
  97. package/dist/deepseek/barriers.d.ts +0 -11
  98. package/dist/deepseek/barriers.d.ts.map +0 -1
  99. package/dist/deepseek/barriers.js +0 -36
  100. package/dist/deepseek/barriers.js.map +0 -1
  101. package/dist/deepseek/index.d.ts +0 -97
  102. package/dist/deepseek/index.d.ts.map +0 -1
  103. package/dist/deepseek/index.js +0 -603
  104. package/dist/deepseek/index.js.map +0 -1
  105. package/dist/deepseek/persistence.d.ts +0 -83
  106. package/dist/deepseek/persistence.d.ts.map +0 -1
  107. package/dist/deepseek/persistence.js +0 -262
  108. package/dist/deepseek/persistence.js.map +0 -1
  109. package/dist/index.d.ts +0 -14
  110. package/dist/index.d.ts.map +0 -1
  111. package/dist/index.js +0 -17
  112. package/dist/index.js.map +0 -1
  113. package/dist/langgraph/checkpointer.d.ts +0 -52
  114. package/dist/langgraph/checkpointer.d.ts.map +0 -1
  115. package/dist/langgraph/checkpointer.js +0 -477
  116. package/dist/langgraph/checkpointer.js.map +0 -1
  117. package/dist/langgraph/context.d.ts +0 -10
  118. package/dist/langgraph/context.d.ts.map +0 -1
  119. package/dist/langgraph/context.js +0 -21
  120. package/dist/langgraph/context.js.map +0 -1
  121. package/dist/langgraph/errors.d.ts +0 -16
  122. package/dist/langgraph/errors.d.ts.map +0 -1
  123. package/dist/langgraph/errors.js +0 -30
  124. package/dist/langgraph/errors.js.map +0 -1
  125. package/dist/langgraph/graph.d.ts +0 -25
  126. package/dist/langgraph/graph.d.ts.map +0 -1
  127. package/dist/langgraph/graph.js +0 -378
  128. package/dist/langgraph/graph.js.map +0 -1
  129. package/dist/langgraph/index.d.ts +0 -119
  130. package/dist/langgraph/index.d.ts.map +0 -1
  131. package/dist/langgraph/index.js +0 -325
  132. package/dist/langgraph/index.js.map +0 -1
  133. package/dist/langgraph/keepalive.d.ts +0 -16
  134. package/dist/langgraph/keepalive.d.ts.map +0 -1
  135. package/dist/langgraph/keepalive.js +0 -51
  136. package/dist/langgraph/keepalive.js.map +0 -1
  137. package/dist/langgraph/nodes.d.ts +0 -71
  138. package/dist/langgraph/nodes.d.ts.map +0 -1
  139. package/dist/langgraph/nodes.js +0 -148
  140. package/dist/langgraph/nodes.js.map +0 -1
  141. package/dist/messages.d.ts +0 -18
  142. package/dist/messages.d.ts.map +0 -1
  143. package/dist/messages.js +0 -182
  144. package/dist/messages.js.map +0 -1
  145. package/dist/object.d.ts +0 -213
  146. package/dist/object.d.ts.map +0 -1
  147. package/dist/object.js +0 -309
  148. package/dist/object.js.map +0 -1
  149. package/dist/opencode/db.d.ts +0 -81
  150. package/dist/opencode/db.d.ts.map +0 -1
  151. package/dist/opencode/db.js +0 -249
  152. package/dist/opencode/db.js.map +0 -1
  153. package/dist/opencode/index.d.ts +0 -184
  154. package/dist/opencode/index.d.ts.map +0 -1
  155. package/dist/opencode/index.js +0 -1079
  156. package/dist/opencode/index.js.map +0 -1
  157. package/dist/output.d.ts +0 -25
  158. package/dist/output.d.ts.map +0 -1
  159. package/dist/output.js +0 -99
  160. package/dist/output.js.map +0 -1
  161. package/dist/pi/commits.d.ts +0 -6
  162. package/dist/pi/commits.d.ts.map +0 -1
  163. package/dist/pi/commits.js +0 -3
  164. package/dist/pi/commits.js.map +0 -1
  165. package/dist/steering.d.ts +0 -32
  166. package/dist/steering.d.ts.map +0 -1
  167. package/dist/steering.js +0 -45
  168. package/dist/steering.js.map +0 -1
  169. package/dist/tools.d.ts +0 -267
  170. package/dist/tools.d.ts.map +0 -1
  171. package/dist/tools.js +0 -305
  172. package/dist/tools.js.map +0 -1
  173. package/dist/webhook.d.ts +0 -71
  174. package/dist/webhook.d.ts.map +0 -1
  175. package/dist/webhook.js +0 -102
  176. package/dist/webhook.js.map +0 -1
  177. package/src/agentlib/README.md +0 -229
  178. package/src/agentlib/agent.ts +0 -216
  179. package/src/agentlib/index.ts +0 -16
  180. package/src/agentlib/messages.ts +0 -207
  181. package/src/agentlib/model.ts +0 -156
  182. package/src/agentlib/options.ts +0 -62
  183. package/src/agentlib/runtime.ts +0 -252
  184. package/src/agentlib/state.ts +0 -93
  185. package/src/agentlib/steering.ts +0 -53
  186. package/src/agentlib/tools.ts +0 -355
  187. package/src/agentlib/turn.ts +0 -302
  188. package/src/calls.ts +0 -330
  189. package/src/claude/README.md +0 -107
  190. package/src/claude/index.ts +0 -487
  191. package/src/client.ts +0 -187
  192. package/src/common.ts +0 -766
  193. package/src/companion.ts +0 -675
  194. package/src/conversation.ts +0 -1799
  195. package/src/deepseek/README.md +0 -202
  196. package/src/deepseek/barriers.ts +0 -63
  197. package/src/deepseek/index.ts +0 -740
  198. package/src/deepseek/persistence.ts +0 -337
  199. package/src/index.ts +0 -41
  200. package/src/langgraph/README.md +0 -199
  201. package/src/langgraph/checkpointer.ts +0 -614
  202. package/src/langgraph/context.ts +0 -27
  203. package/src/langgraph/errors.ts +0 -26
  204. package/src/langgraph/graph.ts +0 -422
  205. package/src/langgraph/index.ts +0 -500
  206. package/src/langgraph/keepalive.ts +0 -58
  207. package/src/langgraph/nodes.ts +0 -247
  208. package/src/messages.ts +0 -244
  209. package/src/object.ts +0 -454
  210. package/src/opencode/README.md +0 -249
  211. package/src/opencode/db.ts +0 -387
  212. package/src/opencode/index.ts +0 -1339
  213. package/src/output.ts +0 -116
  214. package/src/pi/README.md +0 -174
  215. package/src/pi/commits.ts +0 -7
  216. package/src/steering.ts +0 -68
  217. package/src/tools.ts +0 -515
  218. package/src/webhook.ts +0 -161
@@ -1,337 +0,0 @@
1
- // The DeepSeek Harness's session persistence (`ctx.sessionPersistence`) over
2
- // a Restate virtual object's SQL database: each session's header, and its
3
- // event log, one row per event, in order.
4
- //
5
- // The harness writes a session through a handle: `append` accepts a batch,
6
- // and `flush` is the durability barrier. Here an append is kept in memory and
7
- // a write stores everything appended before it in one SQL transaction; a new
8
- // session's header is stored with its first write, so a session that crashed
9
- // before then never existed. The session checkpoint policy
10
- // (dsh-session-checkpoint-policy) flushes before each model request, before
11
- // each tool body, and before each step.
12
- //
13
- // A write is a commit to Restate, so the harness's flushes are soft once the
14
- // adapter has put its own barriers in place (`barriered`, set by index.ts
15
- // only when it has): a soft flush stores nothing and resolves, leaving the
16
- // events queued. The adapter's barriers (`writeNow`) store everything queued
17
- // right before each model request and each tool body, before each Restate
18
- // effect and publish, and at the end of the run. So the events a tool's call
19
- // follows from are stored before the tool runs, and a crash loses only
20
- // events that nothing has acted on. Without the barriers every flush is a
21
- // write.
22
- import type { Context } from '@deepseek-ai/cordis';
23
- import { SessionLogOffset, type SessionEvent, type SessionHeader, type SessionId } from '@deepseek-ai/dsh-session';
24
- import {
25
- SessionAlreadyExistsError,
26
- SessionAlreadyOwnedError,
27
- SessionHandleClosedError,
28
- SessionPersistence,
29
- SessionPersistenceNotFoundError,
30
- SessionPersistenceRevision,
31
- SessionReadOnlyError,
32
- assertContiguous,
33
- materializeAppendBatch,
34
- materializeCreateHeader,
35
- validateStoredEvents,
36
- type SessionAccess,
37
- type SessionHandle,
38
- type SessionHandleReadResult,
39
- type SessionPersistenceCreateOptions,
40
- type SessionPersistenceSnapshot,
41
- } from '@deepseek-ai/dsh-session-persistence';
42
- import type { Database, Transaction } from '@restatedev/sessions';
43
- import { Schema } from '@restatedev/sessions/internal';
44
-
45
- const SCHEMA = new Schema('restate-agents.deepseek', [
46
- 'CREATE TABLE restate_deepseek_sessions (id TEXT PRIMARY KEY, header TEXT NOT NULL, inherited INTEGER NOT NULL)',
47
- 'CREATE TABLE restate_deepseek_events (session TEXT NOT NULL, seq INTEGER NOT NULL, event TEXT NOT NULL, PRIMARY KEY (session, seq))',
48
- ]);
49
-
50
- /** A session as stored: its header, inherited prefix length and event count. */
51
- interface Stored {
52
- header: SessionHeader;
53
- inherited: number;
54
- count: number;
55
- }
56
-
57
- /** The harness's session persistence (a cordis plugin, `{ db }`): see the top of this file. */
58
- export class SqlSessionPersistence extends SessionPersistence {
59
- // Plain fields, not private ones: cordis hands out the service through a proxy.
60
- db: Database;
61
- schema: Promise<void> | undefined;
62
- queue: Promise<unknown> = Promise.resolve();
63
- /** The open write handle of each session, by id. */
64
- writers = new Map<SessionId, SqlSessionHandle>();
65
- /** Sessions created and not stored yet: their headers and inherited counts, by id. */
66
- created = new Map<SessionId, Omit<Stored, 'count'>>();
67
- handles = new Set<SqlSessionHandle>();
68
- abandoned = false;
69
- /**
70
- * Whether the harness's flushes are soft: set by the code that installs the
71
- * adapter's barriers (index.ts), once every one of them is in place. Unset,
72
- * each flush stores what is queued.
73
- */
74
- barriered = false;
75
- /**
76
- * What each flush's events are copied into beside the log, in the flush's
77
- * transaction: the conversation of turns (index.ts), so that the copy and
78
- * the log commit together.
79
- */
80
- copy: ((tx: Transaction, events: readonly SessionEvent[]) => Promise<void>) | undefined;
81
- /** What runs once each flush is stored, outside its transaction: to tell others what it stored, say. */
82
- flushed: (() => Promise<void>) | undefined;
83
-
84
- /** `config.db`: the object's database (`ctx.db`). */
85
- constructor(ctx: Context, config: { db: Database }) {
86
- super(ctx);
87
- this.db = config.db;
88
- // The live session's events go to its write handle; its flushes and its
89
- // disposal reach the handle too.
90
- ctx.on('session/event', (session, event) => this.writers.get(session.id)?.enqueue(event));
91
- ctx.on('session/flush', (session) => this.writers.get(session.id)?.harnessFlush());
92
- ctx.on('session/disposed', (session) => void this.writers.get(session.id)?.close());
93
- ctx.effect(
94
- () => async () => {
95
- await Promise.all([...this.handles].map((handle) => handle.close()));
96
- },
97
- 'sql session handles',
98
- );
99
- }
100
-
101
- /**
102
- * Store nothing more: what is not stored yet is lost, as in a crash. For an
103
- * attempt that fails, so that its retry resumes from the last checkpoint.
104
- */
105
- abandon() {
106
- this.abandoned = true;
107
- }
108
-
109
- /** Run `operation` on the database after the ones before it: it serves one statement at a time. */
110
- serial<T>(operation: (db: Database) => Promise<T>): Promise<T> {
111
- if (this.abandoned) return Promise.reject(new Error('sql session persistence: abandoned'));
112
- this.schema ??= SCHEMA.ensure(this.db);
113
- const result = this.queue.then(() => this.schema).then(() => operation(this.db));
114
- this.queue = result.catch(() => {});
115
- return result;
116
- }
117
-
118
- async stored(id: SessionId): Promise<Stored | undefined> {
119
- const created = this.created.get(id);
120
- if (created) return { ...created, count: 0 };
121
- const [row] = await this.serial((db) =>
122
- db.values(
123
- 'SELECT header, inherited, (SELECT count(*) FROM restate_deepseek_events WHERE session = id) FROM restate_deepseek_sessions WHERE id = ?',
124
- [id],
125
- ),
126
- );
127
- return row && { header: JSON.parse(String(row[0])), inherited: Number(row[1]), count: Number(row[2]) };
128
- }
129
-
130
- async create(header: SessionHeader, options: SessionPersistenceCreateOptions = {}): Promise<SessionHandle> {
131
- const meta = materializeCreateHeader(header);
132
- if (await this.stored(meta.id)) throw new SessionAlreadyExistsError(meta.id);
133
- const inherited = options.inheritedEventCount ?? 0;
134
- this.created.set(meta.id, { header: meta, inherited });
135
- return this.openHandle(meta, inherited, 0, 'write');
136
- }
137
-
138
- async open(id: SessionId, access: SessionAccess): Promise<SessionHandle> {
139
- const stored = await this.stored(id);
140
- if (!stored) throw new SessionPersistenceNotFoundError(id);
141
- if (access === 'write' && this.writers.has(id)) throw new SessionAlreadyOwnedError(id);
142
- return this.openHandle(stored.header, stored.inherited, stored.count, access);
143
- }
144
-
145
- openHandle(header: SessionHeader, inherited: number, count: number, access: SessionAccess): SqlSessionHandle {
146
- const handle: SqlSessionHandle = new SqlSessionHandle(this, header, inherited, count, access, () => {
147
- this.handles.delete(handle);
148
- if (this.writers.get(handle.id) === handle) this.writers.delete(handle.id);
149
- });
150
- this.handles.add(handle);
151
- if (access === 'write') this.writers.set(handle.id, handle);
152
- return handle;
153
- }
154
-
155
- /** Store everything queued for session `id` now, or throw: the adapter's barrier before an effect (see the top). */
156
- async writeNow(id: SessionId): Promise<void> {
157
- await this.writers.get(id)?.writeNow();
158
- }
159
-
160
- async flush(): Promise<void> {
161
- const results = await Promise.allSettled([...this.writers.values()].map((writer) => writer.flush()));
162
- const errors = results.flatMap((r) => (r.status === 'rejected' ? [r.reason] : []));
163
- if (errors.length > 0) throw new AggregateError(errors, 'sql session persistence: flush failed');
164
- }
165
-
166
- async stat(id: SessionId): Promise<SessionPersistenceSnapshot | undefined> {
167
- const stored = await this.stored(id);
168
- return stored && snapshot(stored);
169
- }
170
-
171
- async list(): Promise<readonly SessionPersistenceSnapshot[]> {
172
- const rows = await this.serial((db) =>
173
- db.values(
174
- 'SELECT header, inherited, (SELECT count(*) FROM restate_deepseek_events WHERE session = id) FROM restate_deepseek_sessions',
175
- ),
176
- );
177
- return [
178
- ...[...this.created.values()].map((created) => snapshot({ ...created, count: 0 })),
179
- ...rows.map(([header, inherited, count]) =>
180
- snapshot({ header: JSON.parse(String(header)), inherited: Number(inherited), count: Number(count) }),
181
- ),
182
- ];
183
- }
184
- }
185
-
186
- // The log is append-only, so its length identifies its revision.
187
- const snapshot = ({ header, count }: Stored): SessionPersistenceSnapshot => ({
188
- header,
189
- revision: SessionPersistenceRevision(`${header.id}:${count}`),
190
- eventCount: count,
191
- });
192
-
193
- /** One open session: its stored events, and for a write handle the ones appended and not yet stored. */
194
- class SqlSessionHandle implements SessionHandle {
195
- readonly id: SessionId;
196
- readonly header: SessionHeader;
197
- readonly inheritedEventCount: SessionLogOffset;
198
- readonly access: SessionAccess;
199
- #store: SqlSessionPersistence;
200
- #release: () => void;
201
- #stored: number; // events stored
202
- #pending: SessionEvent[] = []; // appended, not stored yet
203
- #flushing: Promise<void> = Promise.resolve();
204
- #closed = false;
205
-
206
- constructor(
207
- store: SqlSessionPersistence,
208
- header: SessionHeader,
209
- inherited: number,
210
- stored: number,
211
- access: SessionAccess,
212
- release: () => void,
213
- ) {
214
- this.#store = store;
215
- this.header = header;
216
- this.id = header.id;
217
- this.inheritedEventCount = SessionLogOffset(inherited);
218
- this.access = access;
219
- this.#stored = stored;
220
- this.#release = release;
221
- }
222
-
223
- #check(operation: string) {
224
- if (this.#closed) throw new SessionHandleClosedError(this.id, operation);
225
- }
226
-
227
- /** The next seq: after every stored and appended event. */
228
- get #end() {
229
- return this.#stored + this.#pending.length;
230
- }
231
-
232
- async read(offset = 0, length = Infinity): Promise<SessionHandleReadResult> {
233
- this.#check('read');
234
- const rows = await this.#store.serial((db) =>
235
- db.values('SELECT event FROM restate_deepseek_events WHERE session = ? AND seq >= ? ORDER BY seq', [
236
- this.id,
237
- offset,
238
- ]),
239
- );
240
- let events: SessionEvent[] = [
241
- ...rows.map(([event]) => JSON.parse(String(event)) as SessionEvent),
242
- ...this.#pending.filter((e) => e.seq >= offset),
243
- ];
244
- if (offset === 0) events = validateStoredEvents(this.header, events);
245
- return { eventState: 'detached', events: events.slice(0, length) };
246
- }
247
-
248
- async append(events: readonly SessionEvent[]): Promise<void> {
249
- this.#check('append');
250
- if (this.access !== 'write') throw new SessionReadOnlyError(this.id, 'append');
251
- const batch = materializeAppendBatch(events);
252
- assertContiguous(this.id, batch, this.#end);
253
- this.#pending.push(...batch);
254
- }
255
-
256
- /** A live session's event, routed here by the persistence service. */
257
- enqueue(event: SessionEvent) {
258
- if (this.#closed || event.seq < this.#end) return;
259
- this.#pending.push(...materializeAppendBatch([event]));
260
- }
261
-
262
- /**
263
- * The harness's flush (`session/flush`): a write, unless the adapter's
264
- * barriers cover the effects (`barriered`), when the events stay queued for
265
- * the next barrier.
266
- */
267
- harnessFlush(): Promise<void> {
268
- if (!this.#store.barriered) return this.flush();
269
- this.#check('flush');
270
- if (this.access !== 'write') throw new SessionReadOnlyError(this.id, 'flush');
271
- return Promise.resolve();
272
- }
273
-
274
- /** Store every event appended before the call, or throw if one is not stored. */
275
- async writeNow(): Promise<void> {
276
- const end = this.#end;
277
- await this.flush();
278
- // Events appended while it stored are for the next write; none before may be left.
279
- if (this.#stored < end || this.#store.created.has(this.id)) {
280
- throw new Error(`sql session persistence: the events of session ${this.id} are not stored`);
281
- }
282
- }
283
-
284
- /** Store every event appended so far, in one transaction. */
285
- flush(): Promise<void> {
286
- this.#check('flush');
287
- if (this.access !== 'write') throw new SessionReadOnlyError(this.id, 'flush');
288
- this.#flushing = this.#flushing.then(() => this.#write());
289
- return this.#flushing;
290
- }
291
-
292
- /** Store the events appended so far, and the session's header the first time, in one transaction. */
293
- async #write(): Promise<void> {
294
- const batch = this.#pending.slice();
295
- const created = this.#store.created.get(this.id);
296
- if (batch.length === 0 && !created) return;
297
- await this.#store.serial((db) =>
298
- db.transaction(async (tx) => {
299
- if (created) {
300
- await tx.execute('INSERT INTO restate_deepseek_sessions (id, header, inherited) VALUES (?, ?, ?)', [
301
- this.id,
302
- JSON.stringify(created.header),
303
- created.inherited,
304
- ]);
305
- }
306
- for (const event of batch) {
307
- await tx.execute('INSERT INTO restate_deepseek_events (session, seq, event) VALUES (?, ?, ?)', [
308
- this.id,
309
- event.seq,
310
- JSON.stringify(event),
311
- ]);
312
- }
313
- if (this.#store.copy) await this.#store.copy(tx, batch);
314
- }),
315
- );
316
- if (created) this.#store.created.delete(this.id);
317
- this.#pending.splice(0, batch.length);
318
- this.#stored += batch.length;
319
- if (this.#store.flushed) await this.#store.flushed();
320
- }
321
-
322
- async close(): Promise<void> {
323
- if (this.#closed) return;
324
- try {
325
- if (this.access === 'write') await this.flush().catch(() => {});
326
- } finally {
327
- this.#closed = true;
328
- // A session never stored is gone with its writer.
329
- if (this.access === 'write') this.#store.created.delete(this.id);
330
- this.#release();
331
- }
332
- }
333
-
334
- [Symbol.asyncDispose]() {
335
- return this.close();
336
- }
337
- }
package/src/index.ts DELETED
@@ -1,41 +0,0 @@
1
- // @restatedev/agents: agent frameworks in Restate session objects. Each framework
2
- // is a subpath (@restatedev/agents/pi, /langgraph, /claude, /deepseek, /opencode, /agentlib); this is what they share: session objects, tools for
3
- // any of them, and the tools that are Restate itself.
4
-
5
- export {
6
- type AgentContext,
7
- type AgentViewContext,
8
- CANCELLED,
9
- chatHandler,
10
- type ChatMessage,
11
- type Messages,
12
- type MessagesRequest,
13
- type Part,
14
- REFUSED,
15
- type Answering,
16
- UNANSWERED,
17
- type Configure,
18
- } from './common.ts';
19
- export { sessionObject, type Status, type Stopped } from './object.ts';
20
- export {
21
- COMPANION_SUFFIX,
22
- companionOf,
23
- deliver,
24
- type Companion,
25
- type Resolved,
26
- type Signal,
27
- type Steered,
28
- type Steering,
29
- type Waiting,
30
- } from './companion.ts';
31
- export { call, send, signal, subagent, tool, workflow, type Tool, type ToolCall, type ToolContext } from './tools.ts';
32
- export { webhook, webhookMessage, type WebhookAuth, type WebhookEvent, type WebhookOptions } from './webhook.ts';
33
-
34
- /**
35
- * @restatedev/sessions' `serve`: the services on PORT, with what they need
36
- * beside them (each agent's companion); `connect`, the same for Restate
37
- * Cloud, where the SDK's own `connect` would leave the companions out; and
38
- * `served`, those services, for an endpoint of your own
39
- * (`restate.endpoint()`).
40
- */
41
- export { connect, serve, served } from '@restatedev/sessions';
@@ -1,199 +0,0 @@
1
- # LangGraph
2
-
3
- [LangGraph](https://langchain-ai.github.io/langgraphjs/) runs an agent as a
4
- graph of steps. The built-in agent here stores each step in the agent's
5
- conversation of turns, in its SQL database
6
- ([SQL in Restate virtual objects](../../../sessions/README.md)); a graph of
7
- your own keeps its checkpoints there too, with `SqlCheckpointSaver`.
8
-
9
- ## Use
10
-
11
- ```ts
12
- import { serve } from '@restatedev/agents';
13
- import * as langgraph from '@restatedev/agents/langgraph';
14
- import { weather } from './weather.ts';
15
-
16
- const assistant = langgraph.agent({ name: 'assistant', system: 'Answer briefly.', tools: [weather] });
17
- await serve(assistant);
18
- ```
19
-
20
- | Option | What |
21
- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
22
- | `model` | `openai/model-id` (`ChatOpenAI`) or `anthropic/model-id` (`ChatAnthropic`); or else `MODEL`, or else `openai/gpt-6-sol` (`OPENAI_API_KEY`); or any LangChain chat model that calls tools |
23
- | `system` | The system prompt |
24
- | `tools` | `tool()`s and Restate's tools of `@restatedev/agents`, or LangChain's tools |
25
- | `output` | A zod object: the answer as data, which the agent replies with as JSON, and `chat` answers with (see [Structured answers](../../README.md#structured-answers)) |
26
-
27
- For a session object of your own, `langgraph.chat(options)` is the handler and
28
- `langgraph.messages()` the view; `options` may be a function of the
29
- invocation's context (each user's system prompt, say). `langgraph.prompt(ctx,
30
- text, options)` answers a prompt in a handler of your own, once, however
31
- often the handler runs; each prompt of an invocation is a prompt of its own. The graph is the usual tool-calling
32
- loop: a model node, a tools node, and back to the model until it answers.
33
-
34
- ## A graph of your own
35
-
36
- Bring a graph built on LangGraph's `MessagesAnnotation` (or a compiled one,
37
- such as LangChain's `createAgent` makes): `chat` then runs it, with each
38
- message as a new `HumanMessage`, and answers with its last AI message
39
- ([`graph.ts`](graph.ts)). It has its own model and tools, so it takes no
40
- `model`, `system`, `tools` or `recursionLimit`.
41
-
42
- ```ts
43
- const desk = langgraph.agent({ name: 'desk', graph });
44
- // LangGraph's run context, for a graph with a context schema of its own: by default the handler's context.
45
- const desk = langgraph.agent({ name: 'desk', graph, context: { region: 'eu' } });
46
- ```
47
-
48
- - **Its checkpoints are in the key's database** (`SqlCheckpointSaver`, one
49
- thread per key), each stored before its step runs (`durability: 'sync'`):
50
- a retried attempt resumes the run it cut off, and a step stored is not run
51
- again. Between turns the thread keeps its latest checkpoint (`prune`).
52
- - **The `messages` view shows the run as it goes**: after each step, the AI
53
- and tool messages it added are copied into the conversation, by their ids
54
- (a step's tool messages in one write).
55
- The conversation is a log: a message the graph removes or edits later
56
- stays as it was copied.
57
- - **`interrupt()` waits for a signal** named `interrupt`, which the agent's
58
- `pending` view lists with the interrupt's value, and `signal` resolves; the
59
- run resumes with the signal's value as `interrupt()`'s result. The turn
60
- waits without holding a process. Static breakpoints (`interruptBefore`,
61
- `interruptAfter`) have nothing to wait for: a graph with them is refused.
62
- - **A step's side effects run again after a crash** (a payment, a plain
63
- LangChain tool): a graph is durable a step at a time. A model request may
64
- be made again; for the rest, use Restate's tools.
65
- - **Any error fails the attempt**, which Restate retries; a
66
- `restate.TerminalError` (and LangGraph's own errors that a retry would
67
- meet again) ends the turn. A stopped, refused or failed run is not
68
- resumed: the next message starts a run of its own, with what closed the
69
- last one (its cut-off calls' results and the note that ends it) first.
70
- - **The graph's state is its own**: its models read the state, not the
71
- conversation, so `window`, `budget` and `summarize` do not reach them.
72
- Trim it in the graph (a node that returns a `RemoveMessage` for each
73
- message to drop, say).
74
- - **`output`**: the graph's own prompts must ask for it. A graph that writes
75
- a `structuredResponse` (LangChain's `createAgent` with a `responseFormat`)
76
- answers with it, as JSON; else its last AI message is validated.
77
-
78
- ### Restate's steps in a graph of your own
79
-
80
- A graph is durable a step at a time: a crash runs the step it cut off
81
- again, which is fine for a model request, but not for a payment. Make a
82
- step's side effects Restate's, done once:
83
-
84
- - **Prebuilt nodes** ([`nodes.ts`](nodes.ts)): `nodes.waitForSignal`,
85
- `nodes.workflow`, `nodes.call`, `nodes.send` and `nodes.subagent` each
86
- read their input from the state and write what they get back to the field
87
- `output`. A node run again (a crash, a retried attempt) gets the same task
88
- id from LangGraph, so it joins the call, the workflow or the wait it
89
- started rather than start another.
90
-
91
- ```ts
92
- const graph = new StateGraph(State)
93
- .addNode('approve', nodes.waitForSignal('approval', { input: (s) => s.refund, output: 'approved' }))
94
- .addNode('ship', nodes.workflow(shipping, { input: (s) => s.order, output: 'receipt' }));
95
- ```
96
-
97
- - **Restate's tools** in a `ToolNode`, or LangChain's `createAgent`:
98
- `langgraph.tools([...])` makes `tool()`s and Restate's tools (`call`,
99
- `send`, `workflow`, `subagent`, `signal`) LangChain tools. Restate's make
100
- their calls once per tool call, as the model's reply with the call's id is
101
- checkpointed before the tools run; LangChain's tools are passed through.
102
-
103
- Both take the handler's context from the graph's run: `langgraph.agent({
104
- graph })` gives it, and a handler of your own passes it as the run context
105
- (`invoke(input, { context: ctx, durability: 'sync' })`, with a
106
- `SqlCheckpointSaver(ctx.db)`). A node refuses to run without it, a
107
- checkpointer, or `durability: 'sync'`.
108
-
109
- ## Kept alive
110
-
111
- An attempt of a session object is shut down by Restate after its inactivity
112
- timeout (a minute), and run again from the start, unless work keeps it alive
113
- (`ctx.working`). Each request of a model does: the built-in graph's model
114
- node, the summarizer's, and, in a graph of your own, every chat model's request
115
- wherever the graph makes it (a node's, `createAgent`'s), through a callback
116
- handler the agent passes in the run's config (so a graph of your own needs
117
- nothing). A tool is not kept alive, unless it sets `keepalive`.
118
-
119
- ## Through crashes
120
-
121
- The built-in agent keeps no checkpoints: its conversation is the object's
122
- conversation of turns ([docs/conversation.md](../../docs/conversation.md)),
123
- whose items are LangChain's messages, and its graph starts from what the
124
- model sees of it (the earlier turns as their prompt and answer, within
125
- `budget`; the latest `window` turns whole). The handler is not replayed: a
126
- retried attempt runs it again from the start, from what is stored.
127
-
128
- - **The model node stores its reply with tool calls before it returns, and
129
- the tools node the round's results in one write, once its tools ran.** So
130
- a crash during the tools runs the round's calls again, those that had
131
- finished too, with the same tool call ids, without asking the model
132
- again. The final reply, which no tool waits for, is stored with
133
- the turn's answer, in one commit: a crash before it asks the model again.
134
- - **A tool is idempotent by its tool call id** (`callId` of `tool()`'s
135
- `run`), which it passes on, such as in an idempotency key.
136
- - **A tool's error fails the attempt**, and Restate retries it (the ToolNode
137
- would hand it to the model); a `restate.TerminalError` of a
138
- `@restatedev/agents` tool is its answer to the model, and so are arguments
139
- that do not fit a tool, and a call of a tool the agent does not have.
140
- - **A turn takes at most `recursionLimit` steps** (default 10 000): past
141
- it, it fails for good. So do LangGraph's other errors that a retry would
142
- meet again: an invalid state update, and a run with no input
143
- ([`errors.ts`](errors.ts)).
144
- - **A message is answered once per invocation** (`answerOnce`). A turn that
145
- a killed invocation left is closed (`ended`), never finished.
146
-
147
- The checkpointer ([`checkpointer.ts`](checkpointer.ts), `SqlCheckpointSaver`),
148
- for a graph of your own, keeps checkpoints, channel values and pending
149
- writes in three tables; a step stores only the channels it changed. With
150
- `history: 'latest'` a thread keeps its latest checkpoint only, and the
151
- ancestors a `DeltaChannel` is rebuilt from; by default it keeps them all,
152
- for LangGraph's history.
153
-
154
- A task's pending writes are stored in the transaction of the checkpoint that
155
- follows them, when that comes in the same macrotask (the step's last task has
156
- just finished): a step is one commit. While other tasks of the step still run,
157
- the writes of one that finished are stored on their own at the end of the
158
- macrotask, so that it does not run again after a crash. A `putWrites` promise
159
- resolves once its rows are stored (and fails with the error of the commit that
160
- carried them), so a graph's `invoke` that returns has everything stored, as
161
- LangGraph awaits them. Reads and `prune` store what is pending first.
162
-
163
- ## Run
164
-
165
- ```sh
166
- cd packages/examples && OPENAI_API_KEY=… node basic/langgraph.ts
167
- ```
168
-
169
- With a Restate server, and the agent registered with it: see
170
- [Run an example](../../../examples/README.md#run-an-example).
171
-
172
- ## Tests
173
-
174
- The tests run on a scripted model, [`test/fakes/langgraph.ts`](../../test/fakes/langgraph.ts)
175
- (`pnpm --filter @restatedev/agents test langgraph`, from the repository root):
176
-
177
- - [`test/storage/langgraph.test.ts`](../../test/storage/langgraph.test.ts):
178
- LangGraph's checkpointer conformance suite
179
- (`@langchain/langgraph-checkpoint-validation`, 718 tests); and
180
- [`langgraph-fork.test.ts`](../../test/storage/langgraph-fork.test.ts),
181
- a forked thread; [`langgraph-latest.test.ts`](../../test/storage/langgraph-latest.test.ts),
182
- `history: 'latest'` with a `DeltaChannel`, and graphs of more channels than
183
- an `OR` of them can match.
184
- - [`test/langgraph-graph.test.ts`](../../test/langgraph-graph.test.ts): a
185
- graph of your own: its thread across turns, a run a crash cut off,
186
- `interrupt()` as signals (a retried attempt joins the same wait), the
187
- structured response, what closed a failed run, and the graphs refused;
188
- [`langgraph-nodes.test.ts`](../../test/langgraph-nodes.test.ts), the
189
- prebuilt nodes and `tools()`, through crashes;
190
- [`storage/langgraph-prune.test.ts`](../../test/storage/langgraph-prune.test.ts),
191
- the checkpointer's `prune` and `metadata`.
192
- - [`test/langgraph.test.ts`](../../test/langgraph.test.ts):
193
- each point above, with crashes that stop an attempt in a tool call, or
194
- at any of its state requests; the
195
- system prompt; arguments that do not fit a tool; the recursion limit; and
196
- `messages`.
197
- - [`test/langgraph.ts`](../../test/langgraph.ts): the
198
- bank agent, through crashes in [the crash test](../../../e2e/crash.ts)
199
- (`pnpm --filter e2e crash`): every message moves money exactly once.