@flue/client 0.0.17 → 0.0.20

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/LICENSE ADDED
@@ -0,0 +1,200 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to the Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by the Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding any notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. Please also get an
186
+ information on the current year for the copyright.
187
+
188
+ Copyright [yyyy] [name of copyright owner]
189
+
190
+ Licensed under the Apache License, Version 2.0 (the "License");
191
+ you may not use this file except in compliance with the License.
192
+ You may obtain a copy of the License at
193
+
194
+ http://www.apache.org/licenses/LICENSE-2.0
195
+
196
+ Unless required by applicable law or agreed to in writing, software
197
+ distributed under the License is distributed on an "AS IS" BASIS,
198
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
199
+ implied. See the License for the specific language governing
200
+ permissions and limitations under the License.
package/dist/index.d.mts CHANGED
@@ -1,3 +1,4 @@
1
+ import { i as ProxyService, n as ProxyPolicy, r as ProxyPresetResult, t as PolicyRule } from "./types-Ch4cwdD8.mjs";
1
2
  import * as v from "valibot";
2
3
 
3
4
  //#region src/errors.d.ts
@@ -82,8 +83,8 @@ interface FlueOptions {
82
83
  branch?: string;
83
84
  /** Workflow arguments. */
84
85
  args?: Record<string, unknown>;
85
- /** Scoped secrets. */
86
- secrets?: Record<string, string>;
86
+ /** Proxy instructions to append to every skill/prompt call. */
87
+ proxyInstructions?: string[];
87
88
  /** Default model for skill/prompt invocations. */
88
89
  model?: {
89
90
  providerID: string;
@@ -132,9 +133,8 @@ declare class Flue {
132
133
  readonly branch: string;
133
134
  /** Workflow arguments passed by the runner. */
134
135
  readonly args: Record<string, unknown>;
135
- /** Scoped secrets passed by the runner. */
136
- readonly secrets: Record<string, string>;
137
136
  private readonly workdir;
137
+ private readonly proxyInstructions;
138
138
  private readonly model?;
139
139
  private readonly client;
140
140
  constructor(options: FlueOptions);
@@ -156,4 +156,4 @@ declare class Flue {
156
156
  close(): Promise<void>;
157
157
  }
158
158
  //#endregion
159
- export { Flue, type FlueEvent, type FlueOptions, type PromptOptions, type ShellOptions, type ShellResult, type SkillOptions, SkillOutputError, transformEvent };
159
+ export { Flue, type FlueEvent, type FlueOptions, type PolicyRule, type PromptOptions, type ProxyPolicy, type ProxyPresetResult, type ProxyService, type ShellOptions, type ShellResult, type SkillOptions, SkillOutputError, transformEvent };
package/dist/index.mjs CHANGED
@@ -199,25 +199,28 @@ function buildResultInstructions(schema) {
199
199
  ].join("\n");
200
200
  }
201
201
  /**
202
+ * Build a single string from proxy instructions to append to prompts.
203
+ */
204
+ function buildProxyInstructions(instructions) {
205
+ if (instructions.length === 0) return "";
206
+ return "\n\n" + instructions.join("\n");
207
+ }
208
+ /**
202
209
  * Build the prompt text for a skill invocation.
203
210
  *
204
211
  * If `name` looks like a file path (contains '/' or ends with '.md'), the
205
212
  * prompt instructs the agent to read and follow that file under
206
213
  * `.agents/skills/`. Otherwise, it instructs the agent to use the named
207
214
  * skill.
208
- *
209
- * @param name - A skill name or a file path relative to .agents/skills/.
210
- * @param args - Key-value arguments to include in the prompt.
211
- * @param schema - Optional Valibot schema for result extraction.
212
- * @returns The complete prompt string.
213
215
  */
214
- function buildSkillPrompt(name, args, schema) {
216
+ function buildSkillPrompt(name, args, schema, proxyInstructions) {
215
217
  const parts = [
216
218
  HEADLESS_PREAMBLE,
217
219
  "",
218
- isFilePath(name) ? `Read and use the .agents/skills/${name} skill.` : `Use the ${name} skill.`
220
+ isFilePath(name) ? `Read the file .agents/skills/${name} directly from disk (do not use the skill tool) and follow it as your skill instructions.` : `Use the ${name} skill.`
219
221
  ];
220
222
  if (args && Object.keys(args).length > 0) parts.push(`\nArguments:\n${JSON.stringify(args, null, 2)}`);
223
+ if (proxyInstructions && proxyInstructions.length > 0) parts.push(buildProxyInstructions(proxyInstructions));
221
224
  if (schema) parts.push(buildResultInstructions(schema));
222
225
  return parts.join("\n");
223
226
  }
@@ -235,10 +238,7 @@ async function runShell(command, options) {
235
238
  return new Promise((resolve) => {
236
239
  const child = exec(command, {
237
240
  cwd: options?.cwd,
238
- env: options?.env ? {
239
- ...process.env,
240
- ...options.env
241
- } : process.env,
241
+ env: options?.env ?? process.env,
242
242
  timeout: options?.timeout
243
243
  }, (error, stdout, stderr) => {
244
244
  const rawCode = error && typeof error.code === "number" ? error.code : 0;
@@ -384,9 +384,9 @@ async function runPrompt(client, workdir, label, prompt, options) {
384
384
  * Run a named skill: builds the skill prompt from the name + args + schema,
385
385
  * then delegates to runPrompt().
386
386
  */
387
- async function runSkill(client, workdir, name, options) {
387
+ async function runSkill(client, workdir, name, options, proxyInstructions) {
388
388
  const { args, result: schema, model } = options ?? {};
389
- const prompt = buildSkillPrompt(name, args, schema);
389
+ const prompt = buildSkillPrompt(name, args, schema, proxyInstructions);
390
390
  return runPrompt(client, workdir, `skill("${name}")`, prompt, {
391
391
  result: schema,
392
392
  model
@@ -483,15 +483,14 @@ var Flue = class {
483
483
  branch;
484
484
  /** Workflow arguments passed by the runner. */
485
485
  args;
486
- /** Scoped secrets passed by the runner. */
487
- secrets;
488
486
  workdir;
487
+ proxyInstructions;
489
488
  model;
490
489
  client;
491
490
  constructor(options) {
492
491
  this.branch = options.branch ?? "main";
493
492
  this.args = options.args ?? {};
494
- this.secrets = options.secrets ?? {};
493
+ this.proxyInstructions = options.proxyInstructions ?? [];
495
494
  this.workdir = options.workdir;
496
495
  this.model = options.model;
497
496
  this.client = createOpencodeClient({
@@ -508,7 +507,7 @@ var Flue = class {
508
507
  } : void 0,
509
508
  model: options?.model ?? this.model
510
509
  };
511
- return runSkill(this.client, this.workdir, name, mergedOptions);
510
+ return runSkill(this.client, this.workdir, name, mergedOptions, this.proxyInstructions);
512
511
  }
513
512
  async prompt(promptText, options) {
514
513
  const schema = options?.result;
@@ -517,6 +516,7 @@ var Flue = class {
517
516
  "",
518
517
  promptText
519
518
  ];
519
+ if (this.proxyInstructions.length > 0) parts.push(buildProxyInstructions(this.proxyInstructions));
520
520
  if (schema) parts.push(buildResultInstructions(schema));
521
521
  const fullPrompt = parts.join("\n");
522
522
  const label = `prompt("${promptText.length > 40 ? promptText.slice(0, 40) + "…" : promptText}")`;
@@ -0,0 +1,51 @@
1
+ import { i as ProxyService, n as ProxyPolicy, r as ProxyPresetResult, t as PolicyRule } from "../types-Ch4cwdD8.mjs";
2
+
3
+ //#region src/proxies/anthropic.d.ts
4
+ /**
5
+ * Anthropic model provider proxy preset.
6
+ *
7
+ * Proxies requests to api.anthropic.com with the API key injected.
8
+ * Reads ANTHROPIC_API_KEY from the environment by default.
9
+ * Strips all non-allowlisted headers for security.
10
+ */
11
+ declare function anthropic(opts?: {
12
+ apiKey?: string;
13
+ }): ProxyService;
14
+ //#endregion
15
+ //#region src/proxies/github.d.ts
16
+ /**
17
+ * GitHub proxy preset.
18
+ *
19
+ * Returns two `ProxyService` objects:
20
+ * - `github-api`: unix socket proxy for REST/GraphQL API (api.github.com),
21
+ * used by the `gh` CLI and `curl`.
22
+ * - `github-git`: TCP port proxy for git smart HTTP (github.com),
23
+ * used by `git clone`, `git fetch`, `git push`.
24
+ *
25
+ * Both share the same token and policy.
26
+ */
27
+ declare function github(opts: {
28
+ token: string;
29
+ policy?: string | ProxyPolicy;
30
+ }): ProxyService[];
31
+ /**
32
+ * Body validation helpers for GitHub API requests.
33
+ *
34
+ * These return validator functions suitable for `PolicyRule.body`.
35
+ */
36
+ declare const githubBody: {
37
+ /** Validate an issue creation body. */issue(opts: {
38
+ titleMatch?: RegExp;
39
+ requiredLabels?: string[];
40
+ }): (body: unknown) => boolean; /** Validate a comment body. */
41
+ comment(opts: {
42
+ maxLength?: number;
43
+ pattern?: RegExp;
44
+ }): (body: unknown) => boolean; /** Validate a GraphQL request — restrict to queries only, or specific operations. */
45
+ graphql(opts?: {
46
+ allowedOperations?: string[];
47
+ denyMutations?: boolean;
48
+ }): (body: unknown) => boolean;
49
+ };
50
+ //#endregion
51
+ export { type PolicyRule, type ProxyPolicy, type ProxyPresetResult, type ProxyService, anthropic, github, githubBody };
@@ -0,0 +1,155 @@
1
+ //#region src/proxies/anthropic.ts
2
+ /**
3
+ * Anthropic model provider proxy preset.
4
+ *
5
+ * Proxies requests to api.anthropic.com with the API key injected.
6
+ * Reads ANTHROPIC_API_KEY from the environment by default.
7
+ * Strips all non-allowlisted headers for security.
8
+ */
9
+ function anthropic(opts) {
10
+ const apiKey = opts?.apiKey || process.env.ANTHROPIC_API_KEY;
11
+ if (!apiKey) throw new Error("anthropic() proxy requires ANTHROPIC_API_KEY. Set it in your environment or pass { apiKey } explicitly.");
12
+ return {
13
+ name: "anthropic",
14
+ target: "https://api.anthropic.com",
15
+ transform: (req) => {
16
+ const safe = [
17
+ "content-type",
18
+ "content-length",
19
+ "accept",
20
+ "anthropic-version",
21
+ "anthropic-beta",
22
+ "user-agent"
23
+ ];
24
+ const filtered = {};
25
+ for (const key of safe) if (req.headers[key]) filtered[key] = req.headers[key];
26
+ filtered["x-api-key"] = apiKey;
27
+ return { headers: filtered };
28
+ },
29
+ isModelProvider: true,
30
+ providerConfig: {
31
+ providerKey: "anthropic",
32
+ options: { apiKey: "sk-dummy-value-real-key-injected-by-proxy" }
33
+ }
34
+ };
35
+ }
36
+
37
+ //#endregion
38
+ //#region src/proxies/github.ts
39
+ /**
40
+ * GitHub proxy preset.
41
+ *
42
+ * Returns two `ProxyService` objects:
43
+ * - `github-api`: unix socket proxy for REST/GraphQL API (api.github.com),
44
+ * used by the `gh` CLI and `curl`.
45
+ * - `github-git`: TCP port proxy for git smart HTTP (github.com),
46
+ * used by `git clone`, `git fetch`, `git push`.
47
+ *
48
+ * Both share the same token and policy.
49
+ */
50
+ function github(opts) {
51
+ const resolvedPolicy = resolveGitHubPolicy(opts.policy ?? "read-only");
52
+ const denyResponse = ({ method, path, reason }) => ({
53
+ status: 403,
54
+ headers: { "Content-Type": "application/json" },
55
+ body: JSON.stringify({
56
+ message: `Blocked by flue proxy policy: ${method} ${path} — ${reason}`,
57
+ documentation_url: "https://flue.dev/docs/proxy-policy"
58
+ })
59
+ });
60
+ return [{
61
+ name: "github-api",
62
+ target: "https://api.github.com",
63
+ headers: {
64
+ authorization: `token ${opts.token}`,
65
+ host: "api.github.com",
66
+ "user-agent": "flue-proxy"
67
+ },
68
+ policy: resolvedPolicy,
69
+ socket: true,
70
+ env: { GH_TOKEN: "proxy-placeholder" },
71
+ setup: ["gh config set http_unix_socket {{socketPath}} 2>/dev/null || true"],
72
+ instructions: ["The `gh` CLI is pre-configured with authentication.", "For GitHub API calls, prefer `gh api` over raw `curl`."].join(" "),
73
+ denyResponse
74
+ }, {
75
+ name: "github-git",
76
+ target: "https://github.com",
77
+ headers: {
78
+ authorization: `Basic ${Buffer.from(`x-access-token:${opts.token}`).toString("base64")}`,
79
+ "user-agent": "flue-proxy"
80
+ },
81
+ policy: resolvedPolicy,
82
+ setup: ["git config --global url.\"{{proxyUrl}}/\".insteadOf \"https://github.com/\"", "git config --global http.{{proxyUrl}}/.extraheader \"Authorization: Bearer proxy-placeholder\""],
83
+ denyResponse
84
+ }];
85
+ }
86
+ /**
87
+ * Resolve GitHub-specific policy level names to concrete ProxyPolicy rules.
88
+ *
89
+ * Levels:
90
+ * - 'read-only': GET/HEAD only (default)
91
+ * - 'read-only+clone': GET/HEAD + git smart HTTP fetch (clone/pull)
92
+ * - 'allow-all': everything allowed
93
+ */
94
+ function resolveGitHubPolicy(policy) {
95
+ if (typeof policy !== "string") return policy;
96
+ switch (policy) {
97
+ case "read-only": return { default: "deny-non-safe" };
98
+ case "read-only+clone": return {
99
+ default: "deny-non-safe",
100
+ allow: [{
101
+ method: "POST",
102
+ path: "/*/git-upload-pack"
103
+ }, {
104
+ method: "GET",
105
+ path: "/*/info/refs"
106
+ }]
107
+ };
108
+ case "allow-all": return { default: "allow-all" };
109
+ default: throw new Error(`Unknown github() policy level: '${policy}'`);
110
+ }
111
+ }
112
+ /**
113
+ * Body validation helpers for GitHub API requests.
114
+ *
115
+ * These return validator functions suitable for `PolicyRule.body`.
116
+ */
117
+ const githubBody = {
118
+ issue(opts) {
119
+ return (body) => {
120
+ const b = body;
121
+ if (opts.titleMatch && !opts.titleMatch.test(b?.title ?? "")) return false;
122
+ if (opts.requiredLabels) {
123
+ const labels = (b?.labels ?? []).map((l) => typeof l === "string" ? l : l?.name);
124
+ if (!opts.requiredLabels.every((r) => labels.includes(r))) return false;
125
+ }
126
+ return true;
127
+ };
128
+ },
129
+ comment(opts) {
130
+ return (body) => {
131
+ const b = body;
132
+ if (typeof b?.body !== "string") return false;
133
+ if (opts.maxLength && b.body.length > opts.maxLength) return false;
134
+ if (opts.pattern && !opts.pattern.test(b.body)) return false;
135
+ return true;
136
+ };
137
+ },
138
+ graphql(opts) {
139
+ return (body) => {
140
+ const b = body;
141
+ if (typeof b?.query !== "string") return false;
142
+ if (opts?.denyMutations !== false) {
143
+ const trimmed = b.query.replace(/\s+/g, " ").trim();
144
+ if (trimmed.startsWith("mutation") || /^\s*mutation\b/.test(trimmed)) return false;
145
+ }
146
+ if (opts?.allowedOperations) {
147
+ if (!b.operationName || !opts.allowedOperations.includes(b.operationName)) return false;
148
+ }
149
+ return true;
150
+ };
151
+ }
152
+ };
153
+
154
+ //#endregion
155
+ export { anthropic, github, githubBody };
@@ -0,0 +1,170 @@
1
+ //#region src/proxies/types.d.ts
2
+ interface ProxyService {
3
+ /**
4
+ * Human-readable name for logging and debugging.
5
+ * Examples: 'anthropic', 'github-api', 'github-git', 'internal-api'
6
+ */
7
+ name: string;
8
+ /**
9
+ * Upstream URL to forward requests to.
10
+ * Examples: 'https://api.anthropic.com', 'https://api.github.com'
11
+ */
12
+ target: string;
13
+ /**
14
+ * Headers to inject/override on every proxied request.
15
+ * Existing request headers with the same key are replaced.
16
+ * This is the simple path — for most proxies, this is all you need.
17
+ */
18
+ headers?: Record<string, string>;
19
+ /**
20
+ * Advanced: custom request transformation function.
21
+ * Receives the incoming request info, returns modified headers.
22
+ * Runs AFTER `headers` are applied (if both are set).
23
+ * Use this when you need to inspect the request before deciding
24
+ * what headers to set (e.g., different auth for different paths).
25
+ */
26
+ transform?: (req: {
27
+ method: string;
28
+ url: string;
29
+ headers: Record<string, string>;
30
+ }) => {
31
+ headers: Record<string, string>;
32
+ };
33
+ /**
34
+ * Shell commands to run inside the container during setup.
35
+ * Executed in order after the container starts, before any skills run.
36
+ *
37
+ * Template variables (resolved by the runner at startup):
38
+ * {{proxyUrl}} - HTTP URL reachable from inside the container
39
+ * e.g., http://host.docker.internal:4101
40
+ * {{socketPath}} - Path to the unix socket inside the container
41
+ * (only available when socket: true)
42
+ * {{port}} - TCP port number the proxy listens on
43
+ */
44
+ setup?: string[];
45
+ /**
46
+ * Environment variables to set in the container.
47
+ * Template variables ({{proxyUrl}}, {{socketPath}}, {{port}}) are resolved.
48
+ */
49
+ env?: Record<string, string>;
50
+ /**
51
+ * Instructions appended to every skill/prompt call.
52
+ * Used when the proxy can't be made fully transparent and the LLM
53
+ * needs guidance (e.g., "prefer `gh api` over raw `curl`").
54
+ */
55
+ instructions?: string;
56
+ /**
57
+ * Listen on a unix socket instead of a TCP port.
58
+ * The socket file is created on the host and bind-mounted into the container.
59
+ * Useful for tools like the GitHub CLI that support unix socket routing.
60
+ * Default: false (TCP port).
61
+ */
62
+ socket?: boolean;
63
+ /**
64
+ * Access control policy for this proxy.
65
+ *
66
+ * String shorthand: a named policy level defined by the preset.
67
+ * Object form: full control with default level + allow/deny rules.
68
+ *
69
+ * When a string is provided, it is equivalent to { default: theString }.
70
+ *
71
+ * If omitted, defaults to 'read-only' (GET/HEAD only).
72
+ * Each preset defines what its policy levels mean — see the preset
73
+ * documentation for available levels.
74
+ */
75
+ policy?: string | ProxyPolicy;
76
+ /**
77
+ * Marks this proxy as a model provider (Anthropic, Google, etc.).
78
+ * The CLI validates that at least one model provider proxy is present
79
+ * in sandbox mode. Model provider proxies also configure OpenCode's
80
+ * provider settings automatically.
81
+ */
82
+ isModelProvider?: boolean;
83
+ /**
84
+ * Provider-specific config for OpenCode integration.
85
+ * Only relevant when isModelProvider is true.
86
+ * Used to generate OPENCODE_CONFIG_CONTENT for the container.
87
+ */
88
+ providerConfig?: {
89
+ /** Provider key in OpenCode config (e.g., 'anthropic', 'google') */providerKey: string; /** Additional options merged into the provider config */
90
+ options?: Record<string, unknown>;
91
+ };
92
+ /**
93
+ * Generate the deny response body for this proxy's API format.
94
+ * Called when a request is blocked by policy. The preset knows whether
95
+ * the upstream API uses JSON, plain text, etc.
96
+ *
97
+ * If not provided, the proxy returns a generic JSON error body.
98
+ */
99
+ denyResponse?: (info: {
100
+ method: string;
101
+ path: string;
102
+ reason: string;
103
+ }) => {
104
+ status: number;
105
+ headers: Record<string, string>;
106
+ body: string;
107
+ };
108
+ }
109
+ interface ProxyPolicy {
110
+ /**
111
+ * The base policy level. Preset-defined string that maps to a set of rules.
112
+ * Common levels: 'read-only', 'allow-all', 'deny-all'.
113
+ * Presets may define additional levels (e.g., 'read-only+clone' for GitHub).
114
+ */
115
+ default: string;
116
+ /**
117
+ * Explicit allow rules. Evaluated after deny rules.
118
+ * A request matching an allow rule is permitted (subject to rate limits).
119
+ * If a request matches method + path but fails body validation, the rule
120
+ * does not match and evaluation continues to the next rule or default.
121
+ */
122
+ allow?: PolicyRule[];
123
+ /**
124
+ * Explicit deny rules. Evaluated first — a matching deny always wins.
125
+ * Use for hard restrictions that should never be overridden.
126
+ */
127
+ deny?: PolicyRule[];
128
+ }
129
+ interface PolicyRule {
130
+ /**
131
+ * HTTP method(s) to match. '*' matches any method.
132
+ * Examples: 'GET', 'POST', ['GET', 'HEAD'], '*'
133
+ */
134
+ method: string | string[];
135
+ /**
136
+ * URL path pattern to match. Uses glob-style wildcards:
137
+ * a single `*` matches exactly one path segment, and `**`
138
+ * matches any number of path segments.
139
+ */
140
+ path: string;
141
+ /**
142
+ * Maximum number of times this rule can be matched per workflow run.
143
+ * After the limit is hit, subsequent matching requests are denied.
144
+ * Omit for unlimited.
145
+ *
146
+ * The counter lives in-memory in the proxy process. Since each proxy
147
+ * process maps to one workflow run, counters reset naturally when the
148
+ * workflow ends.
149
+ */
150
+ limit?: number;
151
+ /**
152
+ * Validate the parsed JSON request body.
153
+ * Return true to allow, false to deny.
154
+ *
155
+ * Only called for requests with a JSON Content-Type.
156
+ * If the body isn't JSON or can't be parsed, the validator receives null.
157
+ *
158
+ * This is a plain JavaScript function — presets can provide helper
159
+ * functions for common patterns (see githubBody helpers).
160
+ */
161
+ body?: (parsedBody: unknown) => boolean;
162
+ }
163
+ /**
164
+ * Return type for preset functions. A preset may return a single
165
+ * ProxyService or an array (e.g., github() returns two proxies).
166
+ * The CLI auto-flattens with proxies.flat().
167
+ */
168
+ type ProxyPresetResult = ProxyService | ProxyService[];
169
+ //#endregion
170
+ export { ProxyService as i, ProxyPolicy as n, ProxyPresetResult as r, PolicyRule as t };
package/package.json CHANGED
@@ -1,29 +1,33 @@
1
1
  {
2
- "name": "@flue/client",
3
- "version": "0.0.17",
4
- "type": "module",
5
- "license": "Apache-2.0",
6
- "exports": {
7
- ".": {
8
- "types": "./dist/index.d.mts",
9
- "import": "./dist/index.mjs"
10
- }
11
- },
12
- "main": "./dist/index.mjs",
13
- "types": "./dist/index.d.mts",
14
- "files": [
15
- "dist"
16
- ],
17
- "scripts": {
18
- "build": "tsdown",
19
- "check:types": "tsc --noEmit"
20
- },
21
- "dependencies": {
22
- "@opencode-ai/sdk": "^1.1.56",
23
- "@valibot/to-json-schema": "^1.0.0",
24
- "valibot": "^1.0.0"
25
- },
26
- "devDependencies": {
27
- "tsdown": "^0.20.3"
28
- }
29
- }
2
+ "name": "@flue/client",
3
+ "version": "0.0.20",
4
+ "type": "module",
5
+ "license": "Apache-2.0",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.mts",
9
+ "import": "./dist/index.mjs"
10
+ },
11
+ "./proxies": {
12
+ "types": "./dist/proxies/index.d.mts",
13
+ "import": "./dist/proxies/index.mjs"
14
+ }
15
+ },
16
+ "main": "./dist/index.mjs",
17
+ "types": "./dist/index.d.mts",
18
+ "files": [
19
+ "dist"
20
+ ],
21
+ "dependencies": {
22
+ "@opencode-ai/sdk": "^1.1.56",
23
+ "@valibot/to-json-schema": "^1.0.0",
24
+ "valibot": "^1.0.0"
25
+ },
26
+ "devDependencies": {
27
+ "tsdown": "^0.20.3"
28
+ },
29
+ "scripts": {
30
+ "build": "tsdown",
31
+ "check:types": "tsc --noEmit"
32
+ }
33
+ }