@trama-dev/runtime 0.3.1 → 0.5.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 (47) hide show
  1. package/README.md +4 -3
  2. package/dist/abort.d.ts +12 -0
  3. package/dist/abort.js +31 -0
  4. package/dist/agent-backend.d.ts +0 -6
  5. package/dist/agent-backend.js +1 -21
  6. package/dist/agent.d.ts +16 -1
  7. package/dist/agent.js +108 -35
  8. package/dist/bridge-client.js +44 -14
  9. package/dist/child-process.d.ts +1 -20
  10. package/dist/child-process.js +11 -86
  11. package/dist/client.d.ts +2 -1
  12. package/dist/client.js +5 -15
  13. package/dist/context.d.ts +36 -7
  14. package/dist/context.js +83 -92
  15. package/dist/errors.d.ts +2 -0
  16. package/dist/errors.js +2 -0
  17. package/dist/index.d.ts +12 -1
  18. package/dist/index.js +93 -53
  19. package/dist/ipc-server.d.ts +12 -6
  20. package/dist/ipc-server.js +124 -136
  21. package/dist/journal-view.d.ts +9 -0
  22. package/dist/journal-view.js +139 -0
  23. package/dist/journal.d.ts +70 -0
  24. package/dist/journal.js +454 -0
  25. package/dist/meta.d.ts +18 -0
  26. package/dist/meta.js +29 -0
  27. package/dist/path-guard.d.ts +128 -19
  28. package/dist/path-guard.js +384 -68
  29. package/dist/pi-adapter.d.ts +7 -6
  30. package/dist/pi-adapter.js +15 -26
  31. package/dist/replace-file.d.ts +31 -0
  32. package/dist/replace-file.js +75 -0
  33. package/dist/runner-types.d.ts +2 -0
  34. package/dist/runner.d.ts +37 -37
  35. package/dist/runner.js +565 -239
  36. package/dist/serializable.d.ts +10 -4
  37. package/dist/serializable.js +56 -31
  38. package/dist/{watchdog.d.ts → stopping.d.ts} +15 -0
  39. package/dist/stopping.js +268 -0
  40. package/dist/tools.js +44 -13
  41. package/dist/tree.d.ts +234 -0
  42. package/dist/tree.js +1409 -0
  43. package/dist/types.d.ts +6 -3
  44. package/dist/workspace.d.ts +7 -0
  45. package/dist/workspace.js +93 -104
  46. package/package.json +2 -2
  47. package/dist/watchdog.js +0 -167
@@ -1,107 +1,423 @@
1
- import { existsSync, realpathSync, lstatSync, readlinkSync } from "fs";
2
- import { resolve, dirname, sep } from "path";
1
+ import { lstatSync, mkdirSync, readlinkSync, statSync } from "fs";
2
+ import { dirname, isAbsolute, join, parse, resolve, sep } from "path";
3
3
  /**
4
4
  * Keep file access inside a bounded root directory (a project directory or a
5
5
  * session workspace) — rejecting escapes via ".." segments or symlinks.
6
6
  *
7
+ * A path is read the way the system reads it: one step at a time, each link
8
+ * followed where it stands, ".." taken from where the walk has got to. It is
9
+ * never tidied up as text first — "dir/../file" is "file" only if "dir" is a
10
+ * directory that is not a link, and the text cannot know.
11
+ *
7
12
  * Not a security sandbox — just a footgun guard against malicious shared
8
13
  * projects where files like state.json or .gitignore are symlinks pointing
9
14
  * outside the project directory.
10
15
  */
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);
16
+ /**
17
+ * The most links followed on the way to one path. More than this is a loop —
18
+ * to the strictest of the systems this runs on (macOS stops at 32, Linux at 40).
19
+ */
20
+ const MAX_LINKS = 32;
21
+ const tooManyLinks = (path) => new Error(`Too many levels of symbolic links: ${path}`);
22
+ /**
23
+ * A step that is not a name: what the walk has come to must be a directory.
24
+ * A path says so by ending in a slash. (It is not the same as a last step of
25
+ * ".", which is looked up in the directory and so needs leave to search it.)
26
+ */
27
+ const A_DIRECTORY = sep;
28
+ /** The steps of a path, one name at a time. */
29
+ function stepsOf(path) {
30
+ const steps = path.split(sep).filter(Boolean);
31
+ if (steps.length > 0 && path.endsWith(sep))
32
+ steps.push(A_DIRECTORY);
33
+ return steps;
14
34
  }
35
+ const UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
15
36
  /**
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.
37
+ * A byte buffer as UTF-8 text — undefined if its bytes are not valid UTF-8.
38
+ * Leading BOM bytes are preserved as text rather than stripped.
19
39
  */
20
- export function resolveBounded(rootDir, relativePath) {
21
- const normalizedDir = resolve(rootDir);
22
- const resolved = resolve(normalizedDir, relativePath);
23
- if (!isInside(resolved, normalizedDir)) {
24
- throw new Error(`Path escapes project directory: ${relativePath}`);
40
+ export function utf8Text(raw) {
41
+ try {
42
+ return UTF8.decode(raw);
25
43
  }
26
- return resolved;
27
- }
28
- function verifyRealPath(realPath, realRoot, originalPath) {
29
- if (!isInside(realPath, realRoot)) {
30
- throw new Error(`Path escapes project directory via symlink: ${originalPath}`);
44
+ catch {
45
+ return undefined;
31
46
  }
32
47
  }
33
48
  /**
34
- * Walk up from `resolved` to find the deepest existing ancestor,
35
- * then verify its real path is inside the root.
36
- * This catches symlink escapes BEFORE any mkdir side effects.
49
+ * What a link says, as text — undefined if it says nothing a path can be made
50
+ * of: a name that is not valid UTF-8, or nothing at all (macOS lets a link to
51
+ * nothing be made, and then refuses every use of it).
37
52
  */
38
- function verifyNearestAncestor(resolved, realRoot, originalPath) {
39
- let cur = resolved;
40
- while (!existsSync(cur)) {
41
- const parent = dirname(cur);
42
- if (parent === cur)
43
- return; // reached filesystem root — nothing to verify
44
- cur = parent;
45
- }
46
- verifyRealPath(realpathSync(cur), realRoot, originalPath);
53
+ export function linkText(link) {
54
+ const text = utf8Text(readlinkSync(link, "buffer"));
55
+ return text !== "" ? text : undefined;
47
56
  }
57
+ /** The top of the file system an absolute path starts from: where every walk begins. */
58
+ const topOf = (path) => ({ at: parse(path).root, links: 0, missing: false });
48
59
  /**
49
- * Verify that an existing symlink's target resolves inside the root.
50
- * For dangling symlinks, falls back to verifyNearestAncestor on the link target.
60
+ * Where a path leads once every symlink on the way is followed. The path is
61
+ * taken as it is written, and may say "..", "." or end in a slash. One that
62
+ * starts at the top of the file system is walked from there; any other, on
63
+ * from `from` — so a path with no steps at all leads to where it started.
64
+ *
65
+ * Like realpath, but through what does not exist yet: a link whose
66
+ * destination is missing is still followed to where it points — and from
67
+ * there on, if that is a link too — and once nothing is there, the rest is
68
+ * taken as it is named. This is where a write to the path lands, and where a
69
+ * mkdir on the way to it creates directories.
70
+ *
71
+ * `passing` is told each place the walk comes to, the first and the last
72
+ * among them, with the steps still to be taken from there, and may give the
73
+ * place another name to go on by. `link` is asked about each link the walk
74
+ * comes to — where it is, and whether the path ends there — and may say where
75
+ * the walk is to be instead of following it. (A link so taken counts as one
76
+ * followed, however many it stands for: the count is then only what stops a
77
+ * walk that goes round. Whoever has links taken so, and needs to know whether
78
+ * the system would follow the words, asks the system.)
51
79
  */
52
- function verifySymlink(target, realRoot, originalPath) {
53
- try {
54
- verifyRealPath(realpathSync(target), realRoot, originalPath);
55
- }
56
- catch (e) {
57
- if (e.code !== "ENOENT")
58
- throw e;
59
- // Dangling symlink — resolve what we can via nearest existing ancestor
60
- const linkDest = resolve(dirname(target), readlinkSync(target));
61
- verifyNearestAncestor(linkDest, realRoot, originalPath);
80
+ function follow(path, from, watch = {}) {
81
+ const fromTop = isAbsolute(path);
82
+ let { at, links, missing } = fromTop ? topOf(path) : from;
83
+ let steps = stepsOf(fromTop ? path.slice(at.length) : path);
84
+ for (;;) {
85
+ at = watch.passing?.(at, steps) ?? at;
86
+ if (steps.length === 0)
87
+ break;
88
+ const step = steps.shift();
89
+ if (step === "." || step === ".." || step === A_DIRECTORY) {
90
+ // "Here", "up" and "this is a directory" are said of a directory. Of
91
+ // something that is not there they lead nowhere the system would go —
92
+ // it cannot be created as a file and be a directory too. (Of a file
93
+ // they are refused further down, where the file is come to.)
94
+ if (missing) {
95
+ throw new Error(`Path cannot be followed: ${path} (it leads on from what does not exist)`);
96
+ }
97
+ if (step === A_DIRECTORY)
98
+ continue;
99
+ // Asked of the system rather than assumed: it takes a directory, and leave to search it.
100
+ lstatSync(at + sep + step);
101
+ if (step === "..")
102
+ at = dirname(at);
103
+ continue;
104
+ }
105
+ const next = join(at, step);
106
+ if (missing) {
107
+ at = next;
108
+ continue;
109
+ }
110
+ let stat;
111
+ try {
112
+ stat = lstatSync(next);
113
+ }
114
+ catch (e) {
115
+ if (e.code !== "ENOENT")
116
+ throw e;
117
+ missing = true;
118
+ at = next;
119
+ continue;
120
+ }
121
+ if (!stat.isSymbolicLink()) {
122
+ // Nothing lies beyond a file — not a name, and not "." or ".." either.
123
+ // The system refuses to go on, and so does this.
124
+ if (!stat.isDirectory() && steps.length > 0) {
125
+ throw Object.assign(new Error(`ENOTDIR: not a directory, ${next} (on the way to ${path})`), { code: "ENOTDIR" });
126
+ }
127
+ at = next;
128
+ continue;
129
+ }
130
+ const instead = watch.link?.(next, steps.length === 0);
131
+ if (instead) {
132
+ if (++links > MAX_LINKS)
133
+ throw tooManyLinks(path);
134
+ ({ at, missing } = instead);
135
+ // As where a file is come to by a step: nothing lies beyond one.
136
+ if (steps.length > 0 && !missing && !lstatSync(at).isDirectory()) {
137
+ throw Object.assign(new Error(`ENOTDIR: not a directory, ${at} (on the way to ${path})`), { code: "ENOTDIR" });
138
+ }
139
+ continue;
140
+ }
141
+ if (++links > MAX_LINKS)
142
+ throw tooManyLinks(path);
143
+ const target = linkText(next);
144
+ if (target === undefined) {
145
+ throw new Error(`Path cannot be followed: ${next} (it links to nothing, or to what is not readable as text)`);
146
+ }
147
+ if (isAbsolute(target))
148
+ at = parse(target).root;
149
+ steps = [...stepsOf(target), ...steps];
62
150
  }
151
+ return { at, links, missing };
63
152
  }
64
- /** The real (symlink-resolved) location of a root directory, or its normalized path if it doesn't exist yet. */
153
+ /**
154
+ * The real (symlink-resolved) location of a root directory, whether or not it
155
+ * exists yet. A root is named by whoever runs the program, not by the
156
+ * program, and is read as the rest of Node reads a directory it is given.
157
+ */
65
158
  export function realRootOf(rootDir) {
66
- const normalizedDir = resolve(rootDir);
159
+ const root = resolve(rootDir);
160
+ return follow(root, topOf(root)).at;
161
+ }
162
+ /** Whether one normalized path is another or lies under it — as text, which is all this can say. */
163
+ const within = (path, root) => path === root || path.startsWith(root.endsWith(sep) ? root : root + sep);
164
+ export const identityIn = (stat) => `${stat.dev}:${stat.ino}`;
165
+ /**
166
+ * What tells one file or directory from every other — undefined if nothing is
167
+ * there to be told apart. Two paths with one identity are one place, however
168
+ * each is spelled; a link is itself, not what it points at.
169
+ *
170
+ * This is how the runtime asks whether two paths are the same. Their text
171
+ * cannot say: a file system that takes "Data" and "data" for one name has
172
+ * many names for every directory.
173
+ *
174
+ * Undefined says that nothing is there, and only that. What is there and may
175
+ * not be looked at is not nothing: it throws.
176
+ */
177
+ export function identityOf(path) {
178
+ const stat = lstatSync(path, { bigint: true, throwIfNoEntry: false });
179
+ return stat && identityIn(stat);
180
+ }
181
+ /**
182
+ * A destination by the root's own name for it, if it is the root or lies
183
+ * under it — undefined if it does not.
184
+ *
185
+ * Under it by name, or by being there: a file system that takes "Data" and
186
+ * "data" for one name has many names for every directory, and a link may use
187
+ * any of them. So where the names do not say, each directory above the
188
+ * destination is asked whether it is the root.
189
+ */
190
+ function underRoot(destination, realRoot) {
191
+ if (within(destination, realRoot))
192
+ return destination;
193
+ const root = identityOf(realRoot);
194
+ if (!root)
195
+ return undefined;
196
+ for (let at = destination;; at = dirname(at)) {
197
+ if (identityOf(at) === root)
198
+ return join(realRoot, destination.slice(at.length));
199
+ if (at === dirname(at))
200
+ return undefined;
201
+ }
202
+ }
203
+ /**
204
+ * A reader of the links in `root` (named without links), for one who means
205
+ * to keep a copy of the root.
206
+ *
207
+ * It reads as a copy of the root would have to be read. A link of the root
208
+ * that a way passes through is not followed step by step but taken for the
209
+ * place it names: a copy has that link too, saying whatever it must to name
210
+ * the same place there, and how it says so is no part of the way. A link
211
+ * outside the root is nobody's copy, and is followed like any other step —
212
+ * to the end, also where the words end at it: what matters of it is where it
213
+ * leads.
214
+ *
215
+ * Whether a place is in the root is asked of the place (see underRoot), not
216
+ * read off its name: a way that has left the root may come back to it by any
217
+ * of the names the file system has for it.
218
+ */
219
+ export function linksOf(root) {
220
+ /** What each link of the root that a way has passed through names — null while that is being worked out. */
221
+ const named = new Map();
222
+ let depth = 0;
223
+ const nameOf = (link) => {
224
+ const known = named.get(link);
225
+ if (known)
226
+ return known;
227
+ // (A link that is being worked out leads back to itself. And one link's words may lead through another's, and
228
+ // those through a third: the system follows so many in one way and no more, and neither is this to go deeper.)
229
+ if (known === null || depth >= MAX_LINKS)
230
+ throw tooManyLinks(link);
231
+ named.set(link, null);
232
+ depth += 1;
233
+ try {
234
+ const text = linkText(link);
235
+ if (text === undefined)
236
+ throw new Error(`Path cannot be followed: ${link} (it links to nothing, or to what is not readable as text)`);
237
+ const { place } = lead(dirname(link), text);
238
+ named.set(link, place);
239
+ return place;
240
+ }
241
+ catch (err) {
242
+ named.delete(link);
243
+ throw err;
244
+ }
245
+ finally {
246
+ depth -= 1;
247
+ }
248
+ };
249
+ const isLink = (place) => !place.missing && lstatSync(place.at, { throwIfNoEntry: false })?.isSymbolicLink() === true;
250
+ const lead = (dir, text, seen = {}) => {
251
+ let inside = !isAbsolute(text) && underRoot(dir, root) !== undefined;
252
+ let strays = false;
253
+ const place = follow(text, { at: dir, links: 0, missing: false }, {
254
+ passing(at, ahead) {
255
+ const own = underRoot(at, root);
256
+ if ((own !== undefined) !== inside) {
257
+ strays = true;
258
+ // A step into the root arrives at its top, with the rest still to be said.
259
+ seen.stayed = own === root;
260
+ if (own === root)
261
+ seen.sinceRoot = ahead.length === 0 ? "" : sep + ahead.map((step) => (step === A_DIRECTORY ? "" : step)).join(sep);
262
+ }
263
+ inside = own !== undefined;
264
+ return own;
265
+ },
266
+ link(link, last) {
267
+ if (!within(link, root))
268
+ return undefined;
269
+ if (last)
270
+ return { at: link, links: 0, missing: false };
271
+ let place = nameOf(link);
272
+ for (let hops = 1; within(place.at, root) && isLink(place); hops++) {
273
+ if (hops === MAX_LINKS)
274
+ throw tooManyLinks(link);
275
+ place = nameOf(place.at);
276
+ }
277
+ inside = within(place.at, root); // arrived by a link of the root, not by a step of this way
278
+ return place;
279
+ },
280
+ });
281
+ return { place, strays };
282
+ };
283
+ return {
284
+ names(dir, text) {
285
+ const seen = {};
286
+ const { place, strays } = lead(dir, text, seen);
287
+ return { to: place.at, strays, home: seen.stayed ? seen.sinceRoot : undefined };
288
+ },
289
+ sinceRoot(dir, text) {
290
+ const seen = {};
291
+ try {
292
+ lead(dir, text, seen);
293
+ }
294
+ catch {
295
+ // The way cannot be followed to its end. How far it came is known all the same, and is all that is asked.
296
+ }
297
+ return seen.sinceRoot;
298
+ },
299
+ };
300
+ }
301
+ /**
302
+ * The places under a root that make a path lead where it does: every place
303
+ * the way comes to there — each name it steps to, each link it follows, each
304
+ * directory it goes through (also one it leaves again with ".."), and the
305
+ * place it ends at. With any of them another thing, or gone, the path leads
306
+ * somewhere else, or nowhere. Told as far as the way can be followed, each
307
+ * as the way names it — which need not be how its directory lists it.
308
+ */
309
+ export function wayTo(rootDir, path) {
310
+ const root = realRootOf(rootDir);
311
+ const places = new Set();
312
+ const cameTo = (at) => {
313
+ const own = underRoot(at, root);
314
+ if (own !== undefined && own !== root)
315
+ places.add(own);
316
+ };
67
317
  try {
68
- return realpathSync(normalizedDir);
318
+ follow(path, { at: root, links: 0, missing: false }, {
319
+ passing(at) { cameTo(at); return undefined; },
320
+ link(link) { cameTo(link); return undefined; },
321
+ });
69
322
  }
70
323
  catch {
71
- return normalizedDir;
324
+ // The way cannot be followed to its end. How far it came is all that is known of it.
72
325
  }
326
+ return [...places];
73
327
  }
74
328
  /**
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.
329
+ * Where a project is — which is a directory that is there. Nothing in the
330
+ * runtime makes one for a project that is gone: what it makes for a project,
331
+ * it makes in it. (Making the directories on the way to a file would make a
332
+ * project of that file, at the path of one that somebody has moved away.)
333
+ */
334
+ export function projectAt(projectDir) {
335
+ const project = realRootOf(projectDir);
336
+ if (!statSync(project, { throwIfNoEntry: false })?.isDirectory())
337
+ throw new Error(`There is no project at ${project}.`);
338
+ return project;
339
+ }
340
+ /**
341
+ * A question to ask later: whether what is at a project's path is still the
342
+ * directory that is there now. A project is known by what it is, and what is
343
+ * done over some time — generate a program, ask for a fix, try it, install it,
344
+ * write it down — is done to the project it was started on: not to another
345
+ * directory that somebody has put at the path meanwhile. (Gone is not another:
346
+ * what is to be done where no project is, each step says for itself.)
347
+ */
348
+ export function sameProjectAs(projectDir) {
349
+ const start = lstatSync(realRootOf(projectDir), { bigint: true, throwIfNoEntry: false });
350
+ const wasId = start?.isDirectory() ? identityIn(start) : undefined;
351
+ return () => {
352
+ const root = realRootOf(projectDir);
353
+ const now = lstatSync(root, { bigint: true, throwIfNoEntry: false });
354
+ if (wasId !== undefined && now && !(now.isDirectory() && identityIn(now) === wasId)) {
355
+ throw new Error(`What is at ${root} is not the project this was started on: nothing more is done there.`);
356
+ }
357
+ };
358
+ }
359
+ /**
360
+ * Make a directory under a root, with those on the way to it — in the root,
361
+ * which must be there: no root is made for the sake of what goes into it.
362
+ * This is for a root that is something in itself — a project, which
363
+ * somebody may have moved away since it was named: making the directory
364
+ * anew at its path would make another, and put into it what was meant for
365
+ * the first. (A workspace is nothing but its path, and is made as needed,
366
+ * with the way to it.)
367
+ * `dir` is a place the guard has passed.
368
+ */
369
+ export function makeDirsIn(rootDir, dir) {
370
+ const root = realRootOf(rootDir);
371
+ if (!statSync(root, { throwIfNoEntry: false })?.isDirectory()) {
372
+ throw Object.assign(new Error(`There is no directory at ${root}.`), { code: "ENOENT" });
373
+ }
374
+ mkdirSync(dir, { recursive: true });
375
+ }
376
+ /**
377
+ * The guard for reading or writing a path under a bounded root: where the
378
+ * path leads, every link on the way followed — refused unless that is inside
379
+ * the root, and a file, a directory, or nothing yet. What comes back has no
380
+ * link left in it, so using it goes where this looked.
78
381
  *
79
- * For paths that don't exist yet, checks the nearest existing ancestor —
80
- * so a caller can safely mkdir and write afterwards.
382
+ * A path that does not exist yet is followed as far as it does, so a caller
383
+ * can safely mkdir and write afterwards: a write lands on what a link points
384
+ * at, not on a link on the way.
81
385
  */
82
- export function guardPath(rootDir, relativePath) {
83
- const realRoot = realRootOf(rootDir);
84
- const resolved = resolveBounded(rootDir, relativePath);
85
- // Use lstatSync (not existsSync) to detect dangling symlinks.
86
- // existsSync returns false for dangling symlinks, which would skip the
87
- // symlink check and allow writes to follow the link to an external target.
88
- let stat;
386
+ export function guardPath(rootDir, path) {
387
+ const root = resolve(rootDir);
388
+ // The root is walked first, and the path on from where that arrives: the
389
+ // way the system reads the two written one after the other.
390
+ const realRoot = follow(root, topOf(root));
391
+ const destination = underRoot(follow(path, realRoot).at, realRoot.at);
392
+ // The same, as the system is asked about it below.
393
+ const given = isAbsolute(path) ? path : root + sep + path;
394
+ if (destination === undefined) {
395
+ // Said for whoever reads the refusal: if the text alone stays inside, it is the links that lead out.
396
+ throw new Error(`Path escapes project directory${within(resolve(given), root) ? " via symlink" : ""}: ${path}`);
397
+ }
398
+ // The walk above is this guard's own reading of the path. The system has
399
+ // the last word on it: where it can follow the path, it must arrive where
400
+ // the walk did, and where it cannot, that must be because nothing is there
401
+ // yet — not because it will not go (too many links, a name too long, no
402
+ // leave to pass), which the walk may not have noticed. A path the two read
403
+ // differently is one a write would put somewhere a read does not look.
404
+ let found;
89
405
  try {
90
- stat = lstatSync(resolved);
406
+ found = statSync(given, { bigint: true });
91
407
  }
92
408
  catch (e) {
93
409
  if (e.code !== "ENOENT")
94
410
  throw e;
95
- // Path truly doesn't exist (not even as a dangling symlink)
96
- // — verify nearest ancestor is inside the root
97
- verifyNearestAncestor(resolved, realRoot, relativePath);
98
- return resolved;
99
411
  }
100
- if (stat.isSymbolicLink()) {
101
- verifySymlink(resolved, realRoot, relativePath);
412
+ const there = lstatSync(destination, { bigint: true, throwIfNoEntry: false });
413
+ if (found ? !(there && identityIn(there) === identityIn(found)) : there !== undefined) {
414
+ throw new Error(`Path cannot be followed: ${path} (the system does not take it where its links say)`);
102
415
  }
103
- else {
104
- verifyRealPath(realpathSync(resolved), realRoot, relativePath);
416
+ // What is there is content, or a place for it. A pipe, a socket or a device
417
+ // is the end of something else: reading one, or writing to one, can wait
418
+ // for ever on whoever is at the other end — and with it this whole process.
419
+ if (there && !there.isFile() && !there.isDirectory()) {
420
+ throw new Error(`Not a file or a directory: ${path}`);
105
421
  }
106
- return resolved;
422
+ return destination;
107
423
  }
@@ -1,4 +1,4 @@
1
- import { type AgentBackend, type AgentCall } from "./agent-backend.js";
1
+ import type { AgentBackend, AgentCall } from "./agent-backend.js";
2
2
  import type { ModelConfig } from "./runner-types.js";
3
3
  /** The pi version this runtime is built against (recorded in each project's meta.json). */
4
4
  export declare const piVersion: () => Promise<string>;
@@ -14,11 +14,12 @@ export declare class PiAdapter implements AgentBackend {
14
14
  private warnUnknownModel;
15
15
  private extractText;
16
16
  /**
17
- * Abort cancellation relies on session.dispose() interrupting session.prompt().
18
- * This is an upstream contract of pi-coding-agent — if dispose() does not
19
- * actually settle the in-flight prompt, the abort signal will not terminate the call.
20
- * pi 1.x settles the prompt by resolving it (not rejecting), so abort is
21
- * re-checked after prompt() returns.
17
+ * Run one prompt in a fresh session and return the assistant's text reply.
18
+ *
19
+ * Cancellation during `createSession` is handled step-by-step inside it; once
20
+ * `session.prompt()` is running, abort disposes the session so pi settles the
21
+ * in-flight prompt (pi 1.x resolves rather than rejects on dispose, so
22
+ * `signal.aborted` is checked again when `prompt()` returns).
22
23
  */
23
24
  ask(prompt: string, call: AgentCall): Promise<string>;
24
25
  }
@@ -1,4 +1,4 @@
1
- import { rejectOnAbort } from "./agent-backend.js";
1
+ import { onAbort, rejectOnAbort, throwIfAborted } from "./abort.js";
2
2
  /**
3
3
  * pi is loaded when it is first needed, not when this file is: it is most of
4
4
  * what the runtime weighs, and listing projects, reading logs, or running a
@@ -16,8 +16,6 @@ export class PiAdapter {
16
16
  this.config = config;
17
17
  }
18
18
  async createSession(cwd, systemPrompt, signal) {
19
- if (signal?.aborted)
20
- throw new Error("Aborted");
21
19
  // Each step below is given up on the moment the call is cancelled.
22
20
  const raceAbort = (step) => rejectOnAbort(step, signal);
23
21
  const { createAgentSession, SessionManager, DefaultResourceLoader, ModelRuntime, getAgentDir } = await raceAbort(loadPi());
@@ -30,14 +28,10 @@ export class PiAdapter {
30
28
  ...(systemPrompt && { appendSystemPrompt: [systemPrompt] }),
31
29
  });
32
30
  await raceAbort(resourceLoader.reload());
33
- if (signal?.aborted)
34
- throw new Error("Aborted");
35
31
  // Resolve the model through pi's model runtime (built-in catalog plus the
36
32
  // user's models.json). An unknown provider/model resolves to undefined, in
37
33
  // which case pi falls back to its own default selection.
38
34
  const modelRuntime = await raceAbort(ModelRuntime.create({ signal }));
39
- if (signal?.aborted)
40
- throw new Error("Aborted");
41
35
  const model = modelRuntime.getModel(this.config.provider, this.config.model);
42
36
  // Keep a reference to the raw promise so we can clean up a late-arriving session
43
37
  const sessionPromise = createAgentSession({
@@ -95,38 +89,33 @@ export class PiAdapter {
95
89
  return "";
96
90
  }
97
91
  /**
98
- * Abort cancellation relies on session.dispose() interrupting session.prompt().
99
- * This is an upstream contract of pi-coding-agent — if dispose() does not
100
- * actually settle the in-flight prompt, the abort signal will not terminate the call.
101
- * pi 1.x settles the prompt by resolving it (not rejecting), so abort is
102
- * re-checked after prompt() returns.
92
+ * Run one prompt in a fresh session and return the assistant's text reply.
93
+ *
94
+ * Cancellation during `createSession` is handled step-by-step inside it; once
95
+ * `session.prompt()` is running, abort disposes the session so pi settles the
96
+ * in-flight prompt (pi 1.x resolves rather than rejects on dispose, so
97
+ * `signal.aborted` is checked again when `prompt()` returns).
103
98
  */
104
99
  async ask(prompt, call) {
105
100
  const { cwd, system, signal } = call;
106
- if (signal?.aborted)
107
- throw new Error("Aborted");
108
- // Track session so abort can dispose it at any point — even during createSession
109
- let session = null;
110
- const onAbort = () => session?.dispose();
111
- signal?.addEventListener("abort", onAbort, { once: true });
101
+ throwIfAborted(signal);
102
+ const session = await this.createSession(cwd, system, signal);
103
+ let offAbort = () => { };
112
104
  try {
113
- session = await this.createSession(cwd, system, signal);
114
- // Re-check: abort may have fired during createSession (before session existed)
115
- if (signal?.aborted)
116
- throw new Error("Aborted");
105
+ throwIfAborted(signal);
106
+ offAbort = onAbort(signal, () => session.dispose());
117
107
  await session.prompt(prompt);
118
108
  // An aborted prompt resolves with no usable answer — report it as an abort,
119
109
  // not as an empty LLM response.
120
- if (signal?.aborted)
121
- throw new Error("Aborted");
110
+ throwIfAborted(signal);
122
111
  const text = this.extractText(session);
123
112
  if (!text)
124
113
  throw new Error("Empty response from LLM");
125
114
  return text;
126
115
  }
127
116
  finally {
128
- signal?.removeEventListener("abort", onAbort);
129
- session?.dispose();
117
+ offAbort();
118
+ session.dispose();
130
119
  }
131
120
  }
132
121
  }
@@ -0,0 +1,31 @@
1
+ /** Whether a file name is that of a temp file made here — not content, though it sits among it for a moment. */
2
+ export declare const isStagedName: (name: string) => boolean;
3
+ /**
4
+ * A name beside a destination for what is to take its place. It is not made
5
+ * of the destination's own: a name near the longest a directory takes leaves
6
+ * no room to add to.
7
+ */
8
+ export declare const stagedNameFor: (destination: string) => string;
9
+ export interface StagedFile {
10
+ /** Where the content will be: the path given, with every link on the way followed. */
11
+ destination: string;
12
+ /** Move the content into place. If that cannot be done, nothing is left behind. */
13
+ commit(): void;
14
+ /** Call it off: the destination stays as it is. */
15
+ discard(): void;
16
+ }
17
+ /**
18
+ * Write `content` beside where `relativePath` under `rootDir` leads, ready to
19
+ * take its place.
20
+ *
21
+ * The destination is where the links on the way point, so a link is written
22
+ * through, not replaced. It must be a file's place: the root itself is
23
+ * refused, since "beside" it is outside it. Directories on the way are
24
+ * created. The temp file is created, never opened: a name that is already
25
+ * there — a link somebody planted, say — is not written through. A file that
26
+ * is being replaced hands on its permissions, as it would if it were written
27
+ * into — unless `mode` says what the new file's are. It is a new file all the
28
+ * same, so a second hard link to the old one, or its owner, are not carried
29
+ * over.
30
+ */
31
+ export declare function stageFile(rootDir: string, relativePath: string, content: string | Buffer, mode?: number): StagedFile;