@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,202 +0,0 @@
1
- # DeepSeek Harness
2
-
3
- The [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness)
4
- (`@deepseek-ai/dsh-*`) is an agent harness built from plugins on
5
- [cordis](https://www.npmjs.com/package/@deepseek-ai/cordis): an agent loop, a
6
- model service, a tool registry, and an event-sourced session that is the
7
- source of truth for everything the agent did. Here the session is in the
8
- agent's SQL database ([SQL in Restate virtual objects](../../../sessions/README.md)),
9
- and is the object's key. The integration pins the harness's `next` release
10
- line, 0.2.1-rc.2, exactly: its packages are release candidates that require
11
- each other's exact versions.
12
-
13
- ## Use
14
-
15
- ```ts
16
- import { serve } from '@restatedev/agents';
17
- import * as deepseek from '@restatedev/agents/deepseek';
18
- import { weather } from './weather.ts';
19
-
20
- const assistant = deepseek.agent({ name: 'assistant', system: 'Answer briefly.', tools: [weather] });
21
- await serve(assistant);
22
- ```
23
-
24
- | Option | What |
25
- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
26
- | `model` | `provider/model-id`; or else `MODEL`, or else `deepseek/deepseek-flash` (see below) |
27
- | `system` | The system prompt |
28
- | `tools` | `tool()`s and Restate's tools of `@restatedev/agents`, or the harness's `defineTool`s |
29
- | `approval` | The tool calls that wait for a person's approval before they run: the names of their tools, or a function of a call (see [Approvals](#approvals)) |
30
- | `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)) |
31
- | `compaction` | When the model's input is condensed: `@deepseek-ai/dsh-compaction-basic`'s settings, such as `thresholdRatio` (by default 0.8 of the model's context window) |
32
-
33
- ## Models
34
-
35
- DeepSeek's models go to DeepSeek, with `DEEPSEEK_API_KEY`. Any other model
36
- pi-ai knows goes through the harness's pi-ai adapter
37
- (`@deepseek-ai/dsh-llm-pi-ai`), with its provider's usual key: nothing else
38
- to set up.
39
-
40
- ```ts
41
- deepseek.agent({ name: 'assistant' }); // deepseek/deepseek-flash, with DEEPSEEK_API_KEY
42
- deepseek.agent({ name: 'assistant', model: 'openai/gpt-6-sol' }); // with OPENAI_API_KEY
43
- deepseek.agent({ name: 'assistant', model: 'anthropic/claude-sonnet-5-5' }); // with ANTHROPIC_API_KEY
44
- ```
45
-
46
- A provider or model pi-ai does not know fails when the agent is defined; a
47
- missing or wrong key fails the invocation with a terminal error (424).
48
-
49
- For a session object of your own, `deepseek.chat(options)` is the handler and
50
- `deepseek.messages()` the view; `options` may be a function of the
51
- invocation's context (each user's system prompt, say). `deepseek.prompt(ctx,
52
- text, options)` answers a prompt in a handler of your own, once, however
53
- often the handler runs; each prompt of an invocation is a prompt of its own.
54
-
55
- ## Approvals
56
-
57
- The harness can ask a person before a tool call runs. `approval` names the
58
- calls that ask: by their tools, or as a function of a call (its tool's
59
- `name`, and its `args`):
60
-
61
- ```ts
62
- deepseek.agent({ name: 'bank', tools: [transfer, audit], approval: ['transfer'] });
63
- deepseek.agent({
64
- name: 'bank',
65
- tools: [transfer, audit],
66
- approval: ({ name, args }) => name === 'transfer' && (args as { amount: number }).amount > 100,
67
- });
68
- ```
69
-
70
- Such a call waits, before it runs, for the signal `approval`
71
- (`deepseek.APPROVAL`) to the agent, as a `signal()` tool waits
72
- ([Signals](../../README.md#signals)): without holding a process, for as
73
- long as it takes. `pending` lists the wait, with the call's tool and
74
- arguments, and `signal` answers it, by its id, or as the oldest wait for
75
- `approval`:
76
-
77
- ```sh
78
- curl localhost:8080/bank/alice/pending
79
- # [{"id": "inv_1f…:call_01", "name": "approval", "input": {"tool": "transfer", "args": {"from": 1, "to": 2, "amount": 500}}, "since": "…"}]
80
- curl localhost:8080/bank/alice/signal --json '{"id": "inv_1f…:call_01", "value": "approved"}'
81
- curl localhost:8080/bank/alice/signal --json '{"name": "approval", "value": "no"}'
82
- ```
83
-
84
- `true`, `{"approved": true}`, or a text such as `approved`, `yes` or `ok`
85
- approves the call, once; anything else denies it, and the tool never runs.
86
- The model gets the harness's denial (`Error: the user rejected tool
87
- "transfer"`): the text of a denial does not reach it.
88
-
89
- It is the harness's own approval: a policy of its tool runtime
90
- (`tools/pre-execute`) asks, and its approval service
91
- (`@deepseek-ai/dsh-user-approval`, mounted with `approval`) puts the
92
- question to its answerer, the wait. The log keeps each question and its
93
- decision (`approval/asked`, `approval/decided`), and the model is told, in
94
- the harness's runtime context, that a call may ask for an approval.
95
-
96
- A crash while a call waits, or a suspension (a wait that outlasts
97
- Restate's inactivity timeout restarts the handler), asks the model again
98
- ([below](#through-crashes)): it makes the call again under a new id, and
99
- the call, with the same arguments, joins the wait. The person is asked
100
- once, and the tool runs once, after the decision. A call with other
101
- arguments, such as a transfer retried with `retryOf` after a crash left its
102
- outcome unknown, is a call of its own, and asks anew. A turn stopped while
103
- the call waits, or while the approved tool runs, ends the call as
104
- cancelled: its approval is not its outcome.
105
-
106
- ## Through crashes
107
-
108
- The persistence ([`persistence.ts`](persistence.ts),
109
- `SqlSessionPersistence`) keeps each session's header, and its event log, one
110
- row per event; a write stores what was appended before it in one SQL
111
- transaction. The harness's flushes, its durability barrier, are soft here:
112
- the adapter does the writing, right before each effect (below). The handler is not replayed: a
113
- retried attempt boots the harness again and resumes the session from the
114
- stored log. The harness does not resume an interrupted turn: resuming closes
115
- it, and leaves the model to decide what to do about it. So:
116
-
117
- - **A tool runs only once its call is stored.** The harness's checkpoint
118
- policy flushes the session before each model request, each tool body and
119
- each step, but those flushes store nothing once the adapter's own barriers
120
- are in place ([`barriers.ts`](barriers.ts)). The adapter stores everything
121
- queued right before each model request (the innermost listener of the
122
- harness's `llm/stream`, checked to be the last on each request) and each
123
- tool body (the wrapper of each tool it registers), before each Restate
124
- effect and publish, and when the run ends, and it does not start the
125
- request or the body if the write fails. So a flush at a step and the one
126
- before its request are one commit: a turn of 4 model requests and 3 tool
127
- calls commits the ask, one write before each effect, the final flush and
128
- the answer. If a barrier cannot be installed, every flush stays a write.
129
- A crash loses what was queued since the last write, which nothing has
130
- acted on; the tool's result of a body that ran is then unknown to the retry,
131
- as below. The wait for an approval is the exception: it opens with the
132
- tool call not stored, as before.
133
- - **A tool call stored without a result has an unknown outcome.** Resuming
134
- gives each such call an error result that says so, and tells the model to
135
- retry only an idempotent operation; the handler then asks the agent to
136
- continue. A tool that must not run twice needs a way for a retry to name
137
- the call it retries (the bank agent's `transfer` takes `retryOf`). Restate's own tools
138
- (`call`, `send`, `workflow`, `subagent`, `signal`) need none: made again
139
- with the same input, the call is the one the cut-off call made, which
140
- matters for a long one, such as a wait for an approval, since a suspension
141
- (after Restate's inactivity timeout) restarts the handler too.
142
- - **A tool's error fails the attempt**, and Restate retries it; a
143
- `restate.TerminalError` of a `@restatedev/agents` tool is its answer to the
144
- model. The failed attempt stores nothing more, so its retry finds the call
145
- without a result, as above.
146
- - **A failed turn fails the attempt**: a model request that failed, or a
147
- checkpoint that could not store the log, and Restate retries.
148
- - **A message is answered once per invocation** (`answerOnce`): a retried
149
- attempt continues its own prompt (`CONTINUE`, a step of its turn), and
150
- returns the answer once it has one. A turn a killed invocation left is
151
- closed (`ended`) in the agent's conversation of turns, never continued,
152
- and the harness's next turn is told how it ended.
153
-
154
- The harness keeps its own event log, and its model's input is the harness's;
155
- each flush of the log copies the turn's new messages (the model's replies,
156
- the tools' results) into the agent's conversation of turns, in the same
157
- transaction: what `messages` shows
158
- ([docs/conversation.md](../../docs/conversation.md)). A flush that copied a
159
- reply with tool calls, or tools' results, is published once it is stored,
160
- in a `chat` turn (a `prompt()` in a handler of your own publishes nothing),
161
- and nothing else is: a tool call's start publishes nothing. The tools of a
162
- reply run one after another, and each result is written with the next call,
163
- before its tool runs (the adapter's barrier): one commit, and one
164
- publish, per tool call. The harness's input
165
- stays within the model's context window: as it nears the window (or
166
- overflows it), the harness condenses the oldest history into a summary, one
167
- more model request, after trimming tool results that are too long
168
- (`@deepseek-ai/dsh-compaction-basic`, with the token meter and the tool
169
- result pruner). The log keeps every event, and `messages` every message; a
170
- crash while condensing is condensed again by the retry.
171
-
172
- ## Run
173
-
174
- ```sh
175
- cd packages/examples && DEEPSEEK_API_KEY=… node basic/deepseek.ts
176
- cd packages/examples && MODEL=openai/gpt-6-sol OPENAI_API_KEY=… node basic/deepseek.ts # on GPT
177
- ```
178
-
179
- With a Restate server, and the agent registered with it: see
180
- [Run an example](../../../examples/README.md#run-an-example).
181
-
182
- ## Tests
183
-
184
- The tests run on a scripted model, [`test/fakes/deepseek.ts`](../../test/fakes/deepseek.ts),
185
- which makes a fresh tool call id for every call, as a model does
186
- (`pnpm --filter @restatedev/agents test deepseek`, from the repository root):
187
-
188
- - [`test/deepseek.test.ts`](../../test/deepseek.test.ts):
189
- each point above, with crashes that stop an attempt in a tool call, or
190
- at any of its state requests; approvals (approved, denied, waited for
191
- through a crash, at any state request, and cancelled); and
192
- `messages`. Without the checkpoint policy four of its tests fail, and with
193
- a transfer tool that ignores `retryOf` three do.
194
- - [`test/deepseek-commits.test.ts`](../../test/deepseek-commits.test.ts) and
195
- [`test/deepseek-barriers.test.ts`](../../test/deepseek-barriers.test.ts):
196
- the commits of a turn, what is stored before each effect, a follower's
197
- publishes, a turn that condenses, a crash before a result is written, and
198
- the barriers (and a turn without them).
199
- - [`test/deepseek.ts`](../../test/deepseek.ts): the
200
- bank agent, whose `transfer` uses `retryOf`, or its own call id, as the
201
- transfer id, through crashes in [the crash test](../../../e2e/crash.ts)
202
- (`pnpm --filter e2e crash`): every message moves money exactly once.
@@ -1,63 +0,0 @@
1
- // The adapter's own barriers before the harness's effects. The session
2
- // checkpoint policy flushes before each model request and each tool body, but
3
- // those flushes are soft (persistence.ts): what the adapter stores, it stores
4
- // itself, right before the effect starts, so that nothing the harness or a
5
- // plugin does can come between the write and the effect.
6
- //
7
- // A tool's body is wrapped where the adapter registers the tool (`tracked` of
8
- // index.ts: its `execute` is the last thing before the body, for a nested call
9
- // too). The model's request has no such place, as the model adapter is a
10
- // plugin's: the barrier is the innermost `llm/stream` listener, run right
11
- // before the adapter's stream starts. Listeners run outermost first, and the
12
- // one registered last is the innermost: so each request checks that the
13
- // barrier is still the last registered, and fails the request if a listener
14
- // was added after it.
15
- import type { Context } from '@deepseek-ai/cordis';
16
- import type { SessionId } from '@deepseek-ai/dsh-session';
17
- import type { StreamChunk } from '@deepseek-ai/dsh-llm';
18
- import type { SqlSessionPersistence } from './persistence.ts';
19
-
20
- /** What the event service keeps of a listener (cordis's `Hook`): the barrier's is marked. */
21
- interface Hook {
22
- barrier?: symbol;
23
- }
24
-
25
- /** The mark of the barrier's listener. */
26
- const BARRIER = Symbol('the adapter barrier before a model request');
27
-
28
- /** The `llm/stream` listeners, in the order they run: outermost first, `undefined` if the harness does not keep them so. */
29
- const listeners = (harness: Context): Hook[] | undefined => {
30
- const hooks = Reflect.get(harness.events, '_hooks') as Record<string, unknown> | undefined;
31
- const found = hooks?.['llm/stream'];
32
- return Array.isArray(found) ? (found as Hook[]) : undefined;
33
- };
34
-
35
- /** Whether the barrier is the innermost `llm/stream` listener. */
36
- const innermost = (harness: Context) => listeners(harness)?.at(-1)?.barrier === BARRIER;
37
-
38
- /**
39
- * Store the events of each model request's session right before its stream
40
- * starts, as the innermost `llm/stream` listener; a request is not made if
41
- * they are not stored, nor if a listener came after the barrier. Returns
42
- * whether the barrier is installed, and innermost: if not (the hooks are not
43
- * where they were), it is removed and the harness's flushes must stay writes.
44
- */
45
- export function guardModelRequests(harness: Context, persistence: SqlSessionPersistence): boolean {
46
- const dispose = harness.on(
47
- 'llm/stream',
48
- (options: { sessionId?: SessionId }, next: () => AsyncIterable<StreamChunk>): AsyncIterable<StreamChunk> => {
49
- const { sessionId } = options;
50
- if (sessionId === undefined) return next();
51
- return (async function* () {
52
- if (!innermost(harness)) throw new Error('deepseek: a listener of llm/stream runs after the barrier');
53
- await persistence.writeNow(sessionId);
54
- yield* next();
55
- })();
56
- },
57
- { barrier: BARRIER } as never,
58
- );
59
- if (innermost(harness)) return true;
60
- // Not where it must be: left in, it would fail every request, not leave the flushes writes.
61
- dispose();
62
- return false;
63
- }