@trama-dev/runtime 0.5.0 → 0.6.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.
- package/dist/agent-backend.d.ts +127 -1
- package/dist/agent-backend.js +41 -2
- package/dist/agent-host.d.ts +50 -0
- package/dist/agent-host.js +97 -0
- package/dist/agent-hosts.d.ts +14 -0
- package/dist/agent-hosts.js +321 -0
- package/dist/agent.d.ts +10 -2
- package/dist/agent.js +85 -36
- package/dist/bridge-client.d.ts +6 -0
- package/dist/bridge-client.js +31 -8
- package/dist/budget.d.ts +52 -0
- package/dist/budget.js +118 -0
- package/dist/child-process.d.ts +18 -0
- package/dist/child-process.js +29 -0
- package/dist/client.d.ts +2 -2
- package/dist/client.js +4 -4
- package/dist/index.d.ts +3 -1
- package/dist/index.js +191 -56
- package/dist/ipc-server.d.ts +11 -2
- package/dist/ipc-server.js +104 -41
- package/dist/journal-view.d.ts +2 -0
- package/dist/journal-view.js +41 -4
- package/dist/journal.d.ts +12 -4
- package/dist/journal.js +7 -2
- package/dist/model-relay.d.ts +130 -0
- package/dist/model-relay.js +339 -0
- package/dist/pi-adapter.d.ts +34 -9
- package/dist/pi-adapter.js +857 -47
- package/dist/runner-types.d.ts +35 -0
- package/dist/runner.d.ts +190 -4
- package/dist/runner.js +652 -189
- package/dist/stopping.d.ts +33 -2
- package/dist/stopping.js +119 -11
- package/dist/tools.d.ts +2 -1
- package/dist/tools.js +52 -13
- package/dist/tree.d.ts +9 -2
- package/dist/tree.js +25 -3
- package/dist/types.d.ts +100 -12
- package/package.json +1 -1
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
// The runner's side of agent-host.ts: the processes that serve its agent
|
|
2
|
+
// calls with extensions, started as they are needed and kept while they can
|
|
3
|
+
// be used again.
|
|
4
|
+
//
|
|
5
|
+
// A host serves one call at a time. A call takes a host that is free, or
|
|
6
|
+
// starts one; when it has been answered the host is free again — pi is
|
|
7
|
+
// loaded once for the calls of a run that follow one another, and once for
|
|
8
|
+
// each that is made beside another. A call that is cancelled is asked to
|
|
9
|
+
// stop, as it is in the runner, and given the time anything asked to stop is
|
|
10
|
+
// given: a host that has not let go of it by then — its extension does not
|
|
11
|
+
// return, or goes round without end — is put an end to, with all it started.
|
|
12
|
+
// That is one call's failure. No other call was in that process.
|
|
13
|
+
import { fork } from "child_process";
|
|
14
|
+
import { fileURLToPath } from "url";
|
|
15
|
+
import { onAbort, throwIfAborted } from "./abort.js";
|
|
16
|
+
import { CutOff, addReply, atLeast, nothingYet } from "./agent-backend.js";
|
|
17
|
+
import { createModelRelay, relayClient, relayServer } from "./model-relay.js";
|
|
18
|
+
import { messageOf } from "./errors.js";
|
|
19
|
+
import { KILL_GRACE_MS, groupsUnder, requireWatchdog, stopGroups, stopWithThisProcess } from "./stopping.js";
|
|
20
|
+
const HOST = fileURLToPath(new URL("./agent-host.js", import.meta.url));
|
|
21
|
+
/**
|
|
22
|
+
* What a host said, if it is something a host says. The channel is the
|
|
23
|
+
* host's process's, and so is in the reach of whatever runs there — an
|
|
24
|
+
* extension, which may write to it by mistake (`process.send("ready")` is
|
|
25
|
+
* what many a library says to whatever started it) or on purpose. Anything
|
|
26
|
+
* that is not of the protocol is passed over: it is not for a word on the
|
|
27
|
+
* channel to fail a runner.
|
|
28
|
+
*/
|
|
29
|
+
function saidBy(message) {
|
|
30
|
+
if (typeof message !== "object" || message === null)
|
|
31
|
+
return undefined;
|
|
32
|
+
const said = message;
|
|
33
|
+
const counted = (usage) => typeof usage === "object" && usage !== null;
|
|
34
|
+
if (said.ready === true)
|
|
35
|
+
return { ready: true };
|
|
36
|
+
if (counted(said.sofar))
|
|
37
|
+
return { sofar: said.sofar, ...(said.answered === true && { answered: true }) };
|
|
38
|
+
if (counted(said.had))
|
|
39
|
+
return { had: said.had };
|
|
40
|
+
if (counted(said.used))
|
|
41
|
+
return { used: said.used };
|
|
42
|
+
if (typeof said.answer === "string")
|
|
43
|
+
return { answer: said.answer };
|
|
44
|
+
if (typeof said.cutOff === "string")
|
|
45
|
+
return { cutOff: said.cutOff };
|
|
46
|
+
if (typeof said.error === "string")
|
|
47
|
+
return { error: said.error };
|
|
48
|
+
// What a call would have a model asked, and what a model answered (see model-relay.ts).
|
|
49
|
+
const held = (value) => typeof value === "object" && value !== null;
|
|
50
|
+
const { relay, relayAbort, relayed } = said;
|
|
51
|
+
if (held(relay) && typeof relay.id === "number" && held(relay.request)) {
|
|
52
|
+
const { model, options } = relay.request;
|
|
53
|
+
if (held(model) && typeof model.provider === "string" && typeof model.id === "string" && held(options))
|
|
54
|
+
return { relay };
|
|
55
|
+
}
|
|
56
|
+
if (typeof relayAbort === "number")
|
|
57
|
+
return { relayAbort };
|
|
58
|
+
if (held(relayed) && typeof relayed.id === "number" && (relayed.not === true || (held(relayed.event) && typeof relayed.event.type === "string")))
|
|
59
|
+
return { relayed };
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
/** Of a call, what can be sent to another process. */
|
|
63
|
+
const sendable = ({ signal: _signal, used: _used, sofar: _sofar, had: _had, relay: _relay, ...call }) => call;
|
|
64
|
+
/**
|
|
65
|
+
* The hosts of one runner's calls. `env`: variables the hosts are started
|
|
66
|
+
* with, over this process's own — a run's, whose agents are then that run's
|
|
67
|
+
* in what they find of pi, of a provider's key, and in the commands they run.
|
|
68
|
+
*/
|
|
69
|
+
export function createAgentHosts(env) {
|
|
70
|
+
/** The hosts that are there: those serving a call, and those free to serve one. */
|
|
71
|
+
const all = new Set(), free = [];
|
|
72
|
+
/** Put an end to a host, and to what it has under it. Resolves when they are gone. */
|
|
73
|
+
const end = async (host) => {
|
|
74
|
+
// Whoever waits for a host to be gone is held until it is seen to be. (A free host keeps nobody waiting —
|
|
75
|
+
// see `release` — and a process held by nothing else would end in the middle of this wait, well and without
|
|
76
|
+
// a word, the moment the host's group was gone and before the host was seen to end: whatever was to come
|
|
77
|
+
// after — a run's failure said, its exit code — would not.)
|
|
78
|
+
host.process.ref();
|
|
79
|
+
if (!host.gone) {
|
|
80
|
+
host.gone = true;
|
|
81
|
+
const at = free.indexOf(host);
|
|
82
|
+
if (at !== -1)
|
|
83
|
+
free.splice(at, 1);
|
|
84
|
+
// (Its process leads a group of its own; what it started in groups of their own is looked for first, while it is there to be asked of.)
|
|
85
|
+
const { pid } = host.process;
|
|
86
|
+
if (pid !== undefined)
|
|
87
|
+
host.stopped = groupsUnder(pid).then(groups => stopGroups([pid, ...groups]));
|
|
88
|
+
}
|
|
89
|
+
await Promise.all([host.ended, host.stopped]);
|
|
90
|
+
};
|
|
91
|
+
const start = () => {
|
|
92
|
+
// If this process ends while a host is there, the watchdog stops the host — with what it has under it.
|
|
93
|
+
requireWatchdog();
|
|
94
|
+
let child;
|
|
95
|
+
try {
|
|
96
|
+
child = fork(HOST, [], { detached: true, stdio: ["ignore", "inherit", "inherit", "ipc"], execArgv: [], ...(env && { env: { ...process.env, ...env } }) });
|
|
97
|
+
}
|
|
98
|
+
catch (err) {
|
|
99
|
+
// (What the system refuses at once — more variables than a process can be handed — is said as what is found out later is.)
|
|
100
|
+
throw new Error(`The agent's process could not be started: ${messageOf(err)}`);
|
|
101
|
+
}
|
|
102
|
+
const watched = child.pid !== undefined ? stopWithThisProcess(child.pid, true) : () => { };
|
|
103
|
+
const host = {
|
|
104
|
+
process: child,
|
|
105
|
+
gone: false,
|
|
106
|
+
ready: new Promise((resolve, reject) => {
|
|
107
|
+
const there = (message) => {
|
|
108
|
+
const said = saidBy(message);
|
|
109
|
+
if (!said || !("ready" in said))
|
|
110
|
+
return;
|
|
111
|
+
child.off("message", there);
|
|
112
|
+
resolve();
|
|
113
|
+
};
|
|
114
|
+
child.on("message", there);
|
|
115
|
+
child.once("error", (err) => reject(new Error(`The agent's process could not be started: ${err.message}`)));
|
|
116
|
+
child.once("exit", (code, signal) => reject(new Error(`The agent's process ended as it started (${signal ?? `exit code ${code}`}).`)));
|
|
117
|
+
}),
|
|
118
|
+
ended: new Promise((resolve) => {
|
|
119
|
+
const over = () => {
|
|
120
|
+
host.gone = true;
|
|
121
|
+
all.delete(host);
|
|
122
|
+
const at = free.indexOf(host);
|
|
123
|
+
if (at !== -1)
|
|
124
|
+
free.splice(at, 1);
|
|
125
|
+
watched();
|
|
126
|
+
resolve();
|
|
127
|
+
};
|
|
128
|
+
child.once("exit", over);
|
|
129
|
+
child.once("error", over);
|
|
130
|
+
}),
|
|
131
|
+
};
|
|
132
|
+
// (A host that ends before it was there is found out by whoever waits for it: nothing is thrown at nobody.)
|
|
133
|
+
host.ready.catch(() => { });
|
|
134
|
+
all.add(host);
|
|
135
|
+
return host;
|
|
136
|
+
};
|
|
137
|
+
/**
|
|
138
|
+
* Who asks the models of the calls these hosts serve (see model-relay.ts).
|
|
139
|
+
* Where the hosts are this process's own in all but being apart, that is
|
|
140
|
+
* this process: with its pi, and the keys it has. Where they were started
|
|
141
|
+
* with variables — a run's, which may name another pi and other keys — it
|
|
142
|
+
* is a process started with the same, that serves no call and so has
|
|
143
|
+
* nobody's code in it but pi's and trama's: started when it is first
|
|
144
|
+
* wanted, and again if it was lost.
|
|
145
|
+
*/
|
|
146
|
+
let asker;
|
|
147
|
+
const apart = {
|
|
148
|
+
async ask(request, signal) {
|
|
149
|
+
try {
|
|
150
|
+
if (!asker || asker.host.gone) {
|
|
151
|
+
const host = start();
|
|
152
|
+
const child = host.process;
|
|
153
|
+
// (It keeps nobody waiting: a call that has asked by it is waited for by its own host.)
|
|
154
|
+
child.unref();
|
|
155
|
+
child.channel?.unref();
|
|
156
|
+
const asks = relayClient((message) => { if (child.connected)
|
|
157
|
+
child.send(message, () => { }); });
|
|
158
|
+
child.on("message", (word) => {
|
|
159
|
+
const said = saidBy(word);
|
|
160
|
+
if (said && "relayed" in said)
|
|
161
|
+
asks.heard(said.relayed);
|
|
162
|
+
});
|
|
163
|
+
child.once("exit", () => asks.close());
|
|
164
|
+
asker = { host, asks };
|
|
165
|
+
}
|
|
166
|
+
const { host, asks } = asker;
|
|
167
|
+
await host.ready;
|
|
168
|
+
return await asks.relay.ask(request, signal);
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
// (A process that cannot be had is not one to ask by: whoever asked asks itself.)
|
|
172
|
+
return undefined;
|
|
173
|
+
}
|
|
174
|
+
},
|
|
175
|
+
};
|
|
176
|
+
return {
|
|
177
|
+
async ask(config, prompt, call) {
|
|
178
|
+
throwIfAborted(call.signal);
|
|
179
|
+
const host = free.pop() ?? start();
|
|
180
|
+
const child = host.process;
|
|
181
|
+
// (While it serves a call it is this process's to wait for; free, it keeps nobody waiting.)
|
|
182
|
+
child.ref();
|
|
183
|
+
child.channel?.ref();
|
|
184
|
+
/** The host goes back among the free ones: it has answered, or was never asked. */
|
|
185
|
+
const release = () => {
|
|
186
|
+
kept = true;
|
|
187
|
+
child.unref();
|
|
188
|
+
child.channel?.unref();
|
|
189
|
+
free.push(host);
|
|
190
|
+
};
|
|
191
|
+
let kept = false;
|
|
192
|
+
try {
|
|
193
|
+
await host.ready;
|
|
194
|
+
return await new Promise((resolve, reject) => {
|
|
195
|
+
let giveUp, offAbort = () => { }, isOver = false;
|
|
196
|
+
// What the call last said it had used, and whether it has said what it used in the end.
|
|
197
|
+
let last, usedSaid = false;
|
|
198
|
+
// What the replies used that the call's model was asked for from here: seen come, and nobody's word.
|
|
199
|
+
// A count the host says is taken for no less than that.
|
|
200
|
+
const seen = nothingYet();
|
|
201
|
+
// How many replies were seen, and how many had been when the call was last told what it had used;
|
|
202
|
+
// and whether whoever was told has said, of the call when it was over, that nothing more may be asked
|
|
203
|
+
// on its account. (Said of a call still at its work, a no stops nothing: such a call is stopped by
|
|
204
|
+
// being cancelled — see AgentCall.sofar. Here as where the call is served.)
|
|
205
|
+
let replies = 0, told = 0, noMore = false;
|
|
206
|
+
let asksHere;
|
|
207
|
+
let asked;
|
|
208
|
+
const asking = () => asked ??= relayServer(env ? apart : asksHere = createModelRelay(), (answer) => { if (child.connected)
|
|
209
|
+
child.send(answer, () => { }); }, {
|
|
210
|
+
// A model is not asked for a call that has not been told of all it was seen to use: the host says
|
|
211
|
+
// what the call has used before each request (below) — and where a request comes that it did not
|
|
212
|
+
// say that before, the call is told from here (as of a call that is over, where the request
|
|
213
|
+
// says it is asked beside one). A no to such a request is a no from then on, whatever is asked
|
|
214
|
+
// after and whatever it says of itself. And a call that is cancelled, or done with, has its model
|
|
215
|
+
// asked no more, whatever in its host would have it asked.
|
|
216
|
+
async refuse(request) {
|
|
217
|
+
if (!noMore && replies !== told) {
|
|
218
|
+
told = replies;
|
|
219
|
+
const sofar = atLeast(last, seen), answered = request.answered === true;
|
|
220
|
+
if (sofar && await call.sofar?.(sofar, answered) === false && answered)
|
|
221
|
+
noMore = true;
|
|
222
|
+
}
|
|
223
|
+
return noMore || isOver || call.signal?.aborted === true;
|
|
224
|
+
},
|
|
225
|
+
replied(used) {
|
|
226
|
+
addReply(seen, used);
|
|
227
|
+
replies += 1;
|
|
228
|
+
const had = atLeast(last, seen);
|
|
229
|
+
if (had)
|
|
230
|
+
call.had?.(had);
|
|
231
|
+
},
|
|
232
|
+
});
|
|
233
|
+
/** The call is over: by an answer of the host's, which is then free again — or without one, and the host is ended. */
|
|
234
|
+
const over = (settle, hostIsWell) => {
|
|
235
|
+
if (isOver)
|
|
236
|
+
return;
|
|
237
|
+
isOver = true;
|
|
238
|
+
offAbort();
|
|
239
|
+
clearTimeout(giveUp);
|
|
240
|
+
child.off("message", heard);
|
|
241
|
+
child.off("exit", exited);
|
|
242
|
+
asked?.close();
|
|
243
|
+
void asksHere?.close();
|
|
244
|
+
if (hostIsWell && !host.gone)
|
|
245
|
+
release();
|
|
246
|
+
// A host that is ended with a call in it never says what the call used in the end: what
|
|
247
|
+
// it last said the call had used — and what was seen of it here — is then all that is
|
|
248
|
+
// known of it, and what the call is taken to have used. (And a host that is well and
|
|
249
|
+
// says nothing, of a call whose model was asked from here, is not taken at its silence.)
|
|
250
|
+
if (!usedSaid) {
|
|
251
|
+
const used = atLeast(last, seen);
|
|
252
|
+
if (used)
|
|
253
|
+
call.used?.(used);
|
|
254
|
+
}
|
|
255
|
+
settle();
|
|
256
|
+
};
|
|
257
|
+
const heard = (word) => {
|
|
258
|
+
const message = saidBy(word);
|
|
259
|
+
if (!message)
|
|
260
|
+
return;
|
|
261
|
+
if ("relay" in message || "relayAbort" in message)
|
|
262
|
+
return asking().heard(message);
|
|
263
|
+
if ("sofar" in message) {
|
|
264
|
+
const sofar = atLeast(last = message.sofar, seen);
|
|
265
|
+
told = replies;
|
|
266
|
+
// The host waits to hear whether the call is to go on — or, of a call that has its answer, whether
|
|
267
|
+
// what would be asked beside it may be. (Where hearing what it used cancelled the call, the host
|
|
268
|
+
// has been told that first, below: this then tells it nothing.)
|
|
269
|
+
void Promise.resolve(sofar && call.sofar?.(sofar, message.answered === true)).then((go) => {
|
|
270
|
+
if (go === false && message.answered === true)
|
|
271
|
+
noMore = true;
|
|
272
|
+
if (!isOver && child.connected)
|
|
273
|
+
child.send({ go: go !== false }, () => { });
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
else if ("had" in message) {
|
|
277
|
+
const had = atLeast(last = message.had, seen);
|
|
278
|
+
if (had)
|
|
279
|
+
call.had?.(had);
|
|
280
|
+
}
|
|
281
|
+
else if ("used" in message) {
|
|
282
|
+
usedSaid = true;
|
|
283
|
+
const used = atLeast(message.used, seen);
|
|
284
|
+
if (used)
|
|
285
|
+
call.used?.(used);
|
|
286
|
+
}
|
|
287
|
+
else if ("answer" in message)
|
|
288
|
+
over(() => resolve(message.answer), true);
|
|
289
|
+
else if ("cutOff" in message)
|
|
290
|
+
over(() => reject(new CutOff(message.cutOff)), true);
|
|
291
|
+
else if ("error" in message)
|
|
292
|
+
over(() => reject(new Error(message.error)), true);
|
|
293
|
+
};
|
|
294
|
+
const exited = (code, signal) => over(() => reject(new Error(`The agent's process ended before it had answered (${signal ?? `exit code ${code}`}): the call was not finished.`)), false);
|
|
295
|
+
child.on("message", heard);
|
|
296
|
+
child.once("exit", exited);
|
|
297
|
+
child.send({ ask: { config, prompt, call: sendable(call) } }, (err) => {
|
|
298
|
+
if (err)
|
|
299
|
+
over(() => reject(new Error(`The agent's process could not be asked: ${err.message}`)), false);
|
|
300
|
+
});
|
|
301
|
+
// A cancelled call is asked to stop where it is, and waited for no longer than anything asked to stop is.
|
|
302
|
+
offAbort = onAbort(call.signal, () => {
|
|
303
|
+
// (What its model is being asked from here is asked no further, whether or not its host hears.)
|
|
304
|
+
asked?.close();
|
|
305
|
+
if (child.connected)
|
|
306
|
+
child.send({ abort: true }, () => { });
|
|
307
|
+
giveUp = setTimeout(() => over(() => reject(new Error("Aborted")), false), KILL_GRACE_MS);
|
|
308
|
+
});
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
finally {
|
|
312
|
+
// (A host that did not answer — it never came to be there, it ended, it would not let go — is not one to keep.)
|
|
313
|
+
if (!kept)
|
|
314
|
+
void end(host);
|
|
315
|
+
}
|
|
316
|
+
},
|
|
317
|
+
async close() {
|
|
318
|
+
await Promise.all([...all].map(end));
|
|
319
|
+
},
|
|
320
|
+
};
|
|
321
|
+
}
|
package/dist/agent.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Agent } from "./types.js";
|
|
2
|
-
import type
|
|
2
|
+
import { type AgentBackend, type AgentCall } from "./agent-backend.js";
|
|
3
3
|
/**
|
|
4
4
|
* The program in an LLM reply that was asked to contain nothing else: the last
|
|
5
5
|
* fenced block if there is one (models add explanations, or show a "before"
|
|
@@ -21,8 +21,16 @@ import type { AgentBackend } from "./agent-backend.js";
|
|
|
21
21
|
* and the validation that follows says so.
|
|
22
22
|
*/
|
|
23
23
|
export declare function stripCodeFences(text: string): string;
|
|
24
|
+
/** Hears what a call used — each time its backend was asked: a `generate` that had to ask again is heard twice. */
|
|
25
|
+
type Used = AgentCall["used"];
|
|
26
|
+
/** The runner's side of a program's `agent`: its calls, and for each a place to say what it used. */
|
|
27
|
+
export interface RunnerAgent {
|
|
28
|
+
instruct(prompt: string, options?: Parameters<Agent["instruct"]>[1], used?: Used): Promise<string>;
|
|
29
|
+
generate<T>(input: Parameters<Agent["generate"]>[0], used?: Used): Promise<T>;
|
|
30
|
+
}
|
|
24
31
|
/**
|
|
25
32
|
* The `agent` a program talks to: its calls, served by `backend` working in
|
|
26
33
|
* `cwd`, and cancelled together through `signal`.
|
|
27
34
|
*/
|
|
28
|
-
export declare function createAgent(backend: AgentBackend, cwd: string, signal?: AbortSignal):
|
|
35
|
+
export declare function createAgent(backend: AgentBackend, cwd: string, signal?: AbortSignal): RunnerAgent;
|
|
36
|
+
export {};
|
package/dist/agent.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { CutOff } from "./agent-backend.js";
|
|
1
2
|
import { isJsonObject } from "./serializable.js";
|
|
2
3
|
const NAMED = /[\w.+#-]*\s*\n/y;
|
|
3
4
|
/** The fences of a text, in the order they stand in. */
|
|
@@ -81,55 +82,103 @@ export function stripCodeFences(text) {
|
|
|
81
82
|
}
|
|
82
83
|
return last ?? reply;
|
|
83
84
|
}
|
|
84
|
-
const
|
|
85
|
+
const SCHEMA_PRIMITIVES = new Set(["string", "number", "boolean"]);
|
|
86
|
+
/** How the two shapes that are not named in a word are written, for whoever named them in one. */
|
|
87
|
+
const HOW_WRITTEN = `a list is written as the shape of its items, in brackets: ["string"]; an object as its fields: { name: "string" }`;
|
|
88
|
+
const fieldOf = (where, key) => (where === null ? key : `${where}.${key}`);
|
|
85
89
|
/**
|
|
86
|
-
*
|
|
87
|
-
*
|
|
90
|
+
* Read the caller's schema declaration, up front: what the value at `where`
|
|
91
|
+
* is to be. In words — "string", "number", "boolean", where what follows a
|
|
92
|
+
* ":" describes the value to the model and is not read here — or an object
|
|
93
|
+
* of such, or a list of one element: the shape of every item.
|
|
88
94
|
*/
|
|
89
|
-
function
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
if (typeof typeDesc !== "string" || !SUPPORTED_SCHEMA_TYPES.has(expectedType)) {
|
|
94
|
-
throw new Error(`Schema validation failed: unsupported schema type "${expectedType}" for key "${key}"`);
|
|
95
|
+
function shapeOf(declared, where) {
|
|
96
|
+
if (Array.isArray(declared)) {
|
|
97
|
+
if (declared.length !== 1) {
|
|
98
|
+
throw new Error(`Schema validation failed: the list at "${where}" is written with ${declared.length} elements — it takes one, the shape of every item`);
|
|
95
99
|
}
|
|
96
|
-
return [
|
|
97
|
-
}
|
|
100
|
+
return { items: shapeOf(declared[0], `${where}[]`) };
|
|
101
|
+
}
|
|
102
|
+
if (isJsonObject(declared)) {
|
|
103
|
+
return { fields: Object.entries(declared).map(([key, value]) => [key, shapeOf(value, fieldOf(where, key))]) };
|
|
104
|
+
}
|
|
105
|
+
// (Anything else says nothing that is supported — and is said back as JSON would write it, which is no word for a kind.)
|
|
106
|
+
const named = typeof declared === "string" ? declared.split(":")[0].trim() : JSON.stringify(declared);
|
|
107
|
+
if (!SCHEMA_PRIMITIVES.has(named)) {
|
|
108
|
+
throw new Error(`Schema validation failed: unsupported schema type "${named}" for key "${where}" (${HOW_WRITTEN})`);
|
|
109
|
+
}
|
|
110
|
+
return named;
|
|
98
111
|
}
|
|
112
|
+
const hasList = (shape) => typeof shape !== "string" && ("items" in shape || shape.fields.some(([, field]) => hasList(field)));
|
|
113
|
+
/** What a value is, said as a reply is told of it. */
|
|
114
|
+
const said = (value) => value === null ? "null" : Array.isArray(value) ? "a list" : typeof value === "number" ? String(value) : typeof value;
|
|
99
115
|
/**
|
|
100
|
-
*
|
|
101
|
-
*
|
|
116
|
+
* Shape validation and projection: verifies that the value at `where` is of
|
|
117
|
+
* the shape declared — every field there, every item of a list — and returns
|
|
118
|
+
* it holding the declared fields and no others.
|
|
102
119
|
*/
|
|
103
|
-
function
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
}
|
|
115
|
-
picked[key] = val;
|
|
120
|
+
function conform(value, shape, where) {
|
|
121
|
+
const mismatch = (expected) => new Error(`Schema validation failed: ${where}: expected ${expected}, got ${said(value)}`);
|
|
122
|
+
if (typeof shape === "string") {
|
|
123
|
+
if (typeof value !== shape || (shape === "number" && !Number.isFinite(value)))
|
|
124
|
+
throw mismatch(shape);
|
|
125
|
+
return value;
|
|
126
|
+
}
|
|
127
|
+
if ("items" in shape) {
|
|
128
|
+
if (!Array.isArray(value))
|
|
129
|
+
throw mismatch("a list");
|
|
130
|
+
return value.map((item, index) => conform(item, shape.items, `${where}[${index}]`));
|
|
116
131
|
}
|
|
117
|
-
|
|
132
|
+
if (!isJsonObject(value))
|
|
133
|
+
throw where === null ? new Error("Schema validation failed: response is not an object") : mismatch("an object");
|
|
134
|
+
return Object.fromEntries(shape.fields.map(([key, field]) => {
|
|
135
|
+
// (A field is the reply's own: what every object has by birth is not something a reply said.)
|
|
136
|
+
if (!Object.hasOwn(value, key))
|
|
137
|
+
throw new Error(`Schema validation failed: missing key: ${fieldOf(where, key)}`);
|
|
138
|
+
return [key, conform(value[key], field, fieldOf(where, key))];
|
|
139
|
+
}));
|
|
118
140
|
}
|
|
141
|
+
/** Of what a call may ask for, what it did ask for: a backend is not handed a thing nobody named. */
|
|
142
|
+
const asked = (options) => Object.fromEntries(Object.entries(options).filter(([, value]) => value !== undefined));
|
|
119
143
|
/**
|
|
120
144
|
* The `agent` a program talks to: its calls, served by `backend` working in
|
|
121
145
|
* `cwd`, and cancelled together through `signal`.
|
|
122
146
|
*/
|
|
123
147
|
export function createAgent(backend, cwd, signal) {
|
|
148
|
+
/**
|
|
149
|
+
* Ask the backend — and of a reply that was cut off at the output limit,
|
|
150
|
+
* make what the call said to make of it: its failure, unless the call
|
|
151
|
+
* keeps such a reply, and there is something of it to keep.
|
|
152
|
+
*/
|
|
153
|
+
const ask = async (prompt, call, cutOff) => {
|
|
154
|
+
if (cutOff !== undefined && cutOff !== "fail" && cutOff !== "keep") {
|
|
155
|
+
throw new Error(`cutOff is "fail" or "keep", not ${JSON.stringify(cutOff)}`);
|
|
156
|
+
}
|
|
157
|
+
try {
|
|
158
|
+
return await backend.ask(prompt, call);
|
|
159
|
+
}
|
|
160
|
+
catch (err) {
|
|
161
|
+
if (cutOff === "keep" && err instanceof CutOff && err.text !== "")
|
|
162
|
+
return err.text;
|
|
163
|
+
throw err;
|
|
164
|
+
}
|
|
165
|
+
};
|
|
124
166
|
return {
|
|
125
|
-
async instruct(prompt, options) {
|
|
126
|
-
|
|
167
|
+
async instruct(prompt, options, used) {
|
|
168
|
+
const { system, model, thinking, tools, skills, templates, extensions, cutOff } = options ?? {};
|
|
169
|
+
return ask(prompt, { cwd, system, signal, ...asked({ model, thinking, tools, skills, templates, extensions, used }) }, cutOff);
|
|
127
170
|
},
|
|
128
|
-
async generate(input) {
|
|
129
|
-
|
|
130
|
-
|
|
171
|
+
async generate(input, used) {
|
|
172
|
+
if (!isJsonObject(input.schema))
|
|
173
|
+
throw new Error("Schema validation failed: a schema is an object of the fields the answer is to have");
|
|
174
|
+
const shape = shapeOf(input.schema, null);
|
|
175
|
+
const schemaInstruction = `Respond with ONLY a JSON object matching this shape:\n${JSON.stringify(input.schema, null, 2)}\n${hasList(shape) ? "Where the shape shows a list, it shows one item: answer with as many as there are, each of that shape.\n" : ""}No markdown. No explanation. Just the JSON.`;
|
|
131
176
|
const fullPrompt = `${input.prompt}\n\n${schemaInstruction}`;
|
|
132
|
-
const
|
|
177
|
+
const { system, model, thinking, tools, skills, extensions, cutOff } = input;
|
|
178
|
+
// The prompt of a typed answer is text, whatever it begins with: what says how to answer follows it, and a
|
|
179
|
+
// skill called up by name, or a command, would take that for its own — and would not be there at a second asking.
|
|
180
|
+
const asText = skills !== undefined || extensions !== undefined ? true : undefined;
|
|
181
|
+
const call = { cwd, system, signal, ...asked({ model, thinking, tools, skills, extensions, asText, used }) };
|
|
133
182
|
const parseAndValidate = (response) => {
|
|
134
183
|
const trimmed = response.trim();
|
|
135
184
|
// Try raw parse first — avoids mangling valid JSON that contains
|
|
@@ -142,17 +191,17 @@ export function createAgent(backend, cwd, signal) {
|
|
|
142
191
|
const fenceMatch = trimmed.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);
|
|
143
192
|
parsed = JSON.parse(fenceMatch ? fenceMatch[1].trim() : trimmed);
|
|
144
193
|
}
|
|
145
|
-
return
|
|
194
|
+
return conform(parsed, shape, null);
|
|
146
195
|
};
|
|
147
196
|
// First attempt — backend errors (network/auth) propagate immediately.
|
|
148
197
|
// Only parse/validation failures trigger a retry.
|
|
149
|
-
const response = await
|
|
198
|
+
const response = await ask(fullPrompt, call, cutOff);
|
|
150
199
|
try {
|
|
151
200
|
return parseAndValidate(response);
|
|
152
201
|
}
|
|
153
202
|
catch (firstError) {
|
|
154
203
|
const retryPrompt = `Your previous response failed validation: ${firstError}.\nTry again.\n\n${fullPrompt}`;
|
|
155
|
-
const retryResponse = await
|
|
204
|
+
const retryResponse = await ask(retryPrompt, call, cutOff);
|
|
156
205
|
return parseAndValidate(retryResponse);
|
|
157
206
|
}
|
|
158
207
|
}
|
package/dist/bridge-client.d.ts
CHANGED
|
@@ -5,6 +5,12 @@ export interface Bridge {
|
|
|
5
5
|
/** POST one call to the runner and return its result. */
|
|
6
6
|
call(endpoint: string, body: unknown): Promise<any>;
|
|
7
7
|
}
|
|
8
|
+
/**
|
|
9
|
+
* The body of a call that takes options: what the call is made with, and the
|
|
10
|
+
* options beside it. An option that bears the name of one of those is not an
|
|
11
|
+
* option — and would otherwise take its place.
|
|
12
|
+
*/
|
|
13
|
+
export declare function withOptions(madeWith: Record<string, unknown>, options?: object | null): Record<string, unknown>;
|
|
8
14
|
/**
|
|
9
15
|
* @param port - the runner's loopback port (TRAMA_PORT)
|
|
10
16
|
* @param initPath - the file the runner wrote for this program (TRAMA_INIT)
|
package/dist/bridge-client.js
CHANGED
|
@@ -1,24 +1,46 @@
|
|
|
1
1
|
// The program's end of the IPC bridge: how code running inside a program
|
|
2
2
|
// reaches the runner that started it (ipc-server.ts is the other end).
|
|
3
3
|
import { readFileSync } from "fs";
|
|
4
|
-
import { request } from "http";
|
|
4
|
+
import { Agent, request } from "http";
|
|
5
5
|
import { messageOf } from "./errors.js";
|
|
6
6
|
let cached;
|
|
7
|
+
/**
|
|
8
|
+
* How calls reach the runner: straight to it. Not by way of a proxy that the
|
|
9
|
+
* program's environment names for its HTTP — which node's own agent would
|
|
10
|
+
* take, and hand the call, with the bridge's secret, to. (Otherwise as node's
|
|
11
|
+
* own agent is.)
|
|
12
|
+
*/
|
|
13
|
+
const direct = new Agent({ keepAlive: true, scheduling: "lifo", timeout: 5000 });
|
|
7
14
|
/**
|
|
8
15
|
* A call's body as it goes over the bridge. JSON has no way to say NaN or
|
|
9
|
-
* Infinity: it writes null for them
|
|
10
|
-
*
|
|
11
|
-
* carried out as it was made, or not
|
|
16
|
+
* Infinity, a function or a symbol: it writes null for them or leaves them
|
|
17
|
+
* out, which the other end reads as a field that was not given. So what it
|
|
18
|
+
* cannot carry is refused here — a call is carried out as it was made, or not
|
|
19
|
+
* at all.
|
|
12
20
|
*/
|
|
13
21
|
function encode(endpoint, body) {
|
|
14
22
|
return JSON.stringify(body, function (name, value) {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
23
|
+
const lost = typeof value === "number" && !Number.isFinite(value) ? String(value)
|
|
24
|
+
: typeof value === "function" || typeof value === "symbol" ? `a ${typeof value}`
|
|
25
|
+
: undefined;
|
|
26
|
+
if (lost !== undefined) {
|
|
27
|
+
const where = Array.isArray(this) ? `item ${name} of a list` : name || "what the call is made with";
|
|
28
|
+
throw new TypeError(`${where} is ${lost}, which cannot be sent to the runner (${endpoint})`);
|
|
18
29
|
}
|
|
19
30
|
return value;
|
|
20
31
|
});
|
|
21
32
|
}
|
|
33
|
+
/**
|
|
34
|
+
* The body of a call that takes options: what the call is made with, and the
|
|
35
|
+
* options beside it. An option that bears the name of one of those is not an
|
|
36
|
+
* option — and would otherwise take its place.
|
|
37
|
+
*/
|
|
38
|
+
export function withOptions(madeWith, options) {
|
|
39
|
+
const taken = Object.keys(options ?? {}).find(name => Object.hasOwn(madeWith, name));
|
|
40
|
+
if (taken !== undefined)
|
|
41
|
+
throw new TypeError(`${taken} is what the call is made with, and cannot be given as an option`);
|
|
42
|
+
return { ...madeWith, ...options };
|
|
43
|
+
}
|
|
22
44
|
/**
|
|
23
45
|
* @param port - the runner's loopback port (TRAMA_PORT)
|
|
24
46
|
* @param initPath - the file the runner wrote for this program (TRAMA_INIT)
|
|
@@ -38,6 +60,7 @@ export function openBridge(port, initPath) {
|
|
|
38
60
|
port,
|
|
39
61
|
path: endpoint,
|
|
40
62
|
method: "POST",
|
|
63
|
+
agent: direct,
|
|
41
64
|
headers: {
|
|
42
65
|
"Content-Type": "application/json",
|
|
43
66
|
"Content-Length": Buffer.byteLength(payload),
|
|
@@ -96,6 +119,6 @@ export function remoteWorkspace(call, dir) {
|
|
|
96
119
|
read: (path) => call("/workspace/read", { dir, path }),
|
|
97
120
|
write: (path, content) => call("/workspace/write", { dir, path, content }),
|
|
98
121
|
list: (pattern) => call("/workspace/list", { dir, pattern }),
|
|
99
|
-
observe: (pattern, options) => call("/workspace/observe", { dir, pattern,
|
|
122
|
+
observe: async (pattern, options) => call("/workspace/observe", withOptions({ dir, pattern }, options)),
|
|
100
123
|
};
|
|
101
124
|
}
|
package/dist/budget.d.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { AgentUsage } from "./agent-backend.js";
|
|
2
|
+
/** A cap on what is asked of a model. What is not named is not capped. */
|
|
3
|
+
export interface Budget {
|
|
4
|
+
/** US dollars, as the backend's price list counts what was used. */
|
|
5
|
+
cost?: number;
|
|
6
|
+
/** Tokens: all the model read and wrote, from a cache or not. */
|
|
7
|
+
tokens?: number;
|
|
8
|
+
/**
|
|
9
|
+
* How many calls to a model's agent may be taken on: an agent call is one,
|
|
10
|
+
* a `generate` that had to ask again two, a request for a fix one. (A call
|
|
11
|
+
* counts when it is taken on, whatever then becomes of it.)
|
|
12
|
+
*/
|
|
13
|
+
calls?: number;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* A budget as it was given — in a config, to a run, over the bridge — held to
|
|
17
|
+
* what one is: a plain object of caps, each a number that is not negative,
|
|
18
|
+
* and `calls` a whole one. Returns a copy. Throws with what is wrong, as said
|
|
19
|
+
* of `what` it was given as.
|
|
20
|
+
*/
|
|
21
|
+
export declare function checkedBudget(given: unknown, what?: string): Budget;
|
|
22
|
+
/** What is counted of one call to a backend, while it lasts. */
|
|
23
|
+
export interface Account {
|
|
24
|
+
/**
|
|
25
|
+
* What the call has used by now, in all. Returns why the call is to go no
|
|
26
|
+
* further — a budget it counts in has been reached — or nothing.
|
|
27
|
+
*/
|
|
28
|
+
sofar(usage: AgentUsage): string | undefined;
|
|
29
|
+
/** The call is over: what it used is what was last said of it, and what is said of it from here on is counted nowhere. */
|
|
30
|
+
close(): void;
|
|
31
|
+
}
|
|
32
|
+
export interface Meter {
|
|
33
|
+
/** The caps it holds a run to, as they were given. */
|
|
34
|
+
readonly limit: Budget;
|
|
35
|
+
/** Whether it holds what it counts to anything: a cap of its own, or of a meter above. */
|
|
36
|
+
capped(): boolean;
|
|
37
|
+
/** Why nothing more may be asked of a model under it — or nothing, while something may. */
|
|
38
|
+
spent(): string | undefined;
|
|
39
|
+
/** Take on a call to a backend. Throws, with why, where nothing more may be asked. */
|
|
40
|
+
admit(): Account;
|
|
41
|
+
/** Why what is under way is to go no further: a cap on what calls use has been reached, here or above. */
|
|
42
|
+
reached(): string | undefined;
|
|
43
|
+
/** Add to the count, here and above: calls taken on, and what calls used — more than was said of them before, or less. */
|
|
44
|
+
count(calls: number, cost: number, tokens: number): void;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The count of what a run uses, held to `limit`. What it counts is counted
|
|
48
|
+
* under `above` too — the meter of the run that asked for this one — and is
|
|
49
|
+
* refused where that has no room: a run cannot use what the run it is part of
|
|
50
|
+
* may not.
|
|
51
|
+
*/
|
|
52
|
+
export declare function createMeter(limit?: Budget, above?: Meter): Meter;
|