@trama-dev/runtime 0.6.0 → 0.7.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 +51 -0
- package/dist/agent-backend.js +4 -0
- package/dist/agent-host.d.ts +46 -7
- package/dist/agent-host.js +59 -19
- package/dist/agent-hosts.js +122 -56
- package/dist/agent.d.ts +16 -5
- package/dist/agent.js +22 -64
- package/dist/bridge-client.d.ts +6 -2
- package/dist/bridge-client.js +6 -1
- package/dist/client.d.ts +2 -2
- package/dist/client.js +126 -2
- package/dist/context.js +3 -2
- package/dist/history.d.ts +9 -0
- package/dist/history.js +98 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +70 -41
- package/dist/ipc-server.d.ts +2 -3
- package/dist/ipc-server.js +93 -37
- package/dist/journal-view.js +19 -9
- package/dist/journal.d.ts +10 -4
- package/dist/journal.js +28 -6
- package/dist/merge-deeds.d.ts +22 -0
- package/dist/merge-deeds.js +201 -0
- package/dist/merge-doing.d.ts +9 -0
- package/dist/merge-doing.js +410 -0
- package/dist/merge-settle.d.ts +14 -0
- package/dist/merge-settle.js +166 -0
- package/dist/merge-shared.d.ts +64 -0
- package/dist/merge-shared.js +159 -0
- package/dist/merge.d.ts +150 -0
- package/dist/merge.js +209 -0
- package/dist/model-relay.d.ts +63 -5
- package/dist/model-relay.js +206 -23
- package/dist/own-tools.d.ts +60 -0
- package/dist/own-tools.js +209 -0
- package/dist/path-guard.js +8 -6
- package/dist/pi-adapter.d.ts +22 -0
- package/dist/pi-adapter.js +294 -72
- package/dist/project.d.ts +31 -0
- package/dist/project.js +253 -0
- package/dist/replace-file.d.ts +13 -2
- package/dist/replace-file.js +23 -6
- package/dist/runner-backend.d.ts +43 -0
- package/dist/runner-backend.js +125 -0
- package/dist/runner-types.d.ts +8 -0
- package/dist/runner.d.ts +8 -123
- package/dist/runner.js +57 -453
- package/dist/schema.d.ts +38 -0
- package/dist/schema.js +104 -0
- package/dist/stopping.js +2 -3
- package/dist/tools.js +31 -7
- package/dist/tree.d.ts +33 -149
- package/dist/tree.js +43 -1077
- package/dist/types.d.ts +54 -2
- package/dist/workspace.d.ts +20 -0
- package/dist/workspace.js +76 -12
- package/package.json +2 -2
package/dist/project.js
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
// What a project is on disk before anything of it is run: the files trama
|
|
2
|
+
// keeps around a program.ts, the config a run of it goes by, and the state
|
|
3
|
+
// its last run left.
|
|
4
|
+
import { readFileSync, writeFileSync, mkdirSync, existsSync, symlinkSync, rmSync, lstatSync, readlinkSync, accessSync, constants, } from "fs";
|
|
5
|
+
import { join, dirname } from "path";
|
|
6
|
+
import { homedir } from "os";
|
|
7
|
+
import { fileURLToPath } from "url";
|
|
8
|
+
import { checkedBudget } from "./budget.js";
|
|
9
|
+
import { guardPath, projectAt } from "./path-guard.js";
|
|
10
|
+
import { stageFileInProject } from "./replace-file.js";
|
|
11
|
+
import { readProjectMeta } from "./meta.js";
|
|
12
|
+
import { describeJson, isJsonObject } from "./serializable.js";
|
|
13
|
+
import { messageOf } from "./errors.js";
|
|
14
|
+
// --- Locating the runtime itself ---
|
|
15
|
+
/** The installed @trama-dev/runtime package — this file lives in its dist/. */
|
|
16
|
+
const RUNTIME_PACKAGE_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
|
|
17
|
+
/**
|
|
18
|
+
* The @trama-dev packages a program.ts can import, and where they are installed.
|
|
19
|
+
* The runtime always; the session layer when it is installed alongside (as it
|
|
20
|
+
* is with the CLI). The runtime never imports the session layer itself — it
|
|
21
|
+
* only makes it reachable from projects.
|
|
22
|
+
*/
|
|
23
|
+
const IMPORTABLE_PACKAGES = { runtime: RUNTIME_PACKAGE_DIR };
|
|
24
|
+
try {
|
|
25
|
+
// Resolves to <package>/dist/index.js
|
|
26
|
+
IMPORTABLE_PACKAGES.session = dirname(dirname(fileURLToPath(import.meta.resolve("@trama-dev/session"))));
|
|
27
|
+
}
|
|
28
|
+
catch { /* not installed — programs simply cannot import it */ }
|
|
29
|
+
// --- Project scaffolding ---
|
|
30
|
+
/**
|
|
31
|
+
* Point the project's node_modules/@trama-dev/<name> at an installed package,
|
|
32
|
+
* so program.ts can import it. Replaces any existing symlink whose target
|
|
33
|
+
* differs (including user-managed ones). Only refuses to touch a real
|
|
34
|
+
* directory/file to avoid destroying user content.
|
|
35
|
+
*
|
|
36
|
+
* The link points outside the project, and is meant to. Where it is put is
|
|
37
|
+
* inside it, like everything else the runtime writes: a project whose
|
|
38
|
+
* node_modules leads somewhere else is refused, not followed there.
|
|
39
|
+
*/
|
|
40
|
+
function linkPackage(projectDir, name, target) {
|
|
41
|
+
const linkDir = guardPath(projectDir, join("node_modules", "@trama-dev"));
|
|
42
|
+
// Not through the guard: it is the link itself that is looked at and replaced, not what it points at.
|
|
43
|
+
const linkPath = join(linkDir, name);
|
|
44
|
+
try {
|
|
45
|
+
if (!lstatSync(linkPath).isSymbolicLink()) {
|
|
46
|
+
throw new Error(`${linkPath} exists and is not a symlink. ` +
|
|
47
|
+
`trama needs this path for module resolution. ` +
|
|
48
|
+
`Remove it manually or rename it to proceed.`);
|
|
49
|
+
}
|
|
50
|
+
if (readlinkSync(linkPath) === target)
|
|
51
|
+
return;
|
|
52
|
+
rmSync(linkPath);
|
|
53
|
+
}
|
|
54
|
+
catch (err) {
|
|
55
|
+
if (err.code !== "ENOENT")
|
|
56
|
+
throw err;
|
|
57
|
+
}
|
|
58
|
+
mkdirSync(linkDir, { recursive: true });
|
|
59
|
+
symlinkSync(target, linkPath, "dir");
|
|
60
|
+
}
|
|
61
|
+
/** Make sure package.json exists and declares an ES module (program.ts uses top-level await). */
|
|
62
|
+
function ensureModulePackageJson(projectDir) {
|
|
63
|
+
const pkgPath = guardPath(projectDir, "package.json");
|
|
64
|
+
if (!existsSync(pkgPath)) {
|
|
65
|
+
writeFileSync(pkgPath, JSON.stringify({ type: "module" }, null, 2));
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
const advice = "trama will not overwrite it automatically; fix or remove it and try again.";
|
|
69
|
+
let pkg;
|
|
70
|
+
try {
|
|
71
|
+
pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
|
|
72
|
+
}
|
|
73
|
+
catch (err) {
|
|
74
|
+
throw new Error(`Malformed package.json at ${pkgPath}. ${advice}\n` +
|
|
75
|
+
`Parse error: ${messageOf(err)}`);
|
|
76
|
+
}
|
|
77
|
+
if (!isJsonObject(pkg)) {
|
|
78
|
+
throw new Error(`Malformed package.json at ${pkgPath} — expected a JSON object but got ${describeJson(pkg)}. ${advice}`);
|
|
79
|
+
}
|
|
80
|
+
if (pkg.type !== "module") {
|
|
81
|
+
pkg.type = "module";
|
|
82
|
+
writeFileSync(pkgPath, JSON.stringify(pkg, null, 2));
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/** Make sure .gitignore excludes what trama generates, without disturbing existing entries. */
|
|
86
|
+
function ensureGitignore(projectDir) {
|
|
87
|
+
const giPath = guardPath(projectDir, ".gitignore");
|
|
88
|
+
const required = ["node_modules/", "state.json", "logs/", "history/"];
|
|
89
|
+
const existing = existsSync(giPath) ? readFileSync(giPath, "utf-8") : "";
|
|
90
|
+
const present = new Set(existing.split("\n").map(line => line.trim()));
|
|
91
|
+
const missing = required.filter(entry => !present.has(entry));
|
|
92
|
+
if (missing.length === 0)
|
|
93
|
+
return;
|
|
94
|
+
const separator = existing === "" || existing.endsWith("\n") ? "" : "\n";
|
|
95
|
+
writeFileSync(giPath, existing + separator + missing.join("\n") + "\n");
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Everything a project directory needs around program.ts before it can run:
|
|
99
|
+
* history/ and logs/, an ESM package.json, .gitignore entries, and links to the
|
|
100
|
+
* @trama-dev packages it can import.
|
|
101
|
+
* Idempotent — called before every run, so a freshly cloned project just works.
|
|
102
|
+
*/
|
|
103
|
+
export function ensureProjectScaffold(projectDir) {
|
|
104
|
+
projectAt(projectDir);
|
|
105
|
+
mkdirSync(guardPath(projectDir, "history"), { recursive: true });
|
|
106
|
+
mkdirSync(guardPath(projectDir, "logs"), { recursive: true });
|
|
107
|
+
ensureModulePackageJson(projectDir);
|
|
108
|
+
ensureGitignore(projectDir);
|
|
109
|
+
for (const [name, target] of Object.entries(IMPORTABLE_PACKAGES))
|
|
110
|
+
linkPackage(projectDir, name, target);
|
|
111
|
+
}
|
|
112
|
+
// --- Config & state loaders ---
|
|
113
|
+
export function loadConfig() {
|
|
114
|
+
const configPath = join(homedir(), ".trama", "config.json");
|
|
115
|
+
const defaults = {
|
|
116
|
+
provider: "anthropic",
|
|
117
|
+
model: "claude-opus-5-5",
|
|
118
|
+
maxRepairAttempts: 3,
|
|
119
|
+
defaultTimeout: 300_000,
|
|
120
|
+
defaultMaxIterations: 100,
|
|
121
|
+
journalRuns: 20,
|
|
122
|
+
agentChanges: "keep",
|
|
123
|
+
};
|
|
124
|
+
let raw;
|
|
125
|
+
try {
|
|
126
|
+
raw = readFileSync(configPath, "utf-8");
|
|
127
|
+
}
|
|
128
|
+
catch (err) {
|
|
129
|
+
if (err.code === "ENOENT")
|
|
130
|
+
return defaults;
|
|
131
|
+
throw err;
|
|
132
|
+
}
|
|
133
|
+
let parsed;
|
|
134
|
+
try {
|
|
135
|
+
parsed = JSON.parse(raw);
|
|
136
|
+
}
|
|
137
|
+
catch (err) {
|
|
138
|
+
throw new Error(`Malformed config at ${configPath} — fix or delete it.\n` +
|
|
139
|
+
`Parse error: ${messageOf(err)}`);
|
|
140
|
+
}
|
|
141
|
+
if (!isJsonObject(parsed)) {
|
|
142
|
+
throw new Error(`Malformed config at ${configPath} — expected a JSON object but got ${describeJson(parsed)}. Fix or delete it to proceed.`);
|
|
143
|
+
}
|
|
144
|
+
// null is how JSON says a field is not there.
|
|
145
|
+
const given = Object.fromEntries(Object.entries(parsed).filter(([, value]) => value !== null));
|
|
146
|
+
return checkedConfig({ ...defaults, ...given }, "config");
|
|
147
|
+
}
|
|
148
|
+
/** A config that holds what the runtime can work with — or an error naming what does not, and where it came from. */
|
|
149
|
+
function checkedConfig(merged, source) {
|
|
150
|
+
const s = (v) => typeof v === "string" && v.length > 0;
|
|
151
|
+
const pint = (v) => Number.isInteger(v) && v > 0;
|
|
152
|
+
const checks = [
|
|
153
|
+
[s(merged.provider), `"provider" must be a non-empty string (got ${JSON.stringify(merged.provider)})`],
|
|
154
|
+
[s(merged.model), `"model" must be a non-empty string (got ${JSON.stringify(merged.model)})`],
|
|
155
|
+
[Number.isInteger(merged.maxRepairAttempts) && merged.maxRepairAttempts >= 0, `"maxRepairAttempts" must be a non-negative integer (got ${merged.maxRepairAttempts})`],
|
|
156
|
+
[Number.isFinite(merged.defaultTimeout) && merged.defaultTimeout > 0, `"defaultTimeout" must be a positive number (got ${merged.defaultTimeout})`],
|
|
157
|
+
[pint(merged.defaultMaxIterations), `"defaultMaxIterations" must be a positive integer (got ${merged.defaultMaxIterations})`],
|
|
158
|
+
[Number.isInteger(merged.journalRuns) && merged.journalRuns >= 0, `"journalRuns" must be a non-negative integer (got ${merged.journalRuns})`],
|
|
159
|
+
[merged.agentChanges === "keep" || merged.agentChanges === "discard", `"agentChanges" must be "keep" or "discard" (got ${JSON.stringify(merged.agentChanges)})`],
|
|
160
|
+
];
|
|
161
|
+
for (const [ok, msg] of checks) {
|
|
162
|
+
if (!ok)
|
|
163
|
+
throw new Error(`Invalid ${source}: ${msg}`);
|
|
164
|
+
}
|
|
165
|
+
if (merged.budget === undefined)
|
|
166
|
+
return merged;
|
|
167
|
+
try {
|
|
168
|
+
return { ...merged, budget: checkedBudget(merged.budget, `"budget"`) };
|
|
169
|
+
}
|
|
170
|
+
catch (err) {
|
|
171
|
+
throw new Error(`Invalid ${source}: ${messageOf(err)}`);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
/** The time a run is given, held to what a time is. */
|
|
175
|
+
export function checkedTimeout(timeout) {
|
|
176
|
+
if (!Number.isFinite(timeout) || timeout <= 0)
|
|
177
|
+
throw new Error(`Invalid timeout: ${timeout}. Must be a positive number.`);
|
|
178
|
+
return timeout;
|
|
179
|
+
}
|
|
180
|
+
/** How many fixes a run may be tried with, held to what a count is. */
|
|
181
|
+
export function checkedRepairAttempts(attempts) {
|
|
182
|
+
if (!Number.isInteger(attempts) || attempts < 0)
|
|
183
|
+
throw new Error(`Invalid maxRepairAttempts: ${attempts}. Must be a non-negative integer.`);
|
|
184
|
+
return attempts;
|
|
185
|
+
}
|
|
186
|
+
/** The global config, with the model/provider a project was created with taking precedence. */
|
|
187
|
+
export function loadProjectConfig(projectDir, meta = readProjectMeta(projectDir)) {
|
|
188
|
+
const config = loadConfig();
|
|
189
|
+
// null is how JSON says a field is not there. Anything else a project says
|
|
190
|
+
// is taken, and held to what the global config is held to — an empty or
|
|
191
|
+
// mistyped name is an error here, not a quiet return to another model.
|
|
192
|
+
if (meta.model != null)
|
|
193
|
+
config.model = meta.model;
|
|
194
|
+
if (meta.provider != null)
|
|
195
|
+
config.provider = meta.provider;
|
|
196
|
+
return checkedConfig(config, `meta.json in ${projectDir}`);
|
|
197
|
+
}
|
|
198
|
+
export function loadState(projectDir) {
|
|
199
|
+
const statePath = guardPath(projectDir, "state.json");
|
|
200
|
+
let raw;
|
|
201
|
+
try {
|
|
202
|
+
raw = readFileSync(statePath, "utf-8");
|
|
203
|
+
}
|
|
204
|
+
catch (err) {
|
|
205
|
+
if (err.code === "ENOENT")
|
|
206
|
+
return {};
|
|
207
|
+
throw err;
|
|
208
|
+
}
|
|
209
|
+
function fail(reason) {
|
|
210
|
+
throw new Error(`Corrupt state.json in ${projectDir} — cannot safely continue.\n${reason}\n` +
|
|
211
|
+
`Back up or delete state.json to reset state.`);
|
|
212
|
+
}
|
|
213
|
+
let parsed;
|
|
214
|
+
try {
|
|
215
|
+
parsed = JSON.parse(raw);
|
|
216
|
+
}
|
|
217
|
+
catch (err) {
|
|
218
|
+
fail(`Parse error: ${messageOf(err)}`);
|
|
219
|
+
}
|
|
220
|
+
if (!isJsonObject(parsed)) {
|
|
221
|
+
fail(`Expected a JSON object but got ${describeJson(parsed)}.`);
|
|
222
|
+
}
|
|
223
|
+
return parsed;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Put a project's state on file: all of it, in the place of what was there.
|
|
227
|
+
* It is written beside the file and moved into its place, and not written
|
|
228
|
+
* into it — a program that is stopped in the middle of a checkpoint leaves
|
|
229
|
+
* the state before, and not half of a state, which no run after would start
|
|
230
|
+
* from. (Taking a file's place does not ask the file's leave, as writing
|
|
231
|
+
* into it did: so it is asked here. A state file its owner made read-only
|
|
232
|
+
* stays as it is.)
|
|
233
|
+
*
|
|
234
|
+
* Where no file can be made beside it — a project whose own directory is
|
|
235
|
+
* closed to that, and whose files are not — the state is written into its
|
|
236
|
+
* file, as it always was: there is no other way to it there, and a project
|
|
237
|
+
* kept so is still one that can be run.
|
|
238
|
+
*/
|
|
239
|
+
export function saveState(projectDir, state) {
|
|
240
|
+
const path = guardPath(projectDir, "state.json");
|
|
241
|
+
const text = JSON.stringify(state, null, 2);
|
|
242
|
+
if (existsSync(path))
|
|
243
|
+
accessSync(path, constants.W_OK);
|
|
244
|
+
try {
|
|
245
|
+
stageFileInProject(projectDir, "state.json", text).commit();
|
|
246
|
+
}
|
|
247
|
+
catch (err) {
|
|
248
|
+
const code = err.code;
|
|
249
|
+
if (code !== "EACCES" && code !== "EPERM" && code !== "EROFS")
|
|
250
|
+
throw err;
|
|
251
|
+
writeFileSync(path, text);
|
|
252
|
+
}
|
|
253
|
+
}
|
package/dist/replace-file.d.ts
CHANGED
|
@@ -26,6 +26,17 @@ export interface StagedFile {
|
|
|
26
26
|
* is being replaced hands on its permissions, as it would if it were written
|
|
27
27
|
* into — unless `mode` says what the new file's are. It is a new file all the
|
|
28
28
|
* same, so a second hard link to the old one, or its owner, are not carried
|
|
29
|
-
* over.
|
|
29
|
+
* over. And while it is being written it is its writer's alone, where it is
|
|
30
|
+
* to have permissions that are handed to it: what takes the place of a file
|
|
31
|
+
* others may not read is not readable by them for the time the writing takes.
|
|
32
|
+
*
|
|
33
|
+
* `makeDirs` makes the directories on the way — with the root itself, unless
|
|
34
|
+
* it is given as what does not (see stageFileInProject).
|
|
35
|
+
*/
|
|
36
|
+
export declare function stageFile(rootDir: string, relativePath: string, content: string | Buffer, mode?: number, makeDirs?: (dir: string) => void): StagedFile;
|
|
37
|
+
/**
|
|
38
|
+
* stageFile, under a root that is something in itself — a project, which
|
|
39
|
+
* somebody may have moved away since it was named: it must be there, and is
|
|
40
|
+
* not made anew for the sake of what goes into it (see makeDirsIn).
|
|
30
41
|
*/
|
|
31
|
-
export declare function
|
|
42
|
+
export declare function stageFileInProject(projectDir: string, relativePath: string, content: string | Buffer, mode?: number): StagedFile;
|
package/dist/replace-file.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
import { chmodSync, closeSync, fdatasyncSync, mkdirSync, openSync, renameSync, rmSync, statSync, writeFileSync } from "fs";
|
|
9
9
|
import { randomBytes } from "crypto";
|
|
10
10
|
import { dirname, join } from "path";
|
|
11
|
-
import { guardPath, realRootOf } from "./path-guard.js";
|
|
11
|
+
import { guardPath, makeDirsIn, realRootOf } from "./path-guard.js";
|
|
12
12
|
/** Whether a file name is that of a temp file made here — not content, though it sits among it for a moment. */
|
|
13
13
|
export const isStagedName = (name) => /\.trama-tmp-[0-9a-f]{12}$/.test(name);
|
|
14
14
|
/**
|
|
@@ -29,20 +29,29 @@ export const stagedNameFor = (destination) => join(dirname(destination), `.trama
|
|
|
29
29
|
* is being replaced hands on its permissions, as it would if it were written
|
|
30
30
|
* into — unless `mode` says what the new file's are. It is a new file all the
|
|
31
31
|
* same, so a second hard link to the old one, or its owner, are not carried
|
|
32
|
-
* over.
|
|
32
|
+
* over. And while it is being written it is its writer's alone, where it is
|
|
33
|
+
* to have permissions that are handed to it: what takes the place of a file
|
|
34
|
+
* others may not read is not readable by them for the time the writing takes.
|
|
35
|
+
*
|
|
36
|
+
* `makeDirs` makes the directories on the way — with the root itself, unless
|
|
37
|
+
* it is given as what does not (see stageFileInProject).
|
|
33
38
|
*/
|
|
34
|
-
export function stageFile(rootDir, relativePath, content, mode) {
|
|
39
|
+
export function stageFile(rootDir, relativePath, content, mode, makeDirs = (dir) => { mkdirSync(dir, { recursive: true }); }) {
|
|
35
40
|
const destination = guardPath(rootDir, relativePath);
|
|
36
41
|
if (destination === realRootOf(rootDir)) {
|
|
37
42
|
throw new Error(`Not a file path: "${relativePath}" is the directory itself`);
|
|
38
43
|
}
|
|
39
|
-
|
|
44
|
+
makeDirs(dirname(destination));
|
|
40
45
|
const staged = stagedNameFor(destination);
|
|
41
46
|
const discard = () => { try {
|
|
42
47
|
rmSync(staged, { force: true });
|
|
43
48
|
}
|
|
44
49
|
catch { /* best-effort */ } };
|
|
45
|
-
const
|
|
50
|
+
const handedOn = () => mode ?? statSync(destination, { throwIfNoEntry: false })?.mode;
|
|
51
|
+
// (Made closed where it is to be handed permissions, and opened as far as they go once it is whole. One that
|
|
52
|
+
// takes nobody's place and is told nothing is made as any new file is.)
|
|
53
|
+
const first = handedOn();
|
|
54
|
+
const fd = openSync(staged, "wx", first === undefined ? 0o666 : 0o600);
|
|
46
55
|
try {
|
|
47
56
|
try {
|
|
48
57
|
writeFileSync(fd, content);
|
|
@@ -51,7 +60,7 @@ export function stageFile(rootDir, relativePath, content, mode) {
|
|
|
51
60
|
finally {
|
|
52
61
|
closeSync(fd);
|
|
53
62
|
}
|
|
54
|
-
const permissions =
|
|
63
|
+
const permissions = handedOn() ?? first;
|
|
55
64
|
if (permissions !== undefined)
|
|
56
65
|
chmodSync(staged, permissions & 0o777);
|
|
57
66
|
}
|
|
@@ -73,3 +82,11 @@ export function stageFile(rootDir, relativePath, content, mode) {
|
|
|
73
82
|
},
|
|
74
83
|
};
|
|
75
84
|
}
|
|
85
|
+
/**
|
|
86
|
+
* stageFile, under a root that is something in itself — a project, which
|
|
87
|
+
* somebody may have moved away since it was named: it must be there, and is
|
|
88
|
+
* not made anew for the sake of what goes into it (see makeDirsIn).
|
|
89
|
+
*/
|
|
90
|
+
export function stageFileInProject(projectDir, relativePath, content, mode) {
|
|
91
|
+
return stageFile(projectDir, relativePath, content, mode, (dir) => makeDirsIn(projectDir, dir));
|
|
92
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { AgentBackend } from "./agent-backend.js";
|
|
2
|
+
import { type Meter } from "./budget.js";
|
|
3
|
+
import type { TramaConfig } from "./runner-types.js";
|
|
4
|
+
/**
|
|
5
|
+
* What does the LLM work for a project. The only place that picks a backend:
|
|
6
|
+
* everything else is handed one and does not know which it is.
|
|
7
|
+
*
|
|
8
|
+
* It is also where what is asked of a model is counted, and held to a
|
|
9
|
+
* budget (`meter`): every call passes here, whoever makes it. A call that
|
|
10
|
+
* comes when the budget is spent is refused; one under way is stopped where
|
|
11
|
+
* its agent would ask the model again — what the model was asked before
|
|
12
|
+
* that is used, and what it was answering is let finish. `spent` is told
|
|
13
|
+
* why, the first time either happens.
|
|
14
|
+
*/
|
|
15
|
+
export declare function createBackend(config: TramaConfig, meter?: Meter, spent?: (why: string) => void, env?: Record<string, string>): Backend;
|
|
16
|
+
/**
|
|
17
|
+
* Say that a budget is spent, once for the budget — whoever comes up against
|
|
18
|
+
* it first: the run's own backend, or the backend of a project being made
|
|
19
|
+
* for the run's program, of which there may be many.
|
|
20
|
+
*/
|
|
21
|
+
export declare const saysOnce: (meter: Meter, say: (why: string) => void) => (why: string) => void;
|
|
22
|
+
/** A backend as the runner holds it: one whose cancelled calls are answered at once, and can be waited for apart. */
|
|
23
|
+
export interface Backend extends AgentBackend {
|
|
24
|
+
/** Why nothing more may be asked of it — the budget it counts in is spent — or nothing, while something may. */
|
|
25
|
+
spent(): string | undefined;
|
|
26
|
+
/** Why a call of it was first refused or stopped for the budget, if one was — whatever the count has come to since. */
|
|
27
|
+
refused(): string | undefined;
|
|
28
|
+
/** Whether what its calls use is held to anything: then what a call it cut off used is to be waited for, recorded or not. */
|
|
29
|
+
counts(): boolean;
|
|
30
|
+
/**
|
|
31
|
+
* End what the backend kept to serve calls with — a process of its own for
|
|
32
|
+
* those that have extensions. Whatever it served is over: a run, a
|
|
33
|
+
* validation. (Asked again after this, it starts anew.)
|
|
34
|
+
*/
|
|
35
|
+
close(): Promise<void>;
|
|
36
|
+
/**
|
|
37
|
+
* Resolves when the backend has let go of the calls that were cancelled so
|
|
38
|
+
* far: whoever cancelled one went on at once, and the backend still had to
|
|
39
|
+
* stop what it was doing, and to say what the call had used. They are
|
|
40
|
+
* waited for no longer than anything asked to stop is.
|
|
41
|
+
*/
|
|
42
|
+
letGo(): Promise<void>;
|
|
43
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// The backend as a runner holds it: the one place that picks what does the
|
|
2
|
+
// LLM work, and where every call of a run is counted and held to its budget.
|
|
3
|
+
import { onAbort, rejectOnAbort } from "./abort.js";
|
|
4
|
+
import { createMeter } from "./budget.js";
|
|
5
|
+
import { PiAdapter } from "./pi-adapter.js";
|
|
6
|
+
import { KILL_GRACE_MS } from "./stopping.js";
|
|
7
|
+
import { messageOf } from "./errors.js";
|
|
8
|
+
/**
|
|
9
|
+
* What does the LLM work for a project. The only place that picks a backend:
|
|
10
|
+
* everything else is handed one and does not know which it is.
|
|
11
|
+
*
|
|
12
|
+
* It is also where what is asked of a model is counted, and held to a
|
|
13
|
+
* budget (`meter`): every call passes here, whoever makes it. A call that
|
|
14
|
+
* comes when the budget is spent is refused; one under way is stopped where
|
|
15
|
+
* its agent would ask the model again — what the model was asked before
|
|
16
|
+
* that is used, and what it was answering is let finish. `spent` is told
|
|
17
|
+
* why, the first time either happens.
|
|
18
|
+
*/
|
|
19
|
+
export function createBackend(config, meter = createMeter(), spent = () => { }, env) {
|
|
20
|
+
// (`env`: the variables of the run whose calls these are — its agents' too, as they are its program's and its commands'.)
|
|
21
|
+
const backend = new PiAdapter(config, env);
|
|
22
|
+
// The calls that were cancelled.
|
|
23
|
+
const cutOff = new Set();
|
|
24
|
+
// Why a call was first refused, or stopped, for the budget.
|
|
25
|
+
let refused;
|
|
26
|
+
const overBudget = (why) => {
|
|
27
|
+
if (refused === undefined)
|
|
28
|
+
spent(why);
|
|
29
|
+
refused ??= why;
|
|
30
|
+
return new Error(why);
|
|
31
|
+
};
|
|
32
|
+
return {
|
|
33
|
+
spent: () => meter.spent(),
|
|
34
|
+
refused: () => refused,
|
|
35
|
+
counts: () => meter.capped(),
|
|
36
|
+
// The interface promises that a cancelled call rejects, and a run's end
|
|
37
|
+
// waits on that. Every backend is held to it here, rather than trusted with it.
|
|
38
|
+
async ask(prompt, call) {
|
|
39
|
+
let account;
|
|
40
|
+
try {
|
|
41
|
+
account = meter.admit();
|
|
42
|
+
}
|
|
43
|
+
catch (err) {
|
|
44
|
+
throw overBudget(messageOf(err));
|
|
45
|
+
}
|
|
46
|
+
// Stops the call where the budget is reached while it is under way.
|
|
47
|
+
const over = new AbortController();
|
|
48
|
+
let why;
|
|
49
|
+
const signal = call.signal ? AbortSignal.any([call.signal, over.signal]) : over.signal;
|
|
50
|
+
const work = backend.ask(prompt, {
|
|
51
|
+
...call,
|
|
52
|
+
signal,
|
|
53
|
+
sofar(usage, answered) {
|
|
54
|
+
const reached = account.sofar(usage);
|
|
55
|
+
call.sofar?.(usage, answered);
|
|
56
|
+
// A call that is over keeps what it ended with — its answer, or its own failure: what would be
|
|
57
|
+
// asked beside it is not asked, and that is all. (It is a request refused for the budget all the
|
|
58
|
+
// same, and said as one.)
|
|
59
|
+
if (answered) {
|
|
60
|
+
const spent = why ?? reached;
|
|
61
|
+
if (spent === undefined)
|
|
62
|
+
return true;
|
|
63
|
+
overBudget(spent);
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
// (Once it is to stop, it is to stop — whatever is said of it after.)
|
|
67
|
+
why ??= reached;
|
|
68
|
+
if (why === undefined)
|
|
69
|
+
return true;
|
|
70
|
+
over.abort();
|
|
71
|
+
return false;
|
|
72
|
+
},
|
|
73
|
+
// (What the call has used is counted from when it is known: nothing is stopped for it here — a reply that
|
|
74
|
+
// has come is not taken back — but whatever is asked next, by this call or another, is asked against it.)
|
|
75
|
+
had(usage) {
|
|
76
|
+
account.sofar(usage);
|
|
77
|
+
call.had?.(usage);
|
|
78
|
+
},
|
|
79
|
+
used(usage) {
|
|
80
|
+
account.sofar(usage);
|
|
81
|
+
call.used?.(usage);
|
|
82
|
+
},
|
|
83
|
+
});
|
|
84
|
+
const off = onAbort(signal, () => { cutOff.add(work); });
|
|
85
|
+
// What the call used is counted as its own until the backend has let go of it — which
|
|
86
|
+
// is when it has said the last of it — however long ago whoever asked was answered.
|
|
87
|
+
const settled = () => {
|
|
88
|
+
off();
|
|
89
|
+
account.close();
|
|
90
|
+
// (Let go of: nobody need wait for it any more.)
|
|
91
|
+
cutOff.delete(work);
|
|
92
|
+
};
|
|
93
|
+
work.then(settled, settled);
|
|
94
|
+
try {
|
|
95
|
+
return await rejectOnAbort(work, signal);
|
|
96
|
+
}
|
|
97
|
+
catch (err) {
|
|
98
|
+
// (Stopped by whoever asked, it was stopped by them, whatever the budget had come to.)
|
|
99
|
+
throw why !== undefined && !call.signal?.aborted ? overBudget(why) : err;
|
|
100
|
+
}
|
|
101
|
+
},
|
|
102
|
+
close: () => backend.close(),
|
|
103
|
+
async letGo() {
|
|
104
|
+
let giveUp;
|
|
105
|
+
await Promise.race([
|
|
106
|
+
Promise.allSettled(cutOff),
|
|
107
|
+
new Promise(resolve => { giveUp = setTimeout(resolve, KILL_GRACE_MS); }),
|
|
108
|
+
]);
|
|
109
|
+
clearTimeout(giveUp);
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
/** The budgets of which it has been said that they are spent. */
|
|
114
|
+
const saidSpent = new WeakSet();
|
|
115
|
+
/**
|
|
116
|
+
* Say that a budget is spent, once for the budget — whoever comes up against
|
|
117
|
+
* it first: the run's own backend, or the backend of a project being made
|
|
118
|
+
* for the run's program, of which there may be many.
|
|
119
|
+
*/
|
|
120
|
+
export const saysOnce = (meter, say) => (why) => {
|
|
121
|
+
if (saidSpent.has(meter))
|
|
122
|
+
return;
|
|
123
|
+
saidSpent.add(meter);
|
|
124
|
+
say(why);
|
|
125
|
+
};
|
package/dist/runner-types.d.ts
CHANGED
|
@@ -54,6 +54,14 @@ export interface RunOptions {
|
|
|
54
54
|
}
|
|
55
55
|
/** A run as one program asks its runner for it: everything in RunOptions that can cross the bridge. */
|
|
56
56
|
export type RunRequest = Omit<RunOptions, "signal">;
|
|
57
|
+
/** A project a program asks its runner to make, or to change (see createProject and updateProject). */
|
|
58
|
+
export interface MakeRequest {
|
|
59
|
+
kind: "create" | "update";
|
|
60
|
+
name: string;
|
|
61
|
+
prompt: string;
|
|
62
|
+
model?: string;
|
|
63
|
+
args?: Record<string, unknown>;
|
|
64
|
+
}
|
|
57
65
|
export interface TramaConfig extends ModelConfig {
|
|
58
66
|
maxRepairAttempts: number;
|
|
59
67
|
defaultTimeout: number;
|