@pmndre/pine 0.35.2 → 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/owner.js ADDED
@@ -0,0 +1,531 @@
1
+ // What the owner does to pine's setup with their own hand, through the control API: the same
2
+ // things the main agent does by tool call when it is asked, and that the `pine` command does in
3
+ // the files. A UI that is only a client of the daemon offers them as a settings panel.
4
+ //
5
+ // There is no second road here. Each request is checked by the function that checks the tool's
6
+ // arguments and carried out by the function the tool calls after the owner said yes; what is
7
+ // missing is only the question, because the bearer token is the owner. Nothing in this file
8
+ // decides what is allowed.
9
+ import crypto from "node:crypto";
10
+ import fs from "node:fs";
11
+ import path from "node:path";
12
+ import { addRoute, applySetting, checkRoute, checkSetting, dropRoute, SETTINGS } from "./admin.js";
13
+ import { AGENT_TOOLS } from "./agent-admin.js";
14
+ import { loadConfig, mainAgentId, PINE_ROOT, SHARED_FILES } from "./config.js";
15
+ import { login, logout } from "./login.js";
16
+ import { findServer, piMcp, serverStates } from "./mcp-config.js";
17
+ import { addModelServer, checkServerName, listModelServers, lookAt, modelKeys, modelServerUsers, removeModelServer, serverUrl } from "./models.js";
18
+ import { audit, isInside, realish, sandboxAvailable } from "./security.js";
19
+ import { allSkills, checkSkill, deleteSkill, skillDir, skillsBeside, writeSkill } from "./skills.js";
20
+ import { localTime } from "./timers.js";
21
+ import { errText, parseDuration } from "./util.js";
22
+ import { MAX_EDIT, writeText } from "./workspace-view.js";
23
+ /** A request that is refused, with the status it is answered with and what a client needs besides the sentence. */
24
+ export class Refusal extends Error {
25
+ status;
26
+ more;
27
+ constructor(status, message, more) {
28
+ super(message);
29
+ this.status = status;
30
+ this.more = more;
31
+ }
32
+ }
33
+ /** The most text of an instruction file that is handed to a UI. */
34
+ const MAX_TEXT = 200_000;
35
+ const SHARED_ABOUT = {
36
+ "AGENTS.md": "Traits and behaviour for all agents: how every agent is to be and to act.",
37
+ "TOOLS.md": "Tooling for all agents: defaults and preferences for the tools, and other technical details of your setup.",
38
+ "USER.md": "What every agent knows about you.",
39
+ };
40
+ /**
41
+ * A file's text, if it is a file. A link is not followed: an agent's workspace is its own to
42
+ * write, and a link there must not make the daemon read something else out to a UI.
43
+ */
44
+ function textOf(file) {
45
+ let fd;
46
+ try {
47
+ fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
48
+ if (!fs.fstatSync(fd).isFile())
49
+ return undefined;
50
+ const buf = Buffer.alloc(Math.min(fs.fstatSync(fd).size, MAX_TEXT * 4));
51
+ fs.readSync(fd, buf, 0, buf.length, 0);
52
+ return buf.toString("utf8").slice(0, MAX_TEXT);
53
+ }
54
+ catch {
55
+ return undefined;
56
+ }
57
+ finally {
58
+ if (fd !== undefined)
59
+ fs.closeSync(fd);
60
+ }
61
+ }
62
+ /** A skill's instructions: its SKILL.md without the header that names it. */
63
+ const skillBody = (dir) => (textOf(path.join(dir, "SKILL.md")) ?? "").replace(/^---\n[\s\S]*?\n---\n*/, "").trimEnd();
64
+ const MAX_LOGINS = 4;
65
+ const KEEP_ENDED_MS = 5 * 60_000;
66
+ /**
67
+ * Sign-ins to model providers that a UI drives over several requests. pi's flow asks questions
68
+ * and waits (for a key to be typed, for a browser to come back): here each question is parked
69
+ * until the UI answers it, and what the flow says is kept for the UI to read. The browser is
70
+ * the client's to open, where the owner sits, so an address is only recorded. An answer is
71
+ * handed to the flow and kept nowhere.
72
+ */
73
+ export class Logins {
74
+ sessions = new Map();
75
+ run;
76
+ secret;
77
+ ended;
78
+ constructor(run, opts = {}) {
79
+ this.run = run;
80
+ this.secret = opts.secret ?? (() => { });
81
+ this.ended = opts.ended ?? (async () => { });
82
+ }
83
+ tidy() {
84
+ for (const [id, s] of this.sessions)
85
+ if (s.ended && Date.now() - s.ended > KEEP_ENDED_MS)
86
+ this.sessions.delete(id);
87
+ }
88
+ start(provider, type) {
89
+ this.tidy();
90
+ // One sign-in per provider: a second one takes the place of the first.
91
+ for (const s of this.sessions.values())
92
+ if (s.provider === provider && !s.done)
93
+ this.end(s, "another sign-in for this provider was started");
94
+ if ([...this.sessions.values()].filter((s) => !s.done).length >= MAX_LOGINS)
95
+ throw new Refusal(429, `${MAX_LOGINS} sign-ins are under way already. Finish or cancel one first`);
96
+ const id = crypto.randomBytes(9).toString("base64url");
97
+ const s = { provider, lines: [], done: false, abort: new AbortController() };
98
+ this.sessions.set(id, s);
99
+ const ask = (question) => new Promise((resolve, reject) => {
100
+ if (s.done)
101
+ return reject(new Error("cancelled"));
102
+ s.question = question;
103
+ s.answer = (value) => {
104
+ s.question = undefined;
105
+ s.answer = undefined;
106
+ if (question.secret)
107
+ this.secret(value);
108
+ resolve(value);
109
+ };
110
+ s.abort.signal.addEventListener("abort", () => reject(new Error("cancelled")), { once: true });
111
+ });
112
+ const prompter = {
113
+ text: (message) => ask({ message, secret: false }),
114
+ secret: (message) => ask({ message, secret: true }),
115
+ select: (message, options) => ask({ message, secret: false, options }),
116
+ say: (line) => {
117
+ if (s.lines.length < 200)
118
+ s.lines.push(String(line).slice(0, 2000));
119
+ },
120
+ open: (url) => {
121
+ s.url = url;
122
+ },
123
+ device: (uri, code) => {
124
+ s.url = uri;
125
+ s.code = code;
126
+ },
127
+ };
128
+ void this.run(provider, type, prompter, s.abort.signal).then(async (models) => {
129
+ if (s.done)
130
+ return;
131
+ s.models = models;
132
+ await this.ended().catch(() => { });
133
+ this.end(s);
134
+ }, (e) => this.end(s, errText(e)));
135
+ return id;
136
+ }
137
+ end(s, error) {
138
+ if (s.done)
139
+ return;
140
+ s.done = true;
141
+ s.ended = Date.now();
142
+ s.error = error;
143
+ s.question = undefined;
144
+ s.answer = undefined;
145
+ s.abort.abort();
146
+ }
147
+ view(id) {
148
+ this.tidy();
149
+ const s = this.sessions.get(id);
150
+ return s && { lines: s.lines, url: s.url, code: s.code, question: s.question, done: s.done, error: s.error, models: s.models };
151
+ }
152
+ answer(id, value) {
153
+ const s = this.sessions.get(id);
154
+ if (!s?.answer)
155
+ return false;
156
+ s.answer(value);
157
+ return true;
158
+ }
159
+ cancel(id) {
160
+ const s = this.sessions.get(id);
161
+ if (!s || s.done)
162
+ return false;
163
+ this.end(s, "cancelled");
164
+ return true;
165
+ }
166
+ stop() {
167
+ for (const s of this.sessions.values())
168
+ this.end(s, "pine is stopping");
169
+ }
170
+ }
171
+ export class OwnerApi {
172
+ cfg;
173
+ manager;
174
+ sources;
175
+ schedules;
176
+ router;
177
+ log;
178
+ logins;
179
+ constructor(deps) {
180
+ this.cfg = deps.cfg;
181
+ this.manager = deps.manager;
182
+ this.sources = deps.sources;
183
+ this.schedules = deps.schedules;
184
+ this.router = deps.router;
185
+ this.log = deps.log;
186
+ this.logins = new Logins(deps.loginRunner ?? ((provider, type, prompter, signal) => login(this.cfg, provider, type, prompter, signal)), {
187
+ // A key that was typed is a secret from then on, wherever it might turn up.
188
+ secret: (value) => this.sources?.keepOut([value]),
189
+ ended: () => this.manager.reloadModels(),
190
+ });
191
+ }
192
+ stop() {
193
+ this.logins.stop();
194
+ }
195
+ agent(id) {
196
+ const agent = typeof id === "string" ? this.cfg.agents[id] : undefined;
197
+ if (!agent)
198
+ throw new Refusal(404, `there is no agent "${String(id)}". Agents: ${Object.keys(this.cfg.agents).join(", ")}`);
199
+ return agent;
200
+ }
201
+ /** The agent a request names, or none when it names none (which means: for all agents). */
202
+ maybeAgent(id) {
203
+ return id === undefined || id === null || id === "" ? undefined : this.agent(id);
204
+ }
205
+ need(what, name) {
206
+ if (!what)
207
+ throw new Refusal(404, `this pine runs without ${name}`);
208
+ return what;
209
+ }
210
+ /** A GET request. Undefined: not one of these. */
211
+ async get(parts, q) {
212
+ const cfg = this.cfg;
213
+ const at = parts.join("/");
214
+ if (at === "overview") {
215
+ const pkg = JSON.parse(fs.readFileSync(path.join(PINE_ROOT, "package.json"), "utf8"));
216
+ return { version: String(pkg.version), home: cfg.home, main: mainAgentId(cfg), platform: process.platform, sandbox: sandboxAvailable(), warnings: audit(cfg), modelNotes: modelKeys(cfg.home).problems, log: path.join(cfg.dataDir, "pine.log") };
217
+ }
218
+ if (at === "settings") {
219
+ // What is saved and holds only from the next start is said beside what is in force.
220
+ let saved;
221
+ try {
222
+ saved = loadConfig(cfg.home);
223
+ }
224
+ catch {
225
+ // A file that does not load says nothing about what is saved.
226
+ }
227
+ return Object.entries(SETTINGS).map(([key, s]) => {
228
+ const now = s.now(cfg);
229
+ const next = saved ? s.now(saved) : now;
230
+ return { key, about: s.about, kind: s.kind, now, live: s.live, ...(next !== now ? { saved: next } : {}) };
231
+ });
232
+ }
233
+ if (parts[0] === "agents" && parts[2] === "detail" && parts.length === 3) {
234
+ const a = this.agent(parts[1]);
235
+ const file = (name) => textOf(path.join(a.workspace, name));
236
+ const files = { instructions: file("AGENTS.md"), soul: file("SOUL.md"), tooling: file("TOOLS.md"), memory: file("MEMORY.md"), rules: textOf(path.join(a.dir, "AGENTS.md")) };
237
+ return {
238
+ id: a.id, main: a.id === mainAgentId(cfg), description: a.description, workspace: a.workspace, dir: a.dir,
239
+ ...(a.model ? { model: a.model } : {}), defaultModel: cfg.defaults.model, thinking: a.thinking, mode: a.mode,
240
+ tools: a.tools ?? AGENT_TOOLS, allTools: AGENT_TOOLS, delegates: a.delegates, network: a.sandbox.network === true, read: a.sandbox.read, write: a.sandbox.write,
241
+ holdings: { ...this.manager.holdings(a.id), routes: cfg.routes.filter((r) => r.agent === a.id).map((r) => r.name) },
242
+ files: Object.fromEntries(Object.entries(files).filter(([, text]) => text !== undefined)),
243
+ };
244
+ }
245
+ if (at === "shared")
246
+ return SHARED_FILES.map((name) => ({ name, about: SHARED_ABOUT[name] ?? "", text: textOf(path.join(cfg.home, name)) ?? "" }));
247
+ if (at === "skills")
248
+ return allSkills(cfg).map((s) => ({ ...s, instructions: skillBody(s.dir) }));
249
+ if (at === "schedules")
250
+ return this.need(this.schedules, "a scheduler").list();
251
+ if (at === "routes")
252
+ return cfg.routes.map((r) => ({ name: r.name, on: r.on, when: r.when, throttleMs: r.throttleMs, debounceMs: r.debounceMs, agent: r.agent, prompt: r.prompt, session: r.session, set: r.set, publish: r.publish, call: r.call, trust: r.trust }));
253
+ if (at === "sources/types")
254
+ return this.need(this.sources, "event sources").typeList().map((t) => ({ name: t.name, summary: t.summary, options: t.options, own: t.name in cfg.sourceTypes }));
255
+ if (at === "models/servers")
256
+ return listModelServers(cfg.home);
257
+ if (at === "models/providers") {
258
+ // What pi says of each provider. `signedIn` is "pi has a credential or a key for it", which
259
+ // for a model server of the owner's own without a key is true as well; `oauth` is "its
260
+ // definition has a browser sign-in", whether or not that is how it is signed in now.
261
+ const rt = this.manager.models;
262
+ return rt.getProviders().map((p) => ({ id: p.id, name: p.name, signedIn: rt.hasConfiguredAuth(p.id), models: safe(() => p.getModels().length, 0), oauth: Boolean(p.auth?.oauth) })).sort((a, b) => Number(b.signedIn) - Number(a.signedIn) || a.id.localeCompare(b.id));
263
+ }
264
+ if (at === "mcp/states")
265
+ return serverStates(cfg);
266
+ if (parts[0] === "models" && parts[1] === "login" && parts.length === 3) {
267
+ const view = this.logins.view(parts[2]);
268
+ if (!view)
269
+ throw new Refusal(404, "there is no such sign-in (it ended a while ago, or pine was restarted). Start it again");
270
+ return view;
271
+ }
272
+ return undefined;
273
+ }
274
+ /** A POST request. Undefined: not one of these. `long` is called by a request that takes as long as a person does. */
275
+ async post(parts, body, long = () => { }) {
276
+ const at = parts.join("/");
277
+ const mine = ["settings", "shared", "skills", "skills/remove", "schedules", "schedules/remove", "routes", "routes/remove", "sources", "sources/propose", "sources/remove", "models/servers", "models/servers/remove", "models/login", "models/logout", "mcp/login"].includes(at) || (parts[0] === "models" && parts[1] === "login" && parts.length === 3) || (parts[0] === "agents" && parts[2] === "view" && parts[3] === "write" && parts.length === 4);
278
+ if (!mine)
279
+ return undefined;
280
+ try {
281
+ return await this.change(at, parts, body ?? {}, long);
282
+ }
283
+ catch (e) {
284
+ // What a checker says is wrong is the caller's to correct.
285
+ throw e instanceof Refusal ? e : new Refusal(400, errText(e));
286
+ }
287
+ }
288
+ async change(at, parts, body, long) {
289
+ const cfg = this.cfg;
290
+ const manager = this.manager;
291
+ const str = (v) => (typeof v === "string" && v !== "" ? v : undefined);
292
+ if (at === "settings") {
293
+ const key = String(body.key ?? "");
294
+ const checked = checkSetting(cfg, key, body.value, SETTINGS[key]?.kind === "model" ? await manager.availableModels() : []);
295
+ applySetting(cfg, checked);
296
+ if (checked.setting.live)
297
+ await manager.refreshSessions();
298
+ this.log.info(`setting ${checked.key} set to ${checked.text} through the control API`);
299
+ return { key: checked.key, now: checked.setting.live ? checked.setting.now(cfg) : checked.text, live: checked.setting.live };
300
+ }
301
+ if (at === "shared") {
302
+ // One of a fixed list of names, never a path.
303
+ if (!SHARED_FILES.includes(body.name))
304
+ throw new Refusal(400, `"${String(body.name)}" is not one of the files for all agents: ${SHARED_FILES.join(", ")}`);
305
+ if (typeof body.text !== "string")
306
+ throw new Refusal(400, "text: what the file is to hold");
307
+ if (body.text.length > MAX_TEXT)
308
+ throw new Refusal(400, `that is too long for a file every agent reads with every conversation (${body.text.length} characters, at most ${MAX_TEXT})`);
309
+ // The main agent may write this file too. What lies there is taken away and a new file
310
+ // made, never written through: it could be a link to somewhere else.
311
+ const target = path.join(cfg.home, body.name);
312
+ fs.rmSync(target, { force: true });
313
+ fs.writeFileSync(target, body.text && !body.text.endsWith("\n") ? `${body.text}\n` : body.text, { mode: 0o600, flag: "wx" });
314
+ return { ok: true };
315
+ }
316
+ if (at === "skills") {
317
+ const agent = this.maybeAgent(body.agent);
318
+ const scope = agent ? "agent" : "global";
319
+ const holder = agent ?? this.agent(mainAgentId(cfg));
320
+ const skill = checkSkill({ name: body.name, description: body.description, instructions: body.instructions }, holder.workspace);
321
+ const dir = skillDir(cfg, holder, scope, "main", skill.name);
322
+ const seen = skillsBeside(cfg, holder, scope, "main");
323
+ const there = seen.find((x) => x.name === skill.name && realish(x.dir) !== realish(dir));
324
+ if (there)
325
+ throw new Refusal(409, `a skill named "${skill.name}" exists already (${there.managed ? (there.scope === "global" ? "for all agents" : there.scope === "agent" ? "an agent's own" : "one conversation's own") : `yours, in ${there.dir}`}); pick another name${there.managed ? ", or remove that one first" : ""}`);
326
+ const replaced = fs.existsSync(dir);
327
+ writeSkill(dir, skill);
328
+ await manager.refreshSessions(agent ? [agent.id] : undefined);
329
+ return { name: skill.name, dir, replaced };
330
+ }
331
+ if (at === "skills/remove") {
332
+ const agent = this.maybeAgent(body.agent);
333
+ const session = str(body.session);
334
+ const found = allSkills(cfg).find((s) => s.name === body.name && (agent ? s.agent === agent.id && (session ? s.session === session : s.scope === "agent") : s.scope === "global"));
335
+ if (!found)
336
+ throw new Refusal(404, `there is no skill "${String(body.name)}" ${agent ? `of ${agent.id}${session ? ` in its conversation ${session}` : ""}` : "for all agents"}`);
337
+ if (!found.managed)
338
+ throw new Refusal(409, `"${found.name}" lies in a folder you named in the configuration (${found.dir}), and stays yours: take it out there`);
339
+ deleteSkill(found.dir, agent ? agent.dir : cfg.home);
340
+ await manager.refreshSessions(agent ? [agent.id] : undefined);
341
+ return { removed: true };
342
+ }
343
+ if (at === "schedules") {
344
+ const sched = this.need(this.schedules, "a scheduler");
345
+ const agent = this.maybeAgent(body.agent);
346
+ const given = [body.cron, body.every, body.at, body.in].filter((x) => x !== undefined && x !== null && x !== "");
347
+ if (given.length !== 1)
348
+ throw new Refusal(400, 'give exactly one of "cron" (set times), "every" (an interval), "at" (once, at a time) or "in" (once, after this long)');
349
+ if (str(body.every) && parseDuration(body.every) < 60_000)
350
+ throw new Refusal(400, '"every" must be at least "1m"');
351
+ let when;
352
+ if (str(body.in))
353
+ when = Date.now() + parseDuration(body.in);
354
+ if (body.at !== undefined && body.at !== null && body.at !== "") {
355
+ when = typeof body.at === "number" ? body.at : Date.parse(String(body.at).trim().replace(" ", "T"));
356
+ if (!Number.isFinite(when))
357
+ throw new Refusal(400, `"${body.at}" is not a time. Write it as 2026-12-24 17:00`);
358
+ if (when < Date.now() - 60_000)
359
+ throw new Refusal(400, `${body.at} is in the past: it is ${localTime(Date.now()).replace("T", " ")} now`);
360
+ }
361
+ if (str(body.session) && !agent)
362
+ throw new Refusal(400, '"session" names a conversation of an agent: give "agent" too');
363
+ const entry = sched.check({ name: body.name, task: body.task, cron: str(body.cron), every: str(body.every), at: when, session: agent ? str(body.session) : undefined });
364
+ return sched.add(agent?.id, entry);
365
+ }
366
+ if (at === "schedules/remove") {
367
+ const agent = this.maybeAgent(body.agent);
368
+ const removed = this.need(this.schedules, "a scheduler").remove(agent?.id, String(body.name ?? ""));
369
+ if (!removed)
370
+ throw new Refusal(404, `there is no schedule "${String(body.name)}" ${agent ? `of ${agent.id}` : "for all agents"}`);
371
+ return { removed };
372
+ }
373
+ if (at === "routes") {
374
+ const input = body;
375
+ const checked = checkRoute(cfg, input, input.call_model ? await manager.availableModels() : []);
376
+ this.router?.add(addRoute(cfg, checked.entry));
377
+ return { name: String(checked.entry.name), lines: checked.lines, ...(checked.wider ? { wider: checked.wider } : {}) };
378
+ }
379
+ if (at === "routes/remove") {
380
+ const found = cfg.routes.find((r) => r.name === body.name);
381
+ if (!found)
382
+ throw new Refusal(404, `there is no route "${String(body.name)}". ${cfg.routes.length ? `Routes: ${cfg.routes.map((r) => r.name).join(", ")}` : "There are no routes"}`);
383
+ dropRoute(cfg, found.name);
384
+ this.router?.remove(found.name);
385
+ return { removed: true };
386
+ }
387
+ if (at === "sources/propose" || at === "sources") {
388
+ const host = this.need(this.sources, "event sources");
389
+ const agent = this.maybeAgent(body.agent);
390
+ // A source for all agents is set up as the main agent would: a path is meant from its workspace.
391
+ const by = agent?.id ?? mainAgentId(cfg);
392
+ const name = String(body.name ?? "");
393
+ const type = String(body.type ?? "");
394
+ const options = body.options && typeof body.options === "object" && !Array.isArray(body.options) ? body.options : {};
395
+ if (at === "sources/propose") {
396
+ const plan = host.propose(by, name, type, options, !agent, Array.isArray(body.ask) ? body.ask.map(String) : []);
397
+ // What it would do, and what only the owner has. No option's value goes back: one of them may be a secret.
398
+ return { does: plan.does, opens: plan.opens, needs: plan.needs, ...(plan.owner ? { owner: true } : {}), ...(plan.tell ? { tell: plan.tell } : {}) };
399
+ }
400
+ // What the owner typed for what was needed: a secret from here on, checked by the type like any option.
401
+ const values = body.values && typeof body.values === "object" && !Array.isArray(body.values) ? Object.fromEntries(Object.entries(body.values).map(([k, v]) => [k, String(v)])) : {};
402
+ host.keepOut(Object.values(values));
403
+ const plan = host.propose(by, name, type, { ...options, ...values }, !agent, Array.isArray(body.ask) ? body.ask.map(String) : []);
404
+ if (plan.needs.length)
405
+ throw new Refusal(400, `this source needs you to enter ${plan.needs.map((n) => n.name).join(", ")}: send ${plan.needs.length === 1 ? "it" : "them"} in "values"`, { needs: plan.needs });
406
+ const entry = { type, description: String(body.description ?? ""), ...plan.options };
407
+ if (body.own === true || plan.owner)
408
+ entry.trust = "owner";
409
+ const made = host.add(agent?.id, name, entry, plan.read, plan.secrets);
410
+ if (plan.read)
411
+ await manager.refreshSessions([by]);
412
+ return { name, type: made.type, ...(plan.tell ? { tell: plan.tell } : {}) };
413
+ }
414
+ if (at === "sources/remove") {
415
+ const agent = this.maybeAgent(body.agent);
416
+ const gone = await this.need(this.sources, "event sources").remove(agent?.id, String(body.name ?? ""));
417
+ if (!gone.removed)
418
+ throw new Refusal(404, `there is no event source "${String(body.name)}" ${agent ? `of ${agent.id}` : "for all agents"}`);
419
+ if (agent)
420
+ await manager.refreshSessions([agent.id]);
421
+ return gone;
422
+ }
423
+ if (at === "models/servers") {
424
+ const baseUrl = serverUrl(String(body.url ?? ""));
425
+ const name = String(body.name ?? "");
426
+ checkServerName(name, manager.models.getProviders().map((p) => p.id));
427
+ const given = str(body.key);
428
+ if (given)
429
+ this.sources?.keepOut([given]);
430
+ // Asked without a key first: one that the server does not want is not kept.
431
+ let look = await lookAt(baseUrl);
432
+ let key;
433
+ if (look.locked) {
434
+ if (!given)
435
+ throw new Refusal(409, `${new URL(baseUrl).host} wants a key. Send it as "key"`, { locked: true });
436
+ look = await lookAt(baseUrl, given);
437
+ if (look.locked)
438
+ throw new Refusal(409, "the server did not accept that key. Nothing was added", { locked: true });
439
+ key = given;
440
+ }
441
+ const context = body.context === undefined || body.context === null || body.context === "" ? undefined : Number(body.context);
442
+ const models = addModelServer(cfg.home, { name, baseUrl, key, models: look.models, context, reasoning: typeof body.reasoning === "boolean" ? body.reasoning : undefined });
443
+ await manager.reloadModels();
444
+ return { models };
445
+ }
446
+ if (at === "models/servers/remove") {
447
+ const name = String(body.name ?? "");
448
+ if (!listModelServers(cfg.home).some((s) => s.name === name))
449
+ throw new Refusal(404, `there is no model server "${name}"`);
450
+ const users = modelServerUsers(cfg, name);
451
+ if (users.length)
452
+ throw new Refusal(409, `"${name}" is in use by ${users.join(", ")}. Give ${users.length === 1 ? "it" : "them"} another model first`, { users });
453
+ removeModelServer(cfg, name);
454
+ await manager.reloadModels();
455
+ return { removed: true };
456
+ }
457
+ if (at === "models/login") {
458
+ const provider = String(body.provider ?? "");
459
+ if (!manager.models.getProvider(provider))
460
+ throw new Refusal(400, `unknown provider "${provider}". GET /models/providers lists them`);
461
+ if (body.type !== undefined && body.type !== "api_key" && body.type !== "oauth")
462
+ throw new Refusal(400, '"type" is api_key or oauth; left out, the provider\'s usual way is taken');
463
+ return { id: this.logins.start(provider, body.type) };
464
+ }
465
+ if (parts[0] === "models" && parts[1] === "login" && parts.length === 3) {
466
+ if (body.cancel === true)
467
+ return { cancelled: this.logins.cancel(parts[2]) };
468
+ if (typeof body.answer !== "string")
469
+ throw new Refusal(400, 'send { "answer": "..." } for the question that is open, or { "cancel": true }');
470
+ if (!this.logins.view(parts[2]))
471
+ throw new Refusal(404, "there is no such sign-in. Start it again");
472
+ if (!this.logins.answer(parts[2], body.answer))
473
+ throw new Refusal(409, "this sign-in is not waiting for an answer right now");
474
+ return { ok: true };
475
+ }
476
+ if (at === "models/logout") {
477
+ await logout(cfg, String(body.provider ?? ""), () => { });
478
+ await manager.reloadModels();
479
+ return { ok: true };
480
+ }
481
+ if (at === "mcp/login") {
482
+ const name = String(body.name ?? "");
483
+ const agent = this.maybeAgent(body.agent);
484
+ const server = findServer(cfg, name, agent?.id);
485
+ if (!server)
486
+ throw new Refusal(404, `there is no MCP server "${name}"${agent ? ` of ${agent.id}` : ""}`);
487
+ if (!server.url)
488
+ throw new Refusal(400, `"${name}" is a local server; only a remote one has a sign-in`);
489
+ // It waits for a person in a browser.
490
+ long();
491
+ const done = await piMcp(cfg, { [name]: server }, ["login", name], { capture: true });
492
+ // Sessions that started before the sign-in do not have the server's tools yet.
493
+ if (done.code === 0)
494
+ await manager.refreshSessions();
495
+ return { code: done.code, out: done.out };
496
+ }
497
+ if (parts[0] === "agents" && parts[2] === "view" && parts[3] === "write") {
498
+ this.agent(parts[1]);
499
+ const root = manager.viewRoot(parts[1], str(body.session) ?? "main");
500
+ if (!root)
501
+ throw new Refusal(404, "no such agent");
502
+ if (typeof body.path !== "string" || typeof body.text !== "string")
503
+ throw new Refusal(400, "path and text required: the file, from the top of the folder, and what it is to hold");
504
+ if (Buffer.byteLength(body.text, "utf8") > MAX_EDIT)
505
+ throw new Refusal(413, `that is too much for one file here (at most ${MAX_EDIT} bytes)`);
506
+ // A conversation works in a folder of the owner's or in its agent's workspace. Neither is
507
+ // pine's home or pine's code, nor holds them: where one would be, nothing is written.
508
+ const base = realish(root);
509
+ for (const own of [realish(cfg.home), realish(PINE_ROOT)])
510
+ if (base === own || isInside(base, own))
511
+ throw new Refusal(403, "pine's own files are not written through a conversation's folder");
512
+ if (isInside(realish(PINE_ROOT), base))
513
+ throw new Refusal(403, "pine's own code is not written through a conversation's folder");
514
+ try {
515
+ return await writeText(root, body.path, body.text);
516
+ }
517
+ catch (e) {
518
+ throw new Refusal(409, errText(e));
519
+ }
520
+ }
521
+ throw new Refusal(404, "not found");
522
+ }
523
+ }
524
+ const safe = (fn, otherwise) => {
525
+ try {
526
+ return fn();
527
+ }
528
+ catch {
529
+ return otherwise;
530
+ }
531
+ };
package/src/pine.js CHANGED
@@ -114,7 +114,7 @@ export async function startPine(opts = {}) {
114
114
  pruner.unref();
115
115
  let http;
116
116
  if (cfg.http && opts.http !== false) {
117
- http = new HttpServer({ cfg, bus, state, tasks, manager: agents, approvals, sources, log: log.child("http"), token });
117
+ http = new HttpServer({ cfg, bus, state, tasks, manager: agents, approvals, sources, schedules: timers, router, log: log.child("http"), token });
118
118
  await http.start();
119
119
  }
120
120
  const warnings = audit(cfg);
@@ -0,0 +1,18 @@
1
+ import type { PineConfig } from "./config.ts";
2
+ export interface Service {
3
+ /** Where the control API answers. */
4
+ base: string;
5
+ token: string;
6
+ mode: "attached" | "embedded daemon" | "embedded daemon + claude -p";
7
+ /** Whether this process started the daemon, and so is the one that stops it. */
8
+ started: boolean;
9
+ /** Stops what was started here. A daemon that was only attached to goes on. */
10
+ stop(): Promise<void>;
11
+ }
12
+ /** Where a home's control API is reached from the same machine. */
13
+ export declare const controlBase: (cfg: PineConfig) => string;
14
+ /**
15
+ * The daemon of this home: the one that runs, or one started in this process (logging to
16
+ * data/pine.log), which `stop` ends again.
17
+ */
18
+ export declare function ensureDaemon(cfg: PineConfig): Promise<Service>;
package/src/service.js ADDED
@@ -0,0 +1,69 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ const reachable = async (url, headers) => {
4
+ try {
5
+ return (await fetch(url, { signal: AbortSignal.timeout(800), headers })).ok;
6
+ }
7
+ catch {
8
+ return false;
9
+ }
10
+ };
11
+ /** Where a home's control API is reached from the same machine. */
12
+ export const controlBase = (cfg) => `http://${cfg.http && cfg.http.host !== "0.0.0.0" ? cfg.http.host : "127.0.0.1"}:${cfg.http ? cfg.http.port : 0}`;
13
+ /**
14
+ * The daemon of this home: the one that runs, or one started in this process (logging to
15
+ * data/pine.log), which `stop` ends again.
16
+ */
17
+ export async function ensureDaemon(cfg) {
18
+ if (!cfg.http)
19
+ throw new Error('a UI needs the control API; remove "http": false from pine.json');
20
+ const base = controlBase(cfg);
21
+ if (await reachable(`${base}/health`)) {
22
+ // Something answers. It is this home's daemon only if it takes this home's token: a second
23
+ // home with the same port has a pine of its own there, and that one is not to be driven.
24
+ const tokenFile = path.join(cfg.dataDir, "http-token");
25
+ const token = cfg.http.token ?? (fs.existsSync(tokenFile) ? fs.readFileSync(tokenFile, "utf8").trim() : "");
26
+ if (!token || !(await reachable(`${base}/status`, { authorization: `Bearer ${token}` }))) {
27
+ throw new Error(`something answers on ${base}, but it is not the pine of ${cfg.home}: it does not take this home's token. Another pine home uses the same port. Stop that one, or give this home a port of its own ("http": { "port": ... } in ${path.join(cfg.home, "pine.json")}).`);
28
+ }
29
+ return { base, token, mode: "attached", started: false, stop: async () => { } };
30
+ }
31
+ const cleanup = [];
32
+ let mode = "embedded daemon";
33
+ // A provider called "dev" is the claude -p stand-in; bring it up too if nothing serves it.
34
+ try {
35
+ const models = JSON.parse(fs.readFileSync(path.join(cfg.home, "models.json"), "utf8"));
36
+ const dev = models.providers?.dev?.baseUrl;
37
+ const uses = [cfg.defaults.model, ...Object.values(cfg.agents).map((a) => a.model)].some((m) => m?.startsWith("dev/"));
38
+ if (dev && uses && !(await reachable(`${dev}/models`))) {
39
+ const { startClaudeModel } = await import("./dev/claude-model.js");
40
+ const server = await startClaudeModel({ port: Number(new URL(dev).port) });
41
+ cleanup.push(() => server.close());
42
+ mode = "embedded daemon + claude -p";
43
+ }
44
+ }
45
+ catch {
46
+ // No models.json or no dev provider: nothing to start.
47
+ }
48
+ try {
49
+ const { startPine } = await import("./pine.js");
50
+ const pine = await startPine({ config: cfg, logFile: path.join(cfg.dataDir, "pine.log") });
51
+ cleanup.push(() => pine.stop());
52
+ // (With port 0 the system picked one, and the configuration has it now.)
53
+ return {
54
+ base: controlBase(cfg),
55
+ token: pine.token,
56
+ mode,
57
+ started: true,
58
+ stop: async () => {
59
+ for (const fn of cleanup.splice(0).reverse())
60
+ await Promise.resolve(fn()).catch(() => { });
61
+ },
62
+ };
63
+ }
64
+ catch (e) {
65
+ for (const fn of cleanup.reverse())
66
+ await Promise.resolve(fn()).catch(() => { });
67
+ throw e;
68
+ }
69
+ }
@@ -4,13 +4,21 @@ import type { SourceApi } from "../sources.ts";
4
4
  * Times the tests set: what a second of "wait this long" from Slack lasts, how long a new
5
5
  * connection may take to be greeted, within what time Slack has to answer a ping (the SDK pings
6
6
  * three times in that time, and takes a connection without an answer for dead), and how long a
7
- * goodbye is waited for before the socket is cut.
7
+ * goodbye is waited for before the socket is cut. For the time it was not connected: how often
8
+ * it notes that the connection works (`beat`), how far before that note it asks Slack for what was
9
+ * written (`margin`: a line can be dead for a ping's time before anybody knows, and Slack's clock is
10
+ * not this machine's), from how long on a gap is reported (`quiet`), and the rest between two
11
+ * conversations when many are asked for (`between`).
8
12
  */
9
13
  export declare const pace: {
10
14
  second: number;
11
15
  hello: number;
12
16
  ping: number;
13
17
  bye: number;
18
+ beat: number;
19
+ margin: number;
20
+ quiet: number;
21
+ between: number;
14
22
  };
15
23
  export declare const type: SourceType;
16
24
  export default function slack(source: SourceApi): Promise<void>;