dsh-mo-image 0.7.0 → 1.0.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.
@@ -0,0 +1,291 @@
1
+ import { resolveHttpUrl } from './adapter-kit.js';
2
+ import { applyFields } from './field-templates.js';
3
+ import { DEFAULT_EMPTY_MESSAGE, outputProfile, outputProfiles } from './output-profiles.js';
4
+
5
+ const MIB = 1024 * 1024;
6
+ const METHODS = ['GET', 'POST', 'PUT', 'PATCH'];
7
+ const TRANSPORTS = ['json', 'multipart', 'form', 'query'];
8
+ const IMAGE_FIELDS = new Set(['prompt', 'negative', 'model', 'n', 'image', 'quality', 'size', 'width', 'height', 'aspect', 'tier']);
9
+ const NON_DATA_KEYS = new Set(['__proto__', 'prototype', 'constructor']);
10
+ const ROUTE_TASK_FIELDS = {
11
+ statusPath: ['status', 'state'],
12
+ success: ['succeeded', 'success', 'completed', 'done', 'ready'],
13
+ failure: ['failed', 'error', 'canceled', 'cancelled'],
14
+ resultPath: ['output', 'result', 'images', 'url']
15
+ };
16
+
17
+ const OUTPUT_PRESETS = {
18
+ openai: {
19
+ kind: 'json',
20
+ pick: [{ path: 'data.0.b64_json', as: 'base64' }, { path: 'data.0.url', as: 'url' }]
21
+ },
22
+ binary: { kind: 'binary' },
23
+ 'image-url': { kind: 'json', pick: [{ path: 'image_url', as: 'url' }, { path: 'url', as: 'url' }] },
24
+ 'image-base64': { kind: 'json', pick: [{ path: 'image', as: 'base64' }, { path: 'base64', as: 'base64' }] },
25
+ 'task-location': {
26
+ kind: 'task', pollUrlFrom: 'location', ...ROUTE_TASK_FIELDS
27
+ },
28
+ 'task-json': {
29
+ kind: 'task', idPath: ['task_id', 'job_id', 'id'], path: '/tasks/{taskId}',
30
+ ...ROUTE_TASK_FIELDS
31
+ }
32
+ };
33
+
34
+ export function outputPresetManifest() {
35
+ return ['auto', ...Object.keys(OUTPUT_PRESETS)];
36
+ }
37
+
38
+ function plainObject(value) {
39
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
40
+ && [null, Object.prototype].includes(Object.getPrototypeOf(value));
41
+ }
42
+
43
+ function knownKeys(raw, keys, label) {
44
+ if (!plainObject(raw)) throw new Error(label + ' 必须是对象');
45
+ for (const key of Object.keys(raw)) {
46
+ if (!keys.includes(key)) throw new Error(label + ' 不支持字段 ' + key);
47
+ }
48
+ }
49
+
50
+ function cleanData(value, depth = 0) {
51
+ if (depth > 16) throw new Error('操作配置最多嵌套 16 层');
52
+ if (Array.isArray(value)) return value.map((item) => cleanData(item, depth + 1));
53
+ if (!plainObject(value)) {
54
+ if (value !== null && !['string', 'number', 'boolean'].includes(typeof value)) {
55
+ throw new Error('操作配置只接受 JSON 数据');
56
+ }
57
+ return value;
58
+ }
59
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => {
60
+ if (NON_DATA_KEYS.has(key)) throw new Error('操作配置包含无效属性 ' + key);
61
+ return [key, cleanData(item, depth + 1)];
62
+ }));
63
+ }
64
+
65
+ function bound(value, from, to, name) {
66
+ if (!Number.isInteger(value) || value < from || value > to) {
67
+ throw new Error(name + ' 必须是 ' + from + ' 到 ' + to + ' 之间的整数');
68
+ }
69
+ }
70
+
71
+ function configuredOutput(raw) {
72
+ const source = typeof raw === 'string' && Object.hasOwn(OUTPUT_PRESETS, raw) ? OUTPUT_PRESETS[raw] : raw;
73
+ if (!plainObject(source)) throw new Error('请选择有效的返回格式预设或填写输出描述符');
74
+ const profile = { maxBytes: 32 * MIB, emptyMessage: DEFAULT_EMPTY_MESSAGE, ...source };
75
+ if (profile.kind === 'task') {
76
+ if (profile.backoff === undefined && profile.intervalMs === undefined) profile.intervalMs = 2000;
77
+ if (profile.failure === undefined) profile.failure = [];
78
+ if (profile.pollOutput === 'binary' && profile.success === undefined) profile.success = [];
79
+ for (const [name, value] of [
80
+ ['intervalMs', profile.intervalMs], ['backoff.startMs', profile.backoff?.startMs], ['backoff.maxMs', profile.backoff?.maxMs],
81
+ ['timeoutMs', profile.timeoutMs]
82
+ ]) {
83
+ if (value !== undefined) bound(value, 250, 340000, name);
84
+ }
85
+ }
86
+ bound(profile.maxBytes, 1, 64 * MIB, 'maxBytes');
87
+ if (profile.via) bound(profile.via.maxBytes, 1, 64 * MIB, 'via.maxBytes');
88
+ for (const pick of [...(Array.isArray(profile.pick) ? profile.pick : []), ...(Array.isArray(profile.from) ? profile.from : [])]) {
89
+ if (pick?.text !== undefined) throw new Error('自定义输出请使用字段路径。文本正则由内置预设提供');
90
+ }
91
+ return outputProfile(profile, '自定义返回格式');
92
+ }
93
+
94
+ export function resolveConfiguredOutput(raw, fallback) {
95
+ if (raw === undefined || raw === 'auto') return fallback;
96
+ if (!Array.isArray(raw)) return configuredOutput(raw);
97
+ if (raw.length > 8) throw new Error('最多配置 8 个返回格式候选');
98
+ return outputProfiles(raw.map(configuredOutput), '自定义返回格式');
99
+ }
100
+
101
+ export function operationOutputOf(raw, fallback) {
102
+ return parsedOutput(raw) || fallback;
103
+ }
104
+
105
+ function staticHeaders(raw) {
106
+ if (!plainObject(raw)) throw new Error('headers 必须是对象');
107
+ const entries = Object.entries(raw);
108
+ if (entries.length > 16) throw new Error('每项操作最多配置 16 个请求头');
109
+ for (const [name, value] of entries) {
110
+ if (!/^[A-Za-z0-9-]{1,64}$/.test(name)
111
+ || /^(?:authorization|proxy-|cookie|host|connection|content-length|transfer-encoding|content-type)|(?:token|secret|api-?key)/i.test(name)
112
+ || typeof value !== 'string' || value.length > 1024 || /[\x00-\x1F\x7F]/.test(value)) {
113
+ throw new Error('无效的操作请求头 ' + name + '。凭据请在鉴权方式中设置');
114
+ }
115
+ }
116
+ return raw;
117
+ }
118
+
119
+ function originsOf(raw, label) {
120
+ if (!Array.isArray(raw) || raw.length > 8) throw new Error(label + ' 最多接受 8 个 HTTP(S) 源');
121
+ return [...new Set(raw.map((entry) => {
122
+ const url = resolveHttpUrl(entry);
123
+ if (!url || url !== new URL(url).origin + '/') throw new Error(label + ' 必须使用完整的 HTTP(S) 源');
124
+ return new URL(url).origin;
125
+ }))];
126
+ }
127
+
128
+ function modelListOutput(raw) {
129
+ knownKeys(raw, ['path', 'idPath', 'namePath'], '模型列表返回格式');
130
+ for (const [key, value] of Object.entries(raw)) {
131
+ if (typeof value !== 'string' || value.length > 256 || (key === 'namePath' && !value.trim())) {
132
+ throw new Error('模型列表字段路径无效');
133
+ }
134
+ }
135
+ return raw;
136
+ }
137
+
138
+ function validateFields(fields) {
139
+ if (!plainObject(fields)) throw new Error('fields 必须是对象');
140
+ for (const [name, spec] of Object.entries(fields)) {
141
+ if (!IMAGE_FIELDS.has(name)) throw new Error('未知的输入字段 ' + name);
142
+ if (spec !== null && spec !== false && !plainObject(spec)) throw new Error(name + ' 需要字段映射或 null');
143
+ }
144
+ applyFields({}, fields, {});
145
+ }
146
+
147
+ /** Validate interactions after provider and model settings have been merged. */
148
+ export function validateOperationTransport(kind, operation, transport) {
149
+ if (operation.method === 'GET' && transport !== 'query') throw new Error('GET 操作必须使用 query 传输');
150
+ for (const [name, spec] of Object.entries(operation.fields || {})) {
151
+ if (!spec) continue;
152
+ if (spec.multipart && (transport !== 'multipart' || (name === 'image' && kind !== 'edit'))) {
153
+ throw new Error(name + ' 的 multipart 映射与操作的传输方式不符');
154
+ }
155
+ if (name === 'image' && (kind !== 'edit' || (transport === 'multipart' && !spec.multipart)
156
+ || (!spec.multipart && !spec.as))) {
157
+ throw new Error('参考图字段映射与编辑操作的传输方式不符');
158
+ }
159
+ }
160
+ }
161
+
162
+ /** Versioned data shared by saved providers, model overrides, and unsaved connection tests. */
163
+ export function normalizeOperations(raw, modelOnly = false) {
164
+ if (raw === undefined || raw === null) return undefined;
165
+ const label = '操作配置';
166
+ if (JSON.stringify(raw).length > 64 * 1024) throw new Error(label + ' 超过大小限制');
167
+ const config = cleanData(raw);
168
+ knownKeys(config, modelOnly ? ['version', 'generate', 'edit'] : ['version', 'generate', 'edit', 'models'], label);
169
+ if (config.version !== undefined && config.version !== 1) throw new Error('暂不支持此操作配置版本');
170
+ for (const kind of ['generate', 'edit', 'models']) {
171
+ const operation = config[kind];
172
+ if (operation === undefined) continue;
173
+ const models = kind === 'models';
174
+ knownKeys(operation, models
175
+ ? ['path', 'method', 'body', 'headers', 'output']
176
+ : ['path', 'method', 'transport', 'input', 'body', 'fields', 'headers', 'output', 'pollOrigins', 'resultOrigins',
177
+ 'pollHeaders', 'pollNotFoundPending', ...(kind === 'edit' ? ['maxImages', 'imageTypes'] : [])], kind);
178
+ if (operation.path !== undefined) {
179
+ if (typeof operation.path !== 'string' || operation.path.length > 2048) throw new Error(kind + ' 的 path 无效');
180
+ operation.path = operation.path.trim();
181
+ if (/^\/\//.test(operation.path) || /^(?!https?:)[a-z][a-z\d+.-]*:/i.test(operation.path)
182
+ || /^https?:/i.test(operation.path) && !resolveHttpUrl(operation.path)) {
183
+ throw new Error(kind + ' 的 path 需要 HTTP(S) 地址或相对路径');
184
+ }
185
+ }
186
+ if (operation.method !== undefined && !METHODS.includes(operation.method)) throw new Error(kind + ' 的 HTTP 方法无效');
187
+ if (operation.transport !== undefined && !TRANSPORTS.includes(operation.transport)) throw new Error(kind + ' 的传输方式无效');
188
+ if (operation.input !== undefined && !['inherit', 'explicit'].includes(operation.input)) throw new Error(kind + ' 的 input 无效');
189
+ if (operation.maxImages !== undefined
190
+ && (!Number.isInteger(operation.maxImages) || operation.maxImages < 1 || operation.maxImages > 16)) {
191
+ throw new Error('edit.maxImages 需要 1–16 的整数');
192
+ }
193
+ if (operation.imageTypes !== undefined) {
194
+ const types = operation.imageTypes;
195
+ if (!Array.isArray(types) || !types.length || types.length > 16
196
+ || types.some((type) => typeof type !== 'string' || !/^image\/[a-z0-9.+-]+$/.test(type))) {
197
+ throw new Error('edit.imageTypes 需要填写支持的图片 MIME 类型');
198
+ }
199
+ }
200
+ if (operation.fields !== undefined) validateFields(operation.fields);
201
+ if (operation.headers !== undefined) operation.headers = staticHeaders(operation.headers);
202
+ if (operation.pollHeaders !== undefined) operation.pollHeaders = staticHeaders(operation.pollHeaders);
203
+ if (operation.pollNotFoundPending !== undefined && typeof operation.pollNotFoundPending !== 'boolean') {
204
+ throw new Error('pollNotFoundPending 必须是布尔值');
205
+ }
206
+ if (operation.body !== undefined && !plainObject(operation.body)) throw new Error(kind + ' 的 body 必须是 JSON 对象');
207
+ if (models && operation.body !== undefined && (!operation.method || operation.method === 'GET')) throw new Error('GET 模型列表使用端点查询参数');
208
+ if (modelOnly && operation.output === 'auto') {
209
+ // Legacy model-level Auto inherits the provider format. Provider-level Auto
210
+ // still selects the protocol default.
211
+ delete operation.output;
212
+ if (!Object.keys(operation).length) delete config[kind];
213
+ } else if (operation.output !== undefined) {
214
+ if (models) modelListOutput(operation.output);
215
+ else resolveConfiguredOutput(operation.output);
216
+ }
217
+ for (const key of ['pollOrigins', 'resultOrigins']) {
218
+ if (operation[key] !== undefined) operation[key] = originsOf(operation[key], key);
219
+ }
220
+ }
221
+ return { ...config, version: 1 };
222
+ }
223
+
224
+ /** Built-ins keep their request dialect and can opt into a different response format. */
225
+ export function normalizeResponseOverrides(raw, modelOnly = false) {
226
+ const operations = normalizeOperations(raw, modelOnly);
227
+ if (!operations) return operations;
228
+ if (operations.models) throw new Error('此协议使用内置模型列表格式');
229
+ for (const entry of [operations.generate, operations.edit]) {
230
+ if (entry) knownKeys(entry, ['output'], '内置协议的返回格式');
231
+ }
232
+ return operations;
233
+ }
234
+
235
+ const outputCache = new WeakMap();
236
+ const presetCache = new Map();
237
+
238
+ function parsedOutput(raw) {
239
+ if (raw === 'auto' || raw === undefined) return undefined;
240
+ if (typeof raw === 'string') {
241
+ if (!presetCache.has(raw)) presetCache.set(raw, resolveConfiguredOutput(raw));
242
+ return presetCache.get(raw);
243
+ }
244
+ if (!raw || typeof raw !== 'object') return resolveConfiguredOutput(raw);
245
+ let result = outputCache.get(raw);
246
+ if (!result) {
247
+ result = resolveConfiguredOutput(raw);
248
+ outputCache.set(raw, result);
249
+ }
250
+ return result;
251
+ }
252
+
253
+ export function responseOverridesOf(provider, model) {
254
+ const defaults = provider?.operations;
255
+ const override = provider?.modelOptions?.[model]?.operations;
256
+ if (!defaults && !override) return null;
257
+ const base = compiledOperations(defaults, 'responses');
258
+ const settings = compiledOperations(override, 'model-responses');
259
+ return {
260
+ generate: parsedOutput(settings.generate?.output ?? base.generate?.output),
261
+ edit: parsedOutput(settings.edit?.output ?? base.edit?.output)
262
+ };
263
+ }
264
+
265
+ export function providerOperationsOf(provider, model) {
266
+ const base = compiledOperations(provider?.operations, 'operations');
267
+ const override = compiledOperations(provider?.modelOptions?.[model]?.operations, 'model-operations');
268
+ return Object.fromEntries(['generate', 'edit', 'models'].flatMap((kind) => {
269
+ if (!base[kind] && !override[kind]) return [];
270
+ const entry = { ...base[kind], ...override[kind] };
271
+ if (base[kind]?.fields || override[kind]?.fields) entry.fields = { ...base[kind]?.fields, ...override[kind]?.fields };
272
+ return [[kind, entry]];
273
+ }));
274
+ }
275
+
276
+ export function assertReferenceCount(operation, count) {
277
+ if (operation?.maxImages && count > operation.maxImages) {
278
+ throw new Error('此编辑接口最多接受 ' + operation.maxImages + ' 张参考图,当前 ' + count + ' 张。');
279
+ }
280
+ }
281
+
282
+ const compiled = new WeakMap();
283
+
284
+ function compiledOperations(raw, scope) {
285
+ const modelOnly = scope.startsWith('model-');
286
+ const normalize = scope.endsWith('responses') ? normalizeResponseOverrides : normalizeOperations;
287
+ if (!plainObject(raw)) return normalize(raw, modelOnly) || {};
288
+ let cache = compiled.get(raw);
289
+ if (!cache) compiled.set(raw, cache = {});
290
+ return cache[scope] ||= normalize(raw, modelOnly);
291
+ }
@@ -15,11 +15,17 @@ const NO_BODY = Symbol('no-body');
15
15
 
16
16
  function parseProxyUrl(proxyUrl) {
17
17
  let url;
18
- try { url = new URL(String(proxyUrl || '')); } catch (_error) { throw new Error('网络连接配置无效:' + proxyUrl); }
19
- if (url.protocol !== 'http:') throw new Error('只支持 http:// 形式的连接配置:' + proxyUrl);
20
- const auth = url.username
21
- ? 'Basic ' + Buffer.from(decodeURIComponent(url.username) + ':' + decodeURIComponent(url.password || '')).toString('base64')
22
- : '';
18
+ try { url = new URL(String(proxyUrl || '')); } catch (_error) { throw new Error('代理地址格式无效'); }
19
+ if (url.protocol !== 'http:') throw new Error('代理地址必须使用 http://');
20
+ let auth = '';
21
+ if (url.username) {
22
+ try {
23
+ const credentials = decodeURIComponent(url.username) + ':' + decodeURIComponent(url.password);
24
+ auth = 'Basic ' + Buffer.from(credentials).toString('base64');
25
+ } catch (_error) {
26
+ throw new Error('代理认证信息编码无效');
27
+ }
28
+ }
23
29
  return {
24
30
  host: url.hostname.replace(/^\[|\]$/g, ''),
25
31
  port: Number(url.port) || 80,
package/lib/proxy.js CHANGED
@@ -13,14 +13,16 @@ function normalizeProxySpec(spec) {
13
13
  const raw = String(spec || '').trim();
14
14
  if (!raw) return undefined;
15
15
  const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : 'http://' + raw;
16
- let url;
17
- try { url = new URL(withScheme); } catch (_error) { return undefined; }
18
- if (url.protocol !== 'http:') return undefined;
19
- if (!url.hostname) return undefined;
20
- const auth = url.username
21
- ? encodeURIComponent(decodeURIComponent(url.username)) + ':' + encodeURIComponent(decodeURIComponent(url.password || '')) + '@'
22
- : '';
23
- return 'http://' + auth + url.host;
16
+ try {
17
+ const url = new URL(withScheme);
18
+ if (url.protocol !== 'http:' || !url.hostname) return undefined;
19
+ const auth = url.username
20
+ ? encodeURIComponent(decodeURIComponent(url.username)) + ':' + encodeURIComponent(decodeURIComponent(url.password || '')) + '@'
21
+ : '';
22
+ return 'http://' + auth + url.host;
23
+ } catch (_error) {
24
+ return undefined;
25
+ }
24
26
  }
25
27
 
26
28
  /**
@@ -4,19 +4,20 @@
4
4
  * 为什么要单独一层:提交地址是用户配置的提供商,轮询地址和结果地址却常常来自上游响应
5
5
  * (polling_url / status_url / urls.get)或 CDN。把提交用的 Key 原样带到这些地址,
6
6
  * 等于把凭据发给任何上游指定过的主机。这里只按目标域判断,不看响应内容。
7
+ *
8
+ * 结果图下载**只有 fetchResultImage() 一个入口**:12 条走 execute() 的协议、
9
+ * 异步轮询、通用 composeBody 路径全部走它。别在别处再写一个「拿 URL 直接 GET」的
10
+ * 下载函数——同一个 data[0].url 在两条路径上带不带 Key 不一致,就是这么来的。
7
11
  */
8
12
  import {
9
- MAX_IMAGE_BYTES, authHeaders, baseUrlOf, looksLikeImage, readResponseBytes, sniffType
13
+ MAX_IMAGE_BYTES, authenticatedUrl, authHeaderNameOf, authHeaders, authSpecOf, baseUrlOf, looksLikeImage, readResponseBytes,
14
+ resolveHttpUrl, sniffType
10
15
  } from './adapter-kit.js';
11
16
  import { request } from './net.js';
12
17
 
13
18
  function parseUrl(value) {
14
- try {
15
- const url = new URL(String(value || ''));
16
- return url.origin && url.origin !== 'null' ? url : null;
17
- } catch (_error) {
18
- return null;
19
- }
19
+ const url = resolveHttpUrl(value);
20
+ return url ? new URL(url) : null;
20
21
  }
21
22
 
22
23
  function baseUrlOfProvider(provider) {
@@ -64,11 +65,27 @@ function pollTrustOrigins(adapter) {
64
65
  return out;
65
66
  }
66
67
 
68
+ function isTrusted(adapter, provider, url, stage) {
69
+ const target = parseUrl(url);
70
+ const base = parseUrl(baseUrlOfProvider(provider));
71
+ if (!target || !base) return false;
72
+ if (target.origin === base.origin || target.origin === adapter?.operationOrigin) return true;
73
+ const origins = stage === 'poll' ? pollTrustOrigins(adapter) : adapter && adapter.resultAuthOrigins;
74
+ return isDeclaredTarget(origins, target);
75
+ }
76
+
77
+ /**
78
+ * 适配器自己声明的轮询头。新写法挂在适配器上(`taskPollHeaders`),老写法在 `async.pollHeaders`。
79
+ * 描述符(output)**不许**带 headers:一旦允许,就是给「裸请求」开一扇门。
80
+ */
67
81
  function adapterPollHeaders(adapter, provider) {
68
- if (!adapter || !adapter.async || typeof adapter.async !== 'object') return null;
69
- if (typeof adapter.async.pollHeaders !== 'function') return null;
82
+ if (!adapter) return null;
83
+ const source = typeof adapter.taskPollHeaders === 'function'
84
+ ? adapter.taskPollHeaders
85
+ : (adapter.async && typeof adapter.async === 'object' ? adapter.async.pollHeaders : null);
86
+ if (typeof source !== 'function') return null;
70
87
  try {
71
- return plainHeaders(adapter.async.pollHeaders(provider));
88
+ return plainHeaders(source(provider));
72
89
  } catch (_error) {
73
90
  return null;
74
91
  }
@@ -84,15 +101,10 @@ function adapterPollHeaders(adapter, provider) {
84
101
  * @returns {Record<string,string>}
85
102
  */
86
103
  export function pollRequestHeaders(adapter, provider, url) {
87
- const target = parseUrl(url);
88
- if (!target) return {};
89
- const base = parseUrl(baseUrlOfProvider(provider));
90
- if (!base) return {};
91
- const own = adapterPollHeaders(adapter, provider);
92
- const sameOrigin = target.origin === base.origin;
93
- if (sameOrigin) return own || authHeaders(provider, adapter);
94
- if (isDeclaredTarget(pollTrustOrigins(adapter), target)) return own || authHeaders(provider, adapter);
95
- return {};
104
+ if (!isTrusted(adapter, provider, url, 'poll')) return {};
105
+ const name = authHeaderNameOf(provider, adapter).toLowerCase();
106
+ const extra = Object.fromEntries(Object.entries(adapter?.pollHeaders || {}).filter(([key]) => key.toLowerCase() !== name));
107
+ return { ...extra, ...(adapterPollHeaders(adapter, provider) || authHeaders(provider, adapter)) };
96
108
  }
97
109
 
98
110
  /**
@@ -103,13 +115,60 @@ export function pollRequestHeaders(adapter, provider, url) {
103
115
  * @returns {Record<string,string>}
104
116
  */
105
117
  export function downloadRequestHeaders(adapter, provider, url) {
106
- const target = parseUrl(url);
107
- if (!target) return {};
108
- const base = parseUrl(baseUrlOfProvider(provider));
109
- if (!base) return {};
110
- if (target.origin === base.origin) return authHeaders(provider, adapter);
111
- if (isDeclaredTarget(adapter && adapter.resultAuthOrigins, target)) return authHeaders(provider, adapter);
112
- return {};
118
+ return isTrusted(adapter, provider, url, 'result') ? authHeaders(provider, adapter) : {};
119
+ }
120
+
121
+ const REDIRECTS = new Set([301, 302, 303, 307, 308]);
122
+
123
+ /** A provider operation's configured URL is trusted. Only same-origin redirects inherit its auth. */
124
+ export function requestProvider(url, init, provider, adapter, follow = true) {
125
+ const target = resolveHttpUrl(url);
126
+ if (!target) throw new Error('提供商请求地址无效');
127
+ const options = { ...init, redirect: 'manual' };
128
+ const spec = authSpecOf(provider, adapter);
129
+ // Submission redirects are returned to the executor. Following a redirect could replay a mutation.
130
+ if (!follow || (options.method && options.method !== 'GET' && options.method !== 'HEAD')) {
131
+ return request(authenticatedUrl(url, provider, adapter), options);
132
+ }
133
+ const origin = new URL(target).origin;
134
+ return readWithRedirects(url, options, (next) => new URL(next).origin === origin
135
+ ? { url: authenticatedUrl(next, provider, adapter), headers: options.headers }
136
+ : { url: next }, spec.mode === 'query' ? spec.name : '');
137
+ }
138
+
139
+ async function readWithRedirects(url, init, authorize, credentialParam) {
140
+ let next = url;
141
+ for (let hop = 0; ; hop++) {
142
+ const { url: target, headers } = authorize(next);
143
+ const options = { ...init, redirect: 'manual' };
144
+ if (headers && (Object.keys(headers).length || init.method === 'GET')) options.headers = headers;
145
+ else delete options.headers;
146
+ const response = await request(target, options);
147
+ const location = REDIRECTS.has(response.status) && response.headers.get('location');
148
+ if (!location) return response;
149
+ try { await response.body?.cancel(); } catch (_error) { /* already closed */ }
150
+ if (hop >= 4) throw new Error('上游请求重定向次数过多');
151
+ next = resolveHttpUrl(location, next);
152
+ if (!next) throw new Error('上游返回了无效的重定向地址');
153
+ if (credentialParam) {
154
+ const before = new URL(target);
155
+ const after = new URL(next);
156
+ if (before.origin !== after.origin && before.searchParams.has(credentialParam)) {
157
+ after.searchParams.delete(credentialParam, before.searchParams.get(credentialParam));
158
+ next = after.href;
159
+ }
160
+ }
161
+ }
162
+ }
163
+
164
+ /** Re-evaluate authentication at each read-only hop. */
165
+ export function requestResult(url, signal, adapter, provider, stage) {
166
+ if (!parseUrl(url)) throw downloadFailure('上游结果地址无效');
167
+ const spec = authSpecOf(provider, adapter);
168
+ return readWithRedirects(url, stage === 'poll' ? { signal, method: 'GET' } : { signal }, (next) => ({
169
+ url: isTrusted(adapter, provider, next, stage) ? authenticatedUrl(next, provider, adapter) : next,
170
+ headers: stage === 'poll' ? pollRequestHeaders(adapter, provider, next) : downloadRequestHeaders(adapter, provider, next)
171
+ }), spec.mode === 'query' ? spec.name : '');
113
172
  }
114
173
 
115
174
  function downloadFailure(message, fields) {
@@ -126,11 +185,7 @@ function downloadFailure(message, fields) {
126
185
  */
127
186
  export async function fetchResultImage(url, signal, adapter, provider) {
128
187
  if (!parseUrl(url)) throw downloadFailure('下载生成图失败:结果地址无效');
129
- const headers = downloadRequestHeaders(adapter, provider, url);
130
- const init = { signal: signal };
131
- // 空头不要写成 {}:跨源下载必须保持「完全不带 headers」这一可观察行为。
132
- if (Object.keys(headers).length) init.headers = headers;
133
- const response = await request(url, init);
188
+ const response = await requestResult(url, signal, adapter, provider, 'result');
134
189
  if (!response.ok) {
135
190
  try { await response.body?.cancel(); } catch (_error) { /* 已关闭 */ }
136
191
  throw downloadFailure('下载生成图失败:HTTP ' + response.status, { status: response.status });
@@ -1,33 +1,117 @@
1
- /**
2
- * 「这个会话看到的配置有没有变」:按会话记住上一次读到的配置快照。
3
- *
4
- * 比较的是快照,不是变更次数:用户把某个值改了又改回去、中间没有对话时,
5
- * 快照与上次相同,仍然算「没有变化」,不会白白作废一次读取。
6
- *
7
- * 快照挂在 session 对象上(WeakMap),所以天然不跨会话共享:新会话没有快照,
8
- * 状态是 unread,要读一次才放行。
9
- */
10
- const snapshots = new WeakMap();
11
-
12
- /** 配置快照:settings 返回给模型的那份 payload 的稳定文本。 */
13
- export function settingsSignature(payload) {
14
- return JSON.stringify(payload || {});
1
+ import { createHash } from 'node:crypto';
2
+ import { stableStringify } from './image-request.js';
3
+ import { settingsForModel } from './prompt-profiles.js';
4
+
5
+ export const SETTINGS_REFRESH_TURNS = 8;
6
+ const MAX_CANDIDATE_READS = 512;
7
+
8
+ export function settingsSnapshot(payload, signature) {
9
+ const visible = settingsForModel(payload);
10
+ // Keep field digests per session. Large catalogs and parameter lists stay in the live view.
11
+ const fields = new Map();
12
+ for (const [key, value] of Object.entries(visible)) {
13
+ if (value !== undefined) fields.set(key, createHash('sha256').update(stableStringify(value)).digest('hex'));
14
+ }
15
+ return { payload, visible, signature: signature ?? createHash('sha256').update(stableStringify([...fields])).digest('hex'), fields };
16
+ }
17
+
18
+ function contextPosition(ctx, session) {
19
+ let turn;
20
+ try {
21
+ const boundary = ctx.get?.('agents')?.turnBoundaryOf?.(session)
22
+ ?? ctx.get?.('sessionProjections')?.stateOf(session, 'turnBoundary');
23
+ if (Number.isSafeInteger(boundary?.lastTurn)) turn = boundary.lastTurn;
24
+ } catch { /* The host projection is optional. */ }
25
+ // Replacements and tool-result projections can invalidate a baseline without changing the turn.
26
+ const surface = session.surface;
27
+ const generation = surface?.contentGeneration ?? surface?.replaceGeneration;
28
+ return { turn, generation: Number.isSafeInteger(generation) ? generation : undefined };
29
+ }
30
+
31
+ function readingState(previous, signature, position) {
32
+ if (!previous) return 'unread';
33
+ const { checkpoint } = previous;
34
+ if (position.generation !== checkpoint.generation || position.fallback !== checkpoint.fallback
35
+ || position.count < checkpoint.count || position.count - checkpoint.count >= SETTINGS_REFRESH_TURNS) return 'refresh';
36
+ return previous.signature === signature ? 'fresh' : 'stale';
15
37
  }
16
38
 
17
- /** 记下这个会话刚刚看到的配置。 */
18
- export function rememberSettings(session, signature) {
19
- // WeakMap 只接受对象键:宿主要么给 Session 实例,要么什么都不给;给字符串时安静忽略。
20
- if (!session || typeof session !== 'object') return;
21
- if (typeof signature !== 'string') return;
22
- snapshots.set(session, signature);
39
+ function diffSettings(previous, current) {
40
+ const changes = {};
41
+ const removed = [];
42
+ for (const [key, digest] of current.fields) {
43
+ if (previous.fields.get(key) !== digest) changes[key] = current.visible[key];
44
+ }
45
+ for (const key of previous.fields.keys()) {
46
+ if (!current.fields.has(key)) removed.push(key);
47
+ }
48
+ return { changes, removed };
23
49
  }
24
50
 
25
- /**
26
- * @returns {'unread'|'fresh'|'stale'} unread = 本会话还没读过;fresh = 和上次读到的一致;stale = 配置改过
27
- */
28
- export function settingsState(session, signature) {
29
- if (!session || typeof session !== 'object') return 'unread';
30
- const last = snapshots.get(session);
31
- if (last === undefined) return 'unread';
32
- return last === signature ? 'fresh' : 'stale';
51
+ export function createSettingsMemory(ctx) {
52
+ const sessions = new WeakMap();
53
+ const countedSteps = new WeakSet();
54
+
55
+ function position(session, memory, step, advance) {
56
+ const { turn, generation } = contextPosition(ctx, session);
57
+ if (turn !== undefined) return { count: turn, generation, fallback: false };
58
+ // Legacy hosts: count uses of the image tools, once per available host step.
59
+ if (advance) {
60
+ if (step && typeof step === 'object') {
61
+ if (!countedSteps.has(step)) { countedSteps.add(step); memory.uses++; }
62
+ } else {
63
+ memory.uses++;
64
+ }
65
+ }
66
+ return { count: memory.uses, generation, fallback: true };
67
+ }
68
+
69
+ function state(session, signature) {
70
+ const memory = sessions.get(session);
71
+ return memory ? readingState(memory.settings, signature, position(session, memory)) : 'unread';
72
+ }
73
+
74
+ function read(session, current, { step, refresh = false, candidate = false, onlyIfNeeded = false } = {}) {
75
+ if (!session || typeof session !== 'object') return { state: 'unread', reply: { ...current.payload, revision: 1 } };
76
+ let memory = sessions.get(session);
77
+ if (!memory) {
78
+ memory = { uses: 0, settings: null, candidates: new Map() };
79
+ sessions.set(session, memory);
80
+ }
81
+ const now = position(session, memory, step, true);
82
+ const key = candidate ? JSON.stringify([current.payload.provider, current.payload.model]) : '';
83
+ const previous = candidate ? memory.candidates.get(key) : memory.settings;
84
+ const status = readingState(previous, current.signature, now);
85
+ const full = refresh || status === 'unread' || status === 'refresh';
86
+ const revision = (previous?.revision || 0) + Number(previous?.signature !== current.signature);
87
+ let reply;
88
+ if (full) {
89
+ reply = { ...current.payload, revision };
90
+ } else if (status === 'stale') {
91
+ const { changes, removed } = diffSettings(previous, current);
92
+ // Some request changes affect only on-demand candidate details or upstream behavior.
93
+ reply = {
94
+ baseRevision: previous.revision, revision, changes,
95
+ ...(removed.length ? { removed } : {}),
96
+ ...(candidate ? { model: current.payload.model } : {}),
97
+ hint: current.payload.model === 'auto'
98
+ ? '应用变更;需要候选细节时查询所选模型。'
99
+ : '应用变更,保留其余字段。'
100
+ };
101
+ } else {
102
+ if (onlyIfNeeded) return { state: status, reply: null };
103
+ return { state: status, reply: { ...(candidate ? { model: current.payload.model } : {}), unchanged: true, hint: '配置没变。' } };
104
+ }
105
+ const saved = { signature: current.signature, fields: current.fields, revision, checkpoint: full ? now : previous.checkpoint };
106
+ if (candidate) {
107
+ memory.candidates.delete(key);
108
+ memory.candidates.set(key, saved);
109
+ if (memory.candidates.size > MAX_CANDIDATE_READS) memory.candidates.delete(memory.candidates.keys().next().value);
110
+ } else {
111
+ memory.settings = saved;
112
+ }
113
+ return { state: status, reply };
114
+ }
115
+
116
+ return { state, read };
33
117
  }