@restatedev/agents 0.10.3 → 0.11.1
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.
- package/README.md +10 -0
- package/dist/agentlib/tools.js +2 -0
- package/dist/agentlib/tools.js.map +1 -1
- package/dist/calls.d.ts +29 -8
- package/dist/calls.d.ts.map +1 -1
- package/dist/calls.js +63 -19
- package/dist/calls.js.map +1 -1
- package/dist/claude/index.d.ts.map +1 -1
- package/dist/claude/index.js +33 -4
- package/dist/claude/index.js.map +1 -1
- package/dist/common.d.ts +12 -0
- package/dist/common.d.ts.map +1 -1
- package/dist/common.js +34 -1
- package/dist/common.js.map +1 -1
- package/dist/deepseek/barriers.d.ts +11 -0
- package/dist/deepseek/barriers.d.ts.map +1 -0
- package/dist/deepseek/barriers.js +36 -0
- package/dist/deepseek/barriers.js.map +1 -0
- package/dist/deepseek/index.d.ts.map +1 -1
- package/dist/deepseek/index.js +52 -17
- package/dist/deepseek/index.js.map +1 -1
- package/dist/deepseek/persistence.d.ts +16 -0
- package/dist/deepseek/persistence.d.ts.map +1 -1
- package/dist/deepseek/persistence.js +33 -1
- package/dist/deepseek/persistence.js.map +1 -1
- package/dist/langgraph/checkpointer.d.ts +8 -1
- package/dist/langgraph/checkpointer.d.ts.map +1 -1
- package/dist/langgraph/checkpointer.js +117 -31
- package/dist/langgraph/checkpointer.js.map +1 -1
- package/dist/langgraph/graph.d.ts.map +1 -1
- package/dist/langgraph/graph.js +15 -2
- package/dist/langgraph/graph.js.map +1 -1
- package/dist/langgraph/index.d.ts.map +1 -1
- package/dist/langgraph/index.js +2 -2
- package/dist/langgraph/index.js.map +1 -1
- package/dist/langgraph/keepalive.d.ts +16 -0
- package/dist/langgraph/keepalive.d.ts.map +1 -0
- package/dist/langgraph/keepalive.js +51 -0
- package/dist/langgraph/keepalive.js.map +1 -0
- package/dist/opencode/index.d.ts.map +1 -1
- package/dist/opencode/index.js +129 -25
- package/dist/opencode/index.js.map +1 -1
- package/dist/pi/commits.d.ts +6 -0
- package/dist/pi/commits.d.ts.map +1 -0
- package/dist/pi/commits.js +3 -0
- package/dist/pi/commits.js.map +1 -0
- package/dist/pi/index.d.ts +14 -1
- package/dist/pi/index.d.ts.map +1 -1
- package/dist/pi/index.js +91 -9
- package/dist/pi/index.js.map +1 -1
- package/dist/pi/keepalive.d.ts +21 -0
- package/dist/pi/keepalive.d.ts.map +1 -0
- package/dist/pi/keepalive.js +98 -0
- package/dist/pi/keepalive.js.map +1 -0
- package/dist/pi/storage.d.ts +62 -3
- package/dist/pi/storage.d.ts.map +1 -1
- package/dist/pi/storage.js +355 -12
- package/dist/pi/storage.js.map +1 -1
- package/dist/tools.d.ts +9 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +9 -1
- package/dist/tools.js.map +1 -1
- package/package.json +3 -3
- package/src/agentlib/tools.ts +2 -0
- package/src/calls.ts +86 -21
- package/src/claude/index.ts +36 -6
- package/src/common.ts +36 -1
- package/src/deepseek/README.md +24 -5
- package/src/deepseek/barriers.ts +63 -0
- package/src/deepseek/index.ts +55 -14
- package/src/deepseek/persistence.ts +47 -6
- package/src/langgraph/README.md +19 -0
- package/src/langgraph/checkpointer.ts +134 -35
- package/src/langgraph/graph.ts +14 -2
- package/src/langgraph/index.ts +3 -3
- package/src/langgraph/keepalive.ts +58 -0
- package/src/opencode/README.md +15 -0
- package/src/opencode/index.ts +124 -23
- package/src/pi/README.md +64 -15
- package/src/pi/commits.ts +7 -0
- package/src/pi/index.ts +116 -7
- package/src/pi/keepalive.ts +121 -0
- package/src/pi/storage.ts +382 -10
- package/src/tools.ts +12 -1
package/src/opencode/index.ts
CHANGED
|
@@ -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,
|
|
@@ -98,6 +104,7 @@ import {
|
|
|
98
104
|
toolCallStarted,
|
|
99
105
|
approves,
|
|
100
106
|
} from '../common.ts';
|
|
107
|
+
import { flushCalls } from '../calls.ts';
|
|
101
108
|
import { answerOnce, invocationOf, type Call, type Items, type Parsed, STEPS, type Turn } from '../conversation.ts';
|
|
102
109
|
import { conversationView } from '../messages.ts';
|
|
103
110
|
import { tookSteers } from '../steering.ts';
|
|
@@ -142,7 +149,25 @@ const native = (t: AnyTool, ctx: restate.SessionContext): OpenCodeTool => {
|
|
|
142
149
|
},
|
|
143
150
|
},
|
|
144
151
|
};
|
|
145
|
-
return {
|
|
152
|
+
return {
|
|
153
|
+
name: t.name,
|
|
154
|
+
description: t.description,
|
|
155
|
+
input,
|
|
156
|
+
execute: async (args, callId) => {
|
|
157
|
+
// OpenCode stores the result (or the error a call answered with) in its own database, which a commit of
|
|
158
|
+
// `ctx.db` does not reach: a call that answered is recorded before it is handed over. The tool's own error
|
|
159
|
+
// is the one thrown, whatever the flush does.
|
|
160
|
+
let result: string;
|
|
161
|
+
try {
|
|
162
|
+
result = await t.run(args, { ctx, callId });
|
|
163
|
+
} catch (error) {
|
|
164
|
+
await flushCalls(ctx).catch(() => {});
|
|
165
|
+
throw error;
|
|
166
|
+
}
|
|
167
|
+
await flushCalls(ctx);
|
|
168
|
+
return result;
|
|
169
|
+
},
|
|
170
|
+
};
|
|
146
171
|
};
|
|
147
172
|
|
|
148
173
|
/** The session every prompt goes to. */
|
|
@@ -506,6 +531,58 @@ const active = async (host: Host) => {
|
|
|
506
531
|
return turns[SESSION as string] !== undefined;
|
|
507
532
|
};
|
|
508
533
|
|
|
534
|
+
/**
|
|
535
|
+
* Keeps the attempt alive (`ctx.working`) while OpenCode's turn runs, but
|
|
536
|
+
* not while a tool that is not kept alive executes, nor while a wait on
|
|
537
|
+
* Restate is made: OpenCode has no hook at the end of a model's request, so
|
|
538
|
+
* the turn's scope minus those windows is the nearest. The scope is open
|
|
539
|
+
* exactly while a turn is running (`turn`) and nothing is paused (`pause`:
|
|
540
|
+
* a set of ids, since tools may overlap, and a pause is made once per id).
|
|
541
|
+
* `end` closes it for good, whichever way the attempt ends.
|
|
542
|
+
*/
|
|
543
|
+
function gateOf(ctx: restate.SessionContext) {
|
|
544
|
+
let turns = 0;
|
|
545
|
+
let closed = false;
|
|
546
|
+
const paused = new Set<string>();
|
|
547
|
+
let release: (() => void) | undefined;
|
|
548
|
+
const sync = () => {
|
|
549
|
+
const open = !closed && turns > 0 && paused.size === 0;
|
|
550
|
+
if (open && !release) release = keepAlive(ctx);
|
|
551
|
+
else if (!open && release) {
|
|
552
|
+
release();
|
|
553
|
+
release = undefined;
|
|
554
|
+
}
|
|
555
|
+
};
|
|
556
|
+
return {
|
|
557
|
+
/** Run `fn` as a turn: the scope is open meanwhile, unless paused. Closed on every way out. */
|
|
558
|
+
async turn<T>(fn: () => Promise<T>): Promise<T> {
|
|
559
|
+
turns++;
|
|
560
|
+
sync();
|
|
561
|
+
try {
|
|
562
|
+
return await fn();
|
|
563
|
+
} finally {
|
|
564
|
+
turns--;
|
|
565
|
+
if (turns === 0) paused.clear();
|
|
566
|
+
sync();
|
|
567
|
+
}
|
|
568
|
+
},
|
|
569
|
+
pause(id: string) {
|
|
570
|
+
paused.add(id);
|
|
571
|
+
sync();
|
|
572
|
+
},
|
|
573
|
+
resume(id: string) {
|
|
574
|
+
paused.delete(id);
|
|
575
|
+
sync();
|
|
576
|
+
},
|
|
577
|
+
end() {
|
|
578
|
+
closed = true;
|
|
579
|
+
paused.clear();
|
|
580
|
+
sync();
|
|
581
|
+
},
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
type Gate = ReturnType<typeof gateOf>;
|
|
585
|
+
|
|
509
586
|
/** How long a prompt's turn may be neither running nor ended: one resumed at boot starts well within it. */
|
|
510
587
|
const STALLED_MS = 5_000;
|
|
511
588
|
|
|
@@ -845,6 +922,7 @@ function permissionPlugin(
|
|
|
845
922
|
ctx: restate.SessionContext,
|
|
846
923
|
approval: boolean,
|
|
847
924
|
fail: (error: unknown) => Promise<never>,
|
|
925
|
+
gate: Gate,
|
|
848
926
|
): Plugin.Plugin {
|
|
849
927
|
return {
|
|
850
928
|
id: 'restate-agents.permission',
|
|
@@ -865,7 +943,12 @@ function permissionPlugin(
|
|
|
865
943
|
const call = calls.get(callId);
|
|
866
944
|
const asked = { ...call, action: event.action, resources: [...event.resources] };
|
|
867
945
|
// An error of the wait fails the attempt: the ask never settles.
|
|
868
|
-
|
|
946
|
+
// A wait on Restate is never inside a scope, whatever tool it is of (one kept alive, say).
|
|
947
|
+
const waiting = `approval:${callId}`;
|
|
948
|
+
gate.pause(waiting);
|
|
949
|
+
const value = await waitFor(ctx, callId, APPROVAL, asked, { approval: true, rejoin: true })
|
|
950
|
+
.catch(fail)
|
|
951
|
+
.finally(() => gate.resume(waiting));
|
|
869
952
|
const decision = decided(value);
|
|
870
953
|
if (decision.allowed) {
|
|
871
954
|
event.effect = 'allow';
|
|
@@ -898,6 +981,10 @@ export const withOpenCode = async <T>(
|
|
|
898
981
|
const workspace = typeof where === 'function' ? await where(ctx) : where;
|
|
899
982
|
if (workspace) await mkdir(workspace, { recursive: true });
|
|
900
983
|
const fence: Fence = { closed: false };
|
|
984
|
+
const gate = gateOf(ctx);
|
|
985
|
+
// OpenCode's own tools (shell, read, edit...) work on the machine and keep the turn alive; ours say so
|
|
986
|
+
// themselves (their `run` opens a scope of its own).
|
|
987
|
+
const ours = new Set(tools.map((t) => t.name));
|
|
901
988
|
const { promise: failure, reject: failed } = Promise.withResolvers<never>();
|
|
902
989
|
failure.catch(() => {});
|
|
903
990
|
// A tool's error ends the attempt: nothing more is stored, and the tool
|
|
@@ -991,27 +1078,39 @@ export const withOpenCode = async <T>(
|
|
|
991
1078
|
const followPlugin: Plugin.Plugin = {
|
|
992
1079
|
id: 'restate-agents.follow',
|
|
993
1080
|
async setup(plugin) {
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
1081
|
+
// A tool's window: the hooks run, and the tool executes, with the turn's scope paused (the hooks
|
|
1082
|
+
// copy and publish, which wait on Restate), unless the tool is kept alive: then only the hooks.
|
|
1083
|
+
const before = await plugin.tool.hook('execute.before', async (event) => {
|
|
1084
|
+
gate.pause(event.id);
|
|
1085
|
+
try {
|
|
1086
|
+
await copy()
|
|
1087
|
+
.then(() => toolCallStarted(ctx))
|
|
1088
|
+
.catch(fail);
|
|
1089
|
+
} finally {
|
|
1090
|
+
if (!ours.has(event.tool)) gate.resume(event.id);
|
|
1091
|
+
}
|
|
998
1092
|
});
|
|
999
1093
|
const after = await plugin.tool.hook('execute.after', async (event) => {
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
.
|
|
1094
|
+
gate.pause(event.id);
|
|
1095
|
+
try {
|
|
1096
|
+
if (!inboxOf(ctx)) return;
|
|
1097
|
+
const output =
|
|
1098
|
+
event.status === 'error'
|
|
1099
|
+
? // As OpenCode stores it: a denied permission's reason, say, not the tool's "Unable to read".
|
|
1100
|
+
toSessionError(event.error).message
|
|
1101
|
+
: outputOf({ type: 'tool', state: { status: 'completed', ...event.result } as Content['state'] });
|
|
1102
|
+
const result: ItemResult = {
|
|
1103
|
+
id: event.id,
|
|
1104
|
+
name: event.tool,
|
|
1105
|
+
output,
|
|
1106
|
+
...(event.status === 'error' ? { error: true } : {}),
|
|
1107
|
+
};
|
|
1108
|
+
await copy({ result, from: `${event.messageID}/${event.id}` })
|
|
1109
|
+
.then(steer)
|
|
1110
|
+
.catch(fail);
|
|
1111
|
+
} finally {
|
|
1112
|
+
gate.resume(event.id);
|
|
1113
|
+
}
|
|
1015
1114
|
});
|
|
1016
1115
|
return async () => {
|
|
1017
1116
|
await before.dispose();
|
|
@@ -1054,7 +1153,7 @@ export const withOpenCode = async <T>(
|
|
|
1054
1153
|
fail,
|
|
1055
1154
|
workspace !== undefined,
|
|
1056
1155
|
),
|
|
1057
|
-
permissionPlugin(ctx, approval, fail),
|
|
1156
|
+
permissionPlugin(ctx, approval, fail, gate),
|
|
1058
1157
|
...(system ? [systemPlugin(system)] : []),
|
|
1059
1158
|
// An outage OpenCode would stop retrying fails the attempt, as a tool's error does (never a refusal).
|
|
1060
1159
|
retryPlugin(retry ?? {}, (error) => void fail(error)),
|
|
@@ -1144,7 +1243,8 @@ export const withOpenCode = async <T>(
|
|
|
1144
1243
|
}),
|
|
1145
1244
|
);
|
|
1146
1245
|
}
|
|
1147
|
-
|
|
1246
|
+
// The turn runs from its submit: the scope is open while it does, minus the tools' windows.
|
|
1247
|
+
const now = await gate.turn(() => settled(opened, messageId));
|
|
1148
1248
|
// A prompt the cancellation's interrupt ended fails with the cancellation.
|
|
1149
1249
|
if (cancelled) throw cancelled;
|
|
1150
1250
|
await copy();
|
|
@@ -1174,6 +1274,7 @@ export const withOpenCode = async <T>(
|
|
|
1174
1274
|
return done;
|
|
1175
1275
|
} finally {
|
|
1176
1276
|
stop?.removeEventListener('abort', onStop);
|
|
1277
|
+
gate.end();
|
|
1177
1278
|
if (turn) live.delete(turn);
|
|
1178
1279
|
if (booted) {
|
|
1179
1280
|
const opened = await booted.catch(() => undefined);
|
package/src/pi/README.md
CHANGED
|
@@ -17,16 +17,17 @@ const assistant = pi.agent({ name: 'assistant', system: 'Answer briefly.', tools
|
|
|
17
17
|
await serve(assistant);
|
|
18
18
|
```
|
|
19
19
|
|
|
20
|
-
| Option | What
|
|
21
|
-
| ------------- |
|
|
22
|
-
| `model` | `provider/model-id`, of any provider pi-ai knows; or else `MODEL`, or else `openai/gpt-6-sol` (`OPENAI_API_KEY`)
|
|
23
|
-
| `models` | A pi-ai model registry, for a provider of your own
|
|
24
|
-
| `system` | The system prompt
|
|
25
|
-
| `tools` | `tool()`s and Restate's tools of `@restatedev/agents`, or pi-durable's `defineTool`s
|
|
26
|
-
| `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))
|
|
27
|
-
| `workspace` | A directory for pi-durable's coding tools (`read`, `write`, `edit`, `bash`), on the local file system; use a sandbox
|
|
28
|
-
| `serviceTier` | OpenAI's service tier for each request: `fast` for its fast mode (priced higher), `flex`, and so on
|
|
29
|
-
| `retry` | How pi asks the model again after a request failed for a reason that passes (an outage, a rate limit): by default without limit, 2 s to a minute apart
|
|
20
|
+
| Option | What |
|
|
21
|
+
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
22
|
+
| `model` | `provider/model-id`, of any provider pi-ai knows; or else `MODEL`, or else `openai/gpt-6-sol` (`OPENAI_API_KEY`) |
|
|
23
|
+
| `models` | A pi-ai model registry, for a provider of your own |
|
|
24
|
+
| `system` | The system prompt |
|
|
25
|
+
| `tools` | `tool()`s and Restate's tools of `@restatedev/agents`, or pi-durable's `defineTool`s |
|
|
26
|
+
| `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)) |
|
|
27
|
+
| `workspace` | A directory for pi-durable's coding tools (`read`, `write`, `edit`, `bash`), on the local file system; use a sandbox |
|
|
28
|
+
| `serviceTier` | OpenAI's service tier for each request: `fast` for its fast mode (priced higher), `flex`, and so on |
|
|
29
|
+
| `retry` | How pi asks the model again after a request failed for a reason that passes (an outage, a rate limit): by default without limit, 2 s to a minute apart |
|
|
30
|
+
| `commits` | `'each'` (the default): each pi commit is one write to Restate; `'effects'`: one for all the commits between two effects (see [Through crashes](#through-crashes)) |
|
|
30
31
|
|
|
31
32
|
For a session object of your own, `pi.chat(options)` is the handler and
|
|
32
33
|
`pi.messages()` the view; `options` may be a function of the invocation's context, such as
|
|
@@ -56,9 +57,10 @@ model and persona in the object's database.
|
|
|
56
57
|
|
|
57
58
|
## Through crashes
|
|
58
59
|
|
|
59
|
-
|
|
60
|
-
([`storage.ts`](storage.ts)), stored in order with
|
|
61
|
-
handler does. A retried attempt opens the Harness again
|
|
60
|
+
By default (`commits: 'each'`), each pi-durable commit is an SQL transaction
|
|
61
|
+
in the object's database ([`storage.ts`](storage.ts)), stored in order with
|
|
62
|
+
everything else the handler does. A retried attempt opens the Harness again
|
|
63
|
+
and carries on:
|
|
62
64
|
|
|
63
65
|
- a prompt is submitted once, by its id (pi-durable's `requestId`, the
|
|
64
66
|
invocation's id);
|
|
@@ -84,16 +86,63 @@ copies its new entries (the model's replies, the tools' results) into the
|
|
|
84
86
|
agent's conversation of turns, in the same transaction: what `messages`
|
|
85
87
|
shows ([docs/conversation.md](../../docs/conversation.md)). A commit that
|
|
86
88
|
copied a reply with tool calls, or tools' results, is published once it is
|
|
87
|
-
done, in a `chat` turn (pi commits each result on its
|
|
88
|
-
a `prompt()` in a handler of your own publishes nothing), and nothing else
|
|
89
|
+
done, in a `chat` turn (with `commits: 'each'`, pi commits each result on its
|
|
90
|
+
own: one publish each; a `prompt()` in a handler of your own publishes nothing), and nothing else
|
|
89
91
|
is: a tool call's start publishes nothing, so a follower reads the calls
|
|
90
92
|
once they are stored, and each output once it is. The views show
|
|
91
93
|
each turn as it was asked and answered, not pi's summaries and handoffs.
|
|
92
94
|
|
|
95
|
+
### One write for each effect
|
|
96
|
+
|
|
97
|
+
A step of a turn makes several pi commits (the preparation, the request, the
|
|
98
|
+
reply, the tool's start, its result), and each costs one round trip to
|
|
99
|
+
Restate: a turn of four model requests and three tool calls makes 30. With
|
|
100
|
+
`commits: 'effects'`, the commits between two effects (a model request, a
|
|
101
|
+
tool call) share one write: the same turn makes 10 (the turn opening, each
|
|
102
|
+
effect's start, the answer, the turn closing); in a `chat` turn that is
|
|
103
|
+
followed, a publish after each round that reads what was steered to it adds
|
|
104
|
+
one for each round. While an effect runs, its own commits (a model's
|
|
105
|
+
progress, a tool's result) are written at once, as with `'each'`; so is
|
|
106
|
+
everything outside a prompt (`work`, a compaction).
|
|
107
|
+
|
|
108
|
+
What `'effects'` keeps: what pi committed before a tool call, or a model call
|
|
109
|
+
that returns a promise, starts is stored before it does, so it never runs
|
|
110
|
+
ahead of its own history (a streamed model request starts while that write is
|
|
111
|
+
in flight, which is harmless: a retry only repeats the request); and what
|
|
112
|
+
anyone else can see (a publish, a Restate call, a send, the
|
|
113
|
+
end of the handler, a `ctx.db` call of your own) comes after a write of all
|
|
114
|
+
of it, never before. A failed pi commit still undoes only itself, and a
|
|
115
|
+
`ctx.db` call from inside one is refused, as with `'each'`.
|
|
116
|
+
|
|
117
|
+
What it gives up: what pi commits in the milliseconds between one effect's
|
|
118
|
+
result and the next effect's start is lost in a crash, and the retried
|
|
119
|
+
attempt does it again from the state that was stored. Tools that start together start
|
|
120
|
+
after one write, and the results of tools that end together are stored in one
|
|
121
|
+
commit, and published once. A `ctx.db` call of yours made while pi has
|
|
122
|
+
commits to write costs one more write (for the commits, which it waits for),
|
|
123
|
+
and no stall. A write of the commits that fails fails the attempt, as a
|
|
124
|
+
failed commit does, though pi was told its commits were done.
|
|
125
|
+
|
|
93
126
|
The files of a `workspace` are not in the database: they last as long as the
|
|
94
127
|
disk does, and a coding tool a crash cut off is not run again (the model is
|
|
95
128
|
told it was interrupted).
|
|
96
129
|
|
|
130
|
+
## Kept alive
|
|
131
|
+
|
|
132
|
+
An attempt of a session object is shut down by Restate after its inactivity
|
|
133
|
+
timeout (a minute), and run again from the start, unless work keeps it alive
|
|
134
|
+
(`ctx.working`). Each request of a model does, wherever pi makes it (a turn's,
|
|
135
|
+
a deferred response's, a compaction's): the agent wraps the model registry (its
|
|
136
|
+
own, or the `models` given), and a request is kept alive from its call until
|
|
137
|
+
its response ends, fails, is abandoned or is aborted. So does each built-in
|
|
138
|
+
coding tool (`read`, `write`, `edit`, `bash`): it works on the machine, and a
|
|
139
|
+
`bash` may run for minutes.
|
|
140
|
+
|
|
141
|
+
A tool of your own is not kept alive: a `tool()` sets `keepalive` if it may
|
|
142
|
+
work for longer than the timeout, or it is cut off, as by a crash (the next
|
|
143
|
+
attempt tells the model it was interrupted, see above). A tool kept alive must
|
|
144
|
+
not wait on Restate (a call, a signal) inside.
|
|
145
|
+
|
|
97
146
|
## Run
|
|
98
147
|
|
|
99
148
|
```sh
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// The default of the pi option `commits` (index.ts), in one place: the tests
|
|
2
|
+
// of the whole suite set it (test/commits-default.ts) to run the pi suites in
|
|
3
|
+
// both modes.
|
|
4
|
+
import type { Commits } from './storage.ts';
|
|
5
|
+
|
|
6
|
+
/** What `commits` is when an agent does not say. */
|
|
7
|
+
export const commitsDefault: { commits: Commits } = { commits: 'each' };
|
package/src/pi/index.ts
CHANGED
|
@@ -63,7 +63,9 @@ import {
|
|
|
63
63
|
type ConversationRetryPolicy,
|
|
64
64
|
type ConversationStreamOptions,
|
|
65
65
|
type ToolRegistration,
|
|
66
|
+
type Wrap,
|
|
66
67
|
} from '@earendil-works/pi-durable';
|
|
68
|
+
import { keptModels } from './keepalive.ts';
|
|
67
69
|
import { NodeExecutionEnv } from '@earendil-works/pi-durable/env/node';
|
|
68
70
|
import { CodingTools } from '@earendil-works/pi-durable/tools';
|
|
69
71
|
import type { Transaction } from '@restatedev/sessions';
|
|
@@ -86,6 +88,7 @@ import {
|
|
|
86
88
|
stopSignalOf,
|
|
87
89
|
toolCallStarted,
|
|
88
90
|
} from '../common.ts';
|
|
91
|
+
import { holding } from '../calls.ts';
|
|
89
92
|
import { answerOnce, invocationOf, type Items, type Parsed, type Turn } from '../conversation.ts';
|
|
90
93
|
import { tookSteers } from '../steering.ts';
|
|
91
94
|
import { conversationView } from '../messages.ts';
|
|
@@ -93,7 +96,8 @@ import { type Answer, withChecked } from '../output.ts';
|
|
|
93
96
|
import { type Definition, sessionObject } from '../object.ts';
|
|
94
97
|
import { isTool, jsonSchemaOf, type Tool as AnyTool } from '../tools.ts';
|
|
95
98
|
import type { z } from 'zod';
|
|
96
|
-
import {
|
|
99
|
+
import { commitsDefault } from './commits.ts';
|
|
100
|
+
import { type Commits, openSqlKvStorage, SqlKvDatabase } from './storage.ts';
|
|
97
101
|
|
|
98
102
|
/** What `work` gets: `prompt(text)`, the `conversation()`, and the `harness` and chord `context` for anything else. */
|
|
99
103
|
export interface Pi {
|
|
@@ -280,6 +284,17 @@ export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undef
|
|
|
280
284
|
* key, an unknown model) is never asked again.
|
|
281
285
|
*/
|
|
282
286
|
retry?: Partial<ConversationRetryPolicy>;
|
|
287
|
+
/**
|
|
288
|
+
* How pi's commits are written: `'each'` (the default), one write to
|
|
289
|
+
* Restate each, or `'effects'`, one for all the commits between two effects
|
|
290
|
+
* (a model call, a tool call), so that a step of a turn costs about one
|
|
291
|
+
* write, not several. With `'effects'`, what pi commits in the milliseconds
|
|
292
|
+
* between one effect's result and the next effect's start is lost in a
|
|
293
|
+
* crash, and the retry does it again from the same stored state; what
|
|
294
|
+
* others see (a publish, a call, a send, the end of the handler) is
|
|
295
|
+
* written first.
|
|
296
|
+
*/
|
|
297
|
+
commits?: Commits;
|
|
283
298
|
/**
|
|
284
299
|
* The answer as data: a zod object, whose JSON the agent replies with
|
|
285
300
|
* (checked), and `chat` and `prompt` answer with (see output.ts).
|
|
@@ -287,6 +302,8 @@ export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undef
|
|
|
287
302
|
output?: O;
|
|
288
303
|
}
|
|
289
304
|
|
|
305
|
+
export type { Commits };
|
|
306
|
+
|
|
290
307
|
/** OpenAI's service tiers (its Responses API's `service_tier`). */
|
|
291
308
|
export type ServiceTier = 'auto' | 'default' | 'fast' | 'flex' | 'priority';
|
|
292
309
|
|
|
@@ -313,6 +330,9 @@ const native = (t: AnyTool, ctx: restate.SessionContext): ToolRegistration =>
|
|
|
313
330
|
}),
|
|
314
331
|
});
|
|
315
332
|
|
|
333
|
+
/** Run an effect (a tool), after what pi committed before it is written, and without batching its own commits. */
|
|
334
|
+
type Effect = <T>(run: () => Promise<T>) => Promise<T>;
|
|
335
|
+
|
|
316
336
|
/**
|
|
317
337
|
* The tools of an agent, `system` added to its system prompt, and, with a
|
|
318
338
|
* `workspace`, pi's coding tools working there, with the environment they
|
|
@@ -323,6 +343,8 @@ async function extensions(
|
|
|
323
343
|
system: string | undefined,
|
|
324
344
|
workspace: string | undefined,
|
|
325
345
|
afterTools: (conversation: ConversationId) => Promise<void>,
|
|
346
|
+
ctx: restate.SessionContext,
|
|
347
|
+
effect: Effect,
|
|
326
348
|
) {
|
|
327
349
|
const registry = createRegistry();
|
|
328
350
|
registry.install(defineExtension({ name: 'tools', tools }));
|
|
@@ -339,6 +361,14 @@ async function extensions(
|
|
|
339
361
|
registry.install(CodingTools);
|
|
340
362
|
// Tell the model where the coding tools work.
|
|
341
363
|
registry.install(defineExtension({ name: 'workspace', sections: [section('cwd', () => workspace)] }));
|
|
364
|
+
// The coding tools run in `ctx.working`: they work on the machine (a `bash` may run for minutes), and never
|
|
365
|
+
// wait on Restate. Installed after theirs, which they wrap.
|
|
366
|
+
const kept = (t: ToolRegistration): ToolRegistration => ({
|
|
367
|
+
...t,
|
|
368
|
+
execute: (args, api, context) => effect(() => ctx.working(() => t.execute(args, api, context))),
|
|
369
|
+
});
|
|
370
|
+
const wraps = (CodingTools.tools ?? []).map((t): Wrap => ({ tool: t.name, wrap: kept }));
|
|
371
|
+
registry.install(defineExtension({ name: 'keepalive', wraps }));
|
|
342
372
|
return { registry, env: () => new NodeExecutionEnv({ cwd: workspace }) };
|
|
343
373
|
}
|
|
344
374
|
|
|
@@ -381,7 +411,16 @@ function unanswered(id: string, why: string | null | undefined, detail: unknown,
|
|
|
381
411
|
*/
|
|
382
412
|
export const withPi = async <T>(
|
|
383
413
|
ctx: restate.SessionContext,
|
|
384
|
-
{
|
|
414
|
+
{
|
|
415
|
+
model: named,
|
|
416
|
+
models,
|
|
417
|
+
system,
|
|
418
|
+
tools = [],
|
|
419
|
+
workspace,
|
|
420
|
+
serviceTier,
|
|
421
|
+
retry,
|
|
422
|
+
commits = commitsDefault.commits,
|
|
423
|
+
}: Options,
|
|
385
424
|
work: (pi: Pi) => Promise<T>,
|
|
386
425
|
): Promise<T> => {
|
|
387
426
|
const model = modelOf(named);
|
|
@@ -437,10 +476,35 @@ export const withPi = async <T>(
|
|
|
437
476
|
// Whether a tool of the round asks to end the run (`terminate`, a handoff): pi then ends the round at its final
|
|
438
477
|
// boundary, which would start a run of its own for a message submitted there, outside the turn.
|
|
439
478
|
let ending = false;
|
|
479
|
+
// pi's storage (storage.ts): with `commits: 'effects'` it batches pi's commits, which a failed commit loses
|
|
480
|
+
// (reported to pi as done): that fails the attempt, as a tool's error does.
|
|
481
|
+
const database = new SqlKvDatabase(ctx.db, {
|
|
482
|
+
commits,
|
|
483
|
+
failed: (error) => {
|
|
484
|
+
failed(error);
|
|
485
|
+
cancel(error);
|
|
486
|
+
},
|
|
487
|
+
});
|
|
488
|
+
// With 'each' none of this is there: the code is as it was, without a batch in the way.
|
|
489
|
+
const batching = commits === 'effects';
|
|
490
|
+
const effect: Effect = !batching
|
|
491
|
+
? (run) => run()
|
|
492
|
+
: async (run) => {
|
|
493
|
+
const ended = database.effectStarted();
|
|
494
|
+
try {
|
|
495
|
+
await database.flush();
|
|
496
|
+
return await run();
|
|
497
|
+
} finally {
|
|
498
|
+
ended();
|
|
499
|
+
}
|
|
500
|
+
};
|
|
440
501
|
const tracked = (t: ToolRegistration): ToolRegistration => ({
|
|
441
502
|
...t,
|
|
442
503
|
execute: async (args, api, task) => {
|
|
504
|
+
// A tool is an effect: what pi committed before it is written first, and its own commits are not batched.
|
|
505
|
+
const ended = database.effectStarted();
|
|
443
506
|
try {
|
|
507
|
+
if (batching) await database.flush();
|
|
444
508
|
await toolCallStarted(ctx);
|
|
445
509
|
const result = await t.execute(args, api, task);
|
|
446
510
|
if (result.control?.terminate === true || result.control?.handoff !== undefined) ending = true;
|
|
@@ -449,6 +513,8 @@ export const withPi = async <T>(
|
|
|
449
513
|
// The tool's error: never taken for the model's provider refusing (a tool may call a model API).
|
|
450
514
|
fromTool(ctx, error);
|
|
451
515
|
return stopped(error, task);
|
|
516
|
+
} finally {
|
|
517
|
+
ended();
|
|
452
518
|
}
|
|
453
519
|
},
|
|
454
520
|
});
|
|
@@ -460,8 +526,15 @@ export const withPi = async <T>(
|
|
|
460
526
|
// A round that may end the run takes no steered message: each waits for the turn's end, then is a turn of its own.
|
|
461
527
|
const ends = ending;
|
|
462
528
|
ending = false;
|
|
463
|
-
if (
|
|
529
|
+
if (ends) return;
|
|
530
|
+
// The round's results are published before the inbox is read: a message steered while its tools ran is
|
|
531
|
+
// told of by that publish (`INBOX`), and pi places it only if it is submitted now. A turn nobody can
|
|
532
|
+
// steer has nothing to read.
|
|
533
|
+
if (batching && inboxOf(ctx)) await database.flush();
|
|
534
|
+
await steering?.(of);
|
|
464
535
|
},
|
|
536
|
+
ctx,
|
|
537
|
+
effect,
|
|
465
538
|
);
|
|
466
539
|
const settings = {
|
|
467
540
|
// A task that crashes is run again however often Restate retries the attempt (its retry policy decides):
|
|
@@ -475,12 +548,47 @@ export const withPi = async <T>(
|
|
|
475
548
|
// pi-durable hands its stream settings to pi-ai's requests as they are: serviceTier is pi-ai's.
|
|
476
549
|
...(serviceTier ? { stream: { serviceTier } as ConversationStreamOptions } : {}),
|
|
477
550
|
};
|
|
478
|
-
const database = new SqlKvDatabase(ctx.db);
|
|
479
551
|
const harness = await Harness.open(
|
|
480
552
|
await openSqlKvStorage(ctx.db, database),
|
|
481
|
-
|
|
553
|
+
// Each request of a model is kept alive, whoever made the registry (see keepalive.ts), and is an effect.
|
|
554
|
+
{
|
|
555
|
+
models: keptModels(
|
|
556
|
+
ctx,
|
|
557
|
+
models,
|
|
558
|
+
batching ? { started: () => database.effectStarted(), flush: () => database.flush() } : undefined,
|
|
559
|
+
),
|
|
560
|
+
registry,
|
|
561
|
+
env,
|
|
562
|
+
settings,
|
|
563
|
+
},
|
|
482
564
|
context,
|
|
483
565
|
);
|
|
566
|
+
if (batching) await database.flush();
|
|
567
|
+
|
|
568
|
+
/**
|
|
569
|
+
* `run`, a prompt's run, with pi's commits batched between effects (`commits: 'effects'`), and written, however
|
|
570
|
+
* it ends, before it returns: what others see of the turn (its close, the next call) comes after.
|
|
571
|
+
*/
|
|
572
|
+
const batched = <S, R>(run: (store: S) => Promise<R>): ((store: S) => Promise<R>) =>
|
|
573
|
+
!batching
|
|
574
|
+
? run
|
|
575
|
+
: async (store: S): Promise<R> => {
|
|
576
|
+
database.armed = true;
|
|
577
|
+
holding(ctx, () => database.flush(), 'pi');
|
|
578
|
+
let ran = false;
|
|
579
|
+
try {
|
|
580
|
+
const result = await run(store);
|
|
581
|
+
ran = true;
|
|
582
|
+
return result;
|
|
583
|
+
} finally {
|
|
584
|
+
database.armed = false;
|
|
585
|
+
holding(ctx, undefined, 'pi');
|
|
586
|
+
// A failed write has failed the attempt already: it never hides the error the run ended with.
|
|
587
|
+
await database.flush().catch((error: unknown) => {
|
|
588
|
+
if (ran) throw error;
|
|
589
|
+
});
|
|
590
|
+
}
|
|
591
|
+
};
|
|
484
592
|
|
|
485
593
|
const prompt = (text: string, check?: Check, reminder?: string) => {
|
|
486
594
|
// 0.3.0's `prompt(text, id)` took a prompt's id: from JavaScript, it would
|
|
@@ -494,7 +602,7 @@ export const withPi = async <T>(
|
|
|
494
602
|
ctx,
|
|
495
603
|
text,
|
|
496
604
|
items,
|
|
497
|
-
async (store) => {
|
|
605
|
+
batched(async (store) => {
|
|
498
606
|
const current = store.turn;
|
|
499
607
|
const id = current.id;
|
|
500
608
|
const root = await conversation();
|
|
@@ -565,7 +673,7 @@ export const withPi = async <T>(
|
|
|
565
673
|
const reply = entry?.model?.at(-1);
|
|
566
674
|
if (!reply) throw new restate.TerminalError(`prompt ${id}: no answer entry`);
|
|
567
675
|
return textOf(reply.content);
|
|
568
|
-
},
|
|
676
|
+
}),
|
|
569
677
|
// pi keeps the model's history: the conversation reads only its latest turns.
|
|
570
678
|
{ check, reminder, ownHistory: true },
|
|
571
679
|
);
|
|
@@ -587,6 +695,7 @@ export const withPi = async <T>(
|
|
|
587
695
|
// invocation's own (a retried attempt's) goes on.
|
|
588
696
|
const working = async () => {
|
|
589
697
|
await abortLeft((r) => invocationOf(r) === ctx.request.id || r.startsWith('steer:'));
|
|
698
|
+
if (batching) await database.flush();
|
|
590
699
|
return work({ harness, context, conversation, prompt });
|
|
591
700
|
};
|
|
592
701
|
try {
|