@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
package/src/pi/storage.ts CHANGED
@@ -1,24 +1,24 @@
1
- // pi-durable storage on an SQL database: the `SqliteDatabase` facade of
2
- // @earendil-works/chord/sqlite, over a database session `db` (in Restate,
3
- // `ctx.db`), which has `query`, `get`, `execute` and
4
- // `transaction(body)`.
1
+ // pi-durable storage in the key's database: `SqlKvDatabase` is chord's
2
+ // `SqliteDatabase` facade over a database session (`ctx.db`). The session runs
3
+ // operations one at a time, as the facade requires, and a statement outside a
4
+ // transaction is its own transaction.
5
5
  //
6
- // The facade's operations must run one at a time, a transaction excluding
7
- // every other: the session does that, and a transaction's handle is invalid
8
- // once its body settles. A statement outside a transaction is its own
9
- // transaction.
6
+ // Each pi commit is one session transaction, one commit to Restate. A retry
7
+ // finds exactly the commits that completed, and pi resumes from them.
10
8
  //
11
- // With `commits: 'effects'` the adapter batches: between two effects (a model
12
- // call, a tool) the commits of pi share one transaction of the session, held
13
- // open and written once, when an effect starts, something else is about to
14
- // see what was stored, or another call to the session waits for it. See
15
- // {@link SqlKvDatabase}.
16
- //
17
- // pi-durable's tables and indexes are named `restate_pi_<name>` (its
18
- // storage's `prefix`), apart from the tables of yours in the same database.
19
- import { AsyncLocalStorage } from 'node:async_hooks';
20
- import type { DatabaseWriter, Database, Transaction } from '@restatedev/sessions';
21
- import { deferSql, undeferSql } from '@restatedev/sessions/internal';
9
+ // pi-durable's tables and indexes are prefixed `restate_pi_`, apart from yours.
10
+ // The integration's own table, `restate_withpi_writer`, holds one row: the
11
+ // invocation that last wrote pi's storage after `abortLeft` checked it
12
+ // (left.ts), in the same database. It is written in the first transaction of
13
+ // pi on that database that writes after the check, as part of it. pi writes
14
+ // only in transactions, its migrations included: each open of its storage runs
15
+ // them in one, which always runs statements, though on tables that are there
16
+ // it changes nothing. So the row rides a commit pi makes anyway, unless the
17
+ // attempt has written nothing since its check and opens pi's storage again
18
+ // (another closure, a `messages()`): that open's migrations then commit the
19
+ // row, a commit the attempt would not make otherwise. An attempt whose check
20
+ // finds it recorded already records nothing, so a retry adds no commit.
21
+ import type { DatabaseWriter, Database } from '@restatedev/sessions';
22
22
  import {
23
23
  SqliteStorage,
24
24
  type SqliteDatabase,
@@ -26,23 +26,47 @@ import {
26
26
  type SqliteValue,
27
27
  } from '@earendil-works/pi-durable/storage/sqlite';
28
28
 
29
- /** The prefix of pi-durable's tables and indexes. */
30
29
  const PREFIX = 'restate_pi_';
31
30
 
32
- /** SQL through `db`: the session, or one transaction's. */
31
+ /** The table of the invocation that last wrote pi's storage after `abortLeft` checked it: one row. */
32
+ const WRITER = 'restate_withpi_writer';
33
+
34
+ /** The invocation each attempt's database records as pi's writer, by the database object, and whether it has. */
35
+ const writers = new WeakMap<Database, { invocation: string; recorded: boolean }>();
36
+
37
+ /**
38
+ * From now on, pi's next commit on `db` that writes also records `invocation` as the writer, once. `abortLeft` calls
39
+ * it once it has aborted the runs it found: every run live after that is the invocation's own.
40
+ */
41
+ export function recordWriter(db: Database, invocation: string): void {
42
+ if (!writers.has(db)) writers.set(db, { invocation, recorded: false });
43
+ }
44
+
45
+ /** The invocation that last wrote pi's storage on `db` after checking it, if one did. */
46
+ export async function lastWriter(db: Database): Promise<string | undefined> {
47
+ const table = await db.get("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?", [WRITER]);
48
+ if (table === undefined) return undefined;
49
+ return (await db.get<{ invocation: string }>(`SELECT invocation FROM ${WRITER}`))?.invocation;
50
+ }
51
+
33
52
  class Executor implements SqliteExecutor {
34
53
  readonly db: DatabaseWriter;
54
+ /** Whether a statement that may write ran through this executor. */
55
+ wrote = false;
35
56
  constructor(db: DatabaseWriter) {
36
57
  this.db = db;
37
58
  }
38
59
  async exec(sql: string) {
60
+ this.wrote = true;
39
61
  await this.db.execute(sql);
40
62
  }
41
63
  async run(sql: string, ...params: SqliteValue[]) {
64
+ this.wrote = true;
42
65
  await this.db.execute(sql, params);
43
66
  }
44
- /** `run`, resolving with the rows it changed: SQLite's `changes()`, read next on the same connection. */
67
+ /** `run`, resolving with SQLite's `changes()`, read next on the same connection. */
45
68
  async runCounted(sql: string, ...params: SqliteValue[]): Promise<number> {
69
+ this.wrote = true;
46
70
  await this.db.execute(sql, params);
47
71
  return (await this.db.get<{ n: number }>('SELECT changes() AS n'))!.n;
48
72
  }
@@ -54,410 +78,52 @@ class Executor implements SqliteExecutor {
54
78
  }
55
79
  }
56
80
 
57
- /** The savepoint of a pi commit in a batch, and its end. */
58
- const SAVEPOINT = 'SAVEPOINT restate_pi';
59
- const RELEASE = 'RELEASE restate_pi';
60
-
61
- /** What runs at the end of each pi commit, in its transaction: the copy of its entries (index.ts). */
62
- export type OnCommit = (tx: Transaction) => Promise<void>;
63
-
64
- /** How pi's commits are written: one each, or one for all those between two effects. */
65
- export type Commits = 'effects' | 'each';
66
-
67
- /** What the adapter reports and takes. */
68
- export interface SqlKvOptions {
69
- /** Default `'each'`: every pi commit is a transaction of the session, as ever. */
70
- commits?: Commits;
71
- /**
72
- * Told once, with the error, when a batch fails to commit: the pi commits
73
- * in it were reported to pi as done and are lost, so the attempt must
74
- * fail (the adapter's later calls all reject with that error, too).
75
- */
76
- failed?: (error: unknown) => void;
77
- }
78
-
79
- /** The transaction that holds a batch of pi's commits open: its handle, and how to end it. */
80
- interface Batch {
81
- readonly tx: Transaction;
82
- /** Run a function in the async context of the transaction's body, where the session refuses `ctx.db` calls. */
83
- readonly run: <R>(fn: () => R) => R;
84
- /** Let the body return, so that the transaction commits. */
85
- readonly release: () => void;
86
- /** Make the body throw `error`, so that the session rolls the whole transaction back, its sends with it. */
87
- readonly abort: (error: unknown) => void;
88
- }
89
-
90
- /** An open batch, and the promise that settles when its transaction has committed or failed. */
91
- interface Held {
92
- readonly batch: Batch;
93
- readonly done: Promise<void>;
94
- /** Whether a write of it was told to its caller as done: only then is a failure to commit it a loss. */
95
- acknowledged: boolean;
96
- }
97
-
98
- /** `tx`, whose `send` is the real one, and tells `sent` when it is called. */
99
- function noting(tx: Transaction, sent: () => void): Transaction {
100
- const send = new Proxy(tx.send, {
101
- apply(target, thisArg, args: Parameters<Transaction['send']>) {
102
- sent();
103
- return Reflect.apply(target, thisArg, args) as unknown;
104
- },
105
- });
106
- return { ...tx, send };
107
- }
108
-
109
- /** The refusal of a call to the adapter from the callback of one of its transactions, which would wait for itself. */
110
- const REFUSED = 'inside a transaction, use the transaction handle its callback gets';
111
-
112
- /**
113
- * The `SqliteDatabase` facade over the session `db`.
114
- *
115
- * With the default `commits: 'each'`, each `transaction(callback)` of pi is
116
- * one transaction of the session: one write, one round trip to Restate.
117
- *
118
- * With `'effects'`, while it is {@link armed} and no effect is in flight
119
- * ({@link effectStarted}), the first write opens one transaction of the
120
- * session that stays open, and each pi transaction is a savepoint in it
121
- * (a failed one undoes only itself). {@link flush} ends it: the real commit,
122
- * and then the `afterCommit` of every pi commit in it. It ends also when
123
- * another call to the session queues behind it (a `ctx.db` call of the
124
- * handler): that call then waits for one commit and no more. While an
125
- * effect is in flight, every pi commit is a transaction of its own, as with
126
- * `'each'`. Reads see the open batch. All calls run one at a time on a chain
127
- * of their own.
128
- */
81
+ /** chord's `SqliteDatabase` facade over the session `db`: each pi transaction is a session transaction. */
129
82
  export class SqlKvDatabase extends Executor implements SqliteDatabase {
130
83
  readonly #session: Database;
131
- readonly #batching: boolean;
132
- readonly #failed: ((error: unknown) => void) | undefined;
133
- /** Runs at the end of each commit, in its transaction, so that what it writes commits with it. */
134
- onCommit: OnCommit | undefined;
135
- /** Runs once each commit is done, outside its transaction: to tell others what it stored, say. */
136
- afterCommit: (() => Promise<void>) | undefined;
137
- /** Settles when the last call made so far has: the next runs after it. */
138
- #chain: Promise<unknown> = Promise.resolve();
139
- #batch: Held | undefined;
140
- #armed = false;
141
- #effects = 0;
142
- /** The `afterCommit` of each commit in the batch, run after its real commit. */
143
- #after: (() => Promise<void>)[] = [];
144
- /** The error of the first batch that failed, which every later call fails with. */
145
- #failure: { error: unknown } | undefined;
146
- /** Whether the attempt has been told of it. */
147
- #told = false;
148
- /** Settles when the `afterCommit` callbacks started so far have run. */
149
- #afterRun: Promise<unknown> = Promise.resolve();
150
- /** Set while `afterCommit` callbacks run: a flush from one of them has them to wait for. */
151
- readonly #inAfter = new AsyncLocalStorage<true>();
152
- /** Set inside the callback of a transaction: a call to the adapter from there would wait for itself. */
153
- readonly #inside = new AsyncLocalStorage<true>();
154
84
 
155
- constructor(db: Database, { commits = 'each', failed }: SqlKvOptions = {}) {
85
+ constructor(db: Database) {
156
86
  super(db);
157
87
  this.#session = db;
158
- this.#batching = commits === 'effects';
159
- this.#failed = failed;
160
- }
161
-
162
- /**
163
- * Whether commits are batched while no effect is in flight: set while pi
164
- * runs a prompt, and off otherwise. Ending the batch is the caller's
165
- * ({@link flush}). Without `'effects'` it does nothing.
166
- */
167
- set armed(armed: boolean) {
168
- this.#armed = armed && this.#batching;
169
88
  }
170
89
 
171
90
  /**
172
- * An effect starts: a model call or a tool, which must see what pi stored
173
- * before, and which may store commits of its own. Until the returned
174
- * function is called (once at most; later calls do nothing) every commit
175
- * is written at once. It starts no flush: {@link flush} does. An effect
176
- * whose end is never called leaves the batching off, which is how it was.
91
+ * Commits when the callback resolves; rolls back, and rejects with its error, when it rejects. A transaction that
92
+ * wrote also records the writer, if `recordWriter` asked for it and it is not recorded yet.
177
93
  */
178
- effectStarted(): () => void {
179
- if (!this.#batching) return () => {};
180
- this.#effects++;
181
- let ended = false;
182
- return () => {
183
- if (ended) return;
184
- ended = true;
185
- this.#effects--;
186
- };
187
- }
188
-
189
- /**
190
- * Write what the batch holds: its real commit, then what `afterCommit`
191
- * of each of its commits does, in order. Nothing if none is open.
192
- * Rejects if the commit failed (see {@link SqlKvOptions.failed}), and from
193
- * the callback of a transaction, which would wait for itself.
194
- */
195
- async flush(): Promise<void> {
196
- if (!this.#batching) return;
197
- if (this.#inside.getStore()) throw new Error(REFUSED);
198
- await this.#run(() => this.#closeBatch());
199
- await this.#runAfter();
200
- }
201
-
202
- /** Commits when the callback resolves; rolls back, and rejects with its error, when it rejects. */
203
94
  async transaction<T>(callback: (transaction: SqliteExecutor) => Promise<T>): Promise<T> {
204
- if (!this.#batching) {
205
- const result = await this.#session.transaction(async (tx) => {
206
- const done = await callback(new Executor(tx));
207
- if (this.onCommit) await this.onCommit(tx);
208
- return done;
209
- });
210
- if (this.afterCommit) await this.afterCommit();
211
- return result;
212
- }
213
- this.#refuseInside();
214
- const after = this.afterCommit;
215
- const { result, batched } = await this.#run(async () => {
216
- if (!this.#writesBatched()) return { result: await this.#commitAlone(callback), batched: false };
217
- return { result: await this.#savepoint(callback, after), batched: true };
218
- });
219
- // Outside the chain: it may publish, which flushes.
220
- if (!batched && after) await after();
221
- return result;
222
- }
223
-
224
- override exec(sql: string) {
225
- return this.#batching ? this.#write((e) => e.exec(sql)) : super.exec(sql);
226
- }
227
-
228
- override run(sql: string, ...params: SqliteValue[]) {
229
- return this.#batching ? this.#write((e) => e.run(sql, ...params)) : super.run(sql, ...params);
230
- }
231
-
232
- /**
233
- * Outside a transaction, the statement and its count are one: another
234
- * statement between them would be what `changes()` counted.
235
- */
236
- override runCounted(sql: string, ...params: SqliteValue[]): Promise<number> {
237
- if (!this.#batching) return this.#session.transaction((tx) => new Executor(tx).runCounted(sql, ...params));
238
- return this.#write((e) => e.runCounted(sql, ...params), true);
239
- }
240
-
241
- override get<T extends object>(sql: string, ...params: SqliteValue[]): Promise<T | undefined> {
242
- return this.#batching ? this.#read((e) => e.get<T>(sql, ...params)) : super.get<T>(sql, ...params);
243
- }
244
-
245
- override all<T extends object>(sql: string, ...params: SqliteValue[]): Promise<T[]> {
246
- return this.#batching ? this.#read((e) => e.all<T>(sql, ...params)) : super.all<T>(sql, ...params);
247
- }
248
-
249
- /**
250
- * Writes what the batch holds (a prompt's end has written it already: a batch left now is one of a run that
251
- * was abandoned as the attempt ended or failed), without failing: the error the attempt ends with is the
252
- * attempt's, not this write's, which is told to the attempt and refused to every later call. The session is
253
- * the caller's to end, after the calls made before.
254
- */
255
- async close() {
256
- await this.flush().catch(() => {});
257
- }
258
-
259
- /** Whether the next write joins the batch: armed, and no effect in flight. */
260
- #writesBatched(): boolean {
261
- return this.#armed && this.#effects === 0;
262
- }
263
-
264
- #refuseInside() {
265
- if (this.#inside.getStore()) throw new Error(REFUSED);
266
- }
267
-
268
- /** `call`, once the calls before it have ended, unless a batch failed. */
269
- #run<T>(call: () => Promise<T>): Promise<T> {
270
- const result = this.#chain.then(() => {
271
- if (this.#failure) {
272
- this.#tell();
273
- throw this.#failure.error;
95
+ const writer = writers.get(this.#session);
96
+ const record = writer !== undefined && !writer.recorded;
97
+ let wrote = false;
98
+ const result = await this.#session.transaction(async (tx) => {
99
+ const executor = new Executor(tx);
100
+ const value = await callback(executor);
101
+ wrote = executor.wrote;
102
+ if (record && wrote) {
103
+ await tx.execute(
104
+ `CREATE TABLE IF NOT EXISTS ${WRITER} (singleton INTEGER PRIMARY KEY CHECK (singleton = 1), invocation TEXT NOT NULL)`,
105
+ );
106
+ await tx.execute(
107
+ `INSERT INTO ${WRITER} (singleton, invocation) VALUES (1, ?) ON CONFLICT (singleton) DO UPDATE SET invocation = excluded.invocation`,
108
+ [writer.invocation],
109
+ );
274
110
  }
275
- return call();
111
+ return value;
276
112
  });
277
- this.#chain = result.catch(() => {});
278
- return result;
279
- }
280
-
281
- /** A read: in the batch if one is open (it sees its writes), else on the session, which opens nothing. */
282
- #read<T>(read: (executor: Executor) => Promise<T>): Promise<T> {
283
- this.#refuseInside();
284
- return this.#run(() => read(new Executor(this.#batch ? this.#batch.batch.tx : this.#session)));
285
- }
286
-
287
- /** A write outside a transaction: in the batch if batched, else a transaction of its own. */
288
- #write<T>(write: (executor: Executor) => Promise<T>, counted = false): Promise<T> {
289
- this.#refuseInside();
290
- return this.#run(async () => {
291
- if (this.#writesBatched()) {
292
- const batch = await this.#opened();
293
- const result = await write(new Executor(batch.tx));
294
- this.#batch!.acknowledged = true;
295
- return result;
296
- }
297
- await this.#closeBatch();
298
- // `runCounted` is a transaction of its own, as ever; the others are one statement.
299
- return counted ? this.#session.transaction((tx) => write(new Executor(tx))) : write(new Executor(this.#session));
300
- });
301
- }
302
-
303
- /** One pi transaction that is a transaction of the session: not batched, with its `onCommit` in it. */
304
- async #commitAlone<T>(callback: (transaction: SqliteExecutor) => Promise<T>): Promise<T> {
305
- await this.#closeBatch();
306
- return this.#session.transaction((tx) =>
307
- this.#inside.run(true, async () => {
308
- const done = await callback(new Executor(tx));
309
- if (this.onCommit) await this.onCommit(tx);
310
- return done;
311
- }),
312
- );
313
- }
314
-
315
- /**
316
- * One pi transaction in the batch, as a savepoint: released when it
317
- * succeeds, rolled back (and released) when it fails, so that a failed
318
- * one undoes only itself. Its `afterCommit` waits for the batch's commit.
319
- */
320
- async #savepoint<T>(
321
- callback: (transaction: SqliteExecutor) => Promise<T>,
322
- after: (() => Promise<void>) | undefined,
323
- ): Promise<T> {
324
- const { tx, run } = await this.#opened();
325
- const held = this.#batch!;
326
- // The savepoint goes with the first statement of the commit, and the release that ended the one before it
327
- // (queued below), in the same crossing, in order. A session that cannot defer runs it at once.
328
- const deferred = deferSql(tx, SAVEPOINT);
329
- if (!deferred) await tx.execute(SAVEPOINT);
330
- // Whether this commit sent something. A send is recorded on the held transaction, and its real commit
331
- // makes it whatever a savepoint did: rolling the savepoint back does not take it back. So a commit that
332
- // sent and then failed cannot be undone alone; the whole batch is (below).
333
- let sent = false;
334
- let result: T;
335
- try {
336
- // In the async context of the batch's body, so that a call to `ctx.db` from the callback is refused
337
- // at once, as it is in a transaction of the session, and not left to wait for the batch.
338
- result = await run(() =>
339
- this.#inside.run(true, async () => {
340
- const done = await callback(new Executor(tx));
341
- if (this.onCommit) await this.onCommit(noting(tx, () => (sent = true)));
342
- return done;
343
- }),
344
- );
345
- // A savepoint still queued had no statement run in it: with nothing to undo, it and its release are
346
- // no-ops, and neither is run. Otherwise the release rides with the next statement of the batch, or goes
347
- // with the batch's end (see `#closeBatch`).
348
- if (!deferred) await tx.execute(RELEASE);
349
- else if (!undeferSql(tx, SAVEPOINT) && !deferSql(tx, RELEASE)) await tx.execute(RELEASE);
350
- } catch (error) {
351
- if (sent) {
352
- await this.#abandon(held, error);
353
- throw error;
354
- }
355
- try {
356
- await tx.execute('ROLLBACK TO restate_pi');
357
- await tx.execute(RELEASE);
358
- } catch {
359
- // The session failed too: the error of the commit is what the caller gets, and the next call fails.
360
- }
361
- throw error;
362
- }
363
- held.acknowledged = true;
364
- if (after) this.#after.push(after);
113
+ if (record && wrote) writer.recorded = true;
365
114
  return result;
366
115
  }
367
116
 
368
- /**
369
- * Drop the batch with `error`: its body throws, the session rolls the whole transaction back, and its sends
370
- * are never made. If the commits in it were told to pi as done, they are lost, as with a failed write.
371
- */
372
- async #abandon(held: Held, error: unknown): Promise<void> {
373
- this.#batch = undefined;
374
- held.batch.abort(error);
375
- await held.done.catch(() => {});
376
- if (held.acknowledged) this.#fail(error);
377
- }
378
-
379
- /** The open batch, opened if there is none. */
380
- async #opened(): Promise<Batch> {
381
- if (this.#batch) return this.#batch.batch;
382
- const opened = Promise.withResolvers<Batch>();
383
- const released = Promise.withResolvers<void>();
384
- const done = this.#session.transaction(async (tx) => {
385
- opened.resolve({ tx, run: AsyncLocalStorage.snapshot(), release: released.resolve, abort: released.reject });
386
- await released.promise;
387
- });
388
- // A failure before the body ran: the open itself.
389
- done.catch((error: unknown) => opened.reject(error));
390
- // A batch that could not be opened lost nothing: the call that asked for it fails, as one does without
391
- // batching (a cancellation owed to the handler is delivered once, say), and the next one tries again.
392
- const batch = await opened.promise;
393
- const held: Held = { batch, done, acknowledged: false };
394
- // Failing while it waits to be ended, with something told as done, is every later call's error.
395
- done.catch((error: unknown) => (held.acknowledged ? this.#fail(error, false) : undefined));
396
- this.#batch = held;
397
- // Another call to the session queued behind it: end it, after the call of pi under way.
398
- // A failure is the attempt's already (`#fail`): nobody waits for this flush.
399
- void batch.tx.queued.then(() => (this.#batch === held ? this.flush().catch(() => {}) : undefined));
400
- return batch;
401
- }
402
-
403
- /** End the batch, if one is open: its commit, which the calls after it wait for. */
404
- async #closeBatch(): Promise<void> {
405
- const held = this.#batch;
406
- if (!held) return;
407
- this.#batch = undefined;
408
- // The release of the last commit's savepoint, if nothing ran after it, is not run: the commit ends every
409
- // savepoint of its transaction.
410
- undeferSql(held.batch.tx, RELEASE);
411
- held.batch.release();
412
- try {
413
- await held.done;
414
- } catch (error) {
415
- // What was told to pi as done is lost; if nothing was, this fails as the commit it was would have.
416
- if (!held.acknowledged) throw error;
417
- this.#after = [];
418
- throw this.#fail(error);
419
- }
420
- }
421
-
422
- /**
423
- * Run what the commits of the last batch asked to run after it, in order,
424
- * after what an earlier flush is running: a flush that returns has had
425
- * all of those done, so that effects that start together start after the
426
- * publish that they all wait for, in the order they asked. A callback that
427
- * flushes (a publish does) does not wait for itself.
428
- */
429
- #runAfter(): Promise<void> {
430
- if (this.#inAfter.getStore()) return Promise.resolve();
431
- const callbacks = this.#after.splice(0);
432
- const run = this.#afterRun.then(() =>
433
- this.#inAfter.run(true, async () => {
434
- for (const after of callbacks) await after();
435
- }),
436
- );
437
- this.#afterRun = run.catch(() => {});
438
- return run;
439
- }
440
-
441
- /**
442
- * A batch failed: the first error is every later call's, and the attempt is told once, unless `tell` is
443
- * false: a failure that nobody has run into yet (the session closing as the attempt ends is one) is told
444
- * when the next call meets it, not before, so that the error the attempt ends with is its own.
445
- */
446
- #fail(error: unknown, tell = true): unknown {
447
- this.#failure ??= { error };
448
- this.#after = [];
449
- if (tell) this.#tell();
450
- return this.#failure.error;
117
+ /** Runs the statement and its count together: a statement between them would change what `changes()` counts. */
118
+ override runCounted(sql: string, ...params: SqliteValue[]): Promise<number> {
119
+ return this.transaction((tx) => (tx as Executor).runCounted(sql, ...params));
451
120
  }
452
121
 
453
- #tell() {
454
- if (this.#told || !this.#failure) return;
455
- this.#told = true;
456
- this.#failed?.(this.#failure.error);
457
- }
122
+ /** The session is the caller's to end, after the calls made before. */
123
+ async close() {}
458
124
  }
459
125
 
460
- /** Open pi-durable storage on the session `db`, through `database`, its facade, if given (to set its `onCommit`). */
461
- export function openSqlKvStorage(db: Database, database = new SqlKvDatabase(db)): Promise<SqliteStorage> {
462
- return SqliteStorage.open(database, { prefix: PREFIX });
126
+ /** Opens pi-durable storage on the session `db`. */
127
+ export function openSqlKvStorage(db: Database): Promise<SqliteStorage> {
128
+ return SqliteStorage.open(new SqlKvDatabase(db), { prefix: PREFIX });
463
129
  }
@@ -0,0 +1,78 @@
1
+ // Wraps pi's tool registry (`Harness.open({ registry })`) so that each tool call
2
+ // runs in a `ctx.stoppable` scope and gets the stop signal in
3
+ // `context.abortSignal`. The tool's `execute` runs inside the scope, so a
4
+ // `ctx.suspendable` in it finds the scope through the async context. The
5
+ // Harness reads the registry through this wrapper, so tools of any extension,
6
+ // installed at any time, are covered without patching pi-durable. A wrapper an
7
+ // extension declares (`wrapTool`) wraps the kept tool, so its code before and
8
+ // after the tool runs outside the scope. On a cancellation pi records a
9
+ // stopped call as failed, and the next model request, aborted as it starts,
10
+ // ends the run. A tool that ignores the signal runs to its end.
11
+ import { withAbortSignal } from '@earendil-works/chord/context';
12
+ import type { Extension, RegistryReader, RegistrySnapshot, ToolRegistration } from '@earendil-works/pi-durable';
13
+ import type * as restate from '@restatedev/sessions';
14
+
15
+ /**
16
+ * Wraps `registry` so that each tool keeps the attempt of `ctx` alive while it
17
+ * runs and gets the stop signal in its context:
18
+ *
19
+ * await Harness.open(storage, { models: keptModels(ctx, models), registry: keptTools(ctx, registry) }, context);
20
+ *
21
+ * The registry may keep changing: each snapshot is wrapped as it is read.
22
+ */
23
+ export function keptTools<Tool extends ToolRegistration>(
24
+ ctx: restate.SessionContext,
25
+ registry: RegistryReader<Tool>,
26
+ ): RegistryReader<Tool> {
27
+ // Wrap each object once: the Harness reads snapshots often and may compare their parts by identity.
28
+ const snapshots = new WeakMap<RegistrySnapshot<Tool>, RegistrySnapshot<Tool>>();
29
+ const extensions = new WeakMap<Extension<Tool>, Extension<Tool>>();
30
+ const tools = new WeakMap<Tool, Tool>();
31
+ const keptTool = (tool: Tool): Tool => {
32
+ let kept = tools.get(tool);
33
+ if (kept === undefined) {
34
+ kept = {
35
+ ...tool,
36
+ execute: (args, api, context) =>
37
+ ctx.stoppable((signal) => tool.execute(args, api, withAbortSignal(signal, context))),
38
+ };
39
+ tools.set(tool, kept);
40
+ }
41
+ return kept;
42
+ };
43
+ const keptExtension = (extension: Extension<Tool>): Extension<Tool> => {
44
+ let kept = extensions.get(extension);
45
+ if (kept === undefined) {
46
+ kept = extension.tools === undefined ? extension : { ...extension, tools: extension.tools.map(keptTool) };
47
+ extensions.set(extension, kept);
48
+ }
49
+ return kept;
50
+ };
51
+ const keptSnapshot = (snapshot: RegistrySnapshot<Tool>): RegistrySnapshot<Tool> => {
52
+ let kept = snapshots.get(snapshot);
53
+ if (kept === undefined) {
54
+ const installed = snapshot.installed().map(keptExtension);
55
+ kept = {
56
+ installed: () => installed,
57
+ extension: (name) => {
58
+ const extension = snapshot.extension(name);
59
+ return extension === undefined ? undefined : keptExtension(extension);
60
+ },
61
+ tools: () =>
62
+ snapshot
63
+ .tools()
64
+ .map(({ extension, tool }) => ({ extension: keptExtension(extension), tool: keptTool(tool) })),
65
+ sections: () =>
66
+ snapshot.sections().map(({ extension, section }) => ({ extension: keptExtension(extension), section })),
67
+ tasks: () => snapshot.tasks(),
68
+ task: (name) => snapshot.task(name),
69
+ };
70
+ snapshots.set(snapshot, kept);
71
+ }
72
+ return kept;
73
+ };
74
+ return {
75
+ snapshot: () => keptSnapshot(registry.snapshot()),
76
+ subscribe: (listener) => registry.subscribe(listener),
77
+ };
78
+ }
@@ -1,32 +0,0 @@
1
- import { sdk as restate } from '@restatedev/sessions/internal';
2
- import { type Messages, type MessagesRequest } from '../common.ts';
3
- import { type Notifications, type Resolved, type Signal, type Steer, type Steered, type Waiting, type Watch } from '../companion.ts';
4
- import type { Status, Stopped, Synced, SyncRequest } from '../object.ts';
5
- import type { Definition, Options } from './options.ts';
6
- /**
7
- * An agent of agentlib: a virtual object `name` of the classic Restate SDK,
8
- * with one conversation per key, in its state. `chat` answers a message with
9
- * agentlib's run of the agent, journaled: after a crash, Restate replays it,
10
- * so a model call or a tool call that finished is not made again. It has the
11
- * views of every agent, and its companion, which `serve` serves beside it.
12
- *
13
- * A tool call that needs approval waits for the signal `approval`: `pending`
14
- * lists it, and `signal` approves it (`true`, `"approved"`, `{ "approved":
15
- * true }`) or denies it (anything else).
16
- */
17
- export declare function agent<P extends string, O = string>(definition: Options<O> & Definition<P>): restate.VirtualObjectDefinition<P, {
18
- chat: (ctx: restate.ObjectContext<restate.UntypedState>, input: string) => Promise<string | O>;
19
- steered: (ctx: restate.ObjectContext<restate.UntypedState>, input: Steer) => Promise<void>;
20
- erase: (ctx: restate.ObjectContext<restate.UntypedState>) => Promise<void>;
21
- messages: (ctx: restate.ObjectSharedContext<restate.UntypedState>, input: MessagesRequest | null | undefined) => Promise<Messages>;
22
- status: (ctx: restate.ObjectSharedContext<restate.UntypedState>) => Promise<Status>;
23
- pending: (ctx: restate.ObjectSharedContext<restate.UntypedState>) => Promise<Waiting[]>;
24
- signal: (ctx: restate.ObjectSharedContext<restate.UntypedState>, input: Signal) => Promise<Resolved>;
25
- stop: (ctx: restate.ObjectSharedContext<restate.UntypedState>) => Promise<Stopped>;
26
- clear: (ctx: restate.ObjectSharedContext<restate.UntypedState>) => Promise<Stopped>;
27
- steer: (ctx: restate.ObjectSharedContext<restate.UntypedState>, input: string) => Promise<Steered>;
28
- notifications: (ctx: restate.ObjectSharedContext<restate.UntypedState>) => Promise<Notifications>;
29
- watch: (ctx: restate.ObjectSharedContext<restate.UntypedState>, input: Watch) => Promise<Notifications>;
30
- sync: (ctx: restate.ObjectSharedContext<restate.UntypedState>, input: SyncRequest | null | undefined) => Promise<Synced>;
31
- }>;
32
- //# sourceMappingURL=agent.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../../src/agentlib/agent.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,GAAG,IAAI,OAAO,EAAE,MAAM,+BAA+B,CAAC;AAC/D,OAAO,EAAE,KAAK,QAAQ,EAAE,KAAK,eAAe,EAAgB,MAAM,cAAc,CAAC;AACjF,OAAO,EACL,KAAK,aAAa,EAClB,KAAK,QAAQ,EACb,KAAK,MAAM,EACX,KAAK,KAAK,EACV,KAAK,OAAO,EACZ,KAAK,OAAO,EACZ,KAAK,KAAK,EAEX,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEzE,OAAO,KAAK,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAkCxD;;;;;;;;;;GAUG;AACH,wBAAgB,KAAK,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,GAAG,MAAM,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC;;;;;;;;;;;;;;GAgCzF"}