@trama-dev/runtime 0.6.0 → 0.7.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 (57) hide show
  1. package/dist/agent-backend.d.ts +51 -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.js +122 -56
  6. package/dist/agent.d.ts +16 -5
  7. package/dist/agent.js +22 -64
  8. package/dist/bridge-client.d.ts +6 -2
  9. package/dist/bridge-client.js +6 -1
  10. package/dist/client.d.ts +2 -2
  11. package/dist/client.js +126 -2
  12. package/dist/context.js +3 -2
  13. package/dist/history.d.ts +9 -0
  14. package/dist/history.js +98 -0
  15. package/dist/index.d.ts +1 -0
  16. package/dist/index.js +70 -41
  17. package/dist/ipc-server.d.ts +2 -3
  18. package/dist/ipc-server.js +93 -37
  19. package/dist/journal-view.js +19 -9
  20. package/dist/journal.d.ts +10 -4
  21. package/dist/journal.js +28 -6
  22. package/dist/merge-deeds.d.ts +22 -0
  23. package/dist/merge-deeds.js +201 -0
  24. package/dist/merge-doing.d.ts +9 -0
  25. package/dist/merge-doing.js +410 -0
  26. package/dist/merge-settle.d.ts +14 -0
  27. package/dist/merge-settle.js +166 -0
  28. package/dist/merge-shared.d.ts +64 -0
  29. package/dist/merge-shared.js +159 -0
  30. package/dist/merge.d.ts +150 -0
  31. package/dist/merge.js +209 -0
  32. package/dist/model-relay.d.ts +63 -5
  33. package/dist/model-relay.js +206 -23
  34. package/dist/own-tools.d.ts +60 -0
  35. package/dist/own-tools.js +209 -0
  36. package/dist/path-guard.js +8 -6
  37. package/dist/pi-adapter.d.ts +22 -0
  38. package/dist/pi-adapter.js +294 -72
  39. package/dist/project.d.ts +31 -0
  40. package/dist/project.js +253 -0
  41. package/dist/replace-file.d.ts +13 -2
  42. package/dist/replace-file.js +23 -6
  43. package/dist/runner-backend.d.ts +43 -0
  44. package/dist/runner-backend.js +125 -0
  45. package/dist/runner-types.d.ts +8 -0
  46. package/dist/runner.d.ts +8 -123
  47. package/dist/runner.js +57 -453
  48. package/dist/schema.d.ts +38 -0
  49. package/dist/schema.js +104 -0
  50. package/dist/stopping.js +2 -3
  51. package/dist/tools.js +31 -7
  52. package/dist/tree.d.ts +33 -149
  53. package/dist/tree.js +43 -1077
  54. package/dist/types.d.ts +54 -2
  55. package/dist/workspace.d.ts +20 -0
  56. package/dist/workspace.js +76 -12
  57. package/package.json +2 -2
package/dist/agent.js CHANGED
@@ -1,4 +1,8 @@
1
+ // What a program's `agent` is to its runner: its calls, each made a request
2
+ // of the backend — and, of a reply that was to be a program and nothing
3
+ // else, the program in it.
1
4
  import { CutOff } from "./agent-backend.js";
5
+ import { conform, hasList, shapeOf } from "./schema.js";
2
6
  import { isJsonObject } from "./serializable.js";
3
7
  const NAMED = /[\w.+#-]*\s*\n/y;
4
8
  /** The fences of a text, in the order they stand in. */
@@ -82,62 +86,6 @@ export function stripCodeFences(text) {
82
86
  }
83
87
  return last ?? reply;
84
88
  }
85
- const SCHEMA_PRIMITIVES = new Set(["string", "number", "boolean"]);
86
- /** How the two shapes that are not named in a word are written, for whoever named them in one. */
87
- const HOW_WRITTEN = `a list is written as the shape of its items, in brackets: ["string"]; an object as its fields: { name: "string" }`;
88
- const fieldOf = (where, key) => (where === null ? key : `${where}.${key}`);
89
- /**
90
- * Read the caller's schema declaration, up front: what the value at `where`
91
- * is to be. In words — "string", "number", "boolean", where what follows a
92
- * ":" describes the value to the model and is not read here — or an object
93
- * of such, or a list of one element: the shape of every item.
94
- */
95
- function shapeOf(declared, where) {
96
- if (Array.isArray(declared)) {
97
- if (declared.length !== 1) {
98
- throw new Error(`Schema validation failed: the list at "${where}" is written with ${declared.length} elements — it takes one, the shape of every item`);
99
- }
100
- return { items: shapeOf(declared[0], `${where}[]`) };
101
- }
102
- if (isJsonObject(declared)) {
103
- return { fields: Object.entries(declared).map(([key, value]) => [key, shapeOf(value, fieldOf(where, key))]) };
104
- }
105
- // (Anything else says nothing that is supported — and is said back as JSON would write it, which is no word for a kind.)
106
- const named = typeof declared === "string" ? declared.split(":")[0].trim() : JSON.stringify(declared);
107
- if (!SCHEMA_PRIMITIVES.has(named)) {
108
- throw new Error(`Schema validation failed: unsupported schema type "${named}" for key "${where}" (${HOW_WRITTEN})`);
109
- }
110
- return named;
111
- }
112
- const hasList = (shape) => typeof shape !== "string" && ("items" in shape || shape.fields.some(([, field]) => hasList(field)));
113
- /** What a value is, said as a reply is told of it. */
114
- const said = (value) => value === null ? "null" : Array.isArray(value) ? "a list" : typeof value === "number" ? String(value) : typeof value;
115
- /**
116
- * Shape validation and projection: verifies that the value at `where` is of
117
- * the shape declared — every field there, every item of a list — and returns
118
- * it holding the declared fields and no others.
119
- */
120
- function conform(value, shape, where) {
121
- const mismatch = (expected) => new Error(`Schema validation failed: ${where}: expected ${expected}, got ${said(value)}`);
122
- if (typeof shape === "string") {
123
- if (typeof value !== shape || (shape === "number" && !Number.isFinite(value)))
124
- throw mismatch(shape);
125
- return value;
126
- }
127
- if ("items" in shape) {
128
- if (!Array.isArray(value))
129
- throw mismatch("a list");
130
- return value.map((item, index) => conform(item, shape.items, `${where}[${index}]`));
131
- }
132
- if (!isJsonObject(value))
133
- throw where === null ? new Error("Schema validation failed: response is not an object") : mismatch("an object");
134
- return Object.fromEntries(shape.fields.map(([key, field]) => {
135
- // (A field is the reply's own: what every object has by birth is not something a reply said.)
136
- if (!Object.hasOwn(value, key))
137
- throw new Error(`Schema validation failed: missing key: ${fieldOf(where, key)}`);
138
- return [key, conform(value[key], field, fieldOf(where, key))];
139
- }));
140
- }
141
89
  /** Of what a call may ask for, what it did ask for: a backend is not handed a thing nobody named. */
142
90
  const asked = (options) => Object.fromEntries(Object.entries(options).filter(([, value]) => value !== undefined));
143
91
  /**
@@ -164,21 +112,21 @@ export function createAgent(backend, cwd, signal) {
164
112
  }
165
113
  };
166
114
  return {
167
- async instruct(prompt, options, used) {
115
+ async instruct(prompt, options, used, ownTools) {
168
116
  const { system, model, thinking, tools, skills, templates, extensions, cutOff } = options ?? {};
169
- return ask(prompt, { cwd, system, signal, ...asked({ model, thinking, tools, skills, templates, extensions, used }) }, cutOff);
117
+ return ask(prompt, { cwd, system, signal, ...asked({ model, thinking, tools, ownTools, skills, templates, extensions, used }) }, cutOff);
170
118
  },
171
- async generate(input, used) {
119
+ async generate(input, used, ownTools) {
172
120
  if (!isJsonObject(input.schema))
173
121
  throw new Error("Schema validation failed: a schema is an object of the fields the answer is to have");
174
- const shape = shapeOf(input.schema, null);
122
+ const shape = shapeOf(input.schema);
175
123
  const schemaInstruction = `Respond with ONLY a JSON object matching this shape:\n${JSON.stringify(input.schema, null, 2)}\n${hasList(shape) ? "Where the shape shows a list, it shows one item: answer with as many as there are, each of that shape.\n" : ""}No markdown. No explanation. Just the JSON.`;
176
124
  const fullPrompt = `${input.prompt}\n\n${schemaInstruction}`;
177
125
  const { system, model, thinking, tools, skills, extensions, cutOff } = input;
178
126
  // The prompt of a typed answer is text, whatever it begins with: what says how to answer follows it, and a
179
127
  // skill called up by name, or a command, would take that for its own — and would not be there at a second asking.
180
128
  const asText = skills !== undefined || extensions !== undefined ? true : undefined;
181
- const call = { cwd, system, signal, ...asked({ model, thinking, tools, skills, extensions, asText, used }) };
129
+ const call = { cwd, system, signal, ...asked({ model, thinking, tools, ownTools, skills, extensions, asText, used }) };
182
130
  const parseAndValidate = (response) => {
183
131
  const trimmed = response.trim();
184
132
  // Try raw parse first — avoids mangling valid JSON that contains
@@ -188,10 +136,20 @@ export function createAgent(backend, cwd, signal) {
188
136
  parsed = JSON.parse(trimmed);
189
137
  }
190
138
  catch {
191
- const fenceMatch = trimmed.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);
192
- parsed = JSON.parse(fenceMatch ? fenceMatch[1].trim() : trimmed);
139
+ // Fenced: what stands between the first fence and the last — an answer may hold fences of its own,
140
+ // in what it says — or, where that is not JSON (more blocks than one), what the first block holds.
141
+ const whole = trimmed.match(/```(?:json)?\s*\n?([\s\S]*)\n?\s*```/);
142
+ try {
143
+ if (!whole)
144
+ throw new SyntaxError("not fenced");
145
+ parsed = JSON.parse(whole[1].trim());
146
+ }
147
+ catch {
148
+ const first = trimmed.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);
149
+ parsed = JSON.parse(first ? first[1].trim() : trimmed);
150
+ }
193
151
  }
194
- return conform(parsed, shape, null);
152
+ return conform(parsed, shape);
195
153
  };
196
154
  // First attempt — backend errors (network/auth) propagate immediately.
197
155
  // Only parse/validation failures trigger a retry.
@@ -2,8 +2,12 @@ import type { Workspace } from "./types.js";
2
2
  export interface Bridge {
3
3
  /** What the runner handed the program when it started it — the bridge secret among it. */
4
4
  init: Record<string, any>;
5
- /** POST one call to the runner and return its result. */
6
- call(endpoint: string, body: unknown): Promise<any>;
5
+ /**
6
+ * POST one call to the runner and return its result. With `signal`, the
7
+ * call can be given up: its connection is closed — which is how the runner
8
+ * hears of it — and it rejects.
9
+ */
10
+ call(endpoint: string, body: unknown, signal?: AbortSignal): Promise<any>;
7
11
  }
8
12
  /**
9
13
  * The body of a call that takes options: what the call is made with, and the
@@ -2,6 +2,7 @@
2
2
  // reaches the runner that started it (ipc-server.ts is the other end).
3
3
  import { readFileSync } from "fs";
4
4
  import { Agent, request } from "http";
5
+ import { onAbort } from "./abort.js";
5
6
  import { messageOf } from "./errors.js";
6
7
  let cached;
7
8
  /**
@@ -53,8 +54,10 @@ export function openBridge(port, initPath) {
53
54
  // A call lasts as long as the work behind it — an agent run, or the whole
54
55
  // run of another program — so this uses node:http, which sets no deadline
55
56
  // for the response. (fetch gives up after five minutes without response headers.)
56
- const call = (endpoint, body) => new Promise((resolve, reject) => {
57
+ const call = (endpoint, body, signal) => new Promise((resolve, reject) => {
57
58
  const payload = encode(endpoint, body);
59
+ if (signal?.aborted)
60
+ return reject(new Error(`${endpoint} was given up`));
58
61
  const req = request({
59
62
  host: "127.0.0.1",
60
63
  port,
@@ -85,6 +88,8 @@ export function openBridge(port, initPath) {
85
88
  });
86
89
  });
87
90
  req.on("error", reject);
91
+ const off = onAbort(signal, () => req.destroy(new Error(`${endpoint} was given up`)));
92
+ req.on("close", off);
88
93
  req.end(payload);
89
94
  });
90
95
  const bridge = { init, call };
package/dist/client.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import type { Ctx, Agent, AgentOptions, Thinking, Schema, SchemaField, ShellResult, Tools, ObserveResult, Workspace } from "./types.js";
2
- export type { Ctx, Agent, AgentOptions, Thinking, Schema, SchemaField, ShellResult, Tools, ObserveResult, Workspace };
1
+ import type { Ctx, Agent, AgentOptions, AgentTool, Thinking, Schema, SchemaField, ShellResult, Tools, ObserveResult, Workspace } from "./types.js";
2
+ export type { Ctx, Agent, AgentOptions, AgentTool, Thinking, Schema, SchemaField, ShellResult, Tools, ObserveResult, Workspace };
3
3
  export declare const ctx: Ctx;
4
4
  export declare const agent: Agent;
5
5
  export declare const tools: Tools;
package/dist/client.js CHANGED
@@ -1,7 +1,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,131 @@ 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
+ }
50
174
  export const agent = {
51
- instruct: async (prompt, opts) => call("/agent/instruct", withOptions({ prompt }, opts)),
52
- generate: (input) => call("/agent/generate", input),
175
+ instruct: async (prompt, opts) => agentCall("/agent/instruct", withOptions({ prompt }, opts)),
176
+ generate: async (input) => agentCall("/agent/generate", input),
53
177
  };
54
178
  export const tools = {
55
179
  read: (path) => call("/tools/read", { path }),
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,5 @@
1
1
  export type { Budget, ProgramResult, RunOptions } from "./runner-types.js";
2
+ export { failureOf } from "./runner.js";
2
3
  import type { ProgramResult, RunOptions } from "./runner-types.js";
3
4
  export type { Workspace, ObserveResult } from "./types.js";
4
5
  import type { Workspace } from "./types.js";