@crewhaus/tool-image-generation 0.7.0 → 0.8.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,9 @@
1
+ CrewHaus Factory
2
+ Copyright 2026 Max Meier
3
+
4
+ This product includes software developed by Max Meier
5
+ (operating as StudioMax — https://studiomax.io) and contributors.
6
+
7
+ The CrewHaus name and logo are trademarks of Max Meier. See
8
+ https://github.com/crewhaus/factory/blob/main/TRADEMARK.md for the
9
+ use-of-marks policy.
package/README.md ADDED
@@ -0,0 +1,46 @@
1
+ # @crewhaus/tool-image-generation
2
+
3
+ `ImageGenerate`: an image from a text prompt, through a remote API.
4
+
5
+ ```yaml
6
+ tools:
7
+ - imageGenerate
8
+
9
+ tool_config:
10
+ imageGenerate:
11
+ provider: openai # openai (default when OPENAI_API_KEY is set) or mock
12
+ model: gpt-image-1 # optional; dall-e-3 by default
13
+ ```
14
+
15
+ The key is read from `OPENAI_API_KEY`. It is never written in the spec.
16
+
17
+ ## Where the key is sent
18
+
19
+ By default the key goes to `https://api.openai.com/v1` and nowhere else.
20
+
21
+ `openaiBaseUrl` points the tool at an OpenAI-compatible proxy instead (not
22
+ Azure OpenAI, whose paths and auth header differ). It is an origin and a path,
23
+ with no query or fragment. Because
24
+ the key goes wherever that URL points, a spec cannot set it alone — a spec can
25
+ come from a template or a pull request. The operator approves the endpoint by
26
+ setting `OPENAI_BASE_URL` to the same origin in the environment the harness
27
+ starts in:
28
+
29
+ ```yaml
30
+ tool_config:
31
+ imageGenerate:
32
+ openaiBaseUrl: https://llm-proxy.internal.example/v1
33
+ ```
34
+
35
+ ```sh
36
+ OPENAI_BASE_URL=https://llm-proxy.internal.example/v1 bun agent.ts
37
+ ```
38
+
39
+ - Anything but `https://api.openai.com` without that approval is refused at
40
+ boot and on every call, before a request is made.
41
+ - Plain `http` is refused, because the key would cross the network
42
+ unencrypted. The one exception is a proxy on loopback (`http://127.0.0.1`,
43
+ `http://localhost`), and only with the same approval.
44
+ - A URL with `user:password@` in it is refused.
45
+
46
+ `provider: mock` needs no key and sends nothing; use it for offline tests.
package/dist/index.d.ts CHANGED
@@ -17,6 +17,12 @@
17
17
  * include the URL in its reply; vision-capable models can see the
18
18
  * image inline on subsequent turns via WebFetch.
19
19
  *
20
+ * Bounds (0.7.1): the call ends when the turn's signal aborts (Ctrl-C,
21
+ * `turn_timeout_ms`, `deadline_ms`), when `tool_config.imageGenerate.timeoutMs`
22
+ * passes (default three minutes, request and body together), or when the
23
+ * body passes `maxResponseBytes` (default 32 MiB, refused rather than
24
+ * buffered); an error body is read only as far as its message shows.
25
+ *
20
26
  * Pillar 3: this tool is non-destructive (`destructive: false`) — it
21
27
  * doesn't write to the user's host filesystem; it issues a remote HTTP
22
28
  * request. Tool output is classified post-execution by runtime-core's
@@ -30,8 +36,26 @@ export type ImageGenerationConfig = {
30
36
  readonly provider?: ImageGenerationProvider;
31
37
  /** Provider-specific model id. Defaults: openai → "dall-e-3", replicate → "stability-ai/sdxl". */
32
38
  readonly model?: string;
33
- /** Override the OpenAI base URL (for proxies / Azure OpenAI). */
39
+ /**
40
+ * Override the OpenAI base URL, for an OpenAI-compatible proxy (not Azure
41
+ * OpenAI, whose path, `api-version` query and `api-key` header differ). OPENAI_API_KEY
42
+ * goes wherever this points, so anything but `https://api.openai.com` must
43
+ * also be approved by the operator outside the spec — see
44
+ * {@link resolveOpenAIBaseUrl}.
45
+ */
34
46
  readonly openaiBaseUrl?: string;
47
+ /**
48
+ * How long one generation may take, request and response together, in
49
+ * milliseconds. Default 180000 (three minutes): a high-quality image can
50
+ * take close to two. Past it the call fails with "timed out".
51
+ */
52
+ readonly timeoutMs?: number;
53
+ /**
54
+ * The most response body read, in bytes. Default 33554432 (32 MiB; a
55
+ * 1792x1024 PNG as base64 is a few MB). A larger body is refused, not
56
+ * buffered.
57
+ */
58
+ readonly maxResponseBytes?: number;
35
59
  /** Override fetch implementation for tests. */
36
60
  readonly fetch?: typeof globalThis.fetch;
37
61
  };
@@ -46,6 +70,20 @@ export declare class ImageGenerationError extends CrewhausError {
46
70
  * env-driven defaults work without re-registering.
47
71
  */
48
72
  export declare function registerImageGenerationConfig(config: ImageGenerationConfig): void;
73
+ /**
74
+ * Where OPENAI_API_KEY may be sent, and the only place it is sent.
75
+ *
76
+ * The base URL is `openaiBaseUrl` from the tool's config, else
77
+ * `https://api.openai.com/v1`. A spec can come from a template or a pull
78
+ * request, so it cannot choose where the key goes on its own:
79
+ *
80
+ * - any origin but `https://api.openai.com` needs the operator's approval:
81
+ * `OPENAI_BASE_URL` in the environment naming the same origin;
82
+ * - plain http is refused, except on loopback (a local proxy) with that
83
+ * same approval — the key would otherwise cross the network unencrypted;
84
+ * - a URL with `user:password@` in it is refused.
85
+ */
86
+ export declare function resolveOpenAIBaseUrl(cfg: ImageGenerationConfig, env: Readonly<Record<string, string | undefined>>): string;
49
87
  /**
50
88
  * 0.6.0 §4.4 — the config ONE call runs under: the serving candidate's
51
89
  * `tool_config.imageGenerate` block when its profile declares one
package/dist/index.js CHANGED
@@ -17,6 +17,12 @@
17
17
  * include the URL in its reply; vision-capable models can see the
18
18
  * image inline on subsequent turns via WebFetch.
19
19
  *
20
+ * Bounds (0.7.1): the call ends when the turn's signal aborts (Ctrl-C,
21
+ * `turn_timeout_ms`, `deadline_ms`), when `tool_config.imageGenerate.timeoutMs`
22
+ * passes (default three minutes, request and body together), or when the
23
+ * body passes `maxResponseBytes` (default 32 MiB, refused rather than
24
+ * buffered); an error body is read only as far as its message shows.
25
+ *
20
26
  * Pillar 3: this tool is non-destructive (`destructive: false`) — it
21
27
  * doesn't write to the user's host filesystem; it issues a remote HTTP
22
28
  * request. Tool output is classified post-execution by runtime-core's
@@ -24,7 +30,36 @@
24
30
  */
25
31
  import { CrewhausError } from "@crewhaus/errors";
26
32
  import { buildTool } from "@crewhaus/tool-builder";
33
+ import { readBodyBounded, withRawBody } from "@crewhaus/tool-fetch/body";
27
34
  import { z } from "zod";
35
+ const DEFAULT_TIMEOUT_MS = 180_000;
36
+ const DEFAULT_MAX_RESPONSE_BYTES = 32 * 1024 * 1024;
37
+ /** An error body is shown only up to 500 characters, so only this much is read. */
38
+ const ERROR_BODY_BYTES = 4096;
39
+ /**
40
+ * The longest `timeoutMs` a timer can hold: a delay past 2^31-1 ms (about
41
+ * 24.8 days) overflows, and the runtime fires it after 1 ms instead.
42
+ */
43
+ const MAX_TIMEOUT_MS = 2_147_483_647;
44
+ /**
45
+ * Read `timeoutMs` / `maxResponseBytes` from a config block: a positive whole
46
+ * number (a `timeoutMs` no longer than {@link MAX_TIMEOUT_MS}), else the
47
+ * default. Anything else is refused with the key named, so a typo never
48
+ * silently becomes "no limit" — nor, for a timeout too long for a timer, a
49
+ * call that gives up after 1 ms and reports it timed out.
50
+ */
51
+ function positiveLimit(cfg, key, fallback) {
52
+ const value = cfg[key];
53
+ if (value === undefined)
54
+ return fallback;
55
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
56
+ throw new ImageGenerationError(`tool_config.imageGenerate.${key} must be a positive whole number${key === "timeoutMs" ? " of milliseconds" : " of bytes"}. Remove it for the default (${fallback}).`);
57
+ }
58
+ if (key === "timeoutMs" && value > MAX_TIMEOUT_MS) {
59
+ throw new ImageGenerationError(`tool_config.imageGenerate.timeoutMs is ${value} ms, longer than a timer can wait (${MAX_TIMEOUT_MS} ms, about 24 days). Use a smaller value, or remove it for the default (${fallback}).`);
60
+ }
61
+ return value;
62
+ }
28
63
  const inputSchema = z.object({
29
64
  prompt: z
30
65
  .string()
@@ -54,8 +89,96 @@ let registeredConfig;
54
89
  * env-driven defaults work without re-registering.
55
90
  */
56
91
  export function registerImageGenerationConfig(config) {
92
+ if (config.fetch !== undefined && typeof config.fetch !== "function") {
93
+ throw new ImageGenerationError("tool_config.imageGenerate.fetch is not a setting a spec can write. Remove it.");
94
+ }
95
+ // Checked here as well as on every call, so a spec that points the key
96
+ // somewhere the operator did not approve fails at boot, where someone is
97
+ // looking, and not at the first image.
98
+ if (config.openaiBaseUrl !== undefined)
99
+ resolveOpenAIBaseUrl(config, processEnv());
100
+ positiveLimit(config, "timeoutMs", DEFAULT_TIMEOUT_MS);
101
+ positiveLimit(config, "maxResponseBytes", DEFAULT_MAX_RESPONSE_BYTES);
57
102
  registeredConfig = config;
58
103
  }
104
+ /** The environment, or nothing where there is no `process` (a Worker without Node compat). */
105
+ function processEnv() {
106
+ return typeof process === "undefined" ? {} : process.env;
107
+ }
108
+ const OPENAI_ORIGIN = "https://api.openai.com";
109
+ const OPENAI_DEFAULT_BASE_URL = `${OPENAI_ORIGIN}/v1`;
110
+ /**
111
+ * `text` without its trailing slashes. A loop, not `/\/+$/`, which rescans
112
+ * a run of slashes from every start and is quadratic in its length; a base
113
+ * URL comes from a spec, which may come from a template or a pull request.
114
+ */
115
+ function withoutTrailingSlashes(text) {
116
+ let end = text.length;
117
+ while (end > 0 && text[end - 1] === "/")
118
+ end--;
119
+ return text.slice(0, end);
120
+ }
121
+ function isLoopbackHost(host) {
122
+ const h = host.replace(/^\[/, "").replace(/\]$/, "").toLowerCase();
123
+ return h === "localhost" || h === "::1" || /^127(\.\d{1,3}){3}$/.test(h);
124
+ }
125
+ /**
126
+ * Where OPENAI_API_KEY may be sent, and the only place it is sent.
127
+ *
128
+ * The base URL is `openaiBaseUrl` from the tool's config, else
129
+ * `https://api.openai.com/v1`. A spec can come from a template or a pull
130
+ * request, so it cannot choose where the key goes on its own:
131
+ *
132
+ * - any origin but `https://api.openai.com` needs the operator's approval:
133
+ * `OPENAI_BASE_URL` in the environment naming the same origin;
134
+ * - plain http is refused, except on loopback (a local proxy) with that
135
+ * same approval — the key would otherwise cross the network unencrypted;
136
+ * - a URL with `user:password@` in it is refused.
137
+ */
138
+ export function resolveOpenAIBaseUrl(cfg, env) {
139
+ const operator = env["OPENAI_BASE_URL"];
140
+ const raw = cfg.openaiBaseUrl ?? OPENAI_DEFAULT_BASE_URL;
141
+ let url;
142
+ try {
143
+ url = new URL(raw);
144
+ }
145
+ catch {
146
+ // Not quoted: text that does not parse cannot be told apart from a
147
+ // credential in it (a query, a userinfo, a password holding "/").
148
+ throw new ImageGenerationError("tool_config.imageGenerate.openaiBaseUrl is not an absolute URL (it is not quoted here, since a URL can carry a credential). Write it as https://host/v1.");
149
+ }
150
+ if (url.username !== "" || url.password !== "") {
151
+ throw new ImageGenerationError(`the OpenAI base URL for ${url.protocol}//${url.host} carries user:password@. Remove it; the key is sent from OPENAI_API_KEY.`);
152
+ }
153
+ // `${base}/images/generations` is appended as text, so a query or fragment
154
+ // in the base would swallow the path (and a query can carry a credential):
155
+ // refused, and not echoed.
156
+ if (url.search !== "" || url.hash !== "") {
157
+ throw new ImageGenerationError(`the OpenAI base URL for ${url.protocol}//${url.host} has a query or fragment. Write it as https://host/v1, with nothing after the path.`);
158
+ }
159
+ let approved = false;
160
+ if (operator !== undefined && operator !== "") {
161
+ try {
162
+ approved = new URL(operator).origin === url.origin;
163
+ }
164
+ catch {
165
+ approved = false;
166
+ }
167
+ }
168
+ const approve = `set OPENAI_BASE_URL=${url.origin}${withoutTrailingSlashes(url.pathname)} in the environment the harness starts in`;
169
+ if (url.protocol === "http:") {
170
+ if (!isLoopbackHost(url.hostname) || !approved) {
171
+ throw new ImageGenerationError(`the OpenAI base URL ${url.origin} is plain http, which would send OPENAI_API_KEY unencrypted. Use https. A proxy on loopback is allowed when the operator approves it: ${approve}.`);
172
+ }
173
+ }
174
+ else if (url.protocol !== "https:") {
175
+ throw new ImageGenerationError(`the OpenAI base URL ${url.origin} is not https. Write it as https://host/v1.`);
176
+ }
177
+ else if (url.origin !== OPENAI_ORIGIN && !approved) {
178
+ throw new ImageGenerationError(`tool_config.imageGenerate.openaiBaseUrl would send OPENAI_API_KEY to ${url.origin}. A spec cannot choose where the key goes; to approve this endpoint, ${approve}.`);
179
+ }
180
+ return withoutTrailingSlashes(raw);
181
+ }
59
182
  /**
60
183
  * 0.6.0 §4.4 — the config ONE call runs under: the serving candidate's
61
184
  * `tool_config.imageGenerate` block when its profile declares one
@@ -71,7 +194,8 @@ export function resolveImageGenerationConfig(override) {
71
194
  }
72
195
  export const imageGenerate = buildTool({
73
196
  name: "ImageGenerate",
74
- description: "Generate an image from a text prompt via a remote API. Returns a URL or base64 data URI. Use for: visual concepts, mockups, illustrations, social posts. Don't use for: 'edit this existing photo' (different tool needed).",
197
+ operativeArgs: [],
198
+ description: "Generate an image from a text prompt via a remote API. Returns a URL or base64 data URI. With the OpenAI provider every call is a billed generation on the operator's account, so generate only what the task needs. Use for: visual concepts, mockups, illustrations, social posts. Don't use for: 'edit this existing photo' (different tool needed).",
75
199
  inputSchema,
76
200
  destructive: false,
77
201
  readOnly: false, // not idempotent — each call mints a new image
@@ -85,7 +209,7 @@ export const imageGenerate = buildTool({
85
209
  const provider = cfg.provider ?? defaultProvider(process.env);
86
210
  const responseFormat = input.responseFormat ?? "url";
87
211
  if (provider === "openai") {
88
- return await generateOpenAI(input, cfg, responseFormat);
212
+ return await generateOpenAI(input, cfg, responseFormat, ctx?.signal);
89
213
  }
90
214
  if (provider === "mock") {
91
215
  return await generateMock(input);
@@ -100,14 +224,126 @@ function defaultProvider(env) {
100
224
  return "mock";
101
225
  return "openai"; // surfaces a clear "missing OPENAI_API_KEY" error at call time
102
226
  }
103
- async function generateOpenAI(input, cfg, responseFormat) {
227
+ // ---------------------------------------------------------------------------
228
+ // Bounded request. This package ships in the cf-worker bundles, which cannot
229
+ // take @crewhaus/tool-safety (Bun-only), so the bound is written here with
230
+ // what workerd has too: AbortController, setTimeout and a stream reader.
231
+ // ---------------------------------------------------------------------------
232
+ const pinnedSignals = new WeakSet();
233
+ const noop = () => undefined;
234
+ /**
235
+ * Call `fn` once when `signal` aborts; returns the unsubscribe. Never leaves
236
+ * the caller's signal without a listener: on Bun, removing the last listener
237
+ * from an `AbortSignal.timeout()` signal cancels its timer for good (the rule
238
+ * tool-safety's `onAbort` follows), which would disarm the caller's deadline.
239
+ */
240
+ function onAbort(signal, fn) {
241
+ if (signal === undefined)
242
+ return noop;
243
+ if (!pinnedSignals.has(signal)) {
244
+ pinnedSignals.add(signal);
245
+ signal.addEventListener("abort", noop, { once: true });
246
+ }
247
+ signal.addEventListener("abort", fn, { once: true });
248
+ return () => signal.removeEventListener("abort", fn);
249
+ }
250
+ /** A promise that rejects with `signal.reason` once `signal` aborts (our own
251
+ * controller's signal, so its listener may come and go freely). */
252
+ function rejectOnAbort(signal) {
253
+ const aborted = new Promise((_resolve, reject) => {
254
+ const fail = () => reject(signal.reason);
255
+ if (signal.aborted)
256
+ fail();
257
+ else
258
+ signal.addEventListener("abort", fail, { once: true });
259
+ });
260
+ aborted.catch(noop);
261
+ return aborted;
262
+ }
263
+ /**
264
+ * Read at most `maxBytes` of a body, racing every read against `signal`.
265
+ * Returns the bytes and whether more was there; the stream is cancelled at
266
+ * the cap, so the rest is never buffered. A response with no body stream
267
+ * reads as empty.
268
+ */
269
+ async function readBodyCappedBytes(res, maxBytes, signal) {
270
+ const body = res.body;
271
+ if (body === null || body === undefined)
272
+ return { bytes: new Uint8Array(0), truncated: false };
273
+ const reader = body.getReader();
274
+ const aborted = rejectOnAbort(signal);
275
+ const chunks = [];
276
+ let total = 0;
277
+ let truncated = false;
278
+ try {
279
+ for (;;) {
280
+ const { done, value } = await Promise.race([reader.read(), aborted]);
281
+ if (done)
282
+ break;
283
+ if (total + value.byteLength > maxBytes) {
284
+ chunks.push(value.subarray(0, maxBytes - total));
285
+ total = maxBytes;
286
+ truncated = true;
287
+ break;
288
+ }
289
+ chunks.push(value);
290
+ total += value.byteLength;
291
+ }
292
+ }
293
+ finally {
294
+ // Stop the producer: past the cap, on an abort, or on a read error.
295
+ if (truncated || signal.aborted)
296
+ await reader.cancel().catch(noop);
297
+ }
298
+ const bytes = new Uint8Array(total);
299
+ let offset = 0;
300
+ for (const chunk of chunks) {
301
+ bytes.set(chunk, offset);
302
+ offset += chunk.byteLength;
303
+ }
304
+ return { bytes, truncated };
305
+ }
306
+ /** {@link readBodyCappedBytes}, as UTF-8 text. */
307
+ async function readBodyCapped(res, maxBytes, signal) {
308
+ const { bytes, truncated } = await readBodyCappedBytes(res, maxBytes, signal);
309
+ return { text: new TextDecoder().decode(bytes), truncated };
310
+ }
311
+ /**
312
+ * {@link readBodyCapped} over the RAW body, then decoded with its output
313
+ * bounded by the same cap (tool-fetch's `readBodyBounded`, which is safe in
314
+ * a cf-worker bundle). A body that decodes past the cap reads as truncated;
315
+ * one that cannot be decoded is refused without quoting it.
316
+ */
317
+ async function readDecoded(res, maxBytes, signal) {
318
+ const encoding = res.headers.get("content-encoding");
319
+ if (encoding === null)
320
+ return readBodyCapped(res, maxBytes, signal);
321
+ const raw = await readBodyCappedBytes(res, maxBytes, signal);
322
+ if (raw.truncated)
323
+ return { text: "", truncated: true };
324
+ const decoded = await readBodyBounded(new Response(raw.bytes, { headers: { "content-encoding": encoding } }), maxBytes);
325
+ if (decoded.ok)
326
+ return { text: new TextDecoder().decode(decoded.bytes), truncated: false };
327
+ if (decoded.code === "too-large")
328
+ return { text: "", truncated: true };
329
+ throw new ImageGenerationError(`OpenAI image-generation response ${decoded.reason}`);
330
+ }
331
+ async function generateOpenAI(input, cfg, responseFormat, callerSignal) {
104
332
  const apiKey = process.env["OPENAI_API_KEY"];
105
333
  if (!apiKey) {
106
334
  throw new ImageGenerationError("OPENAI_API_KEY is not set — required for provider=openai. Set the env var or switch to provider=mock for offline testing.");
107
335
  }
108
- const baseUrl = cfg.openaiBaseUrl ?? "https://api.openai.com/v1";
336
+ const baseUrl = resolveOpenAIBaseUrl(cfg, processEnv());
109
337
  const model = cfg.model ?? "dall-e-3";
338
+ // A spec block can only carry a string here; a per-call (model-pool
339
+ // candidate) block used to reach `fetchFn(...)` and crash with "is not a
340
+ // function". Refused like the boot block's.
341
+ if (cfg.fetch !== undefined && typeof cfg.fetch !== "function") {
342
+ throw new ImageGenerationError("tool_config.imageGenerate.fetch is not a setting a spec can write. Remove it.");
343
+ }
110
344
  const fetchFn = cfg.fetch ?? globalThis.fetch;
345
+ const timeoutMs = positiveLimit(cfg, "timeoutMs", DEFAULT_TIMEOUT_MS);
346
+ const maxResponseBytes = positiveLimit(cfg, "maxResponseBytes", DEFAULT_MAX_RESPONSE_BYTES);
111
347
  const body = JSON.stringify({
112
348
  model,
113
349
  prompt: input.prompt,
@@ -116,19 +352,66 @@ async function generateOpenAI(input, cfg, responseFormat) {
116
352
  response_format: responseFormat,
117
353
  ...(model === "dall-e-3" ? { style: input.style ?? "vivid" } : {}),
118
354
  });
119
- const res = await fetchFn(`${baseUrl}/images/generations`, {
120
- method: "POST",
121
- headers: {
122
- Authorization: `Bearer ${apiKey}`,
123
- "Content-Type": "application/json",
124
- },
125
- body,
126
- });
127
- if (!res.ok) {
128
- const text = await res.text().catch(() => "");
129
- throw new ImageGenerationError(`OpenAI image-generation request failed (${res.status} ${res.statusText}): ${text.slice(0, 500)}`);
355
+ // One deadline over the request and the body read, and the turn's own
356
+ // signal (Ctrl-C, turn_timeout_ms, deadline_ms) ends the call too.
357
+ const ctrl = new AbortController();
358
+ const timer = setTimeout(() => ctrl.abort(new ImageGenerationError(`OpenAI image-generation request timed out after ${timeoutMs} ms`)), timeoutMs);
359
+ const cancel = () => ctrl.abort(new ImageGenerationError("OpenAI image-generation request was cancelled"));
360
+ if (callerSignal?.aborted === true)
361
+ cancel();
362
+ const unsubscribe = onAbort(callerSignal, cancel);
363
+ let json;
364
+ try {
365
+ // Raced as well as signalled: a fetch that ignores its signal (or is
366
+ // handed one already aborted) still cannot hold the turn.
367
+ // The body is asked for RAW (Bun's `decompress: false`, via tool-fetch's
368
+ // edge-safe `withRawBody`): otherwise Bun inflates a gzip, deflate, br or
369
+ // zstd reply in native code before any reader sees a byte, so the
370
+ // maxResponseBytes cap bounded nothing (C093). `readDecoded` decodes it,
371
+ // under the cap. On workerd this is a no-op and the body is read as
372
+ // 0.7.0 read it.
373
+ const res = await Promise.race([
374
+ fetchFn(`${baseUrl}/images/generations`, withRawBody({
375
+ method: "POST",
376
+ headers: {
377
+ Authorization: `Bearer ${apiKey}`,
378
+ "Content-Type": "application/json",
379
+ "Accept-Encoding": "identity",
380
+ },
381
+ body,
382
+ signal: ctrl.signal,
383
+ })),
384
+ rejectOnAbort(ctrl.signal),
385
+ ]);
386
+ if (!res.ok) {
387
+ const { text } = await readDecoded(res, ERROR_BODY_BYTES, ctrl.signal).catch(() => ({
388
+ text: "",
389
+ }));
390
+ const shown = text.length > 500 ? `${text.slice(0, 500)}… (truncated)` : text;
391
+ throw new ImageGenerationError(`OpenAI image-generation request failed (${res.status} ${res.statusText}): ${shown}`);
392
+ }
393
+ const read = await readDecoded(res, maxResponseBytes, ctrl.signal);
394
+ if (read.truncated) {
395
+ throw new ImageGenerationError(`OpenAI image-generation response body exceeded ${maxResponseBytes} bytes (tool_config.imageGenerate.maxResponseBytes); nothing past the cap was read`);
396
+ }
397
+ try {
398
+ json = JSON.parse(read.text);
399
+ }
400
+ catch {
401
+ throw new ImageGenerationError(`OpenAI image-generation response was not JSON (${read.text.length} chars)`);
402
+ }
403
+ }
404
+ catch (err) {
405
+ // An abort surfaces as whatever the runtime throws; say which one it was.
406
+ if (ctrl.signal.aborted && ctrl.signal.reason instanceof ImageGenerationError) {
407
+ throw ctrl.signal.reason;
408
+ }
409
+ throw err;
410
+ }
411
+ finally {
412
+ clearTimeout(timer);
413
+ unsubscribe();
130
414
  }
131
- const json = (await res.json());
132
415
  const first = json.data?.[0];
133
416
  if (!first) {
134
417
  throw new ImageGenerationError("OpenAI response missing data[0] — unexpected format");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crewhaus/tool-image-generation",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "description": "M4.1 — image-generation tool (DALL-E 3, Replicate, future Flux/SD). Calls remote API; no host writes; non-destructive.",
6
6
  "main": "dist/index.js",
@@ -8,16 +8,18 @@
8
8
  "exports": {
9
9
  ".": {
10
10
  "types": "./dist/index.d.ts",
11
- "import": "./dist/index.js"
11
+ "import": "./dist/index.js",
12
+ "default": "./dist/index.js"
12
13
  }
13
14
  },
14
15
  "scripts": {
15
16
  "test": "bun test src"
16
17
  },
17
18
  "dependencies": {
18
- "@crewhaus/errors": "0.7.0",
19
- "@crewhaus/tool-builder": "0.7.0",
20
- "@crewhaus/tool-catalog": "0.7.0",
19
+ "@crewhaus/errors": "0.8.0",
20
+ "@crewhaus/tool-builder": "0.8.0",
21
+ "@crewhaus/tool-catalog": "0.8.0",
22
+ "@crewhaus/tool-fetch": "0.8.0",
21
23
  "zod": "^3.23.8"
22
24
  },
23
25
  "license": "Apache-2.0",
@@ -38,5 +40,8 @@
38
40
  "publishConfig": {
39
41
  "access": "public"
40
42
  },
41
- "files": ["dist", "README.md", "LICENSE", "NOTICE"]
43
+ "files": ["dist", "README.md", "LICENSE", "NOTICE"],
44
+ "engines": {
45
+ "bun": ">=1.3.14"
46
+ }
42
47
  }