@pmndre/pine 0.36.0 → 0.37.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/src/tui/run.js CHANGED
@@ -1,18 +1,9 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
1
  import { ProcessTerminal } from "@earendil-works/pi-tui";
4
2
  import { loadConfig } from "../config.js";
5
3
  import { findServer, listServers, piMcp, serverStates } from "../mcp-config.js";
4
+ import { ensureDaemon } from "../service.js";
6
5
  import { PineTui } from "./app.js";
7
6
  import { Client } from "./client.js";
8
- const reachable = async (url) => {
9
- try {
10
- return (await fetch(url, { signal: AbortSignal.timeout(800) })).ok;
11
- }
12
- catch {
13
- return false;
14
- }
15
- };
16
7
  /**
17
8
  * Open the terminal UI. It attaches to a running daemon; if none answers, it starts one inside
18
9
  * this process (logging to data/pine.log) and stops it again on exit.
@@ -22,37 +13,9 @@ export async function runTui(cfg, opts = {}) {
22
13
  throw new Error("the terminal UI needs the control API; remove \"http\": false from pine.json");
23
14
  if (!process.stdout.isTTY || !process.stdin.isTTY)
24
15
  throw new Error("the terminal UI needs an interactive terminal");
25
- const base = `http://${cfg.http.host === "0.0.0.0" ? "127.0.0.1" : cfg.http.host}:${cfg.http.port}`;
26
- const cleanup = [];
27
- let token;
28
- let mode = "attached";
29
- if (await reachable(`${base}/health`)) {
30
- const tokenFile = path.join(cfg.dataDir, "http-token");
31
- token = cfg.http.token ?? fs.readFileSync(tokenFile, "utf8").trim();
32
- }
33
- else {
34
- // A provider called "dev" is the claude -p stand-in; bring it up too if nothing serves it.
35
- try {
36
- const models = JSON.parse(fs.readFileSync(path.join(cfg.home, "models.json"), "utf8"));
37
- const dev = models.providers?.dev?.baseUrl;
38
- const uses = [cfg.defaults.model, ...Object.values(cfg.agents).map((a) => a.model)].some((m) => m?.startsWith("dev/"));
39
- if (dev && uses && !(await reachable(`${dev}/models`))) {
40
- const { startClaudeModel } = await import("../dev/claude-model.js");
41
- const server = await startClaudeModel({ port: Number(new URL(dev).port) });
42
- cleanup.push(() => server.close());
43
- mode = "embedded daemon + claude -p";
44
- }
45
- }
46
- catch {
47
- // No models.json or no dev provider: nothing to start.
48
- }
49
- const { startPine } = await import("../pine.js");
50
- const pine = await startPine({ config: cfg, logFile: path.join(cfg.dataDir, "pine.log") });
51
- cleanup.push(() => pine.stop());
52
- token = pine.token;
53
- if (mode === "attached")
54
- mode = "embedded daemon";
55
- }
16
+ const service = await ensureDaemon(cfg);
17
+ const { base, token, mode } = service;
18
+ const cleanup = [() => service.stop()];
56
19
  const done = Promise.withResolvers();
57
20
  const app = new PineTui({
58
21
  client: new Client(base, token),
@@ -64,9 +64,36 @@ export declare function listDir(root: string, rel: string): {
64
64
  more: boolean;
65
65
  } | undefined;
66
66
  /** A file's text, for reading. Binary files and very large ones are only described. */
67
- export declare function readText(root: string, rel: string): {
67
+ /** The most text one read or one write of a file carries: what an editor in a UI works on. */
68
+ export declare const MAX_EDIT: number;
69
+ export declare function readText(root: string, rel: string, max?: number): {
68
70
  text?: string;
69
71
  size: number;
70
72
  binary: boolean;
71
73
  truncated: boolean;
72
74
  } | undefined;
75
+ /**
76
+ * Write a file's text: what the owner changed in an editor of a UI. The one place here that
77
+ * does not only read, and the owner's alone (the control API; no tool reaches it).
78
+ *
79
+ * The folder is one an agent writes in, so nothing in it is taken at its word: a file of that
80
+ * name may be a link to somewhere else or a second name of a file that lies elsewhere too, and a
81
+ * folder on the way may become a link between a look and the write. The path is looked at
82
+ * first, for a clear refusal. What keeps the write inside is not that look but `putInto`.
83
+ * A missing file is made; a missing folder is not.
84
+ */
85
+ export declare function writeText(root: string, rel: string, text: string): Promise<{
86
+ size: number;
87
+ }>;
88
+ /**
89
+ * Put bytes into place as the file `target`, by a helper that the system's sandbox lets write
90
+ * in `base` and nowhere else, as a restore of the snapshots relies on: whatever a path has
91
+ * become since it was looked at, nothing outside the folder is written. The bytes go into a new
92
+ * file beside the target, which is then moved over it. So the file that was there is never
93
+ * written through, and what else it was (a link, another name of a file elsewhere) is left as
94
+ * it is, with what it pointed at.
95
+ */
96
+ export declare function putInto(base: string, target: string, bytes: Buffer, mode?: number): Promise<{
97
+ code: number;
98
+ err: string;
99
+ }>;
@@ -1,4 +1,5 @@
1
1
  import { spawn } from "node:child_process";
2
+ import crypto from "node:crypto";
2
3
  import fs from "node:fs";
3
4
  import path from "node:path";
4
5
  import { bin, helperArgv, isInside, realish } from "./security.js";
@@ -198,7 +199,9 @@ export function listDir(root, rel) {
198
199
  return { entries: entries.slice(0, 500), more: entries.length > 500 };
199
200
  }
200
201
  /** A file's text, for reading. Binary files and very large ones are only described. */
201
- export function readText(root, rel) {
202
+ /** The most text one read or one write of a file carries: what an editor in a UI works on. */
203
+ export const MAX_EDIT = 2 * 1024 * 1024;
204
+ export function readText(root, rel, max = 256 * 1024) {
202
205
  const file = inside(root, rel);
203
206
  if (!file)
204
207
  return undefined;
@@ -206,7 +209,6 @@ export function readText(root, rel) {
206
209
  const stat = fs.statSync(file);
207
210
  if (!stat.isFile())
208
211
  return undefined;
209
- const max = 256 * 1024;
210
212
  const fd = fs.openSync(file, "r");
211
213
  const buf = Buffer.alloc(Math.min(stat.size, max));
212
214
  fs.readSync(fd, buf, 0, buf.length, 0);
@@ -219,3 +221,86 @@ export function readText(root, rel) {
219
221
  return undefined;
220
222
  }
221
223
  }
224
+ /**
225
+ * Write a file's text: what the owner changed in an editor of a UI. The one place here that
226
+ * does not only read, and the owner's alone (the control API; no tool reaches it).
227
+ *
228
+ * The folder is one an agent writes in, so nothing in it is taken at its word: a file of that
229
+ * name may be a link to somewhere else or a second name of a file that lies elsewhere too, and a
230
+ * folder on the way may become a link between a look and the write. The path is looked at
231
+ * first, for a clear refusal. What keeps the write inside is not that look but `putInto`.
232
+ * A missing file is made; a missing folder is not.
233
+ */
234
+ export async function writeText(root, rel, text) {
235
+ if (typeof rel !== "string" || !rel || rel.includes("\0"))
236
+ throw new Error("path: the file to write, from the top of the folder");
237
+ if (typeof text !== "string")
238
+ throw new Error("text: what the file is to hold");
239
+ const bytes = Buffer.from(text, "utf8");
240
+ if (bytes.length > MAX_EDIT)
241
+ throw new Error(`that is too much for one file here (${bytes.length} bytes, at most ${MAX_EDIT})`);
242
+ const base = realish(root);
243
+ const named = path.resolve(base, rel);
244
+ if (!isInside(base, named))
245
+ throw new Error(`${rel} is not a file in ${base}`);
246
+ const dir = realish(path.dirname(named));
247
+ if (dir !== base && !isInside(base, dir))
248
+ throw new Error(`${rel} leads out of ${base}: a link on the way points elsewhere`);
249
+ let parent;
250
+ try {
251
+ parent = fs.statSync(dir);
252
+ }
253
+ catch {
254
+ // said below
255
+ }
256
+ if (!parent?.isDirectory())
257
+ throw new Error(`there is no folder ${path.dirname(rel)} in ${base}; a file is written into a folder that exists`);
258
+ // Where a link of that name leads, if it is one: a link that stays in the folder is edited where its file lies.
259
+ const target = realish(path.join(dir, path.basename(named)));
260
+ if (!isInside(base, target))
261
+ throw new Error(`${rel} is a link that leads out of ${base}; the file it points at is not written from here`);
262
+ // A file keeps its rights (a script stays one); a new one gets the usual ones.
263
+ let mode = 0o644;
264
+ try {
265
+ const there = fs.statSync(target);
266
+ if (there.isDirectory())
267
+ throw new Error(`${rel} is a folder`);
268
+ if (there.isFile())
269
+ mode = there.mode & 0o777;
270
+ }
271
+ catch (e) {
272
+ if (e.code !== "ENOENT")
273
+ throw e;
274
+ }
275
+ const done = await putInto(base, target, bytes, mode);
276
+ if (done.code !== 0)
277
+ throw new Error(`${rel} could not be written: ${done.err.trim().split("\n")[0] || `the helper ended with ${done.code}`}`);
278
+ return { size: bytes.length };
279
+ }
280
+ /**
281
+ * Put bytes into place as the file `target`, by a helper that the system's sandbox lets write
282
+ * in `base` and nowhere else, as a restore of the snapshots relies on: whatever a path has
283
+ * become since it was looked at, nothing outside the folder is written. The bytes go into a new
284
+ * file beside the target, which is then moved over it. So the file that was there is never
285
+ * written through, and what else it was (a link, another name of a file elsewhere) is left as
286
+ * it is, with what it pointed at.
287
+ */
288
+ export function putInto(base, target, bytes, mode = 0o644) {
289
+ const jail = helperArgv([base]);
290
+ if (!jail)
291
+ return Promise.resolve({ code: 127, err: "there is no sandbox on this system to write the file in, and without one pine writes nothing into a folder an agent works in. Change the file with an editor of your own" });
292
+ // A name nobody can have put there before; and should one be there, it is not written into (-C).
293
+ const fresh = `${target}.pine-${crypto.randomBytes(9).toString("hex")}`;
294
+ const script = 'set -eC; trap \'rm -f "$2"\' EXIT; cat > "$2"; chmod "$3" "$2"; mv -f "$2" "$1"';
295
+ return new Promise((resolve) => {
296
+ // The paths are arguments of their own, never part of the command's text.
297
+ const child = spawn(jail[0], [...jail.slice(1), "/bin/sh", "-c", script, "sh", target, fresh, (mode & 0o777).toString(8)], { stdio: ["pipe", "ignore", "pipe"], env: { PATH: "/usr/bin:/bin", LC_ALL: "C" } });
298
+ let err = "";
299
+ child.stderr.on("data", (d) => (err.length < 2000 ? (err += d.toString("utf8")) : undefined));
300
+ child.stdin.on("error", () => { });
301
+ child.stdin.end(bytes);
302
+ const timer = setTimeout(() => child.kill("SIGKILL"), 15_000);
303
+ child.on("error", (e) => (clearTimeout(timer), resolve({ code: 127, err: e.message })));
304
+ child.on("close", (code) => (clearTimeout(timer), resolve({ code: code ?? 1, err })));
305
+ });
306
+ }