@pmndre/pine 0.36.0 → 0.37.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.
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
- return send(200, this.sources?.available(parts[1]) ?? []);
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
- const body = (await this.json(req, isPrompt ? 64 * MAX_BODY : MAX_BODY));
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
- export declare function logout(cfg: PineConfig, provider: string): Promise<void>;
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
- export async function logout(cfg, provider) {
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
- console.log(`Removed the stored credential for ${provider}.`);
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
+ }