dsh-draw 0.1.2 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/README.es.md +2 -1
- package/README.hi.md +2 -1
- package/README.md +4 -3
- package/README.pt.md +2 -1
- package/README.zh.md +2 -1
- package/cordis.patch.yml +5 -1
- package/lib/client.js +4 -2
- package/lib/client.js.map +1 -1
- package/lib/index.js +173 -9
- package/lib/types/client/present.d.ts +3 -1
- package/lib/types/client/present.d.ts.map +1 -1
- package/lib/types/client/present.js +4 -2
- package/lib/types/config.d.ts +6 -0
- package/lib/types/config.d.ts.map +1 -1
- package/lib/types/config.js +8 -0
- package/lib/types/index.d.ts +1 -0
- package/lib/types/index.d.ts.map +1 -1
- package/lib/types/index.js +1 -0
- package/lib/types/provider.d.ts +39 -0
- package/lib/types/provider.d.ts.map +1 -0
- package/lib/types/provider.js +192 -0
- package/lib/types/router.d.ts +1 -3
- package/lib/types/router.d.ts.map +1 -1
- package/lib/types/router.js +3 -7
- package/lib/types/version.d.ts +4 -3
- package/lib/types/version.d.ts.map +1 -1
- package/lib/types/version.js +4 -3
- package/package.json +28 -2
- package/src/client/present.ts +4 -2
- package/src/config.ts +15 -0
- package/src/index.ts +1 -0
- package/src/provider.ts +237 -0
- package/src/router.ts +4 -8
- package/src/version.ts +4 -3
package/lib/types/router.d.ts
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
import type { ResolvedConfig, ResolvedEngineConfig } from './config.js';
|
|
11
11
|
import { type EngineDeps, type ProducedImage } from './engine.js';
|
|
12
|
-
import {
|
|
12
|
+
import type { StandardImageRequest } from './translate.js';
|
|
13
13
|
/** One recorded attempt against one engine, success or failure. */
|
|
14
14
|
export interface AttemptView {
|
|
15
15
|
/** Engine id. */
|
|
@@ -131,8 +131,6 @@ export declare class EngineRouter {
|
|
|
131
131
|
private chainOrder;
|
|
132
132
|
/** Why an engine may not even be attempted: disabled, cooling down. */
|
|
133
133
|
private skipReason;
|
|
134
|
-
/** Translate the standard request against one engine (the pure translate step). */
|
|
135
|
-
private translate;
|
|
136
134
|
/** Record a success: reset consecutive failures and cooldown. */
|
|
137
135
|
private recordSuccess;
|
|
138
136
|
/** Record a failure: bump the counter, trip cooldown at the threshold, and build the attempt view. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../../src/router.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;AACvE,OAAO,
|
|
1
|
+
{"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../../src/router.ts"],"names":[],"mappings":"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"}
|
package/lib/types/router.js
CHANGED
|
@@ -7,9 +7,9 @@
|
|
|
7
7
|
*
|
|
8
8
|
* @module dsh-draw/router
|
|
9
9
|
*/
|
|
10
|
-
import {
|
|
10
|
+
import { EngineCallError } from './engine.js';
|
|
11
|
+
import { providerFor } from './provider.js';
|
|
11
12
|
import { sanitizeError, sanitizeText, sanitizeUrl } from './sanitize.js';
|
|
12
|
-
import { translateRequest } from './translate.js';
|
|
13
13
|
/**
|
|
14
14
|
* The engine chain with per-engine health and cooldown. All mutations are
|
|
15
15
|
* synchronous bookkeeping guarded by `generate`'s single-writer path (the
|
|
@@ -56,7 +56,7 @@ export class EngineRouter {
|
|
|
56
56
|
}
|
|
57
57
|
tried += 1;
|
|
58
58
|
try {
|
|
59
|
-
const images = await
|
|
59
|
+
const images = await providerFor(engine.provider).generate(engine, request, deps, signal);
|
|
60
60
|
this.recordSuccess(engine.id);
|
|
61
61
|
attempts.push({ engine: engine.id, code: 'ok' });
|
|
62
62
|
return {
|
|
@@ -172,10 +172,6 @@ export class EngineRouter {
|
|
|
172
172
|
}
|
|
173
173
|
return undefined;
|
|
174
174
|
}
|
|
175
|
-
/** Translate the standard request against one engine (the pure translate step). */
|
|
176
|
-
translate(engine, request) {
|
|
177
|
-
return translateRequest(engine, request);
|
|
178
|
-
}
|
|
179
175
|
/** Record a success: reset consecutive failures and cooldown. */
|
|
180
176
|
recordSuccess(engineId) {
|
|
181
177
|
const health = this.health.get(engineId);
|
package/lib/types/version.d.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The plugin version, hardcoded beside `package.json` so the release script
|
|
3
|
-
* bumps both and `tests/
|
|
4
|
-
* `draw/status` snapshot so the settings panel
|
|
3
|
+
* bumps both and the version tripwire in `tests/session-events.spec.ts` trips
|
|
4
|
+
* when they drift. Served in the `draw/status` snapshot so the settings panel
|
|
5
|
+
* shows which plugin build runs.
|
|
5
6
|
*
|
|
6
7
|
* @module dsh-draw/version
|
|
7
8
|
*/
|
|
8
9
|
/** Plugin version; must equal the `version` field in `package.json`. */
|
|
9
|
-
export declare const PLUGIN_VERSION = "0.1
|
|
10
|
+
export declare const PLUGIN_VERSION = "0.2.1";
|
|
10
11
|
//# sourceMappingURL=version.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,wEAAwE;AACxE,eAAO,MAAM,cAAc,UAAU,CAAA"}
|
package/lib/types/version.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The plugin version, hardcoded beside `package.json` so the release script
|
|
3
|
-
* bumps both and `tests/
|
|
4
|
-
* `draw/status` snapshot so the settings panel
|
|
3
|
+
* bumps both and the version tripwire in `tests/session-events.spec.ts` trips
|
|
4
|
+
* when they drift. Served in the `draw/status` snapshot so the settings panel
|
|
5
|
+
* shows which plugin build runs.
|
|
5
6
|
*
|
|
6
7
|
* @module dsh-draw/version
|
|
7
8
|
*/
|
|
8
9
|
/** Plugin version; must equal the `version` field in `package.json`. */
|
|
9
|
-
export const PLUGIN_VERSION = '0.1
|
|
10
|
+
export const PLUGIN_VERSION = '0.2.1';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-draw",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "Unified static-image generation router for DeepSeek Harness: one image_generate tool with standard parameters, config-driven OpenAI-compatible engine routing (OpenAI Images, Zhipu CogView, and any compatible endpoint) with health-aware fallback, durable workspace attachment results, per-session quota accounting, an in-conversation result card, and a Plugins settings panel that stores API keys as credential references.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -129,7 +129,33 @@
|
|
|
129
129
|
"@deepseek-ai/dsh-session": ">=0.1.0-rc.8 <0.2.0",
|
|
130
130
|
"@deepseek-ai/dsh-tools": ">=0.1.0-rc.8 <0.2.0",
|
|
131
131
|
"@deepseek-ai/dsh-typert-protocol": ">=0.1.0-rc.8 <0.2.0",
|
|
132
|
-
"@deepseek-ai/schemastery": "^3.18.0"
|
|
132
|
+
"@deepseek-ai/schemastery": "^3.18.0",
|
|
133
|
+
"@deepseek-ai/dsh-client-connection": ">=0.1.1-rc.2 <0.2.0",
|
|
134
|
+
"@deepseek-ai/dsh-client-locale": ">=0.1.1-rc.2 <0.2.0",
|
|
135
|
+
"@deepseek-ai/dsh-client-runtime": ">=0.1.1-rc.2 <0.2.0",
|
|
136
|
+
"@deepseek-ai/dsh-client-ui-settings": ">=0.1.1-rc.2 <0.2.0",
|
|
137
|
+
"@deepseek-ai/dsh-client-ui-slots": ">=0.1.1-rc.2 <0.2.0",
|
|
138
|
+
"@deepseek-ai/dsh-client-ui-tool": ">=0.1.1-rc.2 <0.2.0"
|
|
139
|
+
},
|
|
140
|
+
"peerDependenciesMeta": {
|
|
141
|
+
"@deepseek-ai/dsh-client-connection": {
|
|
142
|
+
"optional": true
|
|
143
|
+
},
|
|
144
|
+
"@deepseek-ai/dsh-client-locale": {
|
|
145
|
+
"optional": true
|
|
146
|
+
},
|
|
147
|
+
"@deepseek-ai/dsh-client-runtime": {
|
|
148
|
+
"optional": true
|
|
149
|
+
},
|
|
150
|
+
"@deepseek-ai/dsh-client-ui-settings": {
|
|
151
|
+
"optional": true
|
|
152
|
+
},
|
|
153
|
+
"@deepseek-ai/dsh-client-ui-slots": {
|
|
154
|
+
"optional": true
|
|
155
|
+
},
|
|
156
|
+
"@deepseek-ai/dsh-client-ui-tool": {
|
|
157
|
+
"optional": true
|
|
158
|
+
}
|
|
133
159
|
},
|
|
134
160
|
"dependencies": {
|
|
135
161
|
"tsdown": "^0.22.14",
|
package/src/client/present.ts
CHANGED
|
@@ -111,9 +111,11 @@ export interface PresentedDrawPanel {
|
|
|
111
111
|
* Project the panel snapshot onto the settings row model.
|
|
112
112
|
*
|
|
113
113
|
* @param snapshot - the `draw/status` wire snapshot.
|
|
114
|
+
* @param now - clock override for the cooldown flag (default {@link Date.now});
|
|
115
|
+
* injected so the presenter stays a pure function of its inputs.
|
|
114
116
|
* @returns the presented panel model.
|
|
115
117
|
*/
|
|
116
|
-
export function presentDrawPanel(snapshot: DrawStatusSnapshot): PresentedDrawPanel {
|
|
118
|
+
export function presentDrawPanel(snapshot: DrawStatusSnapshot, now: () => number = Date.now): PresentedDrawPanel {
|
|
117
119
|
return {
|
|
118
120
|
pluginVersion: snapshot.pluginVersion,
|
|
119
121
|
engines: snapshot.engines.map(engine => ({
|
|
@@ -127,7 +129,7 @@ export function presentDrawPanel(snapshot: DrawStatusSnapshot): PresentedDrawPan
|
|
|
127
129
|
...(engine.credential.source !== undefined ? { credentialSource: engine.credential.source } : {}),
|
|
128
130
|
credentialWritable: engine.credential.writable,
|
|
129
131
|
consecutiveFailures: engine.health.consecutiveFailures,
|
|
130
|
-
coolingDown: engine.health.cooldownUntil !== null && engine.health.cooldownUntil >
|
|
132
|
+
coolingDown: engine.health.cooldownUntil !== null && engine.health.cooldownUntil > now(),
|
|
131
133
|
lastError: engine.health.lastError,
|
|
132
134
|
})),
|
|
133
135
|
quota: { maxGenerationsPerSession: snapshot.quota.maxGenerationsPerSession, maxBytesPerSession: snapshot.quota.maxBytesPerSession },
|
package/src/config.ts
CHANGED
|
@@ -70,6 +70,9 @@ export interface EngineSizeMap {
|
|
|
70
70
|
/** Whether generated images arrive as base64 payloads or downloadable URLs. */
|
|
71
71
|
export type EngineResponseFormat = 'b64_json' | 'url'
|
|
72
72
|
|
|
73
|
+
/** The image-generation vocabularies a configured engine may declare (provider seam). */
|
|
74
|
+
export type EngineVocabulary = 'openai' | 'replicate' | 'fal'
|
|
75
|
+
|
|
73
76
|
/** One OpenAI-compatible image-generation endpoint the router may use. */
|
|
74
77
|
export interface EngineConfig {
|
|
75
78
|
/** Stable engine id used in tool args, results, and the settings panel. */
|
|
@@ -80,6 +83,8 @@ export interface EngineConfig {
|
|
|
80
83
|
model: string
|
|
81
84
|
/** Credential reference (environment-variable name) the API key resolves from; never a literal key. */
|
|
82
85
|
apiKeyRef: string
|
|
86
|
+
/** Which request/response vocabulary this engine speaks (default `openai`). */
|
|
87
|
+
provider?: EngineVocabulary
|
|
83
88
|
/** Whether the router may use this engine (default true). */
|
|
84
89
|
enabled?: boolean
|
|
85
90
|
/** Standard-size → concrete-size translation (default: the OpenAI sizes). */
|
|
@@ -123,6 +128,7 @@ export const DEFAULT_ENGINES: ReadonlyArray<Required<EngineConfig>> = Object.fre
|
|
|
123
128
|
baseUrl: 'https://api.openai.com/v1',
|
|
124
129
|
model: 'gpt-image-1',
|
|
125
130
|
apiKeyRef: 'OPENAI_API_KEY',
|
|
131
|
+
provider: 'openai',
|
|
126
132
|
enabled: true,
|
|
127
133
|
sizeMap: Object.freeze({ square: '1024x1024', landscape: '1536x1024', portrait: '1024x1536', auto: 'auto' }),
|
|
128
134
|
qualitySupported: true,
|
|
@@ -135,6 +141,7 @@ export const DEFAULT_ENGINES: ReadonlyArray<Required<EngineConfig>> = Object.fre
|
|
|
135
141
|
baseUrl: 'https://open.bigmodel.cn/api/paas/v4',
|
|
136
142
|
model: 'cogview-3-flash',
|
|
137
143
|
apiKeyRef: 'ZHIPU_API_KEY',
|
|
144
|
+
provider: 'openai',
|
|
138
145
|
enabled: true,
|
|
139
146
|
sizeMap: Object.freeze({ square: '1024x1024', landscape: '1344x768', portrait: '768x1344', auto: '1024x1024' }),
|
|
140
147
|
qualitySupported: false,
|
|
@@ -162,6 +169,8 @@ export interface ResolvedEngineConfig {
|
|
|
162
169
|
model: string
|
|
163
170
|
/** Credential reference the API key resolves from. */
|
|
164
171
|
apiKeyRef: string
|
|
172
|
+
/** Request/response vocabulary this engine speaks. */
|
|
173
|
+
provider: EngineVocabulary
|
|
165
174
|
/** Whether the router may use this engine. */
|
|
166
175
|
enabled: boolean
|
|
167
176
|
/** Standard-size → concrete-size translation. */
|
|
@@ -205,6 +214,7 @@ export const Config: z<Config> = z.object({
|
|
|
205
214
|
baseUrl: z.string().min(1).max(2048),
|
|
206
215
|
model: z.string().min(1).max(128),
|
|
207
216
|
apiKeyRef: z.string().min(1).max(128),
|
|
217
|
+
provider: z.union(['openai', 'replicate', 'fal'] as const),
|
|
208
218
|
enabled: z.boolean(),
|
|
209
219
|
sizeMap: z.object({
|
|
210
220
|
square: z.string().min(1).max(64),
|
|
@@ -269,6 +279,10 @@ export function resolveConfig(config: Config | undefined): ResolvedConfig {
|
|
|
269
279
|
if (model === '') throw new Error(`dsh-draw: engine "${id}" model must be a non-empty string of at most 128 characters`)
|
|
270
280
|
const apiKeyRef = typeof engine.apiKeyRef === 'string' && API_KEY_REF_PATTERN.test(engine.apiKeyRef) ? engine.apiKeyRef : ''
|
|
271
281
|
if (apiKeyRef === '') throw new Error(`dsh-draw: engine "${id}" apiKeyRef ${JSON.stringify(engine.apiKeyRef)} must be an environment-variable name`)
|
|
282
|
+
const provider = engine.provider ?? 'openai'
|
|
283
|
+
if (provider !== 'openai' && provider !== 'replicate' && provider !== 'fal') {
|
|
284
|
+
throw new Error(`dsh-draw: engine "${id}" provider must be one of "openai", "replicate", "fal", got ${JSON.stringify(provider)}`)
|
|
285
|
+
}
|
|
272
286
|
const sizeMap = engine.sizeMap === undefined ? DEFAULT_SIZE_MAP : engine.sizeMap
|
|
273
287
|
for (const key of ['square', 'landscape', 'portrait', 'auto'] as const) {
|
|
274
288
|
const value = sizeMap[key]
|
|
@@ -295,6 +309,7 @@ export function resolveConfig(config: Config | undefined): ResolvedConfig {
|
|
|
295
309
|
baseUrl: baseUrl.replace(/\/+$/u, ''),
|
|
296
310
|
model,
|
|
297
311
|
apiKeyRef,
|
|
312
|
+
provider,
|
|
298
313
|
enabled,
|
|
299
314
|
sizeMap: Object.freeze({ ...sizeMap }),
|
|
300
315
|
qualitySupported,
|
package/src/index.ts
CHANGED
|
@@ -40,6 +40,7 @@ export { imageGenerateTool } from './tool.ts'
|
|
|
40
40
|
export { DrawService } from './service.ts'
|
|
41
41
|
export { defaultHttpTransport, fusedSignal, type HttpTransport, type HttpRequest, type HttpResponse, HttpError } from './http.ts'
|
|
42
42
|
export { callEngine, EngineCallError, type EngineDeps, type ProducedImage } from './engine.ts'
|
|
43
|
+
export { providerFor, PROVIDERS, type EngineProvider, type EngineVocabulary } from './provider.ts'
|
|
43
44
|
export { translateRequest, normalizeRequest, type StandardImageRequest } from './translate.ts'
|
|
44
45
|
export { quotaState, checkQuotaGenerations, checkQuotaBytes, type QuotaLimits, type QuotaState } from './quota.ts'
|
|
45
46
|
export { sanitizeUrl, sanitizeText, sanitizeError, REDACTED } from './sanitize.ts'
|
package/src/provider.ts
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The engine-provider seam: one adapter per image-generation vocabulary. The
|
|
3
|
+
* OpenAI provider is the existing OpenAI-compatible `POST /images/generations`
|
|
4
|
+
* adapter; `replicate` and `fal` adapters speak those vendors' native request
|
|
5
|
+
* and response shapes (prediction polling and `fal.run` queue respectively).
|
|
6
|
+
* A configured engine declares its vocabulary (`provider`); the router
|
|
7
|
+
* dispatches through {@link providerFor}, so cooldown fallback, quota, and the
|
|
8
|
+
* audit path stay vocabulary-agnostic.
|
|
9
|
+
*
|
|
10
|
+
* @module dsh-draw/provider
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { ResolvedEngineConfig } from './config.ts'
|
|
14
|
+
import {
|
|
15
|
+
callEngine,
|
|
16
|
+
EngineCallError,
|
|
17
|
+
type EngineDeps,
|
|
18
|
+
type ProducedImage,
|
|
19
|
+
} from './engine.ts'
|
|
20
|
+
import type { StandardImageRequest } from './translate.ts'
|
|
21
|
+
import { translateRequest } from './translate.ts'
|
|
22
|
+
|
|
23
|
+
/** The image-generation vocabularies a configured engine may declare. */
|
|
24
|
+
export type EngineVocabulary = 'openai' | 'replicate' | 'fal'
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* One engine adapter: translates the standard tool request into a vendor
|
|
28
|
+
* request, calls it, and returns produced image bytes. A provider must never
|
|
29
|
+
* leak the credential — `deps.resolveCredential` resolves it per call.
|
|
30
|
+
*/
|
|
31
|
+
export interface EngineProvider {
|
|
32
|
+
/** Which vocabulary this adapter speaks. */
|
|
33
|
+
readonly vocabulary: EngineVocabulary
|
|
34
|
+
/**
|
|
35
|
+
* Generate images for one standardized request.
|
|
36
|
+
* @param engine - resolved engine configuration.
|
|
37
|
+
* @param request - normalized standard request.
|
|
38
|
+
* @param deps - transport and credential resolution.
|
|
39
|
+
* @param signal - caller cancellation.
|
|
40
|
+
* @returns the produced images.
|
|
41
|
+
*/
|
|
42
|
+
generate(engine: ResolvedEngineConfig, request: StandardImageRequest, deps: EngineDeps, signal?: AbortSignal): Promise<ProducedImage[]>
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The OpenAI-compatible adapter: delegates to the existing `/images/generations` path. */
|
|
46
|
+
const openaiProvider: EngineProvider = {
|
|
47
|
+
vocabulary: 'openai',
|
|
48
|
+
generate(engine, request, deps, signal) {
|
|
49
|
+
return callEngine(engine, translateRequest(engine, request), deps, signal)
|
|
50
|
+
},
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Replicate prediction polling interval (ms). */
|
|
54
|
+
const REPLICATE_POLL_INTERVAL_MS = 1_000
|
|
55
|
+
|
|
56
|
+
/** Maximum prediction polls before the call fails as a slow request. */
|
|
57
|
+
const REPLICATE_MAX_POLLS = 120
|
|
58
|
+
|
|
59
|
+
/** Parse one concrete `WIDTHxHEIGHT` size string into dimensions. */
|
|
60
|
+
function dimensionsOf(size: string): { width: number; height: number } | undefined {
|
|
61
|
+
const match = /^(\d{2,5})x(\d{2,5})$/u.exec(size)
|
|
62
|
+
if (match === null) return undefined
|
|
63
|
+
return { width: Number(match[1]), height: Number(match[2]) }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Resolve an engine credential, failing closed when it is unconfigured. */
|
|
67
|
+
async function requireCredential(engine: ResolvedEngineConfig, deps: EngineDeps): Promise<string> {
|
|
68
|
+
const credential = await deps.resolveCredential(engine.apiKeyRef)
|
|
69
|
+
if (credential === undefined) {
|
|
70
|
+
throw new EngineCallError('credential', 'unconfigured', `engine "${engine.id}" has no resolved credential reference ${engine.apiKeyRef}`)
|
|
71
|
+
}
|
|
72
|
+
return credential
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Parse a JSON response body, failing with a structured parse error. */
|
|
76
|
+
function parseJson(engine: ResolvedEngineConfig, body: Uint8Array): Record<string, unknown> {
|
|
77
|
+
let parsed: unknown
|
|
78
|
+
try {
|
|
79
|
+
parsed = JSON.parse(new TextDecoder().decode(body))
|
|
80
|
+
} catch (cause) {
|
|
81
|
+
throw new EngineCallError('parse', 'parse', `engine "${engine.id}" returned a non-JSON response`, { cause })
|
|
82
|
+
}
|
|
83
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
|
84
|
+
throw new EngineCallError('parse', 'parse', `engine "${engine.id}" returned a non-object payload`)
|
|
85
|
+
}
|
|
86
|
+
return parsed as Record<string, unknown>
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Download one image URL with an explicit authorization header value. */
|
|
90
|
+
async function downloadImage(
|
|
91
|
+
engine: ResolvedEngineConfig,
|
|
92
|
+
url: string,
|
|
93
|
+
authorization: string,
|
|
94
|
+
deps: EngineDeps,
|
|
95
|
+
signal?: AbortSignal,
|
|
96
|
+
): Promise<Uint8Array> {
|
|
97
|
+
const response = await deps.transport.request({
|
|
98
|
+
method: 'GET',
|
|
99
|
+
url,
|
|
100
|
+
headers: { authorization },
|
|
101
|
+
...(signal === undefined ? {} : { signal }),
|
|
102
|
+
})
|
|
103
|
+
if (response.status < 200 || response.status >= 300) {
|
|
104
|
+
throw new EngineCallError('request', 'http', `engine "${engine.id}" image download failed with HTTP ${response.status}`, { status: response.status })
|
|
105
|
+
}
|
|
106
|
+
return response.body
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Sleep without swallowing the caller's abort (checked by the caller's loop). */
|
|
110
|
+
function sleep(ms: number): Promise<void> {
|
|
111
|
+
return new Promise(resolve => setTimeout(resolve, ms))
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The Replicate adapter: create a prediction, poll to completion, then download its output URLs. */
|
|
115
|
+
const replicateProvider: EngineProvider = {
|
|
116
|
+
vocabulary: 'replicate',
|
|
117
|
+
async generate(engine, request, deps, signal) {
|
|
118
|
+
const credential = await requireCredential(engine, deps)
|
|
119
|
+
const dimensions = dimensionsOf(engine.sizeMap[request.size ?? 'square'])
|
|
120
|
+
const input: Record<string, unknown> = {
|
|
121
|
+
prompt: request.prompt,
|
|
122
|
+
num_outputs: request.count ?? 1,
|
|
123
|
+
...(dimensions === undefined ? {} : { width: dimensions.width, height: dimensions.height }),
|
|
124
|
+
}
|
|
125
|
+
const create = await deps.transport.request({
|
|
126
|
+
method: 'POST',
|
|
127
|
+
url: `${engine.baseUrl}/models/${engine.model}/predictions`,
|
|
128
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${credential}` },
|
|
129
|
+
body: new TextEncoder().encode(JSON.stringify({ input })),
|
|
130
|
+
...(signal === undefined ? {} : { signal }),
|
|
131
|
+
})
|
|
132
|
+
if (create.status === 401 || create.status === 403) {
|
|
133
|
+
throw new EngineCallError('request', 'auth', `engine "${engine.id}" rejected the credential (HTTP ${create.status})`, { status: create.status })
|
|
134
|
+
}
|
|
135
|
+
if (create.status < 200 || create.status >= 300) {
|
|
136
|
+
throw new EngineCallError('request', 'http', `engine "${engine.id}" failed with HTTP ${create.status}`, { status: create.status })
|
|
137
|
+
}
|
|
138
|
+
let prediction = parseJson(engine, create.body)
|
|
139
|
+
const id = typeof prediction['id'] === 'string' ? prediction['id'] : ''
|
|
140
|
+
const urls = typeof prediction['urls'] === 'object' && prediction['urls'] !== null
|
|
141
|
+
? prediction['urls'] as Record<string, unknown>
|
|
142
|
+
: {}
|
|
143
|
+
const pollUrl = typeof urls['get'] === 'string' && urls['get'] !== '' ? urls['get'] : `${engine.baseUrl}/predictions/${id}`
|
|
144
|
+
for (let poll = 0; poll < REPLICATE_MAX_POLLS; poll += 1) {
|
|
145
|
+
signal?.throwIfAborted()
|
|
146
|
+
const status = typeof prediction['status'] === 'string' ? prediction['status'] : ''
|
|
147
|
+
if (status === 'succeeded') break
|
|
148
|
+
if (status === 'failed' || status === 'canceled') {
|
|
149
|
+
throw new EngineCallError('request', 'http', `engine "${engine.id}" prediction ${status}`)
|
|
150
|
+
}
|
|
151
|
+
await sleep(REPLICATE_POLL_INTERVAL_MS)
|
|
152
|
+
const polled = await deps.transport.request({
|
|
153
|
+
method: 'GET',
|
|
154
|
+
url: pollUrl,
|
|
155
|
+
headers: { authorization: `Bearer ${credential}` },
|
|
156
|
+
...(signal === undefined ? {} : { signal }),
|
|
157
|
+
})
|
|
158
|
+
if (polled.status < 200 || polled.status >= 300) {
|
|
159
|
+
throw new EngineCallError('request', 'http', `engine "${engine.id}" prediction poll failed with HTTP ${polled.status}`, { status: polled.status })
|
|
160
|
+
}
|
|
161
|
+
prediction = parseJson(engine, polled.body)
|
|
162
|
+
}
|
|
163
|
+
if (prediction['status'] !== 'succeeded') {
|
|
164
|
+
throw new EngineCallError('request', 'http', `engine "${engine.id}" prediction did not finish within ${REPLICATE_MAX_POLLS} polls`)
|
|
165
|
+
}
|
|
166
|
+
const output = prediction['output']
|
|
167
|
+
if (!Array.isArray(output)) {
|
|
168
|
+
throw new EngineCallError('parse', 'parse', `engine "${engine.id}" prediction has no output array`)
|
|
169
|
+
}
|
|
170
|
+
const images: ProducedImage[] = []
|
|
171
|
+
for (const item of output) {
|
|
172
|
+
if (typeof item !== 'string' || item === '') {
|
|
173
|
+
throw new EngineCallError('parse', 'parse', `engine "${engine.id}" prediction returned a non-URL output entry`)
|
|
174
|
+
}
|
|
175
|
+
images.push({ data: await downloadImage(engine, item, `Bearer ${credential}`, deps, signal), mediaType: engine.imageMediaType })
|
|
176
|
+
}
|
|
177
|
+
if (images.length === 0) {
|
|
178
|
+
throw new EngineCallError('parse', 'parse', `engine "${engine.id}" prediction returned no images`)
|
|
179
|
+
}
|
|
180
|
+
return images
|
|
181
|
+
},
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** The fal.ai adapter: POST the `fal.run` queue endpoint and download the returned image URLs. */
|
|
185
|
+
const falProvider: EngineProvider = {
|
|
186
|
+
vocabulary: 'fal',
|
|
187
|
+
async generate(engine, request, deps, signal) {
|
|
188
|
+
const credential = await requireCredential(engine, deps)
|
|
189
|
+
const body: Record<string, unknown> = {
|
|
190
|
+
prompt: request.prompt,
|
|
191
|
+
image_size: engine.sizeMap[request.size ?? 'square'],
|
|
192
|
+
num_images: request.count ?? 1,
|
|
193
|
+
}
|
|
194
|
+
const response = await deps.transport.request({
|
|
195
|
+
method: 'POST',
|
|
196
|
+
url: `${engine.baseUrl}/${engine.model}`,
|
|
197
|
+
headers: { 'content-type': 'application/json', authorization: `Key ${credential}` },
|
|
198
|
+
body: new TextEncoder().encode(JSON.stringify(body)),
|
|
199
|
+
...(signal === undefined ? {} : { signal }),
|
|
200
|
+
})
|
|
201
|
+
if (response.status === 401 || response.status === 403) {
|
|
202
|
+
throw new EngineCallError('request', 'auth', `engine "${engine.id}" rejected the credential (HTTP ${response.status})`, { status: response.status })
|
|
203
|
+
}
|
|
204
|
+
if (response.status < 200 || response.status >= 300) {
|
|
205
|
+
throw new EngineCallError('request', 'http', `engine "${engine.id}" failed with HTTP ${response.status}`, { status: response.status })
|
|
206
|
+
}
|
|
207
|
+
const payload = parseJson(engine, response.body)
|
|
208
|
+
const entries = payload['images']
|
|
209
|
+
if (!Array.isArray(entries)) {
|
|
210
|
+
throw new EngineCallError('parse', 'parse', `engine "${engine.id}" response has no images array`)
|
|
211
|
+
}
|
|
212
|
+
const images: ProducedImage[] = []
|
|
213
|
+
for (const raw of entries) {
|
|
214
|
+
const url = typeof raw === 'object' && raw !== null ? (raw as Record<string, unknown>)['url'] : undefined
|
|
215
|
+
if (typeof url !== 'string' || url === '') {
|
|
216
|
+
throw new EngineCallError('parse', 'parse', `engine "${engine.id}" returned an image entry without a URL`)
|
|
217
|
+
}
|
|
218
|
+
images.push({ data: await downloadImage(engine, url, `Key ${credential}`, deps, signal), mediaType: engine.imageMediaType })
|
|
219
|
+
}
|
|
220
|
+
if (images.length === 0) {
|
|
221
|
+
throw new EngineCallError('parse', 'parse', `engine "${engine.id}" returned no images`)
|
|
222
|
+
}
|
|
223
|
+
return images
|
|
224
|
+
},
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** The provider registry, keyed by vocabulary. */
|
|
228
|
+
export const PROVIDERS: Readonly<Record<EngineVocabulary, EngineProvider>> = Object.freeze({
|
|
229
|
+
openai: openaiProvider,
|
|
230
|
+
replicate: replicateProvider,
|
|
231
|
+
fal: falProvider,
|
|
232
|
+
})
|
|
233
|
+
|
|
234
|
+
/** Resolve the provider for one vocabulary (always present — the config gate restricts the value). */
|
|
235
|
+
export function providerFor(vocabulary: EngineVocabulary): EngineProvider {
|
|
236
|
+
return PROVIDERS[vocabulary]
|
|
237
|
+
}
|
package/src/router.ts
CHANGED
|
@@ -9,9 +9,10 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import type { ResolvedConfig, ResolvedEngineConfig } from './config.ts'
|
|
12
|
-
import {
|
|
12
|
+
import { EngineCallError, type EngineDeps, type ProducedImage } from './engine.ts'
|
|
13
|
+
import { providerFor } from './provider.ts'
|
|
13
14
|
import { sanitizeError, sanitizeText, sanitizeUrl } from './sanitize.ts'
|
|
14
|
-
import {
|
|
15
|
+
import type { StandardImageRequest } from './translate.ts'
|
|
15
16
|
|
|
16
17
|
/** One recorded attempt against one engine, success or failure. */
|
|
17
18
|
export interface AttemptView {
|
|
@@ -156,7 +157,7 @@ export class EngineRouter {
|
|
|
156
157
|
}
|
|
157
158
|
tried += 1
|
|
158
159
|
try {
|
|
159
|
-
const images = await
|
|
160
|
+
const images = await providerFor(engine.provider).generate(engine, request, deps, signal)
|
|
160
161
|
this.recordSuccess(engine.id)
|
|
161
162
|
attempts.push({ engine: engine.id, code: 'ok' })
|
|
162
163
|
return {
|
|
@@ -273,11 +274,6 @@ export class EngineRouter {
|
|
|
273
274
|
return undefined
|
|
274
275
|
}
|
|
275
276
|
|
|
276
|
-
/** Translate the standard request against one engine (the pure translate step). */
|
|
277
|
-
private translate(engine: ResolvedEngineConfig, request: StandardImageRequest) {
|
|
278
|
-
return translateRequest(engine, request)
|
|
279
|
-
}
|
|
280
|
-
|
|
281
277
|
/** Record a success: reset consecutive failures and cooldown. */
|
|
282
278
|
private recordSuccess(engineId: string): void {
|
|
283
279
|
const health = this.health.get(engineId)
|
package/src/version.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The plugin version, hardcoded beside `package.json` so the release script
|
|
3
|
-
* bumps both and `tests/
|
|
4
|
-
* `draw/status` snapshot so the settings panel
|
|
3
|
+
* bumps both and the version tripwire in `tests/session-events.spec.ts` trips
|
|
4
|
+
* when they drift. Served in the `draw/status` snapshot so the settings panel
|
|
5
|
+
* shows which plugin build runs.
|
|
5
6
|
*
|
|
6
7
|
* @module dsh-draw/version
|
|
7
8
|
*/
|
|
8
9
|
|
|
9
10
|
/** Plugin version; must equal the `version` field in `package.json`. */
|
|
10
|
-
export const PLUGIN_VERSION = '0.1
|
|
11
|
+
export const PLUGIN_VERSION = '0.2.1'
|