@restatedev/agents 0.10.2 → 0.11.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 (77) hide show
  1. package/README.md +11 -1
  2. package/dist/agentlib/agent.js +3 -1
  3. package/dist/agentlib/agent.js.map +1 -1
  4. package/dist/agentlib/model.d.ts +3 -1
  5. package/dist/agentlib/model.d.ts.map +1 -1
  6. package/dist/agentlib/model.js +13 -4
  7. package/dist/agentlib/model.js.map +1 -1
  8. package/dist/agentlib/tools.js +2 -0
  9. package/dist/agentlib/tools.js.map +1 -1
  10. package/dist/calls.d.ts +14 -8
  11. package/dist/calls.d.ts.map +1 -1
  12. package/dist/calls.js +24 -11
  13. package/dist/calls.js.map +1 -1
  14. package/dist/claude/index.d.ts.map +1 -1
  15. package/dist/claude/index.js +33 -4
  16. package/dist/claude/index.js.map +1 -1
  17. package/dist/common.d.ts +12 -0
  18. package/dist/common.d.ts.map +1 -1
  19. package/dist/common.js +30 -0
  20. package/dist/common.js.map +1 -1
  21. package/dist/deepseek/index.d.ts.map +1 -1
  22. package/dist/deepseek/index.js +7 -3
  23. package/dist/deepseek/index.js.map +1 -1
  24. package/dist/langgraph/graph.d.ts.map +1 -1
  25. package/dist/langgraph/graph.js +8 -0
  26. package/dist/langgraph/graph.js.map +1 -1
  27. package/dist/langgraph/index.d.ts.map +1 -1
  28. package/dist/langgraph/index.js +2 -2
  29. package/dist/langgraph/index.js.map +1 -1
  30. package/dist/langgraph/keepalive.d.ts +16 -0
  31. package/dist/langgraph/keepalive.d.ts.map +1 -0
  32. package/dist/langgraph/keepalive.js +51 -0
  33. package/dist/langgraph/keepalive.js.map +1 -0
  34. package/dist/opencode/index.d.ts.map +1 -1
  35. package/dist/opencode/index.js +108 -24
  36. package/dist/opencode/index.js.map +1 -1
  37. package/dist/pi/commits.d.ts +6 -0
  38. package/dist/pi/commits.d.ts.map +1 -0
  39. package/dist/pi/commits.js +3 -0
  40. package/dist/pi/commits.js.map +1 -0
  41. package/dist/pi/index.d.ts +14 -1
  42. package/dist/pi/index.d.ts.map +1 -1
  43. package/dist/pi/index.js +91 -9
  44. package/dist/pi/index.js.map +1 -1
  45. package/dist/pi/keepalive.d.ts +21 -0
  46. package/dist/pi/keepalive.d.ts.map +1 -0
  47. package/dist/pi/keepalive.js +98 -0
  48. package/dist/pi/keepalive.js.map +1 -0
  49. package/dist/pi/storage.d.ts +62 -3
  50. package/dist/pi/storage.d.ts.map +1 -1
  51. package/dist/pi/storage.js +355 -12
  52. package/dist/pi/storage.js.map +1 -1
  53. package/dist/tools.d.ts +9 -0
  54. package/dist/tools.d.ts.map +1 -1
  55. package/dist/tools.js +9 -1
  56. package/dist/tools.js.map +1 -1
  57. package/package.json +5 -5
  58. package/src/agentlib/README.md +5 -5
  59. package/src/agentlib/agent.ts +3 -1
  60. package/src/agentlib/model.ts +10 -4
  61. package/src/agentlib/tools.ts +2 -0
  62. package/src/calls.ts +25 -11
  63. package/src/claude/index.ts +36 -6
  64. package/src/common.ts +32 -0
  65. package/src/deepseek/index.ts +7 -1
  66. package/src/langgraph/README.md +10 -0
  67. package/src/langgraph/graph.ts +7 -0
  68. package/src/langgraph/index.ts +3 -3
  69. package/src/langgraph/keepalive.ts +58 -0
  70. package/src/opencode/README.md +15 -0
  71. package/src/opencode/index.ts +104 -22
  72. package/src/pi/README.md +64 -15
  73. package/src/pi/commits.ts +7 -0
  74. package/src/pi/index.ts +116 -7
  75. package/src/pi/keepalive.ts +121 -0
  76. package/src/pi/storage.ts +382 -10
  77. package/src/tools.ts +12 -1
@@ -1,5 +1,6 @@
1
1
  // The agentlib agent's model: a model by name (`openai/…`, `anthropic/…`) or
2
2
  // one of agentlib's, and how its provider's refusals end a turn.
3
+ import { isContextOverflow } from '@restatedev/agentlib';
3
4
  import type { CompactionPolicy, Model, ModelRequest } from '@restatedev/agentlib';
4
5
  import type { aiModel } from '@restatedev/agentlib/provider';
5
6
  import { sdk as restate } from '@restatedev/sessions/internal';
@@ -74,10 +75,13 @@ async function loadLanguageModel(
74
75
  * does not change: a request answered with a 4xx (a wrong API key, an unknown
75
76
  * model, a rejected request), or a missing API key. Only a plain
76
77
  * `TerminalError` qualifies: agentlib's own errors (an overflow, a protocol
77
- * error) and cancellations are subclasses.
78
+ * error) and cancellations are subclasses. An overflow is never one: it is a
79
+ * subclass only on the first attempt, and replay restores it as a plain
80
+ * `TerminalError` with code 413, which agentlib still has to see to compact.
78
81
  */
79
82
  export function refused(error: unknown): error is restate.TerminalError {
80
83
  if (!(error instanceof restate.TerminalError)) return false;
84
+ if (isContextOverflow(error)) return false;
81
85
  if (error.constructor !== restate.TerminalError) return false;
82
86
  const clientError = error.code >= 400 && error.code < 500;
83
87
  return clientError || /API key/i.test(error.message);
@@ -119,9 +123,11 @@ export function withoutBounds(schema: unknown): unknown {
119
123
 
120
124
  /**
121
125
  * Wraps an Anthropic `model` so that it gets its tools' schemas without
122
- * numeric bounds. agentlib 0.1.0 asks for strict tools where a schema allows
123
- * it, and Anthropic refuses strict tools with bounded numbers (such as
124
- * agentlib's own `read_tool_result`). The tools still check their input.
126
+ * numeric bounds. agentlib 0.1.0 asked for strict tools where a schema
127
+ * allowed it, and Anthropic refuses strict tools with bounded numbers (such as
128
+ * agentlib's own `read_tool_result`). 0.2.0 leaves strict mode to the AI SDK's
129
+ * defaults; the bounds still go, which costs nothing: the tools still check
130
+ * their input.
125
131
  */
126
132
  function withoutSchemaBounds(model: Model): Model {
127
133
  return (request) => {
@@ -349,5 +349,7 @@ function sessionOf(ctx: restate.ObjectContext): SessionContext {
349
349
  get cancel(): never {
350
350
  return missing('ctx.cancel', CALLS_INSTEAD);
351
351
  },
352
+ // An agentlib agent runs on the SDK's journaled context, which has no `working`: the work just runs.
353
+ working: <T>(fn: () => T | Promise<T>) => (async () => fn())(),
352
354
  });
353
355
  }
package/src/calls.ts CHANGED
@@ -69,24 +69,38 @@ export const SCHEMA = new Schema('restate-agents.calls', [
69
69
  /** What the calls need of a handler's context. */
70
70
  type CallsContext = Pick<restate.SessionContext, 'db' | 'request'>;
71
71
 
72
- /** What writes the rows the conversation of the attempt's turn holds back, by its context. */
73
- const HELD = new ScopeKey<() => Promise<void>>('the held rows of the conversation');
72
+ /** What writes what is held back before anything visible, by holder: the conversation's rows, pi's batch of commits. */
73
+ const HELD = new ScopeKey<Map<string, () => Promise<void>>>('what the attempt holds back');
74
74
 
75
75
  /**
76
- * Have {@link flushHeld} write, with `flush`, the rows that the conversation
77
- * of the attempt's turn holds back (`Conversation.hold`): `answerOnce` does.
76
+ * Have {@link flushHeld} write, with `flush`, what a holder keeps back: by
77
+ * default the rows that the conversation of the attempt's turn holds back
78
+ * (`Conversation.hold`), which `answerOnce` sets. A holder of another `slot`
79
+ * (pi's storage, which holds its commits until an effect starts) coexists
80
+ * with it; one of the same slot replaces it, and without a `flush` the slot
81
+ * is released.
78
82
  */
79
- export const holding = (ctx: restate.SessionContext, flush: () => Promise<void>) => HELD.set(ctx, flush);
83
+ export const holding = (
84
+ ctx: restate.SessionContext,
85
+ flush: (() => Promise<void>) | undefined,
86
+ slot = 'conversation',
87
+ ) => {
88
+ const held = HELD.of(ctx, () => new Map());
89
+ if (flush) held.set(slot, flush);
90
+ else held.delete(slot);
91
+ };
80
92
 
81
93
  /**
82
- * Write the rows that the conversation of the attempt's turn holds back, if
83
- * any (see `Conversation.hold`). Call it before what another party sees, or
84
- * what outlives the attempt: a publish, a Restate call, send or wait. A held
85
- * row is lost in a crash, and the retried attempt makes it again; what was
86
- * seen or called must not depend on it.
94
+ * Write what the holders keep back, in the order they were set, one after
95
+ * the other: the rows that the conversation of the attempt's turn holds back,
96
+ * if any (see `Conversation.hold`), and pi's batched commits. Call it before
97
+ * what another party sees, or what outlives the attempt: a publish, a
98
+ * Restate call, send or wait. What is held is lost in a crash, and the
99
+ * retried attempt makes it again; what was seen or called must not depend
100
+ * on it.
87
101
  */
88
102
  export async function flushHeld(ctx: restate.SessionContext) {
89
- await HELD.get(ctx)?.();
103
+ for (const flush of HELD.get(ctx)?.values() ?? []) await flush();
90
104
  }
91
105
 
92
106
  /**
@@ -43,6 +43,7 @@ import {
43
43
  type Configure,
44
44
  configured,
45
45
  fromTool,
46
+ keepAlive,
46
47
  modelIdOf,
47
48
  modelOf,
48
49
  RETURNED_UNRECORDED,
@@ -245,7 +246,7 @@ const runOf =
245
246
  await step();
246
247
  }
247
248
  let paused = false;
248
- for await (const message of runner) {
249
+ for await (const message of requests(ctx, runner)) {
249
250
  // A reply that cannot go on ends the turn, whose tool calls do not run.
250
251
  const stopped = stoppedShort(message, maxTokens);
251
252
  if (stopped) throw new restate.TerminalError(stopped);
@@ -274,6 +275,33 @@ const runOf =
274
275
  }
275
276
  };
276
277
 
278
+ /**
279
+ * `runner`'s replies, each model request kept alive: from the moment the
280
+ * loop asks for the next reply until it arrives (the runner does not stream,
281
+ * so the reply is the whole response), however it ends: an error, or the turn
282
+ * stopped. The tools run outside it: the loop runs them (`generateToolResponse`)
283
+ * before it asks again, and the runner then finds their results done.
284
+ */
285
+ async function* requests<T>(ctx: restate.SessionContext, runner: AsyncIterable<T>): AsyncGenerator<T> {
286
+ const replies = runner[Symbol.asyncIterator]();
287
+ try {
288
+ for (;;) {
289
+ const release = keepAlive(ctx);
290
+ let next: IteratorResult<T>;
291
+ try {
292
+ next = await replies.next();
293
+ } finally {
294
+ release();
295
+ }
296
+ if (next.done) return;
297
+ yield next.value;
298
+ }
299
+ } finally {
300
+ // Ends the runner's loop (its span and its stream) when the caller leaves it early, as a final reply does.
301
+ await replies.return?.();
302
+ }
303
+ }
304
+
277
305
  /**
278
306
  * Why the model's `message` stopped short of a reply to go on from: cut off
279
307
  * at `maxTokens` (its text, or a tool call's input, unfinished), declined, or
@@ -425,11 +453,13 @@ export const summarizer =
425
453
  (options: Options = {}): Summarize =>
426
454
  async (ctx, request) => {
427
455
  const { client, model, maxTokens } = agentOf(ctx, { ...options, tools: [] });
428
- const message = await client.beta.messages.create({
429
- model,
430
- max_tokens: maxTokens,
431
- messages: [{ role: 'user', content: request }],
432
- });
456
+ const message = await ctx.working(() =>
457
+ client.beta.messages.create({
458
+ model,
459
+ max_tokens: maxTokens,
460
+ messages: [{ role: 'user', content: request }],
461
+ }),
462
+ );
433
463
  return textOf(message.content);
434
464
  };
435
465
 
package/src/common.ts CHANGED
@@ -259,6 +259,38 @@ export class AttemptEnded extends Error {
259
259
  */
260
260
  export const stopSignalOf = (ctx: restate.SessionContext): AbortSignal | undefined => TURN.get(ctx);
261
261
 
262
+ // --- Keeping an attempt alive
263
+ //
264
+ // A model's request runs in `ctx.working`, so that Restate does not shut its
265
+ // attempt down while it streams: the request would be made again, from the
266
+ // start of the turn. Nothing else of a turn does, unless a tool says so
267
+ // (`keepalive`): a wait on Restate (a call, a signal) suspends.
268
+
269
+ /**
270
+ * Open a `ctx.working` scope until the function it returns is called (once
271
+ * or more): for a framework's hooks that bracket a model's request without
272
+ * wrapping it. A scope never released keeps the attempt alive to its end.
273
+ */
274
+ export function keepAlive(ctx: restate.SessionContext): () => void {
275
+ const released = Promise.withResolvers<void>();
276
+ void ctx.working(() => released.promise);
277
+ return () => released.resolve();
278
+ }
279
+
280
+ /**
281
+ * `source`, kept alive while it is iterated: from the first pull to its end,
282
+ * however it ends (done, thrown, or returned early, as a `break` does). A
283
+ * model's streamed response, say.
284
+ */
285
+ export async function* keptAlive<T>(ctx: restate.SessionContext, source: AsyncIterable<T>): AsyncGenerator<T> {
286
+ const release = keepAlive(ctx);
287
+ try {
288
+ yield* source;
289
+ } finally {
290
+ release();
291
+ }
292
+ }
293
+
262
294
  /**
263
295
  * An agent's settings: whether it runs in the background (`background:
264
296
  * true`: no one follows it as it works), and, for an agent on the
@@ -69,6 +69,7 @@ import {
69
69
  configured,
70
70
  fromTool,
71
71
  inboxOf,
72
+ keptAlive,
72
73
  ModelError,
73
74
  modelOf,
74
75
  providerOf,
@@ -138,6 +139,7 @@ function routeOf(model: string): Route {
138
139
  * approval runs (see {@link approving}).
139
140
  */
140
141
  async function boot(
142
+ ctx: restate.SessionContext,
141
143
  db: restate.Database,
142
144
  route: Route,
143
145
  system?: string,
@@ -145,6 +147,10 @@ async function boot(
145
147
  approvals = false,
146
148
  ): Promise<Context> {
147
149
  const harness = new Context();
150
+ // Every model request (a turn's, a compaction's) runs kept alive, from its
151
+ // first pull to the stream's end however it ends. Tools and the approval's
152
+ // wait are not in it.
153
+ harness.on('llm/stream', (_options, next) => keptAlive(ctx, next()));
148
154
  await harness.plugin(LlmRuntime);
149
155
  await harness.plugin(SessionStore);
150
156
  await harness.plugin(SystemPrompt, system ? { personaPrefix: system } : {});
@@ -491,7 +497,7 @@ const runOf =
491
497
  async (conversation) => {
492
498
  const turn = conversation.turn;
493
499
  const route = routeOf(modelOf(named, DEEPSEEK_MODEL));
494
- const harness = await boot(ctx.db, route, system, compaction, approval !== undefined);
500
+ const harness = await boot(ctx, ctx.db, route, system, compaction, approval !== undefined);
495
501
  const persistence = harness.sessionPersistence as SqlSessionPersistence;
496
502
  // A tool's error fails the attempt, which Restate retries: the harness
497
503
  // stores nothing more, so the retry finds the tool's call without a result.
@@ -106,6 +106,16 @@ graph })` gives it, and a handler of your own passes it as the run context
106
106
  `SqlCheckpointSaver(ctx.db)`). A node refuses to run without it, a
107
107
  checkpointer, or `durability: 'sync'`.
108
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
+
109
119
  ## Through crashes
110
120
 
111
121
  The built-in agent keeps no checkpoints: its conversation is the object's
@@ -66,6 +66,7 @@ import { companionHere } from '../companion.ts';
66
66
  import { SqlCheckpointSaver } from './checkpointer.ts';
67
67
  import { running } from './context.ts';
68
68
  import { terminalOf } from './errors.ts';
69
+ import { KeepModelsAlive } from './keepalive.ts';
69
70
 
70
71
  /** A graph of your own: a `StateGraph` (not compiled), or a compiled one such as LangChain's `createAgent` makes. */
71
72
  export type AnyGraph =
@@ -357,12 +358,15 @@ async function runGraph(
357
358
  // version its structured answer had before it.
358
359
  const saver = new SqlCheckpointSaver(ctx.db, { metadata: { [PROMPT]: promptId, [STRUCTURED_BEFORE]: before } });
359
360
  const run = compiled(graph, saver);
361
+ // Each request of a model is kept alive, wherever the graph makes it (see keepalive.ts).
362
+ const kept = new KeepModelsAlive(ctx);
360
363
  const options = {
361
364
  ...THREAD,
362
365
  context,
363
366
  durability: 'sync',
364
367
  streamMode: 'values',
365
368
  signal: stopSignalOf(ctx),
369
+ callbacks: [kept],
366
370
  };
367
371
  if (asked && snapshot.next.length === 0) {
368
372
  // The run had finished, but its answer was not stored: that is the answer, rather than run again.
@@ -394,6 +398,9 @@ async function runGraph(
394
398
  // No refusal, whatever its name: a graph's models, tools and nodes are all its own.
395
399
  fromTool(ctx, error);
396
400
  throw error;
401
+ } finally {
402
+ // A request that never reported its end (a stopped run's) must not keep the attempt alive while it waits.
403
+ kept.releaseAll();
397
404
  }
398
405
  // The run stops at its interrupts: it goes on with the signals that answer them.
399
406
  const paused = await storedState(run);
@@ -254,7 +254,7 @@ function toolLoop(
254
254
  .addNode('model', async ({ messages }) => {
255
255
  const steered = await takeSteers(ctx, conversation);
256
256
  const asked = [...messages, ...steered];
257
- const reply = await withTools.invoke(system ? [new SystemMessage(system), ...asked] : asked);
257
+ const reply = await ctx.working(() => withTools.invoke(system ? [new SystemMessage(system), ...asked] : asked));
258
258
  await turn.appendReply([reply]);
259
259
  return { messages: [...steered, reply] };
260
260
  })
@@ -472,8 +472,8 @@ export const messages = () => conversationView(items);
472
472
  */
473
473
  export const summarizer =
474
474
  (model?: Options['model']): Summarize =>
475
- async (_ctx, request) =>
476
- (await (await modelOfOptions(model)).invoke([new HumanMessage(request)])).text;
475
+ async (ctx, request) =>
476
+ ctx.working(async () => (await (await modelOfOptions(model)).invoke([new HumanMessage(request)])).text);
477
477
 
478
478
  /** An agent: a virtual object `name`, one per key, whose `chat` handler is {@link chat}, and `messages` {@link messages}. */
479
479
  export const agent = <P extends string, O extends z.ZodObject | undefined = undefined>({
@@ -0,0 +1,58 @@
1
+ // A graph of your own calls its models as it likes: its nodes, or LangChain's
2
+ // `createAgent`. The attempt must be kept alive (`ctx.working`) while a model
3
+ // serves a request, and a request is what LangChain's callbacks bracket: a
4
+ // chat model's start opens a scope, its end or error closes it.
5
+ //
6
+ // The handler awaits its handlers (`awaitHandlers`): LangChain awaits the
7
+ // start callback before it sends the request, so the scope is open by then.
8
+ // Not every request ends in a callback: a stream its consumer abandons, or a
9
+ // run cut off by a stop, calls neither the end nor the error. The run
10
+ // releases what is left (`releaseAll`) when its stream ends, however it ends.
11
+ import { BaseCallbackHandler } from '@langchain/core/callbacks/base';
12
+ import type * as restate from '@restatedev/sessions';
13
+ import { keepAlive } from '../common.ts';
14
+
15
+ /** A callback handler that keeps the attempt of `ctx` alive while a model's request of the run is out. */
16
+ export class KeepModelsAlive extends BaseCallbackHandler {
17
+ name = 'restate-keep-models-alive';
18
+ // Awaited, so that the scope is open before LangChain sends the request.
19
+ override awaitHandlers = true;
20
+ readonly #ctx: restate.SessionContext;
21
+ readonly #open = new Map<string, () => void>();
22
+
23
+ constructor(ctx: restate.SessionContext) {
24
+ super();
25
+ this.#ctx = ctx;
26
+ }
27
+
28
+ #begin(runId: string) {
29
+ if (!this.#open.has(runId)) this.#open.set(runId, keepAlive(this.#ctx));
30
+ }
31
+
32
+ #end(runId: string) {
33
+ this.#open.get(runId)?.();
34
+ this.#open.delete(runId);
35
+ }
36
+
37
+ override handleChatModelStart(_llm: unknown, _messages: unknown, runId: string) {
38
+ this.#begin(runId);
39
+ }
40
+
41
+ override handleLLMStart(_llm: unknown, _prompts: unknown, runId: string) {
42
+ this.#begin(runId);
43
+ }
44
+
45
+ override handleLLMEnd(_output: unknown, runId: string) {
46
+ this.#end(runId);
47
+ }
48
+
49
+ override handleLLMError(_error: unknown, runId: string) {
50
+ this.#end(runId);
51
+ }
52
+
53
+ /** Close the scopes of requests that never reported their end: a run's, once its stream has ended. */
54
+ releaseAll() {
55
+ for (const release of this.#open.values()) release();
56
+ this.#open.clear();
57
+ }
58
+ }
@@ -183,6 +183,21 @@ then the file) has each ask answered by the first's answer. OpenCode's hook
183
183
  does not tell an ask from a probe (an edit's hint on a miss), so a probe
184
184
  that would ask waits too.
185
185
 
186
+ ## Keeping alive
187
+
188
+ Restate shuts an attempt down after its inactivity timeout (a minute) and starts it again, unless
189
+ something keeps it alive. The adapter keeps it alive (`ctx.working`) while OpenCode's turn runs:
190
+ while the model streams its requests, and while OpenCode's own tools (shell, read, write, edit,
191
+ glob, grep) work on the machine, a command that runs for minutes included. But not:
192
+
193
+ - while a tool of your own runs, unless it says so itself (`tool({ keepalive: true })`): it may
194
+ wait on Restate (a call, a signal), and such a wait suspends.
195
+ - while it waits for an approval, even of the shell: a wait on Restate suspends.
196
+
197
+ OpenCode has no hook at the end of a model's request, so this is the turn's scope with a gap for
198
+ each tool that runs (tools may overlap: the scope reopens once none runs). A request OpenCode
199
+ makes outside a turn (a session's title, say) is not kept alive.
200
+
186
201
  ## Not yet
187
202
 
188
203
  - **A change of `model`** for a key that has a session already: the session
@@ -71,6 +71,11 @@
71
71
  // `approval`, its tool call waits for a person's approval, through Restate
72
72
  // (`permissionPlugin`).
73
73
  //
74
+ // The attempt is kept alive (`ctx.working`) while OpenCode's turn runs, its
75
+ // own tools (shell, read, edit...) included, but not while a tool of yours
76
+ // executes (it says so itself: `tool({ keepalive })`), nor while an approval
77
+ // is waited for (`gateOf`): OpenCode has no hook at the end of a model's request.
78
+ //
74
79
  // TODO: a change of `model` on an existing session.
75
80
  import * as restate from '@restatedev/sessions';
76
81
  import { database, reset } from '@restatedev/sessions/internal';
@@ -89,6 +94,7 @@ import {
89
94
  configured,
90
95
  fromTool,
91
96
  inboxOf,
97
+ keepAlive,
92
98
  modelOf,
93
99
  providerOf,
94
100
  refusal,
@@ -506,6 +512,58 @@ const active = async (host: Host) => {
506
512
  return turns[SESSION as string] !== undefined;
507
513
  };
508
514
 
515
+ /**
516
+ * Keeps the attempt alive (`ctx.working`) while OpenCode's turn runs, but
517
+ * not while a tool that is not kept alive executes, nor while a wait on
518
+ * Restate is made: OpenCode has no hook at the end of a model's request, so
519
+ * the turn's scope minus those windows is the nearest. The scope is open
520
+ * exactly while a turn is running (`turn`) and nothing is paused (`pause`:
521
+ * a set of ids, since tools may overlap, and a pause is made once per id).
522
+ * `end` closes it for good, whichever way the attempt ends.
523
+ */
524
+ function gateOf(ctx: restate.SessionContext) {
525
+ let turns = 0;
526
+ let closed = false;
527
+ const paused = new Set<string>();
528
+ let release: (() => void) | undefined;
529
+ const sync = () => {
530
+ const open = !closed && turns > 0 && paused.size === 0;
531
+ if (open && !release) release = keepAlive(ctx);
532
+ else if (!open && release) {
533
+ release();
534
+ release = undefined;
535
+ }
536
+ };
537
+ return {
538
+ /** Run `fn` as a turn: the scope is open meanwhile, unless paused. Closed on every way out. */
539
+ async turn<T>(fn: () => Promise<T>): Promise<T> {
540
+ turns++;
541
+ sync();
542
+ try {
543
+ return await fn();
544
+ } finally {
545
+ turns--;
546
+ if (turns === 0) paused.clear();
547
+ sync();
548
+ }
549
+ },
550
+ pause(id: string) {
551
+ paused.add(id);
552
+ sync();
553
+ },
554
+ resume(id: string) {
555
+ paused.delete(id);
556
+ sync();
557
+ },
558
+ end() {
559
+ closed = true;
560
+ paused.clear();
561
+ sync();
562
+ },
563
+ };
564
+ }
565
+ type Gate = ReturnType<typeof gateOf>;
566
+
509
567
  /** How long a prompt's turn may be neither running nor ended: one resumed at boot starts well within it. */
510
568
  const STALLED_MS = 5_000;
511
569
 
@@ -845,6 +903,7 @@ function permissionPlugin(
845
903
  ctx: restate.SessionContext,
846
904
  approval: boolean,
847
905
  fail: (error: unknown) => Promise<never>,
906
+ gate: Gate,
848
907
  ): Plugin.Plugin {
849
908
  return {
850
909
  id: 'restate-agents.permission',
@@ -865,7 +924,12 @@ function permissionPlugin(
865
924
  const call = calls.get(callId);
866
925
  const asked = { ...call, action: event.action, resources: [...event.resources] };
867
926
  // An error of the wait fails the attempt: the ask never settles.
868
- const value = await waitFor(ctx, callId, APPROVAL, asked, { approval: true, rejoin: true }).catch(fail);
927
+ // A wait on Restate is never inside a scope, whatever tool it is of (one kept alive, say).
928
+ const waiting = `approval:${callId}`;
929
+ gate.pause(waiting);
930
+ const value = await waitFor(ctx, callId, APPROVAL, asked, { approval: true, rejoin: true })
931
+ .catch(fail)
932
+ .finally(() => gate.resume(waiting));
869
933
  const decision = decided(value);
870
934
  if (decision.allowed) {
871
935
  event.effect = 'allow';
@@ -898,6 +962,10 @@ export const withOpenCode = async <T>(
898
962
  const workspace = typeof where === 'function' ? await where(ctx) : where;
899
963
  if (workspace) await mkdir(workspace, { recursive: true });
900
964
  const fence: Fence = { closed: false };
965
+ const gate = gateOf(ctx);
966
+ // OpenCode's own tools (shell, read, edit...) work on the machine and keep the turn alive; ours say so
967
+ // themselves (their `run` opens a scope of its own).
968
+ const ours = new Set(tools.map((t) => t.name));
901
969
  const { promise: failure, reject: failed } = Promise.withResolvers<never>();
902
970
  failure.catch(() => {});
903
971
  // A tool's error ends the attempt: nothing more is stored, and the tool
@@ -991,27 +1059,39 @@ export const withOpenCode = async <T>(
991
1059
  const followPlugin: Plugin.Plugin = {
992
1060
  id: 'restate-agents.follow',
993
1061
  async setup(plugin) {
994
- const before = await plugin.tool.hook('execute.before', async () => {
995
- await copy()
996
- .then(() => toolCallStarted(ctx))
997
- .catch(fail);
1062
+ // A tool's window: the hooks run, and the tool executes, with the turn's scope paused (the hooks
1063
+ // copy and publish, which wait on Restate), unless the tool is kept alive: then only the hooks.
1064
+ const before = await plugin.tool.hook('execute.before', async (event) => {
1065
+ gate.pause(event.id);
1066
+ try {
1067
+ await copy()
1068
+ .then(() => toolCallStarted(ctx))
1069
+ .catch(fail);
1070
+ } finally {
1071
+ if (!ours.has(event.tool)) gate.resume(event.id);
1072
+ }
998
1073
  });
999
1074
  const after = await plugin.tool.hook('execute.after', async (event) => {
1000
- if (!inboxOf(ctx)) return;
1001
- const output =
1002
- event.status === 'error'
1003
- ? // As OpenCode stores it: a denied permission's reason, say, not the tool's "Unable to read".
1004
- toSessionError(event.error).message
1005
- : outputOf({ type: 'tool', state: { status: 'completed', ...event.result } as Content['state'] });
1006
- const result: ItemResult = {
1007
- id: event.id,
1008
- name: event.tool,
1009
- output,
1010
- ...(event.status === 'error' ? { error: true } : {}),
1011
- };
1012
- await copy({ result, from: `${event.messageID}/${event.id}` })
1013
- .then(steer)
1014
- .catch(fail);
1075
+ gate.pause(event.id);
1076
+ try {
1077
+ if (!inboxOf(ctx)) return;
1078
+ const output =
1079
+ event.status === 'error'
1080
+ ? // As OpenCode stores it: a denied permission's reason, say, not the tool's "Unable to read".
1081
+ toSessionError(event.error).message
1082
+ : outputOf({ type: 'tool', state: { status: 'completed', ...event.result } as Content['state'] });
1083
+ const result: ItemResult = {
1084
+ id: event.id,
1085
+ name: event.tool,
1086
+ output,
1087
+ ...(event.status === 'error' ? { error: true } : {}),
1088
+ };
1089
+ await copy({ result, from: `${event.messageID}/${event.id}` })
1090
+ .then(steer)
1091
+ .catch(fail);
1092
+ } finally {
1093
+ gate.resume(event.id);
1094
+ }
1015
1095
  });
1016
1096
  return async () => {
1017
1097
  await before.dispose();
@@ -1054,7 +1134,7 @@ export const withOpenCode = async <T>(
1054
1134
  fail,
1055
1135
  workspace !== undefined,
1056
1136
  ),
1057
- permissionPlugin(ctx, approval, fail),
1137
+ permissionPlugin(ctx, approval, fail, gate),
1058
1138
  ...(system ? [systemPlugin(system)] : []),
1059
1139
  // An outage OpenCode would stop retrying fails the attempt, as a tool's error does (never a refusal).
1060
1140
  retryPlugin(retry ?? {}, (error) => void fail(error)),
@@ -1144,7 +1224,8 @@ export const withOpenCode = async <T>(
1144
1224
  }),
1145
1225
  );
1146
1226
  }
1147
- const now = await settled(opened, messageId);
1227
+ // The turn runs from its submit: the scope is open while it does, minus the tools' windows.
1228
+ const now = await gate.turn(() => settled(opened, messageId));
1148
1229
  // A prompt the cancellation's interrupt ended fails with the cancellation.
1149
1230
  if (cancelled) throw cancelled;
1150
1231
  await copy();
@@ -1174,6 +1255,7 @@ export const withOpenCode = async <T>(
1174
1255
  return done;
1175
1256
  } finally {
1176
1257
  stop?.removeEventListener('abort', onStop);
1258
+ gate.end();
1177
1259
  if (turn) live.delete(turn);
1178
1260
  if (booted) {
1179
1261
  const opened = await booted.catch(() => undefined);