@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/dist/tools.js ADDED
@@ -0,0 +1,383 @@
1
+ import { execFile } from "node:child_process";
2
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
3
+ import { dirname, join, relative, resolve, sep } from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { loadRenderedSkillContent, wrapSkillContent, } from "@dev-crowagent/pigeon-agent-kit";
6
+ import { bool, int, obj, opt, str } from "@dev-crowagent/pigeon-schema";
7
+ import { resolveWorkspacePath } from "./workspace.js";
8
+ const execFileAsync = promisify(execFile);
9
+ function textResult(text) {
10
+ return { content: [{ type: "text", text }], details: undefined };
11
+ }
12
+ function errorResult(text) {
13
+ return { content: [{ type: "text", text }], details: undefined, isError: true };
14
+ }
15
+ function truncate(text, maxChars) {
16
+ if (text.length <= maxChars)
17
+ return text;
18
+ return `${text.slice(0, maxChars)}\n... (truncated, ${text.length - maxChars} more characters)`;
19
+ }
20
+ function isBinary(buffer) {
21
+ return buffer.includes(0);
22
+ }
23
+ const ReadFileParams = obj({
24
+ path: str({ description: 'Path relative to the workspace, e.g. "src/index.ts"' }),
25
+ });
26
+ const WriteFileParams = obj({
27
+ path: str({ description: "Path relative to the workspace" }),
28
+ content: str({ description: "Full file content to write" }),
29
+ });
30
+ const EditFileParams = obj({
31
+ path: str({ description: "Path relative to the workspace" }),
32
+ oldText: str({ description: "Exact text to replace; must occur exactly once unless replaceAll is set" }),
33
+ newText: str({ description: "Replacement text" }),
34
+ replaceAll: opt(bool({ description: "Replace every occurrence instead of requiring exactly one" })),
35
+ });
36
+ const ListDirParams = obj({
37
+ path: opt(str({ description: "Directory relative to the workspace; defaults to the workspace root" })),
38
+ });
39
+ const RunCommandParams = obj({
40
+ command: str({ description: "Shell command to run inside the workspace" }),
41
+ timeoutSeconds: opt(int({ description: "Timeout in seconds; defaults to the session limit" })),
42
+ });
43
+ const GrepParams = obj({
44
+ pattern: str({ description: "Regular expression, or literal text when literal is true" }),
45
+ path: opt(str({ description: "File or directory relative to the workspace; defaults to the workspace root" })),
46
+ literal: opt(bool({ description: "Treat pattern as literal text" })),
47
+ ignoreCase: opt(bool({ description: "Case-insensitive match" })),
48
+ contextLines: opt(int({ description: "Context lines around each match" })),
49
+ limit: opt(int({ description: "Maximum matches to return; defaults to 50" })),
50
+ });
51
+ const FindFilesParams = obj({
52
+ pattern: str({ description: 'Glob, e.g. "src/**/*.ts" or "*.md"' }),
53
+ });
54
+ const MemoryParams = obj({
55
+ action: str({ description: "recall, read, list, or write" }),
56
+ query: opt(str({ description: "Search text for recall" })),
57
+ path: opt(str({ description: 'Memory file path, e.g. "notes.md"' })),
58
+ body: opt(str({ description: "File body for write" })),
59
+ name: opt(str({ description: "Display name for write" })),
60
+ description: opt(str({ description: "Description for write" })),
61
+ scope: opt(str({ description: '"user" or "project"; defaults to "user"' })),
62
+ });
63
+ const SkillParams = obj({
64
+ skill: str({ description: 'Id of the skill to load, e.g. "review" for a review/SKILL.md skill' }),
65
+ });
66
+ /** Walks workspace files for grep/find, skipping VCS, deps, binaries, and oversize files. */
67
+ function walkWorkspaceFiles(workspaceDir) {
68
+ const files = [];
69
+ const walk = (dir) => {
70
+ let entries;
71
+ try {
72
+ entries = readdirSync(dir, { withFileTypes: true });
73
+ }
74
+ catch {
75
+ return;
76
+ }
77
+ for (const entry of entries) {
78
+ if (entry.name === ".git" || entry.name === "node_modules")
79
+ continue;
80
+ const full = join(dir, entry.name);
81
+ if (entry.isDirectory()) {
82
+ walk(full);
83
+ }
84
+ else if (entry.isFile()) {
85
+ try {
86
+ if (statSync(full).size <= 1024 * 1024)
87
+ files.push(full);
88
+ }
89
+ catch {
90
+ // Vanished mid-walk; skip it.
91
+ }
92
+ }
93
+ }
94
+ };
95
+ walk(workspaceDir);
96
+ return files.sort();
97
+ }
98
+ function globToRegExp(glob) {
99
+ let pattern = "^";
100
+ for (let i = 0; i < glob.length; i += 1) {
101
+ const char = glob[i];
102
+ if (char === "*") {
103
+ if (glob[i + 1] === "*") {
104
+ pattern += ".*";
105
+ i += 1;
106
+ if (glob[i + 1] === "/")
107
+ i += 1;
108
+ }
109
+ else {
110
+ pattern += "[^/]*";
111
+ }
112
+ }
113
+ else if (char === "?") {
114
+ pattern += "[^/]";
115
+ }
116
+ else if (char === "[") {
117
+ const close = glob.indexOf("]", i);
118
+ pattern += close === -1 ? "\\[" : glob.slice(i, close + 1);
119
+ if (close !== -1)
120
+ i = close;
121
+ }
122
+ else {
123
+ pattern += char.replace(/[.+^${}()|\\]/g, "\\$&");
124
+ }
125
+ }
126
+ return new RegExp(`${pattern}$`);
127
+ }
128
+ /** Workspace-jailed tools for one user's agent. Every path resolves inside the user's workspace. */
129
+ export function createWorkspaceTools(context) {
130
+ const { workspaceDir } = context;
131
+ const tools = [
132
+ {
133
+ name: "read_file",
134
+ label: "Read file",
135
+ description: "Read a file from the workspace. Read before editing; never guess file contents.",
136
+ parameters: ReadFileParams,
137
+ execute: async (_toolCallId, params) => {
138
+ const args = params;
139
+ try {
140
+ const full = resolveWorkspacePath(workspaceDir, args.path);
141
+ if (!existsSync(full))
142
+ return errorResult(`File not found: ${args.path}`);
143
+ const buffer = readFileSync(full);
144
+ if (isBinary(buffer))
145
+ return errorResult(`File is binary: ${args.path}`);
146
+ return textResult(truncate(buffer.toString("utf8"), context.maxToolOutputChars));
147
+ }
148
+ catch (error) {
149
+ return errorResult(error instanceof Error ? error.message : String(error));
150
+ }
151
+ },
152
+ },
153
+ {
154
+ name: "write_file",
155
+ label: "Write file",
156
+ description: "Write a file in the workspace, creating parent directories. Prefer edit_file for small changes.",
157
+ parameters: WriteFileParams,
158
+ execute: async (_toolCallId, params) => {
159
+ const args = params;
160
+ try {
161
+ const full = resolveWorkspacePath(workspaceDir, args.path);
162
+ mkdirSync(dirname(full), { recursive: true });
163
+ writeFileSync(full, args.content, "utf8");
164
+ return textResult(`Wrote ${args.path} (${args.content.length} characters).`);
165
+ }
166
+ catch (error) {
167
+ return errorResult(error instanceof Error ? error.message : String(error));
168
+ }
169
+ },
170
+ },
171
+ {
172
+ name: "edit_file",
173
+ label: "Edit file",
174
+ description: "Replace exact text in a file. oldText must occur exactly once unless replaceAll is set.",
175
+ parameters: EditFileParams,
176
+ execute: async (_toolCallId, params) => {
177
+ const args = params;
178
+ try {
179
+ const full = resolveWorkspacePath(workspaceDir, args.path);
180
+ if (!existsSync(full))
181
+ return errorResult(`File not found: ${args.path}`);
182
+ const content = readFileSync(full, "utf8");
183
+ const occurrences = content.split(args.oldText).length - 1;
184
+ if (occurrences === 0)
185
+ return errorResult(`Text not found in ${args.path}.`);
186
+ if (occurrences > 1 && !args.replaceAll) {
187
+ return errorResult(`Text occurs ${occurrences} times in ${args.path}; be more specific or set replaceAll.`);
188
+ }
189
+ writeFileSync(full, content.split(args.oldText).join(args.newText), "utf8");
190
+ return textResult(`Edited ${args.path} (${occurrences} replacement${occurrences === 1 ? "" : "s"}).`);
191
+ }
192
+ catch (error) {
193
+ return errorResult(error instanceof Error ? error.message : String(error));
194
+ }
195
+ },
196
+ },
197
+ {
198
+ name: "list_dir",
199
+ label: "List directory",
200
+ description: "List a directory in the workspace. Run this first when lost.",
201
+ parameters: ListDirParams,
202
+ execute: async (_toolCallId, params) => {
203
+ const args = params;
204
+ try {
205
+ const full = resolveWorkspacePath(workspaceDir, args.path ?? ".");
206
+ const entries = readdirSync(full, { withFileTypes: true })
207
+ .map((entry) => `${entry.isDirectory() ? `${entry.name}/` : entry.name}`)
208
+ .sort();
209
+ return textResult(entries.length > 0 ? entries.join("\n") : "(empty directory)");
210
+ }
211
+ catch (error) {
212
+ return errorResult(error instanceof Error ? error.message : String(error));
213
+ }
214
+ },
215
+ },
216
+ {
217
+ name: "run_command",
218
+ label: "Run command",
219
+ description: "Run a shell command inside the workspace. Run builds and tests after every edit and report the exact result.",
220
+ parameters: RunCommandParams,
221
+ execute: async (_toolCallId, params, signal) => {
222
+ const args = params;
223
+ const timeoutMs = (args.timeoutSeconds ?? context.bashTimeoutSeconds) * 1000;
224
+ const shell = process.platform === "win32" ? "powershell.exe" : "/bin/sh";
225
+ const shellArgs = process.platform === "win32" ? ["-Command", args.command] : ["-c", args.command];
226
+ try {
227
+ const { stdout, stderr } = await execFileAsync(shell, shellArgs, {
228
+ cwd: workspaceDir,
229
+ timeout: timeoutMs,
230
+ maxBuffer: 10 * 1024 * 1024,
231
+ signal,
232
+ });
233
+ const output = [stdout, stderr].filter(Boolean).join("\n");
234
+ return textResult(truncate(output === "" ? "(no output)" : output, context.maxToolOutputChars));
235
+ }
236
+ catch (error) {
237
+ const message = error instanceof Error ? error.message : String(error);
238
+ const stdout = error.stdout ?? "";
239
+ const stderr = error.stderr ?? "";
240
+ const output = [stdout, stderr, message].filter(Boolean).join("\n");
241
+ return errorResult(truncate(output, context.maxToolOutputChars));
242
+ }
243
+ },
244
+ },
245
+ {
246
+ name: "grep",
247
+ label: "Grep",
248
+ description: "Search workspace files for a pattern. Returns path:line: text matches.",
249
+ parameters: GrepParams,
250
+ execute: async (_toolCallId, params) => {
251
+ const args = params;
252
+ try {
253
+ const flags = args.ignoreCase ? "i" : "";
254
+ const source = args.literal ? args.pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") : args.pattern;
255
+ const regex = new RegExp(source, flags);
256
+ const base = args.path ? resolveWorkspacePath(workspaceDir, args.path) : resolve(workspaceDir);
257
+ const files = statSync(base).isDirectory() ? walkWorkspaceFiles(base) : [base];
258
+ const limit = args.limit ?? 50;
259
+ const contextLines = args.contextLines ?? 0;
260
+ const lines = [];
261
+ for (const file of files) {
262
+ const buffer = readFileSync(file);
263
+ if (isBinary(buffer))
264
+ continue;
265
+ const fileLines = buffer.toString("utf8").split("\n");
266
+ for (let i = 0; i < fileLines.length; i += 1) {
267
+ if (!regex.test(fileLines[i] ?? ""))
268
+ continue;
269
+ const start = Math.max(0, i - contextLines);
270
+ const end = Math.min(fileLines.length, i + contextLines + 1);
271
+ for (let j = start; j < end; j += 1) {
272
+ lines.push(`${relative(workspaceDir, file)}:${j + 1}: ${fileLines[j] ?? ""}`);
273
+ }
274
+ if (lines.length >= limit)
275
+ break;
276
+ }
277
+ if (lines.length >= limit)
278
+ break;
279
+ }
280
+ const output = lines.slice(0, limit).join("\n");
281
+ return textResult(output === "" ? "No matches." : truncate(output, context.maxToolOutputChars));
282
+ }
283
+ catch (error) {
284
+ return errorResult(error instanceof Error ? error.message : String(error));
285
+ }
286
+ },
287
+ },
288
+ {
289
+ name: "find_files",
290
+ label: "Find files",
291
+ description: 'Find workspace files by glob, e.g. "src/**/*.ts". A bare name matches basenames at any depth.',
292
+ parameters: FindFilesParams,
293
+ execute: async (_toolCallId, params) => {
294
+ const args = params;
295
+ try {
296
+ const pattern = args.pattern.includes("/") ? args.pattern : `**/${args.pattern}`;
297
+ const regex = globToRegExp(pattern);
298
+ const matches = walkWorkspaceFiles(workspaceDir)
299
+ .map((file) => relative(workspaceDir, file).split(sep).join("/"))
300
+ .filter((rel) => regex.test(rel));
301
+ return textResult(matches.length > 0 ? matches.slice(0, 200).join("\n") : "No files found.");
302
+ }
303
+ catch (error) {
304
+ return errorResult(error instanceof Error ? error.message : String(error));
305
+ }
306
+ },
307
+ },
308
+ {
309
+ name: "memory",
310
+ label: "Memory",
311
+ description: "Recall, read, list, or write memory. Memory is per user: this user's files only, under the user scope, plus the workspace project scope.",
312
+ parameters: MemoryParams,
313
+ execute: async (_toolCallId, params) => {
314
+ const args = params;
315
+ const scope = args.scope === "project" ? "project" : "user";
316
+ try {
317
+ switch (args.action) {
318
+ case "recall": {
319
+ if (!args.query)
320
+ return errorResult("recall needs a query.");
321
+ const findings = context.memoryStore.recall(args.query, { scopes: [scope] });
322
+ if (findings.length === 0)
323
+ return textResult("Nothing recalled.");
324
+ return textResult(findings.map((finding) => `${finding.path}: ${finding.excerpt}`).join("\n"));
325
+ }
326
+ case "read": {
327
+ if (!args.path)
328
+ return errorResult("read needs a path.");
329
+ const file = context.memoryStore.readFile(scope, args.path);
330
+ return textResult(file.body);
331
+ }
332
+ case "list": {
333
+ const files = context.memoryStore.listFiles(scope);
334
+ if (files.length === 0)
335
+ return textResult("No memory files.");
336
+ return textResult(files.map((file) => `${file.path} — ${file.description}`).join("\n"));
337
+ }
338
+ case "write": {
339
+ if (!args.path || args.body === undefined)
340
+ return errorResult("write needs a path and a body.");
341
+ context.memoryStore.writeFile(scope, args.path, args.body, {
342
+ name: args.name ?? args.path,
343
+ description: args.description ?? "",
344
+ });
345
+ return textResult(`Wrote memory file ${args.path}.`);
346
+ }
347
+ default:
348
+ return errorResult(`Unknown memory action "${args.action}". Use recall, read, list, or write.`);
349
+ }
350
+ }
351
+ catch (error) {
352
+ return errorResult(error instanceof Error ? error.message : String(error));
353
+ }
354
+ },
355
+ },
356
+ {
357
+ name: "skill",
358
+ label: "Skill",
359
+ description: "Load a skill on demand. Reads the skill's SKILL.md from the workspace or this user's memory skills and queues it for the next model request.",
360
+ parameters: SkillParams,
361
+ execute: async (toolCallId, params) => {
362
+ const args = params;
363
+ try {
364
+ if (!args.skill)
365
+ return errorResult("Skill needs a skill id.");
366
+ const rendered = loadRenderedSkillContent(args.skill, {
367
+ roots: {
368
+ projectRoots: [join(workspaceDir, ".pigeon", "skills"), join(workspaceDir, ".skills")],
369
+ memorySkillsDirs: [join(context.memoryStore.userDir, "skills")],
370
+ },
371
+ });
372
+ context.skillQueue.queue(toolCallId, wrapSkillContent(args.skill, rendered));
373
+ return textResult(`Launching skill: ${args.skill}`);
374
+ }
375
+ catch (error) {
376
+ return errorResult(error instanceof Error ? error.message : String(error));
377
+ }
378
+ },
379
+ },
380
+ ];
381
+ return tools;
382
+ }
383
+ //# sourceMappingURL=tools.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools.js","sourceRoot":"","sources":["../src/tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAE9C,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,aAAa,EAAE,MAA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oBAC7E,OAAO,UAAU,CAAC,oBAAoB,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;gBACrD,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBAChB,OAAO,WAAW,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;gBAC5E,CAAC;YACF,CAAC;SACD;KACD,CAAC;IACF,OAAO,KAAK,CAAC;AACd,CAAC","sourcesContent":["import { execFile } from \"node:child_process\";\nimport type { Dirent } from \"node:fs\";\nimport { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from \"node:fs\";\nimport { dirname, join, relative, resolve, sep } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport type { AgentTool, AgentToolResult } from \"@dev-crowagent/pigeon-agent-core\";\nimport {\n\tloadRenderedSkillContent,\n\ttype MemoryStore,\n\ttype SkillContentQueue,\n\twrapSkillContent,\n} from \"@dev-crowagent/pigeon-agent-kit\";\nimport { bool, int, obj, opt, type Static, str } from \"@dev-crowagent/pigeon-schema\";\nimport { resolveWorkspacePath } from \"./workspace.ts\";\n\nconst execFileAsync = promisify(execFile);\n\nexport interface WorkspaceToolContext {\n\tworkspaceDir: string;\n\tmemoryStore: MemoryStore;\n\tskillQueue: SkillContentQueue;\n\tmaxToolOutputChars: number;\n\tbashTimeoutSeconds: number;\n}\n\ntype TextResult = AgentToolResult<undefined>;\n\nfunction textResult(text: string): TextResult {\n\treturn { content: [{ type: \"text\", text }], details: undefined };\n}\n\nfunction errorResult(text: string): TextResult {\n\treturn { content: [{ type: \"text\", text }], details: undefined, isError: true };\n}\n\nfunction truncate(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\treturn `${text.slice(0, maxChars)}\\n... (truncated, ${text.length - maxChars} more characters)`;\n}\n\nfunction isBinary(buffer: Buffer): boolean {\n\treturn buffer.includes(0);\n}\n\nconst ReadFileParams = obj({\n\tpath: str({ description: 'Path relative to the workspace, e.g. \"src/index.ts\"' }),\n});\nconst WriteFileParams = obj({\n\tpath: str({ description: \"Path relative to the workspace\" }),\n\tcontent: str({ description: \"Full file content to write\" }),\n});\nconst EditFileParams = obj({\n\tpath: str({ description: \"Path relative to the workspace\" }),\n\toldText: str({ description: \"Exact text to replace; must occur exactly once unless replaceAll is set\" }),\n\tnewText: str({ description: \"Replacement text\" }),\n\treplaceAll: opt(bool({ description: \"Replace every occurrence instead of requiring exactly one\" })),\n});\nconst ListDirParams = obj({\n\tpath: opt(str({ description: \"Directory relative to the workspace; defaults to the workspace root\" })),\n});\nconst RunCommandParams = obj({\n\tcommand: str({ description: \"Shell command to run inside the workspace\" }),\n\ttimeoutSeconds: opt(int({ description: \"Timeout in seconds; defaults to the session limit\" })),\n});\nconst GrepParams = obj({\n\tpattern: str({ description: \"Regular expression, or literal text when literal is true\" }),\n\tpath: opt(str({ description: \"File or directory relative to the workspace; defaults to the workspace root\" })),\n\tliteral: opt(bool({ description: \"Treat pattern as literal text\" })),\n\tignoreCase: opt(bool({ description: \"Case-insensitive match\" })),\n\tcontextLines: opt(int({ description: \"Context lines around each match\" })),\n\tlimit: opt(int({ description: \"Maximum matches to return; defaults to 50\" })),\n});\nconst FindFilesParams = obj({\n\tpattern: str({ description: 'Glob, e.g. \"src/**/*.ts\" or \"*.md\"' }),\n});\nconst MemoryParams = obj({\n\taction: str({ description: \"recall, read, list, or write\" }),\n\tquery: opt(str({ description: \"Search text for recall\" })),\n\tpath: opt(str({ description: 'Memory file path, e.g. \"notes.md\"' })),\n\tbody: opt(str({ description: \"File body for write\" })),\n\tname: opt(str({ description: \"Display name for write\" })),\n\tdescription: opt(str({ description: \"Description for write\" })),\n\tscope: opt(str({ description: '\"user\" or \"project\"; defaults to \"user\"' })),\n});\nconst SkillParams = obj({\n\tskill: str({ description: 'Id of the skill to load, e.g. \"review\" for a review/SKILL.md skill' }),\n});\n\ntype ReadFileArgs = Static<typeof ReadFileParams>;\ntype WriteFileArgs = Static<typeof WriteFileParams>;\ntype EditFileArgs = Static<typeof EditFileParams>;\ntype ListDirArgs = Static<typeof ListDirParams>;\ntype RunCommandArgs = Static<typeof RunCommandParams>;\ntype GrepArgs = Static<typeof GrepParams>;\ntype FindFilesArgs = Static<typeof FindFilesParams>;\ntype MemoryArgs = Static<typeof MemoryParams>;\ntype SkillArgs = Static<typeof SkillParams>;\n\n/** Walks workspace files for grep/find, skipping VCS, deps, binaries, and oversize files. */\nfunction walkWorkspaceFiles(workspaceDir: string): string[] {\n\tconst files: string[] = [];\n\tconst walk = (dir: string): void => {\n\t\tlet entries: Dirent[];\n\t\ttry {\n\t\t\tentries = readdirSync(dir, { withFileTypes: true });\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.name === \".git\" || entry.name === \"node_modules\") continue;\n\t\t\tconst full = join(dir, entry.name);\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\twalk(full);\n\t\t\t} else if (entry.isFile()) {\n\t\t\t\ttry {\n\t\t\t\t\tif (statSync(full).size <= 1024 * 1024) files.push(full);\n\t\t\t\t} catch {\n\t\t\t\t\t// Vanished mid-walk; skip it.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\twalk(workspaceDir);\n\treturn files.sort();\n}\n\nfunction globToRegExp(glob: string): RegExp {\n\tlet pattern = \"^\";\n\tfor (let i = 0; i < glob.length; i += 1) {\n\t\tconst char = glob[i];\n\t\tif (char === \"*\") {\n\t\t\tif (glob[i + 1] === \"*\") {\n\t\t\t\tpattern += \".*\";\n\t\t\t\ti += 1;\n\t\t\t\tif (glob[i + 1] === \"/\") i += 1;\n\t\t\t} else {\n\t\t\t\tpattern += \"[^/]*\";\n\t\t\t}\n\t\t} else if (char === \"?\") {\n\t\t\tpattern += \"[^/]\";\n\t\t} else if (char === \"[\") {\n\t\t\tconst close = glob.indexOf(\"]\", i);\n\t\t\tpattern += close === -1 ? \"\\\\[\" : glob.slice(i, close + 1);\n\t\t\tif (close !== -1) i = close;\n\t\t} else {\n\t\t\tpattern += char.replace(/[.+^${}()|\\\\]/g, \"\\\\$&\");\n\t\t}\n\t}\n\treturn new RegExp(`${pattern}$`);\n}\n\n/** Workspace-jailed tools for one user's agent. Every path resolves inside the user's workspace. */\nexport function createWorkspaceTools(context: WorkspaceToolContext): AgentTool[] {\n\tconst { workspaceDir } = context;\n\tconst tools: AgentTool[] = [\n\t\t{\n\t\t\tname: \"read_file\",\n\t\t\tlabel: \"Read file\",\n\t\t\tdescription: \"Read a file from the workspace. Read before editing; never guess file contents.\",\n\t\t\tparameters: ReadFileParams,\n\t\t\texecute: async (_toolCallId, params) => {\n\t\t\t\tconst args = params as ReadFileArgs;\n\t\t\t\ttry {\n\t\t\t\t\tconst full = resolveWorkspacePath(workspaceDir, args.path);\n\t\t\t\t\tif (!existsSync(full)) return errorResult(`File not found: ${args.path}`);\n\t\t\t\t\tconst buffer = readFileSync(full);\n\t\t\t\t\tif (isBinary(buffer)) return errorResult(`File is binary: ${args.path}`);\n\t\t\t\t\treturn textResult(truncate(buffer.toString(\"utf8\"), context.maxToolOutputChars));\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn errorResult(error instanceof Error ? error.message : String(error));\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"write_file\",\n\t\t\tlabel: \"Write file\",\n\t\t\tdescription: \"Write a file in the workspace, creating parent directories. Prefer edit_file for small changes.\",\n\t\t\tparameters: WriteFileParams,\n\t\t\texecute: async (_toolCallId, params) => {\n\t\t\t\tconst args = params as WriteFileArgs;\n\t\t\t\ttry {\n\t\t\t\t\tconst full = resolveWorkspacePath(workspaceDir, args.path);\n\t\t\t\t\tmkdirSync(dirname(full), { recursive: true });\n\t\t\t\t\twriteFileSync(full, args.content, \"utf8\");\n\t\t\t\t\treturn textResult(`Wrote ${args.path} (${args.content.length} characters).`);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn errorResult(error instanceof Error ? error.message : String(error));\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"edit_file\",\n\t\t\tlabel: \"Edit file\",\n\t\t\tdescription: \"Replace exact text in a file. oldText must occur exactly once unless replaceAll is set.\",\n\t\t\tparameters: EditFileParams,\n\t\t\texecute: async (_toolCallId, params) => {\n\t\t\t\tconst args = params as EditFileArgs;\n\t\t\t\ttry {\n\t\t\t\t\tconst full = resolveWorkspacePath(workspaceDir, args.path);\n\t\t\t\t\tif (!existsSync(full)) return errorResult(`File not found: ${args.path}`);\n\t\t\t\t\tconst content = readFileSync(full, \"utf8\");\n\t\t\t\t\tconst occurrences = content.split(args.oldText).length - 1;\n\t\t\t\t\tif (occurrences === 0) return errorResult(`Text not found in ${args.path}.`);\n\t\t\t\t\tif (occurrences > 1 && !args.replaceAll) {\n\t\t\t\t\t\treturn errorResult(\n\t\t\t\t\t\t\t`Text occurs ${occurrences} times in ${args.path}; be more specific or set replaceAll.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\twriteFileSync(full, content.split(args.oldText).join(args.newText), \"utf8\");\n\t\t\t\t\treturn textResult(`Edited ${args.path} (${occurrences} replacement${occurrences === 1 ? \"\" : \"s\"}).`);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn errorResult(error instanceof Error ? error.message : String(error));\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"list_dir\",\n\t\t\tlabel: \"List directory\",\n\t\t\tdescription: \"List a directory in the workspace. Run this first when lost.\",\n\t\t\tparameters: ListDirParams,\n\t\t\texecute: async (_toolCallId, params) => {\n\t\t\t\tconst args = params as ListDirArgs;\n\t\t\t\ttry {\n\t\t\t\t\tconst full = resolveWorkspacePath(workspaceDir, args.path ?? \".\");\n\t\t\t\t\tconst entries = readdirSync(full, { withFileTypes: true })\n\t\t\t\t\t\t.map((entry) => `${entry.isDirectory() ? `${entry.name}/` : entry.name}`)\n\t\t\t\t\t\t.sort();\n\t\t\t\t\treturn textResult(entries.length > 0 ? entries.join(\"\\n\") : \"(empty directory)\");\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn errorResult(error instanceof Error ? error.message : String(error));\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"run_command\",\n\t\t\tlabel: \"Run command\",\n\t\t\tdescription:\n\t\t\t\t\"Run a shell command inside the workspace. Run builds and tests after every edit and report the exact result.\",\n\t\t\tparameters: RunCommandParams,\n\t\t\texecute: async (_toolCallId, params, signal) => {\n\t\t\t\tconst args = params as RunCommandArgs;\n\t\t\t\tconst timeoutMs = (args.timeoutSeconds ?? context.bashTimeoutSeconds) * 1000;\n\t\t\t\tconst shell = process.platform === \"win32\" ? \"powershell.exe\" : \"/bin/sh\";\n\t\t\t\tconst shellArgs = process.platform === \"win32\" ? [\"-Command\", args.command] : [\"-c\", args.command];\n\t\t\t\ttry {\n\t\t\t\t\tconst { stdout, stderr } = await execFileAsync(shell, shellArgs, {\n\t\t\t\t\t\tcwd: workspaceDir,\n\t\t\t\t\t\ttimeout: timeoutMs,\n\t\t\t\t\t\tmaxBuffer: 10 * 1024 * 1024,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t});\n\t\t\t\t\tconst output = [stdout, stderr].filter(Boolean).join(\"\\n\");\n\t\t\t\t\treturn textResult(truncate(output === \"\" ? \"(no output)\" : output, context.maxToolOutputChars));\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\t\tconst stdout = (error as { stdout?: string }).stdout ?? \"\";\n\t\t\t\t\tconst stderr = (error as { stderr?: string }).stderr ?? \"\";\n\t\t\t\t\tconst output = [stdout, stderr, message].filter(Boolean).join(\"\\n\");\n\t\t\t\t\treturn errorResult(truncate(output, context.maxToolOutputChars));\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"grep\",\n\t\t\tlabel: \"Grep\",\n\t\t\tdescription: \"Search workspace files for a pattern. Returns path:line: text matches.\",\n\t\t\tparameters: GrepParams,\n\t\t\texecute: async (_toolCallId, params) => {\n\t\t\t\tconst args = params as GrepArgs;\n\t\t\t\ttry {\n\t\t\t\t\tconst flags = args.ignoreCase ? \"i\" : \"\";\n\t\t\t\t\tconst source = args.literal ? args.pattern.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\") : args.pattern;\n\t\t\t\t\tconst regex = new RegExp(source, flags);\n\t\t\t\t\tconst base = args.path ? resolveWorkspacePath(workspaceDir, args.path) : resolve(workspaceDir);\n\t\t\t\t\tconst files = statSync(base).isDirectory() ? walkWorkspaceFiles(base) : [base];\n\t\t\t\t\tconst limit = args.limit ?? 50;\n\t\t\t\t\tconst contextLines = args.contextLines ?? 0;\n\t\t\t\t\tconst lines: string[] = [];\n\t\t\t\t\tfor (const file of files) {\n\t\t\t\t\t\tconst buffer = readFileSync(file);\n\t\t\t\t\t\tif (isBinary(buffer)) continue;\n\t\t\t\t\t\tconst fileLines = buffer.toString(\"utf8\").split(\"\\n\");\n\t\t\t\t\t\tfor (let i = 0; i < fileLines.length; i += 1) {\n\t\t\t\t\t\t\tif (!regex.test(fileLines[i] ?? \"\")) continue;\n\t\t\t\t\t\t\tconst start = Math.max(0, i - contextLines);\n\t\t\t\t\t\t\tconst end = Math.min(fileLines.length, i + contextLines + 1);\n\t\t\t\t\t\t\tfor (let j = start; j < end; j += 1) {\n\t\t\t\t\t\t\t\tlines.push(`${relative(workspaceDir, file)}:${j + 1}: ${fileLines[j] ?? \"\"}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (lines.length >= limit) break;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (lines.length >= limit) break;\n\t\t\t\t\t}\n\t\t\t\t\tconst output = lines.slice(0, limit).join(\"\\n\");\n\t\t\t\t\treturn textResult(output === \"\" ? \"No matches.\" : truncate(output, context.maxToolOutputChars));\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn errorResult(error instanceof Error ? error.message : String(error));\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"find_files\",\n\t\t\tlabel: \"Find files\",\n\t\t\tdescription: 'Find workspace files by glob, e.g. \"src/**/*.ts\". A bare name matches basenames at any depth.',\n\t\t\tparameters: FindFilesParams,\n\t\t\texecute: async (_toolCallId, params) => {\n\t\t\t\tconst args = params as FindFilesArgs;\n\t\t\t\ttry {\n\t\t\t\t\tconst pattern = args.pattern.includes(\"/\") ? args.pattern : `**/${args.pattern}`;\n\t\t\t\t\tconst regex = globToRegExp(pattern);\n\t\t\t\t\tconst matches = walkWorkspaceFiles(workspaceDir)\n\t\t\t\t\t\t.map((file) => relative(workspaceDir, file).split(sep).join(\"/\"))\n\t\t\t\t\t\t.filter((rel) => regex.test(rel));\n\t\t\t\t\treturn textResult(matches.length > 0 ? matches.slice(0, 200).join(\"\\n\") : \"No files found.\");\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn errorResult(error instanceof Error ? error.message : String(error));\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"memory\",\n\t\t\tlabel: \"Memory\",\n\t\t\tdescription:\n\t\t\t\t\"Recall, read, list, or write memory. Memory is per user: this user's files only, under the user scope, plus the workspace project scope.\",\n\t\t\tparameters: MemoryParams,\n\t\t\texecute: async (_toolCallId, params) => {\n\t\t\t\tconst args = params as MemoryArgs;\n\t\t\t\tconst scope = args.scope === \"project\" ? \"project\" : \"user\";\n\t\t\t\ttry {\n\t\t\t\t\tswitch (args.action) {\n\t\t\t\t\t\tcase \"recall\": {\n\t\t\t\t\t\t\tif (!args.query) return errorResult(\"recall needs a query.\");\n\t\t\t\t\t\t\tconst findings = context.memoryStore.recall(args.query, { scopes: [scope] });\n\t\t\t\t\t\t\tif (findings.length === 0) return textResult(\"Nothing recalled.\");\n\t\t\t\t\t\t\treturn textResult(findings.map((finding) => `${finding.path}: ${finding.excerpt}`).join(\"\\n\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \"read\": {\n\t\t\t\t\t\t\tif (!args.path) return errorResult(\"read needs a path.\");\n\t\t\t\t\t\t\tconst file = context.memoryStore.readFile(scope, args.path);\n\t\t\t\t\t\t\treturn textResult(file.body);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \"list\": {\n\t\t\t\t\t\t\tconst files = context.memoryStore.listFiles(scope);\n\t\t\t\t\t\t\tif (files.length === 0) return textResult(\"No memory files.\");\n\t\t\t\t\t\t\treturn textResult(files.map((file) => `${file.path} — ${file.description}`).join(\"\\n\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \"write\": {\n\t\t\t\t\t\t\tif (!args.path || args.body === undefined) return errorResult(\"write needs a path and a body.\");\n\t\t\t\t\t\t\tcontext.memoryStore.writeFile(scope, args.path, args.body, {\n\t\t\t\t\t\t\t\tname: args.name ?? args.path,\n\t\t\t\t\t\t\t\tdescription: args.description ?? \"\",\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn textResult(`Wrote memory file ${args.path}.`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn errorResult(`Unknown memory action \"${args.action}\". Use recall, read, list, or write.`);\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn errorResult(error instanceof Error ? error.message : String(error));\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"skill\",\n\t\t\tlabel: \"Skill\",\n\t\t\tdescription:\n\t\t\t\t\"Load a skill on demand. Reads the skill's SKILL.md from the workspace or this user's memory skills and queues it for the next model request.\",\n\t\t\tparameters: SkillParams,\n\t\t\texecute: async (toolCallId, params) => {\n\t\t\t\tconst args = params as SkillArgs;\n\t\t\t\ttry {\n\t\t\t\t\tif (!args.skill) return errorResult(\"Skill needs a skill id.\");\n\t\t\t\t\tconst rendered = loadRenderedSkillContent(args.skill, {\n\t\t\t\t\t\troots: {\n\t\t\t\t\t\t\tprojectRoots: [join(workspaceDir, \".pigeon\", \"skills\"), join(workspaceDir, \".skills\")],\n\t\t\t\t\t\t\tmemorySkillsDirs: [join(context.memoryStore.userDir, \"skills\")],\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tcontext.skillQueue.queue(toolCallId, wrapSkillContent(args.skill, rendered));\n\t\t\t\t\treturn textResult(`Launching skill: ${args.skill}`);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn errorResult(error instanceof Error ? error.message : String(error));\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t];\n\treturn tools;\n}\n"]}
@@ -0,0 +1,108 @@
1
+ import type { StreamFn } from "@dev-crowagent/pigeon-agent-core";
2
+ import type { Api, Model } from "@dev-crowagent/pigeon-ai";
3
+ /** A user the host serves. In single-user mode this is always the fixed local user. */
4
+ export type UserId = string;
5
+ /** Minimal auth input: the bearer token from the request, if any. */
6
+ export interface ServerAuthContext {
7
+ authorization: string | undefined;
8
+ }
9
+ /**
10
+ * Authenticates a request and returns the user id, or null when the request
11
+ * is not authenticated. Hosts plug in real auth here; the token auth in
12
+ * auth.ts is the shipped default for multi-user mode.
13
+ */
14
+ export type Authenticate = (context: ServerAuthContext) => Promise<UserId | null> | UserId | null;
15
+ /** A tool call the permission system asked the user about. */
16
+ export interface ApprovalRequest {
17
+ id: string;
18
+ sessionId: string;
19
+ toolName: string;
20
+ args: Record<string, unknown>;
21
+ reason: string;
22
+ }
23
+ /** Host-side approval hook. Return true to allow the tool call, false to deny it. */
24
+ export type ApprovalHandler = (request: ApprovalRequest) => Promise<boolean> | boolean;
25
+ /** A custom OpenAI-compatible provider, stored per user in the user's settings file. */
26
+ export interface CustomProviderConfig {
27
+ slug: string;
28
+ baseUrl: string;
29
+ apiKey?: string;
30
+ models: string[];
31
+ name?: string;
32
+ }
33
+ /** Per-user settings, stored in the user's own settings.json (mode 0600). */
34
+ export interface UserSettings {
35
+ model?: string;
36
+ providerKeys?: Record<string, string>;
37
+ customProviders?: CustomProviderConfig[];
38
+ }
39
+ /** Options for {@link createServerHost}. */
40
+ export interface PigeonServerHostOptions {
41
+ /** Root for all per-user data: <dataDir>/users/<userId>/{workspace,memory,sessions,keys.json,settings.json}. */
42
+ dataDir: string;
43
+ port: number;
44
+ host?: string;
45
+ /** "single" serves one fixed user with no auth; "multi" requires authenticate or tokens. */
46
+ mode: "single" | "multi";
47
+ /** User id served in single-user mode. Defaults to "local". */
48
+ singleUserId?: string;
49
+ /** Pluggable auth for multi-user mode. Required when mode is "multi" and tokens is unset. */
50
+ authenticate?: Authenticate;
51
+ /** Per-user bearer tokens for multi-user mode: userId -> token. */
52
+ tokens?: Record<string, string>;
53
+ /** Default model ref, "provider/modelId". Defaults to "anthropic/claude-haiku-4-5". */
54
+ modelRef?: string;
55
+ /** System prompt for every session's agent. */
56
+ systemPrompt?: string;
57
+ /** Stream function override (tests). Defaults to streamSimple from pigeon-ai. */
58
+ streamFn?: StreamFn;
59
+ /** Model override (tests). Defaults to resolving modelRef against the shared catalog. */
60
+ model?: Model<Api>;
61
+ /** Idle milliseconds after which an unused session is evicted. Defaults to 30 minutes. */
62
+ sessionIdleMs?: number;
63
+ /** Maximum assistant turns per run. Defaults to 50. */
64
+ maxTurns?: number;
65
+ /** Maximum tool output characters kept per call. Defaults to 20000. */
66
+ maxToolOutputChars?: number;
67
+ /** Timeout for shell tool calls, in seconds. Defaults to 120. */
68
+ bashTimeoutSeconds?: number;
69
+ /** Approval hook for ask rules. Defaults to deny. */
70
+ onApprovalRequest?: ApprovalHandler;
71
+ /** Milliseconds an approval request waits for an answer before denying. Defaults to 120000. */
72
+ approvalTimeoutMs?: number;
73
+ }
74
+ /** Public session info returned by the API. */
75
+ export interface SessionInfo {
76
+ id: string;
77
+ userId: string;
78
+ model: string;
79
+ createdAt: number;
80
+ lastUsedAt: number;
81
+ active: boolean;
82
+ toolCalls: number;
83
+ }
84
+ /** One event on the prompt SSE stream. */
85
+ export type PromptEvent = {
86
+ type: "text";
87
+ text: string;
88
+ } | {
89
+ type: "tool_start";
90
+ toolCallId: string;
91
+ toolName: string;
92
+ } | {
93
+ type: "tool_end";
94
+ toolCallId: string;
95
+ toolName: string;
96
+ isError: boolean;
97
+ } | {
98
+ type: "approval_request";
99
+ request: ApprovalRequest;
100
+ } | {
101
+ type: "done";
102
+ text: string;
103
+ toolCalls: number;
104
+ } | {
105
+ type: "error";
106
+ message: string;
107
+ };
108
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,kCAAkC,CAAC;AACjE,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,0BAA0B,CAAC;AAE3D,uFAAuF;AACvF,MAAM,MAAM,MAAM,GAAG,MAAM,CAAC;AAE5B,qEAAqE;AACrE,MAAM,WAAW,iBAAiB;IACjC,aAAa,EAAE,MAAM,GAAG,SAAS,CAAC;CAClC;AAED;;;;GAIG;AACH,MAAM,MAAM,YAAY,GAAG,CAAC,OAAO,EAAE,iBAAiB,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,GAAG,MAAM,GAAG,IAAI,CAAC;AAElG,8DAA8D;AAC9D,MAAM,WAAW,eAAe;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC9B,MAAM,EAAE,MAAM,CAAC;CACf;AAED,qFAAqF;AACrF,MAAM,MAAM,eAAe,GAAG,CAAC,OAAO,EAAE,eAAe,KAAK,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;AAEvF,wFAAwF;AACxF,MAAM,WAAW,oBAAoB;IACpC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CA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,MAAM,CAAC;CAC3B;AAED,+CAA+C;AAC/C,MAAM,WAAW,WAAW;IAC3B,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,OAAO,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;CAClB;AAED,0CAA0C;AAC1C,MAAM,MAAM,WAAW,GACpB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAC9B;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,GAC5D;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,GAC5E;IAAE,IAAI,EAAE,kBAAkB,CAAC;IAAC,OAAO,EAAE,eAAe,CAAA;CAAE,GACtD;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GACjD;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC"}
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { StreamFn } from \"@dev-crowagent/pigeon-agent-core\";\nimport type { Api, Model } from \"@dev-crowagent/pigeon-ai\";\n\n/** A user the host serves. In single-user mode this is always the fixed local user. */\nexport type UserId = string;\n\n/** Minimal auth input: the bearer token from the request, if any. */\nexport interface ServerAuthContext {\n\tauthorization: string | undefined;\n}\n\n/**\n * Authenticates a request and returns the user id, or null when the request\n * is not authenticated. Hosts plug in real auth here; the token auth in\n * auth.ts is the shipped default for multi-user mode.\n */\nexport type Authenticate = (context: ServerAuthContext) => Promise<UserId | null> | UserId | null;\n\n/** A tool call the permission system asked the user about. */\nexport interface ApprovalRequest {\n\tid: string;\n\tsessionId: string;\n\ttoolName: string;\n\targs: Record<string, unknown>;\n\treason: string;\n}\n\n/** Host-side approval hook. Return true to allow the tool call, false to deny it. */\nexport type ApprovalHandler = (request: ApprovalRequest) => Promise<boolean> | boolean;\n\n/** A custom OpenAI-compatible provider, stored per user in the user's settings file. */\nexport interface CustomProviderConfig {\n\tslug: string;\n\tbaseUrl: string;\n\tapiKey?: string;\n\tmodels: string[];\n\tname?: string;\n}\n\n/** Per-user settings, stored in the user's own settings.json (mode 0600). */\nexport interface UserSettings {\n\tmodel?: string;\n\tproviderKeys?: Record<string, string>;\n\tcustomProviders?: CustomProviderConfig[];\n}\n\n/** Options for {@link createServerHost}. */\nexport interface PigeonServerHostOptions {\n\t/** Root for all per-user data: <dataDir>/users/<userId>/{workspace,memory,sessions,keys.json,settings.json}. */\n\tdataDir: string;\n\tport: number;\n\thost?: string;\n\t/** \"single\" serves one fixed user with no auth; \"multi\" requires authenticate or tokens. */\n\tmode: \"single\" | \"multi\";\n\t/** User id served in single-user mode. Defaults to \"local\". */\n\tsingleUserId?: string;\n\t/** Pluggable auth for multi-user mode. Required when mode is \"multi\" and tokens is unset. */\n\tauthenticate?: Authenticate;\n\t/** Per-user bearer tokens for multi-user mode: userId -> token. */\n\ttokens?: Record<string, string>;\n\t/** Default model ref, \"provider/modelId\". Defaults to \"anthropic/claude-haiku-4-5\". */\n\tmodelRef?: string;\n\t/** System prompt for every session's agent. */\n\tsystemPrompt?: string;\n\t/** Stream function override (tests). Defaults to streamSimple from pigeon-ai. */\n\tstreamFn?: StreamFn;\n\t/** Model override (tests). Defaults to resolving modelRef against the shared catalog. */\n\tmodel?: Model<Api>;\n\t/** Idle milliseconds after which an unused session is evicted. Defaults to 30 minutes. */\n\tsessionIdleMs?: number;\n\t/** Maximum assistant turns per run. Defaults to 50. */\n\tmaxTurns?: number;\n\t/** Maximum tool output characters kept per call. Defaults to 20000. */\n\tmaxToolOutputChars?: number;\n\t/** Timeout for shell tool calls, in seconds. Defaults to 120. */\n\tbashTimeoutSeconds?: number;\n\t/** Approval hook for ask rules. Defaults to deny. */\n\tonApprovalRequest?: ApprovalHandler;\n\t/** Milliseconds an approval request waits for an answer before denying. Defaults to 120000. */\n\tapprovalTimeoutMs?: number;\n}\n\n/** Public session info returned by the API. */\nexport interface SessionInfo {\n\tid: string;\n\tuserId: string;\n\tmodel: string;\n\tcreatedAt: number;\n\tlastUsedAt: number;\n\tactive: boolean;\n\ttoolCalls: number;\n}\n\n/** One event on the prompt SSE stream. */\nexport type PromptEvent =\n\t| { type: \"text\"; text: string }\n\t| { type: \"tool_start\"; toolCallId: string; toolName: string }\n\t| { type: \"tool_end\"; toolCallId: string; toolName: string; isError: boolean }\n\t| { type: \"approval_request\"; request: ApprovalRequest }\n\t| { type: \"done\"; text: string; toolCalls: number }\n\t| { type: \"error\"; message: string };\n"]}
@@ -0,0 +1,22 @@
1
+ /** User ids are path segments; reject anything that could escape the user directory. */
2
+ export declare function assertValidUserId(userId: string): void;
3
+ /** Per-user data root: <dataDir>/users/<userId>. */
4
+ export declare function userDir(dataDir: string, userId: string): string;
5
+ /** Per-user workspace: the only directory the user's agent tools may touch. */
6
+ export declare function userWorkspaceDir(dataDir: string, userId: string): string;
7
+ /** Per-user memory root for the kit MemoryStore. */
8
+ export declare function userMemoryDir(dataDir: string, userId: string): string;
9
+ /** Per-user session transcripts. */
10
+ export declare function userSessionsDir(dataDir: string, userId: string): string;
11
+ /** Per-user settings file (mode 0600). */
12
+ export declare function userSettingsPath(dataDir: string, userId: string): string;
13
+ /** Per-user provider keys file (mode 0600). */
14
+ export declare function userKeysPath(dataDir: string, userId: string): string;
15
+ /** Creates the per-user directories (workspace, memory, sessions). */
16
+ export declare function ensureUserDirs(dataDir: string, userId: string): void;
17
+ /**
18
+ * Resolves a tool path inside the workspace. Paths that escape the workspace
19
+ * (absolute paths outside it, `..` segments) are rejected.
20
+ */
21
+ export declare function resolveWorkspacePath(workspaceDir: string, relative: string): string;
22
+ //# sourceMappingURL=workspace.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workspace.d.ts","sourceRoot":"","sources":["../src/workspace.ts"],"names":[],"mappings":"AAKA,wFAAwF;AACxF,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAItD;AAED,oDAAoD;AACpD,wBAAgB,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAG/D;AAED,+EAA+E;AAC/E,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAExE;AAED,oDAAoD;AACpD,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAErE;AAED,oCAAoC;AACpC,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAEvE;AAED,0CAA0C;AAC1C,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAExE;AAED,+CAA+C;AAC/C,wBAAgB,YAAY,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAEpE;AAED,sEAAsE;AACtE,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CAIpE;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,YAAY,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAOnF"}