@trama-dev/runtime 0.2.2 → 0.3.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 +18 -0
- package/dist/agent-backend.js +9 -0
- package/dist/agent.d.ts +12 -2
- package/dist/agent.js +23 -6
- package/dist/bridge-client.d.ts +17 -0
- package/dist/bridge-client.js +52 -0
- package/dist/child-process.d.ts +40 -7
- package/dist/child-process.js +180 -25
- package/dist/client.js +2 -39
- package/dist/index.js +12 -11
- package/dist/ipc-server.d.ts +2 -0
- package/dist/ipc-server.js +21 -3
- package/dist/lifetime.d.ts +8 -4
- package/dist/lifetime.js +32 -17
- package/dist/pi-adapter.d.ts +6 -13
- package/dist/pi-adapter.js +9 -32
- package/dist/runner-types.d.ts +9 -7
- package/dist/runner.d.ts +10 -3
- package/dist/runner.js +112 -52
- package/dist/tools.d.ts +2 -2
- package/dist/tools.js +13 -11
- package/package.json +1 -1
package/dist/ipc-server.js
CHANGED
|
@@ -28,7 +28,7 @@ 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, onTerminalSignal, holdClock }) {
|
|
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");
|
|
@@ -86,6 +86,18 @@ function buildRoutes({ ctx, agent, tools, workspace, onTerminalSignal }) {
|
|
|
86
86
|
onTerminalSignal({ status: "yielded", reason: b.reason });
|
|
87
87
|
},
|
|
88
88
|
},
|
|
89
|
+
// A run the program starts — a session participant — is under a timeout
|
|
90
|
+
// of its own, and the program's clock stops while it lasts (see
|
|
91
|
+
// holdParentClock). The hold is the connection: it ends when the caller
|
|
92
|
+
// closes it, and cannot outlast a caller that dies without doing so.
|
|
93
|
+
"/clock/hold": {
|
|
94
|
+
fields: {},
|
|
95
|
+
handle: async (_body, connectionClosed) => {
|
|
96
|
+
const release = holdClock();
|
|
97
|
+
await connectionClosed;
|
|
98
|
+
release();
|
|
99
|
+
},
|
|
100
|
+
},
|
|
89
101
|
"/workspace/read": { fields: { path: "string" }, handle: b => inSession().read(b.path) },
|
|
90
102
|
"/workspace/write": {
|
|
91
103
|
fields: { path: "string", content: "string" },
|
|
@@ -101,7 +113,10 @@ function buildRoutes({ ctx, agent, tools, workspace, onTerminalSignal }) {
|
|
|
101
113
|
export function createIPCServer(backends) {
|
|
102
114
|
const routes = buildRoutes(backends);
|
|
103
115
|
return createServer((req, res) => {
|
|
116
|
+
const connectionClosed = new Promise(resolve => res.once("close", resolve));
|
|
104
117
|
const reply = (status, body, json = false) => {
|
|
118
|
+
if (res.writableEnded || res.destroyed)
|
|
119
|
+
return; // answered already, or nobody left to answer
|
|
105
120
|
res.writeHead(status, json ? { "Content-Type": "application/json" } : undefined);
|
|
106
121
|
res.end(body);
|
|
107
122
|
};
|
|
@@ -120,9 +135,12 @@ export function createIPCServer(backends) {
|
|
|
120
135
|
chunks.push(chunk);
|
|
121
136
|
byteCount += chunk.length;
|
|
122
137
|
if (byteCount > MAX_IPC_BODY) {
|
|
138
|
+
// Answer now, and let the rest of the body arrive and be discarded.
|
|
139
|
+
// Cutting the connection instead would race the answer: a sender still
|
|
140
|
+
// writing sees a broken connection, not the reason for it.
|
|
123
141
|
overflow = true;
|
|
142
|
+
chunks.length = 0;
|
|
124
143
|
reply(413, "IPC request body exceeds 50MB limit");
|
|
125
|
-
req.destroy();
|
|
126
144
|
}
|
|
127
145
|
});
|
|
128
146
|
req.on("end", async () => {
|
|
@@ -134,7 +152,7 @@ export function createIPCServer(backends) {
|
|
|
134
152
|
if (!route)
|
|
135
153
|
return reply(404, "Not found");
|
|
136
154
|
validate(body, route.fields);
|
|
137
|
-
const result = await route.handle(body);
|
|
155
|
+
const result = await route.handle(body, connectionClosed);
|
|
138
156
|
reply(200, JSON.stringify({ result: result ?? null }), true);
|
|
139
157
|
}
|
|
140
158
|
catch (err) {
|
package/dist/lifetime.d.ts
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Register
|
|
3
|
-
*
|
|
4
|
-
* dealt with in the normal course of the run.
|
|
2
|
+
* Register a process group this process started: if this process ends before
|
|
3
|
+
* the returned function is called, the group is stopped (see stopGroupsOnExit).
|
|
5
4
|
*/
|
|
6
|
-
export declare function
|
|
5
|
+
export declare function stopWithThisProcess(pgid: number): () => void;
|
|
6
|
+
/**
|
|
7
|
+
* Register a temp directory this process created: if this process ends before
|
|
8
|
+
* the returned function is called, the directory is removed.
|
|
9
|
+
*/
|
|
10
|
+
export declare function removeWithThisProcess(dir: string): () => void;
|
|
7
11
|
/** Remove a temp directory. Best-effort: failing to clean up must never change a run's outcome. */
|
|
8
12
|
export declare function removeTempDir(dir: string): void;
|
package/dist/lifetime.js
CHANGED
|
@@ -7,17 +7,22 @@
|
|
|
7
7
|
// program running, and a program that coordinates others (a session) would
|
|
8
8
|
// leave them running when it ended.
|
|
9
9
|
import { rmSync } from "fs";
|
|
10
|
+
import { stopGroupsOnExit } from "./child-process.js";
|
|
10
11
|
const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
11
|
-
const
|
|
12
|
+
const pendingGroups = new Set();
|
|
13
|
+
const pendingDirs = new Set();
|
|
12
14
|
let installed = false;
|
|
13
15
|
function runPending() {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
16
|
+
const groups = [...pendingGroups];
|
|
17
|
+
const dirs = [...pendingDirs];
|
|
18
|
+
pendingGroups.clear();
|
|
19
|
+
pendingDirs.clear();
|
|
20
|
+
// The groups are asked to stop and given a moment; whatever sees that through
|
|
21
|
+
// also removes the directories again once they are gone, in case they were
|
|
22
|
+
// still writing to them.
|
|
23
|
+
stopGroupsOnExit(groups, dirs);
|
|
24
|
+
for (const dir of dirs)
|
|
25
|
+
removeTempDir(dir);
|
|
21
26
|
}
|
|
22
27
|
function onSignal(signal) {
|
|
23
28
|
runPending();
|
|
@@ -47,20 +52,30 @@ function uninstall() {
|
|
|
47
52
|
for (const signal of SIGNALS)
|
|
48
53
|
process.removeListener(signal, onSignal);
|
|
49
54
|
}
|
|
50
|
-
/**
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
* dealt with in the normal course of the run.
|
|
54
|
-
*/
|
|
55
|
-
export function untilSettled(undo) {
|
|
56
|
-
pending.add(undo);
|
|
55
|
+
/** Keep `item` pending until the returned function is called. */
|
|
56
|
+
function track(pending, item) {
|
|
57
|
+
pending.add(item);
|
|
57
58
|
install();
|
|
58
59
|
return () => {
|
|
59
|
-
pending.delete(
|
|
60
|
-
if (
|
|
60
|
+
pending.delete(item);
|
|
61
|
+
if (pendingGroups.size === 0 && pendingDirs.size === 0)
|
|
61
62
|
uninstall();
|
|
62
63
|
};
|
|
63
64
|
}
|
|
65
|
+
/**
|
|
66
|
+
* Register a process group this process started: if this process ends before
|
|
67
|
+
* the returned function is called, the group is stopped (see stopGroupsOnExit).
|
|
68
|
+
*/
|
|
69
|
+
export function stopWithThisProcess(pgid) {
|
|
70
|
+
return track(pendingGroups, pgid);
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Register a temp directory this process created: if this process ends before
|
|
74
|
+
* the returned function is called, the directory is removed.
|
|
75
|
+
*/
|
|
76
|
+
export function removeWithThisProcess(dir) {
|
|
77
|
+
return track(pendingDirs, dir);
|
|
78
|
+
}
|
|
64
79
|
/** Remove a temp directory. Best-effort: failing to clean up must never change a run's outcome. */
|
|
65
80
|
export function removeTempDir(dir) {
|
|
66
81
|
try {
|
package/dist/pi-adapter.d.ts
CHANGED
|
@@ -1,14 +1,11 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { AgentBackend, 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
4
|
export { VERSION as PI_VERSION } from "@earendil-works/pi-coding-agent";
|
|
4
|
-
/**
|
|
5
|
-
export declare
|
|
6
|
-
export declare class PiAdapter {
|
|
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,35 +1,20 @@
|
|
|
1
1
|
import { createAgentSession, SessionManager, DefaultResourceLoader, ModelRuntime, getAgentDir, } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
/** The pi version this runtime is built against (recorded in each project's meta.json). */
|
|
3
3
|
export { VERSION as PI_VERSION } from "@earendil-works/pi-coding-agent";
|
|
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
|
-
}
|
|
14
4
|
/** provider/model pairs already warned about, so a loop of agent calls warns once per process. */
|
|
15
5
|
const warnedUnknownModels = new Set();
|
|
6
|
+
/** The pi coding agent, run in-process: a fresh in-memory session for every call. */
|
|
16
7
|
export class PiAdapter {
|
|
17
8
|
config;
|
|
18
|
-
|
|
19
|
-
constructor(config, cwd) {
|
|
9
|
+
constructor(config) {
|
|
20
10
|
this.config = config;
|
|
21
|
-
this.cwd = cwd;
|
|
22
11
|
}
|
|
23
|
-
|
|
24
|
-
withCwd(cwd) {
|
|
25
|
-
return new PiAdapter(this.config, cwd);
|
|
26
|
-
}
|
|
27
|
-
async createSession(systemPrompt, signal) {
|
|
12
|
+
async createSession(cwd, systemPrompt, signal) {
|
|
28
13
|
if (signal?.aborted)
|
|
29
14
|
throw new Error("Aborted");
|
|
30
15
|
const agentDir = getAgentDir();
|
|
31
16
|
const resourceLoader = new DefaultResourceLoader({
|
|
32
|
-
cwd
|
|
17
|
+
cwd,
|
|
33
18
|
agentDir,
|
|
34
19
|
noExtensions: true,
|
|
35
20
|
noSkills: true,
|
|
@@ -67,11 +52,11 @@ export class PiAdapter {
|
|
|
67
52
|
const model = modelRuntime.getModel(this.config.provider, this.config.model);
|
|
68
53
|
// Keep a reference to the raw promise so we can clean up a late-arriving session
|
|
69
54
|
const sessionPromise = createAgentSession({
|
|
70
|
-
cwd
|
|
55
|
+
cwd,
|
|
71
56
|
agentDir,
|
|
72
57
|
modelRuntime,
|
|
73
58
|
model,
|
|
74
|
-
sessionManager: SessionManager.inMemory(
|
|
59
|
+
sessionManager: SessionManager.inMemory(cwd),
|
|
75
60
|
resourceLoader,
|
|
76
61
|
});
|
|
77
62
|
try {
|
|
@@ -127,8 +112,8 @@ export class PiAdapter {
|
|
|
127
112
|
* pi 1.x settles the prompt by resolving it (not rejecting), so abort is
|
|
128
113
|
* re-checked after prompt() returns.
|
|
129
114
|
*/
|
|
130
|
-
async ask(prompt,
|
|
131
|
-
const signal =
|
|
115
|
+
async ask(prompt, call) {
|
|
116
|
+
const { cwd, system, signal } = call;
|
|
132
117
|
if (signal?.aborted)
|
|
133
118
|
throw new Error("Aborted");
|
|
134
119
|
// Track session so abort can dispose it at any point — even during createSession
|
|
@@ -136,7 +121,7 @@ export class PiAdapter {
|
|
|
136
121
|
const onAbort = () => session?.dispose();
|
|
137
122
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
138
123
|
try {
|
|
139
|
-
session = await this.createSession(
|
|
124
|
+
session = await this.createSession(cwd, system, signal);
|
|
140
125
|
// Re-check: abort may have fired during createSession (before session existed)
|
|
141
126
|
if (signal?.aborted)
|
|
142
127
|
throw new Error("Aborted");
|
|
@@ -155,12 +140,4 @@ export class PiAdapter {
|
|
|
155
140
|
session?.dispose();
|
|
156
141
|
}
|
|
157
142
|
}
|
|
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
143
|
}
|
package/dist/runner-types.d.ts
CHANGED
|
@@ -5,24 +5,26 @@ 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;
|
|
19
26
|
}
|
|
20
|
-
export interface
|
|
21
|
-
programSource: string;
|
|
22
|
-
error: string;
|
|
23
|
-
runtimeTypes: string;
|
|
24
|
-
}
|
|
25
|
-
export interface TramaConfig extends PiAdapterConfig {
|
|
27
|
+
export interface TramaConfig extends ModelConfig {
|
|
26
28
|
maxRepairAttempts: number;
|
|
27
29
|
defaultTimeout: number;
|
|
28
30
|
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 —
|
|
@@ -58,7 +65,7 @@ export declare function withTempDir<T>(prefix: string, fn: (dir: string) => Prom
|
|
|
58
65
|
* Only the project's own files are shielded. What the program does beyond
|
|
59
66
|
* them — network calls, shell commands, other projects it runs — is real.
|
|
60
67
|
*/
|
|
61
|
-
export declare function validateProgram(projectDir: string,
|
|
68
|
+
export declare function validateProgram(projectDir: string, backend: AgentBackend, candidate: string, options: {
|
|
62
69
|
timeout: number;
|
|
63
70
|
maxRepairAttempts: number;
|
|
64
71
|
maxIterations: number;
|
package/dist/runner.js
CHANGED
|
@@ -6,18 +6,25 @@ import { fileURLToPath } from "url";
|
|
|
6
6
|
import { randomBytes } from "crypto";
|
|
7
7
|
import { PiAdapter } from "./pi-adapter.js";
|
|
8
8
|
import { createContext } from "./context.js";
|
|
9
|
-
import { createAgent } from "./agent.js";
|
|
9
|
+
import { createAgent, stripCodeFences } from "./agent.js";
|
|
10
10
|
import { createTools } from "./tools.js";
|
|
11
11
|
import { createWorkspace } from "./workspace.js";
|
|
12
12
|
import { guardPath } from "./path-guard.js";
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
13
|
+
import { createAllowance, stopGroups, superviseChild } from "./child-process.js";
|
|
14
|
+
import { openBridge } from "./bridge-client.js";
|
|
15
|
+
import { removeTempDir, removeWithThisProcess, stopWithThisProcess } from "./lifetime.js";
|
|
15
16
|
import { createIPCServer, listen, closeServer } from "./ipc-server.js";
|
|
16
17
|
// --- Locating the runtime itself ---
|
|
17
18
|
/** The installed @trama-dev/runtime package — this file lives in its dist/. */
|
|
18
19
|
const RUNTIME_PACKAGE_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
|
|
19
|
-
/**
|
|
20
|
-
|
|
20
|
+
/**
|
|
21
|
+
* tsx lets node run program.ts. Resolved through the module system, so any
|
|
22
|
+
* install layout works. It is loaded into the program's own node process
|
|
23
|
+
* rather than run as the `tsx` command, which puts a process of its own in
|
|
24
|
+
* front of the program: one that kills the program some 60 ms after a SIGTERM
|
|
25
|
+
* it has not acted on, and reports its death by signal as an exit code.
|
|
26
|
+
*/
|
|
27
|
+
const TSX_LOADER = import.meta.resolve("tsx");
|
|
21
28
|
/**
|
|
22
29
|
* The @trama-dev packages a program.ts can import, and where they are installed.
|
|
23
30
|
* The runtime always; the session layer when it is installed alongside (as it
|
|
@@ -181,6 +188,13 @@ export function loadProjectConfig(projectDir) {
|
|
|
181
188
|
config.provider = meta.provider;
|
|
182
189
|
return config;
|
|
183
190
|
}
|
|
191
|
+
/**
|
|
192
|
+
* What does the LLM work for a project. The only place that picks a backend:
|
|
193
|
+
* everything else is handed one and does not know which it is.
|
|
194
|
+
*/
|
|
195
|
+
export function createBackend(config) {
|
|
196
|
+
return new PiAdapter(config);
|
|
197
|
+
}
|
|
184
198
|
export function loadState(projectDir) {
|
|
185
199
|
const statePath = guardPath(projectDir, "state.json");
|
|
186
200
|
if (!existsSync(statePath))
|
|
@@ -260,7 +274,7 @@ const sameStat = (a, b) => a.size === b.size && a.mtimeMs === b.mtimeMs;
|
|
|
260
274
|
/**
|
|
261
275
|
* Merge what a run did to a staged copy back into the real directory, with a
|
|
262
276
|
* three-way check so that nothing changed in the real directory meanwhile —
|
|
263
|
-
* by
|
|
277
|
+
* by the user, or by another run of the same project — is overwritten.
|
|
264
278
|
*
|
|
265
279
|
* @param stagedDir - the copy after the run (source of changes)
|
|
266
280
|
* @param realDir - the real directory (destination)
|
|
@@ -314,7 +328,7 @@ export function commitStagedChanges(stagedDir, realDir, stagedBefore, realSeed)
|
|
|
314
328
|
/** Run fn in a temp directory, clean up afterwards regardless of outcome — including this process being stopped. */
|
|
315
329
|
export async function withTempDir(prefix, fn) {
|
|
316
330
|
const dir = mkdtempSync(join(tmpdir(), prefix));
|
|
317
|
-
const settled =
|
|
331
|
+
const settled = removeWithThisProcess(dir);
|
|
318
332
|
try {
|
|
319
333
|
return await fn(dir);
|
|
320
334
|
}
|
|
@@ -405,7 +419,7 @@ function settle(projectDir, child, terminalSignal) {
|
|
|
405
419
|
* (bad project, server or spawn failure) or left state.json unreadable.
|
|
406
420
|
*/
|
|
407
421
|
async function runProgramOnce(options) {
|
|
408
|
-
const { projectDir,
|
|
422
|
+
const { projectDir, backend, timeout, maxIterations, argsOverride, stopOnReady, workspaceDir } = options;
|
|
409
423
|
ensureProjectScaffold(projectDir);
|
|
410
424
|
// Cancels in-flight LLM calls, fetches and observes once the run is over.
|
|
411
425
|
const runEnded = new AbortController();
|
|
@@ -423,20 +437,25 @@ async function runProgramOnce(options) {
|
|
|
423
437
|
// Truncate logs only after preflight succeeds — preserves the prior run's
|
|
424
438
|
// diagnostics if scaffolding, state loading, or context creation fails.
|
|
425
439
|
writeFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), "");
|
|
440
|
+
// The program's own time. It stops while a run the program started is in flight.
|
|
441
|
+
const allowance = createAllowance(timeout);
|
|
426
442
|
const tools = createTools(projectDir, runEnded.signal);
|
|
427
443
|
// Known only to this run's program, through its init file.
|
|
428
444
|
const token = randomBytes(32).toString("hex");
|
|
429
445
|
const server = createIPCServer({
|
|
430
446
|
token,
|
|
431
447
|
ctx,
|
|
432
|
-
agent: createAgent(
|
|
448
|
+
agent: createAgent(backend, projectDir, runEnded.signal),
|
|
433
449
|
tools,
|
|
434
450
|
workspace: workspaceDir ? createWorkspace(workspaceDir, runEnded.signal) : null,
|
|
435
451
|
// The first terminal signal wins; ctx itself rejects a conflicting second one.
|
|
436
452
|
onTerminalSignal: result => { terminalSignal ??= result; },
|
|
453
|
+
holdClock: () => allowance.hold(),
|
|
437
454
|
});
|
|
438
|
-
//
|
|
439
|
-
let
|
|
455
|
+
// The program leads a process group of its own, so that everything it starts is in it.
|
|
456
|
+
let programGroup;
|
|
457
|
+
// If this process is stopped while the program is running, the program is stopped with it.
|
|
458
|
+
let programSettled = () => { };
|
|
440
459
|
try {
|
|
441
460
|
const child = await withTempDir("trama-init-", async (initDir) => {
|
|
442
461
|
const port = await listen(server);
|
|
@@ -450,17 +469,17 @@ async function runProgramOnce(options) {
|
|
|
450
469
|
resumed: ctx.resumed,
|
|
451
470
|
yieldReason: ctx.yieldReason,
|
|
452
471
|
});
|
|
453
|
-
const program = spawn(process.execPath, [
|
|
472
|
+
const program = spawn(process.execPath, ["--import", TSX_LOADER, guardPath(projectDir, "program.ts")], {
|
|
454
473
|
cwd: projectDir,
|
|
455
474
|
env: { ...process.env, TRAMA_PORT: String(port), TRAMA_INIT: initFile },
|
|
456
475
|
stdio: ["ignore", "pipe", "pipe"],
|
|
457
476
|
detached: true,
|
|
458
477
|
});
|
|
459
|
-
|
|
460
|
-
if (
|
|
461
|
-
|
|
478
|
+
programGroup = program.pid;
|
|
479
|
+
if (programGroup)
|
|
480
|
+
programSettled = stopWithThisProcess(programGroup);
|
|
462
481
|
return toChildResult(await superviseChild(program, {
|
|
463
|
-
timeout,
|
|
482
|
+
timeout: allowance,
|
|
464
483
|
stopSignal: stopOnReady ? readyStop.signal : undefined,
|
|
465
484
|
sinks: {
|
|
466
485
|
stdout: chunk => { process.stdout.write(chunk); },
|
|
@@ -471,22 +490,31 @@ async function runProgramOnce(options) {
|
|
|
471
490
|
return { outcome: settle(projectDir, child, terminalSignal), failure: describeFailure(child) };
|
|
472
491
|
}
|
|
473
492
|
finally {
|
|
474
|
-
// The program is gone (or never started)
|
|
475
|
-
//
|
|
476
|
-
|
|
493
|
+
// The program is gone (or never started). Nothing it started outlives its
|
|
494
|
+
// run: cancel the calls it left in flight, and stop what is left of its
|
|
495
|
+
// process group and of its shell commands. Only once they are gone is the
|
|
496
|
+
// run over — whoever called will merge or delete what they were writing to.
|
|
477
497
|
if (readyTimer)
|
|
478
498
|
clearTimeout(readyTimer);
|
|
479
499
|
runEnded.abort();
|
|
480
|
-
tools.
|
|
500
|
+
await Promise.all([stopGroups(programGroup ? [programGroup] : []), tools.stopActiveShells()]);
|
|
501
|
+
programSettled();
|
|
481
502
|
server.closeAllConnections();
|
|
482
503
|
await closeServer(server).catch(() => { });
|
|
483
504
|
}
|
|
484
505
|
}
|
|
506
|
+
/** The instructions a request for a fix is made under. (Exported so the tests' stand-in LLM can tell one from any other call.) */
|
|
507
|
+
export const REPAIR_SYSTEM_PROMPT = "You are a TypeScript repair tool.";
|
|
508
|
+
const repairPrompt = (input) => `Fix this program so it runs.\n\n` +
|
|
509
|
+
`Runtime types:\n${RUNTIME_TYPES}\n\n` +
|
|
510
|
+
`Broken program:\n${input.programSource}\n\n` +
|
|
511
|
+
`Error:\n${input.error}\n\n` +
|
|
512
|
+
`Output ONLY the fixed program. No explanation.`;
|
|
485
513
|
/**
|
|
486
|
-
* Ask the LLM for a fix. The
|
|
487
|
-
*
|
|
488
|
-
*
|
|
489
|
-
*
|
|
514
|
+
* Ask the LLM for a fix. The agent has tools, so it works in a throwaway copy
|
|
515
|
+
* of the project that holds the program it is asked to fix — whatever it reads
|
|
516
|
+
* is real, whatever it writes is discarded; only the program text it returns
|
|
517
|
+
* is used. Bounded by its own timeout.
|
|
490
518
|
* Returns null (and records why) if no usable fix came back.
|
|
491
519
|
*/
|
|
492
520
|
async function requestRepair(options, input, repairErrors) {
|
|
@@ -496,7 +524,9 @@ async function requestRepair(options, input, repairErrors) {
|
|
|
496
524
|
const controller = new AbortController();
|
|
497
525
|
const timer = setTimeout(() => controller.abort(), options.timeout);
|
|
498
526
|
try {
|
|
499
|
-
const fixed = await options.
|
|
527
|
+
const fixed = stripCodeFences(await options.backend.ask(repairPrompt(input), {
|
|
528
|
+
cwd: tempDir, system: REPAIR_SYSTEM_PROMPT, signal: controller.signal,
|
|
529
|
+
}));
|
|
500
530
|
if (fixed.trim() === "")
|
|
501
531
|
throw new Error("The repair returned an empty program.");
|
|
502
532
|
if (fixed === input.programSource)
|
|
@@ -513,34 +543,32 @@ async function requestRepair(options, input, repairErrors) {
|
|
|
513
543
|
});
|
|
514
544
|
}
|
|
515
545
|
/**
|
|
516
|
-
* Try a proposed fix
|
|
517
|
-
*
|
|
518
|
-
*
|
|
519
|
-
*
|
|
520
|
-
*
|
|
546
|
+
* Try a proposed fix.
|
|
547
|
+
*
|
|
548
|
+
* The project is the program's own, so the fix runs on a private copy of it.
|
|
549
|
+
* Only if it works does anything reach the real one — the fix becomes
|
|
550
|
+
* program.ts, and what the run wrote is merged back. A fix that fails, or a
|
|
551
|
+
* runner that is stopped half-way, leaves the project exactly as it was,
|
|
552
|
+
* because it was never touched: its state is only ever written by code that
|
|
553
|
+
* is, or becomes, its program.
|
|
554
|
+
*
|
|
555
|
+
* The shared workspace is not copied. It is how the participants of a session
|
|
556
|
+
* talk to each other, and a program that is being fixed still has to be heard
|
|
557
|
+
* and answered — a fix that wrote its requests where nobody could see them
|
|
558
|
+
* would wait for replies forever. So what a fix writes there is written,
|
|
559
|
+
* whether or not the fix works: like anything a run wrote before it failed.
|
|
521
560
|
*/
|
|
522
561
|
async function tryFix(options, fixed) {
|
|
523
|
-
const { projectDir
|
|
524
|
-
const
|
|
562
|
+
const { projectDir } = options;
|
|
563
|
+
const run = await withStagedCopy(projectDir, async (stagedProject) => {
|
|
525
564
|
writeFileSync(guardPath(stagedProject, "program.ts"), fixed);
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
}
|
|
532
|
-
catch (err) {
|
|
533
|
-
// The copy could not be run at all, or was left unusable. Either way this fix did not work.
|
|
534
|
-
run = { outcome: null, failure: `The repaired program could not be run: ${err instanceof Error ? err.message : err}` };
|
|
535
|
-
}
|
|
536
|
-
return { commit: run.outcome !== null, value: run };
|
|
565
|
+
// If the copy cannot be run at all, or is left unusable, this fix did not work either.
|
|
566
|
+
const trial = await runProgramOnce({ ...options, projectDir: stagedProject }).catch((err) => ({
|
|
567
|
+
outcome: null,
|
|
568
|
+
failure: `The repaired program could not be run: ${err instanceof Error ? err.message : err}`,
|
|
569
|
+
}));
|
|
570
|
+
return { commit: trial.outcome !== null, value: trial };
|
|
537
571
|
});
|
|
538
|
-
const run = workspaceDir
|
|
539
|
-
? await withStagedCopy(workspaceDir, async (stagedWorkspace) => {
|
|
540
|
-
const value = await inStagedProject(stagedWorkspace);
|
|
541
|
-
return { commit: value.outcome !== null, value };
|
|
542
|
-
})
|
|
543
|
-
: await inStagedProject(undefined);
|
|
544
572
|
// The merge above carries over what the run changed; the fix itself was
|
|
545
573
|
// written before the run started, so it is installed explicitly.
|
|
546
574
|
if (run.outcome)
|
|
@@ -588,7 +616,7 @@ const VALIDATION_READY_GRACE_MS = 2_000;
|
|
|
588
616
|
* Only the project's own files are shielded. What the program does beyond
|
|
589
617
|
* them — network calls, shell commands, other projects it runs — is real.
|
|
590
618
|
*/
|
|
591
|
-
export async function validateProgram(projectDir,
|
|
619
|
+
export async function validateProgram(projectDir, backend, candidate, options) {
|
|
592
620
|
return withTempDir("trama-validate-", async (trialDir) => {
|
|
593
621
|
copyDirInto(projectDir, trialDir);
|
|
594
622
|
const programPath = guardPath(trialDir, "program.ts");
|
|
@@ -596,7 +624,7 @@ export async function validateProgram(projectDir, adapter, candidate, options) {
|
|
|
596
624
|
const { result, repair } = await executeProgram({
|
|
597
625
|
...options,
|
|
598
626
|
projectDir: trialDir,
|
|
599
|
-
|
|
627
|
+
backend,
|
|
600
628
|
stopOnReady: { graceMs: VALIDATION_READY_GRACE_MS },
|
|
601
629
|
});
|
|
602
630
|
if (result.status === "failed") {
|
|
@@ -620,7 +648,39 @@ export function installValidatedProgram(projectDir, validated, reason, prompt) {
|
|
|
620
648
|
copyToHistory(projectDir, reason, prompt);
|
|
621
649
|
}
|
|
622
650
|
// --- Core execution ---
|
|
651
|
+
/**
|
|
652
|
+
* A run started from inside a program — a session participant, typically — is
|
|
653
|
+
* under a timeout of its own. Tell the runner of the program it was started
|
|
654
|
+
* from, so that program's clock stops while this run lasts and it is not
|
|
655
|
+
* killed for the time its participant was entitled to take.
|
|
656
|
+
*
|
|
657
|
+
* Returns what ends the hold. Best-effort: if that runner cannot be reached
|
|
658
|
+
* its program's run is over, and this one is about to be stopped with it.
|
|
659
|
+
*
|
|
660
|
+
* This exists only because the runner of a participant lives inside the
|
|
661
|
+
* program that spawned it, where that program's own runner cannot see it. It
|
|
662
|
+
* goes away once starting a run is itself a call on the bridge.
|
|
663
|
+
*/
|
|
664
|
+
function holdParentClock() {
|
|
665
|
+
const { TRAMA_PORT: port, TRAMA_INIT: initPath } = process.env;
|
|
666
|
+
if (port && initPath) {
|
|
667
|
+
try {
|
|
668
|
+
return openBridge(port, initPath).hold("/clock/hold");
|
|
669
|
+
}
|
|
670
|
+
catch { /* not held */ }
|
|
671
|
+
}
|
|
672
|
+
return () => { };
|
|
673
|
+
}
|
|
623
674
|
export async function runProgram(options) {
|
|
675
|
+
const releaseParentClock = holdParentClock();
|
|
676
|
+
try {
|
|
677
|
+
return await runProject(options);
|
|
678
|
+
}
|
|
679
|
+
finally {
|
|
680
|
+
releaseParentClock();
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
async function runProject(options) {
|
|
624
684
|
const { projectDir } = options;
|
|
625
685
|
if (!existsSync(join(projectDir, "meta.json"))) {
|
|
626
686
|
throw new Error(`Project not found at ${projectDir}. ` +
|
|
@@ -637,7 +697,7 @@ export async function runProgram(options) {
|
|
|
637
697
|
}
|
|
638
698
|
const { result, repair } = await executeProgram({
|
|
639
699
|
projectDir,
|
|
640
|
-
|
|
700
|
+
backend: createBackend(config),
|
|
641
701
|
maxRepairAttempts,
|
|
642
702
|
timeout,
|
|
643
703
|
maxIterations: config.defaultMaxIterations,
|
package/dist/tools.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Tools } from "./types.js";
|
|
2
2
|
export interface ToolsWithCleanup extends Tools {
|
|
3
|
-
/**
|
|
4
|
-
|
|
3
|
+
/** Stop every shell command still running, and anything they left in the background. Resolves when they are gone. */
|
|
4
|
+
stopActiveShells(): Promise<void>;
|
|
5
5
|
}
|
|
6
6
|
export declare function createTools(projectDir: string, signal?: AbortSignal): ToolsWithCleanup;
|