@pmndre/pine 0.0.0-stage → 0.22.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 (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
@@ -0,0 +1,660 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import crypto from "node:crypto";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { agentSkillsDir, conversationsDir, globalSkillsDir, mainAgentId, PINE_ROOT, unsandboxed, userFile, WORKSPACE_FILES } from "./config.js";
7
+ import { bwrapArgs, Guard, helperArgs, jailed, protectedNow, SESSIONS } from "./sandbox-linux.js";
8
+ import { truncate } from "./util.js";
9
+ /** realpath of the deepest existing ancestor, plus the part that does not exist yet. Defeats symlink escapes. */
10
+ export function realish(p) {
11
+ let cur = path.resolve(p);
12
+ const rest = [];
13
+ for (;;) {
14
+ try {
15
+ return path.join(fs.realpathSync(cur), ...rest.reverse());
16
+ }
17
+ catch {
18
+ const parent = path.dirname(cur);
19
+ if (parent === cur)
20
+ return path.resolve(p);
21
+ rest.push(path.basename(cur));
22
+ cur = parent;
23
+ }
24
+ }
25
+ }
26
+ export const isInside = (root, p) => p === root || p.startsWith(root.endsWith(path.sep) ? root : root + path.sep);
27
+ /** Files that steer an agent or the daemon. A run that has seen outside content must not change them. */
28
+ const INSTRUCTION_FILES = ["AGENTS.md", "AGENTS.override.md", "CLAUDE.md", "SYSTEM.md"];
29
+ const INSTRUCTION_DIRS = [".pi", ".agents", ".git/hooks"];
30
+ export function rootsFor(cfg, agent) {
31
+ const sandboxHome = path.join(cfg.home, "sandbox", agent.id);
32
+ fs.mkdirSync(path.join(sandboxHome, "tmp"), { recursive: true });
33
+ const workspace = realish(agent.workspace);
34
+ const home = realish(cfg.home);
35
+ const tmp = agent.sandbox.sharedTmp ? [...new Set([realish(os.tmpdir()), "/private/tmp"])] : [];
36
+ // pine's manual is readable by every agent, so it can explain how its owner changes the setup.
37
+ // The one file of pine's home that an agent may touch: what is known about the owner, and only for the main agent.
38
+ const user = path.join(home, path.basename(userFile(cfg)));
39
+ const keepsUser = agent.id === mainAgentId(cfg) ? [user] : [];
40
+ // Skills are read, never written, by the agent they are for: its own, its conversations', and those for all agents.
41
+ const skills = [agentSkillsDir(agent), conversationsDir(agent), globalSkillsDir(cfg), ...cfg.skills, ...agent.skills].map(realish);
42
+ const ownedRead = [...new Set([workspace, realish(sandboxHome), realish(path.join(PINE_ROOT, "docs")), ...skills, ...agent.sandbox.read.map(realish), ...keepsUser])];
43
+ const ownedWrite = [...new Set([workspace, realish(sandboxHome), ...agent.sandbox.write.map(realish), ...keepsUser])];
44
+ return {
45
+ workspace,
46
+ cwd: workspace,
47
+ sandboxHome: realish(sandboxHome),
48
+ home,
49
+ read: [...ownedRead, ...tmp],
50
+ write: [...ownedWrite, ...tmp],
51
+ ownedRead,
52
+ ownedWrite,
53
+ userFile: user,
54
+ secrets: [path.join(home, ".env"), path.join(home, "auth.json"), path.join(home, "models.json"), path.join(home, "pine.json"), realish(cfg.dataDir)],
55
+ others: Object.values(cfg.agents)
56
+ .filter((a) => a.id !== agent.id)
57
+ .map((a) => realish(a.workspace))
58
+ .filter((w) => ![...ownedRead, ...ownedWrite].some((own) => isInside(own, w) || isInside(w, own))),
59
+ };
60
+ }
61
+ export const isOpen = (v) => v === "open" || v === "open-restricted";
62
+ /** pine's own program files. Never writable by an agent, in any mode. */
63
+ const PINE_CODE = realish(PINE_ROOT);
64
+ /** Why a file tool may not touch `target`, or undefined when it may. */
65
+ /**
66
+ * "~" in a path a model gave a file tool: the owner's home folder, in every scope. pi's read,
67
+ * write and edit take it that way, so the check and the other file tools must as well, or a
68
+ * path would be judged as one file and opened as another. (An agent in the workspace scope
69
+ * reaches its own private home by its full path.)
70
+ */
71
+ export function tilde(target) {
72
+ return target === "~" ? os.homedir() : target.startsWith("~/") ? path.join(os.homedir(), target.slice(2)) : target;
73
+ }
74
+ export function checkPath(roots, kind, given, cwd, variant) {
75
+ const target = tilde(given);
76
+ const p = realish(path.isAbsolute(target) ? target : path.join(cwd, target));
77
+ const restricted = variant === true || variant === "restricted" || variant === "open-restricted";
78
+ if (roots.secrets.some((s) => isInside(s, p)))
79
+ return `${target} is not accessible to agents`;
80
+ if (isOpen(variant)) {
81
+ // Said as what it is: a model that reads "pine's own configuration" does not think of the tools that are for this.
82
+ if (roots.others.some((o) => isInside(o, p)))
83
+ return `${target} is in another agent's workspace, which is closed to you. What that agent is told is read with the agents tool (id) and changed with update_agent (instructions, soul), by the main agent`;
84
+ if (isInside(roots.home, p) && !(kind === "read" ? roots.ownedRead : roots.ownedWrite).some((r) => isInside(r, p)))
85
+ return `${target} is part of pine's own configuration, which stays closed in every mode`;
86
+ if (kind === "write" && isInside(PINE_CODE, p))
87
+ return `${target} is part of pine's own code, which agents cannot change`;
88
+ if (kind === "write" && restricted)
89
+ return ownRules(roots, target, p);
90
+ return undefined;
91
+ }
92
+ if (roots.others.some((o) => isInside(o, p)))
93
+ return `${target} belongs to another agent; ask that agent instead`;
94
+ // Inside pine's home only the agent's own folders count, even if a shared temp root would cover the path.
95
+ const inHome = isInside(roots.home, p);
96
+ const allowed = kind === "read" ? (inHome ? roots.ownedRead : roots.read) : inHome ? roots.ownedWrite : roots.write;
97
+ if (!allowed.some((r) => isInside(r, p)))
98
+ return `${target} is outside the paths this agent may ${kind} (workspace: ${roots.workspace}). If you need it, call request_access with the path and the reason; your owner decides.`;
99
+ return kind === "write" && restricted ? ownRules(roots, target, p) : undefined;
100
+ }
101
+ /** Whether the owner can give a conversation this path at all: not pine's own files, not another agent's. What `request_access` refuses. */
102
+ export function grantable(roots, kind, p) {
103
+ const about = (root) => isInside(root, p) || isInside(p, root);
104
+ if (roots.secrets.some(about) || about(roots.home))
105
+ return false;
106
+ if (kind === "write" && about(PINE_CODE))
107
+ return false;
108
+ return !roots.others.some(about);
109
+ }
110
+ /**
111
+ * The path a file tool is refused only because it lies outside what the agent was given: the
112
+ * owner can be asked for exactly that. Undefined when the path is fine, or closed for another reason.
113
+ */
114
+ export function outsidePath(roots, kind, given, cwd, variant) {
115
+ if (isOpen(variant))
116
+ return undefined;
117
+ const target = tilde(given);
118
+ const p = realish(path.isAbsolute(target) ? target : path.join(cwd, target));
119
+ if (!grantable(roots, kind, p))
120
+ return undefined;
121
+ return (kind === "read" ? roots.read : roots.write).some((r) => isInside(r, p)) ? undefined : p;
122
+ }
123
+ /**
124
+ * Whether the sandbox of an agent that works in its own folders refuses its shell this path: it
125
+ * reads everything except the owner's home, and writes only what it was given. (The file tools
126
+ * are judged by `checkPath`, which is stricter about reading.)
127
+ */
128
+ export function shellRefuses(roots, kind, p) {
129
+ if (kind === "write")
130
+ return !roots.write.some((r) => isInside(r, p));
131
+ return isInside(realish(os.homedir()), p) && !roots.read.some((r) => isInside(r, p));
132
+ }
133
+ /**
134
+ * What to ask the owner for when a command needs `p`. On Linux a path that does not exist yet
135
+ * cannot be mounted, so a file that is still to be made is asked for as the folder it goes into.
136
+ */
137
+ export function grantPath(p) {
138
+ if (sandboxKind() !== "linux")
139
+ return p;
140
+ let cur = p;
141
+ while (!present(cur) && path.dirname(cur) !== cur)
142
+ cur = path.dirname(cur);
143
+ return cur;
144
+ }
145
+ const present = (p) => {
146
+ try {
147
+ fs.lstatSync(p);
148
+ return true;
149
+ }
150
+ catch {
151
+ return false;
152
+ }
153
+ };
154
+ /** What a run that has handled outside content may not write in the agent's own folders, however far it reaches otherwise. */
155
+ function ownRules(roots, target, p) {
156
+ // Its own files, when the owner has said so for this conversation.
157
+ if (roots.ownOpen && ownFiles(roots).includes(p))
158
+ return undefined;
159
+ const mine = [roots.workspace, ...(roots.folder !== undefined ? [roots.folder] : [])];
160
+ if (mine.some((r) => isGitRunPath(r, p)))
161
+ return `${target} is part of a repository's hooks or configuration, which make git run programs, and cannot be changed in a run that has handled outside content`;
162
+ if (mine.some((r) => isInstructionPath(r, p)) || isOwnFile(roots, p))
163
+ return `${target} holds agent instructions and cannot be changed in a run that has handled outside content`;
164
+ return undefined;
165
+ }
166
+ export function isInstructionPath(workspace, p) {
167
+ if (!isInside(workspace, p))
168
+ return false;
169
+ const rel = path.relative(workspace, p);
170
+ return INSTRUCTION_FILES.includes(path.basename(p)) || INSTRUCTION_DIRS.some((d) => rel === d || rel.startsWith(d + path.sep));
171
+ }
172
+ /** Whether a path is one of the files that are read into the agent's prompt from its workspace, or the owner's file in pine's home. */
173
+ export function isOwnFile(roots, p) {
174
+ return p === roots.userFile || (path.dirname(p) === roots.workspace && WORKSPACE_FILES.includes(path.basename(p)));
175
+ }
176
+ /** The files an agent keeps itself: its memory and instructions at the top of its workspace, and for the main agent what is known about the owner. */
177
+ export function ownFiles(roots) {
178
+ return [...WORKSPACE_FILES.map((f) => path.join(roots.workspace, f)), ...(roots.ownedWrite.includes(roots.userFile) ? [roots.userFile] : [])];
179
+ }
180
+ /** The own file a path given to a file tool means, if it means one. */
181
+ export function ownFileOf(roots, given, cwd) {
182
+ const target = tilde(given);
183
+ const p = realish(path.isAbsolute(target) ? target : path.join(cwd, target));
184
+ return ownFiles(roots).includes(p) ? p : undefined;
185
+ }
186
+ /** Whether a path in one of the agent's folders is a repository's hooks or configuration, or the repository's own folder. */
187
+ export function isGitRunPath(root, p) {
188
+ return isInside(root, p) && GIT_RUNS.test(`/${path.relative(root, p)}`);
189
+ }
190
+ /**
191
+ * The parts of a repository that make git run programs: its hooks and its configuration (which
192
+ * can name a hooks folder, a pager, a file system monitor, an ssh command), also of submodules
193
+ * and of repositories further down. What is put there runs with the owner's rights the next
194
+ * time they use git, so a run that has handled outside content cannot change them, nor move
195
+ * the repository's folder aside to put another in its place.
196
+ */
197
+ const GIT_RUNS = /\/\.git(\/(modules\/.+\/)?(hooks(\/.*)?|config))?$/;
198
+ const GIT_RUNS_PROFILE = String.raw `(.*/)?\.git(/(modules/.+/)?(hooks(/.*)?|config))?$`;
199
+ const q = (s) => `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
200
+ const rx = (s) => s.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
201
+ const subpaths = (list) => list.map((p) => `(subpath ${q(p)})`).join(" ");
202
+ /**
203
+ * macOS sandbox profile for everything an agent does on the file system: its shell commands and
204
+ * its file tools. Nothing is allowed unless a rule here allows it; for file rules the last match wins.
205
+ *
206
+ * Allowed: running programs, reading outside the user's home, writing in the agent's own folders
207
+ * and temp. Not allowed: the user's home, pine's home (secrets, configuration, other agents),
208
+ * other processes (signals, their arguments and environment), launching apps, AppleScript,
209
+ * the keychain, the clipboard, and the network unless the agent's configuration turns it on.
210
+ */
211
+ export function sandboxProfile(_cfg, agent, roots, variant, network = false, tag) {
212
+ const userHome = realish(os.homedir());
213
+ // The system reports every refusal in its log, with this text: how pine finds out what a
214
+ // command was refused (src/access.ts). It changes nothing about what is refused.
215
+ const said = tag ? ` (with message ${q(tag)})` : "";
216
+ const restricted = variant === true || variant === "restricted";
217
+ // What is read into the prompt cannot be rewritten by a run that outside content may steer.
218
+ const frozen = () => {
219
+ const out = [`(deny file-write* ${[roots.userFile, ...WORKSPACE_FILES.map((f) => path.join(roots.workspace, f))].map((f) => `(literal ${q(f)})`).join(" ")}${said})`];
220
+ for (const dir of [roots.workspace, ...(roots.folder ? [roots.folder] : [])]) {
221
+ out.push(`(deny file-write* (regex #"^${rx(dir)}/(.*/)?(${INSTRUCTION_FILES.map(rx).join("|")})$") (regex #"^${rx(dir)}/${GIT_RUNS_PROFILE}") ${subpaths(INSTRUCTION_DIRS.map((d) => path.join(dir, d)))}${said})`);
222
+ }
223
+ // The owner let this conversation keep its own files: exactly those, by name, and nothing
224
+ // that was not the agent's to write before. The last rule that matches a file decides.
225
+ if (roots.ownOpen)
226
+ out.push(`(allow file-write* ${ownFiles(roots).map((f) => `(literal ${q(f)})`).join(" ")})`);
227
+ return out;
228
+ };
229
+ const lines = [
230
+ "(version 1)",
231
+ `(deny default${said})`,
232
+ "(allow process-exec)",
233
+ "(allow process-fork)",
234
+ "(allow signal (target same-sandbox))",
235
+ "(allow process-info* (target same-sandbox))",
236
+ "(allow sysctl-read)",
237
+ "(allow ipc-posix-shm-read*)",
238
+ "(allow ipc-posix-sem)",
239
+ "(allow pseudo-tty)",
240
+ '(allow mach-lookup (global-name "com.apple.system.opendirectoryd.libinfo") (global-name "com.apple.system.DirectoryService.libinfo.v1") (global-name "com.apple.system.opendirectoryd.membership") (global-name "com.apple.system.notification_center") (global-name "com.apple.system.logger") (global-name "com.apple.logd") (global-name "com.apple.bsd.dirhelper"))',
241
+ // Computing on the graphics chip and the neural engine: what the system's own recognition of
242
+ // text and pictures runs on. Devices that compute, and the service that loads a model for
243
+ // them, which is handed the model's files from the agent's own folders. Neither reaches a
244
+ // file, an address or another program. (Found by leaving each out: without one of them,
245
+ // reading the text of a scanned page fails with an error that names nothing.)
246
+ '(allow iokit-open (iokit-user-client-class "IOSurfaceRootUserClient") (iokit-user-client-class "IOSurfaceAcceleratorClient") (iokit-user-client-class "AGXDeviceUserClient") (iokit-user-client-class "H1xANELoadBalancerDirectPathClient"))',
247
+ '(allow mach-lookup (global-name "com.apple.appleneuralengine"))',
248
+ `(allow file-issue-extension ${subpaths(roots.ownedWrite)})`,
249
+ '(allow file-ioctl (regex #"^/dev/tty") (literal "/dev/null"))',
250
+ "(allow file-read*)",
251
+ `(allow file-write* ${subpaths(roots.write)} (literal "/dev/null") (literal "/dev/zero") (literal "/dev/dtracehelper") (regex #"^/dev/tty") (regex #"^/dev/fd/"))`,
252
+ `(deny file-read* (subpath ${q(userHome)})${said})`,
253
+ `(allow file-read-metadata (subpath ${q(userHome)}))`,
254
+ `(allow file-read* ${subpaths(roots.read)})`,
255
+ // pine's home is closed wherever it lies, except for this agent's own folders.
256
+ `(deny file-read* file-write* (subpath ${q(roots.home)})${said})`,
257
+ `(allow file-read-metadata (subpath ${q(roots.home)}))`,
258
+ `(allow file-read* ${subpaths(roots.ownedRead)})`,
259
+ `(allow file-write* ${subpaths(roots.ownedWrite)})`,
260
+ `(deny file-read* file-write* ${subpaths([...roots.secrets, ...roots.others])}${said})`,
261
+ ];
262
+ if (restricted)
263
+ lines.push(...frozen());
264
+ if (agent.sandbox.network || network) {
265
+ // The network is addresses. A socket file is another program on this machine (a terminal
266
+ // multiplexer, an ssh agent, an editor's helper: some run commands for whoever connects),
267
+ // and stays closed. Two exceptions: the system's name lookup, and socket files in the
268
+ // agent's own folders, which are its own programs talking to each other. Shared temp is
269
+ // not one of those folders: that is where the other programs' sockets lie.
270
+ const temp = [realish(os.tmpdir()), "/private/tmp"];
271
+ lines.push('(allow network-outbound (remote ip "*:*"))', '(allow network-inbound (local ip "*:*"))', '(allow network-bind (local ip "*:*"))', '(allow network-outbound (literal "/private/var/run/mDNSResponder"))', `(allow network* ${subpaths(roots.write.filter((w) => !temp.includes(w)))})`, "(allow system-socket)", '(allow mach-lookup (global-name "com.apple.trustd.agent") (global-name "com.apple.trustd") (global-name "com.apple.SystemConfiguration.configd") (global-name "com.apple.SystemConfiguration.DNSConfiguration") (global-name "com.apple.dnssd.service") (global-name "com.apple.networkd") (global-name "com.apple.symptomsd"))');
272
+ }
273
+ return `${lines.join("\n")}\n`;
274
+ }
275
+ /** Where a system program lies on this machine: the same few folders on macOS and Linux, never the agent's PATH. */
276
+ export function bin(name) {
277
+ return ["/bin", "/usr/bin", "/usr/local/bin", "/opt/homebrew/bin"].map((d) => path.join(d, name)).find((f) => fs.existsSync(f)) ?? name;
278
+ }
279
+ let kind;
280
+ let bwrap = "";
281
+ let whyNot = "";
282
+ let bwrapSaid = "";
283
+ let userNamespacesRestricted = false;
284
+ /**
285
+ * The rights a container has to be started with for a sandbox to work inside it: to create
286
+ * namespaces, to give a sandbox without network its loopback interface, and past Docker's own
287
+ * system call filter and AppArmor profile, which forbid the mounts. An ordinary user in the
288
+ * container needs one more, to mount the sandbox's own /proc. (Each was tried by leaving it out.)
289
+ */
290
+ export const containerFlags = (root = process.getuid?.() === 0) => `--cap-add SYS_ADMIN --cap-add NET_ADMIN --security-opt seccomp=unconfined --security-opt apparmor=unconfined${root ? "" : " --security-opt systempaths=unconfined"}`;
291
+ /** Whether pine runs inside a container (Docker, Podman, Kubernetes). */
292
+ export function inContainer() {
293
+ const reads = (file) => {
294
+ try {
295
+ return fs.readFileSync(file, "utf8");
296
+ }
297
+ catch {
298
+ return "";
299
+ }
300
+ };
301
+ return fs.existsSync("/.dockerenv") || fs.existsSync("/run/.containerenv") || /docker|containerd|kubepods|lxc/.test(reads("/proc/1/cgroup"));
302
+ }
303
+ /**
304
+ * Which sandbox this machine has: Apple's sandbox-exec on macOS, bubblewrap on Linux. On Linux
305
+ * it is tried once, because bubblewrap can be installed and still not be allowed to work (a
306
+ * system that has switched off user namespaces for ordinary users, some containers).
307
+ */
308
+ export function sandboxKind() {
309
+ if (kind !== undefined)
310
+ return kind ?? undefined;
311
+ kind = null;
312
+ if (process.platform === "darwin") {
313
+ if (fs.existsSync("/usr/bin/sandbox-exec"))
314
+ kind = "macos";
315
+ else
316
+ whyNot = "sandbox-exec is missing";
317
+ }
318
+ else if (process.platform === "linux") {
319
+ bwrap = [...(process.env.PATH ?? "").split(":").filter((d) => path.isAbsolute(d)), "/usr/bin", "/bin", "/usr/local/bin"].map((d) => path.join(d, "bwrap")).find((f) => fs.existsSync(f)) ?? "";
320
+ if (!bwrap)
321
+ whyNot = 'bubblewrap is not installed (the program is bwrap). Run "pine init": it installs it';
322
+ else {
323
+ try {
324
+ const probe = jailed(bwrap, [...helperArgs([]), bin("true")], false);
325
+ execFileSync(probe[0], probe.slice(1), { stdio: ["ignore", "ignore", "pipe"], timeout: 10_000 });
326
+ kind = "linux";
327
+ }
328
+ catch (e) {
329
+ // What bubblewrap itself said, not the command line it was given.
330
+ const said = String(e.stderr ?? "").trim().split("\n")[0] || (e instanceof Error ? e.message.split("\n")[0].slice(0, 120) : String(e));
331
+ let apparmor = false;
332
+ try {
333
+ apparmor = fs.readFileSync("/proc/sys/kernel/apparmor_restrict_unprivileged_userns", "utf8").trim() === "1";
334
+ }
335
+ catch { }
336
+ bwrapSaid = said;
337
+ userNamespacesRestricted = apparmor;
338
+ const why = inContainer()
339
+ ? `This is a container that was started without the rights for one. To have safe mode in it, start it with: docker run ${containerFlags()} ...`
340
+ : apparmor
341
+ ? 'AppArmor keeps it from creating user namespaces. Run "pine init": it adds the rule that allows it'
342
+ : "Ordinary users may not create user namespaces here (a system that has switched them off)";
343
+ whyNot = `bubblewrap is installed (${bwrap}) but cannot make a sandbox here ("${said}"). ${why}`;
344
+ }
345
+ }
346
+ }
347
+ else
348
+ whyNot = `no sandbox is implemented for ${process.platform}`;
349
+ return kind ?? undefined;
350
+ }
351
+ /**
352
+ * What the try on Linux found, for setting the sandbox up (src/sandbox-setup.ts): where bwrap
353
+ * is, whether it could make a sandbox, what it said when not, and whether AppArmor is why.
354
+ */
355
+ export function sandboxFound() {
356
+ const works = sandboxKind() === "linux";
357
+ return { bwrap, works, said: bwrapSaid, apparmor: userNamespacesRestricted };
358
+ }
359
+ /** Look again: something that was missing may have been installed since. */
360
+ export function sandboxRecheck() {
361
+ kind = undefined;
362
+ bwrap = whyNot = bwrapSaid = "";
363
+ userNamespacesRestricted = false;
364
+ }
365
+ export const sandboxAvailable = () => sandboxKind() !== undefined;
366
+ /**
367
+ * The level an agent works at. "safe" needs a sandbox. On a machine that has none (a container,
368
+ * usually, which is then the wall around all of pine), an agent whose mode nobody chose works
369
+ * in "auto" instead. One that was set to "safe" stays there and gets no shell: what somebody
370
+ * asked for is not widened silently.
371
+ */
372
+ export function levelOf(agent) {
373
+ return agent.level === "safe" && !agent.modeSet && !sandboxAvailable() ? "auto" : agent.level;
374
+ }
375
+ /** Why this machine has no sandbox, in words for the owner. */
376
+ export const sandboxMissing = () => (sandboxKind() ? "" : whyNot);
377
+ /** What a run that has handled outside content must not change, as the Linux sandbox needs it said. */
378
+ const protectedOf = (roots) => ({
379
+ roots: [roots.workspace, ...(roots.folder ? [roots.folder] : [])],
380
+ files: [roots.userFile, ...WORKSPACE_FILES.map((f) => path.join(roots.workspace, f))],
381
+ names: INSTRUCTION_FILES,
382
+ dirs: INSTRUCTION_DIRS.filter((d) => !d.includes("/")),
383
+ open: roots.ownOpen ? ownFiles(roots) : [],
384
+ });
385
+ /**
386
+ * What to put in front of a command so that it runs with an agent's limits: the same rules on
387
+ * both systems, said to Apple's sandbox as a profile and to bubblewrap as mounts. Made anew for
388
+ * every command, because on Linux what exists at that moment is part of it.
389
+ */
390
+ export function sandboxArgv(cfg, agent, roots, variant, network = false, tag) {
391
+ if (sandboxKind() !== "linux")
392
+ return ["/usr/bin/sandbox-exec", "-p", sandboxProfile(cfg, agent, roots, variant, network, tag)];
393
+ const v = variant === true ? "restricted" : variant === false ? "normal" : variant;
394
+ const net = agent.sandbox.network || network;
395
+ // Sockets between programs go with the network, as on macOS.
396
+ return jailed(bwrap, bwrapArgs({
397
+ userHome: realish(os.homedir()),
398
+ pineHome: roots.home,
399
+ pineCode: PINE_CODE,
400
+ // A folder that is gone cannot be mounted, and one missing mount would fail every command.
401
+ read: roots.read.filter(present),
402
+ write: roots.write.filter(present),
403
+ ownedRead: roots.ownedRead,
404
+ ownedWrite: roots.ownedWrite,
405
+ closed: [...roots.secrets, ...roots.others, ...SESSIONS],
406
+ network: net,
407
+ variant: v,
408
+ frozen: v === "restricted" ? protectedNow(protectedOf(roots)) : undefined,
409
+ }), net);
410
+ }
411
+ /**
412
+ * How pine reads what the macOS sandbox refused (src/access.ts): the system's log, for reports
413
+ * that carry a text of pine's, and a refusal pine makes itself to know that it has read up to
414
+ * now. Linux reports nothing of the kind.
415
+ */
416
+ export function denialTools() {
417
+ const mac = () => sandboxKind() === "macos" && fs.existsSync("/usr/bin/log");
418
+ return {
419
+ stream: (needle) => (mac() ? ["/usr/bin/log", "stream", "--style", "ndjson", "--predicate", `eventMessage CONTAINS "${needle.replace(/[^\w:-]/g, "")}"`] : undefined),
420
+ mark: (tag) => (mac() ? ["/usr/bin/sandbox-exec", "-p", `(version 1)(allow default)(deny file-read-data (literal "/private/etc/hosts") (with message ${q(tag)}))`, "/bin/cat", "/private/etc/hosts"] : undefined),
421
+ };
422
+ }
423
+ /**
424
+ * On Linux, mounts cannot forbid making a file of a protected name. Take this before a command
425
+ * in the restricted variant and call `restore` after it: what the command made although it may
426
+ * not is removed again. On macOS the profile forbids it outright and there is nothing to do.
427
+ */
428
+ export function sandboxGuard(roots, variant) {
429
+ return sandboxKind() === "linux" && (variant === true || variant === "restricted") ? new Guard(protectedOf(roots)) : undefined;
430
+ }
431
+ /**
432
+ * What to put in front of a helper that works on things from anywhere (git looking at a folder,
433
+ * a picture converter): it may read, write only in `write`, and has no network. Undefined where
434
+ * there is no sandbox.
435
+ */
436
+ export function helperArgv(write = []) {
437
+ const k = sandboxKind();
438
+ if (k === "linux")
439
+ return jailed(bwrap, helperArgs(write), false);
440
+ if (k === "macos")
441
+ return ["/usr/bin/sandbox-exec", "-p", `(version 1)(allow default)(deny network*)(deny file-write*)(allow file-write* ${subpaths(write)} (literal "/dev/null"))`];
442
+ return undefined;
443
+ }
444
+ /** Names of environment variables that look like they hold a credential. The ssh agent's socket is an address, not one. */
445
+ const SECRET_NAME = /KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH/i;
446
+ const secretName = (k) => SECRET_NAME.test(k) && k !== "SSH_AUTH_SOCK";
447
+ /**
448
+ * Environment for an agent's shell: nothing from the daemon except what a shell needs, and a
449
+ * home of its own. With the whole account (`wide`) it is the owner's own home and environment,
450
+ * so that git, ssh, npm and the owner's toolchains behave as in their terminal; what looks like
451
+ * a credential by its name is still left out, and so is what belongs to the daemon.
452
+ */
453
+ export function shellEnv(agent, roots, sessionEnv, wide = false) {
454
+ const keep = ["PATH", "LANG", "LC_ALL", "LC_CTYPE", "TERM", "TZ", "USER", "LOGNAME", "SHELL"];
455
+ const env = {};
456
+ if (wide) {
457
+ for (const [k, v] of Object.entries(process.env))
458
+ if (v !== undefined && !secretName(k) && !/^(PI|PINE)_/.test(k))
459
+ env[k] = v;
460
+ for (const [k, v] of Object.entries(sessionEnv))
461
+ if (k.startsWith("PI_") && !secretName(k))
462
+ env[k] = v;
463
+ env.HOME = os.homedir();
464
+ env.PINE_AGENT = agent.id;
465
+ return { ...env, ...agent.sandbox.env };
466
+ }
467
+ for (const k of keep)
468
+ if (process.env[k] !== undefined)
469
+ env[k] = process.env[k];
470
+ for (const [k, v] of Object.entries(sessionEnv))
471
+ if (k.startsWith("PI_") && !/KEY|TOKEN|SECRET|AUTH/i.test(k))
472
+ env[k] = v;
473
+ env.HOME = roots.sandboxHome;
474
+ env.TMPDIR = path.join(roots.sandboxHome, "tmp");
475
+ env.GIT_CONFIG_GLOBAL = path.join(roots.sandboxHome, ".gitconfig");
476
+ if (process.platform === "darwin") {
477
+ // Apple's libraries ask the system for the user's home, not the environment. Told this, they
478
+ // take the agent's, and their caches and settings land where it may write.
479
+ env.CFFIXED_USER_HOME = roots.sandboxHome;
480
+ // The compilers keep built modules in a folder of the owner's, which the agent reads and
481
+ // cannot write: a program that needs a module nobody has built yet would not compile.
482
+ env.CLANG_MODULE_CACHE_PATH = path.join(roots.sandboxHome, ".cache", "clang", "ModuleCache");
483
+ }
484
+ env.PINE_AGENT = agent.id;
485
+ return { ...env, ...agent.sandbox.env };
486
+ }
487
+ export const shq = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
488
+ /** Glob with `*` only, anchored. */
489
+ export function globMatch(pattern, value) {
490
+ return new RegExp(`^${pattern.split("*").map((s) => s.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join("[\\s\\S]*")}$`).test(value);
491
+ }
492
+ /** "tool" or "tool:argument-glob". The argument is the command, topic, agent or path the call is about. */
493
+ export function matchesToolPattern(patterns, tool, subject) {
494
+ return patterns.some((pat) => {
495
+ const i = pat.indexOf(":");
496
+ return i < 0 ? globMatch(pat, tool) : globMatch(pat.slice(0, i), tool) && globMatch(pat.slice(i + 1), subject);
497
+ });
498
+ }
499
+ /** The part of a tool call a person needs to see to judge it. */
500
+ export function toolSubject(tool, input) {
501
+ if (!input || typeof input !== "object")
502
+ return "";
503
+ const v = tool === "download" ? input.url : tool === "send" ? input.source : (input.command ?? input.topic ?? input.agent ?? input.path ?? input.url ?? input.key ?? input.query ?? input.app);
504
+ return typeof v === "string" ? v : "";
505
+ }
506
+ /** Human-in-the-loop gate. Requests are events; anything that can reach the owner may answer them. */
507
+ export class Approvals {
508
+ bus;
509
+ log;
510
+ timeoutMs;
511
+ open = new Map();
512
+ constructor(bus, log, timeoutMs) {
513
+ this.bus = bus;
514
+ this.log = log;
515
+ this.timeoutMs = timeoutMs;
516
+ }
517
+ request(r, signal) {
518
+ const req = { ...r, summary: truncate(r.summary, 1500), id: crypto.randomBytes(4).toString("hex"), expires: Date.now() + this.timeoutMs };
519
+ return new Promise((resolve) => {
520
+ const finish = (allow, by, always = false, values) => {
521
+ const entry = this.open.get(req.id);
522
+ if (!entry)
523
+ return;
524
+ clearTimeout(entry.timer);
525
+ this.open.delete(req.id);
526
+ const remembered = allow && always && req.remember !== undefined;
527
+ // What the owner typed goes to whoever asked, and nowhere else: not into this event.
528
+ this.bus.publish("approval/decided", { id: req.id, allow, by, agent: req.agent, tool: req.tool, always: remembered || undefined, remember: remembered ? req.remember : undefined }, { source: "approvals" });
529
+ resolve({ allow, by, always: remembered, values: allow ? values : undefined });
530
+ };
531
+ const timer = setTimeout(() => finish(false, "timeout"), this.timeoutMs);
532
+ timer.unref?.();
533
+ this.open.set(req.id, { req, resolve: ({ allow, by, always, values }) => finish(allow, by, always, values), timer });
534
+ signal?.addEventListener("abort", () => finish(false, "aborted"), { once: true });
535
+ this.log.info(`approval ${req.id} requested: ${req.agent} wants ${req.tool} (${req.why})`);
536
+ this.bus.publish("approval/requested", req, { source: "approvals" });
537
+ });
538
+ }
539
+ /** The fields of an open request that a yes has to come with and that `values` does not have. */
540
+ missing(id, values) {
541
+ return (this.open.get(id)?.req.inputs ?? []).filter((i) => !String(values?.[i.name] ?? "").trim()).map((i) => i.name);
542
+ }
543
+ /** Returns false when the id is unknown or already answered, or when a yes lacks what the request asks the owner to type. */
544
+ decide(id, allow, by, always = false, values) {
545
+ const entry = this.open.get(id);
546
+ if (!entry)
547
+ return false;
548
+ if (allow && this.missing(id, values).length)
549
+ return false;
550
+ const wanted = new Set((entry.req.inputs ?? []).map((i) => i.name));
551
+ entry.resolve({ allow, by, always, values: values ? Object.fromEntries(Object.entries(values).filter(([k]) => wanted.has(k)).map(([k, v]) => [k, String(v).trim()])) : undefined });
552
+ return true;
553
+ }
554
+ pending() {
555
+ return [...this.open.values()].map((e) => e.req);
556
+ }
557
+ denyAll(by) {
558
+ for (const id of [...this.open.keys()])
559
+ this.decide(id, false, by);
560
+ }
561
+ }
562
+ /** Replaces known secret values in text that leaves the daemon. */
563
+ export class Redactor {
564
+ secrets = [];
565
+ add(values) {
566
+ for (const v of values)
567
+ if (v && v.length >= 8 && !this.secrets.includes(v))
568
+ this.secrets.push(v);
569
+ this.secrets.sort((a, b) => b.length - a.length);
570
+ }
571
+ text(s) {
572
+ for (const secret of this.secrets)
573
+ if (s.includes(secret))
574
+ s = s.split(secret).join("[redacted]");
575
+ return s;
576
+ }
577
+ deep(v) {
578
+ if (!this.secrets.length)
579
+ return v;
580
+ if (typeof v === "string")
581
+ return this.text(v);
582
+ if (Array.isArray(v))
583
+ return v.map((x) => this.deep(x));
584
+ if (v && typeof v === "object")
585
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, this.deep(x)]));
586
+ return v;
587
+ }
588
+ }
589
+ export const timingSafeEqual = (a, b) => {
590
+ const ha = crypto.createHash("sha256").update(a).digest();
591
+ const hb = crypto.createHash("sha256").update(b).digest();
592
+ return crypto.timingSafeEqual(ha, hb);
593
+ };
594
+ /** Things about a configuration that weaken its defences. Shown by `pine check` and at startup. */
595
+ export function audit(cfg) {
596
+ const out = [];
597
+ const mode = (p) => {
598
+ try {
599
+ return fs.statSync(p).mode & 0o777;
600
+ }
601
+ catch {
602
+ return undefined;
603
+ }
604
+ };
605
+ for (const f of [".env", "auth.json", "models.json", "pine.json"]) {
606
+ const m = mode(path.join(cfg.home, f));
607
+ if (m !== undefined && m & 0o077)
608
+ out.push(`${f} is readable by other users (mode ${m.toString(8)}); run: chmod 600 ${path.join(cfg.home, f)}`);
609
+ }
610
+ if (!sandboxAvailable())
611
+ out.push(`no sandbox on this machine: ${sandboxMissing()}. An agent in auto or bypass mode works as everywhere, with your rights. An agent set to safe mode gets no shell, runs that events from outside start get none either, and command sources do not run`);
612
+ const homeMode = mode(cfg.home);
613
+ if (homeMode !== undefined && homeMode & 0o077)
614
+ out.push(`pine's home is open to other users (mode ${homeMode.toString(8)}); run: chmod 700 ${cfg.home}`);
615
+ for (const a of Object.values(cfg.agents)) {
616
+ const tools = a.tools ?? ["read", "bash", "edit", "write"];
617
+ const level = levelOf(a);
618
+ if (level !== a.level)
619
+ out.push(`agent ${a.id}: works in auto mode, with your rights and no sandbox, because this machine has no sandbox and nobody chose its mode. Set its mode to say what you want`);
620
+ if (!unsandboxed(level) && a.sandbox.network && tools.includes("bash"))
621
+ out.push(`agent ${a.id}: shell has network access; a prompt injection could send workspace files anywhere (approval is required once the session has seen outside content)`);
622
+ if (level === "bypass")
623
+ out.push(`agent ${a.id}: bypass mode. It never asks, and its shell reaches your whole account and the network${cfg.security.bypassWhenTainted ? ", even after it has read outside content (security.bypassWhenTainted)" : " (it asks again once a session has read outside content)"}`);
624
+ // The main agent works in auto mode unless told otherwise; that is how pine comes, and not a note. Another agent does by somebody's choice.
625
+ if (level === "auto" && a.level === "auto" && a.id !== mainAgentId(cfg) && tools.includes("bash"))
626
+ out.push(`agent ${a.id}: auto mode. Its shell and file tools reach your whole account and the network in your own conversations, without a sandbox; what is critical is checked, and after outside content what reaches out, sends or changes its memory`);
627
+ if (a.trustWorkspace)
628
+ out.push(`agent ${a.id}: trustWorkspace is on; code in ${a.workspace}/.pi/extensions runs inside the daemon`);
629
+ if (isInside(realish(a.workspace), realish(cfg.home)))
630
+ out.push(`agent ${a.id}: the workspace contains pine's home directory`);
631
+ if (a.untrusted && a.untrusted.tools.some((t) => ["bash", "write", "edit"].includes(t)))
632
+ out.push(`agent ${a.id}: runs triggered by untrusted events may use ${a.untrusted.tools.filter((t) => ["bash", "write", "edit"].includes(t)).join(", ")}`);
633
+ }
634
+ if (cfg.http && !["127.0.0.1", "localhost", "::1"].includes(cfg.http.host))
635
+ out.push(`http listens on ${cfg.http.host}; anyone who can reach it and knows the token controls every agent. Prefer loopback plus a tunnel.`);
636
+ for (const [name, h] of Object.entries(cfg.http?.hooks ?? {}))
637
+ if (!h.secret)
638
+ out.push(`http hook "${name}" has no secret; anyone who can reach the port can publish ${h.topic}`);
639
+ // A source whose events count as the owner's words: fine for a paired Telegram account, a risk for anything others can feed.
640
+ for (const [where, sources] of [["pine.json", cfg.sources], ...Object.values(cfg.agents).map((a) => [`agent ${a.id}`, a.sources])]) {
641
+ for (const [name, s] of Object.entries(sources))
642
+ if (s.trust === "owner" && s.type !== "telegram")
643
+ out.push(`${where}: what the source "${name}" (${s.type ?? "custom"}) reports is treated as coming from you; whoever can feed it gets an agent's full tool set`);
644
+ }
645
+ // A source type is a program inside the daemon, whoever wrote it. So is a module a single source names with "use".
646
+ for (const [name, file] of Object.entries(cfg.sourceTypes))
647
+ out.push(`source type "${name}": ${file} runs inside pine with your rights, outside any sandbox`);
648
+ for (const [where, sources] of [["pine.json", cfg.sources], ...Object.values(cfg.agents).map((a) => [`agent ${a.id}`, a.sources])]) {
649
+ for (const [name, s] of Object.entries(sources)) {
650
+ if (s.use)
651
+ out.push(`${where}: the source "${name}" runs the module ${s.use} inside pine with your rights, outside any sandbox`);
652
+ if (s.type === "webhook" && s.options.open === true)
653
+ out.push(`${where}: the webhook source "${name}" has no secret; anyone who can reach the port can make it report`);
654
+ }
655
+ }
656
+ for (const r of cfg.routes)
657
+ if (r.trust === "owner")
658
+ out.push(`route "${r.name}" treats events on ${r.on.join(", ")} as coming from you; whoever can publish there gets the agent's full tool set`);
659
+ return out;
660
+ }