@trama-dev/runtime 0.2.2 → 0.3.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 +24 -0
- package/dist/agent-backend.js +29 -0
- package/dist/agent.d.ts +12 -2
- package/dist/agent.js +23 -6
- package/dist/bridge-client.d.ts +22 -0
- package/dist/bridge-client.js +71 -0
- package/dist/child-process.d.ts +39 -6
- package/dist/child-process.js +132 -25
- package/dist/client.d.ts +1 -0
- package/dist/client.js +5 -48
- package/dist/context.d.ts +2 -0
- package/dist/context.js +1 -1
- package/dist/index.d.ts +6 -2
- package/dist/index.js +61 -15
- package/dist/ipc-server.d.ts +6 -2
- package/dist/ipc-server.js +65 -8
- package/dist/pi-adapter.d.ts +7 -14
- package/dist/pi-adapter.js +20 -54
- package/dist/runner-types.d.ts +18 -7
- package/dist/runner.d.ts +22 -5
- package/dist/runner.js +251 -71
- package/dist/tools.d.ts +2 -2
- package/dist/tools.js +15 -12
- package/dist/watchdog.d.ts +19 -0
- package/dist/watchdog.js +167 -0
- package/package.json +1 -1
- package/dist/lifetime.d.ts +0 -8
- package/dist/lifetime.js +0 -70
package/dist/index.js
CHANGED
|
@@ -1,12 +1,58 @@
|
|
|
1
1
|
// @trama-dev/runtime runner surface — exported via "@trama-dev/runtime/runner"
|
|
2
|
+
import { randomUUID } from "crypto";
|
|
2
3
|
import { readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync, statSync, rmSync } from "fs";
|
|
3
|
-
import { join } from "path";
|
|
4
|
+
import { join, resolve } from "path";
|
|
4
5
|
import { homedir } from "os";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
6
|
+
import { piVersion } from "./pi-adapter.js";
|
|
7
|
+
import { stripCodeFences } from "./agent.js";
|
|
8
|
+
import { loadConfig, loadProjectConfig, loadState, createBackend, validateProgram, installValidatedProgram, withTempDir, ensureProjectScaffold, RUNTIME_TYPES, runProgram as runHere, } from "./runner.js";
|
|
9
|
+
import { createWorkspace as workspaceHere } from "./workspace.js";
|
|
10
|
+
import { parentBridge, remoteWorkspace } from "./bridge-client.js";
|
|
7
11
|
import { guardPath } from "./path-guard.js";
|
|
8
|
-
|
|
9
|
-
|
|
12
|
+
// --- Running a project, and reaching a workspace ---
|
|
13
|
+
//
|
|
14
|
+
// A program never runs another program: it asks its runner to. So these two do
|
|
15
|
+
// their work in this process only when this process is not itself a program.
|
|
16
|
+
// Inside one they are calls on the bridge, carried out by the one runner that
|
|
17
|
+
// owns every run in the tree — which is how it can time them, stop them, and
|
|
18
|
+
// see them.
|
|
19
|
+
/** Run a project to an outcome: done, yielded, or failed. */
|
|
20
|
+
export async function runProgram(options) {
|
|
21
|
+
const bridge = parentBridge();
|
|
22
|
+
if (!bridge)
|
|
23
|
+
return runHere(options);
|
|
24
|
+
// A signal cannot cross the bridge, but what it says can: the runner is told
|
|
25
|
+
// to stop the run, and this call still waits for the run to be over — the
|
|
26
|
+
// same as outside a program.
|
|
27
|
+
const { signal, ...request } = options;
|
|
28
|
+
const id = randomUUID();
|
|
29
|
+
const stop = () => { bridge.call("/run/stop", { id }).catch(() => { }); };
|
|
30
|
+
if (signal?.aborted)
|
|
31
|
+
stop();
|
|
32
|
+
else
|
|
33
|
+
signal?.addEventListener("abort", stop, { once: true });
|
|
34
|
+
try {
|
|
35
|
+
return await bridge.call("/run/program", {
|
|
36
|
+
...request,
|
|
37
|
+
id,
|
|
38
|
+
// The runner does not share this program's working directory.
|
|
39
|
+
projectDir: resolve(request.projectDir),
|
|
40
|
+
workspaceDir: request.workspaceDir && resolve(request.workspaceDir),
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
finally {
|
|
44
|
+
signal?.removeEventListener("abort", stop);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** The shared workspace in a directory, created if it does not exist: read, write, list, observe. */
|
|
48
|
+
export function createWorkspace(dir) {
|
|
49
|
+
const bridge = parentBridge();
|
|
50
|
+
if (!bridge)
|
|
51
|
+
return workspaceHere(dir);
|
|
52
|
+
const absolute = resolve(dir);
|
|
53
|
+
mkdirSync(absolute, { recursive: true }); // it exists from here on, as it does outside a program
|
|
54
|
+
return remoteWorkspace(bridge.call, absolute);
|
|
55
|
+
}
|
|
10
56
|
// --- Example programs (included in system prompt during create/update) ---
|
|
11
57
|
const EXAMPLE_PROGRAMS = `// Example A: Simple — one-shot action, no LLM needed.
|
|
12
58
|
import { ctx, tools } from "@trama-dev/runtime";
|
|
@@ -113,9 +159,9 @@ export function resolveProject(name) {
|
|
|
113
159
|
return dir;
|
|
114
160
|
}
|
|
115
161
|
// --- Helpers ---
|
|
116
|
-
/**
|
|
117
|
-
async function isolatedAsk(
|
|
118
|
-
return withTempDir("trama-gen-", (
|
|
162
|
+
/** Ask in an empty throwaway directory, so the agent's tools cannot write into the real project. */
|
|
163
|
+
async function isolatedAsk(backend, prompt, system) {
|
|
164
|
+
return withTempDir("trama-gen-", (cwd) => backend.ask(prompt, { cwd, system }));
|
|
119
165
|
}
|
|
120
166
|
const validationOptions = (config) => ({
|
|
121
167
|
timeout: config.defaultTimeout,
|
|
@@ -139,20 +185,20 @@ export async function createProject(name, prompt, options) {
|
|
|
139
185
|
const meta = {
|
|
140
186
|
input: { prompt, args: options?.args ?? {} },
|
|
141
187
|
createdAt: new Date().toISOString(),
|
|
142
|
-
piVersion:
|
|
188
|
+
piVersion: await piVersion(),
|
|
143
189
|
model: config.model,
|
|
144
190
|
provider: config.provider,
|
|
145
191
|
};
|
|
146
192
|
writeFileSync(join(projectDir, "meta.json"), JSON.stringify(meta, null, 2));
|
|
147
|
-
const
|
|
193
|
+
const backend = createBackend(config);
|
|
148
194
|
console.log(`Generating program for "${name}"...`);
|
|
149
|
-
const candidate = stripCodeFences(await isolatedAsk(
|
|
195
|
+
const candidate = stripCodeFences(await isolatedAsk(backend, `${prompt}\n\nOutput ONLY the TypeScript program. No markdown fences. No explanation.`, getSystemPrompt()));
|
|
150
196
|
// From here on the project is kept even if validation fails, so the
|
|
151
197
|
// generated program can be inspected and fixed by hand.
|
|
152
198
|
writeFileSync(join(projectDir, "program.ts"), candidate);
|
|
153
199
|
keepProjectOnFailure = true;
|
|
154
200
|
console.log("Validating program...");
|
|
155
|
-
const validated = await validateProgram(projectDir,
|
|
201
|
+
const validated = await validateProgram(projectDir, backend, candidate, validationOptions(config));
|
|
156
202
|
installValidatedProgram(projectDir, validated, "create", prompt);
|
|
157
203
|
console.log(`Created ${name}. Run with: trama run ${name}`);
|
|
158
204
|
}
|
|
@@ -172,7 +218,7 @@ export async function updateProject(name, prompt) {
|
|
|
172
218
|
const state = loadState(projectDir);
|
|
173
219
|
const meta = JSON.parse(readFileSync(guardPath(projectDir, "meta.json"), "utf-8"));
|
|
174
220
|
const config = loadProjectConfig(projectDir);
|
|
175
|
-
const
|
|
221
|
+
const backend = createBackend(config);
|
|
176
222
|
const systemPrompt = getSystemPrompt() +
|
|
177
223
|
`\n\nOriginal prompt: ${meta.input.prompt}` +
|
|
178
224
|
`\n\nCurrent program.ts:\n${originalSource}` +
|
|
@@ -182,9 +228,9 @@ export async function updateProject(name, prompt) {
|
|
|
182
228
|
// nothing to undo.
|
|
183
229
|
try {
|
|
184
230
|
console.log(`Updating "${name}"...`);
|
|
185
|
-
const candidate = stripCodeFences(await isolatedAsk(
|
|
231
|
+
const candidate = stripCodeFences(await isolatedAsk(backend, `${prompt}\n\nOutput the complete updated program.ts. No partial patches. No markdown fences. No explanation.`, systemPrompt));
|
|
186
232
|
console.log("Validating updated program...");
|
|
187
|
-
const validated = await validateProgram(projectDir,
|
|
233
|
+
const validated = await validateProgram(projectDir, backend, candidate, validationOptions(config));
|
|
188
234
|
try {
|
|
189
235
|
installValidatedProgram(projectDir, validated, "update", prompt);
|
|
190
236
|
}
|
package/dist/ipc-server.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type Server } from "http";
|
|
2
2
|
import type { Ctx, Agent, Tools, Workspace } from "./types.js";
|
|
3
|
-
import type { ProgramResult } from "./runner-types.js";
|
|
3
|
+
import type { ProgramResult, RunRequest } from "./runner-types.js";
|
|
4
4
|
export interface IpcBackends {
|
|
5
5
|
/**
|
|
6
6
|
* The secret only this run's program knows. Every request must present it:
|
|
@@ -11,8 +11,12 @@ export interface IpcBackends {
|
|
|
11
11
|
ctx: Ctx;
|
|
12
12
|
agent: Agent;
|
|
13
13
|
tools: Tools;
|
|
14
|
-
/**
|
|
14
|
+
/** The workspace of the session the program is running in — null when it is in none. */
|
|
15
15
|
workspace: Workspace | null;
|
|
16
|
+
/** A workspace by directory, for a program that created a session rather than joined one. */
|
|
17
|
+
workspaceAt(dir: string): Workspace;
|
|
18
|
+
/** Run another project on the program's behalf, until it ends or `stop` says to stop it. */
|
|
19
|
+
run(request: RunRequest, stop: AbortSignal): Promise<ProgramResult>;
|
|
16
20
|
/** Called once ctx.done() or ctx.yield() has been persisted for this run. */
|
|
17
21
|
onTerminalSignal(result: ProgramResult): void;
|
|
18
22
|
}
|
package/dist/ipc-server.js
CHANGED
|
@@ -28,13 +28,23 @@ function isAuthorized(header, token) {
|
|
|
28
28
|
const actual = Buffer.from(header ?? "");
|
|
29
29
|
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
30
30
|
}
|
|
31
|
-
function buildRoutes({ ctx, agent, tools, workspace, onTerminalSignal }) {
|
|
31
|
+
function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run, onTerminalSignal }) {
|
|
32
32
|
/** The program owns ctx.state; each persisting call hands over its current copy. */
|
|
33
33
|
const adoptState = (state) => {
|
|
34
34
|
assertSerializable(state, "ctx.state");
|
|
35
35
|
ctx.state = state;
|
|
36
36
|
};
|
|
37
|
-
|
|
37
|
+
/** Runs the program has asked for and that have not ended, by the id it gave each. */
|
|
38
|
+
const runsAskedFor = new Map();
|
|
39
|
+
/** Ids the program asked to stop before their run was seen here: such a run starts stopped. */
|
|
40
|
+
const stoppedAhead = new Set();
|
|
41
|
+
/** The workspace a call is about: the directory it names, or else the one this run was started with. */
|
|
42
|
+
const workspaceOf = (body) => {
|
|
43
|
+
if (body.dir !== undefined) {
|
|
44
|
+
if (typeof body.dir !== "string" || body.dir === "")
|
|
45
|
+
throw new BadRequest("Invalid field: dir (expected a directory path)");
|
|
46
|
+
return workspaceAt(body.dir);
|
|
47
|
+
}
|
|
38
48
|
if (!workspace)
|
|
39
49
|
throw new BadRequest("Workspace is only available when running in a session");
|
|
40
50
|
return workspace;
|
|
@@ -86,22 +96,66 @@ function buildRoutes({ ctx, agent, tools, workspace, onTerminalSignal }) {
|
|
|
86
96
|
onTerminalSignal({ status: "yielded", reason: b.reason });
|
|
87
97
|
},
|
|
88
98
|
},
|
|
89
|
-
|
|
99
|
+
// A program never runs another program: it asks its runner to. The call
|
|
100
|
+
// lasts as long as the run does, repairs included.
|
|
101
|
+
"/run/program": {
|
|
102
|
+
fields: { projectDir: "string", args: "optional object" },
|
|
103
|
+
handle: async (b, connectionClosed) => {
|
|
104
|
+
const stop = new AbortController();
|
|
105
|
+
// A caller that is gone — its process died, or it gave up — no longer wants the run.
|
|
106
|
+
void connectionClosed.then(() => stop.abort());
|
|
107
|
+
const id = typeof b.id === "string" ? b.id : undefined;
|
|
108
|
+
if (id && stoppedAhead.delete(id))
|
|
109
|
+
stop.abort();
|
|
110
|
+
if (id)
|
|
111
|
+
runsAskedFor.set(id, stop);
|
|
112
|
+
try {
|
|
113
|
+
return await run({
|
|
114
|
+
projectDir: b.projectDir,
|
|
115
|
+
args: b.args,
|
|
116
|
+
timeout: b.timeout,
|
|
117
|
+
maxRepairAttempts: b.maxRepairAttempts,
|
|
118
|
+
workspaceDir: b.workspaceDir,
|
|
119
|
+
label: b.label,
|
|
120
|
+
}, stop.signal);
|
|
121
|
+
}
|
|
122
|
+
finally {
|
|
123
|
+
if (id)
|
|
124
|
+
runsAskedFor.delete(id);
|
|
125
|
+
}
|
|
126
|
+
},
|
|
127
|
+
},
|
|
128
|
+
// Stop a run asked for above. The call that asked for it still gets its
|
|
129
|
+
// answer — a failed run — once the run is over.
|
|
130
|
+
"/run/stop": {
|
|
131
|
+
fields: { id: "string" },
|
|
132
|
+
handle: b => {
|
|
133
|
+
const asked = runsAskedFor.get(b.id);
|
|
134
|
+
if (asked)
|
|
135
|
+
asked.abort();
|
|
136
|
+
else
|
|
137
|
+
stoppedAhead.add(b.id);
|
|
138
|
+
},
|
|
139
|
+
},
|
|
140
|
+
"/workspace/read": { fields: { path: "string" }, handle: b => workspaceOf(b).read(b.path) },
|
|
90
141
|
"/workspace/write": {
|
|
91
142
|
fields: { path: "string", content: "string" },
|
|
92
|
-
handle: b =>
|
|
143
|
+
handle: b => workspaceOf(b).write(b.path, b.content),
|
|
93
144
|
},
|
|
94
|
-
"/workspace/list": { fields: { pattern: "string" }, handle: b =>
|
|
145
|
+
"/workspace/list": { fields: { pattern: "string" }, handle: b => workspaceOf(b).list(b.pattern) },
|
|
95
146
|
"/workspace/observe": {
|
|
96
147
|
fields: { pattern: "string" },
|
|
97
|
-
handle: b =>
|
|
148
|
+
handle: b => workspaceOf(b).observe(b.pattern, { expect: b.expect, timeout: b.timeout }),
|
|
98
149
|
},
|
|
99
150
|
};
|
|
100
151
|
}
|
|
101
152
|
export function createIPCServer(backends) {
|
|
102
153
|
const routes = buildRoutes(backends);
|
|
103
154
|
return createServer((req, res) => {
|
|
155
|
+
const connectionClosed = new Promise(resolve => res.once("close", resolve));
|
|
104
156
|
const reply = (status, body, json = false) => {
|
|
157
|
+
if (res.writableEnded || res.destroyed)
|
|
158
|
+
return; // answered already, or nobody left to answer
|
|
105
159
|
res.writeHead(status, json ? { "Content-Type": "application/json" } : undefined);
|
|
106
160
|
res.end(body);
|
|
107
161
|
};
|
|
@@ -120,9 +174,12 @@ export function createIPCServer(backends) {
|
|
|
120
174
|
chunks.push(chunk);
|
|
121
175
|
byteCount += chunk.length;
|
|
122
176
|
if (byteCount > MAX_IPC_BODY) {
|
|
177
|
+
// Answer now, and let the rest of the body arrive and be discarded.
|
|
178
|
+
// Cutting the connection instead would race the answer: a sender still
|
|
179
|
+
// writing sees a broken connection, not the reason for it.
|
|
123
180
|
overflow = true;
|
|
181
|
+
chunks.length = 0;
|
|
124
182
|
reply(413, "IPC request body exceeds 50MB limit");
|
|
125
|
-
req.destroy();
|
|
126
183
|
}
|
|
127
184
|
});
|
|
128
185
|
req.on("end", async () => {
|
|
@@ -134,7 +191,7 @@ export function createIPCServer(backends) {
|
|
|
134
191
|
if (!route)
|
|
135
192
|
return reply(404, "Not found");
|
|
136
193
|
validate(body, route.fields);
|
|
137
|
-
const result = await route.handle(body);
|
|
194
|
+
const result = await route.handle(body, connectionClosed);
|
|
138
195
|
reply(200, JSON.stringify({ result: result ?? null }), true);
|
|
139
196
|
}
|
|
140
197
|
catch (err) {
|
package/dist/pi-adapter.d.ts
CHANGED
|
@@ -1,14 +1,11 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type AgentBackend, type AgentCall } from "./agent-backend.js";
|
|
2
|
+
import type { ModelConfig } from "./runner-types.js";
|
|
2
3
|
/** The pi version this runtime is built against (recorded in each project's meta.json). */
|
|
3
|
-
export
|
|
4
|
-
/**
|
|
5
|
-
export declare
|
|
6
|
-
export declare class PiAdapter {
|
|
4
|
+
export declare const piVersion: () => Promise<string>;
|
|
5
|
+
/** The pi coding agent, run in-process: a fresh in-memory session for every call. */
|
|
6
|
+
export declare class PiAdapter implements AgentBackend {
|
|
7
7
|
private config;
|
|
8
|
-
|
|
9
|
-
constructor(config: PiAdapterConfig, cwd: string);
|
|
10
|
-
/** Create a copy of this adapter that operates in a different working directory. */
|
|
11
|
-
withCwd(cwd: string): PiAdapter;
|
|
8
|
+
constructor(config: ModelConfig);
|
|
12
9
|
private createSession;
|
|
13
10
|
/**
|
|
14
11
|
* The configured provider/model is not in pi's catalog, so pi picked a model
|
|
@@ -23,9 +20,5 @@ export declare class PiAdapter {
|
|
|
23
20
|
* pi 1.x settles the prompt by resolving it (not rejecting), so abort is
|
|
24
21
|
* re-checked after prompt() returns.
|
|
25
22
|
*/
|
|
26
|
-
ask(prompt: string,
|
|
27
|
-
system?: string;
|
|
28
|
-
signal?: AbortSignal;
|
|
29
|
-
}): Promise<string>;
|
|
30
|
-
repair(input: RepairInput, signal?: AbortSignal): Promise<string>;
|
|
23
|
+
ask(prompt: string, call: AgentCall): Promise<string>;
|
|
31
24
|
}
|
package/dist/pi-adapter.js
CHANGED
|
@@ -1,60 +1,34 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { rejectOnAbort } from "./agent-backend.js";
|
|
2
|
+
/**
|
|
3
|
+
* pi is loaded when it is first needed, not when this file is: it is most of
|
|
4
|
+
* what the runtime weighs, and listing projects, reading logs, or running a
|
|
5
|
+
* program that never calls the agent does not need it.
|
|
6
|
+
*/
|
|
7
|
+
const loadPi = () => import("@earendil-works/pi-coding-agent");
|
|
2
8
|
/** The pi version this runtime is built against (recorded in each project's meta.json). */
|
|
3
|
-
export
|
|
4
|
-
/** Strip markdown code fences and trim whitespace. */
|
|
5
|
-
export function stripCodeFences(text) {
|
|
6
|
-
const trimmed = text.trim();
|
|
7
|
-
// Extract the last fenced code block (LLMs may prepend explanation or emit multiple blocks)
|
|
8
|
-
const matches = [...trimmed.matchAll(/```(?:\w*)\s*\n([\s\S]*?)\n\s*```/g)];
|
|
9
|
-
if (matches.length > 0) {
|
|
10
|
-
return matches[matches.length - 1][1].trim();
|
|
11
|
-
}
|
|
12
|
-
return trimmed;
|
|
13
|
-
}
|
|
9
|
+
export const piVersion = async () => (await loadPi()).VERSION;
|
|
14
10
|
/** provider/model pairs already warned about, so a loop of agent calls warns once per process. */
|
|
15
11
|
const warnedUnknownModels = new Set();
|
|
12
|
+
/** The pi coding agent, run in-process: a fresh in-memory session for every call. */
|
|
16
13
|
export class PiAdapter {
|
|
17
14
|
config;
|
|
18
|
-
|
|
19
|
-
constructor(config, cwd) {
|
|
15
|
+
constructor(config) {
|
|
20
16
|
this.config = config;
|
|
21
|
-
this.cwd = cwd;
|
|
22
17
|
}
|
|
23
|
-
|
|
24
|
-
withCwd(cwd) {
|
|
25
|
-
return new PiAdapter(this.config, cwd);
|
|
26
|
-
}
|
|
27
|
-
async createSession(systemPrompt, signal) {
|
|
18
|
+
async createSession(cwd, systemPrompt, signal) {
|
|
28
19
|
if (signal?.aborted)
|
|
29
20
|
throw new Error("Aborted");
|
|
21
|
+
// Each step below is given up on the moment the call is cancelled.
|
|
22
|
+
const raceAbort = (step) => rejectOnAbort(step, signal);
|
|
23
|
+
const { createAgentSession, SessionManager, DefaultResourceLoader, ModelRuntime, getAgentDir } = await raceAbort(loadPi());
|
|
30
24
|
const agentDir = getAgentDir();
|
|
31
25
|
const resourceLoader = new DefaultResourceLoader({
|
|
32
|
-
cwd
|
|
26
|
+
cwd,
|
|
33
27
|
agentDir,
|
|
34
28
|
noExtensions: true,
|
|
35
29
|
noSkills: true,
|
|
36
30
|
...(systemPrompt && { appendSystemPrompt: [systemPrompt] }),
|
|
37
31
|
});
|
|
38
|
-
// Race an async step against the abort signal.
|
|
39
|
-
// Returns the result on success, or rejects with "Aborted" on abort.
|
|
40
|
-
const raceAbort = (promise) => {
|
|
41
|
-
if (!signal)
|
|
42
|
-
return promise;
|
|
43
|
-
let onAbort = null;
|
|
44
|
-
const cleanup = () => {
|
|
45
|
-
if (onAbort) {
|
|
46
|
-
signal.removeEventListener("abort", onAbort);
|
|
47
|
-
onAbort = null;
|
|
48
|
-
}
|
|
49
|
-
};
|
|
50
|
-
return Promise.race([
|
|
51
|
-
promise.finally(cleanup),
|
|
52
|
-
new Promise((_resolve, reject) => {
|
|
53
|
-
onAbort = () => reject(new Error("Aborted"));
|
|
54
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
55
|
-
}),
|
|
56
|
-
]);
|
|
57
|
-
};
|
|
58
32
|
await raceAbort(resourceLoader.reload());
|
|
59
33
|
if (signal?.aborted)
|
|
60
34
|
throw new Error("Aborted");
|
|
@@ -67,11 +41,11 @@ export class PiAdapter {
|
|
|
67
41
|
const model = modelRuntime.getModel(this.config.provider, this.config.model);
|
|
68
42
|
// Keep a reference to the raw promise so we can clean up a late-arriving session
|
|
69
43
|
const sessionPromise = createAgentSession({
|
|
70
|
-
cwd
|
|
44
|
+
cwd,
|
|
71
45
|
agentDir,
|
|
72
46
|
modelRuntime,
|
|
73
47
|
model,
|
|
74
|
-
sessionManager: SessionManager.inMemory(
|
|
48
|
+
sessionManager: SessionManager.inMemory(cwd),
|
|
75
49
|
resourceLoader,
|
|
76
50
|
});
|
|
77
51
|
try {
|
|
@@ -127,8 +101,8 @@ export class PiAdapter {
|
|
|
127
101
|
* pi 1.x settles the prompt by resolving it (not rejecting), so abort is
|
|
128
102
|
* re-checked after prompt() returns.
|
|
129
103
|
*/
|
|
130
|
-
async ask(prompt,
|
|
131
|
-
const signal =
|
|
104
|
+
async ask(prompt, call) {
|
|
105
|
+
const { cwd, system, signal } = call;
|
|
132
106
|
if (signal?.aborted)
|
|
133
107
|
throw new Error("Aborted");
|
|
134
108
|
// Track session so abort can dispose it at any point — even during createSession
|
|
@@ -136,7 +110,7 @@ export class PiAdapter {
|
|
|
136
110
|
const onAbort = () => session?.dispose();
|
|
137
111
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
138
112
|
try {
|
|
139
|
-
session = await this.createSession(
|
|
113
|
+
session = await this.createSession(cwd, system, signal);
|
|
140
114
|
// Re-check: abort may have fired during createSession (before session existed)
|
|
141
115
|
if (signal?.aborted)
|
|
142
116
|
throw new Error("Aborted");
|
|
@@ -155,12 +129,4 @@ export class PiAdapter {
|
|
|
155
129
|
session?.dispose();
|
|
156
130
|
}
|
|
157
131
|
}
|
|
158
|
-
async repair(input, signal) {
|
|
159
|
-
const response = await this.ask(`Fix this program so it runs.\n\n` +
|
|
160
|
-
`Runtime types:\n${input.runtimeTypes}\n\n` +
|
|
161
|
-
`Broken program:\n${input.programSource}\n\n` +
|
|
162
|
-
`Error:\n${input.error}\n\n` +
|
|
163
|
-
`Output ONLY the fixed program. No explanation.`, { system: "You are a TypeScript repair tool.", signal });
|
|
164
|
-
return stripCodeFences(response);
|
|
165
|
-
}
|
|
166
132
|
}
|
package/dist/runner-types.d.ts
CHANGED
|
@@ -5,24 +5,35 @@ export interface ProgramResult {
|
|
|
5
5
|
/** From ctx.done(result), if provided. */
|
|
6
6
|
result?: unknown;
|
|
7
7
|
}
|
|
8
|
-
|
|
8
|
+
/** Which model serves a project's LLM calls. */
|
|
9
|
+
export interface ModelConfig {
|
|
9
10
|
provider: string;
|
|
10
11
|
model: string;
|
|
11
12
|
}
|
|
12
13
|
export interface RunOptions {
|
|
13
14
|
projectDir: string;
|
|
14
15
|
maxRepairAttempts?: number;
|
|
16
|
+
/**
|
|
17
|
+
* Per-phase limit in ms on the program's own time, for each run and each
|
|
18
|
+
* repair attempt. Time during which a run the program started with
|
|
19
|
+
* runProgram() — a session participant — is in flight is not counted: that
|
|
20
|
+
* run has a timeout of its own.
|
|
21
|
+
*/
|
|
15
22
|
timeout?: number;
|
|
16
23
|
args?: Record<string, unknown>;
|
|
17
24
|
/** Shared workspace directory. When set, workspace.* API is enabled for the program. */
|
|
18
25
|
workspaceDir?: string;
|
|
26
|
+
/** A name for this run — a participant's, say. Its output is shown under it. */
|
|
27
|
+
label?: string;
|
|
28
|
+
/**
|
|
29
|
+
* Stops the run: its program is stopped, no repair is attempted, and the
|
|
30
|
+
* run ends as failed. A fix that was being tried leaves no trace.
|
|
31
|
+
*/
|
|
32
|
+
signal?: AbortSignal;
|
|
19
33
|
}
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
runtimeTypes: string;
|
|
24
|
-
}
|
|
25
|
-
export interface TramaConfig extends PiAdapterConfig {
|
|
34
|
+
/** A run as one program asks its runner for it: everything in RunOptions that can cross the bridge. */
|
|
35
|
+
export type RunRequest = Omit<RunOptions, "signal">;
|
|
36
|
+
export interface TramaConfig extends ModelConfig {
|
|
26
37
|
maxRepairAttempts: number;
|
|
27
38
|
defaultTimeout: number;
|
|
28
39
|
defaultMaxIterations: number;
|
package/dist/runner.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { RunOptions, TramaConfig, ProgramResult } from "./runner-types.js";
|
|
2
|
-
import {
|
|
2
|
+
import { type AgentBackend } from "./agent-backend.js";
|
|
3
3
|
/**
|
|
4
4
|
* Everything a project directory needs around program.ts before it can run:
|
|
5
5
|
* history/ and logs/, an ESM package.json, .gitignore entries, and links to the
|
|
@@ -16,6 +16,11 @@ export declare const RUNTIME_TYPES: string;
|
|
|
16
16
|
export declare function loadConfig(): TramaConfig;
|
|
17
17
|
/** The global config, with the model/provider a project was created with taking precedence. */
|
|
18
18
|
export declare function loadProjectConfig(projectDir: string): TramaConfig;
|
|
19
|
+
/**
|
|
20
|
+
* What does the LLM work for a project. The only place that picks a backend:
|
|
21
|
+
* everything else is handed one and does not know which it is.
|
|
22
|
+
*/
|
|
23
|
+
export declare function createBackend(config: TramaConfig): AgentBackend;
|
|
19
24
|
export declare function loadState(projectDir: string): Record<string, unknown>;
|
|
20
25
|
/**
|
|
21
26
|
* Save the current program.ts as the next version: copy it to history/NNNN.ts
|
|
@@ -33,7 +38,7 @@ export declare function snapshotDir(dir: string, prefix?: string): DirSnapshot;
|
|
|
33
38
|
/**
|
|
34
39
|
* Merge what a run did to a staged copy back into the real directory, with a
|
|
35
40
|
* three-way check so that nothing changed in the real directory meanwhile —
|
|
36
|
-
* by
|
|
41
|
+
* by the user, or by another run of the same project — is overwritten.
|
|
37
42
|
*
|
|
38
43
|
* @param stagedDir - the copy after the run (source of changes)
|
|
39
44
|
* @param realDir - the real directory (destination)
|
|
@@ -49,6 +54,8 @@ export declare function snapshotDir(dir: string, prefix?: string): DirSnapshot;
|
|
|
49
54
|
export declare function commitStagedChanges(stagedDir: string, realDir: string, stagedBefore: DirSnapshot, realSeed: DirSnapshot): void;
|
|
50
55
|
/** Run fn in a temp directory, clean up afterwards regardless of outcome — including this process being stopped. */
|
|
51
56
|
export declare function withTempDir<T>(prefix: string, fn: (dir: string) => Promise<T>): Promise<T>;
|
|
57
|
+
/** The instructions a request for a fix is made under. (Exported so the tests' stand-in LLM can tell one from any other call.) */
|
|
58
|
+
export declare const REPAIR_SYSTEM_PROMPT = "You are a TypeScript repair tool.";
|
|
52
59
|
/**
|
|
53
60
|
* Validate a candidate program.ts for a project without touching the project:
|
|
54
61
|
* run it (with repair) in a throwaway copy. Returns the program that worked —
|
|
@@ -56,9 +63,11 @@ export declare function withTempDir<T>(prefix: string, fn: (dir: string) => Prom
|
|
|
56
63
|
* repaired. Throws if it cannot be made to run.
|
|
57
64
|
*
|
|
58
65
|
* Only the project's own files are shielded. What the program does beyond
|
|
59
|
-
* them — network calls, shell commands,
|
|
66
|
+
* them — network calls, shell commands, agent calls — is real. A run it asks
|
|
67
|
+
* its runner for is not started: the validation ends where it asks for the
|
|
68
|
+
* first.
|
|
60
69
|
*/
|
|
61
|
-
export declare function validateProgram(projectDir: string,
|
|
70
|
+
export declare function validateProgram(projectDir: string, backend: AgentBackend, candidate: string, options: {
|
|
62
71
|
timeout: number;
|
|
63
72
|
maxRepairAttempts: number;
|
|
64
73
|
maxIterations: number;
|
|
@@ -75,5 +84,13 @@ export declare function installValidatedProgram(projectDir: string, validated: {
|
|
|
75
84
|
source: string;
|
|
76
85
|
repairedError?: string;
|
|
77
86
|
}, reason: "create" | "update", prompt: string): void;
|
|
78
|
-
|
|
87
|
+
/**
|
|
88
|
+
* Run a project, in this process: this is what a runner does.
|
|
89
|
+
*
|
|
90
|
+
* `depth` is how many runs deep this one is — 0 unless a program asked for it
|
|
91
|
+
* (see the "/run/program" call), in which case it is one more than that
|
|
92
|
+
* program's own. One runner carries the whole tree, so it is also where the
|
|
93
|
+
* tree is kept from growing without bound.
|
|
94
|
+
*/
|
|
95
|
+
export declare function runProgram(options: RunOptions, depth?: number): Promise<ProgramResult>;
|
|
79
96
|
export {};
|