@trama-dev/runtime 0.5.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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 +188 -0
- package/dist/model-relay.js +492 -0
- package/dist/pi-adapter.d.ts +34 -9
- package/dist/pi-adapter.js +978 -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
package/dist/budget.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// What a run may use of a model, and the count of what it has.
|
|
2
|
+
//
|
|
3
|
+
// A budget is kept by the runner, where every question a run puts to a model
|
|
4
|
+
// passes (see createBackend): its program's agent calls, the requests for a
|
|
5
|
+
// fix, and — counted in the budget of each run above it too — all that the
|
|
6
|
+
// runs it asks for put to theirs. Nothing a program is given raises it.
|
|
7
|
+
// It is a guard and no wall: a program is not confined, and one that set out
|
|
8
|
+
// to could find other ways to a model.
|
|
9
|
+
import { describeJson, isJsonObject } from "./serializable.js";
|
|
10
|
+
const CAPS = ["cost", "tokens", "calls"];
|
|
11
|
+
/** A value as it is said back to whoever gave it. */
|
|
12
|
+
function shown(value) {
|
|
13
|
+
try {
|
|
14
|
+
return typeof value === "number" ? String(value) : JSON.stringify(value) ?? String(value);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return String(value);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* A budget as it was given — in a config, to a run, over the bridge — held to
|
|
22
|
+
* what one is: a plain object of caps, each a number that is not negative,
|
|
23
|
+
* and `calls` a whole one. Returns a copy. Throws with what is wrong, as said
|
|
24
|
+
* of `what` it was given as.
|
|
25
|
+
*/
|
|
26
|
+
export function checkedBudget(given, what = "budget") {
|
|
27
|
+
// (A plain object: what holds its caps some other way — a Map, an object that has them from another — would be read as holding none.)
|
|
28
|
+
if (!isJsonObject(given) || ![Object.prototype, null].includes(Object.getPrototypeOf(given))) {
|
|
29
|
+
throw new Error(`${what} is an object of caps (${CAPS.join(", ")}): got ${isJsonObject(given) ? "an object that is not a plain one" : describeJson(given)}`);
|
|
30
|
+
}
|
|
31
|
+
const budget = {};
|
|
32
|
+
for (const [name, cap] of Object.entries(given)) {
|
|
33
|
+
if (!CAPS.includes(name))
|
|
34
|
+
throw new Error(`${what} has no cap "${name}": its caps are ${CAPS.join(", ")}`);
|
|
35
|
+
// (One given as undefined, or as null where it came as JSON, is one not given.)
|
|
36
|
+
if (cap == null)
|
|
37
|
+
continue;
|
|
38
|
+
if (typeof cap !== "number" || !Number.isFinite(cap) || cap < 0 || (name === "calls" && !Number.isInteger(cap))) {
|
|
39
|
+
throw new Error(`${what}.${name} must be ${name === "calls" ? "a whole number" : "a number"} that is not negative (got ${shown(cap)})`);
|
|
40
|
+
}
|
|
41
|
+
budget[name] = cap;
|
|
42
|
+
}
|
|
43
|
+
return budget;
|
|
44
|
+
}
|
|
45
|
+
/** More than this no one call has used of anything: what a report says beyond it is counted as this. */
|
|
46
|
+
const MOST = 1e15;
|
|
47
|
+
/**
|
|
48
|
+
* A count as it can be added up: what a backend did not say, or said as no
|
|
49
|
+
* number or as less than nothing, is nothing — it is not for a count to fail
|
|
50
|
+
* a call, nor for a report to make room — and what it said as more than any
|
|
51
|
+
* call uses is as much as a call can use: a sum that numbers cannot hold is
|
|
52
|
+
* no sum, and no cap would be reached by it again.
|
|
53
|
+
*/
|
|
54
|
+
const counted = (value) => (typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.min(value, MOST) : 0);
|
|
55
|
+
/** All the tokens of a report: read and written, from a cache or not. */
|
|
56
|
+
const tokensOf = (usage) => counted(usage?.input) + counted(usage?.output) + counted(usage?.cacheRead) + counted(usage?.cacheWrite);
|
|
57
|
+
/**
|
|
58
|
+
* How near a cap on cost counts as reached. A cost is a sum of fractions, and
|
|
59
|
+
* ten tenths of a dollar do not add up to one: a billionth of a dollar short
|
|
60
|
+
* is there.
|
|
61
|
+
*/
|
|
62
|
+
const NEAR = 1e-9;
|
|
63
|
+
/**
|
|
64
|
+
* The count of what a run uses, held to `limit`. What it counts is counted
|
|
65
|
+
* under `above` too — the meter of the run that asked for this one — and is
|
|
66
|
+
* refused where that has no room: a run cannot use what the run it is part of
|
|
67
|
+
* may not.
|
|
68
|
+
*/
|
|
69
|
+
export function createMeter(limit = {}, above) {
|
|
70
|
+
// What the calls taken on have used, as far as each has said, and how many they are.
|
|
71
|
+
let cost = 0, tokens = 0, calls = 0;
|
|
72
|
+
/** A cap on what calls use that has been reached. */
|
|
73
|
+
const used = () => {
|
|
74
|
+
if (limit.cost !== undefined && cost + NEAR >= limit.cost)
|
|
75
|
+
return `$${cost.toFixed(4)} used of $${limit.cost}`;
|
|
76
|
+
if (limit.tokens !== undefined && tokens >= limit.tokens)
|
|
77
|
+
return `${tokens} tokens used of ${limit.tokens}`;
|
|
78
|
+
return undefined;
|
|
79
|
+
};
|
|
80
|
+
/** ...or the cap on how many are made: that stops none that is under way, and admits no more. */
|
|
81
|
+
const made = () => limit.calls !== undefined && calls >= limit.calls ? `${calls} of ${limit.calls} calls to a model made` : undefined;
|
|
82
|
+
const said = (why, inherited) => why !== undefined ? `The budget is spent: ${why}.`
|
|
83
|
+
: inherited?.replace(/^The budget is/, "The budget of a run this one is part of is");
|
|
84
|
+
const meter = {
|
|
85
|
+
limit,
|
|
86
|
+
capped: () => Object.keys(limit).length > 0 || above?.capped() === true,
|
|
87
|
+
spent: () => said(used() ?? made(), above?.spent()),
|
|
88
|
+
reached: () => said(used(), above?.reached()),
|
|
89
|
+
count(more, dollars, read) {
|
|
90
|
+
calls += more;
|
|
91
|
+
cost += dollars;
|
|
92
|
+
tokens += read;
|
|
93
|
+
above?.count(more, dollars, read);
|
|
94
|
+
},
|
|
95
|
+
admit() {
|
|
96
|
+
const refusal = meter.spent();
|
|
97
|
+
if (refusal !== undefined)
|
|
98
|
+
throw new Error(refusal);
|
|
99
|
+
meter.count(1, 0, 0);
|
|
100
|
+
// What the call has said it used, in all: each word of it replaces the last.
|
|
101
|
+
let had = { cost: 0, tokens: 0 }, over = false;
|
|
102
|
+
return {
|
|
103
|
+
sofar(usage) {
|
|
104
|
+
if (!over) {
|
|
105
|
+
const now = { cost: counted(usage?.cost), tokens: tokensOf(usage) };
|
|
106
|
+
meter.count(0, now.cost - had.cost, now.tokens - had.tokens);
|
|
107
|
+
had = now;
|
|
108
|
+
}
|
|
109
|
+
return meter.reached();
|
|
110
|
+
},
|
|
111
|
+
close() {
|
|
112
|
+
over = true;
|
|
113
|
+
},
|
|
114
|
+
};
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
return meter;
|
|
118
|
+
}
|
package/dist/child-process.d.ts
CHANGED
|
@@ -35,6 +35,24 @@ export interface SuperviseOptions {
|
|
|
35
35
|
/** Aborting this asks the child to stop, the same way a timeout does. */
|
|
36
36
|
stopSignal?: AbortSignal;
|
|
37
37
|
}
|
|
38
|
+
/**
|
|
39
|
+
* A variable's name as it is shown, and written down. What follows a "=" in
|
|
40
|
+
* one is left out: a name cannot have one, and whoever wrote "KEY=value" for
|
|
41
|
+
* a name wrote a value there.
|
|
42
|
+
*/
|
|
43
|
+
export declare const variableName: (name: string) => string;
|
|
44
|
+
/**
|
|
45
|
+
* Variables a caller gives for what it starts, over those it would have
|
|
46
|
+
* anyway: each a name and its text. Returns them as they were when asked —
|
|
47
|
+
* the caller's object is its own, to change afterwards — or throws, saying
|
|
48
|
+
* which, for what is none.
|
|
49
|
+
*
|
|
50
|
+
* Two things given are not taken. One given as undefined is one not given.
|
|
51
|
+
* And the two names by which a program finds its runner are the runner's to
|
|
52
|
+
* give, to each program its own: they are passed over — so that a program
|
|
53
|
+
* can hand on its whole environment (`env: process.env`), which holds them.
|
|
54
|
+
*/
|
|
55
|
+
export declare function checkedEnv(env: unknown): Record<string, string>;
|
|
38
56
|
export interface ChildExit {
|
|
39
57
|
code: number | null;
|
|
40
58
|
signal: NodeJS.Signals | null;
|
package/dist/child-process.js
CHANGED
|
@@ -69,6 +69,35 @@ export function createAllowance(ms) {
|
|
|
69
69
|
cancel() { pause(); onSpent = null; },
|
|
70
70
|
};
|
|
71
71
|
}
|
|
72
|
+
/**
|
|
73
|
+
* A variable's name as it is shown, and written down. What follows a "=" in
|
|
74
|
+
* one is left out: a name cannot have one, and whoever wrote "KEY=value" for
|
|
75
|
+
* a name wrote a value there.
|
|
76
|
+
*/
|
|
77
|
+
export const variableName = (name) => (name.includes("=") ? `${name.slice(0, name.indexOf("="))}=…` : name);
|
|
78
|
+
/**
|
|
79
|
+
* Variables a caller gives for what it starts, over those it would have
|
|
80
|
+
* anyway: each a name and its text. Returns them as they were when asked —
|
|
81
|
+
* the caller's object is its own, to change afterwards — or throws, saying
|
|
82
|
+
* which, for what is none.
|
|
83
|
+
*
|
|
84
|
+
* Two things given are not taken. One given as undefined is one not given.
|
|
85
|
+
* And the two names by which a program finds its runner are the runner's to
|
|
86
|
+
* give, to each program its own: they are passed over — so that a program
|
|
87
|
+
* can hand on its whole environment (`env: process.env`), which holds them.
|
|
88
|
+
*/
|
|
89
|
+
export function checkedEnv(env) {
|
|
90
|
+
if (typeof env !== "object" || env === null || Array.isArray(env))
|
|
91
|
+
throw new TypeError("env is an object of variables: each a name, and its text");
|
|
92
|
+
const given = Object.entries(env).filter(([name, value]) => value !== undefined && name !== "TRAMA_PORT" && name !== "TRAMA_INIT");
|
|
93
|
+
for (const [name, value] of given) {
|
|
94
|
+
if (name === "" || /[=\0]/.test(name))
|
|
95
|
+
throw new TypeError(`env has a name no variable can have: ${JSON.stringify(variableName(name))}`);
|
|
96
|
+
if (typeof value !== "string" || value.includes("\0"))
|
|
97
|
+
throw new TypeError(`env gives ${JSON.stringify(name)} what is not text a variable can hold`);
|
|
98
|
+
}
|
|
99
|
+
return Object.fromEntries(given);
|
|
100
|
+
}
|
|
72
101
|
/**
|
|
73
102
|
* Collect a child's output and wait for it to exit, enforcing a time limit
|
|
74
103
|
* and an optional stop request. Either one stops the child's whole process
|
package/dist/client.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { Ctx, Agent, ShellResult, Tools, ObserveResult, Workspace } from "./types.js";
|
|
2
|
-
export type { Ctx, Agent, ShellResult, Tools, ObserveResult, Workspace };
|
|
1
|
+
import type { Ctx, Agent, AgentOptions, Thinking, Schema, SchemaField, ShellResult, Tools, ObserveResult, Workspace } from "./types.js";
|
|
2
|
+
export type { Ctx, Agent, AgentOptions, Thinking, Schema, SchemaField, ShellResult, Tools, ObserveResult, Workspace };
|
|
3
3
|
export declare const ctx: Ctx;
|
|
4
4
|
export declare const agent: Agent;
|
|
5
5
|
export declare const tools: Tools;
|
package/dist/client.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @trama-dev/runtime client — this is what program.ts imports.
|
|
2
2
|
// A thin wrapper that forwards every call to the runner's IPC server
|
|
3
3
|
// (ipc-server.ts), which does the real work.
|
|
4
|
-
import { openBridge, remoteWorkspace } from "./bridge-client.js";
|
|
4
|
+
import { openBridge, remoteWorkspace, withOptions } from "./bridge-client.js";
|
|
5
5
|
import { assertSerializable, toLogData } from "./serializable.js";
|
|
6
6
|
const PORT = process.env.TRAMA_PORT;
|
|
7
7
|
if (!PORT) {
|
|
@@ -48,14 +48,14 @@ export const ctx = {
|
|
|
48
48
|
},
|
|
49
49
|
};
|
|
50
50
|
export const agent = {
|
|
51
|
-
instruct: (prompt, opts) => call("/agent/instruct", { prompt,
|
|
51
|
+
instruct: async (prompt, opts) => call("/agent/instruct", withOptions({ prompt }, opts)),
|
|
52
52
|
generate: (input) => call("/agent/generate", input),
|
|
53
53
|
};
|
|
54
54
|
export const tools = {
|
|
55
55
|
read: (path) => call("/tools/read", { path }),
|
|
56
56
|
write: (path, content) => call("/tools/write", { path, content }),
|
|
57
|
-
shell: (cmd, opts) => call("/tools/shell", { command: cmd,
|
|
58
|
-
fetch: (url, opts) => call("/tools/fetch", { url,
|
|
57
|
+
shell: async (cmd, opts) => call("/tools/shell", withOptions({ command: cmd }, opts)),
|
|
58
|
+
fetch: async (url, opts) => call("/tools/fetch", withOptions({ url }, opts)),
|
|
59
59
|
};
|
|
60
60
|
/** workspace.* exists only inside a session — everywhere else it fails clearly, without a round trip. */
|
|
61
61
|
export const workspace = remoteWorkspace((endpoint, body) => {
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type { ProgramResult, RunOptions } from "./runner-types.js";
|
|
1
|
+
export type { Budget, ProgramResult, RunOptions } from "./runner-types.js";
|
|
2
2
|
import type { ProgramResult, RunOptions } from "./runner-types.js";
|
|
3
3
|
export type { Workspace, ObserveResult } from "./types.js";
|
|
4
4
|
import type { Workspace } from "./types.js";
|
|
@@ -8,11 +8,13 @@ export declare function runProgram(options: RunOptions): Promise<ProgramResult>;
|
|
|
8
8
|
export declare function createWorkspace(dir: string): Workspace;
|
|
9
9
|
export declare function validateProjectName(name: string): void;
|
|
10
10
|
export declare function resolveProject(name: string): string;
|
|
11
|
+
/** Generate a program for a new project from a prompt, validate it, and make it the project's. */
|
|
11
12
|
export declare function createProject(name: string, prompt: string, options?: {
|
|
12
13
|
model?: string;
|
|
13
14
|
args?: Record<string, unknown>;
|
|
14
15
|
signal?: AbortSignal;
|
|
15
16
|
}): Promise<void>;
|
|
17
|
+
/** Generate a new program for a project from a prompt and its current one, validate it, and put it in the other's place. */
|
|
16
18
|
export declare function updateProject(name: string, prompt: string, options?: {
|
|
17
19
|
signal?: AbortSignal;
|
|
18
20
|
}): Promise<void>;
|
package/dist/index.js
CHANGED
|
@@ -6,47 +6,57 @@ import { homedir } from "os";
|
|
|
6
6
|
import { piVersion } from "./pi-adapter.js";
|
|
7
7
|
import { stripCodeFences } from "./agent.js";
|
|
8
8
|
import { onAbort, throwIfAborted } from "./abort.js";
|
|
9
|
+
import { createMeter } from "./budget.js";
|
|
9
10
|
import { LATEST_LOG_PATH } from "./context.js";
|
|
10
11
|
import { readProjectMeta } from "./meta.js";
|
|
11
|
-
import { loadConfig, loadProjectConfig, loadState, createBackend, validateProgram, installValidatedProgram, withTempDir, ensureProjectScaffold, RUNTIME_TYPES, runProgram as runHere, whyNotReplaceable, } from "./runner.js";
|
|
12
|
+
import { loadConfig, loadProjectConfig, loadState, createBackend, validateProgram, installValidatedProgram, withTempDir, prepareProject, shownPaths, ensureProjectScaffold, RUNTIME_TYPES, runProgram as runHere, whyNotReplaceable, tagged, saysOnce, } from "./runner.js";
|
|
12
13
|
import { createWorkspace as workspaceHere, ensureWorkspaceDir } from "./workspace.js";
|
|
13
|
-
import { parentBridge, remoteWorkspace } from "./bridge-client.js";
|
|
14
|
+
import { parentBridge, remoteWorkspace, withOptions } from "./bridge-client.js";
|
|
14
15
|
import { guardPath, identityOf, sameProjectAs } from "./path-guard.js";
|
|
15
|
-
import { printJournals } from "./journal-view.js";
|
|
16
|
+
import { printJournals, spentIn } from "./journal-view.js";
|
|
16
17
|
import { messageOf } from "./errors.js";
|
|
17
|
-
// --- Running a project, and reaching a workspace ---
|
|
18
|
+
// --- Running a project, making one, and reaching a workspace ---
|
|
18
19
|
//
|
|
19
|
-
// A program never runs another program
|
|
20
|
-
// their work in this process only when this
|
|
21
|
-
// Inside one they are calls on the bridge,
|
|
22
|
-
// owns every run in the tree — which is
|
|
23
|
-
// see them.
|
|
24
|
-
/**
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
// same as outside a program.
|
|
32
|
-
const { signal, ...request } = options;
|
|
20
|
+
// A program never runs another program, nor makes or changes a project: it
|
|
21
|
+
// asks its runner to. So these do their work in this process only when this
|
|
22
|
+
// process is not itself a program. Inside one they are calls on the bridge,
|
|
23
|
+
// carried out by the one runner that owns every run in the tree — which is
|
|
24
|
+
// how it can time them, stop them, count what they use, and see them.
|
|
25
|
+
/**
|
|
26
|
+
* Ask this program's runner for something that lasts as long as the call
|
|
27
|
+
* does — a run, a project made. A signal cannot cross the bridge, but what
|
|
28
|
+
* it says can: the runner is told to stop it, and this call still waits for
|
|
29
|
+
* it to be over — the same as outside a program.
|
|
30
|
+
*/
|
|
31
|
+
async function overBridge(bridge, endpoint, asked, signal) {
|
|
33
32
|
const id = randomUUID();
|
|
34
33
|
const offStop = onAbort(signal, () => {
|
|
35
34
|
bridge.call("/run/stop", { id }).catch(() => { });
|
|
36
35
|
});
|
|
37
36
|
try {
|
|
38
|
-
return await bridge.call(
|
|
39
|
-
...request,
|
|
40
|
-
id,
|
|
41
|
-
// The runner does not share this program's working directory.
|
|
42
|
-
projectDir: resolve(request.projectDir),
|
|
43
|
-
workspaceDir: request.workspaceDir && resolve(request.workspaceDir),
|
|
44
|
-
});
|
|
37
|
+
return await bridge.call(endpoint, withOptions({ id }, asked));
|
|
45
38
|
}
|
|
46
39
|
finally {
|
|
47
40
|
offStop();
|
|
48
41
|
}
|
|
49
42
|
}
|
|
43
|
+
/** How this runner makes or changes a project for a program that asks it to (see Making). */
|
|
44
|
+
const making = (request, asked) => request.kind === "create"
|
|
45
|
+
? createHere(request.name, request.prompt, { model: request.model, args: request.args, signal: asked.signal }, asked)
|
|
46
|
+
: updateHere(request.name, request.prompt, { signal: asked.signal }, asked);
|
|
47
|
+
/** Run a project to an outcome: done, yielded, or failed. */
|
|
48
|
+
export async function runProgram(options) {
|
|
49
|
+
const bridge = parentBridge();
|
|
50
|
+
if (!bridge)
|
|
51
|
+
return runHere(options, undefined, making);
|
|
52
|
+
const { signal, ...request } = options;
|
|
53
|
+
return overBridge(bridge, "/run/program", {
|
|
54
|
+
...request,
|
|
55
|
+
// The runner does not share this program's working directory.
|
|
56
|
+
projectDir: resolve(request.projectDir),
|
|
57
|
+
workspaceDir: request.workspaceDir && resolve(request.workspaceDir),
|
|
58
|
+
}, signal);
|
|
59
|
+
}
|
|
50
60
|
/** The shared workspace in a directory, created if it does not exist: read, write, list, observe. */
|
|
51
61
|
export function createWorkspace(dir) {
|
|
52
62
|
const bridge = parentBridge();
|
|
@@ -135,12 +145,19 @@ process.on("SIGINT", () => {
|
|
|
135
145
|
});
|
|
136
146
|
|
|
137
147
|
await new Promise<void>(() => {});`;
|
|
138
|
-
function getSystemPrompt() {
|
|
148
|
+
function getSystemPrompt(kept) {
|
|
139
149
|
return (`You are generating a TypeScript program for the trama runtime.\n\n` +
|
|
140
150
|
`If the program is long-running (for example an HTTP server), call ctx.ready(...) after startup completes and handle SIGTERM/SIGINT for clean shutdown.\n\n` +
|
|
141
151
|
`The workspace object is available when running in a session (shared artifact I/O between agents). ` +
|
|
142
152
|
`ctx.yield(reason) suspends the program cooperatively — persists state and exits. ` +
|
|
143
153
|
`ctx.resumed is true if this run follows a yield; ctx.yieldReason has the reason.\n\n` +
|
|
154
|
+
`You are working in a copy of the project's directory, which is where the program will run: ` +
|
|
155
|
+
`where the task speaks of the project's files, look at them. ` +
|
|
156
|
+
(kept
|
|
157
|
+
? `What the program needs beside it — a package installed, a module it imports, a file it reads — ` +
|
|
158
|
+
`you can make here: it is kept, with the program, if the program then passes its validation. ` +
|
|
159
|
+
`The program itself is what you answer with, whatever you wrote to program.ts here.\n\n`
|
|
160
|
+
: `Nothing you write here is kept — only the program you answer with.\n\n`) +
|
|
144
161
|
`Runtime API:\n${RUNTIME_TYPES}\n\n` +
|
|
145
162
|
`Examples:\n${EXAMPLE_PROGRAMS}`);
|
|
146
163
|
}
|
|
@@ -162,26 +179,129 @@ export function resolveProject(name) {
|
|
|
162
179
|
}
|
|
163
180
|
// --- Helpers ---
|
|
164
181
|
/**
|
|
165
|
-
* Ask for a program — in
|
|
166
|
-
*
|
|
167
|
-
*
|
|
182
|
+
* Ask for a program for a project — in a copy of the project (see Prepared),
|
|
183
|
+
* so that the agent can look at what the program is to work with and make
|
|
184
|
+
* what it needs, and its tools do not write into the real one — and take
|
|
185
|
+
* what comes back for a program only if something does: no program is not a
|
|
186
|
+
* program that does nothing.
|
|
168
187
|
*/
|
|
169
|
-
async function generateProgram(backend, prompt, system, signal) {
|
|
170
|
-
|
|
188
|
+
async function generateProgram(backend, prepared, prompt, system, wrote, signal, label) {
|
|
189
|
+
let reply;
|
|
190
|
+
try {
|
|
191
|
+
reply = await backend.ask(prompt, { cwd: prepared.copy, system, signal, used: (usage) => { wrote.push(usage); } });
|
|
192
|
+
}
|
|
193
|
+
finally {
|
|
194
|
+
// What it took is said whatever came of it: it is on record only with a validation, and there may be none.
|
|
195
|
+
// (A call that was cut off — stopped, or by the budget — says what it took once its backend has let go of it.)
|
|
196
|
+
await backend.letGo();
|
|
197
|
+
if (wrote.length > 0)
|
|
198
|
+
console.log(tagged(label, `[trama] writing the program used ${spentIn(wrote)}`));
|
|
199
|
+
}
|
|
200
|
+
const program = stripCodeFences(reply);
|
|
171
201
|
throwIfAborted(signal);
|
|
172
202
|
if (program === "")
|
|
173
203
|
throw new Error("The model answered with no program.");
|
|
174
204
|
return program;
|
|
175
205
|
}
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
206
|
+
/**
|
|
207
|
+
* The budget a create or an update is held to, writing the program and
|
|
208
|
+
* validating it together: the config's — or, where a run's program asked
|
|
209
|
+
* for it, that run's and those above it, and not the config's a second time.
|
|
210
|
+
*/
|
|
211
|
+
const budgetOf = (config, asked) => (asked.above ? undefined : config.budget);
|
|
212
|
+
/**
|
|
213
|
+
* The backend a create or an update asks: held to its budget, and it is said
|
|
214
|
+
* when that is spent — once, and where a run's program asked, once for that
|
|
215
|
+
* run, in the run's own words: a program may ask for many projects.
|
|
216
|
+
*/
|
|
217
|
+
function backendFor(config, asked) {
|
|
218
|
+
const say = (why) => console.warn(tagged(asked.label, `[trama] ${why}`));
|
|
219
|
+
const { above } = asked;
|
|
220
|
+
// (Asked for by a run's program, the project is written by an agent of that run: with the run's variables.)
|
|
221
|
+
return createBackend(config, createMeter(budgetOf(config, asked), above), above ? saysOnce(above, (why) => say(above.spent() ?? why)) : say, asked.env);
|
|
222
|
+
}
|
|
223
|
+
/** Carry what the agent made beside a program into the project the program is now in, and say what that was. */
|
|
224
|
+
function keepPrepared(prepared, label) {
|
|
225
|
+
const console = shownUnder(label);
|
|
226
|
+
let kept;
|
|
227
|
+
try {
|
|
228
|
+
kept = prepared.keep();
|
|
229
|
+
}
|
|
230
|
+
catch (err) {
|
|
231
|
+
// The program is in the project. That what was made beside it cannot be carried over is said, and does not undo that.
|
|
232
|
+
console.warn(`[trama] what was made beside the program, while it was written, could not be carried into the project: ${messageOf(err)}`);
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
const { changed, unmerged } = kept;
|
|
236
|
+
if (changed.length > 0) {
|
|
237
|
+
console.log(`[trama] ${changed.length} path(s) made or changed beside the program, while it was written: ${shownPaths(changed)}`);
|
|
238
|
+
}
|
|
239
|
+
if (unmerged.length > 0) {
|
|
240
|
+
console.warn(`[trama] ${unmerged.length} thing(s) done while the program was written did not reach the project:`);
|
|
241
|
+
for (const { path, why } of unmerged)
|
|
242
|
+
console.warn(`[trama] ${path} — ${why}`);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Validate a candidate for a project: in the project as the agent prepared
|
|
247
|
+
* it, where what the agent made is to be kept — or in the project as it is.
|
|
248
|
+
* `kept` says which: what was validated is what is then to be in the
|
|
249
|
+
* project. The agent's copy is no place to validate in where it is no longer
|
|
250
|
+
* the copy the agent was given (a link put in its place is not followed), or
|
|
251
|
+
* cannot be copied; the candidate is then validated by itself, which is said
|
|
252
|
+
* (see validateProgram).
|
|
253
|
+
*/
|
|
254
|
+
async function validateCandidate(projectDir, backend, candidate, config, prepared, wrote, signal, asked) {
|
|
255
|
+
let as, alone;
|
|
256
|
+
if (config.agentChanges === "keep") {
|
|
257
|
+
try {
|
|
258
|
+
prepared.ready();
|
|
259
|
+
as = prepared.copy;
|
|
260
|
+
}
|
|
261
|
+
catch (err) {
|
|
262
|
+
alone = messageOf(err);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
const validated = await validateProgram(projectDir, backend, candidate, {
|
|
266
|
+
timeout: config.defaultTimeout,
|
|
267
|
+
maxRepairAttempts: config.maxRepairAttempts,
|
|
268
|
+
maxIterations: config.defaultMaxIterations,
|
|
269
|
+
journalRuns: config.journalRuns,
|
|
270
|
+
signal,
|
|
271
|
+
as,
|
|
272
|
+
alone,
|
|
273
|
+
budget: budgetOf(config, asked),
|
|
274
|
+
wrote,
|
|
275
|
+
label: asked.label,
|
|
276
|
+
env: asked.env,
|
|
277
|
+
askedFor: asked.parent && asked.started && { parent: asked.parent, started: asked.started },
|
|
278
|
+
});
|
|
279
|
+
return { validated, kept: as !== undefined && validated.alone === undefined };
|
|
280
|
+
}
|
|
281
|
+
/** What is shown of a project being made, under the name of the run that asked for it — if one did, and has one. */
|
|
282
|
+
const shownUnder = (label) => ({
|
|
283
|
+
log: (line) => console.log(tagged(label, line)),
|
|
284
|
+
warn: (line) => console.warn(tagged(label, line)),
|
|
182
285
|
});
|
|
183
286
|
// --- Public API ---
|
|
287
|
+
/** Generate a program for a new project from a prompt, validate it, and make it the project's. */
|
|
184
288
|
export async function createProject(name, prompt, options) {
|
|
289
|
+
const bridge = parentBridge();
|
|
290
|
+
if (!bridge)
|
|
291
|
+
return createHere(name, prompt, options);
|
|
292
|
+
const { signal, ...asked } = options ?? {};
|
|
293
|
+
await overBridge(bridge, "/project/create", withOptions({ name, prompt }, asked), signal);
|
|
294
|
+
}
|
|
295
|
+
/** Generate a new program for a project from a prompt and its current one, validate it, and put it in the other's place. */
|
|
296
|
+
export async function updateProject(name, prompt, options) {
|
|
297
|
+
const bridge = parentBridge();
|
|
298
|
+
if (!bridge)
|
|
299
|
+
return updateHere(name, prompt, options);
|
|
300
|
+
const { signal, ...asked } = options ?? {};
|
|
301
|
+
await overBridge(bridge, "/project/update", withOptions({ name, prompt }, asked), signal);
|
|
302
|
+
}
|
|
303
|
+
async function createHere(name, prompt, options, asked = {}) {
|
|
304
|
+
const console = shownUnder(asked.label);
|
|
185
305
|
validateProjectName(name);
|
|
186
306
|
throwIfAborted(options?.signal);
|
|
187
307
|
const projectDir = join(projectsDir(), name);
|
|
@@ -212,18 +332,26 @@ export async function createProject(name, prompt, options) {
|
|
|
212
332
|
provider: config.provider,
|
|
213
333
|
};
|
|
214
334
|
writeFileSync(join(projectDir, "meta.json"), JSON.stringify(meta, null, 2));
|
|
215
|
-
const backend =
|
|
335
|
+
const backend = backendFor(config, asked);
|
|
336
|
+
const wrote = [];
|
|
216
337
|
console.log(`Generating program for "${name}"...`);
|
|
217
|
-
|
|
338
|
+
// (What the agent is given to look at is the project made here, and no other directory that is at its path by now.)
|
|
218
339
|
stillTheProject();
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
340
|
+
await withTempDir("trama-gen-", async (privateDir) => {
|
|
341
|
+
const prepared = prepareProject(projectDir, privateDir);
|
|
342
|
+
const candidate = await generateProgram(backend, prepared, `${prompt}\n\nOutput ONLY the TypeScript program. No markdown fences. No explanation.`, getSystemPrompt(config.agentChanges === "keep"), wrote, options?.signal, asked.label);
|
|
343
|
+
stillTheProject();
|
|
344
|
+
// From here on the project is kept even if validation fails, so the
|
|
345
|
+
// generated program can be inspected and fixed by hand.
|
|
346
|
+
writeFileSync(guardPath(projectDir, "program.ts"), candidate);
|
|
347
|
+
keepProjectOnFailure = true;
|
|
348
|
+
console.log("Validating program...");
|
|
349
|
+
const { validated, kept } = await validateCandidate(projectDir, backend, candidate, config, prepared, wrote, options?.signal, asked);
|
|
350
|
+
stillTheProject();
|
|
351
|
+
installValidatedProgram(projectDir, validated, "create", prompt);
|
|
352
|
+
if (kept)
|
|
353
|
+
keepPrepared(prepared, asked.label);
|
|
354
|
+
});
|
|
227
355
|
console.log(`Created ${name}. Run with: trama run ${name}`);
|
|
228
356
|
}
|
|
229
357
|
catch (err) {
|
|
@@ -233,7 +361,8 @@ export async function createProject(name, prompt, options) {
|
|
|
233
361
|
throw err;
|
|
234
362
|
}
|
|
235
363
|
}
|
|
236
|
-
|
|
364
|
+
async function updateHere(name, prompt, options, asked = {}) {
|
|
365
|
+
const console = shownUnder(asked.label);
|
|
237
366
|
const projectDir = resolveProject(name);
|
|
238
367
|
const unchanged = (why) => new Error(`Update failed — the program is unchanged.\n${messageOf(why)}`);
|
|
239
368
|
const stillTheProject = sameProjectAs(projectDir);
|
|
@@ -253,18 +382,24 @@ export async function updateProject(name, prompt, options) {
|
|
|
253
382
|
const state = loadState(projectDir);
|
|
254
383
|
const meta = readProjectMeta(projectDir);
|
|
255
384
|
const config = loadProjectConfig(projectDir, meta);
|
|
256
|
-
const backend =
|
|
257
|
-
const
|
|
385
|
+
const backend = backendFor(config, asked);
|
|
386
|
+
const wrote = [];
|
|
387
|
+
const systemPrompt = getSystemPrompt(config.agentChanges === "keep") +
|
|
258
388
|
`\n\nOriginal prompt: ${meta.input.prompt}` +
|
|
259
389
|
`\n\nCurrent program.ts:\n${originalSource}` +
|
|
260
390
|
(Object.keys(state).length > 0 ? `\n\nCurrent state:\n${JSON.stringify(state, null, 2)}` : "");
|
|
261
391
|
console.log(`Updating "${name}"...`);
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
392
|
+
await withTempDir("trama-gen-", async (privateDir) => {
|
|
393
|
+
const prepared = prepareProject(projectDir, privateDir);
|
|
394
|
+
const candidate = await generateProgram(backend, prepared, `${prompt}\n\nOutput the complete updated program.ts. No partial patches. No markdown fences. No explanation.`, systemPrompt, wrote, options?.signal, asked.label);
|
|
395
|
+
stillTheProject();
|
|
396
|
+
console.log("Validating updated program...");
|
|
397
|
+
const { validated, kept } = await validateCandidate(projectDir, backend, candidate, config, prepared, wrote, options?.signal, asked);
|
|
398
|
+
stillTheProject();
|
|
399
|
+
installValidatedProgram(projectDir, validated, "update", prompt);
|
|
400
|
+
if (kept)
|
|
401
|
+
keepPrepared(prepared, asked.label);
|
|
402
|
+
});
|
|
268
403
|
}
|
|
269
404
|
catch (err) {
|
|
270
405
|
throw unchanged(err);
|
package/dist/ipc-server.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { type Server } from "http";
|
|
2
|
-
import type {
|
|
2
|
+
import type { Tools, Workspace } from "./types.js";
|
|
3
|
+
import type { RunnerAgent } from "./agent.js";
|
|
3
4
|
import type { RunContext } from "./context.js";
|
|
4
5
|
import type { ProgramResult, RunRequest } from "./runner-types.js";
|
|
6
|
+
import type { MakeRequest } from "./runner.js";
|
|
5
7
|
import type { Journal } from "./journal.js";
|
|
6
8
|
export interface IpcBackends {
|
|
7
9
|
/**
|
|
@@ -11,7 +13,7 @@ export interface IpcBackends {
|
|
|
11
13
|
*/
|
|
12
14
|
token: string;
|
|
13
15
|
ctx: RunContext;
|
|
14
|
-
agent:
|
|
16
|
+
agent: RunnerAgent;
|
|
15
17
|
tools: Tools;
|
|
16
18
|
/** The workspace of the session the program is running in — null when it is in none. */
|
|
17
19
|
workspace: Workspace | null;
|
|
@@ -22,8 +24,15 @@ export interface IpcBackends {
|
|
|
22
24
|
* to stop it. `seq` is the position of the call that asked for it.
|
|
23
25
|
*/
|
|
24
26
|
run(request: RunRequest, stop: AbortSignal, seq: number): Promise<ProgramResult>;
|
|
27
|
+
/** Make a project, or change one, on the program's behalf — until it is done or `stop` says to stop. */
|
|
28
|
+
make(request: MakeRequest, stop: AbortSignal, seq: number): Promise<void>;
|
|
25
29
|
/** Where every call, and how it ended, is written down. */
|
|
26
30
|
journal: Journal;
|
|
31
|
+
/**
|
|
32
|
+
* Whether the program has ended. What comes back for a call after that is
|
|
33
|
+
* no answer — though its connection may not have been seen to close yet.
|
|
34
|
+
*/
|
|
35
|
+
programOver(): boolean;
|
|
27
36
|
}
|
|
28
37
|
export declare function createIPCServer(backends: IpcBackends): Server;
|
|
29
38
|
/** Start listening on an ephemeral loopback port and return it. */
|