@dev-crowagent/pigeon-server 0.0.0-stage → 1.7.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 (46) hide show
  1. package/README.md +146 -2
  2. package/dist/auth.d.ts +12 -0
  3. package/dist/auth.d.ts.map +1 -0
  4. package/dist/auth.js +38 -0
  5. package/dist/auth.js.map +1 -0
  6. package/dist/host.d.ts +25 -0
  7. package/dist/host.d.ts.map +1 -0
  8. package/dist/host.js +82 -0
  9. package/dist/host.js.map +1 -0
  10. package/dist/http.d.ts +24 -0
  11. package/dist/http.d.ts.map +1 -0
  12. package/dist/http.js +278 -0
  13. package/dist/http.js.map +1 -0
  14. package/dist/index.d.ts +11 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +13 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/keys.d.ts +32 -0
  19. package/dist/keys.d.ts.map +1 -0
  20. package/dist/keys.js +190 -0
  21. package/dist/keys.js.map +1 -0
  22. package/dist/model.d.ts +22 -0
  23. package/dist/model.d.ts.map +1 -0
  24. package/dist/model.js +123 -0
  25. package/dist/model.js.map +1 -0
  26. package/dist/permissions.d.ts +43 -0
  27. package/dist/permissions.d.ts.map +1 -0
  28. package/dist/permissions.js +81 -0
  29. package/dist/permissions.js.map +1 -0
  30. package/dist/sessions.d.ts +81 -0
  31. package/dist/sessions.d.ts.map +1 -0
  32. package/dist/sessions.js +320 -0
  33. package/dist/sessions.js.map +1 -0
  34. package/dist/tools.d.ts +12 -0
  35. package/dist/tools.d.ts.map +1 -0
  36. package/dist/tools.js +383 -0
  37. package/dist/tools.js.map +1 -0
  38. package/dist/types.d.ts +108 -0
  39. package/dist/types.d.ts.map +1 -0
  40. package/dist/types.js +2 -0
  41. package/dist/types.js.map +1 -0
  42. package/dist/workspace.d.ts +22 -0
  43. package/dist/workspace.d.ts.map +1 -0
  44. package/dist/workspace.js +53 -0
  45. package/dist/workspace.js.map +1 -0
  46. package/package.json +50 -5
package/README.md CHANGED
@@ -1,3 +1,147 @@
1
- # Temporary Holding Version
1
+ # @dev-crowagent/pigeon-server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Embeddable multi-user host for the pigeon agent SDK. One host serves many
4
+ isolated users over HTTP + SSE, or a single fixed user with no auth for local
5
+ use. Same code path, two modes.
6
+
7
+ Zero framework dependencies: Node's built-in `http` only.
8
+
9
+ ## Quick start
10
+
11
+ ### Single user (local, no auth)
12
+
13
+ ```ts
14
+ import { createServerHost } from "@dev-crowagent/pigeon-server";
15
+
16
+ const host = createServerHost({
17
+ mode: "single",
18
+ dataDir: "~/.pigeon/server",
19
+ port: 8787,
20
+ });
21
+ const { port } = await host.start();
22
+ console.log(`listening on http://127.0.0.1:${port}`);
23
+ ```
24
+
25
+ ### Multi user (token auth)
26
+
27
+ ```ts
28
+ import { createServerHost } from "@dev-crowagent/pigeon-server";
29
+
30
+ const host = createServerHost({
31
+ mode: "multi",
32
+ dataDir: "/var/lib/pigeon-server",
33
+ port: 8787,
34
+ host: "0.0.0.0",
35
+ tokens: {
36
+ alice: "tok-alice-...",
37
+ bob: "tok-bob-...",
38
+ },
39
+ });
40
+ await host.start();
41
+ ```
42
+
43
+ Or bring your own auth (JWT, session cookie, OAuth — anything):
44
+
45
+ ```ts
46
+ const host = createServerHost({
47
+ mode: "multi",
48
+ dataDir: "/var/lib/pigeon-server",
49
+ authenticate: async ({ authorization }) => {
50
+ if (!authorization?.startsWith("Bearer ")) return null;
51
+ return verifyJwt(authorization.slice(7))?.sub ?? null;
52
+ },
53
+ });
54
+ ```
55
+
56
+ > Production note: the built-in token auth is a simple default. For real
57
+ > deployments plug in proper auth (short-lived tokens, rotation, revocation)
58
+ > via `authenticate`. Never ship a hardcoded bypass or a default-allow mode —
59
+ > the host refuses to start in multi-user mode without auth.
60
+
61
+ ## Isolation model
62
+
63
+ Every user gets a private directory tree under `<dataDir>/users/<userId>/`:
64
+
65
+ | Path | Contents |
66
+ | --- | --- |
67
+ | `workspace/` | The agent's working directory. Tools are jailed here; `..` escapes are rejected. |
68
+ | `sessions/` | Session transcripts (one JSON file per session). |
69
+ | `memory/` | The kit memory store (core + project + session memory). |
70
+ | `settings.json` | User settings: custom providers, default model. |
71
+ | `keys.json` | Provider API keys (mode 0600). Never shared between users. |
72
+ | `permissions/` | Per-user tool permission rules (user / project / local). |
73
+
74
+ Additional guarantees:
75
+
76
+ - One `Agent` instance per user session, created on demand, evicted after
77
+ 30 minutes idle (configurable via `sessionIdleMs`).
78
+ - Per-session promise queue: one user's long run never blocks another user,
79
+ and one session never runs two prompts concurrently.
80
+ - The shared model catalog carries descriptors only — no credentials. Keys
81
+ resolve per call through the Agent's `getApiKey`, from the caller's own
82
+ `keys.json` (multi-user mode never reads the process environment for keys;
83
+ single-user mode falls back to env vars like the CLI).
84
+ - The kit skill queue is instance-scoped (`SkillContentQueue`): skill content
85
+ loaded by one session can only drain into that session's next turn.
86
+ - Permission rules load from the user's own rules files, with the kit loader
87
+ called with explicit per-user paths. Default mode is unrestricted; deny
88
+ rules apply; ask rules pause the tool call and either call the host's
89
+ `onApprovalRequest` callback or wait for a client answer on
90
+ `POST /api/sessions/:id/approvals` (120 s timeout, then deny).
91
+
92
+ ## HTTP API
93
+
94
+ All `/api/*` routes require a bearer token in multi-user mode
95
+ (`Authorization: Bearer <token>`). In single-user mode no header is needed.
96
+ Missing or invalid tokens get `401` and never create a session.
97
+
98
+ | Method | Route | Description |
99
+ | --- | --- | --- |
100
+ | `GET` | `/health` | `{ ok: true, mode }`. No auth. |
101
+ | `POST` | `/api/sessions` | Create a session. Body: `{ "model": "anthropic/claude-haiku-4-5" }` (optional). Returns the session. |
102
+ | `GET` | `/api/sessions` | List the caller's sessions. |
103
+ | `GET` | `/api/sessions/:id` | One session. |
104
+ | `DELETE` | `/api/sessions/:id` | Delete a session and its transcript. |
105
+ | `POST` | `/api/sessions/:id/prompt` | Send a prompt. Body: `{ "text": "..." }`. Streams SSE events until the run ends. |
106
+ | `POST` | `/api/sessions/:id/abort` | Abort the running prompt. |
107
+ | `POST` | `/api/sessions/:id/approvals` | Answer a pending approval. Body: `{ "requestId": "...", "approved": true }`. |
108
+ | `GET` | `/api/users/me/keys` | Providers the caller has keys for. |
109
+ | `POST` | `/api/users/me/keys` | Set a key. Body: `{ "provider": "anthropic", "key": "sk-ant-..." }`. |
110
+ | `DELETE` | `/api/users/me/keys/:provider` | Remove a key. |
111
+ | `GET` | `/api/users/me/providers` | The caller's custom OpenAI-compatible providers (no keys). |
112
+ | `POST` | `/api/users/me/providers` | Add one. Body: `{ "slug", "baseUrl", "models": ["..."], "apiKey"? }`. |
113
+ | `DELETE` | `/api/users/me/providers/:slug` | Remove one. |
114
+
115
+ ### SSE events (`POST /api/sessions/:id/prompt`)
116
+
117
+ ```json
118
+ {"type": "text", "text": "Here is"}
119
+ {"type": "text", "text": " the plan."}
120
+ {"type": "tool_start", "toolCallId": "call-1", "toolName": "read_file"}
121
+ {"type": "tool_end", "toolCallId": "call-1", "toolName": "read_file", "isError": false}
122
+ {"type": "approval_request", "request": {"id": "approval-1-x", "sessionId": "...", "toolName": "run_command", "args": {...}}}
123
+ {"type": "done", "text": "Here is the plan.", "toolCalls": 1}
124
+ {"type": "error", "message": "..."}
125
+ ```
126
+
127
+ Events arrive in order; `done` closes the stream. Closing the connection
128
+ aborts the run.
129
+
130
+ ## Tools
131
+
132
+ Each session gets workspace-jailed tools only: `read_file`, `write_file`,
133
+ `edit_file`, `list_dir`, `run_command`, `grep`, `find_files`, plus `recall`,
134
+ `read_memory`, `list_memories`, `write_memory` (kit memory, scoped to the
135
+ user) and `skill` (loads a skill from the user's workspace or memory roots
136
+ into that session only). No shell access outside the workspace, no global
137
+ skills.
138
+
139
+ ## CLI
140
+
141
+ `pigeon serve` starts the host: single-user mode by default, multi-user mode
142
+ with a config file. See `pigeon serve --help`.
143
+
144
+ ## Examples
145
+
146
+ - `examples/single-agent.ts` — one agent, ~20 lines.
147
+ - `examples/multi-user.ts` — two users with per-user workspaces.
package/dist/auth.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ import type { Authenticate, UserId } from "./types.ts";
2
+ /** Extracts a bearer token from an Authorization header value. */
3
+ export declare function parseBearerToken(authorization: string | undefined): string | undefined;
4
+ /**
5
+ * Token auth for multi-user mode: a map of user id to bearer token. Tokens
6
+ * are compared in constant time. No token matches the empty string, and
7
+ * there is no default-allow path: unknown users and missing tokens return null.
8
+ */
9
+ export declare function createTokenAuth(tokens: Readonly<Record<string, string>>): Authenticate;
10
+ /** Single-user mode auth: every request is the fixed local user, no token needed. */
11
+ export declare function createSingleUserAuth(userId: UserId): Authenticate;
12
+ //# sourceMappingURL=auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAEvD,kEAAkE;AAClE,wBAAgB,gBAAgB,CAAC,aAAa,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAItF;AASD;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GAAG,YAAY,CAUtF;AAED,qFAAqF;AACrF,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,YAAY,CAEjE"}
package/dist/auth.js ADDED
@@ -0,0 +1,38 @@
1
+ import { timingSafeEqual } from "node:crypto";
2
+ /** Extracts a bearer token from an Authorization header value. */
3
+ export function parseBearerToken(authorization) {
4
+ if (authorization === undefined)
5
+ return undefined;
6
+ const match = /^Bearer (.+)$/.exec(authorization.trim());
7
+ return match?.[1];
8
+ }
9
+ function tokensEqual(left, right) {
10
+ const leftBuffer = Buffer.from(left, "utf8");
11
+ const rightBuffer = Buffer.from(right, "utf8");
12
+ if (leftBuffer.length !== rightBuffer.length)
13
+ return false;
14
+ return timingSafeEqual(leftBuffer, rightBuffer);
15
+ }
16
+ /**
17
+ * Token auth for multi-user mode: a map of user id to bearer token. Tokens
18
+ * are compared in constant time. No token matches the empty string, and
19
+ * there is no default-allow path: unknown users and missing tokens return null.
20
+ */
21
+ export function createTokenAuth(tokens) {
22
+ const entries = Object.entries(tokens).filter(([, token]) => token !== "");
23
+ return (context) => {
24
+ const presented = parseBearerToken(context.authorization);
25
+ if (presented === undefined)
26
+ return null;
27
+ for (const [userId, token] of entries) {
28
+ if (tokensEqual(presented, token))
29
+ return userId;
30
+ }
31
+ return null;
32
+ };
33
+ }
34
+ /** Single-user mode auth: every request is the fixed local user, no token needed. */
35
+ export function createSingleUserAuth(userId) {
36
+ return () => userId;
37
+ }
38
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAG9C,kEAAkE;AAClE,MAAM,UAAU,gBAAgB,CAAC,aAAiC;IACjE,IAAI,aAAa,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IAClD,MAAM,KAAK,GAAG,eAAe,CAAC,IAAI,CAAC,aAAa,CAAC,IAAI,EAAE,CAAC,CAAC;IACzD,OAAO,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC;AACnB,CAAC;AAED,SAAS,WAAW,CAAC,IAAY,EAAE,KAAa;IAC/C,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IAC7C,MAAM,WAAW,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC/C,IAAI,UAAU,CAAC,MAAM,KAAK,WAAW,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IAC3D,OAAO,eAAe,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;AACjD,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAAC,MAAwC;IACvE,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,KAAK,EAAE,CAAC,CAAC;IAC3E,OAAO,CAAC,OAAO,EAAE,EAAE;QAClB,MAAM,SAAS,GAAG,gBAAgB,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;QAC1D,IAAI,SAAS,KAAK,SAAS;YAAE,OAAO,IAAI,CAAC;QACzC,KAAK,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,IAAI,OAAO,EAAE,CAAC;YACvC,IAAI,WAAW,CAAC,SAAS,EAAE,KAAK,CAAC;gBAAE,OAAO,MAAM,CAAC;QAClD,CAAC;QACD,OAAO,IAAI,CAAC;IACb,CAAC,CAAC;AACH,CAAC;AAED,qFAAqF;AACrF,MAAM,UAAU,oBAAoB,CAAC,MAAc;IAClD,OAAO,GAAG,EAAE,CAAC,MAAM,CAAC;AACrB,CAAC","sourcesContent":["import { timingSafeEqual } from \"node:crypto\";\nimport type { Authenticate, UserId } from \"./types.ts\";\n\n/** Extracts a bearer token from an Authorization header value. */\nexport function parseBearerToken(authorization: string | undefined): string | undefined {\n\tif (authorization === undefined) return undefined;\n\tconst match = /^Bearer (.+)$/.exec(authorization.trim());\n\treturn match?.[1];\n}\n\nfunction tokensEqual(left: string, right: string): boolean {\n\tconst leftBuffer = Buffer.from(left, \"utf8\");\n\tconst rightBuffer = Buffer.from(right, \"utf8\");\n\tif (leftBuffer.length !== rightBuffer.length) return false;\n\treturn timingSafeEqual(leftBuffer, rightBuffer);\n}\n\n/**\n * Token auth for multi-user mode: a map of user id to bearer token. Tokens\n * are compared in constant time. No token matches the empty string, and\n * there is no default-allow path: unknown users and missing tokens return null.\n */\nexport function createTokenAuth(tokens: Readonly<Record<string, string>>): Authenticate {\n\tconst entries = Object.entries(tokens).filter(([, token]) => token !== \"\");\n\treturn (context) => {\n\t\tconst presented = parseBearerToken(context.authorization);\n\t\tif (presented === undefined) return null;\n\t\tfor (const [userId, token] of entries) {\n\t\t\tif (tokensEqual(presented, token)) return userId;\n\t\t}\n\t\treturn null;\n\t};\n}\n\n/** Single-user mode auth: every request is the fixed local user, no token needed. */\nexport function createSingleUserAuth(userId: UserId): Authenticate {\n\treturn () => userId;\n}\n"]}
package/dist/host.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import { SessionManager } from "./sessions.ts";
2
+ import type { PigeonServerHostOptions } from "./types.ts";
3
+ export declare const DEFAULT_MODEL_REF = "anthropic/claude-haiku-4-5";
4
+ export declare const DEFAULT_SESSION_IDLE_MS: number;
5
+ /** A running multi-user (or single-user) pigeon host. */
6
+ export declare class PigeonServerHost {
7
+ private readonly options;
8
+ private readonly authenticate;
9
+ private readonly sessions;
10
+ private server;
11
+ private readonly dataDir;
12
+ constructor(options: PigeonServerHostOptions);
13
+ /** Starts listening. Returns the bound address. */
14
+ start(): Promise<{
15
+ host: string;
16
+ port: number;
17
+ }>;
18
+ /** Stops listening, stops eviction, and disposes every session. */
19
+ stop(): Promise<void>;
20
+ /** Live sessions, for embedding hosts that need them. */
21
+ get sessionManager(): SessionManager;
22
+ }
23
+ /** Creates a host. Call start() to listen. */
24
+ export declare function createServerHost(options: PigeonServerHostOptions): PigeonServerHost;
25
+ //# sourceMappingURL=host.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host.d.ts","sourceRoot":"","sources":["../src/host.ts"],"names":[],"mappings":"AAIA,OAAO,EAMN,cAAc,EACd,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EAAgB,uBAAuB,EAAE,MAAM,YAAY,CAAC;AAExE,eAAO,MAAM,iBAAiB,+BAA+B,CAAC;AAC9D,eAAO,MAAM,uBAAuB,QAAiB,CAAC;AAEtD,yDAAyD;AACzD,qBAAa,gBAAgB;IAC5B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA0B;IAClD,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAe;IAC5C,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAiB;IAC1C,OAAO,CAAC,MAAM,CAAqB;IACnC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IAEjC,YAAY,OAAO,EAAE,uBAAuB,EAa3C;IAED,mDAAmD;IAC7C,KAAK,IAAI,OAAO,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,CA+BrD;IAED,mEAAmE;IAC7D,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAQ1B;IAED,yDAAyD;IACzD,IAAI,cAAc,IAAI,cAAc,CAEnC;CACD;AAED,8CAA8C;AAC9C,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,uBAAuB,GAAG,gBAAgB,CAEnF"}
package/dist/host.js ADDED
@@ -0,0 +1,82 @@
1
+ import { createServer } from "node:http";
2
+ import { resolve } from "node:path";
3
+ import { createSingleUserAuth, createTokenAuth } from "./auth.js";
4
+ import { createHttpHandler } from "./http.js";
5
+ import { DEFAULT_BASH_TIMEOUT_SECONDS, DEFAULT_MAX_TOOL_OUTPUT_CHARS, DEFAULT_MAX_TURNS, DEFAULT_SYSTEM_PROMPT, ensureModelCatalog, SessionManager, } from "./sessions.js";
6
+ export const DEFAULT_MODEL_REF = "anthropic/claude-haiku-4-5";
7
+ export const DEFAULT_SESSION_IDLE_MS = 30 * 60 * 1000;
8
+ /** A running multi-user (or single-user) pigeon host. */
9
+ export class PigeonServerHost {
10
+ options;
11
+ authenticate;
12
+ sessions;
13
+ server;
14
+ dataDir;
15
+ constructor(options) {
16
+ if (options.mode === "multi" && !options.authenticate && !options.tokens) {
17
+ throw new Error("Multi-user mode needs auth: pass authenticate or tokens. There is no default-allow mode.");
18
+ }
19
+ this.options = options;
20
+ this.dataDir = resolve(options.dataDir);
21
+ this.authenticate =
22
+ options.authenticate ??
23
+ (options.tokens ? createTokenAuth(options.tokens) : createSingleUserAuth(options.singleUserId ?? "local"));
24
+ this.sessions = new SessionManager({
25
+ dataDir: this.dataDir,
26
+ sessionIdleMs: options.sessionIdleMs ?? DEFAULT_SESSION_IDLE_MS,
27
+ });
28
+ }
29
+ /** Starts listening. Returns the bound address. */
30
+ async start() {
31
+ ensureModelCatalog();
32
+ const handler = createHttpHandler({
33
+ authenticate: this.authenticate,
34
+ mode: this.options.mode,
35
+ singleUserId: this.options.singleUserId ?? "local",
36
+ sessions: this.sessions,
37
+ dataDir: this.dataDir,
38
+ defaultModelRef: this.options.modelRef ?? DEFAULT_MODEL_REF,
39
+ modelOverride: this.options.model,
40
+ streamFn: this.options.streamFn,
41
+ systemPrompt: this.options.systemPrompt ?? DEFAULT_SYSTEM_PROMPT,
42
+ maxTurns: this.options.maxTurns ?? DEFAULT_MAX_TURNS,
43
+ maxToolOutputChars: this.options.maxToolOutputChars ?? DEFAULT_MAX_TOOL_OUTPUT_CHARS,
44
+ bashTimeoutSeconds: this.options.bashTimeoutSeconds ?? DEFAULT_BASH_TIMEOUT_SECONDS,
45
+ allowEnvKeys: this.options.mode === "single",
46
+ onApprovalRequest: this.options.onApprovalRequest,
47
+ });
48
+ this.server = createServer(handler);
49
+ this.sessions.startEviction();
50
+ const host = this.options.host ?? "127.0.0.1";
51
+ const port = this.options.port;
52
+ await new Promise((resolvePromise, reject) => {
53
+ this.server?.once("error", reject);
54
+ this.server?.listen(port, host, () => resolvePromise());
55
+ });
56
+ const address = this.server.address();
57
+ if (typeof address !== "object" || address === null) {
58
+ throw new Error("Server did not bind an address");
59
+ }
60
+ return { host: address.address, port: address.port };
61
+ }
62
+ /** Stops listening, stops eviction, and disposes every session. */
63
+ async stop() {
64
+ this.sessions.stopAll();
65
+ if (!this.server)
66
+ return;
67
+ const server = this.server;
68
+ this.server = undefined;
69
+ await new Promise((resolvePromise) => {
70
+ server.close(() => resolvePromise());
71
+ });
72
+ }
73
+ /** Live sessions, for embedding hosts that need them. */
74
+ get sessionManager() {
75
+ return this.sessions;
76
+ }
77
+ }
78
+ /** Creates a host. Call start() to listen. */
79
+ export function createServerHost(options) {
80
+ return new PigeonServerHost(options);
81
+ }
82
+ //# sourceMappingURL=host.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host.js","sourceRoot":"","sources":["../src/host.ts"],"names":[],"mappings":"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","sourcesContent":["import { createServer, type Server } from \"node:http\";\nimport { resolve } from \"node:path\";\nimport { createSingleUserAuth, createTokenAuth } from \"./auth.ts\";\nimport { createHttpHandler } from \"./http.ts\";\nimport {\n\tDEFAULT_BASH_TIMEOUT_SECONDS,\n\tDEFAULT_MAX_TOOL_OUTPUT_CHARS,\n\tDEFAULT_MAX_TURNS,\n\tDEFAULT_SYSTEM_PROMPT,\n\tensureModelCatalog,\n\tSessionManager,\n} from \"./sessions.ts\";\nimport type { Authenticate, PigeonServerHostOptions } from \"./types.ts\";\n\nexport const DEFAULT_MODEL_REF = \"anthropic/claude-haiku-4-5\";\nexport const DEFAULT_SESSION_IDLE_MS = 30 * 60 * 1000;\n\n/** A running multi-user (or single-user) pigeon host. */\nexport class PigeonServerHost {\n\tprivate readonly options: PigeonServerHostOptions;\n\tprivate readonly authenticate: Authenticate;\n\tprivate readonly sessions: SessionManager;\n\tprivate server: Server | undefined;\n\tprivate readonly dataDir: string;\n\n\tconstructor(options: PigeonServerHostOptions) {\n\t\tif (options.mode === \"multi\" && !options.authenticate && !options.tokens) {\n\t\t\tthrow new Error(\"Multi-user mode needs auth: pass authenticate or tokens. There is no default-allow mode.\");\n\t\t}\n\t\tthis.options = options;\n\t\tthis.dataDir = resolve(options.dataDir);\n\t\tthis.authenticate =\n\t\t\toptions.authenticate ??\n\t\t\t(options.tokens ? createTokenAuth(options.tokens) : createSingleUserAuth(options.singleUserId ?? \"local\"));\n\t\tthis.sessions = new SessionManager({\n\t\t\tdataDir: this.dataDir,\n\t\t\tsessionIdleMs: options.sessionIdleMs ?? DEFAULT_SESSION_IDLE_MS,\n\t\t});\n\t}\n\n\t/** Starts listening. Returns the bound address. */\n\tasync start(): Promise<{ host: string; port: number }> {\n\t\tensureModelCatalog();\n\t\tconst handler = createHttpHandler({\n\t\t\tauthenticate: this.authenticate,\n\t\t\tmode: this.options.mode,\n\t\t\tsingleUserId: this.options.singleUserId ?? \"local\",\n\t\t\tsessions: this.sessions,\n\t\t\tdataDir: this.dataDir,\n\t\t\tdefaultModelRef: this.options.modelRef ?? DEFAULT_MODEL_REF,\n\t\t\tmodelOverride: this.options.model,\n\t\t\tstreamFn: this.options.streamFn,\n\t\t\tsystemPrompt: this.options.systemPrompt ?? DEFAULT_SYSTEM_PROMPT,\n\t\t\tmaxTurns: this.options.maxTurns ?? DEFAULT_MAX_TURNS,\n\t\t\tmaxToolOutputChars: this.options.maxToolOutputChars ?? DEFAULT_MAX_TOOL_OUTPUT_CHARS,\n\t\t\tbashTimeoutSeconds: this.options.bashTimeoutSeconds ?? DEFAULT_BASH_TIMEOUT_SECONDS,\n\t\t\tallowEnvKeys: this.options.mode === \"single\",\n\t\t\tonApprovalRequest: this.options.onApprovalRequest,\n\t\t});\n\t\tthis.server = createServer(handler);\n\t\tthis.sessions.startEviction();\n\t\tconst host = this.options.host ?? \"127.0.0.1\";\n\t\tconst port = this.options.port;\n\t\tawait new Promise<void>((resolvePromise, reject) => {\n\t\t\tthis.server?.once(\"error\", reject);\n\t\t\tthis.server?.listen(port, host, () => resolvePromise());\n\t\t});\n\t\tconst address = this.server.address();\n\t\tif (typeof address !== \"object\" || address === null) {\n\t\t\tthrow new Error(\"Server did not bind an address\");\n\t\t}\n\t\treturn { host: address.address, port: address.port };\n\t}\n\n\t/** Stops listening, stops eviction, and disposes every session. */\n\tasync stop(): Promise<void> {\n\t\tthis.sessions.stopAll();\n\t\tif (!this.server) return;\n\t\tconst server = this.server;\n\t\tthis.server = undefined;\n\t\tawait new Promise<void>((resolvePromise) => {\n\t\t\tserver.close(() => resolvePromise());\n\t\t});\n\t}\n\n\t/** Live sessions, for embedding hosts that need them. */\n\tget sessionManager(): SessionManager {\n\t\treturn this.sessions;\n\t}\n}\n\n/** Creates a host. Call start() to listen. */\nexport function createServerHost(options: PigeonServerHostOptions): PigeonServerHost {\n\treturn new PigeonServerHost(options);\n}\n"]}
package/dist/http.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import type { StreamFn } from "@dev-crowagent/pigeon-agent-core";
3
+ import type { Api, Model } from "@dev-crowagent/pigeon-ai";
4
+ import type { SessionManager } from "./sessions.ts";
5
+ import type { ApprovalHandler, Authenticate } from "./types.ts";
6
+ export interface HttpHandlerDeps {
7
+ authenticate: Authenticate;
8
+ mode: "single" | "multi";
9
+ singleUserId: string;
10
+ sessions: SessionManager;
11
+ dataDir: string;
12
+ defaultModelRef: string;
13
+ modelOverride?: Model<Api>;
14
+ streamFn?: StreamFn;
15
+ systemPrompt: string;
16
+ maxTurns: number;
17
+ maxToolOutputChars: number;
18
+ bashTimeoutSeconds: number;
19
+ allowEnvKeys: boolean;
20
+ onApprovalRequest?: ApprovalHandler;
21
+ }
22
+ /** HTTP + SSE transport for the host. All /api/* routes require authentication. */
23
+ export declare function createHttpHandler(deps: HttpHandlerDeps): (req: IncomingMessage, res: ServerResponse) => void;
24
+ //# sourceMappingURL=http.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AACjE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,kCAAkC,CAAC;AACjE,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,0BAA0B,CAAC;AAG3D,OAAO,KAAK,EAAE,cAAc,EAAe,MAAM,eAAe,CAAC;AACjE,OAAO,KAAK,EAAE,eAAe,EAAE,YAAY,EAA6C,MAAM,YAAY,CAAC;AAE3G,MAAM,WAAW,eAAe;IAC/B,YAAY,EAAE,YAAY,CAAC;IAC3B,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC;IACzB,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,EAAE,cAAc,CAAC;IACzB,OAAO,EAAE,MAAM,CAAC;IAChB,eAAe,EAAE,MAAM,CAAC;IACxB,aAAa,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;IAC3B,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,EAAE,MAAM,CAAC;IACjB,kBAAkB,EAAE,MAAM,CAAC;IAC3B,kBAAkB,EAAE,MAAM,CAAC;IAC3B,YAAY,EAAE,OAAO,CAAC;IACtB,iBAAiB,CAAC,EAAE,eAAe,CAAC;CACpC;AA+CD,mFAAmF;AACnF,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,eAAe,GAAG,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,cAAc,KAAK,IAAI,CAuR5G"}
package/dist/http.js ADDED
@@ -0,0 +1,278 @@
1
+ import { createKeyStore, loadUserSettings, saveUserSettings } from "./keys.js";
2
+ import { registerCustomProvider, resolveModel } from "./model.js";
3
+ const MAX_BODY_BYTES = 1024 * 1024;
4
+ function sendJson(res, status, body) {
5
+ const text = JSON.stringify(body);
6
+ res.writeHead(status, { "content-type": "application/json", "content-length": Buffer.byteLength(text) });
7
+ res.end(text);
8
+ }
9
+ function sendError(res, status, message) {
10
+ sendJson(res, status, { error: message });
11
+ }
12
+ async function readJsonBody(req) {
13
+ const chunks = [];
14
+ let size = 0;
15
+ for await (const chunk of req) {
16
+ const buffer = chunk;
17
+ size += buffer.length;
18
+ if (size > MAX_BODY_BYTES)
19
+ throw new Error("Request body too large");
20
+ chunks.push(buffer);
21
+ }
22
+ const text = Buffer.concat(chunks).toString("utf8");
23
+ if (text === "")
24
+ return {};
25
+ try {
26
+ return JSON.parse(text);
27
+ }
28
+ catch {
29
+ throw new Error("Request body must be valid JSON");
30
+ }
31
+ }
32
+ function isRecord(value) {
33
+ return typeof value === "object" && value !== null && !Array.isArray(value);
34
+ }
35
+ function writeSse(res, event) {
36
+ res.write(`data: ${JSON.stringify(event)}\n\n`);
37
+ }
38
+ function getBearer(req) {
39
+ const header = req.headers.authorization;
40
+ return Array.isArray(header) ? header[0] : header;
41
+ }
42
+ /** HTTP + SSE transport for the host. All /api/* routes require authentication. */
43
+ export function createHttpHandler(deps) {
44
+ const routes = [
45
+ { method: "GET", pattern: /^\/api\/sessions$/, handler: listSessions, auth: true },
46
+ { method: "POST", pattern: /^\/api\/sessions$/, handler: createSession, auth: true },
47
+ { method: "GET", pattern: /^\/api\/sessions\/([^/]+)$/, handler: getSession, auth: true },
48
+ { method: "DELETE", pattern: /^\/api\/sessions\/([^/]+)$/, handler: deleteSession, auth: true },
49
+ { method: "POST", pattern: /^\/api\/sessions\/([^/]+)\/prompt$/, handler: promptSession, auth: true },
50
+ { method: "POST", pattern: /^\/api\/sessions\/([^/]+)\/abort$/, handler: abortSession, auth: true },
51
+ { method: "POST", pattern: /^\/api\/sessions\/([^/]+)\/approvals$/, handler: answerApproval, auth: true },
52
+ { method: "GET", pattern: /^\/api\/users\/me\/keys$/, handler: listKeys, auth: true },
53
+ { method: "POST", pattern: /^\/api\/users\/me\/keys$/, handler: setKey, auth: true },
54
+ { method: "DELETE", pattern: /^\/api\/users\/me\/keys\/([^/]+)$/, handler: deleteKey, auth: true },
55
+ { method: "GET", pattern: /^\/api\/users\/me\/providers$/, handler: listProviders, auth: true },
56
+ { method: "POST", pattern: /^\/api\/users\/me\/providers$/, handler: addProvider, auth: true },
57
+ { method: "DELETE", pattern: /^\/api\/users\/me\/providers\/([^/]+)$/, handler: deleteProvider, auth: true },
58
+ ];
59
+ async function requireSession(userId, sessionId) {
60
+ return deps.sessions.get(userId, sessionId);
61
+ }
62
+ async function listSessions(_req, res, userId) {
63
+ sendJson(res, 200, deps.sessions.list(userId).map((session) => session.info()));
64
+ }
65
+ async function createSession(req, res, userId) {
66
+ const body = await readJsonBody(req);
67
+ const modelRef = isRecord(body) && typeof body.model === "string" ? body.model : deps.defaultModelRef;
68
+ try {
69
+ resolveModel(modelRef);
70
+ }
71
+ catch (error) {
72
+ sendError(res, 400, error instanceof Error ? error.message : String(error));
73
+ return;
74
+ }
75
+ const session = deps.sessions.create(userId, {
76
+ modelRef,
77
+ modelOverride: deps.modelOverride,
78
+ streamFn: deps.streamFn,
79
+ systemPrompt: deps.systemPrompt,
80
+ maxTurns: deps.maxTurns,
81
+ maxToolOutputChars: deps.maxToolOutputChars,
82
+ bashTimeoutSeconds: deps.bashTimeoutSeconds,
83
+ allowEnvKeys: deps.allowEnvKeys,
84
+ onApprovalRequest: deps.onApprovalRequest,
85
+ });
86
+ sendJson(res, 201, session.info());
87
+ }
88
+ async function getSession(_req, res, userId, params) {
89
+ const session = await requireSession(userId, decodeURIComponent(params[0] ?? ""));
90
+ if (!session) {
91
+ sendError(res, 404, "Session not found");
92
+ return;
93
+ }
94
+ sendJson(res, 200, session.info());
95
+ }
96
+ async function deleteSession(_req, res, userId, params) {
97
+ const deleted = deps.sessions.delete(userId, decodeURIComponent(params[0] ?? ""));
98
+ if (!deleted) {
99
+ sendError(res, 404, "Session not found");
100
+ return;
101
+ }
102
+ res.writeHead(204);
103
+ res.end();
104
+ }
105
+ async function promptSession(req, res, userId, params) {
106
+ const session = await requireSession(userId, decodeURIComponent(params[0] ?? ""));
107
+ if (!session) {
108
+ sendError(res, 404, "Session not found");
109
+ return;
110
+ }
111
+ const body = await readJsonBody(req);
112
+ if (!isRecord(body) || typeof body.text !== "string" || body.text === "") {
113
+ sendError(res, 400, 'Body must be {"text": "..."} with a non-empty text.');
114
+ return;
115
+ }
116
+ res.writeHead(200, {
117
+ "content-type": "text/event-stream",
118
+ "cache-control": "no-cache",
119
+ connection: "keep-alive",
120
+ });
121
+ let finished = false;
122
+ const onClose = () => {
123
+ if (!finished)
124
+ session.abort();
125
+ };
126
+ res.on("close", onClose);
127
+ try {
128
+ await session.prompt(body.text, (event) => writeSse(res, event));
129
+ }
130
+ catch (error) {
131
+ if (!res.writableEnded) {
132
+ writeSse(res, { type: "error", message: error instanceof Error ? error.message : String(error) });
133
+ }
134
+ }
135
+ finally {
136
+ finished = true;
137
+ res.off("close", onClose);
138
+ res.end();
139
+ }
140
+ }
141
+ async function abortSession(_req, res, userId, params) {
142
+ const session = await requireSession(userId, decodeURIComponent(params[0] ?? ""));
143
+ if (!session) {
144
+ sendError(res, 404, "Session not found");
145
+ return;
146
+ }
147
+ session.abort();
148
+ sendJson(res, 200, { aborted: true });
149
+ }
150
+ async function answerApproval(req, res, userId, params) {
151
+ const session = await requireSession(userId, decodeURIComponent(params[0] ?? ""));
152
+ if (!session) {
153
+ sendError(res, 404, "Session not found");
154
+ return;
155
+ }
156
+ const body = await readJsonBody(req);
157
+ if (!isRecord(body) || typeof body.requestId !== "string" || typeof body.approved !== "boolean") {
158
+ sendError(res, 400, 'Body must be {"requestId": "...", "approved": true|false}.');
159
+ return;
160
+ }
161
+ const resolved = session.answerApproval(body.requestId, body.approved);
162
+ if (!resolved) {
163
+ sendError(res, 404, "Approval request not found or already answered");
164
+ return;
165
+ }
166
+ sendJson(res, 200, { resolved: true });
167
+ }
168
+ async function listKeys(_req, res, userId) {
169
+ sendJson(res, 200, { providers: createKeyStore(deps.dataDir, userId).providers() });
170
+ }
171
+ async function setKey(req, res, userId) {
172
+ const body = await readJsonBody(req);
173
+ if (!isRecord(body) || typeof body.provider !== "string" || typeof body.key !== "string" || body.key === "") {
174
+ sendError(res, 400, 'Body must be {"provider": "...", "key": "..."} with a non-empty key.');
175
+ return;
176
+ }
177
+ createKeyStore(deps.dataDir, userId).set(body.provider, body.key);
178
+ sendJson(res, 200, { provider: body.provider });
179
+ }
180
+ async function deleteKey(_req, res, userId, params) {
181
+ createKeyStore(deps.dataDir, userId).remove(decodeURIComponent(params[0] ?? ""));
182
+ res.writeHead(204);
183
+ res.end();
184
+ }
185
+ async function listProviders(_req, res, userId) {
186
+ const settings = loadUserSettings(deps.dataDir, userId);
187
+ sendJson(res, 200, {
188
+ providers: (settings.customProviders ?? []).map((provider) => ({
189
+ slug: provider.slug,
190
+ name: provider.name ?? provider.slug,
191
+ baseUrl: provider.baseUrl,
192
+ models: provider.models,
193
+ hasKey: provider.apiKey !== undefined,
194
+ })),
195
+ });
196
+ }
197
+ async function addProvider(req, res, userId) {
198
+ const body = await readJsonBody(req);
199
+ if (!isRecord(body)) {
200
+ sendError(res, 400, "Body must be a custom provider object.");
201
+ return;
202
+ }
203
+ const config = {
204
+ slug: typeof body.slug === "string" ? body.slug : "",
205
+ baseUrl: typeof body.baseUrl === "string" ? body.baseUrl : "",
206
+ apiKey: typeof body.apiKey === "string" ? body.apiKey : undefined,
207
+ models: Array.isArray(body.models)
208
+ ? body.models.filter((model) => typeof model === "string")
209
+ : [],
210
+ name: typeof body.name === "string" ? body.name : undefined,
211
+ };
212
+ try {
213
+ const settings = loadUserSettings(deps.dataDir, userId);
214
+ const existing = settings.customProviders ?? [];
215
+ if (existing.some((provider) => provider.slug === config.slug)) {
216
+ sendError(res, 409, `Provider "${config.slug}" already exists.`);
217
+ return;
218
+ }
219
+ const providerId = registerCustomProvider(userId, config);
220
+ saveUserSettings(deps.dataDir, userId, { ...settings, customProviders: [...existing, config] });
221
+ sendJson(res, 201, { provider: providerId });
222
+ }
223
+ catch (error) {
224
+ sendError(res, 400, error instanceof Error ? error.message : String(error));
225
+ }
226
+ }
227
+ async function deleteProvider(_req, res, userId, params) {
228
+ const slug = decodeURIComponent(params[0] ?? "");
229
+ const settings = loadUserSettings(deps.dataDir, userId);
230
+ const providers = settings.customProviders ?? [];
231
+ if (!providers.some((provider) => provider.slug === slug)) {
232
+ sendError(res, 404, "Provider not found");
233
+ return;
234
+ }
235
+ saveUserSettings(deps.dataDir, userId, {
236
+ ...settings,
237
+ customProviders: providers.filter((provider) => provider.slug !== slug),
238
+ });
239
+ res.writeHead(204);
240
+ res.end();
241
+ }
242
+ return (req, res) => {
243
+ void (async () => {
244
+ try {
245
+ const url = new URL(req.url ?? "/", "http://localhost");
246
+ const pathname = url.pathname;
247
+ if (req.method === "GET" && pathname === "/health") {
248
+ sendJson(res, 200, { ok: true, mode: deps.mode });
249
+ return;
250
+ }
251
+ const userId = await deps.authenticate({ authorization: getBearer(req) });
252
+ if (userId === null) {
253
+ sendError(res, 401, "Unauthorized: missing or invalid bearer token.");
254
+ return;
255
+ }
256
+ for (const route of routes) {
257
+ if (req.method !== route.method)
258
+ continue;
259
+ const match = route.pattern.exec(pathname);
260
+ if (!match)
261
+ continue;
262
+ await route.handler(req, res, userId, match.slice(1));
263
+ return;
264
+ }
265
+ sendError(res, 404, "Not found");
266
+ }
267
+ catch (error) {
268
+ if (!res.headersSent) {
269
+ sendError(res, 500, error instanceof Error ? error.message : String(error));
270
+ }
271
+ else if (!res.writableEnded) {
272
+ res.end();
273
+ }
274
+ }
275
+ })();
276
+ };
277
+ }
278
+ //# sourceMappingURL=http.js.map