@pmndre/pine 0.0.0-stage → 0.22.1

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 (151) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +226 -2
  3. package/bin/pine.js +27 -0
  4. package/docs/SKILL.md +234 -0
  5. package/docs/references/agents.md +454 -0
  6. package/docs/references/coding.md +311 -0
  7. package/docs/references/computer.md +212 -0
  8. package/docs/references/configuration.md +310 -0
  9. package/docs/references/events.md +267 -0
  10. package/docs/references/mcp.md +420 -0
  11. package/docs/references/operations.md +394 -0
  12. package/docs/references/overview.md +195 -0
  13. package/docs/references/security.md +896 -0
  14. package/docs/references/setup.md +385 -0
  15. package/docs/references/sources.md +772 -0
  16. package/docs/references/stack.md +121 -0
  17. package/docs/references/tui.md +575 -0
  18. package/examples/home/.env.example +7 -0
  19. package/examples/home/USER.md +4 -0
  20. package/examples/home/agents/main/agent.json +4 -0
  21. package/examples/home/agents/main/workspace/AGENTS.md +14 -0
  22. package/examples/home/agents/main/workspace/MEMORY.md +4 -0
  23. package/examples/home/agents/main/workspace/SOUL.md +4 -0
  24. package/examples/home/models.json +62 -0
  25. package/examples/home/pine.json +34 -0
  26. package/examples/home/skills/README.txt +7 -0
  27. package/examples/launchd/com.pine.daemon.plist +32 -0
  28. package/examples/systemd/pine.service +22 -0
  29. package/mcp/browser.d.ts +99 -0
  30. package/mcp/browser.js +496 -0
  31. package/mcp/commands.d.ts +20 -0
  32. package/mcp/commands.js +88 -0
  33. package/mcp/computer.d.ts +139 -0
  34. package/mcp/computer.js +698 -0
  35. package/mcp/computer.swift +989 -0
  36. package/mcp/lib.d.ts +23 -0
  37. package/mcp/lib.js +52 -0
  38. package/mcp/web.d.ts +6 -0
  39. package/mcp/web.js +140 -0
  40. package/package.json +32 -4
  41. package/src/access.d.ts +112 -0
  42. package/src/access.js +438 -0
  43. package/src/actions.d.ts +75 -0
  44. package/src/actions.js +167 -0
  45. package/src/admin.d.ts +167 -0
  46. package/src/admin.js +625 -0
  47. package/src/agent-admin.d.ts +24 -0
  48. package/src/agent-admin.js +55 -0
  49. package/src/agents.d.ts +540 -0
  50. package/src/agents.js +2776 -0
  51. package/src/background.d.ts +29 -0
  52. package/src/background.js +100 -0
  53. package/src/cli.d.ts +2 -0
  54. package/src/cli.js +777 -0
  55. package/src/computer.d.ts +30 -0
  56. package/src/computer.js +32 -0
  57. package/src/config.d.ts +396 -0
  58. package/src/config.js +549 -0
  59. package/src/dev/claude-model.d.ts +37 -0
  60. package/src/dev/claude-model.js +204 -0
  61. package/src/env-file.d.ts +4 -0
  62. package/src/env-file.js +40 -0
  63. package/src/goals.d.ts +133 -0
  64. package/src/goals.js +316 -0
  65. package/src/http.d.ts +46 -0
  66. package/src/http.js +509 -0
  67. package/src/limiter.d.ts +32 -0
  68. package/src/limiter.js +84 -0
  69. package/src/login.d.ts +23 -0
  70. package/src/login.js +130 -0
  71. package/src/manual.d.ts +61 -0
  72. package/src/manual.js +443 -0
  73. package/src/mcp-config.d.ts +49 -0
  74. package/src/mcp-config.js +182 -0
  75. package/src/models.d.ts +90 -0
  76. package/src/models.js +274 -0
  77. package/src/net.d.ts +50 -0
  78. package/src/net.js +150 -0
  79. package/src/pine.d.ts +32 -0
  80. package/src/pine.js +134 -0
  81. package/src/programs.d.ts +123 -0
  82. package/src/programs.js +412 -0
  83. package/src/router.d.ts +56 -0
  84. package/src/router.js +164 -0
  85. package/src/sandbox-fs.d.ts +34 -0
  86. package/src/sandbox-fs.js +186 -0
  87. package/src/sandbox-linux.d.ts +96 -0
  88. package/src/sandbox-linux.js +297 -0
  89. package/src/sandbox-setup.d.ts +70 -0
  90. package/src/sandbox-setup.js +216 -0
  91. package/src/security.d.ts +238 -0
  92. package/src/security.js +660 -0
  93. package/src/skills.d.ts +67 -0
  94. package/src/skills.js +163 -0
  95. package/src/snapshots.d.ts +68 -0
  96. package/src/snapshots.js +306 -0
  97. package/src/source-types.d.ts +61 -0
  98. package/src/source-types.js +1 -0
  99. package/src/sources/command.d.ts +4 -0
  100. package/src/sources/command.js +77 -0
  101. package/src/sources/folder.d.ts +6 -0
  102. package/src/sources/folder.js +116 -0
  103. package/src/sources/ftp.d.ts +4 -0
  104. package/src/sources/ftp.js +307 -0
  105. package/src/sources/http.d.ts +4 -0
  106. package/src/sources/http.js +201 -0
  107. package/src/sources/mqtt.d.ts +18 -0
  108. package/src/sources/mqtt.js +97 -0
  109. package/src/sources/telegram.d.ts +22 -0
  110. package/src/sources/telegram.js +283 -0
  111. package/src/sources/webhook.d.ts +4 -0
  112. package/src/sources/webhook.js +52 -0
  113. package/src/sources.d.ts +344 -0
  114. package/src/sources.js +966 -0
  115. package/src/store.d.ts +99 -0
  116. package/src/store.js +277 -0
  117. package/src/timers.d.ts +83 -0
  118. package/src/timers.js +318 -0
  119. package/src/tools.d.ts +11 -0
  120. package/src/tools.js +1297 -0
  121. package/src/tui/app.d.ts +305 -0
  122. package/src/tui/app.js +3195 -0
  123. package/src/tui/client.d.ts +236 -0
  124. package/src/tui/client.js +131 -0
  125. package/src/tui/code-pane.d.ts +68 -0
  126. package/src/tui/code-pane.js +535 -0
  127. package/src/tui/highlight.d.ts +8 -0
  128. package/src/tui/highlight.js +86 -0
  129. package/src/tui/picture.d.ts +206 -0
  130. package/src/tui/picture.js +801 -0
  131. package/src/tui/run.d.ts +8 -0
  132. package/src/tui/run.js +97 -0
  133. package/src/tui/theme.d.ts +32 -0
  134. package/src/tui/theme.js +128 -0
  135. package/src/tui/undo.d.ts +5 -0
  136. package/src/tui/undo.js +50 -0
  137. package/src/tui/voice.d.ts +49 -0
  138. package/src/tui/voice.js +155 -0
  139. package/src/tui/voice.swift +223 -0
  140. package/src/types.d.ts +139 -0
  141. package/src/types.js +1 -0
  142. package/src/undo.d.ts +224 -0
  143. package/src/undo.js +465 -0
  144. package/src/update.d.ts +35 -0
  145. package/src/update.js +130 -0
  146. package/src/util.d.ts +65 -0
  147. package/src/util.js +171 -0
  148. package/src/watching.d.ts +20 -0
  149. package/src/watching.js +68 -0
  150. package/src/workspace-view.d.ts +72 -0
  151. package/src/workspace-view.js +221 -0
package/src/net.js ADDED
@@ -0,0 +1,150 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import dns from "node:dns";
3
+ import fs from "node:fs";
4
+ import net from "node:net";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { Agent, fetch } from "undici";
8
+ /** Addresses that are not on the public internet: loopback, private ranges, link-local, multicast. */
9
+ export function isPrivateAddress(ip) {
10
+ if (net.isIPv4(ip)) {
11
+ const [a, b] = ip.split(".").map(Number);
12
+ return a === 0 || a === 10 || a === 127 || (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 192 && b === 0) || (a === 198 && (b === 18 || b === 19)) || a >= 224;
13
+ }
14
+ const v = ip.toLowerCase();
15
+ if (v.startsWith("::ffff:"))
16
+ return isPrivateAddress(v.slice(7));
17
+ return v === "::" || v === "::1" || v.startsWith("fc") || v.startsWith("fd") || v.startsWith("fe8") || v.startsWith("fe9") || v.startsWith("fea") || v.startsWith("feb") || v.startsWith("ff") || v.startsWith("64:ff9b:");
18
+ }
19
+ /**
20
+ * Connections that refuse private addresses. The check runs when the connection is made, on the
21
+ * address actually used, so a DNS answer that changes between check and use does not help an attacker.
22
+ */
23
+ export function publicOnlyAgent(timeoutMs, allowPrivate = false) {
24
+ return new Agent({
25
+ connect: {
26
+ lookup: (hostname, opts, cb) => dns.lookup(hostname, { ...opts, all: true }, (err, addrs) => {
27
+ if (err)
28
+ return cb(err);
29
+ const list = Array.isArray(addrs) ? addrs : [{ address: addrs, family: net.isIPv6(addrs) ? 6 : 4 }];
30
+ if (!allowPrivate && list.some((a) => isPrivateAddress(a.address)))
31
+ return cb(new Error(`${hostname} resolves to a private address`));
32
+ return opts?.all ? cb(null, list) : cb(null, list[0].address, list[0].family);
33
+ }),
34
+ },
35
+ headersTimeout: timeoutMs,
36
+ bodyTimeout: timeoutMs,
37
+ });
38
+ }
39
+ /** Names that say by themselves that they are on this computer or the local network. */
40
+ export const isLocalName = (host) => host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal");
41
+ /** "host:port" the way a web address writes it. */
42
+ export const hostPort = (host, port) => `${net.isIPv6(host) ? `[${host}]` : host}:${port}`;
43
+ /**
44
+ * A web address whose host says by itself that it is this computer or the local network:
45
+ * "localhost", a ".local" name, an IP address in a private range. A name that only turns out to
46
+ * be local when it is looked up is not one: what such a name points at can change after a yes.
47
+ */
48
+ export function localTarget(raw) {
49
+ const text = String(raw ?? "").trim();
50
+ let url;
51
+ try {
52
+ // A browser takes "localhost:5173" as well.
53
+ url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(text) ? text : `http://${text}`);
54
+ }
55
+ catch {
56
+ return undefined;
57
+ }
58
+ if (url.protocol !== "http:" && url.protocol !== "https:")
59
+ return undefined;
60
+ const host = url.hostname.replace(/^\[|\]$/g, "").toLowerCase();
61
+ if (!isLocalName(host) && !(net.isIP(host) && isPrivateAddress(host)))
62
+ return undefined;
63
+ const port = Number(url.port || (url.protocol === "https:" ? 443 : 80));
64
+ return { host, port, key: hostPort(host, port) };
65
+ }
66
+ /**
67
+ * Download an address to a temporary file, byte for byte.
68
+ *
69
+ * `trusted` are origins the owner has already connected the caller to (its MCP servers): they are
70
+ * fetched as they are. Any other address is fetched only when `open` is set, and then only over
71
+ * https and never from a private or local address. Redirects are followed by the same rules.
72
+ * `headers` says what to send along to a trusted address (a server's key, for a link it gave).
73
+ */
74
+ export async function fetchToFile(o) {
75
+ const timeoutMs = o.timeoutMs ?? 120_000;
76
+ const check = (raw) => {
77
+ let url;
78
+ try {
79
+ url = new URL(raw);
80
+ }
81
+ catch {
82
+ throw new Error("not a valid URL");
83
+ }
84
+ if (url.username || url.password)
85
+ throw new Error("URLs with credentials are not fetched");
86
+ if (o.trusted.has(url.origin))
87
+ return { url, trusted: true };
88
+ const host = url.hostname.replace(/^\[|\]$/g, "");
89
+ // `open` may answer per host, with the reason when it says no.
90
+ const open = typeof o.open === "function" ? o.open(host) : o.open || `${url.host} is not one of your MCP servers, and this conversation has no network access. Ask your owner with request_access (network: true), then try again`;
91
+ if (open !== true)
92
+ throw new Error(open);
93
+ if (o.allowPrivate)
94
+ return { url, trusted: false };
95
+ if (url.protocol !== "https:")
96
+ throw new Error("only https addresses can be downloaded");
97
+ if (isLocalName(host) || (net.isIP(host) && isPrivateAddress(host)))
98
+ throw new Error("private and local addresses are not fetched");
99
+ return { url, trusted: false };
100
+ };
101
+ const guarded = publicOnlyAgent(timeoutMs, o.allowPrivate);
102
+ const signal = AbortSignal.any([AbortSignal.timeout(timeoutMs), ...(o.signal ? [o.signal] : [])]);
103
+ const file = path.join(os.tmpdir(), `pine-dl-${randomBytes(16).toString("hex")}`);
104
+ let allTrusted = true;
105
+ try {
106
+ let { url, trusted } = check(o.url);
107
+ for (let hop = 0; hop < 6; hop++) {
108
+ allTrusted &&= trusted;
109
+ // `headers` is asked for every hop, and only for a trusted origin: what a server's key is
110
+ // sent with is decided by the caller per address, never carried along a redirect.
111
+ const res = await fetch(url, { ...(trusted ? {} : { dispatcher: guarded }), redirect: "manual", headers: { ...(trusted ? o.headers?.(url) : undefined), accept: "*/*", "user-agent": "pine" }, signal });
112
+ if (res.status >= 300 && res.status < 400 && res.headers.get("location")) {
113
+ await res.body?.cancel();
114
+ ({ url, trusted } = check(new URL(res.headers.get("location"), url).href));
115
+ continue;
116
+ }
117
+ if (!res.ok) {
118
+ await res.body?.cancel();
119
+ throw new Error(`the server answered HTTP ${res.status}`);
120
+ }
121
+ // "wx": the name is new and random; an existing file or link at that name is an error, not a target.
122
+ const out = fs.openSync(file, "wx", 0o600);
123
+ const hash = createHash("sha256");
124
+ let bytes = 0;
125
+ try {
126
+ if (res.body) {
127
+ for await (const chunk of res.body) {
128
+ bytes += chunk.length;
129
+ if (bytes > o.maxBytes)
130
+ throw new Error(`larger than the limit of ${Math.round(o.maxBytes / 1024 / 1024)} MB`);
131
+ hash.update(chunk);
132
+ fs.writeSync(out, chunk);
133
+ }
134
+ }
135
+ }
136
+ finally {
137
+ fs.closeSync(out);
138
+ }
139
+ return { file, url: url.href, bytes, sha256: hash.digest("hex"), type: res.headers.get("content-type") ?? "", trusted: allTrusted };
140
+ }
141
+ throw new Error("too many redirects");
142
+ }
143
+ catch (e) {
144
+ fs.rmSync(file, { force: true });
145
+ throw e;
146
+ }
147
+ finally {
148
+ void guarded.close().catch(() => { });
149
+ }
150
+ }
package/src/pine.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ import { AgentManager } from "./agents.ts";
2
+ import { type PineConfig } from "./config.ts";
3
+ import { HttpServer } from "./http.ts";
4
+ import type { CompleteOptions } from "./router.ts";
5
+ import { SourceHost } from "./sources.ts";
6
+ import { Approvals } from "./security.ts";
7
+ import { Bus, State, TaskStore } from "./store.ts";
8
+ import { Scheduler } from "./timers.ts";
9
+ import { type Logger } from "./util.ts";
10
+ export interface Pine {
11
+ cfg: PineConfig;
12
+ bus: Bus;
13
+ state: State;
14
+ tasks: TaskStore;
15
+ agents: AgentManager;
16
+ approvals: Approvals;
17
+ sources: SourceHost;
18
+ schedules: Scheduler;
19
+ http?: HttpServer;
20
+ /** Bearer token of the control API. */
21
+ token: string;
22
+ warnings: string[];
23
+ complete(o: CompleteOptions): Promise<string>;
24
+ stop(): Promise<void>;
25
+ }
26
+ export declare function startPine(opts?: {
27
+ home?: string;
28
+ config?: PineConfig;
29
+ log?: Logger;
30
+ http?: boolean;
31
+ logFile?: string;
32
+ }): Promise<Pine>;
package/src/pine.js ADDED
@@ -0,0 +1,134 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { Agent, Pool, setGlobalDispatcher } from "undici";
5
+ import { AgentManager } from "./agents.js";
6
+ import { loadConfig } from "./config.js";
7
+ import { modelOrigins } from "./models.js";
8
+ import { HttpServer } from "./http.js";
9
+ import { Router } from "./router.js";
10
+ import { SourceHost } from "./sources.js";
11
+ import { Approvals, audit, Redactor } from "./security.js";
12
+ import { Bus, Kv, openDb, State, TaskStore } from "./store.js";
13
+ import { Scheduler } from "./timers.js";
14
+ import { createLogger, errText } from "./util.js";
15
+ /**
16
+ * pi does not time out a model stream that goes quiet after its headers. Give the model servers
17
+ * their own connection pools with header and idle timeouts; everything else keeps the defaults.
18
+ */
19
+ function installModelTimeouts(cfg) {
20
+ setGlobalDispatcher(new Agent({
21
+ factory: (origin, opts) => new Pool(origin, modelOrigins.has(String(origin)) ? { ...opts, headersTimeout: cfg.limits.modelHeadersTimeoutMs, bodyTimeout: cfg.limits.modelStreamIdleMs } : opts),
22
+ }));
23
+ }
24
+ function controlToken(cfg) {
25
+ if (cfg.http?.token)
26
+ return cfg.http.token;
27
+ const file = path.join(cfg.dataDir, "http-token");
28
+ if (fs.existsSync(file))
29
+ return fs.readFileSync(file, "utf8").trim();
30
+ const token = crypto.randomBytes(24).toString("base64url");
31
+ fs.writeFileSync(file, `${token}\n`, { mode: 0o600 });
32
+ return token;
33
+ }
34
+ export async function startPine(opts = {}) {
35
+ const cfg = opts.config ?? loadConfig(opts.home);
36
+ const redactor = new Redactor();
37
+ redactor.add(cfg.secrets);
38
+ // With a log file (the terminal UI owns the screen) nothing is written to stderr.
39
+ if (opts.logFile)
40
+ fs.mkdirSync(path.dirname(opts.logFile), { recursive: true });
41
+ const sink = opts.logFile ? (line) => fs.appendFileSync(opts.logFile, `${redactor.text(line)}\n`) : (line) => void process.stderr.write(`${redactor.text(line)}\n`);
42
+ const log = opts.log ?? createLogger(cfg.logLevel, "pine", sink);
43
+ // The daemon must not pick up the settings, extensions or MCP servers of a pi you use by hand.
44
+ process.env.PI_CODING_AGENT_DIR = path.join(cfg.dataDir, "pi");
45
+ process.env.PI_SKIP_VERSION_CHECK = "1";
46
+ process.env.PI_TELEMETRY = "0";
47
+ process.env.PI_OFFLINE ??= "1";
48
+ fs.mkdirSync(process.env.PI_CODING_AGENT_DIR, { recursive: true });
49
+ for (const dir of [cfg.home, cfg.dataDir, path.join(cfg.home, "sandbox")]) {
50
+ fs.mkdirSync(dir, { recursive: true });
51
+ if (dir !== cfg.home)
52
+ fs.chmodSync(dir, 0o700);
53
+ }
54
+ installModelTimeouts(cfg);
55
+ const db = openDb(cfg.dataDir);
56
+ const bus = new Bus(db, log.child("bus"));
57
+ const token = controlToken(cfg);
58
+ redactor.add([token]);
59
+ bus.redact = (p) => redactor.deep(p);
60
+ const state = new State(db, bus);
61
+ const kv = new Kv(db);
62
+ const tasks = new TaskStore(db);
63
+ const approvals = new Approvals(bus, log.child("approvals"), cfg.security.approvalTimeoutMs);
64
+ const agents = new AgentManager({ cfg, bus, state, kv, tasks, approvals, log: log.child("agents") });
65
+ const complete = async (o) => {
66
+ const model = agents.resolveModel(o.model ?? cfg.defaults.model ?? Object.values(cfg.agents)[0].model);
67
+ const content = [{ type: "text", text: o.prompt }, ...(o.images ?? []).map((i) => ({ type: "image", data: i.data, mimeType: i.mimeType }))];
68
+ const slot = await agents.limiter.acquire(5);
69
+ try {
70
+ const msg = await agents.models.completeSimple(model, { systemPrompt: o.system, messages: [{ role: "user", content, timestamp: Date.now() }] }, { signal: o.signal, sessionId: "pine-call" });
71
+ if (msg.stopReason === "error" || msg.stopReason === "aborted")
72
+ throw new Error(msg.errorMessage ?? `model call ${msg.stopReason}`);
73
+ return (msg.content ?? []).filter((c) => c.type === "text").map((c) => c.text).join("");
74
+ }
75
+ finally {
76
+ slot.release();
77
+ }
78
+ };
79
+ await agents.init();
80
+ // eslint-disable-next-line prefer-const
81
+ let sources;
82
+ const router = new Router({ cfg, bus, state, manager: agents, complete, log: log.child("router"), mediaRoots: () => sources.mediaRoots });
83
+ sources = new SourceHost({ cfg, bus, kv, redactor, router, log: log.child("sources"), http: Boolean(cfg.http && opts.http !== false), approvals });
84
+ agents.sources = sources;
85
+ agents.router = router;
86
+ router.start();
87
+ await sources.start();
88
+ const timers = new Scheduler(cfg, bus, kv, log.child("timers"), router);
89
+ agents.schedules = timers;
90
+ timers.start();
91
+ const pruned = bus.prune(cfg.limits.eventRetentionDays * 86_400_000);
92
+ if (pruned)
93
+ log.info(`removed ${pruned} events older than ${cfg.limits.eventRetentionDays} days`);
94
+ agents.pruneMedia(cfg.limits.eventRetentionDays * 86_400_000);
95
+ const tidy = () => void agents
96
+ .pruneConversations()
97
+ .then((n) => n && log.info(`removed ${n} conversation${n === 1 ? "" : "s"} not used for ${cfg.limits.conversationDays} days`))
98
+ .catch((e) => log.warn(`could not tidy conversations: ${errText(e)}`));
99
+ tidy();
100
+ const pruner = setInterval(() => {
101
+ bus.prune(cfg.limits.eventRetentionDays * 86_400_000);
102
+ agents.pruneMedia(cfg.limits.eventRetentionDays * 86_400_000);
103
+ tidy();
104
+ }, 6 * 3_600_000);
105
+ pruner.unref();
106
+ let http;
107
+ if (cfg.http && opts.http !== false) {
108
+ http = new HttpServer({ cfg, bus, state, tasks, manager: agents, approvals, sources, log: log.child("http"), token });
109
+ await http.start();
110
+ }
111
+ const warnings = audit(cfg);
112
+ for (const w of warnings)
113
+ log.warn(`security: ${w}`);
114
+ bus.publish("pine/started", { agents: Object.keys(cfg.agents) }, { source: "pine" });
115
+ const src = sources.list();
116
+ log.info(`pine is up: ${Object.keys(cfg.agents).length} agents, ${cfg.routes.length} routes, ${src.length} event sources (${src.filter((s) => s.running).length} running)`);
117
+ let stopped = false;
118
+ return {
119
+ cfg, bus, state, tasks, agents, approvals, sources, schedules: timers, http, token, warnings, complete,
120
+ async stop() {
121
+ if (stopped)
122
+ return;
123
+ stopped = true;
124
+ clearInterval(pruner);
125
+ timers.stop();
126
+ await sources.stop();
127
+ router.stop();
128
+ await http?.stop();
129
+ await agents.stop();
130
+ await bus.drain();
131
+ db.close();
132
+ },
133
+ };
134
+ }
@@ -0,0 +1,123 @@
1
+ import type { ReplyTarget } from "./types.ts";
2
+ export interface Program {
3
+ /** The process group. What `stop` takes. */
4
+ id: number;
5
+ /** The command line of the program, as the system shows it. */
6
+ command: string;
7
+ /** How many processes belong to it. */
8
+ processes: number;
9
+ /** TCP ports it listens on. */
10
+ ports: number[];
11
+ /** How long it has been running. */
12
+ seconds: number;
13
+ /** A command started in the background that is still being run. Its conversation is told when it ends. */
14
+ background?: boolean;
15
+ /** For such a command: the file its output goes to, in the agent's own temp folder. */
16
+ output?: string;
17
+ }
18
+ /** A command started in the background, from its start until its conversation has been told how it ended. */
19
+ export interface Background {
20
+ /** Its process group: the id of the program, as for everything else here. */
21
+ id: number;
22
+ /** The name of its files: the record in pine's home and the output in the agent's folder. */
23
+ token: string;
24
+ /** The conversation that started it ("agent:session"), which is told when it ends. */
25
+ conversation: string;
26
+ agent: string;
27
+ /** The command as the agent gave it. Shown, never run from here again. */
28
+ command: string;
29
+ /** Where its output goes. The agent's file: the daemon reads it only through the agent's sandbox. */
30
+ output: string;
31
+ started: number;
32
+ /** Where the answer of the task that started it goes. The answer about its end goes there too. */
33
+ reply?: ReplyTarget;
34
+ /** What the conversation had read from outside when it started the command, if anything. */
35
+ tainted?: string;
36
+ /** Who stopped it. The agent knows what it stopped itself, and a conversation that was reset is told nothing. */
37
+ stopped?: "owner" | "agent" | "reset";
38
+ /** Set when it has ended. With neither a code nor a signal, how it ended is not known (pine was not running). */
39
+ ended?: {
40
+ code?: number;
41
+ signal?: string;
42
+ seconds?: number;
43
+ };
44
+ }
45
+ /** How many commands one conversation may have in the background at a time. */
46
+ export declare const MAX_BACKGROUND = 8;
47
+ /** "[[days-]hours:]minutes:seconds", as ps prints how long a process has run. */
48
+ export declare function elapsed(text: string): number;
49
+ export declare class Programs {
50
+ private dir;
51
+ /** Background commands by token: those being run, and those that have ended and were not told yet. */
52
+ private jobs;
53
+ /** Those of them that an earlier daemon started: this one is not their parent and has to look. */
54
+ private adopted;
55
+ private telling;
56
+ private looking?;
57
+ private closed;
58
+ private count;
59
+ /** Called a moment after background commands of a conversation have ended: `ended` has them. */
60
+ onEnded?: (conversation: string) => void;
61
+ /** `dir` lies in pine's home, where no agent can write: an agent cannot put a group on a list. */
62
+ constructor(dir: string);
63
+ private file;
64
+ /** A background command's files in pine's home: what is known about it (json), and how it ended (exit). */
65
+ private record;
66
+ private save;
67
+ private drop;
68
+ /**
69
+ * Start a command in the background. `prefix` is the sandbox of its conversation ([] where
70
+ * there is none) and `dir` a folder of the agent's own for the output. The shell leads a
71
+ * group of its own, and the daemon notes that group itself, from what the system said when
72
+ * it started the shell. Returns at once.
73
+ */
74
+ start(o: {
75
+ conversation: string;
76
+ agent: string;
77
+ command: string;
78
+ prefix: string[];
79
+ cwd: string;
80
+ env: NodeJS.ProcessEnv;
81
+ dir: string;
82
+ reply?: ReplyTarget;
83
+ tainted?: string;
84
+ }): Background;
85
+ /** The background commands of a conversation that are still being run. */
86
+ running(conversation: string): Background[];
87
+ /** Those that have ended and that the conversation has not been told about, in the order they were started. */
88
+ ended(conversation: string): Background[];
89
+ /** The conversation has been told about these: they are forgotten. */
90
+ told(jobs: Background[]): void;
91
+ private settle;
92
+ /** The conversation has nothing to do any more: if commands of its own ended while it worked, it is told now. */
93
+ nudge(conversation: string): void;
94
+ /** Tell the conversation in a moment: what else ends until then goes into the same message. */
95
+ private remind;
96
+ /**
97
+ * After a restart: take up the background commands that the daemon before this one knew. One
98
+ * that is still there is listed again and looked at until it ends. One that ended meanwhile
99
+ * is told now. A daemon calls this once, when `onEnded` is set.
100
+ */
101
+ adopt(every?: number): void;
102
+ /** Has a command that an earlier daemon started ended? Its shell wrote the exit code before it went. */
103
+ private look;
104
+ /** A conversation got another name: what it left running and what it has in the background go with it. */
105
+ rename(from: string, to: string): void;
106
+ /** The daemon stops. What is in the background goes on, and what is known about it stays for the next start. */
107
+ close(): void;
108
+ /**
109
+ * Shell text to put in front of a command of this conversation, before its sandbox: the
110
+ * shell notes its own process group. It runs with the daemon's rights, so it is fixed text.
111
+ */
112
+ note(conversation: string): string;
113
+ private groups;
114
+ /** What this conversation's commands left running. Groups with nothing left in them are forgotten on the way. */
115
+ list(conversation: string): Program[];
116
+ /**
117
+ * Stop one of this conversation's programs: asked first, and ended a moment later if it is still there.
118
+ * `by` says who stops a background command, which decides whether its conversation is told.
119
+ */
120
+ stop(conversation: string, id: number, by?: "owner" | "agent" | "reset"): boolean;
121
+ /** Stop everything a conversation left running: it is being reset or removed. */
122
+ stopAll(conversation: string): number;
123
+ }