@flue/sdk 0.1.3 → 0.3.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/dist/client.mjs DELETED
@@ -1,59 +0,0 @@
1
- import { r as discoverSessionContext } from "./agent-BYG0nVbQ.mjs";
2
- import { n as Session } from "./session-CiAMTsLZ.mjs";
3
- import { bashToSessionEnv } from "./sandbox.mjs";
4
- import { Type } from "@mariozechner/pi-ai";
5
-
6
- //#region src/client.ts
7
- function createFlueContext(config) {
8
- let initialized = false;
9
- let currentEventCallback;
10
- return {
11
- get sessionId() {
12
- return config.sessionId;
13
- },
14
- get payload() {
15
- return config.payload;
16
- },
17
- get env() {
18
- return config.env;
19
- },
20
- async init(options) {
21
- if (initialized) throw new Error("[flue] init() can only be called once per request.");
22
- initialized = true;
23
- const sandbox = options?.sandbox;
24
- const env = await resolveSessionEnv(config.sessionId, sandbox, config);
25
- const store = options?.persist ?? config.defaultStore;
26
- const savedData = await store.load(config.sessionId);
27
- const localContext = await discoverSessionContext(env);
28
- const sessionModel = options?.model && config.agentConfig.resolveModel ? config.agentConfig.resolveModel(options.model) : config.agentConfig.model;
29
- const sessionConfig = {
30
- ...config.agentConfig,
31
- systemPrompt: localContext.systemPrompt,
32
- skills: localContext.skills,
33
- model: sessionModel
34
- };
35
- return new Session(config.sessionId, sessionConfig, env, store, savedData, currentEventCallback, options?.commands);
36
- },
37
- setEventCallback(callback) {
38
- currentEventCallback = callback;
39
- }
40
- };
41
- }
42
- /** Duck-type detection for just-bash Bash instances. */
43
- function isBashLike(value) {
44
- return typeof value === "object" && value !== null && "exec" in value && "getCwd" in value && "fs" in value && typeof value.exec === "function" && typeof value.getCwd === "function" && typeof value.fs === "object";
45
- }
46
- /** Resolve sandbox option to SessionEnv: empty → local → BashLike → platform hook → SandboxFactory. */
47
- async function resolveSessionEnv(sessionId, sandbox, config) {
48
- if (sandbox === void 0 || sandbox === "empty") return config.createDefaultEnv();
49
- if (sandbox === "local") return config.createLocalEnv();
50
- if (isBashLike(sandbox)) return bashToSessionEnv(sandbox);
51
- if (config.resolveSandbox) {
52
- const resolved = await config.resolveSandbox(sandbox);
53
- if (resolved) return resolved;
54
- }
55
- return sandbox.createSessionEnv({ sessionId });
56
- }
57
-
58
- //#endregion
59
- export { Type, createFlueContext };
@@ -1,40 +0,0 @@
1
- import { S as SessionStore, b as SessionEnv, s as Command } from "../types-BZPltYah.mjs";
2
- import { t as CommandExecutor } from "../command-helpers-BPcSV93o.mjs";
3
-
4
- //#region src/cloudflare/virtual-sandbox.d.ts
5
- interface VirtualSandboxOptions {
6
- /** R2 key prefix for session isolation. */
7
- prefix?: string;
8
- }
9
- declare function getVirtualSandbox(): Promise<any>;
10
- declare function getVirtualSandbox(bucket: unknown, options?: VirtualSandboxOptions): Promise<any>;
11
- //#endregion
12
- //#region src/cloudflare/define-command.d.ts
13
- declare function defineCommand(name: string, execute: CommandExecutor): Command;
14
- //#endregion
15
- //#region src/cloudflare/cf-sandbox.d.ts
16
- declare function cfSandboxToSessionEnv(sandbox: any, cwd?: string): Promise<SessionEnv>;
17
- //#endregion
18
- //#region src/cloudflare/session-store.d.ts
19
- declare function store(): SessionStore;
20
- //#endregion
21
- //#region src/cloudflare/context.d.ts
22
- /**
23
- * Cloudflare environment context injection. Safe because each DO is single-threaded.
24
- * Set before handler invocation, accessed by runtime primitives, cleared after.
25
- */
26
- interface CloudflareContext {
27
- env: Record<string, any>;
28
- agentInstance: {
29
- state: any;
30
- setState(state: any): void;
31
- };
32
- storage: {
33
- sql: any;
34
- };
35
- }
36
- declare function setCloudflareContext(ctx: CloudflareContext): void;
37
- declare function getCloudflareContext(): CloudflareContext;
38
- declare function clearCloudflareContext(): void;
39
- //#endregion
40
- export { type CloudflareContext, type VirtualSandboxOptions, cfSandboxToSessionEnv, clearCloudflareContext, defineCommand, getCloudflareContext, getVirtualSandbox, setCloudflareContext, store };
@@ -1,230 +0,0 @@
1
- import "../agent-BYG0nVbQ.mjs";
2
- import "../session-CiAMTsLZ.mjs";
3
- import { createSandboxSessionEnv } from "../sandbox.mjs";
4
- import { t as normalizeExecutor } from "../command-helpers-CxRhK1my.mjs";
5
- import { Workspace, WorkspaceFileSystem } from "@cloudflare/shell";
6
-
7
- //#region src/cloudflare/context.ts
8
- let currentContext = null;
9
- function setCloudflareContext(ctx) {
10
- currentContext = ctx;
11
- }
12
- function getCloudflareContext() {
13
- if (!currentContext) throw new Error("[flue:cloudflare] Not running in a Cloudflare context. This function can only be called inside a Cloudflare Worker or Durable Object.");
14
- return currentContext;
15
- }
16
- function clearCloudflareContext() {
17
- currentContext = null;
18
- }
19
-
20
- //#endregion
21
- //#region src/cloudflare/virtual-sandbox.ts
22
- /**
23
- * In-process just-bash sandbox for Cloudflare Workers (no container).
24
- * Without args: empty in-memory. With R2 bucket: persistent files via DO SQLite + R2.
25
- */
26
- function adaptStat(cfStat) {
27
- return {
28
- isFile: cfStat.type === "file",
29
- isDirectory: cfStat.type === "directory",
30
- isSymbolicLink: cfStat.type === "symlink",
31
- mode: cfStat.mode ?? (cfStat.type === "directory" ? 493 : 420),
32
- size: cfStat.size,
33
- mtime: cfStat.mtime
34
- };
35
- }
36
- function adaptToJustBash(cfFs) {
37
- return {
38
- readFile: (path, _opts) => cfFs.readFile(path),
39
- readFileBuffer: (path) => cfFs.readFileBytes(path),
40
- async writeFile(path, content, _opts) {
41
- if (typeof content === "string") await cfFs.writeFile(path, content);
42
- else await cfFs.writeFileBytes(path, content);
43
- },
44
- appendFile: (path, content, _opts) => cfFs.appendFile(path, content),
45
- exists: (path) => cfFs.exists(path),
46
- async stat(path) {
47
- return adaptStat(await cfFs.stat(path));
48
- },
49
- async lstat(path) {
50
- return adaptStat(await cfFs.lstat(path));
51
- },
52
- mkdir: (path, opts) => cfFs.mkdir(path, opts),
53
- readdir: (path) => cfFs.readdir(path),
54
- async readdirWithFileTypes(path) {
55
- return (await cfFs.readdirWithFileTypes(path)).map((e) => ({
56
- name: e.name,
57
- isFile: e.type === "file",
58
- isDirectory: e.type === "directory",
59
- isSymbolicLink: e.type === "symlink"
60
- }));
61
- },
62
- rm: (path, opts) => cfFs.rm(path, opts),
63
- cp: (src, dest, opts) => cfFs.cp(src, dest, opts),
64
- mv: (src, dest) => cfFs.mv(src, dest),
65
- resolvePath: (base, path) => cfFs.resolvePath(base, path),
66
- getAllPaths: () => [],
67
- async chmod(_path, _mode) {},
68
- symlink: (target, linkPath) => cfFs.symlink(target, linkPath),
69
- async link(existingPath, newPath) {
70
- const content = await cfFs.readFileBytes(existingPath);
71
- await cfFs.writeFileBytes(newPath, content);
72
- },
73
- readlink: (path) => cfFs.readlink(path),
74
- realpath: (path) => cfFs.realpath(path),
75
- async utimes(_path, _atime, _mtime) {}
76
- };
77
- }
78
- async function getVirtualSandbox(bucket, options) {
79
- if (bucket === void 0) {
80
- const { Bash, InMemoryFs } = await import(
81
- /* @vite-ignore */
82
- "just-bash"
83
- );
84
- return new Bash({
85
- fs: new InMemoryFs(),
86
- network: { dangerouslyAllowFullInternetAccess: true }
87
- });
88
- }
89
- const { storage } = getCloudflareContext();
90
- const prefix = options?.prefix ?? "default";
91
- const r2Adapter = adaptToJustBash(new WorkspaceFileSystem(new Workspace({
92
- sql: storage.sql,
93
- r2: bucket,
94
- name: () => prefix
95
- })));
96
- const { Bash, MountableFs, InMemoryFs } = await import(
97
- /* @vite-ignore */
98
- "just-bash"
99
- );
100
- const fs = new MountableFs({ base: new InMemoryFs() });
101
- fs.mount("/workspace", r2Adapter);
102
- return new Bash({
103
- fs,
104
- cwd: "/workspace",
105
- network: { dangerouslyAllowFullInternetAccess: true }
106
- });
107
- }
108
-
109
- //#endregion
110
- //#region src/cloudflare/define-command.ts
111
- /**
112
- * Cloudflare-specific `defineCommand`. Function form only — Workers cannot
113
- * spawn host processes, so there is no pass-through sugar. The user supplies
114
- * an executor (typically `fetch`-based or SDK-based) and benefits from
115
- * return-shape normalization plus automatic throw-catching.
116
- *
117
- * ```ts
118
- * const issues = defineCommand('issues', async (args) => {
119
- * const res = await fetch(`https://api.github.com/...`);
120
- * return { stdout: await res.text() };
121
- * });
122
- * ```
123
- */
124
- function defineCommand(name, execute) {
125
- return {
126
- name,
127
- execute: normalizeExecutor(execute)
128
- };
129
- }
130
-
131
- //#endregion
132
- //#region src/cloudflare/cf-sandbox.ts
133
- /** Wraps a @cloudflare/sandbox instance (from getSandbox()) into SessionEnv. */
134
- async function cfSandboxToSessionEnv(sandbox, cwd = "/workspace") {
135
- return createSandboxSessionEnv({
136
- async readFile(path) {
137
- return (await sandbox.readFile(path)).content;
138
- },
139
- async readFileBuffer(path) {
140
- const file = await sandbox.readFile(path, { encoding: "base64" });
141
- const binary = atob(file.content);
142
- const bytes = new Uint8Array(binary.length);
143
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
144
- return bytes;
145
- },
146
- async writeFile(path, content) {
147
- if (typeof content === "string") await sandbox.writeFile(path, content);
148
- else {
149
- let binary = "";
150
- for (let i = 0; i < content.length; i++) binary += String.fromCharCode(content[i]);
151
- const b64 = btoa(binary);
152
- await sandbox.writeFile(path, b64, { encoding: "base64" });
153
- }
154
- },
155
- async stat(path) {
156
- const result = await sandbox.exec(`stat -c '{"size":%s,"isDir":%F}' '${path.replace(/'/g, "'\\''")}'`);
157
- if (!result.success) throw new Error(`stat failed for ${path}: ${result.stderr}`);
158
- try {
159
- const raw = result.stdout.trim();
160
- const sizeMatch = raw.match(/"size":(\d+)/);
161
- const isDir = raw.includes("directory");
162
- return {
163
- isFile: !isDir,
164
- isDirectory: isDir,
165
- isSymbolicLink: false,
166
- size: sizeMatch ? parseInt(sizeMatch[1], 10) : 0,
167
- mtime: /* @__PURE__ */ new Date()
168
- };
169
- } catch {
170
- throw new Error(`Failed to parse stat output for ${path}: ${result.stdout}`);
171
- }
172
- },
173
- async readdir(path) {
174
- const result = await sandbox.exec(`ls -1 '${path.replace(/'/g, "'\\''")}'`);
175
- if (!result.success) throw new Error(`readdir failed for ${path}: ${result.stderr}`);
176
- return result.stdout.trim().split("\n").filter((s) => s.length > 0);
177
- },
178
- async exists(path) {
179
- return (await sandbox.exists(path)).exists;
180
- },
181
- async mkdir(path, opts) {
182
- await sandbox.mkdir(path, opts);
183
- },
184
- async rm(path, opts) {
185
- if (opts?.recursive || opts?.force) {
186
- const flags = [opts.recursive ? "-r" : "", opts.force ? "-f" : ""].filter(Boolean).join("");
187
- await sandbox.exec(`rm ${flags} '${path.replace(/'/g, "'\\''")}'`);
188
- } else await sandbox.deleteFile(path);
189
- },
190
- async exec(command, execOpts) {
191
- const result = await sandbox.exec(command, {
192
- cwd: execOpts?.cwd,
193
- env: execOpts?.env
194
- });
195
- return {
196
- stdout: result.stdout ?? "",
197
- stderr: result.stderr ?? "",
198
- exitCode: result.exitCode ?? (result.success ? 0 : 1)
199
- };
200
- }
201
- }, cwd);
202
- }
203
-
204
- //#endregion
205
- //#region src/cloudflare/session-store.ts
206
- function store() {
207
- return {
208
- async save(_id, data) {
209
- const { agentInstance } = getCloudflareContext();
210
- agentInstance.setState({
211
- ...agentInstance.state,
212
- sessionData: data
213
- });
214
- },
215
- async load(_id) {
216
- const { agentInstance } = getCloudflareContext();
217
- return agentInstance.state?.sessionData ?? null;
218
- },
219
- async delete(_id) {
220
- const { agentInstance } = getCloudflareContext();
221
- agentInstance.setState({
222
- ...agentInstance.state,
223
- sessionData: null
224
- });
225
- }
226
- };
227
- }
228
-
229
- //#endregion
230
- export { cfSandboxToSessionEnv, clearCloudflareContext, defineCommand, getCloudflareContext, getVirtualSandbox, setCloudflareContext, store };
@@ -1,21 +0,0 @@
1
- import { w as ShellResult } from "./types-BZPltYah.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 };
package/dist/index.d.mts DELETED
@@ -1,15 +0,0 @@
1
- import { C as ShellOptions, D as TaskOptions, E as SkillOptions, O as ToolDef, S as SessionStore, T as Skill, _ as Role, a as BuildOptions, b as SessionEnv, c as CommandDef, d as FlueContext, f as FlueEvent, g as PromptResponse, h as PromptOptions, i as BuildContext, l as CommandSupport, m as FlueSession, n as AgentInfo, o as BuildPlugin, p as FlueEventCallback, r as BashLike, s as Command, t as AgentConfig, u as FileStat, v as SandboxFactory, w as ShellResult, x as SessionInit, y as SessionData } from "./types-BZPltYah.mjs";
2
- import { AgentTool } from "@mariozechner/pi-agent-core";
3
-
4
- //#region src/build.d.ts
5
- /**
6
- * Build a workspace into a deployable artifact.
7
- * AGENTS.md and .agents/skills/ are NOT bundled — discovered at runtime from session cwd.
8
- */
9
- declare function build(options: BuildOptions): Promise<void>;
10
- //#endregion
11
- //#region src/agent.d.ts
12
- declare const BUILTIN_TOOL_NAMES: Set<string>;
13
- declare function createTools(env: SessionEnv): AgentTool<any>[];
14
- //#endregion
15
- export { type AgentConfig, type AgentInfo, BUILTIN_TOOL_NAMES, type BashLike, type BuildContext, type BuildOptions, type BuildPlugin, type Command, type CommandDef, type CommandSupport, type FileStat, type FlueContext, type FlueEvent, type FlueEventCallback, type FlueSession, type PromptOptions, type PromptResponse, type Role, type SandboxFactory, type SessionData, type SessionEnv, type SessionInit, type SessionStore, type ShellOptions, type ShellResult, type Skill, type SkillOptions, type TaskOptions, type ToolDef, build, createTools };