pi-durable-bot 0.5.1 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +38 -9
  3. package/dist/agent/agent.js +30 -6
  4. package/dist/agent/agent.js.map +1 -1
  5. package/dist/agent/codemode.js +32 -0
  6. package/dist/agent/codemode.js.map +1 -0
  7. package/dist/agent/mcp.js +353 -0
  8. package/dist/agent/mcp.js.map +1 -0
  9. package/dist/agent/resources.js +4 -2
  10. package/dist/agent/resources.js.map +1 -1
  11. package/dist/bot/bot.js +79 -11
  12. package/dist/bot/bot.js.map +1 -1
  13. package/dist/bot/prompt.js +63 -16
  14. package/dist/bot/prompt.js.map +1 -1
  15. package/dist/cli/agent.js +39 -2
  16. package/dist/cli/agent.js.map +1 -1
  17. package/dist/cli/commands.js +3 -2
  18. package/dist/cli/commands.js.map +1 -1
  19. package/dist/cli/mcp.js +54 -0
  20. package/dist/cli/mcp.js.map +1 -0
  21. package/dist/cli/pots.js +5 -1
  22. package/dist/cli/pots.js.map +1 -1
  23. package/dist/cli/service.js +107 -49
  24. package/dist/cli/service.js.map +1 -1
  25. package/dist/core/home.js +10 -2
  26. package/dist/core/home.js.map +1 -1
  27. package/dist/gateway/config.js.map +1 -1
  28. package/dist/gateway/errors.js +6 -0
  29. package/dist/gateway/errors.js.map +1 -1
  30. package/dist/gateway/gateway.js +12 -3
  31. package/dist/gateway/gateway.js.map +1 -1
  32. package/dist/gateway/routines.js +173 -0
  33. package/dist/gateway/routines.js.map +1 -0
  34. package/dist/gateway/timers.js +248 -21
  35. package/dist/gateway/timers.js.map +1 -1
  36. package/dist/gateway/tracing.js +1 -1
  37. package/dist/gateway/tracing.js.map +1 -1
  38. package/dist/main.js +16 -3
  39. package/dist/main.js.map +1 -1
  40. package/docs/for-agents.md +12 -7
  41. package/package.json +4 -2
@@ -0,0 +1,353 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { join } from "node:path";
10
+ import { defineExtension, defineTool } from "@earendil-works/pi-durable";
11
+ import { piModule } from "./models.js";
12
+ // MCP servers, through pi's own MCP support: pi's mcp.json (~/.pi/agent/mcp.json, and .pi/mcp.json in the bot's working
13
+ // directory), pi's connections and sign-ins (tokens in ~/.pi/agent/mcp-auth.json), and pi's adapters of server tools.
14
+ // pi's MCP extension is written for a pi session, so its parts are joined here for pi-durable: every server tool is a
15
+ // tool that only codemode scripts call and that the codemode section does not list, as with pi's default exposure. So
16
+ // the tools declared to the model and the system prompt stay the same while servers come, go and connect. One set of
17
+ // connections per bot serves its main agent and all its children.
18
+ /** The text of the mcp_servers section without servers, so the sections after it stay where they are. */
19
+ const NO_SERVERS = "MCP servers whose tools are not declared to you: none.";
20
+ /** Script globals that list or look up tools, so a script that uses one may call any tool (pi's codemode tool). */
21
+ const DISCOVERY = /\b(searchTools|describeNamespace|describeTool|ALL_TOOLS)\b/;
22
+ /** pi's resource tools, which reach every server with resources. */
23
+ const RESOURCE_TOOLS = new Set(["list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"]);
24
+ async function loadPi() {
25
+ const [{ getAgentDir }, config, servers, tools, resources, extension] = await Promise.all([
26
+ import("@earendil-works/pi-coding-agent"),
27
+ import(__rewriteRelativeImportExtension(piModule("./extensions/mcp/config.js"))),
28
+ import(__rewriteRelativeImportExtension(piModule("./core/mcp-servers.js"))),
29
+ import(__rewriteRelativeImportExtension(piModule("./extensions/mcp/tools.js"))),
30
+ import(__rewriteRelativeImportExtension(piModule("./extensions/mcp/resources.js"))),
31
+ import(__rewriteRelativeImportExtension(piModule("./extensions/mcp/index.js"))),
32
+ ]);
33
+ return { getAgentDir, ...config, ...servers, ...tools, ...resources, ...extension };
34
+ }
35
+ async function loadRuntime() {
36
+ const [runtime, { StdioTransport }] = await Promise.all([import(__rewriteRelativeImportExtension(piModule("./extensions/mcp/runtime.js"))), import("@earendil-works/pi-mcp")]);
37
+ return { ...runtime, StdioTransport };
38
+ }
39
+ const enabled = (entry) => entry.config.enabled !== false;
40
+ const keyOf = (entry) => JSON.stringify([entry.source, entry.scope, entry.override, entry.config]);
41
+ /** Every exposure but hidden is codemode here: the bot declares no server tool to the model and has no tool_search. */
42
+ const viaCodemode = (exposure) => (exposure === "hidden" ? "hidden" : "codemode");
43
+ /** A tool of pi's MCP extension as a pi-durable tool that only scripts call and that the codemode section leaves out. */
44
+ function scriptTool(tool) {
45
+ return defineTool({
46
+ name: tool.name,
47
+ description: tool.description,
48
+ parameters: tool.parameters,
49
+ ...(tool.outputSchema ? { structuredOutputSchema: tool.outputSchema } : {}),
50
+ callers: ["tools"],
51
+ deferred: true,
52
+ // A call cut off by a crash may have acted on the server already: the script gets an error instead of a second call.
53
+ replay: "unsafe",
54
+ execute: async (args, api, context) => {
55
+ const result = await tool.execute(api.callId, args, context.abortSignal);
56
+ return {
57
+ output: result.content,
58
+ ...(tool.outputSchema && result.structuredContent !== undefined ? { structuredOutput: result.structuredContent } : {}),
59
+ ...(result.isError ? { isError: true } : {}),
60
+ };
61
+ },
62
+ });
63
+ }
64
+ /**
65
+ * The MCP servers of one bot, from pi's mcp.json, read again before each request: a server added, removed or changed
66
+ * there connects, goes or reconnects from the bot's next wake, and a server that needed a sign-in is used from the next
67
+ * request after `pots mcp login`. `extension()` holds the servers' tools; it changes as they connect.
68
+ */
69
+ export class Mcp {
70
+ #options;
71
+ #pi;
72
+ #servers = new Map();
73
+ /** The tools of each server, as their connection offers them. */
74
+ #tools = new Map();
75
+ #resourceTools = [];
76
+ #extension = defineExtension({ name: "mcp" });
77
+ #listeners = new Set();
78
+ #runtime;
79
+ #credentials;
80
+ #serverLog;
81
+ #errors = "";
82
+ #closing = new Set();
83
+ #closed = false;
84
+ constructor(options, pi) {
85
+ this.#options = options;
86
+ this.#pi = pi;
87
+ }
88
+ static async open(options) {
89
+ const mcp = new Mcp(options, await loadPi());
90
+ mcp.reload();
91
+ return mcp;
92
+ }
93
+ /** The extension with the servers' tools; a new one after every change. */
94
+ extension() {
95
+ return this.#extension;
96
+ }
97
+ /** Called after the servers' tools changed. */
98
+ onChange(listener) {
99
+ this.#listeners.add(listener);
100
+ }
101
+ /**
102
+ * Read mcp.json again: connect servers that are new, stop those that are gone, and reconnect those that changed.
103
+ * Reconnect a server that needed a sign-in once its stored sign-in changed. Cheap when nothing changed.
104
+ */
105
+ reload() {
106
+ if (this.#closed)
107
+ return;
108
+ const pi = this.#pi;
109
+ let loaded;
110
+ try {
111
+ loaded = pi.loadMcpConfig({ agentDir: pi.getAgentDir(), cwd: this.#options.cwd, projectTrusted: this.#options.projectTrusted() });
112
+ }
113
+ catch (error) {
114
+ // The servers that run go on.
115
+ this.#options.log("could not read mcp.json", { error: String(error) });
116
+ return;
117
+ }
118
+ const errors = loaded.errors.join("\n");
119
+ if (errors !== this.#errors && errors)
120
+ this.#options.log("mcp.json has errors", { errors });
121
+ this.#errors = errors;
122
+ const next = new Map(loaded.servers.map((entry) => [entry.name, entry]));
123
+ let changed = false;
124
+ for (const [name, server] of this.#servers) {
125
+ const entry = next.get(name);
126
+ if (entry && keyOf(entry) === server.key)
127
+ continue;
128
+ this.#stop(server);
129
+ changed = true;
130
+ }
131
+ for (const entry of loaded.servers) {
132
+ if (this.#servers.has(entry.name))
133
+ continue;
134
+ const server = { entry, key: keyOf(entry) };
135
+ this.#servers.set(entry.name, server);
136
+ if (enabled(entry))
137
+ this.#start(server);
138
+ changed = true;
139
+ }
140
+ this.#reconnectSignedIn();
141
+ if (changed)
142
+ this.#changed();
143
+ }
144
+ /** The mcp_servers section, as pi writes it: the servers whose tools scripts call, with what each offers. */
145
+ section() {
146
+ const listed = [...this.#servers.values()].map((server) => ({
147
+ entry: {
148
+ ...server.entry,
149
+ config: {
150
+ ...server.entry.config,
151
+ exposure: viaCodemode(server.entry.config.exposure ?? "codemode"),
152
+ ...(server.entry.config.toolExposure
153
+ ? { toolExposure: Object.fromEntries(Object.entries(server.entry.config.toolExposure).map(([tool, exposure]) => [tool, viaCodemode(exposure)])) }
154
+ : {}),
155
+ },
156
+ },
157
+ ...(server.connection?.instructions ? { connection: { instructions: server.connection.instructions } } : {}),
158
+ }));
159
+ return `<mcp_servers>\n${this.#pi.renderServersSection(listed) ?? NO_SERVERS}\n</mcp_servers>`;
160
+ }
161
+ /** The servers as codemode namespaces, for describeNamespace() and searchTools(). */
162
+ namespaces() {
163
+ return [...this.#servers.values()]
164
+ .filter((server) => enabled(server.entry))
165
+ .map((server) => {
166
+ const name = this.#pi.mcpNamespace(server.entry.name);
167
+ const description = server.entry.config.description?.trim();
168
+ const instructions = server.connection?.instructions;
169
+ return { name, prefix: `${name}__`, ...(description ? { description } : {}), ...(instructions ? { instructions } : {}) };
170
+ });
171
+ }
172
+ /**
173
+ * Wait for the servers a script may call, as pi does: those whose namespace (mcp__<server>) it names, or all of them
174
+ * when it looks tools up or uses a resource tool. Returns whether it waited for any.
175
+ */
176
+ async ready(code, signal) {
177
+ const words = DISCOVERY.test(code) ? undefined : (code.match(/\w+/g) ?? []);
178
+ const all = words === undefined || words.some((word) => RESOURCE_TOOLS.has(word));
179
+ const waiting = [...this.#servers.values()].filter((server) => {
180
+ if (!server.ready || !enabled(server.entry))
181
+ return false;
182
+ const namespace = this.#pi.mcpNamespace(server.entry.name);
183
+ return all || words.some((word) => word.includes(namespace));
184
+ });
185
+ if (waiting.length === 0)
186
+ return false;
187
+ const connected = Promise.all(waiting.map((server) => server.ready));
188
+ if (!signal) {
189
+ await connected;
190
+ return true;
191
+ }
192
+ let onAbort = () => { };
193
+ const aborted = new Promise((resolve) => (onAbort = resolve));
194
+ if (signal.aborted)
195
+ onAbort();
196
+ else
197
+ signal.addEventListener("abort", onAbort, { once: true });
198
+ try {
199
+ await Promise.race([connected, aborted]);
200
+ }
201
+ finally {
202
+ signal.removeEventListener("abort", onAbort);
203
+ }
204
+ return true;
205
+ }
206
+ /** Stop every server and wait until their processes and connections are closed. */
207
+ async close() {
208
+ this.#closed = true;
209
+ for (const server of this.#servers.values())
210
+ this.#stop(server);
211
+ await Promise.allSettled([...this.#closing]);
212
+ }
213
+ #start(server) {
214
+ server.ready = (async () => {
215
+ const runtime = await (this.#runtime ??= loadRuntime());
216
+ if (server.stopped)
217
+ return;
218
+ this.#credentials ??= new runtime.McpOAuthCredentialStore();
219
+ this.#serverLog ??= new runtime.McpServerLog(join(this.#pi.getAgentDir(), "mcp.log"));
220
+ const connection = new runtime.McpServerConnection({
221
+ entry: server.entry,
222
+ cwd: this.#options.cwd,
223
+ createTransport: (entry, cwd, authProvider) => this.#transport(runtime, entry, cwd, authProvider),
224
+ credentials: this.#credentials,
225
+ providerToken: async (provider) => {
226
+ try {
227
+ return (await this.#options.models.getAuth(provider))?.auth.apiKey;
228
+ }
229
+ catch {
230
+ return undefined;
231
+ }
232
+ },
233
+ log: this.#serverLog,
234
+ onTools: (current) => {
235
+ if (!server.stopped)
236
+ this.#register(server, current);
237
+ },
238
+ onChange: (current) => {
239
+ if (!server.stopped)
240
+ this.#stateChanged(server, current);
241
+ },
242
+ });
243
+ server.connection = connection;
244
+ await connection.getClient().catch(() => undefined);
245
+ })().catch((error) => this.#options.log("could not start the MCP server", { server: server.entry.name, error: String(error) }));
246
+ }
247
+ /** pi's transport, with a stdio server given the environment of the bot's bash instead of the gateway's. */
248
+ #transport(runtime, entry, cwd, authProvider) {
249
+ const transport = runtime.createDefaultTransport(entry, cwd, authProvider);
250
+ if ("url" in entry.config)
251
+ return transport;
252
+ const options = transport.options;
253
+ const base = Object.fromEntries(Object.entries(this.#options.env).filter((entry) => entry[1] !== undefined));
254
+ return new runtime.StdioTransport({ ...options, env: { ...base, ...options.env }, inheritEnv: false });
255
+ }
256
+ #stop(server) {
257
+ server.stopped = true;
258
+ this.#servers.delete(server.entry.name);
259
+ this.#tools.delete(server.entry.name);
260
+ const closing = Promise.allSettled([server.ready, server.connection?.close()]);
261
+ this.#closing.add(closing);
262
+ void closing.finally(() => this.#closing.delete(closing));
263
+ }
264
+ /** The server's tools as its connection offers them now; as in pi, tools whose names clash get a hash. */
265
+ #register(server, connection) {
266
+ const pi = this.#pi;
267
+ const name = server.entry.name;
268
+ const plain = [...new Set(connection.tools.map((tool) => tool.name))].map((tool) => pi.createMcpToolName(name, tool));
269
+ const taken = new Set();
270
+ const tools = connection.tools.flatMap((tool) => {
271
+ if (pi.getMcpToolExposure(server.entry.config, tool.name) === "hidden")
272
+ return [];
273
+ const toolName = pi.createMcpToolName(name, tool.name, (candidate) => taken.has(candidate) || plain.indexOf(candidate) !== plain.lastIndexOf(candidate));
274
+ taken.add(toolName);
275
+ const definition = pi.createMcpToolDefinition({
276
+ server: name,
277
+ tool,
278
+ name: toolName,
279
+ exposure: "codemode",
280
+ namespace: { name: pi.mcpNamespace(name) },
281
+ timeoutMs: connection.timeoutMs,
282
+ getClient: async () => this.#client(name, tool.name),
283
+ readableResources: () => this.#resourceServers().some((each) => each.name === name),
284
+ });
285
+ return [scriptTool(definition)];
286
+ });
287
+ this.#tools.set(name, tools);
288
+ this.#changed();
289
+ }
290
+ /** The connection for a call, found when the call runs: the server may have changed since the script started. */
291
+ #client(server, tool) {
292
+ const current = this.#servers.get(server);
293
+ if (!current || !enabled(current.entry))
294
+ throw new Error(`MCP server "${server}" is disabled.`);
295
+ const connection = current.connection;
296
+ if (!connection)
297
+ throw new Error(`MCP server "${server}" is still starting.`);
298
+ if (this.#pi.getMcpToolExposure(current.entry.config, tool) === "hidden" ||
299
+ (connection.state === "connected" && !connection.tools.some((offered) => offered.name === tool))) {
300
+ throw new Error(`MCP tool "${server}/${tool}" is no longer available.`);
301
+ }
302
+ return connection;
303
+ }
304
+ /** Enabled servers with resources whose exposure is not hidden: what the resource tools reach. */
305
+ #resourceServers() {
306
+ return [...this.#servers.values()].flatMap((server) => server.connection?.hasResources && enabled(server.entry) && server.entry.config.exposure !== "hidden" ? [server.connection] : []);
307
+ }
308
+ #stateChanged(server, connection) {
309
+ // As in pi: a server that needs a sign-in is reconnected once its stored sign-in changes.
310
+ if (connection.state !== "needs-auth")
311
+ server.signIn = undefined;
312
+ else
313
+ server.signIn ??= this.#storedSignIn(connection);
314
+ const problem = connection.state === "needs-auth" || connection.state === "failed" ? connection.state : undefined;
315
+ if (problem && server.logged !== problem) {
316
+ this.#options.log("MCP server not connected", { server: server.entry.name, state: problem, ...(connection.error ? { error: connection.error } : {}) });
317
+ }
318
+ server.logged = problem;
319
+ // The resource tools come with the first server that has resources.
320
+ if (connection.state === "connected" && connection.hasResources && this.#resourceTools.length === 0)
321
+ this.#changed();
322
+ }
323
+ #storedSignIn(connection) {
324
+ const url = connection.oauthUrl;
325
+ return url && this.#credentials ? JSON.stringify(this.#credentials.tokens(connection.name, url) ?? null) : "null";
326
+ }
327
+ /** Servers that needed a sign-in and whose stored sign-in changed since, for example by pots mcp login. */
328
+ #reconnectSignedIn() {
329
+ for (const server of this.#servers.values()) {
330
+ const connection = server.connection;
331
+ if (!connection || server.signIn === undefined || this.#storedSignIn(connection) === server.signIn)
332
+ continue;
333
+ server.signIn = undefined;
334
+ const previous = server.ready;
335
+ server.ready = (async () => {
336
+ await previous;
337
+ await connection.reconnect().catch(() => undefined);
338
+ })();
339
+ }
340
+ }
341
+ #changed() {
342
+ const withResources = this.#resourceServers().length > 0;
343
+ if (withResources !== this.#resourceTools.length > 0) {
344
+ this.#resourceTools = withResources
345
+ ? this.#pi.createMcpResourceToolDefinitions({ exposure: "codemode", servers: () => this.#resourceServers() }).map(scriptTool)
346
+ : [];
347
+ }
348
+ this.#extension = defineExtension({ name: "mcp", tools: [...[...this.#tools.values()].flat(), ...this.#resourceTools] });
349
+ for (const listener of this.#listeners)
350
+ listener();
351
+ }
352
+ }
353
+ //# sourceMappingURL=mcp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp.js","sourceRoot":"","sources":["../../src/agent/mcp.ts"],"names":[],"mappings":";;;;;;;;AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAIjC,OAAO,EAAE,eAAe,EAAE,UAAU,EAAyC,MAAM,4BAA4B,CAAC;AAEhH,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,wHAAwH;AACxH,sHAAsH;AACtH,sHAAsH;AACtH,sHAAsH;AACtH,qHAAqH;AACrH,kEAAkE;AAElE,yGAAyG;AACzG,MAAM,UAAU,GAAG,wDAAwD,CAAC;AAC5E,mHAAmH;AACnH,MAAM,SAAS,GAAG,4DAA4D,CAAC;AAC/E,oEAAoE;AACpE,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC,CAAC,oBAAoB,EAAE,6BAA6B,EAAE,mBAAmB,CAAC,CAAC,CAAC;AA4E3G,KAAK,UAAU,MAAM;IACnB,MAAM,CAAC,EAAE,WAAW,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;QACxF,MAAM,CAAC,iCAAiC,CAAC;QACzC,MAAM,kCAAC,QAAQ,CAAC,4BAA4B,CAAC,EAAC;QAC9C,MAAM,kCAAC,QAAQ,CAAC,uBAAuB,CAAC,EAAC;QACzC,MAAM,kCAAC,QAAQ,CAAC,2BAA2B,CAAC,EAAC;QAC7C,MAAM,kCAAC,QAAQ,CAAC,+BAA+B,CAAC,EAAC;QACjD,MAAM,kCAAC,QAAQ,CAAC,2BAA2B,CAAC,EAAC;KAC9C,CAAC,CAAC;IACH,OAAO,EAAE,WAAW,EAAE,GAAG,MAAM,EAAE,GAAG,OAAO,EAAE,GAAG,KAAK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AM,CAAC,MAAM,GAAG,SAAS,CAAC;YAC1B,MAAM,QAAQ,GAAG,MAAM,CAAC,KAAK,CAAC;YAC9B,MAAM,CAAC,KAAK,GAAG,CAAC,KAAK,IAAI,EAAE;gBACzB,MAAM,QAAQ,CAAC;gBACf,MAAM,UAAU,CAAC,SAAS,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;YACtD,CAAC,CAAC,EAAE,CAAC;QACP,CAAC;IACH,CAAC;IAED,QAAQ;QACN,MAAM,aAAa,GAAG,IAAI,CAAC,gBAAgB,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC;QACzD,IAAI,aAAa,KAAK,IAAI,CAAC,cAAc,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACrD,IAAI,CAAC,cAAc,GAAG,aAAa;gBACjC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,gCAAgC,CAAC,EAAE,QAAQ,EAAE,UAAU,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,gBAAgB,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC;gBAC7H,CAAC,CAAC,EAAE,CAAC;QACT,CAAC;QACD,IAAI,CAAC,UAAU,GAAG,eAAe,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,IAAI,EAAE,EAAE,GAAG,IAAI,CAAC,cAAc,CAAC,EAAE,CAAC,CAAC;QACzH,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,UAAU;YAAE,QAAQ,EAAE,CAAC;IACrD,CAAC;CACF"}
@@ -9,12 +9,13 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
9
9
  import { piModule } from "./models.js";
10
10
  export async function openResources(cwd, log) {
11
11
  // The loader from pi's public entry; pi does not export how it writes the two sections.
12
- const [{ DefaultResourceLoader: Loader, getAgentDir }, { buildSystemPromptSections }] = await Promise.all([
12
+ const [{ DefaultResourceLoader: Loader, getAgentDir, SettingsManager }, { buildSystemPromptSections }] = await Promise.all([
13
13
  import("@earendil-works/pi-coding-agent"),
14
14
  import(__rewriteRelativeImportExtension(piModule("./core/system-prompt.js"))),
15
15
  ]);
16
16
  // Only what a pi session puts in its system prompt; pi's extensions, prompt templates and themes are for its terminal.
17
- const loader = new Loader({ cwd, agentDir: getAgentDir(), noExtensions: true, noPromptTemplates: true, noThemes: true });
17
+ const settingsManager = SettingsManager.create(cwd, getAgentDir());
18
+ const loader = new Loader({ cwd, agentDir: getAgentDir(), settingsManager, noExtensions: true, noPromptTemplates: true, noThemes: true });
18
19
  let sections = {};
19
20
  let warnings = "";
20
21
  const load = async () => {
@@ -33,6 +34,7 @@ export async function openResources(cwd, log) {
33
34
  reload: () => (loading ??= load().finally(() => (loading = undefined))),
34
35
  projectContext: () => sections.project_context,
35
36
  skills: () => sections.skills,
37
+ projectTrusted: () => settingsManager.isProjectTrusted(),
36
38
  };
37
39
  await resources.reload();
38
40
  return resources;
@@ -1 +1 @@
1
- {"version":3,"file":"resources.js","sourceRoot":"","sources":["../../src/agent/resources.ts"],"names":[],"mappings":";;;;;;;;AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAuBvC,MAAM,CAAC,KAAK,UAAU,aAAa,CAAC,GAAW,EAAE,GAA8D;IAC7G,wFAAwF;IACxF,MAAM,CAAC,EAAE,qBAAqB,EAAE,MAAM,EAAE,WAAW,EAAE,EAAE,EAAE,yBAAyB,EAAE,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;QACxG,MAAM,CAAC,iCAAiC,CAAC;QACzC,MAAM,kCAAC,QAAQ,CAAC,yBAAyB,CAAC,EAA0D;KACrG,CAAC,CAAC;IACH,uHAAuH;IACvH,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,EAAE,GAAG,EAAE,QAAQ,EAAE,WAAW,EAAE,EAA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CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,GAAG,UAAU,CAAC,IAAI,IAAI,EAAE,KAAK,UAAU,CAAC,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC1G,IAAI,GAAG,IAAI,GAAG,KAAK,QAAQ;YAAE,GAAG,CAAC,gBAAgB,EAAE,EAAE,QAAQ,EAAE,GAAG,EAAE,CAAC,CAAC;QACtE,QAAQ,GAAG,GAAG,CAAC;IACjB,CAAC,CAAC;IACF,+DAA+D;IAC/D,IAAI,OAAkC,CAAC;IACvC,MAAM,SAAS,GAAgB;QAC7B,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC,OAAO,KAAK,IAAI,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,OAAO,GAAG,SAAS,CAAC,CAAC,CAAC;QACvE,cAAc,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,eAAe;QAC9C,MAAM,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,MAAM;QAC7B,cAAc,EAAE,GAAG,EAAE,CAAC,eAAe,CAAC,gBAAgB,EAAE;KACzD,CAAC;IACF,MAAM,SAAS,CAAC,MAAM,EAAE,CAAC;IACzB,OAAO,SAAS,CAAC;AACnB,CAAC"}
package/dist/bot/bot.js CHANGED
@@ -4,15 +4,21 @@ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
4
4
  import { homedir } from "node:os";
5
5
  import { basename, delimiter, dirname, join } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
+ import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
8
+ import { NodeExecutionEnv } from "@earendil-works/pi-durable/env/node";
7
9
  import { Agent, openDatabase } from "../agent/agent.js";
8
10
  import { describeChild, reportRequestId } from "../agent/children.js";
11
+ import { createCodemode } from "../agent/codemode.js";
9
12
  import { SCREEN_VARIABLES, screenOf } from "../agent/screen.js";
10
13
  import { createJudge } from "../agent/judge.js";
14
+ import { Mcp } from "../agent/mcp.js";
11
15
  import { openResources } from "../agent/resources.js";
12
16
  import { loadChannel } from "../channels/load.js";
13
17
  import { MEMORY_DIR, SECRETS_DIR } from "../core/home.js";
14
18
  import { VERSION } from "../core/version.js";
19
+ import { formatTime } from "../core/time.js";
15
20
  import { Gateway } from "../gateway/gateway.js";
21
+ import { describeSchedule, describeWork, renderRoutines } from "../gateway/routines.js";
16
22
  import { ControlServer } from "./control.js";
17
23
  import { botPaths } from "./definition.js";
18
24
  import { describeMachine } from "./machine.js";
@@ -147,12 +153,23 @@ export class Bot {
147
153
  const current = () => (bot ? bot.#definition : definition);
148
154
  const settings = () => current().settings;
149
155
  const judge = createJudge(definition.judge, env.models, () => current().model);
156
+ // The environment of bash commands, of routines' commands and of the stdio MCP servers. Without the screen's variables: a command that uses
157
+ // the screen goes through the screen tool, which holds the screen for one agent at a time. Without POTS_FROM, which
158
+ // only a routine's command has.
159
+ const left = new Set([...SCREEN_VARIABLES, "POTS_FROM"]);
160
+ const shellEnv = {
161
+ ...Object.fromEntries(Object.entries(process.env).filter((entry) => entry[1] !== undefined && !left.has(entry[0]))),
162
+ POTS_BOT: id,
163
+ PATH: `${dirname(env.potsCommand)}${delimiter}${process.env.PATH ?? ""}`,
164
+ HOME: process.env.HOME ?? homedir(),
165
+ };
150
166
  const gateway = await Gateway.open(sql, {
151
167
  bot: id,
152
168
  judge: () => (bot ? bot.#judge : judge),
153
169
  settings,
154
170
  fallbackWakeMinutes: () => settings().fallbackWakeMinutes,
155
171
  fireTimer: (timer, caller) => self().#deliverTimer(timer, caller),
172
+ runCommand: commandRunner(paths.workspace, shellEnv),
156
173
  filesDir: paths.files,
157
174
  print,
158
175
  });
@@ -182,6 +199,19 @@ export class Bot {
182
199
  },
183
200
  };
184
201
  const skills = { name: "skills", render: () => resources.skills() ?? NO_SKILLS };
202
+ // MCP servers from pi's mcp.json, which pi and pots mcp share; they connect now, in the background. Read again before
203
+ // each request, so a change counts from the next wake.
204
+ const mcp = await Mcp.open({ cwd: paths.workspace, projectTrusted: () => resources.projectTrusted(), env: shellEnv, models: env.models, log: print });
205
+ // pi's code mode, for every agent of the bot; its scripts call the servers' tools.
206
+ const codemode = createCodemode(() => mcp.namespaces());
207
+ const codemodeSection = { name: "codemode", render: codemode.section };
208
+ const mcpServers = {
209
+ name: "mcp_servers",
210
+ render: () => {
211
+ mcp.reload();
212
+ return mcp.section();
213
+ },
214
+ };
185
215
  // The memory, as Claude Code's auto memory: files in the bot's memory folder and in the one all bots share.
186
216
  const folders = { own: paths.memory, shared: MEMORY_DIR };
187
217
  const memoryOn = () => settings().autoMemory;
@@ -195,19 +225,13 @@ export class Bot {
195
225
  thinking: definition.thinking,
196
226
  compaction: () => settings().compaction,
197
227
  workspace: paths.workspace,
198
- // Without the screen's variables: a command that uses the screen goes through the screen tool, which holds the
199
- // screen for one agent at a time.
200
- shellEnv: {
201
- ...Object.fromEntries(Object.entries(process.env).filter(([name]) => !SCREEN_VARIABLES.includes(name))),
202
- POTS_BOT: id,
203
- PATH: `${dirname(env.potsCommand)}${delimiter}${process.env.PATH ?? ""}`,
204
- HOME: process.env.HOME ?? homedir(),
205
- },
228
+ shellEnv,
206
229
  screen: { current: () => screenOf(current().screen, process.env), bot: paths.dir, name: () => current().name },
207
230
  // The start of every request, so the provider's prompt cache can keep it: only facts that stay the same. What
208
231
  // changes from one wake to the next (the time, the context use, the bot's own address in a channel) is in the
209
232
  // wake. The bot's own sections are pinned for the page; a new name shows at once, as AGENTS.md and skills do,
210
- // since people change them on purpose. New sections go at the end, and every section always has a text.
233
+ // since people change them on purpose. New sections go at the end, before the memory, and every section but the
234
+ // memory always has a text.
211
235
  sections: [
212
236
  { name: "identity", render: () => identitySection(facts()) },
213
237
  { name: "work", render: () => workSection(facts()), pin: true },
@@ -217,6 +241,8 @@ export class Bot {
217
241
  { name: "memory", render: () => contextSection(facts()), pin: true },
218
242
  projectContext,
219
243
  skills,
244
+ codemodeSection,
245
+ mcpServers,
220
246
  // Without the memory, no section: it is the last one, so the others stay where they are.
221
247
  { name: "remembered", render: async () => (memoryOn() ? memorySection(facts(), await indexes()) : undefined), pin: true },
222
248
  ],
@@ -232,6 +258,8 @@ export class Bot {
232
258
  { name: "folder", render: () => folderSection(facts(), true) },
233
259
  projectContext,
234
260
  skills,
261
+ codemodeSection,
262
+ mcpServers,
235
263
  { name: "remembered", render: async () => (memoryOn() ? childMemorySection(facts(), await indexes()) : undefined), pin: true },
236
264
  ],
237
265
  place: () => (bot ? bot.#currentPlace() : undefined),
@@ -258,9 +286,12 @@ export class Bot {
258
286
  react: (message, emoji, remove, trace) => self().react(message, emoji, remove, trace),
259
287
  call: (channel, method, params, trace) => self().call(channel, method, params, trace),
260
288
  },
289
+ codemode,
290
+ mcp,
261
291
  telemetry: gateway.telemetry,
262
292
  log: print,
263
293
  }).catch(async (error) => {
294
+ await mcp.close();
264
295
  await gateway.stop().catch(() => { });
265
296
  throw error;
266
297
  });
@@ -401,7 +432,7 @@ export class Bot {
401
432
  }
402
433
  async #deliverTimer(timer, caller) {
403
434
  const text = renderTimerWake(timer, await this.#agent.contextStatus(), this.#definition.settings.fallbackWakeMinutes, this.#workingChildren());
404
- return this.#submit(`timer:${timer.id}`, timer.set_by === "fallback" ? "fallback" : "timer", undefined, text, false, caller);
435
+ return this.#submit(`timer:${timer.id}`, timer.set_by === "agent" ? "timer" : timer.set_by, undefined, text, false, caller);
405
436
  }
406
437
  /** A child ended: a wake for the main agent, once per reporter, also when this runs again after a restart. */
407
438
  async #deliverChildEnd(end) {
@@ -500,7 +531,11 @@ export class Bot {
500
531
  "POST /call": async (body) => this.call(text(body.channel, "channel"), text(body.method, "method"), body.params ?? {}),
501
532
  "POST /wake": async (body) => {
502
533
  const at = typeof body.at === "number" ? body.at : Date.now();
503
- return this.#timers.add(at, typeof body.note === "string" ? body.note : "");
534
+ const options = {
535
+ ...(typeof body.from === "string" && body.from ? { source: body.from } : {}),
536
+ ...(typeof body.id === "string" && body.id ? { requestId: body.id } : {}),
537
+ };
538
+ return this.#timers.add(at, typeof body.note === "string" ? body.note : "", options);
504
539
  },
505
540
  "GET /wakes": async () => this.#timers.pending(),
506
541
  "POST /wakes/cancel": async (body) => {
@@ -508,6 +543,31 @@ export class Bot {
508
543
  throw new Error(`no pending wake ${String(body.id)}`);
509
544
  return "cancelled";
510
545
  },
546
+ "GET /routines": async () => {
547
+ const listing = await this.#timers.routines();
548
+ return { ...listing, text: renderRoutines(listing, Date.now()) };
549
+ },
550
+ "POST /routines/add": async (body) => {
551
+ const input = { name: text(body.name, "name") };
552
+ if (typeof body.every === "number")
553
+ input.every = body.every;
554
+ if (typeof body.cron === "string")
555
+ input.cron = body.cron;
556
+ if (typeof body.note === "string")
557
+ input.note = body.note;
558
+ if (typeof body.run === "string")
559
+ input.run = body.run;
560
+ if (typeof body.timeout === "number")
561
+ input.timeout = body.timeout;
562
+ const { routine, replaced } = await this.#timers.addRoutine(input);
563
+ return `${replaced ? "Replaced" : "Added"} routine ${routine.name}: ${describeSchedule(routine)}, ${describeWork(routine)}\n next: ${formatTime(routine.next_at)}`;
564
+ },
565
+ "POST /routines/remove": async (body) => {
566
+ const name = text(body.name, "name");
567
+ if (!(await this.#timers.removeRoutine(name)))
568
+ throw new Error(`there is no routine ${JSON.stringify(name)}`);
569
+ return `Removed routine ${name}.`;
570
+ },
511
571
  "GET /context": async () => {
512
572
  const [status, cache] = await Promise.all([this.#agent.contextStatus(), this.#agent.cacheUse()]);
513
573
  return { ...status, cache, text: `${renderContext(status)}\n${renderCacheUse(cache)}` };
@@ -538,4 +598,12 @@ export class Bot {
538
598
  };
539
599
  }
540
600
  }
601
+ /** Runs a routine's command as the bash tool runs one: the same shell, environment and working directory. */
602
+ function commandRunner(workspace, shellEnv) {
603
+ const shell = new NodeExecutionEnv({ cwd: workspace, shellEnv });
604
+ return async (command, env, signal, onOutput) => {
605
+ const result = await shell.exec(command, { env: { ...shellEnv, ...env }, inheritEnv: false, onOutput: (text) => onOutput(text) }, withAbortSignal(signal, BACKGROUND_CONTEXT));
606
+ return result.ok ? { exitCode: result.value.exitCode } : { error: result.error.message };
607
+ };
608
+ }
541
609
  //# sourceMappingURL=bot.js.map