@flue/sdk 0.3.10 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flue/sdk",
3
- "version": "0.3.10",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
6
  "exports": {
@@ -8,6 +8,10 @@
8
8
  "types": "./dist/index.d.mts",
9
9
  "import": "./dist/index.mjs"
10
10
  },
11
+ "./app": {
12
+ "types": "./dist/app.d.mts",
13
+ "import": "./dist/app.mjs"
14
+ },
11
15
  "./client": {
12
16
  "types": "./dist/client.d.mts",
13
17
  "import": "./dist/client.mjs"
@@ -27,6 +31,10 @@
27
31
  "./node": {
28
32
  "types": "./dist/node/index.d.mts",
29
33
  "import": "./dist/node/index.mjs"
34
+ },
35
+ "./config": {
36
+ "types": "./dist/config.d.mts",
37
+ "import": "./dist/config.mjs"
30
38
  }
31
39
  },
32
40
  "main": "./dist/index.mjs",
@@ -34,6 +42,9 @@
34
42
  "files": [
35
43
  "dist"
36
44
  ],
45
+ "engines": {
46
+ "node": ">=22.18.0"
47
+ },
37
48
  "dependencies": {
38
49
  "@cloudflare/shell": "^0.3.2",
39
50
  "@hono/node-server": "^1.14.0",
@@ -45,6 +56,7 @@
45
56
  "hono": "^4.7.0",
46
57
  "just-bash": "^2.14.2",
47
58
  "package-up": "^5.0.0",
59
+ "typescript": "^5.9.2",
48
60
  "valibot": "^1.0.0"
49
61
  },
50
62
  "devDependencies": {
@@ -1,453 +0,0 @@
1
- import { Type } from "@mariozechner/pi-ai";
2
-
3
- //#region src/context.ts
4
- /** Parse optional YAML frontmatter (--- delimited). Basic `key: value` only. */
5
- function parseFrontmatterFile(content, defaultName) {
6
- const frontmatterMatch = content.match(/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/);
7
- if (!frontmatterMatch) return {
8
- name: defaultName,
9
- description: "",
10
- body: content.trim(),
11
- frontmatter: {}
12
- };
13
- const rawFrontmatter = frontmatterMatch[1] ?? "";
14
- const body = frontmatterMatch[2] ?? "";
15
- const frontmatter = {};
16
- for (const line of rawFrontmatter.split("\n")) {
17
- const match = line.match(/^(\w+):\s*(.+)$/);
18
- if (match?.[1] && match[2]) frontmatter[match[1]] = match[2].trim();
19
- }
20
- return {
21
- name: frontmatter.name || defaultName,
22
- description: frontmatter.description || "",
23
- body: body.trim(),
24
- frontmatter
25
- };
26
- }
27
- /** Read AGENTS.md (and CLAUDE.md if present) from a directory. Returns concatenated contents. */
28
- async function readAgentsMd(env, basePath) {
29
- const parts = [];
30
- for (const filename of ["AGENTS.md", "CLAUDE.md"]) {
31
- const filePath = basePath.endsWith("/") ? basePath + filename : `${basePath}/${filename}`;
32
- if (await env.exists(filePath)) {
33
- const content = await env.readFile(filePath);
34
- parts.push(content.trim());
35
- }
36
- }
37
- return parts.join("\n\n");
38
- }
39
- /**
40
- * Load a skill directly by relative path under `.agents/skills/`.
41
- *
42
- * The path is taken as-is — no extension is auto-appended. Callers reference
43
- * the full filename, e.g. `'triage/reproduce.md'`. Returns `null` if the file
44
- * doesn't exist.
45
- *
46
- * Used as a fallback by `session.skill()` when the requested name doesn't match
47
- * a discovered skill's frontmatter `name:` field. Lets users organise skills as
48
- * a pack of sibling markdown files under one directory (orchestration SKILL.md
49
- * + stage files) without forcing each stage into its own `SKILL.md` subdirectory.
50
- */
51
- async function loadSkillByPath(env, basePath, relPath) {
52
- const filePath = `${basePath.endsWith("/") ? `${basePath}.agents/skills` : `${basePath}/.agents/skills`}/${relPath}`;
53
- if (!await env.exists(filePath)) return null;
54
- const parsed = parseFrontmatterFile(await env.readFile(filePath), relPath.replace(/\.(md|markdown)$/i, ""));
55
- return {
56
- name: parsed.name,
57
- description: parsed.description,
58
- instructions: parsed.body
59
- };
60
- }
61
- /** Discover skills from .agents/skills/<name>/SKILL.md under basePath. */
62
- async function discoverLocalSkills(env, basePath) {
63
- const skillsDir = basePath.endsWith("/") ? `${basePath}.agents/skills` : `${basePath}/.agents/skills`;
64
- if (!await env.exists(skillsDir)) return {};
65
- const skills = {};
66
- const entries = await env.readdir(skillsDir);
67
- for (const entry of entries) {
68
- const skillDir = `${skillsDir}/${entry}`;
69
- try {
70
- if (!(await env.stat(skillDir)).isDirectory) continue;
71
- } catch {
72
- continue;
73
- }
74
- const skillMdPath = `${skillDir}/SKILL.md`;
75
- if (!await env.exists(skillMdPath)) continue;
76
- const parsed = parseFrontmatterFile(await env.readFile(skillMdPath), entry);
77
- skills[parsed.name] = {
78
- name: parsed.name,
79
- description: parsed.description,
80
- instructions: parsed.body
81
- };
82
- }
83
- return skills;
84
- }
85
- function composeSystemPrompt(agentsMd, skills, env) {
86
- const parts = [];
87
- if (agentsMd) parts.push(agentsMd);
88
- const skillEntries = Object.values(skills);
89
- if (skillEntries.length > 0) {
90
- parts.push("", "## Available Skills", "");
91
- for (const skill of skillEntries) {
92
- const desc = skill.description ? ` - ${skill.description}` : "";
93
- parts.push(`- **${skill.name}**${desc}`);
94
- }
95
- }
96
- if (env) {
97
- const date = (/* @__PURE__ */ new Date()).toLocaleDateString("en-US", {
98
- weekday: "short",
99
- year: "numeric",
100
- month: "short",
101
- day: "numeric"
102
- });
103
- parts.push("", `Date: ${date}`);
104
- parts.push(`Working directory: ${env.cwd}`);
105
- if (env.directoryListing && env.directoryListing.length > 0) parts.push("", "Directory structure:", env.directoryListing.join("\n"));
106
- }
107
- return parts.join("\n");
108
- }
109
- /** Discover AGENTS.md, local skills, and directory listing from the session's cwd. */
110
- async function discoverSessionContext(env) {
111
- const cwd = env.cwd;
112
- const agentsMd = await readAgentsMd(env, cwd);
113
- const skills = await discoverLocalSkills(env, cwd);
114
- let directoryListing;
115
- try {
116
- directoryListing = await env.readdir(cwd);
117
- } catch {}
118
- return {
119
- systemPrompt: composeSystemPrompt(agentsMd, skills, {
120
- cwd,
121
- directoryListing
122
- }),
123
- skills
124
- };
125
- }
126
-
127
- //#endregion
128
- //#region src/agent.ts
129
- const MAX_READ_LINES = 2e3;
130
- const MAX_READ_BYTES = 50 * 1024;
131
- const MAX_GREP_MATCHES = 100;
132
- const MAX_GREP_LINE_LENGTH = 500;
133
- const MAX_GLOB_RESULTS = 1e3;
134
- const BUILTIN_TOOL_NAMES = new Set([
135
- "read",
136
- "write",
137
- "edit",
138
- "bash",
139
- "grep",
140
- "glob",
141
- "task"
142
- ]);
143
- function createTools(env, options) {
144
- const tools = [
145
- createReadTool(env),
146
- createWriteTool(env),
147
- createEditTool(env),
148
- createBashTool(env),
149
- createGrepTool(env),
150
- createGlobTool(env)
151
- ];
152
- if (options?.task) tools.push(createTaskTool(options.task, options.roles ?? {}));
153
- return tools;
154
- }
155
- function createReadTool(env) {
156
- return {
157
- name: "read",
158
- label: "Read File",
159
- description: "Read a file or list a directory. For files, output is truncated to 2000 lines or 50KB — use offset/limit for large files. For directories, returns the list of entries.",
160
- parameters: Type.Object({
161
- path: Type.String({ description: "Path to the file to read" }),
162
- offset: Type.Optional(Type.Number({ description: "Line number to start from (1-indexed)" })),
163
- limit: Type.Optional(Type.Number({ description: "Maximum number of lines to read" }))
164
- }),
165
- async execute(_toolCallId, params, signal) {
166
- throwIfAborted(signal);
167
- try {
168
- if ((await env.stat(params.path)).isDirectory) {
169
- const entries = await env.readdir(params.path);
170
- return {
171
- content: [{
172
- type: "text",
173
- text: entries.join("\n") || "(empty directory)"
174
- }],
175
- details: {
176
- path: params.path,
177
- isDirectory: true,
178
- entries: entries.length
179
- }
180
- };
181
- }
182
- } catch {}
183
- const allLines = (await env.readFile(params.path)).split("\n");
184
- const startLine = params.offset ? Math.max(0, params.offset - 1) : 0;
185
- if (startLine >= allLines.length) throw new Error(`Offset ${params.offset} is beyond end of file (${allLines.length} lines total)`);
186
- const endLine = params.limit ? startLine + params.limit : allLines.length;
187
- const { text: truncatedText, wasTruncated } = truncateHead(allLines.slice(startLine, endLine), MAX_READ_LINES, MAX_READ_BYTES);
188
- let output = truncatedText;
189
- if (wasTruncated) {
190
- const shownEnd = startLine + truncatedText.split("\n").length;
191
- output += `\n\n[Showing lines ${startLine + 1}-${shownEnd} of ${allLines.length}. Use offset=${shownEnd + 1} to continue.]`;
192
- }
193
- return {
194
- content: [{
195
- type: "text",
196
- text: output
197
- }],
198
- details: {
199
- path: params.path,
200
- lines: allLines.length
201
- }
202
- };
203
- }
204
- };
205
- }
206
- function createWriteTool(env) {
207
- return {
208
- name: "write",
209
- label: "Write File",
210
- description: "Write content to a file. Creates the file and parent directories if they do not exist.",
211
- parameters: Type.Object({
212
- path: Type.String({ description: "Path to the file to write" }),
213
- content: Type.String({ description: "Content to write to the file" })
214
- }),
215
- async execute(_toolCallId, params, signal) {
216
- throwIfAborted(signal);
217
- const resolved = env.resolvePath(params.path);
218
- const dir = resolved.replace(/\/[^/]*$/, "");
219
- if (dir && dir !== resolved) await env.mkdir(dir, { recursive: true });
220
- await env.writeFile(resolved, params.content);
221
- return {
222
- content: [{
223
- type: "text",
224
- text: `Successfully wrote ${params.content.length} bytes to ${params.path}`
225
- }],
226
- details: {
227
- path: params.path,
228
- size: params.content.length
229
- }
230
- };
231
- }
232
- };
233
- }
234
- function createEditTool(env) {
235
- return {
236
- name: "edit",
237
- label: "Edit File",
238
- description: "Edit a file using exact text replacement. The oldText must match a unique region of the file. Use replaceAll to replace all occurrences.",
239
- parameters: Type.Object({
240
- path: Type.String({ description: "Path to the file to edit" }),
241
- oldText: Type.String({ description: "Exact text to find (must be unique)" }),
242
- newText: Type.String({ description: "Replacement text" }),
243
- replaceAll: Type.Optional(Type.Boolean({ description: "Replace all occurrences" }))
244
- }),
245
- async execute(_toolCallId, params, signal) {
246
- throwIfAborted(signal);
247
- const content = await env.readFile(params.path);
248
- if (params.replaceAll) {
249
- const newContent = content.replaceAll(params.oldText, params.newText);
250
- if (newContent === content) throw new Error(`Could not find the text in ${params.path}. No changes made.`);
251
- await env.writeFile(params.path, newContent);
252
- const count = content.split(params.oldText).length - 1;
253
- return {
254
- content: [{
255
- type: "text",
256
- text: `Replaced ${count} occurrences in ${params.path}`
257
- }],
258
- details: {
259
- path: params.path,
260
- replacements: count
261
- }
262
- };
263
- }
264
- const occurrences = countOccurrences(content, params.oldText);
265
- if (occurrences === 0) throw new Error(`Could not find the exact text in ${params.path}. Make sure your oldText matches exactly, including whitespace and indentation.`);
266
- if (occurrences > 1) throw new Error(`Found ${occurrences} occurrences of the text in ${params.path}. Provide more surrounding context to make the match unique, or use replaceAll.`);
267
- const newContent = content.replace(params.oldText, params.newText);
268
- await env.writeFile(params.path, newContent);
269
- return {
270
- content: [{
271
- type: "text",
272
- text: `Successfully edited ${params.path}`
273
- }],
274
- details: { path: params.path }
275
- };
276
- }
277
- };
278
- }
279
- function createBashTool(env) {
280
- return {
281
- name: "bash",
282
- label: "Run Command",
283
- description: "Execute a bash command. Returns stdout and stderr. Output is truncated to the last 2000 lines or 50KB.",
284
- parameters: Type.Object({
285
- command: Type.String({ description: "Bash command to execute" }),
286
- timeout: Type.Optional(Type.Number({ description: "Timeout in seconds" }))
287
- }),
288
- async execute(_toolCallId, params, signal) {
289
- throwIfAborted(signal);
290
- return formatBashResult(await env.exec(params.command, { timeout: params.timeout }), params.command);
291
- }
292
- };
293
- }
294
- function createTaskTool(runTask, roles) {
295
- const roleNames = Object.keys(roles);
296
- return {
297
- name: "task",
298
- label: "Run Task",
299
- description: "Delegate a focused task to a detached child agent with its own context. Use this for independent research, file exploration, or parallel work. The task returns only its final answer to this conversation." + (roleNames.length > 0 ? ` Available roles: ${roleNames.join(", ")}.` : " No roles are currently defined."),
300
- parameters: Type.Object({
301
- description: Type.Optional(Type.String({ description: "Short human-readable label for the delegated work" })),
302
- prompt: Type.String({ description: "Focused instructions for the child agent" }),
303
- role: Type.Optional(Type.String({ description: "Role to use for the child agent" })),
304
- cwd: Type.Optional(Type.String({ description: "Working directory for the child agent. AGENTS.md and skills are discovered from here." }))
305
- }),
306
- async execute(_toolCallId, params, signal) {
307
- throwIfAborted(signal);
308
- return runTask(params, signal);
309
- }
310
- };
311
- }
312
- function formatBashResult(result, command) {
313
- const { text: output } = truncateTail((result.stdout + (result.stderr ? "\n" + result.stderr : "")).trim(), MAX_READ_LINES, MAX_READ_BYTES);
314
- if (result.exitCode !== 0) throw new Error(`${output}\n\nCommand exited with code ${result.exitCode}`);
315
- return {
316
- content: [{
317
- type: "text",
318
- text: output || "(no output)"
319
- }],
320
- details: {
321
- command,
322
- exitCode: result.exitCode
323
- }
324
- };
325
- }
326
- function createGrepTool(env) {
327
- return {
328
- name: "grep",
329
- label: "Search Files",
330
- description: "Search file contents for a regex pattern. Returns matching lines with file paths and line numbers.",
331
- parameters: Type.Object({
332
- pattern: Type.String({ description: "Search pattern (regex)" }),
333
- path: Type.Optional(Type.String({ description: "Directory or file to search (default: .)" })),
334
- include: Type.Optional(Type.String({ description: "Glob filter, e.g. \"*.ts\"" }))
335
- }),
336
- async execute(_toolCallId, params, signal) {
337
- throwIfAborted(signal);
338
- const searchPath = params.path || ".";
339
- let cmd = `grep -rn "${escapeShellArg(params.pattern)}" ${escapeShellArg(searchPath)}`;
340
- if (params.include) cmd = `grep -rn --include="${escapeShellArg(params.include)}" "${escapeShellArg(params.pattern)}" ${escapeShellArg(searchPath)}`;
341
- const result = await env.exec(cmd);
342
- if (result.exitCode === 1 && !result.stdout.trim()) return {
343
- content: [{
344
- type: "text",
345
- text: "No matches found."
346
- }],
347
- details: { matchCount: 0 }
348
- };
349
- if (result.exitCode > 1) throw new Error(`grep failed: ${result.stderr}`);
350
- const lines = result.stdout.trim().split("\n");
351
- let finalOutput = lines.slice(0, MAX_GREP_MATCHES).map((line) => line.length > MAX_GREP_LINE_LENGTH ? line.slice(0, MAX_GREP_LINE_LENGTH) + "..." : line).join("\n");
352
- if (lines.length > MAX_GREP_MATCHES) finalOutput += `\n\n[Showing ${MAX_GREP_MATCHES} of ${lines.length} matches. Narrow your search.]`;
353
- return {
354
- content: [{
355
- type: "text",
356
- text: finalOutput
357
- }],
358
- details: { matchCount: Math.min(lines.length, MAX_GREP_MATCHES) }
359
- };
360
- }
361
- };
362
- }
363
- function createGlobTool(env) {
364
- return {
365
- name: "glob",
366
- label: "Find Files",
367
- description: "Find files by glob pattern. Returns matching file paths.",
368
- parameters: Type.Object({
369
- pattern: Type.String({ description: "Glob pattern, e.g. \"**/*.ts\"" }),
370
- path: Type.Optional(Type.String({ description: "Directory to search in (default: .)" }))
371
- }),
372
- async execute(_toolCallId, params, signal) {
373
- throwIfAborted(signal);
374
- const cmd = `find ${escapeShellArg(params.path || ".")} -type f -name "${escapeShellArg(params.pattern)}" 2>/dev/null | head -${MAX_GLOB_RESULTS}`;
375
- const result = await env.exec(cmd);
376
- if (result.exitCode !== 0 && !result.stdout.trim()) return {
377
- content: [{
378
- type: "text",
379
- text: "No files found matching pattern."
380
- }],
381
- details: { matchCount: 0 }
382
- };
383
- const paths = result.stdout.trim().split("\n").filter(Boolean);
384
- if (paths.length === 0) return {
385
- content: [{
386
- type: "text",
387
- text: "No files found matching pattern."
388
- }],
389
- details: { matchCount: 0 }
390
- };
391
- return {
392
- content: [{
393
- type: "text",
394
- text: paths.join("\n")
395
- }],
396
- details: { matchCount: paths.length }
397
- };
398
- }
399
- };
400
- }
401
- function throwIfAborted(signal) {
402
- if (signal?.aborted) throw new Error("Operation aborted");
403
- }
404
- function countOccurrences(str, substr) {
405
- let count = 0;
406
- let pos = str.indexOf(substr, 0);
407
- while (pos !== -1) {
408
- count++;
409
- pos = str.indexOf(substr, pos + substr.length);
410
- }
411
- return count;
412
- }
413
- function escapeShellArg(arg) {
414
- return arg.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\$/g, "\\$").replace(/`/g, "\\`");
415
- }
416
- function truncateHead(lines, maxLines, maxBytes) {
417
- let result = "";
418
- let lineCount = 0;
419
- let wasTruncated = false;
420
- for (const line of lines) {
421
- if (lineCount >= maxLines) {
422
- wasTruncated = true;
423
- break;
424
- }
425
- const next = lineCount === 0 ? line : "\n" + line;
426
- if (result.length + next.length > maxBytes) {
427
- wasTruncated = true;
428
- break;
429
- }
430
- result += next;
431
- lineCount++;
432
- }
433
- return {
434
- text: result,
435
- wasTruncated
436
- };
437
- }
438
- function truncateTail(text, maxLines, maxBytes) {
439
- const lines = text.split("\n");
440
- if (lines.length <= maxLines && text.length <= maxBytes) return {
441
- text,
442
- wasTruncated: false
443
- };
444
- let result = lines.slice(-maxLines).join("\n");
445
- if (result.length > maxBytes) result = result.slice(-maxBytes);
446
- return {
447
- text: result,
448
- wasTruncated: true
449
- };
450
- }
451
-
452
- //#endregion
453
- export { parseFrontmatterFile as a, loadSkillByPath as i, createTools as n, discoverSessionContext as r, BUILTIN_TOOL_NAMES as t };
@@ -1,21 +0,0 @@
1
- import { A as ShellResult } from "./types-CKcp6T-y.mjs";
2
-
3
- //#region src/command-helpers.d.ts
4
- /**
5
- * Loose return shape accepted from user-supplied command executors. All forms
6
- * are normalized to a full `ShellResult` by `normalizeExecutor()`.
7
- */
8
- type CommandExecutorResult = ShellResult | {
9
- stdout?: string;
10
- stderr?: string;
11
- exitCode?: number;
12
- } | string | void;
13
- /**
14
- * User-supplied command executor. Can return a full `ShellResult`, a partial
15
- * `{ stdout?, stderr?, exitCode? }` object, a bare string (treated as stdout),
16
- * or void (empty success). Thrown errors are caught and converted to an
17
- * `exitCode`-bearing `ShellResult` — no `try`/`catch` needed at the call site.
18
- */
19
- type CommandExecutor = (args: string[]) => Promise<CommandExecutorResult>;
20
- //#endregion
21
- export { CommandExecutor as t };
@@ -1,37 +0,0 @@
1
- //#region src/command-helpers.ts
2
- /**
3
- * Wrap a user-supplied `CommandExecutor` to always resolve with a full
4
- * `ShellResult`. Applies loose-return normalization and catches throws.
5
- */
6
- function normalizeExecutor(executor) {
7
- return async (args) => {
8
- try {
9
- const raw = await executor(args);
10
- if (raw === void 0 || raw === null) return {
11
- stdout: "",
12
- stderr: "",
13
- exitCode: 0
14
- };
15
- if (typeof raw === "string") return {
16
- stdout: raw,
17
- stderr: "",
18
- exitCode: 0
19
- };
20
- return {
21
- stdout: raw.stdout ?? "",
22
- stderr: raw.stderr ?? "",
23
- exitCode: raw.exitCode ?? 0
24
- };
25
- } catch (err) {
26
- const e = err ?? {};
27
- return {
28
- stdout: typeof e.stdout === "string" ? e.stdout : "",
29
- stderr: typeof e.stderr === "string" ? e.stderr : String(err),
30
- exitCode: typeof e.code === "number" ? e.code : 1
31
- };
32
- }
33
- };
34
- }
35
-
36
- //#endregion
37
- export { normalizeExecutor as t };