@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/README.md +10 -0
- package/changes.json +19 -13
- package/docs/SKILL.md +1 -0
- package/docs/references/coding.md +2 -1
- package/docs/references/desktop.md +298 -0
- package/docs/references/operations.md +66 -2
- package/docs/references/security.md +8 -0
- package/docs/references/source-types.md +55 -6
- package/docs/references/tui.md +2 -0
- package/package.json +1 -1
- package/src/cli.js +49 -2
- package/src/http.d.ts +8 -0
- package/src/http.js +20 -4
- package/src/login.d.ts +11 -2
- package/src/login.js +11 -3
- package/src/owner.d.ts +87 -0
- package/src/owner.js +531 -0
- package/src/pine.js +1 -1
- package/src/service.d.ts +18 -0
- package/src/service.js +69 -0
- package/src/sources/slack.d.ts +9 -1
- package/src/sources/slack.js +297 -13
- package/src/tui/run.js +4 -41
- package/src/workspace-view.d.ts +28 -1
- package/src/workspace-view.js +87 -2
|
@@ -1050,7 +1050,7 @@ What you write yourself is never reported to you.
|
|
|
1050
1050
|
| `ignore` | | User ids that are never reported: a colleague's bot account, a channel's chatterbox. An app's id (`B...`) is taken too. What the token's own account writes (with a user token: you) is left out without being listed. |
|
|
1051
1051
|
| `sendTo` | none | Where an agent may write, by id only: channels (`"C0123ABCD"`) and people (`"U0123ABCD"`, a direct message). Without it the source only listens. Needs `token`. See "Sending" below. |
|
|
1052
1052
|
| `perMinute` | `60` | At most this many reports a minute, 1 to 600. What comes on top is counted and dropped, and the next report says how many were (`dropped`). |
|
|
1053
|
-
| `history` | `true` | With a `token`: an agent may read what was written earlier where the source listens (`read_source`),
|
|
1053
|
+
| `history` | `true` | With a `token`: an agent may read what was written earlier where the source listens (`read_source`), an answer in a thread comes with the messages it answers, and what was written while the source was not connected is asked for afterwards. `false` turns all three off. |
|
|
1054
1054
|
| `context` | `3` | How many earlier messages of a thread come with an answer in it, the thread's first message among them. `0` for none, `10` at most. |
|
|
1055
1055
|
| `maxMb` | `10` | Files that come with a message are fetched up to this size (50 at most). A larger one is named in the event, without a `path`. Needs `token`. |
|
|
1056
1056
|
| `keepDays` | `7` | Fetched files are deleted after this many days. |
|
|
@@ -1071,7 +1071,7 @@ shown where the sources are listed: `there is no channel named "opps" that the a
|
|
|
1071
1071
|
|
|
1072
1072
|
| `events` | Event | Fields | When |
|
|
1073
1073
|
|---|---|---|---|
|
|
1074
|
-
| `"message"` | `message` | `{ text, user, userName?, channel, channelName?, kind, ts, thread?, reply?, bot?, mention?, keyword?, from?, files?, images?, dropped? }` | Somebody wrote something that counts. |
|
|
1074
|
+
| `"message"` | `message` | `{ text, user, userName?, channel, channelName?, kind, ts, thread?, reply?, bot?, mention?, keyword?, from?, files?, images?, late?, dropped? }` | Somebody wrote something that counts. |
|
|
1075
1075
|
| `"reaction"` | `reaction` | `{ reaction, added, user, userName?, channel, channelName?, ts, author?, authorName? }` | Somebody put an emoji on a message (`added: true`) or took it away (`false`). `ts` is the message, `author` who wrote it. |
|
|
1076
1076
|
| `"edit"` | `edited` | `{ text, previous?, user, userName?, channel, channelName?, kind, ts, mention?, keyword?, from? }` | A message was changed. `previous` is what it said before. The preview Slack puts under a link is not an edit. |
|
|
1077
1077
|
| `"edit"` | `deleted` | `{ channel, channelName?, ts, previous? }` | A message was deleted. `previous` is what it said. |
|
|
@@ -1080,6 +1080,7 @@ shown where the sources are listed: `there is no channel named "opps" that the a
|
|
|
1080
1080
|
| `"pin"` | `pin` | `{ added, channel, channelName?, ts?, user, userName? }` | A message was pinned (`added: true`) or unpinned. |
|
|
1081
1081
|
| `"command"` | `command` | `{ command, text, user, userName?, channel, channelName? }` | Somebody typed a slash command of your app: `command` is `"/deploy"`, `text` what followed it. Whoever typed it reads "Passed on." |
|
|
1082
1082
|
| `"other"` | `event` | `{ type, data }` | Any other event your app is subscribed to. `type` is Slack's name for it, `data` the event as Slack sent it, cut at 4000 characters. |
|
|
1083
|
+
| always | `gap` | `{ text, from, to, seconds, found, looked, complete, missing? }` | The source was not connected for a minute or longer, and is again. `text` says it in a sentence. `complete: false` means that not everything from that time is known, and `missing` lists why. See "After a time without a connection". |
|
|
1083
1084
|
|
|
1084
1085
|
Any event can carry `dropped`: how many reports were left out before it, when more than
|
|
1085
1086
|
`perMinute` counted in a minute.
|
|
@@ -1096,6 +1097,7 @@ The fields of a `message`:
|
|
|
1096
1097
|
| `thread`, `reply` | For an answer in a thread: `reply: true`, and `thread` is the time stamp of the thread. `thread` is what `send` takes to answer in that thread. |
|
|
1097
1098
|
| `context` | For an answer in a thread: what it answers, as a list of `{ user, userName?, text, ts }`, oldest first. The thread's first message and the last ones before the answer, `context` of them (3). Not there with `history: false`, without a `token`, or when the app may not read history. |
|
|
1098
1099
|
| `bot` | `true` when an app or integration posted it. |
|
|
1100
|
+
| `late` | `true` when it was written while the source was not connected, and pine asked Slack for it afterwards. `ts` says when it was written. |
|
|
1099
1101
|
| `why` | Why it is reported, a word for each reason: `"dm"` (written to you directly), `"mention"`, `"keyword"`, `"from"` (its sender is on `from`), or `"channel"` when it is none of these and simply was written where the source listens. A list, since a message can be several: a subscription picks with `"payload.why": { "contains": "mention" }`. |
|
|
1100
1102
|
| `mention`, `keyword` | Which entry of `mentions` it mentions (for `"me"`: the id), and which word on `keywords` it contains. |
|
|
1101
1103
|
| `from` | `true` when its sender is on `from`. |
|
|
@@ -1161,13 +1163,16 @@ On api.slack.com/apps, "Create New App", "From scratch":
|
|
|
1161
1163
|
| names of people | | `users:read` |
|
|
1162
1164
|
| names of channels, and `channels` by name | | `channels:read`, and `groups:read` for private channels |
|
|
1163
1165
|
| the files of a message | | `files:read` |
|
|
1166
|
+
| what was written while it was not connected, in conversations it has seen a message in | | the `...:history` scope of that kind of conversation, which being told of messages there needs anyway |
|
|
1167
|
+
| the same in conversations it has not seen a message in yet (somebody who writes to you for the first time) | | `im:read` for direct conversations; without a list of `channels` also `channels:read`, `groups:read` and `mpim:read` |
|
|
1164
1168
|
| posting a message | | `chat:write` (and `chat:write.public` to post in a public channel the bot is not in) |
|
|
1165
1169
|
| a direct message to a person on `sendTo` | | `chat:write`, `im:write` |
|
|
1166
1170
|
| an emoji on a message | | `reactions:write` |
|
|
1167
1171
|
| sending a file | | `files:write` |
|
|
1168
1172
|
|
|
1169
1173
|
A scope that is missing does not stop the source, with one exception: a name is left out, a
|
|
1170
|
-
file has no `path`,
|
|
1174
|
+
file has no `path`, a `send` says which scope Slack wants, and after a time without a
|
|
1175
|
+
connection the `gap` event names what could not be looked at. The exception is a channel
|
|
1171
1176
|
given by its name, which cannot be found without `channels:read`.
|
|
1172
1177
|
|
|
1173
1178
|
A **bot token** (`xoxb-`) sees the channels the bot was invited to (`/invite @yourapp`) and
|
|
@@ -1238,9 +1243,9 @@ there writes /invite and its name`.
|
|
|
1238
1243
|
|
|
1239
1244
|
If the connection ends it is made again, as described under `stream` ("Staying connected").
|
|
1240
1245
|
Slack itself closes it now and then and says so beforehand; pine connects again at once.
|
|
1241
|
-
Slack is pinged every few seconds, so a line that died without a word is noticed.
|
|
1242
|
-
|
|
1243
|
-
to a call, pine waits as long as Slack says and asks again.
|
|
1246
|
+
Slack is pinged every few seconds, so a line that died without a word is noticed. A machine
|
|
1247
|
+
that slept does not trust the line it finds open when it wakes: pine connects again. When
|
|
1248
|
+
Slack says "slow down" to a call, pine waits as long as Slack says and asks again.
|
|
1244
1249
|
|
|
1245
1250
|
Where the sources are listed, the line says how things stand: `connected since 14:02:11.
|
|
1246
1251
|
listening to 2 channels and direct messages, for messages, reactions`, or `cannot connect
|
|
@@ -1248,6 +1253,50 @@ since 14:02:11 (3 attempts): Slack refused apps.connections.open: invalid_auth`.
|
|
|
1248
1253
|
that Slack does not take, and a channel name it does not know, are why a source does not
|
|
1249
1254
|
start at all.
|
|
1250
1255
|
|
|
1256
|
+
#### After a time without a connection
|
|
1257
|
+
|
|
1258
|
+
Slack does not send again what was written while nobody was connected: the machine was
|
|
1259
|
+
asleep, the network was gone, pine was not running. So pine notes when the connection last
|
|
1260
|
+
worked (also across a restart), and when it is connected again it asks Slack for what was
|
|
1261
|
+
written since, where the source listens and nowhere else:
|
|
1262
|
+
|
|
1263
|
+
- Each message that counts is reported like any other, with `late: true`, oldest first. An
|
|
1264
|
+
answer in a thread is found when the thread began among the last 50 messages of its channel.
|
|
1265
|
+
- After a minute or more, a `gap` event comes first:
|
|
1266
|
+
|
|
1267
|
+
```json
|
|
1268
|
+
{ "text": "Slack was not connected from 2026-03-02 14:02:11 to 2026-03-02 14:07:30 (5 minutes). 2 messages written in that time follow, marked \"late\". It looked through all 14 conversations it listens to.",
|
|
1269
|
+
"from": "2026-03-02 14:02:11", "to": "2026-03-02 14:07:30", "seconds": 319, "found": 2, "looked": 14, "complete": true }
|
|
1270
|
+
```
|
|
1271
|
+
|
|
1272
|
+
`complete: false` means that the time is not fully known, and `missing` says why, each reason
|
|
1273
|
+
a sentence. An agent that tells you what came in passes that on, and does not say "nothing
|
|
1274
|
+
new" for a time it could not look at:
|
|
1275
|
+
|
|
1276
|
+
| `missing` says | Why | What helps |
|
|
1277
|
+
|---|---|---|
|
|
1278
|
+
| `direct conversations this source had not seen a message in were not looked at (the app lacks the scope im:read)` | pine knows a conversation from the first message it saw in it. Which others there are, it has to ask Slack, and the app may not. The same for `public channels` (`channels:read`), `private channels` (`groups:read`) and `group conversations` (`mpim:read`) when the source has no list of `channels`. | Add the scope to the Slack app (for a user token among the User Token Scopes) and install the app again. |
|
|
1279
|
+
| `1 direct conversation could not be read (the app lacks the scope im:history)` | The app may not read what was written earlier in that kind of conversation. | Add that scope. |
|
|
1280
|
+
| `3 conversations could not be read (not_in_channel)` | Slack refused, in its own word, or could not be reached. | For `not_in_channel`: invite the app to the channel. |
|
|
1281
|
+
| `this source has no token, so it could not ask Slack what was written in that time` | Asking needs the `token`. | Set the source up again with a `token`. |
|
|
1282
|
+
| `this source was set up not to read what was written earlier ("history": false)` | | |
|
|
1283
|
+
| `2 more messages from that time were left out, since at most 60 are reported in a minute` | `perMinute`. | The agent reads the rest with `read_source`. |
|
|
1284
|
+
| `what else happened in that time (reactions, edits) cannot be asked for afterwards` | Slack keeps messages, and not who reacted, joined or edited when. A source that reports such things always says this. | |
|
|
1285
|
+
| `what the people on "from" wrote outside the listed channels was not looked for` | With a list of `channels`, only those and direct conversations are asked for. | |
|
|
1286
|
+
| `12 more conversations were not looked at: 200 is the most at once` | | |
|
|
1287
|
+
|
|
1288
|
+
A gap shorter than a minute (Slack renewing the connection, which it does now and then and
|
|
1289
|
+
which takes a moment) is made up for quietly: pine asks in the listed `channels` and in the conversations
|
|
1290
|
+
it has seen a message in, 40 at most, and reports no `gap`. After a longer one it also asks
|
|
1291
|
+
Slack which conversations there are, 200 at most. Reactions, edits and the other kinds are
|
|
1292
|
+
never made up for.
|
|
1293
|
+
|
|
1294
|
+
Where the sources are listed, the last gap is said too: `connected since 14:07:30. listening
|
|
1295
|
+
to ... Not connected from 2026-03-02 14:02:11 to 2026-03-02 14:07:30: not everything from
|
|
1296
|
+
then is known`. A subscription that picks with `when` (`"payload.why": { "contains":
|
|
1297
|
+
"mention" }`) is not woken by a `gap`, which has no `why`: an agent that is asked what came
|
|
1298
|
+
in looks at that line.
|
|
1299
|
+
|
|
1251
1300
|
#### Coming from the old Slack monitor
|
|
1252
1301
|
|
|
1253
1302
|
The OpenClaw plugin `openclaw-slack-monitor`:
|
package/docs/references/tui.md
CHANGED
|
@@ -710,3 +710,5 @@ mode 600, where agents cannot read it. The key you type is not echoed.
|
|
|
710
710
|
tasks run the next time a daemon starts.
|
|
711
711
|
- The UI is one of several ways in. Everything it does goes through the same events, tasks and
|
|
712
712
|
approvals as Telegram or `pine send`.
|
|
713
|
+
- On a Mac there is also an app with a window of its own, which shows the same conversations
|
|
714
|
+
and tabs and adds an editor and a settings panel: [desktop.md](desktop.md).
|
package/package.json
CHANGED
package/src/cli.js
CHANGED
|
@@ -28,6 +28,10 @@ Daemon
|
|
|
28
28
|
as administrator; --yes skips the question). Safe to run again
|
|
29
29
|
pine check validate the configuration and list what it sets up
|
|
30
30
|
pine start run the daemon in the foreground
|
|
31
|
+
pine service [--keep] for a UI that is a program of its own: find the running daemon or start one,
|
|
32
|
+
and say on one line of JSON where it answers and with which token. A daemon
|
|
33
|
+
it started runs until this command is ended or its input closes (--keep:
|
|
34
|
+
only until it is ended)
|
|
31
35
|
pine dev-model [--port 7464] [--model haiku]
|
|
32
36
|
OpenAI-compatible model server backed by "claude -p" (development only)
|
|
33
37
|
pine update [--check] bring pine up to date (npm for an install, git for a checkout) with what the
|
|
@@ -105,7 +109,7 @@ function parseArgs(argv) {
|
|
|
105
109
|
else if (a.startsWith("--no-"))
|
|
106
110
|
flags[a.slice(5)] = false;
|
|
107
111
|
else if (a.startsWith("--"))
|
|
108
|
-
flags[a.slice(2)] = argv[i + 1] !== undefined && !argv[i + 1].startsWith("--") && !["follow", "json", "api-key", "oauth", "taints", "offline", "always", "separate", "fresh", "global", "yes", "keep-files", "network"].includes(a.slice(2)) ? argv[++i] : true;
|
|
112
|
+
flags[a.slice(2)] = argv[i + 1] !== undefined && !argv[i + 1].startsWith("--") && !["follow", "json", "api-key", "oauth", "taints", "offline", "always", "separate", "fresh", "global", "yes", "keep-files", "network", "keep", "detach-stdin"].includes(a.slice(2)) ? argv[++i] : true;
|
|
109
113
|
else
|
|
110
114
|
rest.push(a);
|
|
111
115
|
}
|
|
@@ -379,7 +383,7 @@ async function installBrowser() {
|
|
|
379
383
|
const cli = path.join(path.dirname(createRequire(import.meta.url).resolve("playwright-core")), "cli.js");
|
|
380
384
|
return spawnSync(process.execPath, [cli, "install", "chromium"], { stdio: "inherit" }).status ?? 1;
|
|
381
385
|
}
|
|
382
|
-
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"]);
|
|
386
|
+
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", "service", "skills", "sources", "start", "state", "status", "subscribe", "task", "tasks", "tui", "unsubscribe", "update", "version"]);
|
|
383
387
|
/** 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. */
|
|
384
388
|
function folderArgument(word, cwd = process.cwd()) {
|
|
385
389
|
if (!word || COMMANDS.has(word))
|
|
@@ -493,6 +497,49 @@ async function main() {
|
|
|
493
497
|
process.on("SIGINT", () => void server.close().then(() => process.exit(0)));
|
|
494
498
|
return;
|
|
495
499
|
}
|
|
500
|
+
if (cmd === "service") {
|
|
501
|
+
// The answer is for a program: one line of JSON on stdout, whatever happens, and nothing else there.
|
|
502
|
+
const say = (o) => process.stdout.write(`${JSON.stringify(o)}\n`);
|
|
503
|
+
let service;
|
|
504
|
+
try {
|
|
505
|
+
if (!fs.existsSync(path.join(home, "pine.json")))
|
|
506
|
+
throw new Error(`there is no pine home at ${home} yet. Create one with: pine init${home === defaultHome() ? "" : ` ${home}`}`);
|
|
507
|
+
const cfg = loadConfig(home);
|
|
508
|
+
const { ensureDaemon } = await import("./service.js");
|
|
509
|
+
service = await ensureDaemon(cfg);
|
|
510
|
+
const version = String(JSON.parse(fs.readFileSync(path.join(PINE_ROOT, "package.json"), "utf8")).version);
|
|
511
|
+
say({ base: service.base, token: service.token, mode: service.mode, started: service.started, home: cfg.home, version });
|
|
512
|
+
}
|
|
513
|
+
catch (e) {
|
|
514
|
+
say({ error: e instanceof Error ? e.message : String(e) });
|
|
515
|
+
process.exit(1);
|
|
516
|
+
}
|
|
517
|
+
// A daemon that runs already goes on without this command.
|
|
518
|
+
if (!service.started)
|
|
519
|
+
process.exit(0);
|
|
520
|
+
process.on("unhandledRejection", (e) => console.error(`${new Date().toISOString()} ERROR [pine] unhandled rejection: ${e instanceof Error ? (e.stack ?? e.message) : e}`));
|
|
521
|
+
process.on("uncaughtException", (e) => console.error(`${new Date().toISOString()} ERROR [pine] uncaught exception: ${e.stack ?? e.message}`));
|
|
522
|
+
let stopping = false;
|
|
523
|
+
const stop = () => {
|
|
524
|
+
if (stopping)
|
|
525
|
+
return;
|
|
526
|
+
stopping = true;
|
|
527
|
+
void service.stop().then(() => process.exit(0));
|
|
528
|
+
setTimeout(() => process.exit(1), 10_000).unref();
|
|
529
|
+
};
|
|
530
|
+
process.on("SIGINT", stop);
|
|
531
|
+
process.on("SIGTERM", stop);
|
|
532
|
+
// The program that started this holds its input open for as long as it lives. When that
|
|
533
|
+
// closes, the program is gone, however it went, and its daemon is not left behind. A
|
|
534
|
+
// terminal's input is a person's: there Ctrl-C ends it.
|
|
535
|
+
if (flags.keep !== true && flags["detach-stdin"] !== true && !process.stdin.isTTY) {
|
|
536
|
+
process.stdin.on("end", stop);
|
|
537
|
+
process.stdin.on("close", stop);
|
|
538
|
+
process.stdin.on("error", stop);
|
|
539
|
+
process.stdin.resume();
|
|
540
|
+
}
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
496
543
|
if ((!cmd || cmd === "tui") && !fs.existsSync(path.join(home, "pine.json")))
|
|
497
544
|
return out(`No pine home at ${home} yet. Create one with:\n\n pine init\n\n${HELP}`);
|
|
498
545
|
const cfg = loadConfig(home);
|
package/src/http.d.ts
CHANGED
|
@@ -2,7 +2,10 @@ import type { AgentManager } from "./agents.ts";
|
|
|
2
2
|
import { type PineConfig } from "./config.ts";
|
|
3
3
|
import { type Approvals } from "./security.ts";
|
|
4
4
|
import type { Bus, State, TaskStore } from "./store.ts";
|
|
5
|
+
import { type LoginRunner } from "./owner.ts";
|
|
6
|
+
import type { Router } from "./router.ts";
|
|
5
7
|
import type { SourceHost } from "./sources.ts";
|
|
8
|
+
import type { Scheduler } from "./timers.ts";
|
|
6
9
|
import { type Logger } from "./util.ts";
|
|
7
10
|
/**
|
|
8
11
|
* Control API and webhooks. Every request except /health and /hook/* needs the bearer token.
|
|
@@ -22,6 +25,8 @@ export declare class HttpServer {
|
|
|
22
25
|
private hits;
|
|
23
26
|
port: number;
|
|
24
27
|
private sources?;
|
|
28
|
+
/** What the owner changes about pine's setup with their own hand (src/owner.ts). */
|
|
29
|
+
private owner;
|
|
25
30
|
constructor(deps: {
|
|
26
31
|
cfg: PineConfig;
|
|
27
32
|
bus: Bus;
|
|
@@ -30,8 +35,11 @@ export declare class HttpServer {
|
|
|
30
35
|
manager: AgentManager;
|
|
31
36
|
approvals: Approvals;
|
|
32
37
|
sources?: SourceHost;
|
|
38
|
+
schedules?: Scheduler;
|
|
39
|
+
router?: Router;
|
|
33
40
|
log: Logger;
|
|
34
41
|
token: string;
|
|
42
|
+
loginRunner?: LoginRunner;
|
|
35
43
|
});
|
|
36
44
|
start(): Promise<void>;
|
|
37
45
|
stop(): Promise<void>;
|
package/src/http.js
CHANGED
|
@@ -3,7 +3,8 @@ import http from "node:http";
|
|
|
3
3
|
import { mainAgentId } from "./config.js";
|
|
4
4
|
import { timingSafeEqual } from "./security.js";
|
|
5
5
|
import { addServer, listServers, removeServer } from "./mcp-config.js";
|
|
6
|
-
import { changes, diffOf, listDir, readText, findFiles } from "./workspace-view.js";
|
|
6
|
+
import { changes, diffOf, listDir, MAX_EDIT, readText, findFiles } from "./workspace-view.js";
|
|
7
|
+
import { OwnerApi, Refusal } from "./owner.js";
|
|
7
8
|
import { errText, topicMatches } from "./util.js";
|
|
8
9
|
const MAX_BODY = 1024 * 1024;
|
|
9
10
|
class HttpError extends Error {
|
|
@@ -31,8 +32,11 @@ export class HttpServer {
|
|
|
31
32
|
hits = new Map();
|
|
32
33
|
port = 0;
|
|
33
34
|
sources;
|
|
35
|
+
/** What the owner changes about pine's setup with their own hand (src/owner.ts). */
|
|
36
|
+
owner;
|
|
34
37
|
constructor(deps) {
|
|
35
38
|
this.sources = deps.sources;
|
|
39
|
+
this.owner = new OwnerApi({ cfg: deps.cfg, manager: deps.manager, sources: deps.sources, schedules: deps.schedules, router: deps.router, log: deps.log, loginRunner: deps.loginRunner });
|
|
36
40
|
this.cfg = deps.cfg;
|
|
37
41
|
this.bus = deps.bus;
|
|
38
42
|
this.state = deps.state;
|
|
@@ -58,6 +62,7 @@ export class HttpServer {
|
|
|
58
62
|
this.log.info(`http listening on ${host}:${this.port}`);
|
|
59
63
|
}
|
|
60
64
|
async stop() {
|
|
65
|
+
this.owner.stop();
|
|
61
66
|
this.server?.closeAllConnections?.();
|
|
62
67
|
await new Promise((r) => (this.server ? this.server.close(() => r()) : r()));
|
|
63
68
|
}
|
|
@@ -104,7 +109,8 @@ export class HttpServer {
|
|
|
104
109
|
if (parts[0] === "agents" && parts[2] === "sources" && parts.length === 3) {
|
|
105
110
|
if (!this.cfg.agents[parts[1]])
|
|
106
111
|
throw new HttpError(404, "no such agent");
|
|
107
|
-
|
|
112
|
+
// (For one conversation with `session`: what that conversation is subscribed to on its own is said too.)
|
|
113
|
+
return send(200, this.sources?.available(parts[1], q.get("session") ?? "main") ?? []);
|
|
108
114
|
}
|
|
109
115
|
if (parts[0] === "agents" && parts[2] === "sessions" && parts.length === 3) {
|
|
110
116
|
if (!this.cfg.agents[parts[1]])
|
|
@@ -167,7 +173,7 @@ export class HttpServer {
|
|
|
167
173
|
if (!root)
|
|
168
174
|
throw new HttpError(404, "no such agent");
|
|
169
175
|
const rel = q.get("path") ?? "";
|
|
170
|
-
const found = parts[3] === "find" ? { files: await findFiles(root, (q.get("q") ?? "").slice(0, 200)) } : parts[3] === "changes" ? { root, ...(await changes(root)) } : parts[3] === "diff" ? await diffOf(root, rel) : parts[3] === "tree" ? listDir(root, rel) : parts[3] === "file" ? readText(root, rel) : undefined;
|
|
176
|
+
const found = parts[3] === "find" ? { files: await findFiles(root, (q.get("q") ?? "").slice(0, 200)) } : parts[3] === "changes" ? { root, ...(await changes(root)) } : parts[3] === "diff" ? await diffOf(root, rel) : parts[3] === "tree" ? listDir(root, rel) : parts[3] === "file" ? readText(root, rel, q.has("max") ? Math.max(1, Math.min(MAX_EDIT, Math.floor(num("max") || 0))) : undefined) : undefined;
|
|
171
177
|
if (!found)
|
|
172
178
|
throw new HttpError(404, "nothing there");
|
|
173
179
|
return send(200, found);
|
|
@@ -184,13 +190,21 @@ export class HttpServer {
|
|
|
184
190
|
return send(200, this.state.list(q.get("key") ?? "#"));
|
|
185
191
|
if (url.pathname === "/approvals")
|
|
186
192
|
return send(200, this.approvals.pending());
|
|
193
|
+
const found = await this.owner.get(parts, q);
|
|
194
|
+
if (found !== undefined)
|
|
195
|
+
return send(200, found);
|
|
187
196
|
throw new HttpError(404, "not found");
|
|
188
197
|
}
|
|
189
198
|
if (method !== "POST")
|
|
190
199
|
throw new HttpError(405, "method not allowed");
|
|
191
200
|
// A message may carry attached files; everything else stays small.
|
|
192
201
|
const isPrompt = parts[0] === "agents" && parts[2] === "prompt" && parts.length === 3;
|
|
193
|
-
|
|
202
|
+
// (So does a file's text from an editor: what it may hold, and room for how JSON writes it.)
|
|
203
|
+
const isFile = parts[0] === "agents" && parts[2] === "view" && parts[3] === "write" && parts.length === 4;
|
|
204
|
+
const body = (await this.json(req, isPrompt ? 64 * MAX_BODY : isFile ? 8 * MAX_BODY : MAX_BODY));
|
|
205
|
+
const changed = await this.owner.post(parts, body, () => res.setTimeout(0));
|
|
206
|
+
if (changed !== undefined)
|
|
207
|
+
return send(200, changed);
|
|
194
208
|
if (url.pathname === "/images/fetch") {
|
|
195
209
|
if (typeof body.url !== "string")
|
|
196
210
|
throw new HttpError(400, "url required");
|
|
@@ -414,6 +428,8 @@ export class HttpServer {
|
|
|
414
428
|
throw new HttpError(404, "not found");
|
|
415
429
|
}
|
|
416
430
|
catch (e) {
|
|
431
|
+
if (e instanceof Refusal)
|
|
432
|
+
return send(e.status, { error: e.message, ...e.more });
|
|
417
433
|
const status = e instanceof HttpError ? e.status : /unknown agent|too many queued|does not accept|invalid topic|invalid state key|busy|is not defined in models.json|mode must be one of|at most 10 files|larger than 20 MB|inbox folder|can attach files|usable server name|MCP server needs|not a valid URL|must use https|reasoning level must be/.test(errText(e)) ? 400 : 500;
|
|
418
434
|
if (status === 500)
|
|
419
435
|
this.log.error("http request failed", e);
|
package/src/login.d.ts
CHANGED
|
@@ -4,6 +4,14 @@ export interface Prompter {
|
|
|
4
4
|
secret(message: string): Promise<string>;
|
|
5
5
|
say(line: string): void;
|
|
6
6
|
open(url: string): void;
|
|
7
|
+
/** A choice among a few, for a prompter that can show one. Without it the options are printed and a number is asked for. */
|
|
8
|
+
select?(message: string, options: Array<{
|
|
9
|
+
id: string;
|
|
10
|
+
label: string;
|
|
11
|
+
description?: string;
|
|
12
|
+
}>): Promise<string>;
|
|
13
|
+
/** A code to enter on a page, for a prompter that shows the two apart. Without it they are said in a line and the page is opened. */
|
|
14
|
+
device?(uri: string, code: string): void;
|
|
7
15
|
}
|
|
8
16
|
/**
|
|
9
17
|
* Read one line without showing it. The prompt stays on screen and says that the input is hidden,
|
|
@@ -19,5 +27,6 @@ export declare function knownProviders(cfg: PineConfig): Promise<string[]>;
|
|
|
19
27
|
* Sign in to a model provider with pi's own login flow and store the credential in
|
|
20
28
|
* <home>/auth.json (mode 600). Agents cannot read that file.
|
|
21
29
|
*/
|
|
22
|
-
export declare function login(cfg: PineConfig, provider: string, type?: "api_key" | "oauth", prompter?: Prompter): Promise<string[]>;
|
|
23
|
-
|
|
30
|
+
export declare function login(cfg: PineConfig, provider: string, type?: "api_key" | "oauth", prompter?: Prompter, signal?: AbortSignal): Promise<string[]>;
|
|
31
|
+
/** `say` is where the one line about it goes: the terminal for the command, nowhere for the daemon, which must not write to its output. */
|
|
32
|
+
export declare function logout(cfg: PineConfig, provider: string, say?: (line: string) => void): Promise<void>;
|
package/src/login.js
CHANGED
|
@@ -76,7 +76,7 @@ export async function knownProviders(cfg) {
|
|
|
76
76
|
* Sign in to a model provider with pi's own login flow and store the credential in
|
|
77
77
|
* <home>/auth.json (mode 600). Agents cannot read that file.
|
|
78
78
|
*/
|
|
79
|
-
export async function login(cfg, provider, type, prompter) {
|
|
79
|
+
export async function login(cfg, provider, type, prompter, signal) {
|
|
80
80
|
const rt = await runtime(cfg);
|
|
81
81
|
if (!rt.getProvider(provider))
|
|
82
82
|
throw new Error(`unknown provider "${provider}". Known: ${rt.getProviders().map((p) => p.id).sort().join(", ")}`);
|
|
@@ -85,9 +85,12 @@ export async function login(cfg, provider, type, prompter) {
|
|
|
85
85
|
try {
|
|
86
86
|
const kind = type ?? (OAUTH_FIRST.includes(provider) ? "oauth" : "api_key");
|
|
87
87
|
await rt.login(provider, kind, {
|
|
88
|
+
signal,
|
|
88
89
|
prompt: async (q) => {
|
|
89
90
|
if (q.type === "secret")
|
|
90
91
|
return p.secret(q.message);
|
|
92
|
+
if (q.type === "select" && p.select)
|
|
93
|
+
return p.select(q.message, q.options.map((o) => ({ id: o.id, label: o.label, description: o.description })));
|
|
91
94
|
if (q.type === "select") {
|
|
92
95
|
q.options.forEach((o, i) => p.say(` ${i + 1}) ${o.label}${o.description ? ` - ${o.description}` : ""}`));
|
|
93
96
|
const n = Number(await p.text(`${q.message} [1-${q.options.length}]`));
|
|
@@ -100,6 +103,8 @@ export async function login(cfg, provider, type, prompter) {
|
|
|
100
103
|
p.say(`Open this page to sign in:\n\n ${e.url}\n${e.instructions ? `\n${e.instructions}\n` : ""}`);
|
|
101
104
|
p.open(e.url);
|
|
102
105
|
}
|
|
106
|
+
else if (e.type === "device_code" && p.device)
|
|
107
|
+
p.device(e.verificationUri, e.userCode);
|
|
103
108
|
else if (e.type === "device_code") {
|
|
104
109
|
p.say(`Go to ${e.verificationUri} and enter the code ${e.userCode}`);
|
|
105
110
|
p.open(e.verificationUri);
|
|
@@ -122,9 +127,12 @@ export async function login(cfg, provider, type, prompter) {
|
|
|
122
127
|
p.say(`${head} ${models.length} models are available, for example:\n${models.slice(0, 8).map((m) => ` ${m}`).join("\n")}\n\nUse one with "defaults": { "model": "<provider/id>" } in pine.json, or /model in the terminal UI.`);
|
|
123
128
|
return models;
|
|
124
129
|
}
|
|
125
|
-
|
|
130
|
+
/** `say` is where the one line about it goes: the terminal for the command, nowhere for the daemon, which must not write to its output. */
|
|
131
|
+
export async function logout(cfg, provider, say = (line) => console.log(line)) {
|
|
126
132
|
const rt = await runtime(cfg);
|
|
133
|
+
if (!rt.getProvider(provider))
|
|
134
|
+
throw new Error(`unknown provider "${provider}". Known: ${rt.getProviders().map((p) => p.id).sort().join(", ")}`);
|
|
127
135
|
await rt.logout(provider);
|
|
128
136
|
await rt.settleCredentialWrites?.();
|
|
129
|
-
|
|
137
|
+
say(`Removed the stored credential for ${provider}.`);
|
|
130
138
|
}
|
package/src/owner.d.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import type { AgentManager } from "./agents.ts";
|
|
2
|
+
import { type PineConfig } from "./config.ts";
|
|
3
|
+
import { type Prompter } from "./login.ts";
|
|
4
|
+
import type { Router } from "./router.ts";
|
|
5
|
+
import type { SourceHost } from "./sources.ts";
|
|
6
|
+
import { type Scheduler } from "./timers.ts";
|
|
7
|
+
import { type Logger } from "./util.ts";
|
|
8
|
+
/** A request that is refused, with the status it is answered with and what a client needs besides the sentence. */
|
|
9
|
+
export declare class Refusal extends Error {
|
|
10
|
+
status: number;
|
|
11
|
+
more?: Record<string, unknown>;
|
|
12
|
+
constructor(status: number, message: string, more?: Record<string, unknown>);
|
|
13
|
+
}
|
|
14
|
+
/** What a UI is shown of a sign-in that is under way. */
|
|
15
|
+
export interface LoginView {
|
|
16
|
+
lines: string[];
|
|
17
|
+
url?: string;
|
|
18
|
+
code?: string;
|
|
19
|
+
question?: {
|
|
20
|
+
message: string;
|
|
21
|
+
secret: boolean;
|
|
22
|
+
options?: Array<{
|
|
23
|
+
id: string;
|
|
24
|
+
label: string;
|
|
25
|
+
description?: string;
|
|
26
|
+
}>;
|
|
27
|
+
};
|
|
28
|
+
done: boolean;
|
|
29
|
+
error?: string;
|
|
30
|
+
models?: string[];
|
|
31
|
+
}
|
|
32
|
+
/** What a sign-in is run with: pi's own flow, or a stand-in in a test. Returns the models the provider then has. */
|
|
33
|
+
export type LoginRunner = (provider: string, type: "api_key" | "oauth" | undefined, prompter: Prompter, signal: AbortSignal) => Promise<string[]>;
|
|
34
|
+
/**
|
|
35
|
+
* Sign-ins to model providers that a UI drives over several requests. pi's flow asks questions
|
|
36
|
+
* and waits (for a key to be typed, for a browser to come back): here each question is parked
|
|
37
|
+
* until the UI answers it, and what the flow says is kept for the UI to read. The browser is
|
|
38
|
+
* the client's to open, where the owner sits, so an address is only recorded. An answer is
|
|
39
|
+
* handed to the flow and kept nowhere.
|
|
40
|
+
*/
|
|
41
|
+
export declare class Logins {
|
|
42
|
+
private sessions;
|
|
43
|
+
private run;
|
|
44
|
+
private secret;
|
|
45
|
+
private ended;
|
|
46
|
+
constructor(run: LoginRunner, opts?: {
|
|
47
|
+
secret?: (value: string) => void;
|
|
48
|
+
ended?: () => Promise<void>;
|
|
49
|
+
});
|
|
50
|
+
private tidy;
|
|
51
|
+
start(provider: string, type?: "api_key" | "oauth"): string;
|
|
52
|
+
private end;
|
|
53
|
+
view(id: string): LoginView | undefined;
|
|
54
|
+
answer(id: string, value: string): boolean;
|
|
55
|
+
cancel(id: string): boolean;
|
|
56
|
+
stop(): void;
|
|
57
|
+
}
|
|
58
|
+
export interface OwnerDeps {
|
|
59
|
+
cfg: PineConfig;
|
|
60
|
+
manager: AgentManager;
|
|
61
|
+
sources?: SourceHost;
|
|
62
|
+
schedules?: Scheduler;
|
|
63
|
+
router?: Router;
|
|
64
|
+
log: Logger;
|
|
65
|
+
/** In place of pi's sign-in flow, for a test. */
|
|
66
|
+
loginRunner?: LoginRunner;
|
|
67
|
+
}
|
|
68
|
+
export declare class OwnerApi {
|
|
69
|
+
private cfg;
|
|
70
|
+
private manager;
|
|
71
|
+
private sources?;
|
|
72
|
+
private schedules?;
|
|
73
|
+
private router?;
|
|
74
|
+
private log;
|
|
75
|
+
readonly logins: Logins;
|
|
76
|
+
constructor(deps: OwnerDeps);
|
|
77
|
+
stop(): void;
|
|
78
|
+
private agent;
|
|
79
|
+
/** The agent a request names, or none when it names none (which means: for all agents). */
|
|
80
|
+
private maybeAgent;
|
|
81
|
+
private need;
|
|
82
|
+
/** A GET request. Undefined: not one of these. */
|
|
83
|
+
get(parts: string[], q: URLSearchParams): Promise<unknown | undefined>;
|
|
84
|
+
/** A POST request. Undefined: not one of these. `long` is called by a request that takes as long as a person does. */
|
|
85
|
+
post(parts: string[], body: any, long?: () => void): Promise<unknown | undefined>;
|
|
86
|
+
private change;
|
|
87
|
+
}
|