pi-durable-bot 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +279 -2
- package/dist/agent/agent.js +244 -0
- package/dist/agent/agent.js.map +1 -0
- package/dist/agent/judge.js +78 -0
- package/dist/agent/judge.js.map +1 -0
- package/dist/agent/models.js +72 -0
- package/dist/agent/models.js.map +1 -0
- package/dist/bot/bot.js +351 -0
- package/dist/bot/bot.js.map +1 -0
- package/dist/bot/control.js +67 -0
- package/dist/bot/control.js.map +1 -0
- package/dist/bot/definition.js +123 -0
- package/dist/bot/definition.js.map +1 -0
- package/dist/bot/machine.js +26 -0
- package/dist/bot/machine.js.map +1 -0
- package/dist/bot/prompt.js +169 -0
- package/dist/bot/prompt.js.map +1 -0
- package/dist/bot/timers.js +2 -0
- package/dist/bot/timers.js.map +1 -0
- package/dist/channels/load.js +21 -0
- package/dist/channels/load.js.map +1 -0
- package/dist/channels/slack/index.js +518 -0
- package/dist/channels/slack/index.js.map +1 -0
- package/dist/channels/slack/sdk.js +55 -0
- package/dist/channels/slack/sdk.js.map +1 -0
- package/dist/channels/terminal/index.js +19 -0
- package/dist/channels/terminal/index.js.map +1 -0
- package/dist/channels/test/index.js +197 -0
- package/dist/channels/test/index.js.map +1 -0
- package/dist/cli/agent.js +78 -0
- package/dist/cli/agent.js.map +1 -0
- package/dist/cli/ai.js +126 -0
- package/dist/cli/ai.js.map +1 -0
- package/dist/cli/bots.js +57 -0
- package/dist/cli/bots.js.map +1 -0
- package/dist/cli/chat.js +157 -0
- package/dist/cli/chat.js.map +1 -0
- package/dist/cli/control.js +52 -0
- package/dist/cli/control.js.map +1 -0
- package/dist/cli/init.js +104 -0
- package/dist/cli/init.js.map +1 -0
- package/dist/cli/pots.js +75 -0
- package/dist/cli/pots.js.map +1 -0
- package/dist/cli/service.js +228 -0
- package/dist/cli/service.js.map +1 -0
- package/dist/cli/trace.js +172 -0
- package/dist/cli/trace.js.map +1 -0
- package/dist/core/channel.js +52 -0
- package/dist/core/channel.js.map +1 -0
- package/dist/core/env-file.js +22 -0
- package/dist/core/env-file.js.map +1 -0
- package/dist/core/home.js +16 -0
- package/dist/core/home.js.map +1 -0
- package/dist/core/judge.js +2 -0
- package/dist/core/judge.js.map +1 -0
- package/dist/core/sql.js +2 -0
- package/dist/core/sql.js.map +1 -0
- package/dist/core/wake.js +2 -0
- package/dist/core/wake.js.map +1 -0
- package/dist/gateway/channels.js +69 -0
- package/dist/gateway/channels.js.map +1 -0
- package/dist/gateway/config.js +4 -0
- package/dist/gateway/config.js.map +1 -0
- package/dist/gateway/errors.js +54 -0
- package/dist/gateway/errors.js.map +1 -0
- package/dist/gateway/gateway.js +239 -0
- package/dist/gateway/gateway.js.map +1 -0
- package/dist/gateway/inbox.js +80 -0
- package/dist/gateway/inbox.js.map +1 -0
- package/dist/gateway/log.js +251 -0
- package/dist/gateway/log.js.map +1 -0
- package/dist/gateway/outbox.js +77 -0
- package/dist/gateway/outbox.js.map +1 -0
- package/dist/gateway/telemetry.js +131 -0
- package/dist/gateway/telemetry.js.map +1 -0
- package/dist/gateway/timers.js +121 -0
- package/dist/gateway/timers.js.map +1 -0
- package/dist/gateway/tracing.js +187 -0
- package/dist/gateway/tracing.js.map +1 -0
- package/dist/gateway/waker.js +226 -0
- package/dist/gateway/waker.js.map +1 -0
- package/dist/main.js +148 -0
- package/dist/main.js.map +1 -0
- package/docs/channels/slack-app-manifest.yaml +54 -0
- package/docs/channels/slack.md +22 -0
- package/package.json +61 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Crokily
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,280 @@
|
|
|
1
|
-
|
|
1
|
+
<div align="center">
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<img src="docs/media/logo.png" width="112" alt="Pots logo">
|
|
4
|
+
|
|
5
|
+
# pi-durable-bot (Pots)
|
|
6
|
+
|
|
7
|
+
**The open-source AI coworker that acts on its own.**
|
|
8
|
+
|
|
9
|
+
It reads every channel, email and event you give it, decides what matters,<br>
|
|
10
|
+
does the work on its own computer, and speaks up when it should.
|
|
11
|
+
|
|
12
|
+
[Demo](#see-it-work) · [Quick start](#quick-start) · [How it decides](#how-it-decides-to-act) · [Open and yours](#open-and-yours) · [How it works](#how-it-works)
|
|
13
|
+
|
|
14
|
+
[](https://www.npmjs.com/package/pi-durable-bot)
|
|
15
|
+
[](#quick-start)
|
|
16
|
+
[](LICENSE)
|
|
17
|
+
[](https://github.com/earendil-works/pi)
|
|
18
|
+
[](https://chat-sdk.dev)
|
|
19
|
+
[](https://nodejs.org)
|
|
20
|
+
|
|
21
|
+
</div>
|
|
22
|
+
|
|
23
|
+
<p align="center" id="see-it-work">
|
|
24
|
+
<a href="docs/media/demo.mp4"><img src="docs/media/demo.gif" width="900" alt="Pots reads Slack, email, Discord, X and calendars on its own, decides what matters, speaks up in #pricing, and does real work on its own computer"></a>
|
|
25
|
+
</p>
|
|
26
|
+
|
|
27
|
+
Grok Bot, dots and Claude Tag showed what an AI teammate can be. pi-durable-bot gives you the same kind of coworker as open source: it runs on your machine, with the model you choose, in the places your team already talks.
|
|
28
|
+
|
|
29
|
+
## Not a bot. A coworker.
|
|
30
|
+
|
|
31
|
+
Most AI bots are a command line with a chat bubble. You @ them, they answer, they forget. A real coworker works differently:
|
|
32
|
+
|
|
33
|
+
| | A chat bot | pi-durable-bot |
|
|
34
|
+
|---|---|---|
|
|
35
|
+
| **What it sees** | The message that mentions it | Everything in the places it was invited to: chats, DMs, emails, events, pages it watches |
|
|
36
|
+
| **When it acts** | When you @ it | When it decides it should. It can also answer when you @ it |
|
|
37
|
+
| **What it remembers** | This thread, maybe | One long memory across every channel, kept on disk |
|
|
38
|
+
| **How it works** | Calls the tools someone wired in | Writes and runs its own code on its own computer |
|
|
39
|
+
| **What happens later** | Nothing | It sets its own reminders and comes back |
|
|
40
|
+
| **After a crash** | Starts over, or sends twice | Picks up where it stopped. Never sends the same message twice |
|
|
41
|
+
|
|
42
|
+
## What it does
|
|
43
|
+
|
|
44
|
+
### 📥 Its own inbox
|
|
45
|
+
|
|
46
|
+
Every message in every place you invite it to lands in one inbox: channel messages that never mention it, edits, deletions, reactions, people joining, and its own messages. It keeps all of it in a local SQLite log and reads that log with SQL whenever it needs context. Nothing is thrown away when a conversation gets long.
|
|
47
|
+
|
|
48
|
+
### 🧠 Its own judgment
|
|
49
|
+
|
|
50
|
+
It is woken in three ways, the same three ways a person notices work:
|
|
51
|
+
|
|
52
|
+
| | Like a coworker who... | How |
|
|
53
|
+
|---|---|---|
|
|
54
|
+
| **Someone asks** | gets a message or an @ | A mention or a DM wakes it at once (after a short pause, so you can finish typing) |
|
|
55
|
+
| **It notices** | overhears something that is their job | A judge reads each message that does not mention it and asks two questions: *is this about me?* and *should I respond?* It sees the bot's own list of responsibilities. The judge is the bot's own model, a fast classifier such as TypeSafe's Jev, or a local model |
|
|
56
|
+
| **It checks in** | looks around now and then, and keeps promises | It sets its own timed wakes: "check Acme's pricing every Monday", "follow up at 5 pm". If it has none, it looks around every two hours |
|
|
57
|
+
|
|
58
|
+
Being woken is not the same as speaking. Each time, the agent reads the log and decides if it should say anything, where, and when. Most of the time the right answer is to stay quiet.
|
|
59
|
+
|
|
60
|
+
### 💻 Its own computer
|
|
61
|
+
|
|
62
|
+
It has a real machine with a shell, files, the internet, and a screen it uses like a person: the browser and the apps on it, with the mouse and keyboard. It does not wait for a plugin. It writes the script it needs, runs it, fixes it, and keeps the useful ones. That covers research, spreadsheets, reports, monitoring a web page, filling a form, or booking a flight, and also code.
|
|
63
|
+
|
|
64
|
+
This is **code mode**: the agent gets a few general tools (`read`, `write`, `edit`, `bash`) plus three channel actions (`send`, `react`, `call`), and builds the rest itself.
|
|
65
|
+
|
|
66
|
+
### 💬 Its own voice
|
|
67
|
+
|
|
68
|
+
When it speaks, it speaks like a teammate: in the right channel or thread, in its own words, with the file attached. It can reply in a thread, start a new message, DM a person, add a reaction, edit its own message, or call any other platform API.
|
|
69
|
+
|
|
70
|
+
### ⏰ Its own schedule
|
|
71
|
+
|
|
72
|
+
It promises to come back, and it does. Timed wakes live in the same database as everything else, so they survive restarts. It can also add normal cron jobs on its machine.
|
|
73
|
+
|
|
74
|
+
### 📓 Its own memory
|
|
75
|
+
|
|
76
|
+
Each bot has one long conversation, across every channel. When the context gets full, the bot decides when to **turn the page**: it writes notes for itself, starts a fresh context, and the notes come with it. The full message log stays on disk, so nothing is lost. Its persona, its responsibilities and its notes are plain files it edits itself.
|
|
77
|
+
|
|
78
|
+
### 🛟 Durable by design
|
|
79
|
+
|
|
80
|
+
Built on [pi-durable](https://github.com/earendil-works/pi), every step is journaled. Kill the process in the middle of a task and it continues after restart. Every incoming event is written to disk before it is acknowledged. Every outgoing message carries a send ID, and after a crash the bot checks whether the message already went out before it sends again.
|
|
81
|
+
|
|
82
|
+
## Open and yours
|
|
83
|
+
|
|
84
|
+
Grok Bot, dots, Muse and Claude Duet are closed products. They run on someone else's computer, with someone else's model, inside the apps they chose. pi-durable-bot is MIT-licensed and runs where you put it.
|
|
85
|
+
|
|
86
|
+
| | Closed AI coworkers | pi-durable-bot |
|
|
87
|
+
|---|---|---|
|
|
88
|
+
| Source code | Closed | Open, MIT |
|
|
89
|
+
| Where it runs | The vendor's cloud | Your server, your VM, your office box |
|
|
90
|
+
| Model | The vendor's | Your subscription login, any of 40+ providers, or a local model |
|
|
91
|
+
| Your data | Sent to the vendor | Stays on your machine in one SQLite file per bot |
|
|
92
|
+
| Channels | The ones the vendor supports | Any channel with a [Chat SDK](https://chat-sdk.dev) adapter |
|
|
93
|
+
| Custom work | What the vendor allows | Anything. Change the code, add tools, connect your own systems |
|
|
94
|
+
|
|
95
|
+
**Any model.** Log in once with a subscription you already pay for, use an API key from any of the 40+ providers [pi](https://github.com/earendil-works/pi) supports, point it at any OpenAI-compatible endpoint (vLLM, SGLang, a proxy), or run a local model with Ollama, LM Studio or llama.cpp. The bot uses pi's own model layer, so every model pi can use, the bot can use. With a local model for the agent and the judge, nothing leaves your machine. You are not locked to one model vendor.
|
|
96
|
+
|
|
97
|
+
**Any channel.** The core speaks in five plain words: channel, place, thread, message, person. Platform details stay inside one adapter per platform, so adding Discord, Teams, Telegram or email is one adapter, not a rewrite. One bot can be in many channels and stays the same person everywhere.
|
|
98
|
+
|
|
99
|
+
**Your business.** Give it your own tools, data and workflows. It can run several bots on one machine, each with its own name, persona, responsibilities and memory. A bot can even edit its own definition, or create a new bot.
|
|
100
|
+
|
|
101
|
+
## Quick start
|
|
102
|
+
|
|
103
|
+
> [!IMPORTANT]
|
|
104
|
+
> The bot gets full control of the computer it runs on, with no approval step. Give it a computer or VM of its own.
|
|
105
|
+
|
|
106
|
+
You need [Node.js](https://nodejs.org) 24 or newer, on macOS, Linux or Windows (with [Git for Windows](https://git-scm.com/download/win)).
|
|
107
|
+
|
|
108
|
+
```sh
|
|
109
|
+
npm install -g pi-durable-bot
|
|
110
|
+
pots init
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
`pots init` asks three things:
|
|
114
|
+
|
|
115
|
+
1. **Your bot's name.**
|
|
116
|
+
2. **Its AI.** Sign in with a subscription you already pay for (ChatGPT, Claude, GitHub Copilot, Grok, Kimi and more), use an API key, or point it at a local server (Ollama, LM Studio, llama.cpp).
|
|
117
|
+
3. **In one sentence, what it is for.** Optional. The bot writes its own persona and responsibilities from it.
|
|
118
|
+
|
|
119
|
+
Then the gateway starts as a background service (it starts again at login) and you are talking to your bot in the terminal. It first checks that it can use the computer's screen and walks you through any permission it needs, such as Screen Recording and Accessibility on a Mac. On a server with no desktop, it works without a screen and asks you before it sets one up. Tell it which chat apps to join. It sets them up itself on its computer and asks you only for what it cannot do, like signing in to Slack or approving the app. Leave with Ctrl+C; come back with `pots chat`.
|
|
120
|
+
|
|
121
|
+
It joins only the places it is invited to, like a new hire who is added to the right channels.
|
|
122
|
+
|
|
123
|
+
| Command | What it does |
|
|
124
|
+
|---|---|
|
|
125
|
+
| `pots init` | Set up your first bot, or another one |
|
|
126
|
+
| `pots chat` | Talk to a bot in this terminal |
|
|
127
|
+
| `pots status` | The gateway, the service and each bot |
|
|
128
|
+
| `pots service install \| uninstall \| restart \| logs` | The gateway as a background service: launchd on macOS, systemd on Linux (`--system` for a server), Task Scheduler on Windows |
|
|
129
|
+
| `pots start` | Run the gateway in this terminal instead |
|
|
130
|
+
| `pots bot new \| list` | Create and list bots |
|
|
131
|
+
| `pots trace` | What a bot did: its last wakes, or one wake from the events to its run and the messages it sent |
|
|
132
|
+
|
|
133
|
+
To upgrade, run `npm install -g pi-durable-bot@latest`, then `pots service restart`. To remove it, run `pots service uninstall`, then `npm uninstall -g pi-durable-bot`. The bots stay in `~/.pots/` until you delete that folder.
|
|
134
|
+
|
|
135
|
+
### Choose the models
|
|
136
|
+
|
|
137
|
+
`pots init` sets up the model. Each bot's `bot.json` names two models, and you can change them at any time; edits apply within seconds. Logins, API keys and local endpoints are stored in pi's files in `~/.pi/agent/`, so the [pi](https://github.com/earendil-works/pi) command line, if you use it, shares them.
|
|
138
|
+
|
|
139
|
+
| Field | What it does | Values |
|
|
140
|
+
|---|---|---|
|
|
141
|
+
| `model` | The agent that reads, thinks and acts | Any pi model as `provider/modelId`, for example `openai/gpt-6.1-sol` or `anthropic/claude-opus-5-5` |
|
|
142
|
+
| `judge` | Decides which messages that do not mention the bot should wake it | `main` (default): the bot's own model judges, no extra account<br>`provider/modelId` of a classifier: `typesafe/jev-latest`, `openrouter/typesafe/jev-1.14`, `opencode/jev-1.13-free`, or a llama.cpp model<br>`off`: every message wakes the bot, and the agent decides |
|
|
143
|
+
|
|
144
|
+
A fast classifier is cheaper and quicker than the main model: Jev answers in about 0.3 seconds. With `main`, each group of messages costs one short request to the main model.
|
|
145
|
+
|
|
146
|
+
**OpenAI-compatible and local endpoints** (Ollama, LM Studio, vLLM, a proxy): `pots init` adds them for you. By hand, they go in pi's `~/.pi/agent/models.json` ([fields](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/models.md)):
|
|
147
|
+
|
|
148
|
+
```json
|
|
149
|
+
{
|
|
150
|
+
"providers": {
|
|
151
|
+
"ollama": {
|
|
152
|
+
"baseUrl": "http://localhost:11434/v1",
|
|
153
|
+
"api": "openai-completions",
|
|
154
|
+
"apiKey": "ollama",
|
|
155
|
+
"compat": { "supportsDeveloperRole": false, "supportsReasoningEffort": false },
|
|
156
|
+
"models": [{ "id": "qwen3:8b", "contextWindow": 32768 }]
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
Then set `"model": "ollama/qwen3:8b"`. The agent needs a model that calls tools well and a context window of 32K tokens or more. In our tests a 4B model judged well but was too small to do the work alone; use the largest model your machine runs well.
|
|
163
|
+
|
|
164
|
+
**llama.cpp** can be both the agent and the judge. Start `llama-server` in router mode, then log in once with the pi command line: run `pi`, then `/login llama.cpp` ([guide](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/llama-cpp.md)). Its chat models appear as `llama.cpp/<model>`. For the judge, use a decision model such as [Kev-4B](https://huggingface.co/ggml-org/Kev-4B-GGUF) (3 GB), which answers through llama.cpp's `/v1/systemone`; any chat model also works as a judge.
|
|
165
|
+
|
|
166
|
+
```json
|
|
167
|
+
{ "model": "llama.cpp/<your chat model>", "judge": "llama.cpp/Kev-4B-Q4_K_M" }
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
## How it decides to act
|
|
171
|
+
|
|
172
|
+
```mermaid
|
|
173
|
+
flowchart LR
|
|
174
|
+
E[New event] --> L[(Message log)]
|
|
175
|
+
E --> M{Mention or DM?}
|
|
176
|
+
M -- yes --> W[Wake the agent]
|
|
177
|
+
M -- no --> J{Judge: about me?<br/>need to respond?}
|
|
178
|
+
J -- yes --> W
|
|
179
|
+
J -- no --> Q[Stay quiet, remember it]
|
|
180
|
+
T[Its own timers] --> W
|
|
181
|
+
W --> A{Agent reads the log<br/>and decides}
|
|
182
|
+
A --> S[Speak, react or act]
|
|
183
|
+
A --> N[Do nothing]
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
- Messages that arrive close together are grouped: it waits 3 seconds after the last one (20 seconds at most) before it judges.
|
|
187
|
+
- If it is already working in a place, new messages there are handed to it as it works, so it can change course.
|
|
188
|
+
- The wake message says only where, who, why and when. The agent reads the content itself.
|
|
189
|
+
|
|
190
|
+
## How it works
|
|
191
|
+
|
|
192
|
+
```mermaid
|
|
193
|
+
flowchart LR
|
|
194
|
+
subgraph Adapters[Channel adapters]
|
|
195
|
+
S[Slack]
|
|
196
|
+
T[Terminal]
|
|
197
|
+
D[Discord, Teams, ...]
|
|
198
|
+
end
|
|
199
|
+
subgraph Gateway[Gateway core, one per bot]
|
|
200
|
+
I[Inbox] --> G[(Message log)]
|
|
201
|
+
G --> K[Waker]
|
|
202
|
+
O[Outbox]
|
|
203
|
+
end
|
|
204
|
+
subgraph Bot[Bot]
|
|
205
|
+
P[Persona, responsibilities, notes, timers]
|
|
206
|
+
A[pi-durable agent<br/>read write edit bash<br/>send react call]
|
|
207
|
+
end
|
|
208
|
+
S --> I
|
|
209
|
+
T --> I
|
|
210
|
+
D --> I
|
|
211
|
+
K --> A
|
|
212
|
+
A --> O
|
|
213
|
+
O --> S
|
|
214
|
+
O --> T
|
|
215
|
+
O --> D
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
| Layer | Job |
|
|
219
|
+
|---|---|
|
|
220
|
+
| Channel adapter | One per channel account. Translates events in and actions out, backfills what it missed. Platform concepts never leave this layer. |
|
|
221
|
+
| Gateway core | Inbox, message log, waker and outbox. The same for every platform. |
|
|
222
|
+
| Bot | Identity, persona, responsibilities, notes, timers, workspace and one long conversation. |
|
|
223
|
+
| Agent | [pi-durable](https://github.com/earendil-works/pi): runs the model, journals every step, owns the tools. |
|
|
224
|
+
|
|
225
|
+
One gateway process runs every bot on the machine. Everything lives in `~/.pots/` (or `$POTS_HOME`): one folder per bot in `bots/`, channel tokens in `secrets/`, the gateway's output in `logs/` on macOS and Windows (on Linux, `pots service logs` reads the journal). Each bot folder holds:
|
|
226
|
+
|
|
227
|
+
| File | What it is |
|
|
228
|
+
|---|---|
|
|
229
|
+
| `bot.json` | Name, model, judge, channel accounts, settings. Edits apply within seconds. |
|
|
230
|
+
| `persona.md` | Personality and voice. The bot maintains it. |
|
|
231
|
+
| `responsibilities.md` | What it is responsible for. The judge reads it. The bot maintains it. |
|
|
232
|
+
| `notes.md` | Notes it carries across pages. |
|
|
233
|
+
| `workspace/` | Its working directory. |
|
|
234
|
+
| `terminal/` | Its terminal channel: what you and the bot say in `pots chat`. |
|
|
235
|
+
| `bot.sqlite` | Message log, timers and the agent's journal in one file. |
|
|
236
|
+
|
|
237
|
+
The same `pots` command gives the bot (and its scripts and cron jobs) its actions from a shell: `pots send`, `pots react`, `pots call`, `pots wake`, `pots context`, `pots turn-page`. Tokens stay inside the running gateway; the agent never sees them.
|
|
238
|
+
|
|
239
|
+
## Status
|
|
240
|
+
|
|
241
|
+
pi-durable-bot runs every day as a teammate in a real workspace. What works today and what is next:
|
|
242
|
+
|
|
243
|
+
- [x] Slack adapter (socket mode), with backfill after downtime
|
|
244
|
+
- [x] Mention, DM, judge and timer wakes, grouping, and steering
|
|
245
|
+
- [x] Code mode on its own machine, `pots` command line
|
|
246
|
+
- [x] Turning the page with notes, compaction as a fallback
|
|
247
|
+
- [x] Crash-safe inbox and outbox, tested with a forced crash mid-send
|
|
248
|
+
- [x] Several bots per machine
|
|
249
|
+
- [x] `pots init`: name, AI and one sentence, then the bot sets up its own chat apps from the terminal
|
|
250
|
+
- [x] macOS, Linux and Windows, as a background service of the user
|
|
251
|
+
- [x] The screen, mouse and keyboard of its computer, used like a person (computer use), or no screen on a server
|
|
252
|
+
- [x] Any model pi can use: subscription logins, API keys, OpenAI-compatible endpoints, local models
|
|
253
|
+
- [x] A judge you choose: the bot's own model, Jev or another classifier, a local llama.cpp model, or none
|
|
254
|
+
- [ ] More adapters: Discord, Teams, Telegram, email
|
|
255
|
+
- [ ] `pots init` in a web page, for people who do not use a terminal
|
|
256
|
+
|
|
257
|
+
## Develop
|
|
258
|
+
|
|
259
|
+
```sh
|
|
260
|
+
git clone https://github.com/Crokily/pi-durable-bot && cd pi-durable-bot
|
|
261
|
+
npm install
|
|
262
|
+
npm run pots -- status # the pots command, straight from src/ (Node 24 runs TypeScript)
|
|
263
|
+
npm run check # type check
|
|
264
|
+
npm test # tests, including a real gateway with a fake model
|
|
265
|
+
npm run tla # the TLA+ models of the inbox, outbox and waker (needs Java and tla2tools.jar)
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
`npm run build` writes the JavaScript that the npm package ships to `dist/`. Set `POTS_HOME` to try things without touching `~/.pots/`. With `OTEL_EXPORTER_OTLP_ENDPOINT` set, the gateway also sends its traces to any OpenTelemetry tool (Jaeger, Grafana Tempo, Honeycomb). Tests, the TLA+ models and traces in detail: [docs/development.md](docs/development.md). Coding agents: read [AGENTS.md](AGENTS.md).
|
|
269
|
+
|
|
270
|
+
## Built on
|
|
271
|
+
|
|
272
|
+
- [pi-durable](https://github.com/earendil-works/pi) for the durable agent runtime
|
|
273
|
+
- [Chat SDK](https://chat-sdk.dev) for channel adapters
|
|
274
|
+
- [pi](https://github.com/earendil-works/pi)'s model layer for logins, providers and local models
|
|
275
|
+
- [Effect](https://effect.website) for the gateway core and the `pots` command line
|
|
276
|
+
- [TypeSafe AI](https://typesafe.ai)'s Jev, one of the judges you can choose
|
|
277
|
+
|
|
278
|
+
## License
|
|
279
|
+
|
|
280
|
+
MIT. The demo video, music, sky images and logo in [`docs/media`](docs/media) were made for this project and use the same license.
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { BACKGROUND_CONTEXT, withTelemetry } from "@earendil-works/chord/context";
|
|
4
|
+
import { Type } from "@earendil-works/pi-ai";
|
|
5
|
+
import { calculateContextTokens, estimateMessageTokens } from "@earendil-works/pi-ai/utils/estimate";
|
|
6
|
+
import { createRegistry, DEFAULT_COMPACTION_POLICY, defineExtension, defineTool, Harness, section, } from "@earendil-works/pi-durable";
|
|
7
|
+
import { NodeExecutionEnv } from "@earendil-works/pi-durable/env/node";
|
|
8
|
+
import { SqliteStorage } from "@earendil-works/pi-durable/storage/sqlite";
|
|
9
|
+
import { openNodeSqliteDatabase } from "@earendil-works/pi-durable/storage/sqlite/node";
|
|
10
|
+
import { CodingTools } from "@earendil-works/pi-durable/tools";
|
|
11
|
+
import { modelRef, requireModel } from "./models.js";
|
|
12
|
+
const context = BACKGROUND_CONTEXT;
|
|
13
|
+
/** Open the bot's SQLite file. The one connection is shared: the agent's tables start with pi_, the others use it too. */
|
|
14
|
+
export async function openDatabase(path) {
|
|
15
|
+
return (await openNodeSqliteDatabase(path));
|
|
16
|
+
}
|
|
17
|
+
/** Call results longer than this go to a file in the workspace. */
|
|
18
|
+
const CALL_OUTPUT_CHARS = 30_000;
|
|
19
|
+
/** The window assumed for a model whose catalog entry gives none. */
|
|
20
|
+
const DEFAULT_WINDOW = 200_000;
|
|
21
|
+
/** Room kept free for the answer and long tool results; pi's own default is 16K. */
|
|
22
|
+
const RESERVE_TOKENS = 32_768;
|
|
23
|
+
/**
|
|
24
|
+
* The bot's agent: one long-lived pi-durable conversation (the root). Tools: read, write, edit, bash, and the
|
|
25
|
+
* channel actions send, react and call. Everything else the agent does with code.
|
|
26
|
+
*/
|
|
27
|
+
export class Agent {
|
|
28
|
+
#options;
|
|
29
|
+
#harness;
|
|
30
|
+
#root;
|
|
31
|
+
#models;
|
|
32
|
+
#model;
|
|
33
|
+
#runInputs;
|
|
34
|
+
#runListeners = new Set();
|
|
35
|
+
#disposeView;
|
|
36
|
+
constructor(options, harness, root) {
|
|
37
|
+
this.#options = options;
|
|
38
|
+
this.#harness = harness;
|
|
39
|
+
this.#root = root;
|
|
40
|
+
this.#models = options.models;
|
|
41
|
+
this.#model = modelRef(options.model);
|
|
42
|
+
}
|
|
43
|
+
static async open(options) {
|
|
44
|
+
const { actions, models } = options;
|
|
45
|
+
// The connection is the bot's and shared with the gateway, which still writes after the agent has stopped. Closing
|
|
46
|
+
// the harness closes its storage, not the connection; the bot closes that last.
|
|
47
|
+
const connection = new Proxy(options.database, {
|
|
48
|
+
get: (target, property) => property === "close" ? async () => { } : typeof Reflect.get(target, property) === "function" ? Reflect.get(target, property).bind(target) : Reflect.get(target, property),
|
|
49
|
+
});
|
|
50
|
+
const storage = await SqliteStorage.open(connection, { prefix: "pi_" });
|
|
51
|
+
await requireChatModel(models, options.model);
|
|
52
|
+
const text = (value) => [{ type: "text", text: value }];
|
|
53
|
+
const tools = [
|
|
54
|
+
defineTool({
|
|
55
|
+
name: "send",
|
|
56
|
+
description: "Say something in a channel. to: a place, thread, message or person address, copied from a wake message or the log. " +
|
|
57
|
+
"A place gets a new message; a thread or message gets a reply in that thread; a person gets a DM. text: Markdown; " +
|
|
58
|
+
"write <person address> to mention someone. Sent exactly once, also across restarts. Returns the new message's address.",
|
|
59
|
+
parameters: Type.Object({ to: Type.String(), text: Type.String() }),
|
|
60
|
+
// A rerun after a crash keeps the task ID, so the outbox finds the first attempt instead of sending again.
|
|
61
|
+
replay: "safe",
|
|
62
|
+
execute: async (args, api, call) => {
|
|
63
|
+
const sent = await actions.send(args.to, args.text, `tool:${api.taskId}`, call.telemetry);
|
|
64
|
+
return { output: text(`sent: ${sent.message}${sent.recovered ? " (found after a restart, not sent again)" : ""}`) };
|
|
65
|
+
},
|
|
66
|
+
}),
|
|
67
|
+
defineTool({
|
|
68
|
+
name: "react",
|
|
69
|
+
description: "Add an emoji reaction to a message (message address), for example eyes or white_check_mark. remove: true takes it away.",
|
|
70
|
+
parameters: Type.Object({ message: Type.String(), emoji: Type.String(), remove: Type.Optional(Type.Boolean()) }),
|
|
71
|
+
replay: "safe",
|
|
72
|
+
execute: async (args, _api, call) => {
|
|
73
|
+
await actions.react(args.message, args.emoji, args.remove ?? false, call.telemetry);
|
|
74
|
+
return { output: text("ok") };
|
|
75
|
+
},
|
|
76
|
+
}),
|
|
77
|
+
defineTool({
|
|
78
|
+
name: "call",
|
|
79
|
+
description: "Call a platform API method directly, for what send and react do not cover, for example editing your own message or uploading a file. " +
|
|
80
|
+
"channel: the channel account (the part of an address before the first colon). method and params: as the platform's API documents them; " +
|
|
81
|
+
"take platform IDs from the raw column of the log. Returns the platform's answer as JSON.",
|
|
82
|
+
parameters: Type.Object({ channel: Type.String(), method: Type.String(), params: Type.Optional(Type.Record(Type.String(), Type.Any())) }),
|
|
83
|
+
execute: async (args, api, call) => {
|
|
84
|
+
const result = JSON.stringify(await actions.call(args.channel, args.method, args.params ?? {}, call.telemetry), null, 1) ?? "null";
|
|
85
|
+
if (result.length <= CALL_OUTPUT_CHARS)
|
|
86
|
+
return { output: text(result) };
|
|
87
|
+
const dir = join(options.workspace, "call-results");
|
|
88
|
+
await mkdir(dir, { recursive: true });
|
|
89
|
+
const file = join(dir, `${api.taskId}.json`);
|
|
90
|
+
await writeFile(file, result);
|
|
91
|
+
return { output: text(`The answer is ${result.length} characters; full JSON in ${file}. First part:\n${result.slice(0, 4_000)}`) };
|
|
92
|
+
},
|
|
93
|
+
}),
|
|
94
|
+
];
|
|
95
|
+
const bot = defineExtension({
|
|
96
|
+
name: "bot",
|
|
97
|
+
tools,
|
|
98
|
+
sections: options.sections.map((part) => section(part.name, () => part.render(), { tag: false })),
|
|
99
|
+
});
|
|
100
|
+
const registry = createRegistry();
|
|
101
|
+
registry.install(CodingTools);
|
|
102
|
+
registry.install(bot);
|
|
103
|
+
let agent;
|
|
104
|
+
const harness = await Harness.open(storage, {
|
|
105
|
+
models,
|
|
106
|
+
registry,
|
|
107
|
+
settings: {
|
|
108
|
+
// Several queued wakes go into one run.
|
|
109
|
+
steeringMode: "all",
|
|
110
|
+
followUpMode: "all",
|
|
111
|
+
afterFailedRun: "continue",
|
|
112
|
+
retry: { maxRetries: 4 },
|
|
113
|
+
// The fallback when the agent does not turn the page itself.
|
|
114
|
+
get compaction() {
|
|
115
|
+
return compactionFor(models, agent ? agent.#model : modelRef(options.model), options.compaction());
|
|
116
|
+
},
|
|
117
|
+
},
|
|
118
|
+
env: () => new NodeExecutionEnv({ cwd: options.workspace, shellEnv: options.shellEnv }),
|
|
119
|
+
...(options.telemetry ? { telemetry: options.telemetry } : {}),
|
|
120
|
+
onReport: (error, info) => options.log("pi report", { type: info.type, error: String(error) }),
|
|
121
|
+
}, context);
|
|
122
|
+
const model = modelRef(options.model);
|
|
123
|
+
const root = await harness.root(context, { agent: { model, thinkingLevel: options.thinking } });
|
|
124
|
+
await root.configure({ model, thinkingLevel: options.thinking, cwd: options.workspace }, context);
|
|
125
|
+
agent = new Agent(options, harness, root);
|
|
126
|
+
await agent.#watchRun();
|
|
127
|
+
return agent;
|
|
128
|
+
}
|
|
129
|
+
/** Continue the work the last process left unfinished. Call once the channels are up, so its tools can act. */
|
|
130
|
+
resume() {
|
|
131
|
+
this.#harness.resume();
|
|
132
|
+
}
|
|
133
|
+
async #watchRun() {
|
|
134
|
+
const view = await this.#root.viewState(context);
|
|
135
|
+
const update = (value) => {
|
|
136
|
+
const live = value.docs["pi.live"];
|
|
137
|
+
const inputs = live?.run ? (live.run.inputs ?? []).map(String) : undefined;
|
|
138
|
+
const changed = (inputs === undefined) !== (this.#runInputs === undefined) || inputs?.join() !== this.#runInputs?.join();
|
|
139
|
+
this.#runInputs = inputs;
|
|
140
|
+
if (changed)
|
|
141
|
+
for (const listener of this.#runListeners)
|
|
142
|
+
listener(inputs);
|
|
143
|
+
};
|
|
144
|
+
update(view.value);
|
|
145
|
+
const unsubscribe = view.subscribe(update);
|
|
146
|
+
this.#disposeView = () => {
|
|
147
|
+
unsubscribe();
|
|
148
|
+
view.dispose();
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
async close() {
|
|
152
|
+
this.#disposeView?.();
|
|
153
|
+
await this.#harness.close(context);
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Hand text to the agent. Busy: steer joins the running work after the current tool round; otherwise it waits for
|
|
157
|
+
* the run to end. Idle: starts a run. The same id is one submission. caller: the span of what woke the agent;
|
|
158
|
+
* pi-durable links the submission to it. Returns the submission ID and its stored trace context, which is the first
|
|
159
|
+
* one for a submission made before.
|
|
160
|
+
*/
|
|
161
|
+
async submit(input) {
|
|
162
|
+
const submission = await this.#root.submit({
|
|
163
|
+
type: "input",
|
|
164
|
+
content: input.text,
|
|
165
|
+
requestId: input.id,
|
|
166
|
+
whenBusy: input.steer ? "steer" : "followUp",
|
|
167
|
+
entry: { kind: "bot.wake", ...(input.data === undefined ? {} : { data: input.data }) },
|
|
168
|
+
}, input.caller ? withTelemetry(input.caller, context) : context);
|
|
169
|
+
const { trace } = await submission.status(context);
|
|
170
|
+
return { id: String(submission.id), ...(trace ? { trace } : {}) };
|
|
171
|
+
}
|
|
172
|
+
/** Why a run with these submissions got no answer, such as a missing login; undefined when they were answered. */
|
|
173
|
+
async runError(inputs) {
|
|
174
|
+
for (const id of inputs) {
|
|
175
|
+
const submission = await this.#harness.submission(Number(id), context);
|
|
176
|
+
const record = (submission ? await submission.status(context) : undefined);
|
|
177
|
+
if (record?.status === "unanswered" && record.reason === "model_error")
|
|
178
|
+
return String(record.detail ?? "the model request failed");
|
|
179
|
+
}
|
|
180
|
+
return undefined;
|
|
181
|
+
}
|
|
182
|
+
/** The submissions the current run works on, or undefined while idle. */
|
|
183
|
+
get runInputs() {
|
|
184
|
+
return this.#runInputs;
|
|
185
|
+
}
|
|
186
|
+
onRunChange(listener) {
|
|
187
|
+
this.#runListeners.add(listener);
|
|
188
|
+
}
|
|
189
|
+
/** Start a new context whose first message is the handoff. While busy, the current run ends at the next boundary. */
|
|
190
|
+
async turnPage(handoff) {
|
|
191
|
+
await this.#root.reset(handoff, context);
|
|
192
|
+
}
|
|
193
|
+
/** Change the model ("provider/modelId") or the thinking level. Throws for an unknown model. */
|
|
194
|
+
async configure(model, thinking) {
|
|
195
|
+
await requireChatModel(this.#models, model);
|
|
196
|
+
this.#model = modelRef(model);
|
|
197
|
+
await this.#root.configure({ model: this.#model, thinkingLevel: thinking }, context);
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Tokens in the context: the provider's count for the last request, plus an estimate of what came after.
|
|
201
|
+
* pi estimates from characters, which counts Chinese at about half, so the estimate is doubled.
|
|
202
|
+
*/
|
|
203
|
+
async contextStatus() {
|
|
204
|
+
const window = this.#models.getModel(this.#model.provider, this.#model.modelId)?.contextWindow ?? DEFAULT_WINDOW;
|
|
205
|
+
const messages = (await this.#root.context(context)).messages;
|
|
206
|
+
let index = -1;
|
|
207
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
208
|
+
const message = messages[i];
|
|
209
|
+
if (message.role === "assistant" && calculateContextTokens(message.usage) > 0) {
|
|
210
|
+
index = i;
|
|
211
|
+
break;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
let used = index >= 0 ? calculateContextTokens(messages[index].usage) : 0;
|
|
215
|
+
for (const message of messages.slice(index + 1))
|
|
216
|
+
used += 2 * estimateMessageTokens(message);
|
|
217
|
+
// Before the first answer in this context, the provider has not counted the system prompt yet.
|
|
218
|
+
if (index < 0) {
|
|
219
|
+
const parts = await Promise.all(this.#options.sections.map(async (part) => (await part.render()) ?? ""));
|
|
220
|
+
used += 2 * estimateMessageTokens({ role: "user", content: parts.join("\n\n"), timestamp: 0 });
|
|
221
|
+
}
|
|
222
|
+
// pi compacts in the background from (window - reserve - background), and blocks at (window - reserve).
|
|
223
|
+
const policy = compactionFor(this.#models, this.#model, this.#options.compaction());
|
|
224
|
+
const compactAt = window - policy.reserveTokens - (policy.backgroundTokens > 0 ? policy.backgroundTokens : 0);
|
|
225
|
+
return { used, window, compactAt };
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Compaction for the model's context window: what bot.json sets, else the defaults, each at most 15% of the window,
|
|
230
|
+
* so a small local model still has room to work.
|
|
231
|
+
*/
|
|
232
|
+
function compactionFor(models, ref, set) {
|
|
233
|
+
const window = models.getModel(ref.provider, ref.modelId)?.contextWindow ?? DEFAULT_WINDOW;
|
|
234
|
+
const fit = (tokens) => Math.min(tokens, Math.floor(window * 0.15));
|
|
235
|
+
return {
|
|
236
|
+
reserveTokens: set.reserveTokens ?? fit(RESERVE_TOKENS),
|
|
237
|
+
keepRecentTokens: set.keepRecentTokens ?? fit(DEFAULT_COMPACTION_POLICY.keepRecentTokens),
|
|
238
|
+
backgroundTokens: set.backgroundTokens ?? fit(DEFAULT_COMPACTION_POLICY.backgroundTokens),
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
async function requireChatModel(models, model) {
|
|
242
|
+
await requireModel(models, model, (provider, id) => models.getModel(provider, id));
|
|
243
|
+
}
|
|
244
|
+
//# sourceMappingURL=agent.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent.js","sourceRoot":"","sources":["../../src/agent/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAClF,OAAO,EAA6B,IAAI,EAAE,MAAM,uBAAuB,CAAC;AACxE,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AACrG,OAAO,EAEL,cAAc,EACd,yBAAyB,EACzB,eAAe,EACf,UAAU,EACV,OAAO,EAGP,OAAO,GACR,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC;AACvE,OAAO,EAAE,aAAa,EAAE,MAAM,2CAA2C,CAAC;AAC1E,OAAO,EAAE,sBAAsB,EAAE,MAAM,gDAAgD,CAAC;AACxF,OAAO,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAC;AAG/D,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAErD,MAAM,OAAO,GAAG,kBAAkB,CAAC;AAoBnC,0HAA0H;AAC1H,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,IAAY;IAC7C,OAAO,CAAC,MAAM,sBAAsB,CAAC,IAAI,CAAC,CAAgD,CAAC;AAC7F,CAAC;AA6BD,mEAAmE;AACnE,MAAM,iBAAiB,GAAG,MAAM,CAAC;AACjC,qEAAqE;AACrE,MAAM,cAAc,GAAG,OAAO,CAAC;AA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AC,MAAM,CAAC,gBAAgB,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAC9G,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;IACrC,CAAC;CACF;AAED;;;GAGG;AACH,SAAS,aAAa,CAAC,MAAc,EAAE,GAAa,EAAE,GAAe;IACnE,MAAM,MAAM,GAAG,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,OAAO,CAAC,EAAE,aAAa,IAAI,cAAc,CAAC;IAC3F,MAAM,GAAG,GAAG,CAAC,MAAc,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC;IAC5E,OAAO;QACL,aAAa,EAAE,GAAG,CAAC,aAAa,IAAI,GAAG,CAAC,cAAc,CAAC;QACvD,gBAAgB,EAAE,GAAG,CAAC,gBAAgB,IAAI,GAAG,CAAC,yBAAyB,CAAC,gBAAgB,CAAC;QACzF,gBAAgB,EAAE,GAAG,CAAC,gBAAgB,IAAI,GAAG,CAAC,yBAAyB,CAAC,gBAAgB,CAAC;KAC1F,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,gBAAgB,CAAC,MAAc,EAAE,KAAa;IAC3D,MAAM,YAAY,CAAC,MAAM,EAAE,KAAK,EAAE,CAAC,QAAQ,EAAE,EAAE,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,CAAC;AACrF,CAAC"}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { getSupportedThinkingLevels } from "@earendil-works/pi-ai";
|
|
2
|
+
import { requireModel } from "./models.js";
|
|
3
|
+
/**
|
|
4
|
+
* The judge for events that do not mention the bot, or undefined for "off" (every such event wakes the bot).
|
|
5
|
+
* A classifier ("typesafe/jev-latest", "llama.cpp/Kev-4B-Q4_K_M", ...) answers through pi's classify().
|
|
6
|
+
* "main" asks the bot's own chat model, so no extra account is needed. Models are looked up for each judgment:
|
|
7
|
+
* a judge that is not reachable now (a local server that is down) fails that judgment, and the events go to the bot.
|
|
8
|
+
*/
|
|
9
|
+
export function createJudge(setting, models, mainModel) {
|
|
10
|
+
if (setting === "off")
|
|
11
|
+
return undefined;
|
|
12
|
+
if (setting === "main")
|
|
13
|
+
return chatJudge(models, mainModel);
|
|
14
|
+
return {
|
|
15
|
+
async judge(input, trace) {
|
|
16
|
+
const classifier = await requireModel(models, setting, (provider, id) => models.getModelOfType("classifier", provider, id));
|
|
17
|
+
const result = await models.classify(classifier, { state: judgeState(input), questions: judgeQuestions(input.name) }, trace ? { telemetry: trace } : {});
|
|
18
|
+
if (result.stopReason !== "stop")
|
|
19
|
+
throw new Error(result.errorMessage ?? result.stopReason);
|
|
20
|
+
return { related: probability(result.answers.related), respond: probability(result.answers.respond) };
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
const CHAT_JUDGE_PROMPT = `You judge events in a team chat for one team member. The user message is JSON: "state" has the team member, what they are responsible for, the place, earlier messages and the new events; "questions" has two yes-or-no questions about the new events.
|
|
25
|
+
For each question, give the probability from 0 to 1 that the answer is yes. Answer with only this JSON: {"related": <probability>, "respond": <probability>}`;
|
|
26
|
+
function chatJudge(models, mainModel) {
|
|
27
|
+
return {
|
|
28
|
+
async judge(input, trace) {
|
|
29
|
+
const model = await requireModel(models, mainModel(), (provider, id) => models.getModel(provider, id));
|
|
30
|
+
// A short judgment: the lowest thinking level the model has.
|
|
31
|
+
const levels = getSupportedThinkingLevels(model);
|
|
32
|
+
const reasoning = ["minimal", "low"].find((level) => levels.includes(level));
|
|
33
|
+
const content = JSON.stringify({ state: judgeState(input), questions: judgeQuestions(input.name) }, null, 1);
|
|
34
|
+
const reply = await models.completeSimple(model, { systemPrompt: CHAT_JUDGE_PROMPT, messages: [{ role: "user", content, timestamp: Date.now() }] }, { ...(reasoning ? { reasoning } : {}), ...(trace ? { telemetry: trace } : {}) });
|
|
35
|
+
if (reply.stopReason === "error" || reply.stopReason === "aborted")
|
|
36
|
+
throw new Error(reply.errorMessage ?? reply.stopReason);
|
|
37
|
+
const text = reply.content.map((block) => (block.type === "text" ? block.text : "")).join("");
|
|
38
|
+
return parseAnswer(text);
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function judgeState(input) {
|
|
43
|
+
return {
|
|
44
|
+
team_member: input.name,
|
|
45
|
+
what_this_team_member_is_responsible_for: input.responsibilities,
|
|
46
|
+
place: input.place,
|
|
47
|
+
earlier_messages: input.earlier.map((item) => ({ ...item })),
|
|
48
|
+
new_events: input.latest.map((item) => ({ ...item })),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function judgeQuestions(name) {
|
|
52
|
+
return {
|
|
53
|
+
related: {
|
|
54
|
+
type: "bool",
|
|
55
|
+
instructions: `Are the new events about something ${name} is responsible for, or addressed to ${name}?`,
|
|
56
|
+
criteria: { true: `About ${name}'s responsibilities, or addressed to ${name}`, false: `Not about ${name}` },
|
|
57
|
+
},
|
|
58
|
+
respond: {
|
|
59
|
+
type: "bool",
|
|
60
|
+
instructions: `Does ${name} need to respond to the new events?`,
|
|
61
|
+
criteria: { true: `${name} should respond`, false: `${name} does not need to respond` },
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
function probability(answer) {
|
|
66
|
+
if (answer?.type !== "bool")
|
|
67
|
+
throw new Error(`the judge gave no yes-or-no answer: ${JSON.stringify(answer)}`);
|
|
68
|
+
return answer.probability;
|
|
69
|
+
}
|
|
70
|
+
function parseAnswer(text) {
|
|
71
|
+
const json = /\{[\s\S]*\}/.exec(text)?.[0];
|
|
72
|
+
const value = json ? JSON.parse(json) : undefined;
|
|
73
|
+
const valid = (n) => typeof n === "number" && n >= 0 && n <= 1;
|
|
74
|
+
if (!value || !valid(value.related) || !valid(value.respond))
|
|
75
|
+
throw new Error(`the judge did not answer with two probabilities: ${text.slice(0, 200)}`);
|
|
76
|
+
return { related: value.related, respond: value.respond };
|
|
77
|
+
}
|
|
78
|
+
//# sourceMappingURL=judge.js.map
|