@trama-dev/runtime 0.1.4 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/dist/agent.js +3 -3
- package/dist/child-process.d.ts +40 -0
- package/dist/child-process.js +108 -0
- package/dist/client.d.ts +2 -1
- package/dist/client.js +52 -53
- package/dist/context.d.ts +11 -0
- package/dist/context.js +62 -17
- package/dist/index.d.ts +3 -0
- package/dist/index.js +39 -59
- package/dist/ipc-server.d.ts +22 -0
- package/dist/ipc-server.js +168 -0
- package/dist/path-guard.d.ts +16 -26
- package/dist/path-guard.js +42 -37
- package/dist/pi-adapter.d.ts +11 -2
- package/dist/pi-adapter.js +49 -6
- package/dist/runner-types.d.ts +29 -0
- package/dist/runner-types.js +3 -0
- package/dist/runner.d.ts +58 -21
- package/dist/runner.js +426 -674
- package/dist/tools.d.ts +3 -5
- package/dist/tools.js +70 -166
- package/dist/types.d.ts +35 -29
- package/dist/types.js +4 -1
- package/dist/workspace.d.ts +2 -0
- package/dist/workspace.js +209 -0
- package/package.json +6 -4
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type Server } from "http";
|
|
2
|
+
import type { Ctx, Agent, Tools, Workspace } from "./types.js";
|
|
3
|
+
import type { ProgramResult } from "./runner-types.js";
|
|
4
|
+
export interface IpcBackends {
|
|
5
|
+
/**
|
|
6
|
+
* The secret only this run's program knows. Every request must present it:
|
|
7
|
+
* the server listens on a loopback port that any local process — or a web
|
|
8
|
+
* page the user happens to have open — could otherwise send commands to.
|
|
9
|
+
*/
|
|
10
|
+
token: string;
|
|
11
|
+
ctx: Ctx;
|
|
12
|
+
agent: Agent;
|
|
13
|
+
tools: Tools;
|
|
14
|
+
/** Null when the program is not running in a session. */
|
|
15
|
+
workspace: Workspace | null;
|
|
16
|
+
/** Called once ctx.done() or ctx.yield() has been persisted for this run. */
|
|
17
|
+
onTerminalSignal(result: ProgramResult): void;
|
|
18
|
+
}
|
|
19
|
+
export declare function createIPCServer(backends: IpcBackends): Server;
|
|
20
|
+
/** Start listening on an ephemeral loopback port and return it. */
|
|
21
|
+
export declare function listen(server: Server): Promise<number>;
|
|
22
|
+
export declare function closeServer(server: Server): Promise<void>;
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// The runner side of the IPC bridge. A running program.ts reaches ctx, agent,
|
|
2
|
+
// tools and workspace by POSTing JSON to this local HTTP server (see client.ts
|
|
3
|
+
// for the other end).
|
|
4
|
+
import { createServer } from "http";
|
|
5
|
+
import { timingSafeEqual } from "crypto";
|
|
6
|
+
import { assertSerializable } from "./serializable.js";
|
|
7
|
+
const MAX_IPC_BODY = 50 * 1024 * 1024; // 50 MB
|
|
8
|
+
/** A request the program got wrong — answered with 400 rather than 500. */
|
|
9
|
+
class BadRequest extends Error {
|
|
10
|
+
}
|
|
11
|
+
const isPlainObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
12
|
+
function validate(body, fields) {
|
|
13
|
+
for (const [name, type] of Object.entries(fields)) {
|
|
14
|
+
const value = body[name];
|
|
15
|
+
if (type === "optional object") {
|
|
16
|
+
if (value !== undefined && !isPlainObject(value)) {
|
|
17
|
+
throw new BadRequest(`Invalid field: ${name} (expected object or undefined)`);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
else if (type === "object" ? !isPlainObject(value) : typeof value !== type) {
|
|
21
|
+
throw new BadRequest(`Missing or invalid field: ${name} (expected ${type})`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/** Whether a request carries `Authorization: Bearer <token>`, compared in constant time. */
|
|
26
|
+
function isAuthorized(header, token) {
|
|
27
|
+
const expected = Buffer.from(`Bearer ${token}`);
|
|
28
|
+
const actual = Buffer.from(header ?? "");
|
|
29
|
+
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
30
|
+
}
|
|
31
|
+
function buildRoutes({ ctx, agent, tools, workspace, onTerminalSignal }) {
|
|
32
|
+
/** The program owns ctx.state; each persisting call hands over its current copy. */
|
|
33
|
+
const adoptState = (state) => {
|
|
34
|
+
assertSerializable(state, "ctx.state");
|
|
35
|
+
ctx.state = state;
|
|
36
|
+
};
|
|
37
|
+
const inSession = () => {
|
|
38
|
+
if (!workspace)
|
|
39
|
+
throw new BadRequest("Workspace is only available when running in a session");
|
|
40
|
+
return workspace;
|
|
41
|
+
};
|
|
42
|
+
return {
|
|
43
|
+
"/agent/instruct": {
|
|
44
|
+
fields: { prompt: "string" },
|
|
45
|
+
handle: b => agent.instruct(b.prompt, { system: b.system }),
|
|
46
|
+
},
|
|
47
|
+
"/agent/generate": {
|
|
48
|
+
fields: { prompt: "string", schema: "object" },
|
|
49
|
+
handle: b => agent.generate(b),
|
|
50
|
+
},
|
|
51
|
+
"/tools/read": { fields: { path: "string" }, handle: b => tools.read(b.path) },
|
|
52
|
+
"/tools/write": { fields: { path: "string", content: "string" }, handle: b => tools.write(b.path, b.content) },
|
|
53
|
+
"/tools/shell": {
|
|
54
|
+
fields: { command: "string" },
|
|
55
|
+
handle: b => tools.shell(b.command, { cwd: b.cwd, timeout: b.timeout }),
|
|
56
|
+
},
|
|
57
|
+
"/tools/fetch": {
|
|
58
|
+
fields: { url: "string" },
|
|
59
|
+
handle: b => tools.fetch(b.url, { method: b.method, headers: b.headers, body: b.body }),
|
|
60
|
+
},
|
|
61
|
+
"/ctx/log": { fields: { message: "string" }, handle: b => ctx.log(b.message, b.data) },
|
|
62
|
+
"/ctx/ready": { fields: { data: "optional object" }, handle: b => ctx.ready(b.data) },
|
|
63
|
+
"/ctx/checkpoint": {
|
|
64
|
+
fields: { state: "object" },
|
|
65
|
+
handle: async (b) => {
|
|
66
|
+
adoptState(b.state);
|
|
67
|
+
await ctx.checkpoint();
|
|
68
|
+
return ctx.iteration;
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
"/ctx/done": {
|
|
72
|
+
fields: { state: "object" },
|
|
73
|
+
handle: async (b) => {
|
|
74
|
+
adoptState(b.state);
|
|
75
|
+
await ctx.done(b.result);
|
|
76
|
+
onTerminalSignal({ status: "done", result: b.result ?? undefined });
|
|
77
|
+
return ctx.iteration;
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
"/ctx/yield": {
|
|
81
|
+
fields: { state: "object", reason: "string" },
|
|
82
|
+
handle: async (b) => {
|
|
83
|
+
adoptState(b.state);
|
|
84
|
+
// Persists the yield marker and returns; the program exits itself once we answer.
|
|
85
|
+
await ctx.yield(b.reason);
|
|
86
|
+
onTerminalSignal({ status: "yielded", reason: b.reason });
|
|
87
|
+
},
|
|
88
|
+
},
|
|
89
|
+
"/workspace/read": { fields: { path: "string" }, handle: b => inSession().read(b.path) },
|
|
90
|
+
"/workspace/write": {
|
|
91
|
+
fields: { path: "string", content: "string" },
|
|
92
|
+
handle: b => inSession().write(b.path, b.content),
|
|
93
|
+
},
|
|
94
|
+
"/workspace/list": { fields: { pattern: "string" }, handle: b => inSession().list(b.pattern) },
|
|
95
|
+
"/workspace/observe": {
|
|
96
|
+
fields: { pattern: "string" },
|
|
97
|
+
handle: b => inSession().observe(b.pattern, { expect: b.expect, timeout: b.timeout }),
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
export function createIPCServer(backends) {
|
|
102
|
+
const routes = buildRoutes(backends);
|
|
103
|
+
return createServer((req, res) => {
|
|
104
|
+
const reply = (status, body, json = false) => {
|
|
105
|
+
res.writeHead(status, json ? { "Content-Type": "application/json" } : undefined);
|
|
106
|
+
res.end(body);
|
|
107
|
+
};
|
|
108
|
+
if (req.method !== "POST")
|
|
109
|
+
return reply(405, "Method not allowed");
|
|
110
|
+
if (!isAuthorized(req.headers.authorization, backends.token)) {
|
|
111
|
+
req.resume(); // discard the body
|
|
112
|
+
return reply(401, "Missing or invalid IPC token");
|
|
113
|
+
}
|
|
114
|
+
const chunks = [];
|
|
115
|
+
let byteCount = 0;
|
|
116
|
+
let overflow = false;
|
|
117
|
+
req.on("data", (chunk) => {
|
|
118
|
+
if (overflow)
|
|
119
|
+
return;
|
|
120
|
+
chunks.push(chunk);
|
|
121
|
+
byteCount += chunk.length;
|
|
122
|
+
if (byteCount > MAX_IPC_BODY) {
|
|
123
|
+
overflow = true;
|
|
124
|
+
reply(413, "IPC request body exceeds 50MB limit");
|
|
125
|
+
req.destroy();
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
req.on("end", async () => {
|
|
129
|
+
if (overflow)
|
|
130
|
+
return;
|
|
131
|
+
try {
|
|
132
|
+
const body = JSON.parse(Buffer.concat(chunks).toString("utf-8"));
|
|
133
|
+
const route = req.url ? routes[req.url] : undefined;
|
|
134
|
+
if (!route)
|
|
135
|
+
return reply(404, "Not found");
|
|
136
|
+
validate(body, route.fields);
|
|
137
|
+
const result = await route.handle(body);
|
|
138
|
+
reply(200, JSON.stringify({ result: result ?? null }), true);
|
|
139
|
+
}
|
|
140
|
+
catch (err) {
|
|
141
|
+
reply(err instanceof BadRequest ? 400 : 500, err instanceof BadRequest ? err.message : String(err));
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
/** Start listening on an ephemeral loopback port and return it. */
|
|
147
|
+
export function listen(server) {
|
|
148
|
+
return new Promise((resolve, reject) => {
|
|
149
|
+
server.once("error", reject);
|
|
150
|
+
server.listen(0, "127.0.0.1", () => {
|
|
151
|
+
const addr = server.address();
|
|
152
|
+
if (addr && typeof addr === "object")
|
|
153
|
+
resolve(addr.port);
|
|
154
|
+
else
|
|
155
|
+
reject(new Error("Failed to get server port"));
|
|
156
|
+
});
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
export function closeServer(server) {
|
|
160
|
+
return new Promise((resolve, reject) => {
|
|
161
|
+
server.close(err => {
|
|
162
|
+
if (!err || err.code === "ERR_SERVER_NOT_RUNNING")
|
|
163
|
+
resolve();
|
|
164
|
+
else
|
|
165
|
+
reject(err);
|
|
166
|
+
});
|
|
167
|
+
});
|
|
168
|
+
}
|
package/dist/path-guard.d.ts
CHANGED
|
@@ -1,37 +1,27 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
2
|
+
* Keep file access inside a bounded root directory (a project directory or a
|
|
3
|
+
* session workspace) — rejecting escapes via ".." segments or symlinks.
|
|
4
4
|
*
|
|
5
5
|
* Not a security sandbox — just a footgun guard against malicious shared
|
|
6
6
|
* projects where files like state.json or .gitignore are symlinks pointing
|
|
7
7
|
* outside the project directory.
|
|
8
8
|
*/
|
|
9
|
+
/** True if `path` is `root` itself or lies underneath it. Both must already be normalized. */
|
|
10
|
+
export declare function isInside(path: string, root: string): boolean;
|
|
9
11
|
/**
|
|
10
|
-
* Resolve `relativePath` against `
|
|
11
|
-
* stays within the
|
|
12
|
+
* Resolve `relativePath` against `rootDir` and verify the logical path
|
|
13
|
+
* stays within the root. Returns the resolved absolute path.
|
|
14
|
+
* Catches ".." traversal only — use guardPath to also catch symlink escapes.
|
|
12
15
|
*/
|
|
13
|
-
export declare function resolveBounded(
|
|
16
|
+
export declare function resolveBounded(rootDir: string, relativePath: string): string;
|
|
17
|
+
/** The real (symlink-resolved) location of a root directory, or its normalized path if it doesn't exist yet. */
|
|
18
|
+
export declare function realRootOf(rootDir: string): string;
|
|
14
19
|
/**
|
|
15
|
-
*
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* Walk up from `resolved` to find the deepest existing ancestor,
|
|
20
|
-
* then verify its real path is inside the project dir.
|
|
21
|
-
* This catches symlink escapes BEFORE any mkdir side effects.
|
|
22
|
-
*/
|
|
23
|
-
export declare function verifyNearestAncestor(resolved: string, realProjectDir: string, originalPath: string): void;
|
|
24
|
-
/**
|
|
25
|
-
* Verify that an existing symlink's target resolves inside the project dir.
|
|
26
|
-
* For dangling symlinks, falls back to verifyNearestAncestor on the link target.
|
|
27
|
-
*/
|
|
28
|
-
export declare function verifySymlink(target: string, realProjectDir: string, originalPath: string): void;
|
|
29
|
-
/**
|
|
30
|
-
* All-in-one guard for reading/writing a file in a project directory.
|
|
31
|
-
* Checks both logical path (.. segments) and symlink resolution.
|
|
32
|
-
* Returns the resolved absolute path.
|
|
20
|
+
* The guard for reading or writing a path under a bounded root.
|
|
21
|
+
* Checks both the logical path (".." segments) and symlink resolution,
|
|
22
|
+
* and returns the resolved absolute path.
|
|
33
23
|
*
|
|
34
|
-
* For
|
|
35
|
-
*
|
|
24
|
+
* For paths that don't exist yet, checks the nearest existing ancestor —
|
|
25
|
+
* so a caller can safely mkdir and write afterwards.
|
|
36
26
|
*/
|
|
37
|
-
export declare function guardPath(
|
|
27
|
+
export declare function guardPath(rootDir: string, relativePath: string): string;
|
package/dist/path-guard.js
CHANGED
|
@@ -1,39 +1,41 @@
|
|
|
1
1
|
import { existsSync, realpathSync, lstatSync, readlinkSync } from "fs";
|
|
2
2
|
import { resolve, dirname, sep } from "path";
|
|
3
3
|
/**
|
|
4
|
-
*
|
|
5
|
-
*
|
|
4
|
+
* Keep file access inside a bounded root directory (a project directory or a
|
|
5
|
+
* session workspace) — rejecting escapes via ".." segments or symlinks.
|
|
6
6
|
*
|
|
7
7
|
* Not a security sandbox — just a footgun guard against malicious shared
|
|
8
8
|
* projects where files like state.json or .gitignore are symlinks pointing
|
|
9
9
|
* outside the project directory.
|
|
10
10
|
*/
|
|
11
|
+
/** True if `path` is `root` itself or lies underneath it. Both must already be normalized. */
|
|
12
|
+
export function isInside(path, root) {
|
|
13
|
+
return path === root || path.startsWith(root + sep);
|
|
14
|
+
}
|
|
11
15
|
/**
|
|
12
|
-
* Resolve `relativePath` against `
|
|
13
|
-
* stays within the
|
|
16
|
+
* Resolve `relativePath` against `rootDir` and verify the logical path
|
|
17
|
+
* stays within the root. Returns the resolved absolute path.
|
|
18
|
+
* Catches ".." traversal only — use guardPath to also catch symlink escapes.
|
|
14
19
|
*/
|
|
15
|
-
export function resolveBounded(
|
|
16
|
-
const normalizedDir = resolve(
|
|
20
|
+
export function resolveBounded(rootDir, relativePath) {
|
|
21
|
+
const normalizedDir = resolve(rootDir);
|
|
17
22
|
const resolved = resolve(normalizedDir, relativePath);
|
|
18
|
-
if (resolved
|
|
23
|
+
if (!isInside(resolved, normalizedDir)) {
|
|
19
24
|
throw new Error(`Path escapes project directory: ${relativePath}`);
|
|
20
25
|
}
|
|
21
26
|
return resolved;
|
|
22
27
|
}
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
*/
|
|
26
|
-
export function verifyRealPath(realPath, realProjectDir, originalPath) {
|
|
27
|
-
if (realPath !== realProjectDir && !realPath.startsWith(realProjectDir + sep)) {
|
|
28
|
+
function verifyRealPath(realPath, realRoot, originalPath) {
|
|
29
|
+
if (!isInside(realPath, realRoot)) {
|
|
28
30
|
throw new Error(`Path escapes project directory via symlink: ${originalPath}`);
|
|
29
31
|
}
|
|
30
32
|
}
|
|
31
33
|
/**
|
|
32
34
|
* Walk up from `resolved` to find the deepest existing ancestor,
|
|
33
|
-
* then verify its real path is inside the
|
|
35
|
+
* then verify its real path is inside the root.
|
|
34
36
|
* This catches symlink escapes BEFORE any mkdir side effects.
|
|
35
37
|
*/
|
|
36
|
-
|
|
38
|
+
function verifyNearestAncestor(resolved, realRoot, originalPath) {
|
|
37
39
|
let cur = resolved;
|
|
38
40
|
while (!existsSync(cur)) {
|
|
39
41
|
const parent = dirname(cur);
|
|
@@ -41,42 +43,45 @@ export function verifyNearestAncestor(resolved, realProjectDir, originalPath) {
|
|
|
41
43
|
return; // reached filesystem root — nothing to verify
|
|
42
44
|
cur = parent;
|
|
43
45
|
}
|
|
44
|
-
verifyRealPath(realpathSync(cur),
|
|
46
|
+
verifyRealPath(realpathSync(cur), realRoot, originalPath);
|
|
45
47
|
}
|
|
46
48
|
/**
|
|
47
|
-
* Verify that an existing symlink's target resolves inside the
|
|
49
|
+
* Verify that an existing symlink's target resolves inside the root.
|
|
48
50
|
* For dangling symlinks, falls back to verifyNearestAncestor on the link target.
|
|
49
51
|
*/
|
|
50
|
-
|
|
52
|
+
function verifySymlink(target, realRoot, originalPath) {
|
|
51
53
|
try {
|
|
52
|
-
verifyRealPath(realpathSync(target),
|
|
54
|
+
verifyRealPath(realpathSync(target), realRoot, originalPath);
|
|
53
55
|
}
|
|
54
56
|
catch (e) {
|
|
55
57
|
if (e.code !== "ENOENT")
|
|
56
58
|
throw e;
|
|
57
59
|
// Dangling symlink — resolve what we can via nearest existing ancestor
|
|
58
60
|
const linkDest = resolve(dirname(target), readlinkSync(target));
|
|
59
|
-
verifyNearestAncestor(linkDest,
|
|
61
|
+
verifyNearestAncestor(linkDest, realRoot, originalPath);
|
|
60
62
|
}
|
|
61
63
|
}
|
|
62
|
-
/**
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
* Returns the resolved absolute path.
|
|
66
|
-
*
|
|
67
|
-
* For writes to paths that don't yet exist, checks the nearest existing
|
|
68
|
-
* ancestor to prevent side effects outside the project.
|
|
69
|
-
*/
|
|
70
|
-
export function guardPath(projectDir, relativePath) {
|
|
71
|
-
const normalizedDir = resolve(projectDir);
|
|
72
|
-
let realDir;
|
|
64
|
+
/** The real (symlink-resolved) location of a root directory, or its normalized path if it doesn't exist yet. */
|
|
65
|
+
export function realRootOf(rootDir) {
|
|
66
|
+
const normalizedDir = resolve(rootDir);
|
|
73
67
|
try {
|
|
74
|
-
|
|
68
|
+
return realpathSync(normalizedDir);
|
|
75
69
|
}
|
|
76
70
|
catch {
|
|
77
|
-
|
|
71
|
+
return normalizedDir;
|
|
78
72
|
}
|
|
79
|
-
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* The guard for reading or writing a path under a bounded root.
|
|
76
|
+
* Checks both the logical path (".." segments) and symlink resolution,
|
|
77
|
+
* and returns the resolved absolute path.
|
|
78
|
+
*
|
|
79
|
+
* For paths that don't exist yet, checks the nearest existing ancestor —
|
|
80
|
+
* so a caller can safely mkdir and write afterwards.
|
|
81
|
+
*/
|
|
82
|
+
export function guardPath(rootDir, relativePath) {
|
|
83
|
+
const realRoot = realRootOf(rootDir);
|
|
84
|
+
const resolved = resolveBounded(rootDir, relativePath);
|
|
80
85
|
// Use lstatSync (not existsSync) to detect dangling symlinks.
|
|
81
86
|
// existsSync returns false for dangling symlinks, which would skip the
|
|
82
87
|
// symlink check and allow writes to follow the link to an external target.
|
|
@@ -88,15 +93,15 @@ export function guardPath(projectDir, relativePath) {
|
|
|
88
93
|
if (e.code !== "ENOENT")
|
|
89
94
|
throw e;
|
|
90
95
|
// Path truly doesn't exist (not even as a dangling symlink)
|
|
91
|
-
// — verify nearest ancestor is inside
|
|
92
|
-
verifyNearestAncestor(resolved,
|
|
96
|
+
// — verify nearest ancestor is inside the root
|
|
97
|
+
verifyNearestAncestor(resolved, realRoot, relativePath);
|
|
93
98
|
return resolved;
|
|
94
99
|
}
|
|
95
100
|
if (stat.isSymbolicLink()) {
|
|
96
|
-
verifySymlink(resolved,
|
|
101
|
+
verifySymlink(resolved, realRoot, relativePath);
|
|
97
102
|
}
|
|
98
103
|
else {
|
|
99
|
-
verifyRealPath(realpathSync(resolved),
|
|
104
|
+
verifyRealPath(realpathSync(resolved), realRoot, relativePath);
|
|
100
105
|
}
|
|
101
106
|
return resolved;
|
|
102
107
|
}
|
package/dist/pi-adapter.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import type { PiAdapterConfig, RepairInput } from "./types.js";
|
|
1
|
+
import type { PiAdapterConfig, RepairInput } from "./runner-types.js";
|
|
2
|
+
/** The pi version this runtime is built against (recorded in each project's meta.json). */
|
|
3
|
+
export { VERSION as PI_VERSION } from "@earendil-works/pi-coding-agent";
|
|
2
4
|
/** Strip markdown code fences and trim whitespace. */
|
|
3
5
|
export declare function stripCodeFences(text: string): string;
|
|
4
6
|
export declare class PiAdapter {
|
|
@@ -8,11 +10,18 @@ export declare class PiAdapter {
|
|
|
8
10
|
/** Create a copy of this adapter that operates in a different working directory. */
|
|
9
11
|
withCwd(cwd: string): PiAdapter;
|
|
10
12
|
private createSession;
|
|
13
|
+
/**
|
|
14
|
+
* The configured provider/model is not in pi's catalog, so pi picked a model
|
|
15
|
+
* on its own. Say so once — otherwise a typo silently runs a different model.
|
|
16
|
+
*/
|
|
17
|
+
private warnUnknownModel;
|
|
11
18
|
private extractText;
|
|
12
19
|
/**
|
|
13
20
|
* Abort cancellation relies on session.dispose() interrupting session.prompt().
|
|
14
21
|
* This is an upstream contract of pi-coding-agent — if dispose() does not
|
|
15
|
-
* actually
|
|
22
|
+
* actually settle the in-flight prompt, the abort signal will not terminate the call.
|
|
23
|
+
* pi 1.x settles the prompt by resolving it (not rejecting), so abort is
|
|
24
|
+
* re-checked after prompt() returns.
|
|
16
25
|
*/
|
|
17
26
|
ask(prompt: string, options?: {
|
|
18
27
|
system?: string;
|
package/dist/pi-adapter.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { createAgentSession, SessionManager, DefaultResourceLoader, } from "@
|
|
2
|
-
|
|
1
|
+
import { createAgentSession, SessionManager, DefaultResourceLoader, ModelRuntime, getAgentDir, } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
/** The pi version this runtime is built against (recorded in each project's meta.json). */
|
|
3
|
+
export { VERSION as PI_VERSION } from "@earendil-works/pi-coding-agent";
|
|
3
4
|
/** Strip markdown code fences and trim whitespace. */
|
|
4
5
|
export function stripCodeFences(text) {
|
|
5
6
|
const trimmed = text.trim();
|
|
@@ -10,6 +11,8 @@ export function stripCodeFences(text) {
|
|
|
10
11
|
}
|
|
11
12
|
return trimmed;
|
|
12
13
|
}
|
|
14
|
+
/** provider/model pairs already warned about, so a loop of agent calls warns once per process. */
|
|
15
|
+
const warnedUnknownModels = new Set();
|
|
13
16
|
export class PiAdapter {
|
|
14
17
|
config;
|
|
15
18
|
cwd;
|
|
@@ -24,11 +27,13 @@ export class PiAdapter {
|
|
|
24
27
|
async createSession(systemPrompt, signal) {
|
|
25
28
|
if (signal?.aborted)
|
|
26
29
|
throw new Error("Aborted");
|
|
30
|
+
const agentDir = getAgentDir();
|
|
27
31
|
const resourceLoader = new DefaultResourceLoader({
|
|
28
32
|
cwd: this.cwd,
|
|
33
|
+
agentDir,
|
|
29
34
|
noExtensions: true,
|
|
30
35
|
noSkills: true,
|
|
31
|
-
...(systemPrompt && { appendSystemPrompt: systemPrompt }),
|
|
36
|
+
...(systemPrompt && { appendSystemPrompt: [systemPrompt] }),
|
|
32
37
|
});
|
|
33
38
|
// Race an async step against the abort signal.
|
|
34
39
|
// Returns the result on success, or rejects with "Aborted" on abort.
|
|
@@ -53,15 +58,32 @@ export class PiAdapter {
|
|
|
53
58
|
await raceAbort(resourceLoader.reload());
|
|
54
59
|
if (signal?.aborted)
|
|
55
60
|
throw new Error("Aborted");
|
|
61
|
+
// Resolve the model through pi's model runtime (built-in catalog plus the
|
|
62
|
+
// user's models.json). An unknown provider/model resolves to undefined, in
|
|
63
|
+
// which case pi falls back to its own default selection.
|
|
64
|
+
const modelRuntime = await raceAbort(ModelRuntime.create({ signal }));
|
|
65
|
+
if (signal?.aborted)
|
|
66
|
+
throw new Error("Aborted");
|
|
67
|
+
const model = modelRuntime.getModel(this.config.provider, this.config.model);
|
|
56
68
|
// Keep a reference to the raw promise so we can clean up a late-arriving session
|
|
57
69
|
const sessionPromise = createAgentSession({
|
|
58
70
|
cwd: this.cwd,
|
|
59
|
-
|
|
60
|
-
|
|
71
|
+
agentDir,
|
|
72
|
+
modelRuntime,
|
|
73
|
+
model,
|
|
74
|
+
sessionManager: SessionManager.inMemory(this.cwd),
|
|
61
75
|
resourceLoader,
|
|
62
76
|
});
|
|
63
77
|
try {
|
|
64
78
|
const { session } = await raceAbort(sessionPromise);
|
|
79
|
+
if (!model) {
|
|
80
|
+
// With nothing to fall back to, pi reports a placeholder model that is
|
|
81
|
+
// not in its catalog — only name the fallback when it is a real one.
|
|
82
|
+
const picked = session.model;
|
|
83
|
+
const fallback = picked && modelRuntime.getModel(picked.provider, picked.id)
|
|
84
|
+
? `${picked.provider}/${picked.id}` : null;
|
|
85
|
+
this.warnUnknownModel(fallback);
|
|
86
|
+
}
|
|
65
87
|
return session;
|
|
66
88
|
}
|
|
67
89
|
catch (err) {
|
|
@@ -70,6 +92,21 @@ export class PiAdapter {
|
|
|
70
92
|
throw err;
|
|
71
93
|
}
|
|
72
94
|
}
|
|
95
|
+
/**
|
|
96
|
+
* The configured provider/model is not in pi's catalog, so pi picked a model
|
|
97
|
+
* on its own. Say so once — otherwise a typo silently runs a different model.
|
|
98
|
+
*/
|
|
99
|
+
warnUnknownModel(fallback) {
|
|
100
|
+
const requested = `${this.config.provider}/${this.config.model}`;
|
|
101
|
+
if (warnedUnknownModels.has(requested))
|
|
102
|
+
return;
|
|
103
|
+
warnedUnknownModels.add(requested);
|
|
104
|
+
console.warn(`[trama] warning: model "${requested}" was not found in pi's model catalog. ` +
|
|
105
|
+
(fallback
|
|
106
|
+
? `pi is falling back to "${fallback}". `
|
|
107
|
+
: `pi has no fallback model available, so LLM calls will fail. `) +
|
|
108
|
+
`Check "provider" and "model" in ~/.trama/config.json or the project's meta.json.`);
|
|
109
|
+
}
|
|
73
110
|
extractText(session) {
|
|
74
111
|
const messages = session.state.messages;
|
|
75
112
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
@@ -86,7 +123,9 @@ export class PiAdapter {
|
|
|
86
123
|
/**
|
|
87
124
|
* Abort cancellation relies on session.dispose() interrupting session.prompt().
|
|
88
125
|
* This is an upstream contract of pi-coding-agent — if dispose() does not
|
|
89
|
-
* actually
|
|
126
|
+
* actually settle the in-flight prompt, the abort signal will not terminate the call.
|
|
127
|
+
* pi 1.x settles the prompt by resolving it (not rejecting), so abort is
|
|
128
|
+
* re-checked after prompt() returns.
|
|
90
129
|
*/
|
|
91
130
|
async ask(prompt, options) {
|
|
92
131
|
const signal = options?.signal;
|
|
@@ -102,6 +141,10 @@ export class PiAdapter {
|
|
|
102
141
|
if (signal?.aborted)
|
|
103
142
|
throw new Error("Aborted");
|
|
104
143
|
await session.prompt(prompt);
|
|
144
|
+
// An aborted prompt resolves with no usable answer — report it as an abort,
|
|
145
|
+
// not as an empty LLM response.
|
|
146
|
+
if (signal?.aborted)
|
|
147
|
+
throw new Error("Aborted");
|
|
105
148
|
const text = this.extractText(session);
|
|
106
149
|
if (!text)
|
|
107
150
|
throw new Error("Empty response from LLM");
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export interface ProgramResult {
|
|
2
|
+
status: "done" | "yielded" | "failed";
|
|
3
|
+
/** Yield reason, or error summary for failed. */
|
|
4
|
+
reason?: string;
|
|
5
|
+
/** From ctx.done(result), if provided. */
|
|
6
|
+
result?: unknown;
|
|
7
|
+
}
|
|
8
|
+
export interface PiAdapterConfig {
|
|
9
|
+
provider: string;
|
|
10
|
+
model: string;
|
|
11
|
+
}
|
|
12
|
+
export interface RunOptions {
|
|
13
|
+
projectDir: string;
|
|
14
|
+
maxRepairAttempts?: number;
|
|
15
|
+
timeout?: number;
|
|
16
|
+
args?: Record<string, unknown>;
|
|
17
|
+
/** Shared workspace directory. When set, workspace.* API is enabled for the program. */
|
|
18
|
+
workspaceDir?: string;
|
|
19
|
+
}
|
|
20
|
+
export interface RepairInput {
|
|
21
|
+
programSource: string;
|
|
22
|
+
error: string;
|
|
23
|
+
runtimeTypes: string;
|
|
24
|
+
}
|
|
25
|
+
export interface TramaConfig extends PiAdapterConfig {
|
|
26
|
+
maxRepairAttempts: number;
|
|
27
|
+
defaultTimeout: number;
|
|
28
|
+
defaultMaxIterations: number;
|
|
29
|
+
}
|