@trama-dev/runtime 0.4.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/README.md +4 -3
- package/dist/abort.d.ts +12 -0
- package/dist/abort.js +31 -0
- package/dist/agent-backend.d.ts +127 -7
- package/dist/agent-backend.js +38 -19
- 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 +26 -3
- package/dist/agent.js +165 -43
- package/dist/bridge-client.d.ts +6 -0
- package/dist/bridge-client.js +69 -16
- 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 +38 -9
- package/dist/client.d.ts +2 -1
- package/dist/client.js +9 -19
- package/dist/context.d.ts +36 -7
- package/dist/context.js +83 -92
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +2 -0
- package/dist/index.d.ts +7 -2
- package/dist/index.js +254 -88
- package/dist/ipc-server.d.ts +14 -5
- package/dist/ipc-server.js +174 -144
- package/dist/journal-view.d.ts +2 -0
- package/dist/journal-view.js +52 -7
- package/dist/journal.d.ts +27 -9
- package/dist/journal.js +216 -79
- package/dist/meta.d.ts +18 -0
- package/dist/meta.js +29 -0
- package/dist/model-relay.d.ts +130 -0
- package/dist/model-relay.js +339 -0
- package/dist/path-guard.d.ts +128 -19
- package/dist/path-guard.js +384 -68
- package/dist/pi-adapter.d.ts +35 -9
- package/dist/pi-adapter.js +865 -66
- package/dist/replace-file.d.ts +31 -0
- package/dist/replace-file.js +75 -0
- package/dist/runner-types.d.ts +35 -0
- package/dist/runner.d.ts +202 -30
- package/dist/runner.js +949 -273
- package/dist/serializable.d.ts +10 -4
- package/dist/serializable.js +56 -31
- package/dist/stopping.d.ts +37 -3
- package/dist/stopping.js +167 -21
- package/dist/tools.d.ts +2 -1
- package/dist/tools.js +90 -21
- package/dist/tree.d.ts +241 -0
- package/dist/tree.js +1431 -0
- package/dist/types.d.ts +106 -15
- package/dist/workspace.d.ts +7 -0
- package/dist/workspace.js +93 -104
- 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,13 +1,36 @@
|
|
|
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"
|
|
6
|
-
* first), otherwise the whole
|
|
6
|
+
* first), otherwise the whole text.
|
|
7
|
+
*
|
|
8
|
+
* A program may hold fences of its own, in a comment. So a reply in which
|
|
9
|
+
* every fence stands in a comment was not fenced at all; and a block ends at
|
|
10
|
+
* the first closing fence, of backticks enough, that does not stand in a
|
|
11
|
+
* comment of the block — or, if there is none such (the block is no program,
|
|
12
|
+
* its comment never ends, it was opened with more backticks than it is
|
|
13
|
+
* closed with), at the first closing fence there is.
|
|
14
|
+
*
|
|
15
|
+
* What this still takes wrongly, where the plain reading would not: a line
|
|
16
|
+
* that begins as a comment begins — among the words, or in another block:
|
|
17
|
+
* `/*.log` in a list of files to ignore, a snippet cut off inside a comment —
|
|
18
|
+
* when what ends a comment comes only further on, past a fence. Then the
|
|
19
|
+
* fences between are taken for a program's own, and the reply comes out
|
|
20
|
+
* whole, or as two blocks and the words between them. It is not a program,
|
|
21
|
+
* and the validation that follows says so.
|
|
7
22
|
*/
|
|
8
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
|
+
}
|
|
9
31
|
/**
|
|
10
32
|
* The `agent` a program talks to: its calls, served by `backend` working in
|
|
11
33
|
* `cwd`, and cancelled together through `signal`.
|
|
12
34
|
*/
|
|
13
|
-
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,51 +1,184 @@
|
|
|
1
|
+
import { CutOff } from "./agent-backend.js";
|
|
2
|
+
import { isJsonObject } from "./serializable.js";
|
|
3
|
+
const NAMED = /[\w.+#-]*\s*\n/y;
|
|
4
|
+
/** The fences of a text, in the order they stand in. */
|
|
5
|
+
function fencesOf(text) {
|
|
6
|
+
const fences = [];
|
|
7
|
+
for (const run of text.matchAll(/`{3,}/g)) {
|
|
8
|
+
const at = run.index, ticks = run[0].length;
|
|
9
|
+
const line = text.lastIndexOf("\n", at - 1) + 1;
|
|
10
|
+
const newline = text.indexOf("\n", at);
|
|
11
|
+
NAMED.lastIndex = at + ticks;
|
|
12
|
+
const opens = NAMED.test(text);
|
|
13
|
+
const closes = text.slice(line, at).trim() === "";
|
|
14
|
+
if (opens || closes)
|
|
15
|
+
fences.push({ at, line, next: newline === -1 ? text.length : newline + 1, ticks, opens, closes });
|
|
16
|
+
}
|
|
17
|
+
return fences;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* A reader of the comments of `text` from `from` on, to be asked of one
|
|
21
|
+
* fence after another, in order, whether it stands in one — and so is the
|
|
22
|
+
* program's own text: a program may show how it is used, between fences, in
|
|
23
|
+
* a comment.
|
|
24
|
+
*
|
|
25
|
+
* Only a comment that begins its line is one here (as a comment that holds
|
|
26
|
+
* lines of its own does): `src/*.ts` in a sentence, or in a command, opens
|
|
27
|
+
* nothing. Nothing else of the language is read — a string or a template
|
|
28
|
+
* literal cannot hold a line of backticks anyway.
|
|
29
|
+
*/
|
|
30
|
+
function commentsFrom(text, from) {
|
|
31
|
+
const marks = /^[ \t]*\/\*|\*\//gm;
|
|
32
|
+
let at = from, open = false;
|
|
33
|
+
const readTo = (end) => {
|
|
34
|
+
marks.lastIndex = at;
|
|
35
|
+
for (let mark; (mark = marks.exec(text)) !== null && mark.index < end;)
|
|
36
|
+
open = mark[0] !== "*/";
|
|
37
|
+
at = end;
|
|
38
|
+
return open;
|
|
39
|
+
};
|
|
40
|
+
return {
|
|
41
|
+
holds: (fence) => readTo(fence.at) || /^[ \t]*\/\//.test(text.slice(fence.line, fence.at)),
|
|
42
|
+
open: () => readTo(text.length),
|
|
43
|
+
};
|
|
44
|
+
}
|
|
1
45
|
/**
|
|
2
46
|
* The program in an LLM reply that was asked to contain nothing else: the last
|
|
3
47
|
* fenced block if there is one (models add explanations, or show a "before"
|
|
4
|
-
* first), otherwise the whole
|
|
48
|
+
* first), otherwise the whole text.
|
|
49
|
+
*
|
|
50
|
+
* A program may hold fences of its own, in a comment. So a reply in which
|
|
51
|
+
* every fence stands in a comment was not fenced at all; and a block ends at
|
|
52
|
+
* the first closing fence, of backticks enough, that does not stand in a
|
|
53
|
+
* comment of the block — or, if there is none such (the block is no program,
|
|
54
|
+
* its comment never ends, it was opened with more backticks than it is
|
|
55
|
+
* closed with), at the first closing fence there is.
|
|
56
|
+
*
|
|
57
|
+
* What this still takes wrongly, where the plain reading would not: a line
|
|
58
|
+
* that begins as a comment begins — among the words, or in another block:
|
|
59
|
+
* `/*.log` in a list of files to ignore, a snippet cut off inside a comment —
|
|
60
|
+
* when what ends a comment comes only further on, past a fence. Then the
|
|
61
|
+
* fences between are taken for a program's own, and the reply comes out
|
|
62
|
+
* whole, or as two blocks and the words between them. It is not a program,
|
|
63
|
+
* and the validation that follows says so.
|
|
5
64
|
*/
|
|
6
65
|
export function stripCodeFences(text) {
|
|
7
|
-
const
|
|
8
|
-
const
|
|
9
|
-
|
|
10
|
-
|
|
66
|
+
const reply = text.trim();
|
|
67
|
+
const fences = fencesOf(reply);
|
|
68
|
+
const whole = commentsFrom(reply, 0);
|
|
69
|
+
if (fences.every((fence) => whole.holds(fence)) && !whole.open())
|
|
70
|
+
return reply;
|
|
71
|
+
let last;
|
|
72
|
+
for (let from = 0;;) {
|
|
73
|
+
const opener = fences.find((fence) => fence.opens && fence.at >= from);
|
|
74
|
+
if (!opener)
|
|
75
|
+
break;
|
|
76
|
+
const closers = fences.filter((fence) => fence.at >= opener.next && fence.closes);
|
|
77
|
+
const inBlock = commentsFrom(reply, opener.next);
|
|
78
|
+
const closer = closers.find((fence) => fence.ticks >= opener.ticks && !inBlock.holds(fence)) ?? closers[0];
|
|
79
|
+
if (closer)
|
|
80
|
+
last = reply.slice(opener.next, closer.line).trim();
|
|
81
|
+
from = (closer ?? opener).at + (closer ?? opener).ticks;
|
|
82
|
+
}
|
|
83
|
+
return last ?? reply;
|
|
84
|
+
}
|
|
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}`);
|
|
89
|
+
/**
|
|
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.
|
|
94
|
+
*/
|
|
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`);
|
|
99
|
+
}
|
|
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))]) };
|
|
11
104
|
}
|
|
12
|
-
|
|
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;
|
|
13
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;
|
|
14
115
|
/**
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
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.
|
|
18
119
|
*/
|
|
19
|
-
function
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
const actual = typeof obj[key];
|
|
31
|
-
if (actual !== expectedType)
|
|
32
|
-
return `${key}: expected ${expectedType}, got ${actual}`;
|
|
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}]`));
|
|
33
131
|
}
|
|
34
|
-
|
|
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
|
+
}));
|
|
35
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));
|
|
36
143
|
/**
|
|
37
144
|
* The `agent` a program talks to: its calls, served by `backend` working in
|
|
38
145
|
* `cwd`, and cancelled together through `signal`.
|
|
39
146
|
*/
|
|
40
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
|
+
};
|
|
41
166
|
return {
|
|
42
|
-
async instruct(prompt, options) {
|
|
43
|
-
|
|
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);
|
|
44
170
|
},
|
|
45
|
-
async generate(input) {
|
|
46
|
-
|
|
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.`;
|
|
47
176
|
const fullPrompt = `${input.prompt}\n\n${schemaInstruction}`;
|
|
48
|
-
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 }) };
|
|
49
182
|
const parseAndValidate = (response) => {
|
|
50
183
|
const trimmed = response.trim();
|
|
51
184
|
// Try raw parse first — avoids mangling valid JSON that contains
|
|
@@ -58,30 +191,19 @@ export function createAgent(backend, cwd, signal) {
|
|
|
58
191
|
const fenceMatch = trimmed.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);
|
|
59
192
|
parsed = JSON.parse(fenceMatch ? fenceMatch[1].trim() : trimmed);
|
|
60
193
|
}
|
|
61
|
-
|
|
62
|
-
if (error)
|
|
63
|
-
throw new Error(`Schema validation failed: ${error}`);
|
|
64
|
-
return stripToSchema(parsed, input.schema);
|
|
194
|
+
return conform(parsed, shape, null);
|
|
65
195
|
};
|
|
66
196
|
// First attempt — backend errors (network/auth) propagate immediately.
|
|
67
197
|
// Only parse/validation failures trigger a retry.
|
|
68
|
-
const response = await
|
|
198
|
+
const response = await ask(fullPrompt, call, cutOff);
|
|
69
199
|
try {
|
|
70
200
|
return parseAndValidate(response);
|
|
71
201
|
}
|
|
72
202
|
catch (firstError) {
|
|
73
203
|
const retryPrompt = `Your previous response failed validation: ${firstError}.\nTry again.\n\n${fullPrompt}`;
|
|
74
|
-
const retryResponse = await
|
|
204
|
+
const retryResponse = await ask(retryPrompt, call, cutOff);
|
|
75
205
|
return parseAndValidate(retryResponse);
|
|
76
206
|
}
|
|
77
207
|
}
|
|
78
208
|
};
|
|
79
209
|
}
|
|
80
|
-
/** Return a new object containing only the keys declared in the schema. */
|
|
81
|
-
function stripToSchema(obj, schema) {
|
|
82
|
-
const result = {};
|
|
83
|
-
for (const key of Object.keys(schema)) {
|
|
84
|
-
result[key] = obj[key];
|
|
85
|
-
}
|
|
86
|
-
return result;
|
|
87
|
-
}
|
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)
|