@trama-dev/runtime 0.6.1 → 0.8.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.
Files changed (64) hide show
  1. package/dist/agent-backend.d.ts +100 -0
  2. package/dist/agent-backend.js +4 -0
  3. package/dist/agent-host.d.ts +46 -7
  4. package/dist/agent-host.js +59 -19
  5. package/dist/agent-hosts.d.ts +8 -0
  6. package/dist/agent-hosts.js +123 -56
  7. package/dist/agent.d.ts +18 -5
  8. package/dist/agent.js +23 -64
  9. package/dist/bridge-client.d.ts +6 -2
  10. package/dist/bridge-client.js +7 -1
  11. package/dist/budget.d.ts +6 -0
  12. package/dist/budget.js +1 -0
  13. package/dist/client.d.ts +3 -2
  14. package/dist/client.js +146 -2
  15. package/dist/context.js +3 -2
  16. package/dist/history.d.ts +9 -0
  17. package/dist/history.js +98 -0
  18. package/dist/index.d.ts +2 -0
  19. package/dist/index.js +73 -41
  20. package/dist/ipc-server.d.ts +2 -3
  21. package/dist/ipc-server.js +99 -38
  22. package/dist/journal-view.d.ts +8 -0
  23. package/dist/journal-view.js +63 -11
  24. package/dist/journal.d.ts +10 -4
  25. package/dist/journal.js +73 -7
  26. package/dist/merge-deeds.d.ts +22 -0
  27. package/dist/merge-deeds.js +201 -0
  28. package/dist/merge-doing.d.ts +9 -0
  29. package/dist/merge-doing.js +410 -0
  30. package/dist/merge-settle.d.ts +14 -0
  31. package/dist/merge-settle.js +166 -0
  32. package/dist/merge-shared.d.ts +64 -0
  33. package/dist/merge-shared.js +159 -0
  34. package/dist/merge.d.ts +150 -0
  35. package/dist/merge.js +209 -0
  36. package/dist/model-relay.d.ts +19 -0
  37. package/dist/model-relay.js +91 -9
  38. package/dist/model-request.d.ts +9 -0
  39. package/dist/model-request.js +185 -0
  40. package/dist/own-tools.d.ts +60 -0
  41. package/dist/own-tools.js +209 -0
  42. package/dist/path-guard.js +8 -6
  43. package/dist/pi-adapter.d.ts +32 -9
  44. package/dist/pi-adapter.js +198 -51
  45. package/dist/project.d.ts +39 -0
  46. package/dist/project.js +270 -0
  47. package/dist/replace-file.d.ts +13 -2
  48. package/dist/replace-file.js +23 -6
  49. package/dist/runner-backend.d.ts +43 -0
  50. package/dist/runner-backend.js +149 -0
  51. package/dist/runner-types.d.ts +26 -0
  52. package/dist/runner.d.ts +10 -125
  53. package/dist/runner.js +148 -461
  54. package/dist/schema.d.ts +45 -0
  55. package/dist/schema.js +113 -0
  56. package/dist/stopping.js +2 -3
  57. package/dist/tools.d.ts +8 -1
  58. package/dist/tools.js +36 -10
  59. package/dist/tree.d.ts +33 -149
  60. package/dist/tree.js +43 -1077
  61. package/dist/types.d.ts +182 -2
  62. package/dist/workspace.d.ts +28 -1
  63. package/dist/workspace.js +88 -13
  64. package/package.json +2 -2
package/dist/client.js CHANGED
@@ -1,7 +1,9 @@
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 { randomUUID } from "crypto";
4
5
  import { openBridge, remoteWorkspace, withOptions } from "./bridge-client.js";
6
+ import { messageOf } from "./errors.js";
5
7
  import { assertSerializable, toLogData } from "./serializable.js";
6
8
  const PORT = process.env.TRAMA_PORT;
7
9
  if (!PORT) {
@@ -47,9 +49,150 @@ export const ctx = {
47
49
  process.exit(0);
48
50
  },
49
51
  };
52
+ /** What kind of image bytes are, told by how they begin: of the kinds a model is shown. */
53
+ function imageKind(bytes) {
54
+ const begins = (at, ...with_) => with_.every((byte, index) => bytes[at + index] === byte);
55
+ if (begins(0, 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a))
56
+ return "image/png";
57
+ if (begins(0, 0xff, 0xd8, 0xff))
58
+ return "image/jpeg";
59
+ if (begins(0, 0x47, 0x49, 0x46, 0x38) && (bytes[4] === 0x37 || bytes[4] === 0x39) && bytes[5] === 0x61)
60
+ return "image/gif";
61
+ if (begins(0, 0x52, 0x49, 0x46, 0x46) && begins(8, 0x57, 0x45, 0x42, 0x50))
62
+ return "image/webp";
63
+ return undefined;
64
+ }
65
+ /**
66
+ * What a tool's result is to a model. Words: a string as it is, anything
67
+ * else as JSON says it. And bytes are an image to be seen — by themselves,
68
+ * or in a list, where what is not bytes is words.
69
+ */
70
+ function said(result) {
71
+ const words = (value) => {
72
+ if (typeof value === "string")
73
+ return value;
74
+ const json = JSON.stringify(value);
75
+ if (json === undefined)
76
+ throw new TypeError(`the tool returned a ${typeof value}, which cannot be said as JSON`);
77
+ return json;
78
+ };
79
+ const parts = result instanceof Uint8Array ? [result] : Array.isArray(result) && result.some(part => part instanceof Uint8Array) ? result : undefined;
80
+ if (!parts)
81
+ return { text: result === undefined ? "Done." : words(result) };
82
+ const text = [], images = [];
83
+ for (const part of parts) {
84
+ if (!(part instanceof Uint8Array)) {
85
+ text.push(words(part));
86
+ continue;
87
+ }
88
+ const mimeType = imageKind(part);
89
+ if (!mimeType)
90
+ throw new TypeError("the tool returned bytes that are no image a model is shown: not a PNG, a JPEG, a GIF or a WebP");
91
+ images.push({ mimeType, data: Buffer.from(part.buffer, part.byteOffset, part.byteLength).toString("base64") });
92
+ }
93
+ return { text: text.join("\n"), images };
94
+ }
95
+ /** Whether a tool a call names is one of the program's own: written out, where the agent's are named. */
96
+ const isOwn = (tool) => typeof tool === "object" && tool !== null;
97
+ /**
98
+ * Make an agent call. The tools of the program's own that it has are
99
+ * functions, and stay here: the runner is sent what each declares, and where
100
+ * this process waits to be asked for them — a call of its own beside the
101
+ * agent call, held by the runner until a tool is called, or one that is
102
+ * running is to stop, and made again for as long as the agent call lasts.
103
+ */
104
+ async function agentCall(endpoint, body) {
105
+ // (What is no call at all is the runner's to refuse, or the bridge's, as it is made.)
106
+ const tools = isOwn(body) ? body.tools : undefined;
107
+ if (!Array.isArray(tools) || !tools.some(isOwn))
108
+ return call(endpoint, body);
109
+ const own = new Map();
110
+ const declared = tools.map((tool) => {
111
+ if (!isOwn(tool))
112
+ return tool;
113
+ const { run, ...rest } = tool;
114
+ if (typeof run !== "function") {
115
+ throw new TypeError(`the tool ${JSON.stringify(rest.name)} has no run: a tool of the program's own is a function of the program's`);
116
+ }
117
+ // (Of two by one name the runner refuses the call, before either is asked.)
118
+ own.set(String(rest.name), run);
119
+ return rest;
120
+ });
121
+ const toolsId = randomUUID();
122
+ const over = new AbortController();
123
+ /** The tools that are running, each by the key its use was told under. */
124
+ const running = new Map();
125
+ const use = async (key, name, args) => {
126
+ const stop = new AbortController();
127
+ running.set(key, stop);
128
+ let answer;
129
+ try {
130
+ answer = said(await own.get(name)(args, { signal: stop.signal }));
131
+ }
132
+ catch (err) {
133
+ answer = { error: messageOf(err) };
134
+ }
135
+ running.delete(key);
136
+ // (What a tool says after it was told to stop, or after its call is over, is said to nobody: the runner has no use for it.)
137
+ await call("/agent/tool/answered", { of: toolsId, key, ...answer }).catch(() => { });
138
+ };
139
+ const waiting = (async () => {
140
+ // How long is waited before it is asked again where the asking failed: longer each time it fails again, and never long.
141
+ let pause = 50;
142
+ while (!over.signal.aborted) {
143
+ let event;
144
+ try {
145
+ event = await call("/agent/tool/asked", { of: toolsId }, over.signal);
146
+ pause = 50;
147
+ }
148
+ catch {
149
+ // Given up, the agent call being over. (Or not answered — which the agent call will say for itself: asked again meanwhile.)
150
+ if (over.signal.aborted)
151
+ return;
152
+ await new Promise(resolve => setTimeout(resolve, pause));
153
+ pause = Math.min(pause * 2, 1000);
154
+ continue;
155
+ }
156
+ if (event === null)
157
+ return;
158
+ if ("stop" in event)
159
+ running.get(event.stop)?.abort();
160
+ else
161
+ void use(event.key, event.name, event.args);
162
+ }
163
+ })();
164
+ try {
165
+ return await call(endpoint, { ...body, tools: declared, toolsId });
166
+ }
167
+ finally {
168
+ over.abort();
169
+ for (const stop of running.values())
170
+ stop.abort();
171
+ await waiting;
172
+ }
173
+ }
174
+ /**
175
+ * A request to a model as it is sent: of each tool, what it declares. Its
176
+ * function stays here, and waits for nobody: no agent is asked that would
177
+ * call it — the program reads the model's calls in the reply, and runs what
178
+ * it will.
179
+ */
180
+ function asSent(request) {
181
+ const tools = isOwn(request) ? request.tools : undefined;
182
+ if (!Array.isArray(tools))
183
+ return request;
184
+ const declared = tools.map((tool) => {
185
+ if (!isOwn(tool))
186
+ return tool;
187
+ const { run: _run, ...rest } = tool;
188
+ return rest;
189
+ });
190
+ return { ...request, tools: declared };
191
+ }
50
192
  export const agent = {
51
- instruct: async (prompt, opts) => call("/agent/instruct", withOptions({ prompt }, opts)),
52
- generate: (input) => call("/agent/generate", input),
193
+ instruct: async (prompt, opts) => agentCall("/agent/instruct", withOptions({ prompt }, opts)),
194
+ generate: async (input) => agentCall("/agent/generate", input),
195
+ complete: async (request) => call("/agent/complete", asSent(request)),
53
196
  };
54
197
  export const tools = {
55
198
  read: (path) => call("/tools/read", { path }),
@@ -64,3 +207,4 @@ export const workspace = remoteWorkspace((endpoint, body) => {
64
207
  }
65
208
  return call(endpoint, body);
66
209
  });
210
+ export { heldTo } from "./schema.js";
package/dist/context.js CHANGED
@@ -1,8 +1,9 @@
1
- import { writeFileSync, appendFileSync } from "fs";
1
+ import { appendFileSync } from "fs";
2
2
  import { join } from "path";
3
3
  import { assertSerializable, isJsonObject } from "./serializable.js";
4
4
  import { guardPath } from "./path-guard.js";
5
5
  import { readProjectMeta } from "./meta.js";
6
+ import { saveState } from "./project.js";
6
7
  /** Where a project's structured run log lives, relative to the project root. */
7
8
  export const LATEST_LOG_PATH = join("logs", "latest.jsonl");
8
9
  /** Append one structured JSONL entry to a run log file. `data` is what the program's side made of what it was given (see toLogData). */
@@ -63,7 +64,7 @@ export function createContext(projectDir, initialState, options) {
63
64
  record.__trama_yield = { reason: ending.reason };
64
65
  else
65
66
  delete record.__trama_yield; // the program has moved on from its last yield
66
- writeFileSync(statePath(), JSON.stringify(record, null, 2));
67
+ saveState(projectDir, record);
67
68
  // Settled only once persisted: a call that failed leaves every call open.
68
69
  iteration += 1;
69
70
  ended = ending ?? null;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Add a version to a project's history: its text as history/NNNN.ts, and a
3
+ * line in index.jsonl saying why (after `notes`, lines that belong with it).
4
+ * Either all of it is written or none of it. Returns how to take it back, for
5
+ * a caller whose own next step may still fail.
6
+ */
7
+ export declare function recordVersion(projectDir: string, source: string | Buffer, reason: string, detail?: string, notes?: Array<Record<string, unknown>>): () => void;
8
+ /** Save the current program.ts as the next version of the project, and record why. */
9
+ export declare function copyToHistory(projectDir: string, reason: string, detail?: string): void;
@@ -0,0 +1,98 @@
1
+ // A project's history: each program it has had, as history/NNNN.ts, and
2
+ // why it came to have it, as a line of history/index.jsonl.
3
+ import { readFileSync, writeFileSync, appendFileSync, readdirSync, statSync, rmSync, openSync, closeSync, truncateSync, } from "fs";
4
+ import { join } from "path";
5
+ import { guardPath } from "./path-guard.js";
6
+ /** The index.jsonl field that carries the detail for each kind of versioned change. */
7
+ const HISTORY_DETAIL_FIELD = { create: "prompt", update: "prompt", repair: "error" };
8
+ /**
9
+ * Add a version to a project's history: its text as history/NNNN.ts, and a
10
+ * line in index.jsonl saying why (after `notes`, lines that belong with it).
11
+ * Either all of it is written or none of it. Returns how to take it back, for
12
+ * a caller whose own next step may still fail.
13
+ */
14
+ export function recordVersion(projectDir, source, reason, detail, notes = []) {
15
+ const historyDir = guardPath(projectDir, "history");
16
+ const indexPath = guardPath(projectDir, join("history", "index.jsonl"));
17
+ const versions = readdirSync(historyDir)
18
+ .filter(f => /^\d+\.ts$/.test(f))
19
+ .map(f => parseInt(f, 10))
20
+ .filter(n => Number.isSafeInteger(n) && n < Number.MAX_SAFE_INTEGER);
21
+ // (In the history directory as the guard found it: no link is left in that. And the file itself is made,
22
+ // never opened — a name that is there already, a link somebody put there among them, is not written through.)
23
+ const fileOf = (version) => join(historyDir, `${String(version).padStart(4, "0")}.ts`);
24
+ // The next number: one more than the highest there is — or, where another run of the project took that
25
+ // one between the looking and the taking, the one after. A version file that is already there is someone
26
+ // else's, and is not written over.
27
+ let version = versions.reduce((a, b) => Math.max(a, b), 0) + 1;
28
+ let snapshot = fileOf(version), fd;
29
+ for (;;) {
30
+ try {
31
+ fd = openSync(snapshot, "wx");
32
+ break;
33
+ }
34
+ catch (err) {
35
+ if (err.code !== "EEXIST")
36
+ throw err;
37
+ snapshot = fileOf(++version);
38
+ }
39
+ }
40
+ const entry = { version, reason, timestamp: new Date().toISOString() };
41
+ const detailField = HISTORY_DETAIL_FIELD[reason];
42
+ if (detailField && detail)
43
+ entry[detailField] = detail;
44
+ const lines = Buffer.from([...notes, entry].map(line => JSON.stringify(line) + "\n").join(""));
45
+ const sizeBefore = statSync(indexPath, { throwIfNoEntry: false })?.size;
46
+ let appended = false;
47
+ // Takes back what was written here and nothing else. Another run of the
48
+ // project may be recording a version of its own at the same moment: if the
49
+ // index no longer ends with these lines alone, they are left in it, and the
50
+ // version file with them — a version on record that was never installed,
51
+ // rather than someone else's record cut out of the history.
52
+ const undo = () => {
53
+ try {
54
+ const index = readFileSync(indexPath);
55
+ const start = sizeBefore ?? 0;
56
+ const sinceThen = index.subarray(Math.min(start, index.length));
57
+ // What was appended is the end of the index — whole, or as far as a failed write got.
58
+ const cutTo = index.subarray(-lines.length).equals(lines) ? index.length - lines.length
59
+ : lines.subarray(0, sinceThen.length).equals(sinceThen) ? start
60
+ : null;
61
+ if (cutTo === null)
62
+ return;
63
+ if (cutTo === 0 && sizeBefore === undefined)
64
+ rmSync(indexPath, { force: true });
65
+ else if (cutTo < index.length)
66
+ truncateSync(indexPath, cutTo);
67
+ }
68
+ catch (err) {
69
+ // The index cannot be looked at. If the lines went into it, they stay,
70
+ // and the version file with them; if they never did, there is only the file.
71
+ if (appended && err.code !== "ENOENT")
72
+ return;
73
+ }
74
+ try {
75
+ rmSync(snapshot, { force: true });
76
+ }
77
+ catch { /* best-effort */ }
78
+ };
79
+ try {
80
+ try {
81
+ writeFileSync(fd, source);
82
+ }
83
+ finally {
84
+ closeSync(fd);
85
+ }
86
+ appendFileSync(indexPath, lines);
87
+ appended = true;
88
+ }
89
+ catch (err) {
90
+ undo();
91
+ throw err;
92
+ }
93
+ return undo;
94
+ }
95
+ /** Save the current program.ts as the next version of the project, and record why. */
96
+ export function copyToHistory(projectDir, reason, detail) {
97
+ recordVersion(projectDir, readFileSync(guardPath(projectDir, "program.ts")), reason, detail);
98
+ }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  export type { Budget, ProgramResult, RunOptions } from "./runner-types.js";
2
+ export { failureOf } from "./runner.js";
3
+ export { requestsWhole } from "./journal-view.js";
2
4
  import type { ProgramResult, RunOptions } from "./runner-types.js";
3
5
  export type { Workspace, ObserveResult } from "./types.js";
4
6
  import type { Workspace } from "./types.js";
package/dist/index.js CHANGED
@@ -9,12 +9,16 @@ import { onAbort, throwIfAborted } from "./abort.js";
9
9
  import { createMeter } from "./budget.js";
10
10
  import { LATEST_LOG_PATH } from "./context.js";
11
11
  import { readProjectMeta } from "./meta.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
+ import { ensureProjectScaffold, loadConfig, loadProjectConfig, loadState, namesAPath, projectNamed } from "./project.js";
13
+ import { createBackend, saysOnce } from "./runner-backend.js";
14
+ import { validateProgram, installValidatedProgram, withTempDir, prepareProject, shownPaths, RUNTIME_TYPES, runProgram as runHere, whyNotReplaceable, tagged, } from "./runner.js";
13
15
  import { createWorkspace as workspaceHere, ensureWorkspaceDir } from "./workspace.js";
14
16
  import { parentBridge, remoteWorkspace, withOptions } from "./bridge-client.js";
15
17
  import { guardPath, identityOf, sameProjectAs } from "./path-guard.js";
16
18
  import { printJournals, spentIn } from "./journal-view.js";
17
19
  import { messageOf } from "./errors.js";
20
+ export { failureOf } from "./runner.js";
21
+ export { requestsWhole } from "./journal-view.js";
18
22
  // --- Running a project, making one, and reaching a workspace ---
19
23
  //
20
24
  // A program never runs another program, nor makes or changes a project: it
@@ -55,6 +59,8 @@ export async function runProgram(options) {
55
59
  // The runner does not share this program's working directory.
56
60
  projectDir: resolve(request.projectDir),
57
61
  workspaceDir: request.workspaceDir && resolve(request.workspaceDir),
62
+ // (A path is this program's to say where it leads. A name is one of the user's projects, wherever it is said.)
63
+ repairWith: request.repairWith !== undefined && namesAPath(request.repairWith) ? projectNamed(request.repairWith) : request.repairWith,
58
64
  }, signal);
59
65
  }
60
66
  /** The shared workspace in a directory, created if it does not exist: read, write, list, observe. */
@@ -165,14 +171,17 @@ function projectsDir() {
165
171
  return join(homedir(), ".trama", "projects");
166
172
  }
167
173
  export function validateProjectName(name) {
168
- if (!name || /[\/\\]/.test(name) || name === "." || name === "..") {
169
- throw new Error(`Invalid project name: "${name}". Must be a simple directory name without path separators.`);
174
+ // (One line of text, too: a name is shown, in a line of its own making, wherever its project is spoken of.)
175
+ if (!name || /[\/\\\x00-\x1f\x7f]/.test(name) || name === "." || name === "..") {
176
+ throw new Error(`Invalid project name: ${JSON.stringify(name)}. Must be a simple directory name without path separators.`);
170
177
  }
171
178
  }
179
+ /** Whether a project is at a path: a directory, reached however the path reaches it. */
180
+ const isProject = (dir) => statSync(dir, { throwIfNoEntry: false })?.isDirectory() === true;
172
181
  export function resolveProject(name) {
173
182
  validateProjectName(name);
174
183
  const dir = join(projectsDir(), name);
175
- if (!existsSync(dir)) {
184
+ if (!isProject(dir)) {
176
185
  throw new Error(`Project "${name}" not found. Run \`trama list\` to see available projects.`);
177
186
  }
178
187
  return dir;
@@ -222,24 +231,24 @@ function backendFor(config, asked) {
222
231
  }
223
232
  /** Carry what the agent made beside a program into the project the program is now in, and say what that was. */
224
233
  function keepPrepared(prepared, label) {
225
- const console = shownUnder(label);
234
+ const say = shownUnder(label);
226
235
  let kept;
227
236
  try {
228
237
  kept = prepared.keep();
229
238
  }
230
239
  catch (err) {
231
240
  // 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)}`);
241
+ say.warn(`[trama] what was made beside the program, while it was written, could not be carried into the project: ${messageOf(err)}`);
233
242
  return;
234
243
  }
235
244
  const { changed, unmerged } = kept;
236
245
  if (changed.length > 0) {
237
- console.log(`[trama] ${changed.length} path(s) made or changed beside the program, while it was written: ${shownPaths(changed)}`);
246
+ say.log(`[trama] ${changed.length} path(s) made or changed beside the program, while it was written: ${shownPaths(changed)}`);
238
247
  }
239
248
  if (unmerged.length > 0) {
240
- console.warn(`[trama] ${unmerged.length} thing(s) done while the program was written did not reach the project:`);
249
+ say.warn(`[trama] ${unmerged.length} thing(s) done while the program was written did not reach the project:`);
241
250
  for (const { path, why } of unmerged)
242
- console.warn(`[trama] ${path} — ${why}`);
251
+ say.warn(`[trama] ${path} — ${why}`);
243
252
  }
244
253
  }
245
254
  /**
@@ -283,6 +292,30 @@ const shownUnder = (label) => ({
283
292
  log: (line) => console.log(tagged(label, line)),
284
293
  warn: (line) => console.warn(tagged(label, line)),
285
294
  });
295
+ /**
296
+ * How a project comes by a program that was asked for — a new project's
297
+ * first, or one in the place of another: written off to the side, in a copy
298
+ * of the project; validated; and only then made the project's, with what
299
+ * the agent made beside it where that is kept. The project is written to
300
+ * once there is a program that works. (`written`: told of the candidate
301
+ * before it is validated, for whoever has a use for one that may yet fail.)
302
+ */
303
+ async function writeValidateInstall(projectDir, how) {
304
+ const { config, backend, stillTheProject, signal, asked } = how;
305
+ const wrote = [];
306
+ await withTempDir("trama-gen-", async (privateDir) => {
307
+ const prepared = prepareProject(projectDir, privateDir);
308
+ const candidate = await generateProgram(backend, prepared, how.ask, how.system, wrote, signal, asked.label);
309
+ stillTheProject();
310
+ how.written?.(candidate);
311
+ shownUnder(asked.label).log(how.validating);
312
+ const { validated, kept } = await validateCandidate(projectDir, backend, candidate, config, prepared, wrote, signal, asked);
313
+ stillTheProject();
314
+ installValidatedProgram(projectDir, validated, how.reason, how.prompt);
315
+ if (kept)
316
+ keepPrepared(prepared, asked.label);
317
+ });
318
+ }
286
319
  // --- Public API ---
287
320
  /** Generate a program for a new project from a prompt, validate it, and make it the project's. */
288
321
  export async function createProject(name, prompt, options) {
@@ -301,8 +334,12 @@ export async function updateProject(name, prompt, options) {
301
334
  await overBridge(bridge, "/project/update", withOptions({ name, prompt }, asked), signal);
302
335
  }
303
336
  async function createHere(name, prompt, options, asked = {}) {
304
- const console = shownUnder(asked.label);
337
+ const say = shownUnder(asked.label);
305
338
  validateProjectName(name);
339
+ // (Asked before a project is made: what is no name of a model would be written down as the project's, and no run of it could read that.)
340
+ if (options?.model !== undefined && typeof options.model !== "string") {
341
+ throw new Error(`Invalid model: ${JSON.stringify(options.model)}. A model is named in text.`);
342
+ }
306
343
  throwIfAborted(options?.signal);
307
344
  const projectDir = join(projectsDir(), name);
308
345
  let keepProjectOnFailure = false;
@@ -331,28 +368,26 @@ async function createHere(name, prompt, options, asked = {}) {
331
368
  model: config.model,
332
369
  provider: config.provider,
333
370
  };
334
- writeFileSync(join(projectDir, "meta.json"), JSON.stringify(meta, null, 2));
371
+ writeFileSync(guardPath(projectDir, "meta.json"), JSON.stringify(meta, null, 2));
335
372
  const backend = backendFor(config, asked);
336
- const wrote = [];
337
- console.log(`Generating program for "${name}"...`);
373
+ say.log(`Generating program for "${name}"...`);
338
374
  // (What the agent is given to look at is the project made here, and no other directory that is at its path by now.)
339
375
  stillTheProject();
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();
376
+ await writeValidateInstall(projectDir, {
377
+ reason: "create",
378
+ prompt,
379
+ ask: `${prompt}\n\nOutput ONLY the TypeScript program. No markdown fences. No explanation.`,
380
+ system: getSystemPrompt(config.agentChanges === "keep"),
381
+ validating: "Validating program...",
382
+ config, backend, stillTheProject, signal: options?.signal, asked,
344
383
  // From here on the project is kept even if validation fails, so the
345
384
  // 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);
385
+ written: (candidate) => {
386
+ writeFileSync(guardPath(projectDir, "program.ts"), candidate);
387
+ keepProjectOnFailure = true;
388
+ },
354
389
  });
355
- console.log(`Created ${name}. Run with: trama run ${name}`);
390
+ say.log(`Created ${name}. Run with: trama run ${name}`);
356
391
  }
357
392
  catch (err) {
358
393
  if (!keepProjectOnFailure && identityOf(projectDir) === made) {
@@ -362,7 +397,7 @@ async function createHere(name, prompt, options, asked = {}) {
362
397
  }
363
398
  }
364
399
  async function updateHere(name, prompt, options, asked = {}) {
365
- const console = shownUnder(asked.label);
400
+ const say = shownUnder(asked.label);
366
401
  const projectDir = resolveProject(name);
367
402
  const unchanged = (why) => new Error(`Update failed — the program is unchanged.\n${messageOf(why)}`);
368
403
  const stillTheProject = sameProjectAs(projectDir);
@@ -383,28 +418,24 @@ async function updateHere(name, prompt, options, asked = {}) {
383
418
  const meta = readProjectMeta(projectDir);
384
419
  const config = loadProjectConfig(projectDir, meta);
385
420
  const backend = backendFor(config, asked);
386
- const wrote = [];
387
421
  const systemPrompt = getSystemPrompt(config.agentChanges === "keep") +
388
422
  `\n\nOriginal prompt: ${meta.input.prompt}` +
389
423
  `\n\nCurrent program.ts:\n${originalSource}` +
390
424
  (Object.keys(state).length > 0 ? `\n\nCurrent state:\n${JSON.stringify(state, null, 2)}` : "");
391
- console.log(`Updating "${name}"...`);
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);
425
+ say.log(`Updating "${name}"...`);
426
+ await writeValidateInstall(projectDir, {
427
+ reason: "update",
428
+ prompt,
429
+ ask: `${prompt}\n\nOutput the complete updated program.ts. No partial patches. No markdown fences. No explanation.`,
430
+ system: systemPrompt,
431
+ validating: "Validating updated program...",
432
+ config, backend, stillTheProject, signal: options?.signal, asked,
402
433
  });
403
434
  }
404
435
  catch (err) {
405
436
  throw unchanged(err);
406
437
  }
407
- console.log(`Updated ${name}. Run with: trama run ${name}`);
438
+ say.log(`Updated ${name}. Run with: trama run ${name}`);
408
439
  }
409
440
  export async function listProjects() {
410
441
  const dir = projectsDir();
@@ -412,8 +443,9 @@ export async function listProjects() {
412
443
  console.log("No projects found.");
413
444
  return;
414
445
  }
446
+ // (What can be run by its name is listed by it: a project reached through a link among them.)
415
447
  const entries = readdirSync(dir, { withFileTypes: true })
416
- .filter(e => e.isDirectory());
448
+ .filter(e => isProject(join(dir, e.name)));
417
449
  if (entries.length === 0) {
418
450
  console.log("No projects found.");
419
451
  return;
@@ -2,9 +2,8 @@ import { type Server } from "http";
2
2
  import type { Tools, Workspace } from "./types.js";
3
3
  import type { RunnerAgent } from "./agent.js";
4
4
  import type { RunContext } from "./context.js";
5
- import type { ProgramResult, RunRequest } from "./runner-types.js";
6
- import type { MakeRequest } from "./runner.js";
7
- import type { Journal } from "./journal.js";
5
+ import type { MakeRequest, ProgramResult, RunRequest } from "./runner-types.js";
6
+ import { type Journal } from "./journal.js";
8
7
  export interface IpcBackends {
9
8
  /**
10
9
  * The secret only this run's program knows. Every request must present it: