@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
package/src/cli.js ADDED
@@ -0,0 +1,777 @@
1
+ #!/usr/bin/env node
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { ConfigError, defaultHome, effectiveMcp, loadConfig, mainAgentId, PINE_ROOT, unsandboxed } from "./config.js";
5
+ import { audit, levelOf } from "./security.js";
6
+ import { pineManual, showRead, showSearch } from "./manual.js";
7
+ import { modelKeys } from "./models.js";
8
+ import { allSkills, listSkills } from "./skills.js";
9
+ import { whenText } from "./timers.js";
10
+ import { expandHome } from "./util.js";
11
+ const HELP = `pine - PI neural engine
12
+
13
+ Start here
14
+ pine open the terminal UI (same as "pine tui")
15
+ pine . | pine <folder> the same, with a tab on that folder: a conversation of the main agent that
16
+ works there (the one from last time, if there is one)
17
+ pine tui chat with your agents; starts a daemon inside if none is running
18
+ pine login <provider> sign in to a model provider (OpenCode, Claude, ChatGPT, ...)
19
+ pine logout <provider>
20
+ pine model add <name> <address> [--context tokens] [--reasoning | --no-reasoning]
21
+ add a model server of your own (llama.cpp, vLLM, LM Studio, ...): pine asks
22
+ it for its models, and for its key if it wants one
23
+ pine model list | pine model remove <name>
24
+
25
+ Daemon
26
+ pine init [dir] [--yes] set pine up: a home directory (default ~/.pine) from the example, the browser
27
+ its web tools use, and on Linux the sandbox (asks before it runs anything
28
+ as administrator; --yes skips the question). Safe to run again
29
+ pine check validate the configuration and list what it sets up
30
+ pine start run the daemon in the foreground
31
+ pine dev-model [--port 7464] [--model haiku]
32
+ OpenAI-compatible model server backed by "claude -p" (development only)
33
+ pine update [--check] bring pine up to date (npm for an install, git for a checkout) with what the
34
+ new version needs; --check only says whether there is something newer
35
+ pine version which version this is and how it is installed
36
+ pine browser-install fetch the browser again (pine init and pine update do this)
37
+
38
+ Talking to a running daemon
39
+ pine status running tasks, live sessions, queue
40
+ pine agents configured agents, as the daemon has them (JSON)
41
+ pine send <agent> <text...> give an agent a task and print its answer
42
+ [--session <key>] [--no-wait]
43
+ pine emit <topic> [json] publish an event
44
+ pine events [--topic <pattern>] [--limit n] [-f]
45
+ show the event log; -f follows live
46
+ pine tasks [--agent id] [--status s] recent tasks
47
+ pine task <id> one task in full
48
+ pine cancel <id> stop a task
49
+ pine state [key-pattern] shared state
50
+ pine approvals open approval requests
51
+ pine approve <id> [--always] | pine deny <id> --always: do not ask again in that conversation
52
+ pine reset <agent> [session] forget a conversation (also clears its taint)
53
+ pine mode <agent> [auto|plan|manual|bypass]
54
+ show or change how much an agent may do without asking
55
+
56
+ Event sources
57
+ pine sources configured sources, whether they run, who is subscribed, last event
58
+ pine subscribe <agent> <source> [--session name] [--note text] [--throttle 5m] [--when json] [--separate]
59
+ wake that agent whenever the source reports something: in its main
60
+ conversation, or only the conversation named with --session
61
+ pine subscribe --global <source> [--note text] ...
62
+ wake every agent that can use the source
63
+ pine unsubscribe <agent> <source> [--session name] | pine unsubscribe --global <source>
64
+
65
+ Schedules, skills, the manual
66
+ pine schedules what is scheduled: for whom, when, and the task
67
+ pine skills every skill: whom it is for and where it lies
68
+ pine manual <words> search pine's manual, as the agents do; --read <id> shows a part in full
69
+
70
+ Agents (the main agent does the same when you ask it: create_agent, update_agent, remove_agent)
71
+ pine agent list the agents: what each is for, its model, its reach, what it has
72
+ pine agent add <id> --description "what it is for" [--instructions "who it is and how it works"]
73
+ [--instructions-file <file>] [--model provider/model] [--tools read,bash,...]
74
+ pine agent update <id> [--description ...] [--instructions ... | --instructions-file <file>]
75
+ [--soul ... | --soul-file <file>]
76
+ [--model provider/model|default] [--thinking off|low|...|max]
77
+ [--mode auto|safe|manual|bypass|plan|default] [--tools read,bash,...] [--delegates id,id|*]
78
+ [--network | --no-network] [--read /path,/path] [--write /path] [--forget /path]
79
+ change an agent's settings; give only what changes, the rest stays
80
+ pine agent remove <id> [--keep-files] [--yes]
81
+ remove an agent with everything it has: conversations, sources,
82
+ schedules, servers, skills, routes that wake it, its folder and
83
+ private home. --keep-files moves the folder to removed/ instead
84
+
85
+ MCP servers
86
+ pine mcp list configured servers, who gets them, and whether they connect
87
+ pine mcp add <name> <https-url> [--agent id] [--description text] [--taints] [--approve always|tainted]
88
+ [--exposure direct|codemode|deferred|hidden] [--timeout seconds]
89
+ pine mcp add <name> [--agent id] -- <command> [args...]
90
+ pine mcp remove <name> [--agent id]
91
+ pine mcp login <name> sign in to a remote server through the browser (OAuth)
92
+ pine mcp logout <name>
93
+
94
+ Options
95
+ --home <dir> home directory (default $PINE_HOME or ~/.pine)
96
+ `;
97
+ function parseArgs(argv) {
98
+ const flags = {};
99
+ const rest = [];
100
+ for (let i = 0; i < argv.length; i++) {
101
+ const a = argv[i];
102
+ if (a === "-f")
103
+ flags.follow = true;
104
+ else if (a.startsWith("--no-"))
105
+ flags[a.slice(5)] = false;
106
+ else if (a.startsWith("--"))
107
+ flags[a.slice(2)] = argv[i + 1] !== undefined && !argv[i + 1].startsWith("--") && !["follow", "json", "api-key", "oauth", "taints", "offline", "always", "separate", "global", "yes", "keep-files", "network"].includes(a.slice(2)) ? argv[++i] : true;
108
+ else
109
+ rest.push(a);
110
+ }
111
+ return { flags, rest };
112
+ }
113
+ function copyDir(from, to, skip = () => false) {
114
+ const created = [];
115
+ for (const entry of fs.readdirSync(from, { withFileTypes: true })) {
116
+ const src = path.join(from, entry.name);
117
+ const dst = path.join(to, entry.name === ".env.example" ? ".env" : entry.name);
118
+ if (entry.isDirectory()) {
119
+ fs.mkdirSync(dst, { recursive: true });
120
+ created.push(...copyDir(src, dst, skip));
121
+ }
122
+ else if (!fs.existsSync(dst) && !skip(dst)) {
123
+ fs.copyFileSync(src, dst);
124
+ fs.chmodSync(dst, 0o600);
125
+ created.push(dst);
126
+ }
127
+ }
128
+ return created;
129
+ }
130
+ function client(cfg) {
131
+ if (!cfg.http)
132
+ throw new Error("http is disabled in pine.json, so there is no control API to talk to");
133
+ const tokenFile = path.join(cfg.dataDir, "http-token");
134
+ const token = cfg.http.token ?? (fs.existsSync(tokenFile) ? fs.readFileSync(tokenFile, "utf8").trim() : "");
135
+ const base = `http://${cfg.http.host === "0.0.0.0" ? "127.0.0.1" : cfg.http.host}:${cfg.http.port}`;
136
+ const call = async (method, url, body) => {
137
+ let res;
138
+ try {
139
+ res = await fetch(base + url, { method, headers: { authorization: `Bearer ${token}`, ...(body !== undefined ? { "content-type": "application/json" } : {}) }, body: body !== undefined ? JSON.stringify(body) : undefined });
140
+ }
141
+ catch {
142
+ throw new Error(`no daemon answers on ${base}. Start it with "pine start".`);
143
+ }
144
+ const json = await res.json().catch(() => ({}));
145
+ if (!res.ok)
146
+ throw new Error(json.error ?? `HTTP ${res.status}`);
147
+ return json;
148
+ };
149
+ return { base, token, get: (u) => call("GET", u), post: (u, b = {}) => call("POST", u, b) };
150
+ }
151
+ const when = (ts) => new Date(ts).toLocaleString("sv-SE");
152
+ const line = (e) => `${when(e.ts)} #${String(e.id).padEnd(5)} ${e.topic.padEnd(34)} ${e.trust === "owner" ? "owner " : "untrusted"} ${e.source.padEnd(14)} ${JSON.stringify(e.payload).slice(0, 160)}`;
153
+ /** pine agent list | add | remove: with a running daemon through it, without one in the files. */
154
+ async function agentCommand(cfg, argv, out) {
155
+ const { applyAgentChange, checkAgentChange, eraseAgent, holdingsOf } = await import("./admin.js");
156
+ const { AGENT_TOOLS, checkNewAgent, createAgent } = await import("./agent-admin.js");
157
+ const { flags, rest } = parseArgs(argv.filter((a, i, all) => !(a === "--home" || all[i - 1] === "--home")));
158
+ const sub = rest.shift() ?? "list";
159
+ const some = (list) => list.join(", ") || "none";
160
+ // A running daemon does it at once, for the sessions and sources that are live. Without one the files are changed.
161
+ // The daemon of THIS home: one that answers on the port and takes this home's token. Another
162
+ // pine can be listening there (a second home with the same port), and it is not to be touched.
163
+ const daemon = async () => {
164
+ try {
165
+ const api = client(cfg);
166
+ if (!(await fetch(`${api.base}/health`, { signal: AbortSignal.timeout(800) })).ok)
167
+ return undefined;
168
+ await api.get("/status");
169
+ return api;
170
+ }
171
+ catch {
172
+ return undefined;
173
+ }
174
+ };
175
+ const main = mainAgentId(cfg);
176
+ switch (sub) {
177
+ case "list": {
178
+ for (const a of [cfg.agents[main], ...Object.values(cfg.agents).filter((x) => x.id !== main)]) {
179
+ const has = holdingsOf(cfg, a.id);
180
+ out(`${a.id}${a.id === main ? " (main)" : ""}: ${a.description || "no description"}\n model ${a.model ?? `${cfg.defaults.model ?? "none"} (the default)`} · reasoning ${a.thinking} · mode ${a.mode} · reach ${unsandboxed(levelOf(a)) ? "your account + network (no sandbox)" : `its own folders (sandbox)${a.sandbox.network ? " + network" : ""}`}\n conversations: ${some(has.conversations)} · sources: ${some(has.sources)} · MCP servers: ${some(has.servers)} · schedules: ${some(has.schedules)} · skills: ${some(has.skills)}${has.routes.length ? ` · routes: ${has.routes.join(", ")}` : ""} · ${has.files} file${has.files === 1 ? "" : "s"} in ${a.workspace}`);
181
+ }
182
+ return;
183
+ }
184
+ case "add": {
185
+ const id = rest[0];
186
+ const usage = 'usage: pine agent add <id> --description "what it is for" [--instructions "..."] [--instructions-file <file>] [--model provider/model] [--tools read,bash,...]';
187
+ if (!id || typeof flags.description !== "string")
188
+ throw new Error(usage);
189
+ const fromFile = typeof flags["instructions-file"] === "string" ? fs.readFileSync(expandHome(flags["instructions-file"]), "utf8") : undefined;
190
+ // Without instructions it starts from what it is for; it keeps the file itself from then on.
191
+ const instructions = fromFile ?? (typeof flags.instructions === "string" ? flags.instructions : `You are ${id}. ${flags.description.trim().replace(/\.?$/, ".")}`);
192
+ const tools = typeof flags.tools === "string" ? flags.tools.split(",").map((t) => t.trim()).filter(Boolean) : undefined;
193
+ const spec = { id, description: flags.description, instructions, model: typeof flags.model === "string" ? flags.model : undefined, tools };
194
+ checkNewAgent(cfg, spec);
195
+ const api = await daemon();
196
+ const workspace = api ? (await api.post("/agents", spec)).workspace : createAgent(cfg, spec).workspace;
197
+ return out(`Created the agent ${id} (tools: ${(tools ?? AGENT_TOOLS).join(", ")}). Its workspace is ${workspace}.${api ? ` Talk to it with: pine send ${id} "..."` : " It is there when pine is started."}`);
198
+ }
199
+ case "update": {
200
+ const id = rest[0];
201
+ const usage = 'usage: pine agent update <id> [--description "..."] [--instructions "..." | --instructions-file <file>] [--soul "..." | --soul-file <file>] [--model provider/model|default] [--thinking off|minimal|low|medium|high|xhigh|max] [--mode auto|safe|manual|bypass|plan|default] [--tools read,bash,...] [--delegates id,id|*] [--network | --no-network] [--read /path,/path] [--write /path] [--forget /path]';
202
+ if (!id)
203
+ throw new Error(usage);
204
+ const agent = cfg.agents[id];
205
+ if (!agent)
206
+ throw new Error(`there is no agent "${id}". Agents: ${Object.keys(cfg.agents).join(", ")}`);
207
+ const str = (v) => (typeof v === "string" ? v : undefined);
208
+ const list = (v) => (typeof v === "string" ? v.split(",").map((x) => x.trim()).filter(Boolean) : undefined);
209
+ const fromFile = typeof flags["instructions-file"] === "string" ? fs.readFileSync(expandHome(flags["instructions-file"]), "utf8") : undefined;
210
+ const change = {
211
+ description: str(flags.description),
212
+ instructions: fromFile ?? str(flags.instructions),
213
+ soul: typeof flags["soul-file"] === "string" ? fs.readFileSync(expandHome(flags["soul-file"]), "utf8") : str(flags.soul),
214
+ model: str(flags.model),
215
+ thinking: str(flags.thinking),
216
+ mode: str(flags.mode),
217
+ tools: list(flags.tools),
218
+ delegates: list(flags.delegates),
219
+ network: typeof flags.network === "boolean" ? flags.network : undefined,
220
+ read: list(flags.read),
221
+ write: list(flags.write),
222
+ forget: list(flags.forget),
223
+ };
224
+ const api = await daemon();
225
+ if (api) {
226
+ const r = (await api.post(`/agents/${encodeURIComponent(id)}/update`, change));
227
+ return out(`Updated the agent ${id}; it holds from its next message on:\n${r.lines.map((l) => ` ${l}`).join("\n")}${r.warnings.length ? `\nNote: ${r.warnings.join("; ")}` : ""}`);
228
+ }
229
+ // Without a daemon the files are changed; a model change is left to the running pine, which can check the model exists.
230
+ if (change.model !== undefined && change.model !== "default" && change.model !== "")
231
+ throw new Error(`changing the model needs a running daemon, which checks that "${change.model}" exists. Start it with "pine start" and run this again, or set "model" in ${path.join(agent.dir, "agent.json")} by hand.`);
232
+ const checked = checkAgentChange(cfg, agent, change, []);
233
+ applyAgentChange(cfg, agent, checked);
234
+ return out(`Updated the agent ${id} (it is there when pine is started):\n${checked.lines.map((l) => ` ${l}`).join("\n")}${checked.warnings.length ? `\nNote: ${checked.warnings.join("; ")}` : ""}`);
235
+ }
236
+ case "remove": {
237
+ const id = rest[0];
238
+ if (!id)
239
+ throw new Error("usage: pine agent remove <id> [--keep-files] [--yes]");
240
+ const agent = cfg.agents[id];
241
+ if (!agent)
242
+ throw new Error(`there is no agent "${id}". Agents: ${Object.keys(cfg.agents).join(", ")}`);
243
+ if (id === main)
244
+ throw new Error(`${id} is the main agent: it administers pine and cannot be removed`);
245
+ const has = holdingsOf(cfg, id);
246
+ const keep = flags["keep-files"] === true;
247
+ out(`${id}: ${agent.description || "no description"}\nWith it go: conversations: ${some(has.conversations)}; event sources: ${some(has.sources)}; MCP servers: ${some(has.servers)}; schedules: ${some(has.schedules)}; skills: ${some(has.skills)}; routes that wake it: ${some(has.routes)}\n${keep ? `Its folder is kept: moved to ${path.join(cfg.home, "removed")} (${has.files} file${has.files === 1 ? "" : "s"} in its workspace).` : `Its folder ${agent.dir} is deleted, with ${has.files} file${has.files === 1 ? "" : "s"} in its workspace and everything said to it. This cannot be undone.`}${has.outside ? `\nIts workspace ${agent.workspace} lies outside pine's home and is left as it is.` : ""}`);
248
+ if (flags.yes !== true) {
249
+ if (!process.stdin.isTTY)
250
+ throw new Error("not removed: this asks before it deletes. Run it in a terminal, or add --yes");
251
+ const readline = await import("node:readline");
252
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
253
+ const answer = await new Promise((resolve) => rl.question(`Remove the agent ${id}? [y/N] `, resolve));
254
+ rl.close();
255
+ if (!/^y(es)?$/i.test(answer.trim()))
256
+ return out("Not removed.");
257
+ }
258
+ const api = await daemon();
259
+ let gone;
260
+ if (api)
261
+ gone = (await api.post(`/agents/${encodeURIComponent(id)}/erase`, { agent: id, keepFiles: keep }));
262
+ else {
263
+ const { Kv, openDb, TaskStore } = await import("./store.js");
264
+ const db = openDb(cfg.dataDir);
265
+ try {
266
+ gone = eraseAgent(cfg, { kv: new Kv(db), tasks: new TaskStore(db) }, id, keep);
267
+ }
268
+ finally {
269
+ db.close();
270
+ }
271
+ }
272
+ if (gone.problem)
273
+ throw new Error(`the agent ${id} is taken out, but what is left of the configuration does not load: ${gone.problem}\nIts folder was kept at ${gone.kept}. Run "pine check".`);
274
+ return out(`Removed the agent ${id}.${gone.kept ? ` Its folder is kept at ${gone.kept}.` : ""}`);
275
+ }
276
+ default:
277
+ throw new Error("usage: pine agent list | add <id> --description ... | update <id> --model ... | remove <id> [--keep-files] [--yes]");
278
+ }
279
+ }
280
+ /** pine mcp list | add | remove | login | logout */
281
+ async function mcpCommand(cfg, argv, out) {
282
+ const { addServer, findServer, listServers, piMcp, removeServer, serverStates } = await import("./mcp-config.js");
283
+ // Everything after "--" is the command line of a local server.
284
+ const dashes = argv.indexOf("--");
285
+ const command = dashes >= 0 ? argv.slice(dashes + 1) : [];
286
+ const { flags, rest } = parseArgs((dashes >= 0 ? argv.slice(0, dashes) : argv).filter((a, i, all) => !(a === "--home" || all[i - 1] === "--home")));
287
+ const sub = rest.shift() ?? "list";
288
+ const agent = typeof flags.agent === "string" ? flags.agent : undefined;
289
+ // A running daemon applies the change at once; without one the files are edited and it applies at the next start.
290
+ const live = async (body) => {
291
+ try {
292
+ const api = client(cfg);
293
+ if (!(await fetch(`${api.base}/health`, { signal: AbortSignal.timeout(800) })).ok)
294
+ return false;
295
+ await api.post("/mcp", body);
296
+ return true;
297
+ }
298
+ catch (e) {
299
+ if (e instanceof Error && !/no daemon|fetch failed|HTTP 404|not found|aborted|timeout/i.test(e.message))
300
+ throw e;
301
+ return false;
302
+ }
303
+ };
304
+ switch (sub) {
305
+ case "list": {
306
+ const servers = listServers(cfg);
307
+ if (!servers.length)
308
+ return out("no MCP servers configured");
309
+ const states = flags.offline ? {} : await serverStates(cfg);
310
+ for (const s of servers)
311
+ out(`${s.name.padEnd(14)} ${(s.enabled ? (states[s.name] ?? (s.remote ? "?" : "local")) : "disabled").padEnd(16)} ${s.scope === "global" ? `all: ${s.agents.join(", ") || "nobody"}` : s.session ? `only the conversation ${s.session} of ${s.scope}` : `only ${s.scope}`}\n${" ".repeat(15)}${s.target}${s.taints ? " [outside content]" : ""}${s.approve !== "never" ? ` [approval: ${s.approve}]` : ""}`);
312
+ return;
313
+ }
314
+ case "add": {
315
+ const name = rest[0];
316
+ const url = rest[1];
317
+ if (!name || (!url && !command.length))
318
+ throw new Error("usage: pine mcp add <name> <https-url> [--agent id] [--description text] [--taints] [--approve always|tainted] [--exposure direct|codemode|deferred|hidden] [--timeout seconds]\n pine mcp add <name> [--agent id] -- <command> [args...]");
319
+ const server = url ? { url } : { command: command[0], args: command.slice(1) };
320
+ if (typeof flags.description === "string")
321
+ server.description = flags.description;
322
+ if (flags.taints === true)
323
+ server.taints = true;
324
+ if (flags.timeout !== undefined) {
325
+ if (!(Number(flags.timeout) > 0))
326
+ throw new Error("--timeout takes a number of seconds, for example --timeout 180");
327
+ server.timeout = Number(flags.timeout);
328
+ }
329
+ if (typeof flags.approve === "string")
330
+ server.approve = flags.approve;
331
+ if (typeof flags.exposure === "string")
332
+ server.exposure = flags.exposure;
333
+ if (!(await live({ name, server, agent })))
334
+ addServer(cfg, name, server, agent);
335
+ out(`Added "${name}" ${agent ? `for agent ${agent}` : "for all agents"}.${url ? ` If it requires sign-in: pine mcp login ${name}` : ""}`);
336
+ return;
337
+ }
338
+ case "remove": {
339
+ if (!rest[0])
340
+ throw new Error("usage: pine mcp remove <name> [--agent id]");
341
+ if (!(await live({ name: rest[0], agent, remove: true })) && !removeServer(cfg, rest[0], agent))
342
+ throw new Error(`no server "${rest[0]}"${agent ? ` on agent ${agent}` : " in pine.json"}`);
343
+ return out(`Removed "${rest[0]}".`);
344
+ }
345
+ case "login":
346
+ case "logout": {
347
+ const name = rest[0];
348
+ const server = name ? findServer(cfg, name, agent) : undefined;
349
+ if (!name || !server)
350
+ throw new Error(name ? `no server "${name}". pine mcp list shows what is configured.` : `usage: pine mcp ${sub} <name>`);
351
+ if (!server.url)
352
+ throw new Error(`"${name}" is a local server; only remote servers have a sign-in`);
353
+ const { code } = await piMcp(cfg, { [name]: server }, [sub, name]);
354
+ if (code === 0 && sub === "login") {
355
+ // Sessions that started before the sign-in do not have the server's tools yet.
356
+ try {
357
+ await client(cfg).post("/mcp/refresh");
358
+ }
359
+ catch {
360
+ // No daemon running: nothing to refresh.
361
+ }
362
+ }
363
+ process.exitCode = code;
364
+ return;
365
+ }
366
+ default:
367
+ throw new Error(`unknown: pine mcp ${sub}. Use list, add, remove, login or logout.`);
368
+ }
369
+ }
370
+ /**
371
+ * Download the Chromium build the bundled browser tools drive. It has to match the Playwright
372
+ * version pine ships with, so that copy's own installer is used. Quick when it is there already.
373
+ */
374
+ async function installBrowser() {
375
+ const { spawnSync } = await import("node:child_process");
376
+ const { createRequire } = await import("node:module");
377
+ const cli = path.join(path.dirname(createRequire(import.meta.url).resolve("playwright-core")), "cli.js");
378
+ return spawnSync(process.execPath, [cli, "install", "chromium"], { stdio: "inherit" }).status ?? 1;
379
+ }
380
+ const COMMANDS = new Set(["agent", "agents", "approvals", "approve", "browser-install", "cancel", "check", "deny", "dev-model", "emit", "events", "help", "init", "login", "logout", "manual", "mcp", "mode", "model", "reset", "schedules", "send", "skills", "sources", "start", "state", "status", "subscribe", "task", "tasks", "tui", "unsubscribe", "update", "version"]);
381
+ /** Whether a first argument means a folder to open: something written as a path, or the name of a folder here that is not a command. */
382
+ function folderArgument(word, cwd = process.cwd()) {
383
+ if (!word || COMMANDS.has(word))
384
+ return undefined;
385
+ const full = path.resolve(cwd, expandHome(word));
386
+ const isDir = (() => {
387
+ try {
388
+ return fs.statSync(full).isDirectory();
389
+ }
390
+ catch {
391
+ return false;
392
+ }
393
+ })();
394
+ if (isDir)
395
+ return full;
396
+ // Written as a path but not there: an error about the folder says more than "unknown command".
397
+ if (/^(\.{1,2}|~)($|\/)|\//.test(word))
398
+ throw new Error(`${word} is not a folder`);
399
+ return undefined;
400
+ }
401
+ async function main() {
402
+ const { flags, rest } = parseArgs(process.argv.slice(2));
403
+ let cmd = rest.shift();
404
+ // "pine ." and "pine ~/dev/project" open the terminal UI with a tab on that folder.
405
+ let folder = folderArgument(cmd);
406
+ if (folder)
407
+ cmd = "tui";
408
+ else if (cmd === "tui")
409
+ folder = folderArgument(rest[0]);
410
+ const home = path.resolve(expandHome(typeof flags.home === "string" ? flags.home : defaultHome()));
411
+ const out = (v) => console.log(typeof v === "string" ? v : JSON.stringify(v, null, 2));
412
+ if (cmd === "help" || flags.help || (!cmd && !process.stdout.isTTY))
413
+ return out(HELP);
414
+ if (cmd === "manual") {
415
+ // The same search the agents use, for you and for trying out what they would find.
416
+ const manual = pineManual(path.join(PINE_ROOT, "docs"));
417
+ if (typeof flags.read === "string")
418
+ return out(showRead(manual, flags.read.split(",")));
419
+ if (!rest.length)
420
+ return out(`The parts of pine's manual. Search it (pine manual telegram pairing), or read a part (pine manual --read sources#telegram).\n${manual.contents()}`);
421
+ return out(showSearch(manual, [rest.join(" ")]));
422
+ }
423
+ if (cmd === "init") {
424
+ const target = path.resolve(expandHome(rest[0] ?? home));
425
+ fs.mkdirSync(target, { recursive: true, mode: 0o700 });
426
+ fs.chmodSync(target, 0o700);
427
+ // A home from before instructions moved into the workspace keeps them where they are: with
428
+ // a second AGENTS.md in the workspace the agent would have both.
429
+ const kept = [];
430
+ const created = copyDir(path.join(PINE_ROOT, "examples", "home"), target, (dst) => {
431
+ const old = path.join(path.dirname(path.dirname(dst)), "AGENTS.md");
432
+ const twice = path.basename(dst) === "AGENTS.md" && path.basename(path.dirname(dst)) === "workspace" && fs.existsSync(old);
433
+ if (twice)
434
+ kept.push(old);
435
+ return twice;
436
+ });
437
+ out(created.length ? `Created in ${target}:\n${created.map((f) => ` ${path.relative(target, f)}`).join("\n")}` : `${target} already has every example file; nothing changed.`);
438
+ for (const old of kept)
439
+ out(`\n${path.relative(target, old)} stays where it is: there the agent reads it but cannot change it. To let the agent keep its own instructions, move it to ${path.relative(target, path.join(path.dirname(old), "workspace", "AGENTS.md"))}.`);
440
+ // Everything the built-in tools need comes with it, so that what is set up also works. The
441
+ // browser is the one large piece; a second run finds it there and takes a moment.
442
+ // (PINE_SKIP_DOWNLOADS is for pine's own tests, which must not fetch 600 MB.)
443
+ let noBrowser = 0;
444
+ if (!process.env.PINE_SKIP_DOWNLOADS) {
445
+ out("\nGetting the browser the built-in web tools drive (about 600 MB, once) ...");
446
+ noBrowser = await installBrowser();
447
+ }
448
+ // On Linux the sandbox needs a package and, on some systems, a rule only an administrator
449
+ // can load; the browser needs system libraries. pine says what it would run and does it
450
+ // after one yes; nothing is left to a manual.
451
+ let noSandbox = false;
452
+ if (process.platform === "linux") {
453
+ const { setUpSandbox } = await import("./sandbox-setup.js");
454
+ noSandbox = !(await setUpSandbox({
455
+ out,
456
+ yes: flags.yes === true,
457
+ confirm: async (question) => {
458
+ if (!process.stdin.isTTY)
459
+ return undefined;
460
+ const readline = await import("node:readline");
461
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
462
+ const answer = await new Promise((resolve) => rl.question(`${question} [Y/n] `, resolve));
463
+ rl.close();
464
+ return !/^n/i.test(answer.trim());
465
+ },
466
+ }));
467
+ }
468
+ if (noBrowser !== 0) {
469
+ out(`\nThe browser could not be downloaded (exit ${noBrowser}). Everything else is set up; web search and page reading work without it. Run "pine init" again when you are online to get it.`);
470
+ process.exitCode = 1;
471
+ return;
472
+ }
473
+ out(`\nReady. Start with: pine${target === defaultHome() ? "" : ` --home ${target}`}\nThe example uses Claude through "claude -p". For another model: pine login <provider>, then /model in the UI.${noSandbox ? "\nThe sandbox is not set up (see above): until it is, agents get no shell. pine check says where it stands." : ""}`);
474
+ return;
475
+ }
476
+ if (cmd === "browser-install")
477
+ process.exit(await installBrowser());
478
+ if (cmd === "version" || flags.version === true) {
479
+ const { installed } = await import("./update.js");
480
+ const me = installed();
481
+ return out(`pine ${me.version} (${me.kind === "checkout" ? `checkout in ${me.root}` : me.kind === "global" ? "installed with npm" : `a dependency in ${me.root}`})`);
482
+ }
483
+ if (cmd === "update") {
484
+ const { update } = await import("./update.js");
485
+ process.exit(await update({ check: flags.check === true, out, browser: !process.env.PINE_SKIP_DOWNLOADS }));
486
+ }
487
+ if (cmd === "dev-model") {
488
+ const { startClaudeModel } = await import("./dev/claude-model.js");
489
+ const server = await startClaudeModel({ port: Number(flags.port ?? 7464), model: typeof flags.model === "string" ? flags.model : "haiku", log: (l) => console.error(`${new Date().toISOString()} ${l}`) });
490
+ out(`claude -p model server on ${server.baseUrl} (model ids: claude-haiku, claude-sonnet, claude-opus). Ctrl-C to stop.`);
491
+ process.on("SIGINT", () => void server.close().then(() => process.exit(0)));
492
+ return;
493
+ }
494
+ if ((!cmd || cmd === "tui") && !fs.existsSync(path.join(home, "pine.json")))
495
+ return out(`No pine home at ${home} yet. Create one with:\n\n pine init\n\n${HELP}`);
496
+ const cfg = loadConfig(home);
497
+ if (!cmd || cmd === "tui") {
498
+ const { runTui } = await import("./tui/run.js");
499
+ return runTui(cfg, { folder });
500
+ }
501
+ if (cmd === "login" || cmd === "logout") {
502
+ const { login, logout } = await import("./login.js");
503
+ if (!rest[0])
504
+ throw new Error(`usage: pine ${cmd} <provider> (for example opencode-go, opencode, anthropic, openai-codex)`);
505
+ if (cmd === "login")
506
+ await login(cfg, rest[0], flags["api-key"] === true ? "api_key" : flags.oauth === true ? "oauth" : undefined);
507
+ else
508
+ await logout(cfg, rest[0]);
509
+ return;
510
+ }
511
+ if (cmd === "mcp")
512
+ return mcpCommand(cfg, process.argv.slice(process.argv.indexOf("mcp") + 1), out);
513
+ if (cmd === "agent")
514
+ return agentCommand(cfg, process.argv.slice(process.argv.indexOf("agent") + 1), out);
515
+ if (cmd === "model") {
516
+ const { addModelServer, checkServerName, listModelServers, lookAt, modelKeyName, removeModelServer, serverUrl } = await import("./models.js");
517
+ const sub = rest.shift() ?? "list";
518
+ const sized = (m) => `${m.contextWindow ? `${m.contextWindow} tokens of context` : "context not given"}, ${m.images ? "text and pictures" : "text"}${m.reasoning ? ", thinks" : ""}`;
519
+ // A running daemon reads the file again at once; without one it is read at the next start.
520
+ const refreshed = async () => {
521
+ try {
522
+ const api = client(cfg);
523
+ if (!(await fetch(`${api.base}/health`, { signal: AbortSignal.timeout(800) })).ok)
524
+ return false;
525
+ await api.post("/models/refresh");
526
+ return true;
527
+ }
528
+ catch {
529
+ return false;
530
+ }
531
+ };
532
+ if (sub === "list") {
533
+ const servers = listModelServers(cfg.home);
534
+ if (!servers.length)
535
+ return out("no model servers of your own. Add one with: pine model add <name> <address> (for example: pine model add studio http://127.0.0.1:8080)");
536
+ for (const s of servers) {
537
+ out(`${s.name} ${s.baseUrl} key: ${s.key}`);
538
+ for (const m of s.models)
539
+ out(` ${s.name}/${m.id} ${sized(m)}`);
540
+ }
541
+ return;
542
+ }
543
+ if (sub === "add") {
544
+ const [name, address] = rest;
545
+ if (!name || !address)
546
+ throw new Error("usage: pine model add <name> <address> [--context tokens] [--reasoning | --no-reasoning]\n for example: pine model add studio http://127.0.0.1:8080");
547
+ const baseUrl = serverUrl(address);
548
+ const { knownProviders, readSecret } = await import("./login.js");
549
+ checkServerName(name, await knownProviders(cfg));
550
+ let look = await lookAt(baseUrl);
551
+ let key;
552
+ if (look.locked) {
553
+ key = await readSecret(`${new URL(baseUrl).host} wants a key. API key`);
554
+ process.stdin.pause();
555
+ if (!key)
556
+ throw new Error("no key given; nothing was added");
557
+ look = await lookAt(baseUrl, key);
558
+ if (look.locked)
559
+ throw new Error("the server did not accept that key; nothing was added");
560
+ }
561
+ const context = flags.context === undefined ? undefined : Number(flags.context);
562
+ const models = addModelServer(cfg.home, { name, baseUrl, key, models: look.models, context, reasoning: typeof flags.reasoning === "boolean" ? flags.reasoning : undefined });
563
+ const live = await refreshed();
564
+ out(`Added "${name}" at ${baseUrl}`);
565
+ for (const m of listModelServers(cfg.home).find((s) => s.name === name)?.models ?? [])
566
+ out(` ${name}/${m.id} ${sized(m)}`);
567
+ if (key)
568
+ out(`Its key is in ${path.join(cfg.home, ".env")} as ${modelKeyName(name)}.`);
569
+ return out(`${live ? "The running pine has it now." : "pine has it when it next starts."} Choose a model with /model ${models[0]} in the terminal UI.`);
570
+ }
571
+ if (sub === "remove") {
572
+ if (!rest[0])
573
+ throw new Error("usage: pine model remove <name>");
574
+ if (!removeModelServer(cfg, rest[0]))
575
+ throw new Error(`no model server "${rest[0]}". pine model list shows what there is.`);
576
+ await refreshed();
577
+ return out(`Removed "${rest[0]}".`);
578
+ }
579
+ throw new Error(`unknown: pine model ${sub}. Use add, list or remove.`);
580
+ }
581
+ if (cmd === "schedules") {
582
+ const list = [...cfg.schedules.map((s) => ({ s, whom: s.task ? "all agents" : `event ${s.topic} only` })), ...Object.values(cfg.agents).flatMap((a) => a.schedules.map((s) => ({ s, whom: s.session ? `conversation ${s.session} of ${a.id}` : `agent ${a.id}` })))];
583
+ if (!list.length)
584
+ return out("nothing is scheduled. An agent schedules something when you ask it to (\"every morning at seven ...\", \"remind me at five\"), or write it under \"schedules\"; see docs/references/events.md");
585
+ for (const { s, whom } of list) {
586
+ out(`${s.name} ${whom} ${whenText(s)}`);
587
+ if (s.task)
588
+ out(` ${s.task}`);
589
+ }
590
+ return;
591
+ }
592
+ if (cmd === "skills") {
593
+ const list = allSkills(cfg);
594
+ if (!list.length)
595
+ return out("no skills yet. An agent writes one when you ask it to (\"make a skill for this\"), or put a folder with a SKILL.md into the skills folder of pine's home or of an agent; see docs/references/agents.md");
596
+ for (const s of list) {
597
+ out(`${s.name} ${s.scope === "global" ? "all agents" : s.scope === "agent" ? `agent ${s.agent}` : `conversation ${s.session} of ${s.agent}`}${s.managed ? "" : " [yours, from the configuration]"}`);
598
+ out(` ${s.description}`);
599
+ out(` ${s.dir}`);
600
+ }
601
+ return;
602
+ }
603
+ if (cmd === "check") {
604
+ out(`home ${cfg.home}`);
605
+ out(`http ${cfg.http ? `${cfg.http.host}:${cfg.http.port}, hooks: ${Object.keys(cfg.http.hooks).join(", ") || "none"}` : "off"}`);
606
+ out(`global mcp ${Object.keys(cfg.mcp).join(", ") || "none"}`);
607
+ out(`routes ${cfg.routes.length}, schedules ${cfg.schedules.length}`);
608
+ for (const a of Object.values(cfg.agents)) {
609
+ out(`\nagent ${a.id}${a.id === mainAgentId(cfg) ? " (main)" : ""}: ${a.description || "no description"}`);
610
+ out(` workspace ${a.workspace}`);
611
+ out(` model ${a.model ?? cfg.defaults.model}`);
612
+ out(` tools ${(a.tools ?? ["read", "bash", "edit", "write"]).join(", ")}`);
613
+ out(` mcp ${Object.keys(effectiveMcp(cfg, a)).join(", ") || "none"}`);
614
+ // App control is given by where pine runs and how far the agent reaches, not by the list above alone.
615
+ if (Object.values(effectiveMcp(cfg, a)).some((s) => s.pine === "computer")) {
616
+ out(` apps ${process.platform !== "darwin" ? "not on this system: app control works on macOS only" : !unsandboxed(levelOf(a)) ? "no: app control is for an agent in auto or bypass mode, which works with your whole account" : "it can operate the apps on this Mac in your own conversations; you are asked once per app"}`);
617
+ }
618
+ out(` skills ${listSkills(cfg, a, "main").map((s) => s.name).join(", ") || "none"}`);
619
+ out(` delegates ${a.delegates.join(", ") || "none"}; sub-agents ${a.subagents.enabled ? `up to ${a.subagents.maxParallel}` : "off"}`);
620
+ out(` mode ${a.mode}`);
621
+ // What that means for this agent, so that nobody has to read code to know.
622
+ const open = unsandboxed(levelOf(a));
623
+ const reach = open ? "your whole account and the network" : `its own folder${a.sandbox.network ? " and the network" : ""}`;
624
+ const after = cfg.security.taint === "off" ? "nothing changes" : "it keeps that; you are asked before it sends something out";
625
+ out(` reaches ${reach}`);
626
+ out(` after outside content: ${a.mode === "bypass" && cfg.security.bypassWhenTainted ? "nothing changes (bypass)" : after}`);
627
+ out(` sandbox ${open ? `off in ${levelOf(a)} mode; on for runs that events from outside start` : `on, network ${a.sandbox.network ? "allowed" : "blocked"}`}; untrusted events: ${a.untrusted === false ? "refused" : a.untrusted.tools.join(", ") || "no tools"}`);
628
+ }
629
+ const keys = modelKeys(cfg.home).problems;
630
+ if (keys.length)
631
+ out(`\nModel notes:\n${keys.map((k) => ` ! ${k}`).join("\n")}`);
632
+ const warnings = audit(cfg);
633
+ out(warnings.length ? `\nSecurity notes:\n${warnings.map((w) => ` ! ${w}`).join("\n")}` : "\nNo security notes.");
634
+ return;
635
+ }
636
+ if (cmd === "start") {
637
+ const { startPine } = await import("./pine.js");
638
+ // One misbehaving extension or MCP client must not take every agent down with it.
639
+ process.on("unhandledRejection", (e) => console.error(`${new Date().toISOString()} ERROR [pine] unhandled rejection: ${e instanceof Error ? (e.stack ?? e.message) : e}`));
640
+ process.on("uncaughtException", (e) => console.error(`${new Date().toISOString()} ERROR [pine] uncaught exception: ${e.stack ?? e.message}`));
641
+ const pine = await startPine({ config: cfg });
642
+ const stop = (sig) => {
643
+ console.error(`\n${sig} received, stopping`);
644
+ void pine.stop().then(() => process.exit(0));
645
+ setTimeout(() => process.exit(1), 10_000).unref();
646
+ };
647
+ process.on("SIGINT", () => stop("SIGINT"));
648
+ process.on("SIGTERM", () => stop("SIGTERM"));
649
+ return;
650
+ }
651
+ const api = client(cfg);
652
+ const qs = (o) => {
653
+ const p = Object.entries(o).filter(([, v]) => v !== undefined && v !== true && v !== false);
654
+ return p.length ? `?${p.map(([k, v]) => `${k}=${encodeURIComponent(String(v))}`).join("&")}` : "";
655
+ };
656
+ switch (cmd) {
657
+ case "status":
658
+ return out(await api.get("/status"));
659
+ case "agents":
660
+ return out(await api.get("/agents"));
661
+ case "send": {
662
+ const agent = rest.shift();
663
+ if (!agent || !rest.length)
664
+ throw new Error("usage: pine send <agent> <text...>");
665
+ const r = await api.post(`/agents/${agent}/prompt`, { prompt: rest.join(" "), session: flags.session, wait: flags.wait !== false });
666
+ if (flags.wait === false)
667
+ return out(`task #${r.task} queued`);
668
+ if (r.status !== "done")
669
+ throw new Error(`task #${r.id} ${r.status}: ${r.error ?? ""}`);
670
+ return out(r.text);
671
+ }
672
+ case "emit": {
673
+ if (!rest[0])
674
+ throw new Error("usage: pine emit <topic> [json]");
675
+ const r = await api.post("/events", { topic: rest[0], payload: rest[1] !== undefined ? JSON.parse(rest[1]) : null });
676
+ return out(`event #${r.id}`);
677
+ }
678
+ case "events": {
679
+ const events = await api.get(`/events${qs({ topic: flags.topic, limit: flags.limit ?? 30 })}`);
680
+ for (const e of events)
681
+ out(line(e));
682
+ if (!flags.follow)
683
+ return;
684
+ const res = await fetch(`${api.base}/events/stream${qs({ topic: flags.topic })}`, { headers: { authorization: `Bearer ${api.token}` } });
685
+ let buf = "";
686
+ for await (const chunk of res.body) {
687
+ buf += Buffer.from(chunk).toString("utf8");
688
+ for (let i = buf.indexOf("\n\n"); i >= 0; i = buf.indexOf("\n\n")) {
689
+ const block = buf.slice(0, i);
690
+ buf = buf.slice(i + 2);
691
+ if (block.startsWith("data: "))
692
+ out(line(JSON.parse(block.slice(6))));
693
+ }
694
+ }
695
+ return;
696
+ }
697
+ case "tasks": {
698
+ const tasks = await api.get(`/tasks${qs({ agent: flags.agent, status: flags.status, limit: flags.limit ?? 20 })}`);
699
+ for (const t of tasks.reverse())
700
+ out(`#${String(t.id).padEnd(5)} ${when(t.created)} ${t.status.padEnd(9)} ${`${t.agent}/${t.session}`.padEnd(26)} ${t.kind.padEnd(9)} ${String(t.meta?.label ?? t.prompt).replace(/\s+/g, " ").slice(0, 90)}`);
701
+ return;
702
+ }
703
+ case "task":
704
+ return out(await api.get(`/tasks/${rest[0]}`));
705
+ case "cancel":
706
+ return out(await api.post(`/tasks/${rest[0]}/cancel`));
707
+ case "state":
708
+ for (const s of (await api.get(`/state${qs({ key: rest[0] })}`)))
709
+ out(`${s.key} = ${JSON.stringify(s.value)} (${when(s.ts)}, ${s.source})`);
710
+ return;
711
+ case "sources": {
712
+ const list = await api.get("/sources");
713
+ if (!list.length)
714
+ return out(`no event sources configured (add "sources" to pine.json or an agent.json; see docs/references/sources.md)`);
715
+ for (const s of list) {
716
+ out(`${s.name}${s.scope === "global" ? "" : ` (of ${s.scope})`} ${s.type} ${s.error ? `not running: ${s.error}` : s.running ? "running" : "idle, nobody is subscribed"}${s.trust === "owner" ? " [yours]" : ""}`);
717
+ if (s.description)
718
+ out(` ${s.description}`);
719
+ if (s.status)
720
+ out(` ${s.status}`);
721
+ out(` subscribers: ${s.subscribers.join(", ") || "none"} · ${s.last ? `last event ${when(s.last.ts)} (${s.last.topic}), ${s.events} since start` : "no events since start"}`);
722
+ }
723
+ return;
724
+ }
725
+ case "subscribe":
726
+ case "unsubscribe": {
727
+ const details = { note: flags.note, throttle: flags.throttle, separate: flags.separate === true, when: typeof flags.when === "string" ? JSON.parse(flags.when) : undefined };
728
+ if (flags.global === true) {
729
+ if (!rest[0])
730
+ throw new Error(`usage: pine ${cmd} --global <source>`);
731
+ if (cmd === "unsubscribe")
732
+ return out((await api.post("/unsubscribe", { source: rest[0] })).unsubscribed ? `all agents: no longer subscribed to ${rest[0]}` : `there was no subscription of all agents to ${rest[0]}`);
733
+ const all = await api.post("/subscribe", { source: rest[0], ...details });
734
+ return out(`all agents are subscribed to ${rest[0]} (${all.running ? "running" : "not running"}); it wakes ${all.agents.join(", ") || "nobody yet"}, each in its main conversation`);
735
+ }
736
+ if (!rest[0] || !rest[1])
737
+ throw new Error(`usage: pine ${cmd} <agent> <source>${cmd === "subscribe" ? " [--session name] [--note text] [--throttle 5m] [--when json]" : " [--session name]"}\n pine ${cmd} --global <source>`);
738
+ if (cmd === "unsubscribe") {
739
+ const r = await api.post(`/agents/${rest[0]}/unsubscribe`, { source: rest[1], session: typeof flags.session === "string" ? flags.session : undefined });
740
+ return out(r.unsubscribed ? `${rest[0]} is no longer subscribed to ${rest[1]}${r.sessions.some((x) => x !== "main") ? ` (conversations: ${r.sessions.join(", ")})` : ""}` : `${rest[0]} was not subscribed to ${rest[1]}`);
741
+ }
742
+ const info = await api.post(`/agents/${rest[0]}/subscribe`, { source: rest[1], session: flags.session, ...details });
743
+ return out(`${rest[0]} is subscribed to ${rest[1]} (${info.running ? "running" : "not running"}); each event wakes it in its conversation "${info.session}"`);
744
+ }
745
+ case "approvals": {
746
+ const list = await api.get("/approvals");
747
+ if (!list.length)
748
+ return out("nothing waits for approval");
749
+ for (const a of list)
750
+ out(`${a.id} ${a.agent} (task #${a.task}) wants ${a.summary.split("\n")[0]}\n why: ${a.why}\n expires ${when(a.expires)}`);
751
+ return;
752
+ }
753
+ case "approve":
754
+ case "deny":
755
+ return out(await api.post(`/approvals/${rest[0]}`, { allow: cmd === "approve", always: flags.always === true }));
756
+ case "mode": {
757
+ if (!rest[0])
758
+ throw new Error("usage: pine mode <agent> [auto|safe|manual|bypass|plan]");
759
+ if (rest[1])
760
+ return out(await api.post(`/agents/${rest[0]}/mode`, { mode: rest[1] }));
761
+ const agent = (await api.get("/agents")).find((a) => a.id === rest[0]);
762
+ if (!agent)
763
+ throw new Error(`unknown agent "${rest[0]}"`);
764
+ return out(agent.mode);
765
+ }
766
+ case "reset":
767
+ if (!rest[0])
768
+ throw new Error("usage: pine reset <agent> [session]");
769
+ return out(await api.post(`/agents/${rest[0]}/reset`, { session: rest[1] }));
770
+ default:
771
+ throw new Error(`unknown command "${cmd}". Run "pine help".`);
772
+ }
773
+ }
774
+ main().catch((e) => {
775
+ console.error(e instanceof ConfigError ? e.message : `pine: ${e instanceof Error ? e.message : e}`);
776
+ process.exit(1);
777
+ });