dsh-model-think-level 2.0.3 → 2.2.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.
Files changed (68) hide show
  1. package/README.md +39 -22
  2. package/lib/autofill.d.ts +20 -2
  3. package/lib/balance.d.ts +44 -0
  4. package/lib/client/ComposerSlider.d.ts +19 -0
  5. package/lib/client/ConfigPane.d.ts +45 -0
  6. package/lib/client/EffortEditor.d.ts +1 -8
  7. package/lib/client/KeyManager.d.ts +2 -2
  8. package/lib/client/balance-client.d.ts +34 -0
  9. package/lib/client/events.d.ts +31 -2
  10. package/lib/client/image-config-client.d.ts +52 -0
  11. package/lib/client/index.d.ts +1 -0
  12. package/lib/client/injection/autofill-run.d.ts +2 -2
  13. package/lib/client/injection/compat-guard.d.ts +33 -0
  14. package/lib/client/injection/config-button-seat.d.ts +96 -0
  15. package/lib/client/injection/create-key-seat.d.ts +3 -3
  16. package/lib/client/injection/create-keys-pane.d.ts +4 -2
  17. package/lib/client/injection/editor-tab-bar.d.ts +1 -1
  18. package/lib/client/injection/editor-tabs.d.ts +1 -1
  19. package/lib/client/injection/image-card.d.ts +85 -0
  20. package/lib/client/injection/imagegen-completion.d.ts +43 -0
  21. package/lib/client/injection/imagegen-entry.d.ts +22 -0
  22. package/lib/client/injection/key-prefetch.d.ts +56 -0
  23. package/lib/client/injection/key-reveal.d.ts +2 -3
  24. package/lib/client/injection/model-order-drag.d.ts +1 -1
  25. package/lib/client/injection/models-page-editor.d.ts +25 -29
  26. package/lib/client/injection/models-page-mutation.d.ts +6 -0
  27. package/lib/client/injection/models-page.d.ts +15 -3
  28. package/lib/client/injection/provider-balance.d.ts +94 -0
  29. package/lib/client/injection/provider-delete-seat.d.ts +4 -1
  30. package/lib/client/injection/provider-disabled-group.d.ts +4 -1
  31. package/lib/client/injection/provider-endpoints.d.ts +2 -2
  32. package/lib/client/injection/provider-order-drag.d.ts +5 -1
  33. package/lib/client/injection/provider-toggle.d.ts +4 -1
  34. package/lib/client/injection/row-drag.d.ts +7 -0
  35. package/lib/client/injection/staged-keys.d.ts +24 -12
  36. package/lib/client/key-manager-client.d.ts +82 -19
  37. package/lib/client/locales.d.ts +40 -6
  38. package/lib/client/model-order.d.ts +9 -0
  39. package/lib/client/ops.d.ts +1 -0
  40. package/lib/client/order-sync.d.ts +63 -0
  41. package/lib/client/styles.d.ts +1 -1
  42. package/lib/client/types.d.ts +4 -1
  43. package/lib/client.js +517 -13
  44. package/lib/client.js.map +4 -4
  45. package/lib/constants.d.ts +53 -0
  46. package/lib/fingerprint/estimate.d.ts +16 -0
  47. package/lib/fingerprint/run.d.ts +6 -0
  48. package/lib/fingerprint/store.d.ts +2 -2
  49. package/lib/fingerprint/verdict.d.ts +24 -0
  50. package/lib/headers-core.d.ts +3 -1
  51. package/lib/headers-fetch.d.ts +25 -0
  52. package/lib/image/command.d.ts +84 -0
  53. package/lib/image/config.d.ts +150 -0
  54. package/lib/image/generate.d.ts +135 -0
  55. package/lib/image/legacy-cleanup.d.ts +29 -0
  56. package/lib/image/sizes.d.ts +28 -0
  57. package/lib/image/tool.d.ts +107 -0
  58. package/lib/index.js +3969 -1555
  59. package/lib/index.js.map +4 -4
  60. package/lib/key-index.d.ts +48 -7
  61. package/lib/key-probe.d.ts +42 -17
  62. package/lib/key-refs.d.ts +43 -19
  63. package/lib/key-route-core.d.ts +100 -32
  64. package/lib/key-serves.d.ts +81 -0
  65. package/lib/knowledge.d.ts +26 -0
  66. package/lib/listing.d.ts +18 -20
  67. package/lib/order-store.d.ts +78 -0
  68. package/package.json +1 -8
@@ -41,6 +41,18 @@ export declare const PROVIDER_KEY_PATH = "/dsh-model-think-level/provider-key";
41
41
  * never needs a new Remote face.
42
42
  */
43
43
  export declare const KEY_INDEX_PATH = "/dsh-model-think-level/key-index";
44
+ /**
45
+ * Same-origin host route that reads one provider's balance.
46
+ *
47
+ * The URL itself is configured per route in the plugin's key index (the
48
+ * `balances` map) and is queried host-side, because only the host can resolve
49
+ * the route's stored API key for the upstream call and the page would otherwise
50
+ * face CORS on a third-party balance API. The route answers
51
+ * `{ok, configured:false}` when the provider has no balance endpoint at all, so
52
+ * the browser half can tell "not configured" (show nothing) from "configured but
53
+ * unreadable" (show nothing but keep the endpoint).
54
+ */
55
+ export declare const BALANCE_PATH = "/dsh-model-think-level/balance";
44
56
  /**
45
57
  * Same-origin host route that reports this plugin's autofill switches. The
46
58
  * browser half runs the running auto-fill complement, and a `dsh.client`
@@ -68,6 +80,21 @@ export declare const HEADERS_CONFIG_PATH = "/dsh-model-think-level/headers-confi
68
80
  * plumbing: run challenges through the llm service, parse, store.
69
81
  */
70
82
  export declare const FINGERPRINT_PATH = "/dsh-model-think-level/fingerprint";
83
+ /**
84
+ * Same-origin host route owning the UI-order document: the provider-row
85
+ * sequence and every provider's model-row sequence the user set by dragging
86
+ * on the official Models page. `GET` answers the stored document,
87
+ * `POST` folds a (whole-state) payload over it — the synced copy the browser
88
+ * half pulls at boot and pushes on every drag, so the orderings survive a
89
+ * machine switch (see {@link ORDER_FILE}).
90
+ */
91
+ export declare const ORDER_PATH = "/dsh-model-think-level/ui-order";
92
+ /**
93
+ * File name of the UI-order document inside the plugin's home dir. Holds no
94
+ * secrets — provider routes and model ids only — which is what makes it safe
95
+ * to carry through a sync mechanism.
96
+ */
97
+ export declare const ORDER_FILE = "ui-order.json";
71
98
  /** The settings namespace this plugin edits: pi-ai custom provider routes. */
72
99
  export declare const PI_AI_NS = "llm-pi-ai";
73
100
  /**
@@ -130,5 +157,31 @@ export declare const AUTOFILL_MARKER = "reasoningEffortsAutofilled";
130
157
  * so a future first-class field can adopt the stored values as-is.
131
158
  */
132
159
  export declare const DEFAULT_EFFORT_FIELD = "defaultEffort";
160
+ /**
161
+ * Same-origin host route owning the image-generation config surface: `GET`
162
+ * answers the derived image-model list merged with the stored overrides,
163
+ * `POST` saves default model / default params / output dir / per-model rows.
164
+ * Backing file: `<DSH_HOME>/dsh-model-think-level/image.json` (see
165
+ * {@link IMAGE_CONFIG_FILE}).
166
+ */
167
+ export declare const IMAGE_CONFIG_PATH = "/dsh-model-think-level/image-config";
168
+ /** File name of the image-generation config inside the plugin's home dir. */
169
+ export declare const IMAGE_CONFIG_FILE = "image.json";
170
+ /**
171
+ * The patch-layer id the RETIRED image-MCP entry carried. No entry is written
172
+ * any more — the native `generate_image` tool replaced the stdio server — but
173
+ * the id and the marker below still matter: the boot-time migration
174
+ * (`src/image/legacy-cleanup.ts`) recognizes and removes a leftover block, so
175
+ * an upgraded profile stops spawning the now-missing `lib/image-mcp.mjs` and
176
+ * stops exposing the duplicate `mcp__dsh-image__generate_image`.
177
+ */
178
+ export declare const IMAGE_MCP_PATCH_ID = "dsh-image-mcp";
179
+ /**
180
+ * Marker-block name the retired installer used inside `cordis.patch.yml`. The
181
+ * begin/end comment lines are `# >>> <name>:begin` / `# <<< <name>:end`; the
182
+ * legacy cleanup splices exactly that byte range, so third-party marker blocks
183
+ * (the dsh-skill-mcp-panel precedent) survive untouched.
184
+ */
185
+ export declare const IMAGE_MCP_PATCH_MARK = "dsh-model-think-level:image-mcp";
133
186
  /** Locale dictionary namespace for the browser half's copy (not a settings namespace). */
134
187
  export declare const STORE_NS = "dsh-model-think-level";
@@ -0,0 +1,16 @@
1
+ import type { FingerprintRecord } from './verdict.js';
2
+ /** 提示里的时长:秒按 5 秒取整,过了 75 秒改报整分钟。 */
3
+ export type RunEstimate = {
4
+ unit: 'seconds';
5
+ value: number;
6
+ } | {
7
+ unit: 'minutes';
8
+ value: number;
9
+ };
10
+ /**
11
+ * 估一次完整检测(`FULL_RUN_QUERIES` 题)大概要等多久。
12
+ *
13
+ * @param records - 同一家供应商已落盘的结论,顺序任意,缺 timing 的跳过。
14
+ * @returns 没有任何可参考的耗时时返回 `undefined`。
15
+ */
16
+ export declare function estimateRun(records: readonly FingerprintRecord[]): RunEstimate | undefined;
@@ -58,6 +58,12 @@ export interface ProbeOutcome {
58
58
  firstTokenMs?: number;
59
59
  /** Total wall time of the challenge, milliseconds. */
60
60
  durationMs?: number;
61
+ /**
62
+ * Aborted BY the early exit: two confident answers already closed the run, so
63
+ * this challenge was never needed. Without the bit a caller cannot tell a
64
+ * deliberate skip from a user cancellation — both come back `cancelled`.
65
+ */
66
+ skipped?: boolean;
61
67
  }
62
68
  /** Everything one model's fingerprint run learned, ready for the bank. */
63
69
  export interface ProbeRunResult {
@@ -1,5 +1,5 @@
1
- import { type FingerprintRecord, type FingerprintStatus, type FingerprintTiming, type FingerprintTopEntry } from './verdict.js';
2
- export { type FingerprintRecord, type FingerprintStatus, type FingerprintTiming, type FingerprintTopEntry };
1
+ import { type FingerprintChallenge, type FingerprintRecord, type FingerprintStatus, type FingerprintTiming, type FingerprintTopEntry } from './verdict.js';
2
+ export { type FingerprintChallenge, type FingerprintRecord, type FingerprintStatus, type FingerprintTiming, type FingerprintTopEntry, };
3
3
  export interface FingerprintDocument {
4
4
  version: 1;
5
5
  /** 银行的 built_at;换银行就整体失效。 */
@@ -20,6 +20,28 @@ export interface FingerprintTopEntry {
20
20
  probability: number;
21
21
  similarity: number;
22
22
  }
23
+ /**
24
+ * 结果卡「逐题」那一行里的一颗药丸:一道题问了多少、答回来多少、算不算数。
25
+ *
26
+ * 为什么落盘:`usedOutputs` 只说「三题里算了几题」,说不出是哪一题不算 ——
27
+ * 而「为什么只回答了部分题目」正是用户看着 `2 / 3 题` 想问的那句话。逐题的
28
+ * 期望数与解析数都是统计量,不涉及作答文本(design §4.2)。
29
+ */
30
+ export interface FingerprintChallenge {
31
+ /** 题号,从 1 开始,与题干发出顺序一致。 */
32
+ index: number;
33
+ /** 这道题要求几个整数(292–332)。 */
34
+ expected: number;
35
+ /** 解析出来的整数个数;拒答、报错、被掐断都是 0。 */
36
+ parsed: number;
37
+ /** 是否达到了计入门槛(`max(80, ceil(expected * 0.55))`)。 */
38
+ accepted: boolean;
39
+ /**
40
+ * 两题早停时被主动掐掉的那道题。它没答不是因为答坏了 —— 药丸上要说的
41
+ * 是「早停跳过」,不是「未计入」,否则用户会去追一个不存在的失败。
42
+ */
43
+ skipped?: boolean;
44
+ }
23
45
  /**
24
46
  * 一个模型的一次检测结论,也是落盘的那一行。
25
47
  *
@@ -40,6 +62,8 @@ export interface FingerprintRecord {
40
62
  familyPrediction?: string;
41
63
  familyProbability?: number;
42
64
  top?: FingerprintTopEntry[];
65
+ /** 逐题记账:哪几题算进去了、哪题没算。旧记录没有这个字段。 */
66
+ challenges?: FingerprintChallenge[];
43
67
  calibration?: {
44
68
  queries: number;
45
69
  cvAccuracy: number;
@@ -82,7 +82,9 @@ export declare function isSendableUserAgent(value: string): boolean;
82
82
  /**
83
83
  * Whether a configured name/value pair can ride a Fetch header. Fetch is the
84
84
  * authority for the exact token grammar, so this accepts arbitrary legal names
85
- * instead of maintaining a brittle allow-list.
85
+ * instead of maintaining a brittle allow-list — except the wire-forbidden set
86
+ * above, which `Headers.set()` (an editing API, not a wire validator) happily
87
+ * accepts and the wire then chokes on.
86
88
  */
87
89
  export declare function isSendableHeader(name: string, value: string): boolean;
88
90
  /** The `headers` dict of one route profile, as string pairs, or undefined. */
@@ -38,6 +38,31 @@
38
38
  */
39
39
  import { emptyIndex, type HeaderIndex } from './headers-core.js';
40
40
  import { type KeyCandidate } from './key-route-core.js';
41
+ /** What a dispatch hook is told about the request it may claim. */
42
+ export interface DispatchContext {
43
+ /** The request URL, as resolved by the wrapper. */
44
+ readonly url: string;
45
+ /** The request method, uppercased (GET when neither side named one). */
46
+ readonly method: string;
47
+ /**
48
+ * Lazily read the request body as text. Cached; a `Request` input is cloned
49
+ * (the caller's stream survives), an `init.body` string is taken directly,
50
+ * and any other shape yields undefined — the hook decides what "unreadable"
51
+ * means (the image dispatch lets those through rather than mis-claiming).
52
+ */
53
+ readonly bodyText: () => Promise<string | undefined>;
54
+ /** The fetch beneath this wrapper, avoiding recursive interception. */
55
+ readonly send: typeof globalThis.fetch;
56
+ }
57
+ /** A dispatch candidate: return a Response to fully claim the request (it is never sent); undefined passes it through. */
58
+ export type DispatchHook = (context: DispatchContext) => Promise<Response | undefined>;
59
+ /**
60
+ * Register one dispatch hook. Order is registration order; the FIRST hook to
61
+ * return a Response claims the request. @returns the remover (idempotent).
62
+ */
63
+ export declare function registerDispatchHook(hook: DispatchHook): () => void;
64
+ /** How many dispatch hooks are live (diagnostics; 0 = the seam costs nothing). */
65
+ export declare function dispatchHookCount(): number;
41
66
  /** What a key resolver is told about the request it must sign. */
42
67
  export interface KeyRouteContext {
43
68
  /** The provider route whose profile matched the request URL. */
@@ -0,0 +1,84 @@
1
+ /**
2
+ * The `/生图` host command (the explicit entry beside the wire dispatch).
3
+ *
4
+ * Registered on the HOST side on purpose: the client's `commandUi.register`
5
+ * can only run a no-argument action — a command that reads parameters would
6
+ * fall through to `remote.commands.execute` and answer "unknown or malformed
7
+ * command". The host-side `ctx.commands.register` with an `input.hint` is the
8
+ * shape the built-in command plugins use (the dsh-command-goal precedent).
9
+ *
10
+ * The handler is a thin argument parser over the SHARED generation core —
11
+ * the same `generateImage` the native `generate_image` tool calls.
12
+ *
13
+ * @module dsh-model-think-level/image/command
14
+ */
15
+ import { generateImage, type GenerateDeps, type GenerateResult } from './generate.js';
16
+ /** The host `commands` service, typed structurally (no new dependency). */
17
+ export interface CommandsServiceLike {
18
+ register(contribution: {
19
+ definitionId: string;
20
+ name: string;
21
+ description: string;
22
+ input?: {
23
+ hint?: string;
24
+ attachments?: boolean;
25
+ };
26
+ handler: (invocation: unknown) => Promise<unknown>;
27
+ }): unknown;
28
+ }
29
+ /** The plugin's command definition id (the built-ins' `@deepseek-ai/<pkg>:<name>` spelling). */
30
+ export declare const IMAGEGEN_DEFINITION_ID = "@deepseek-ai/dsh-model-think-level:imagegen";
31
+ /** The hint the slash menu shows under the command. */
32
+ export declare const IMAGEGEN_HINT = "[<\u6A21\u578B>] [--size 1024x1024] [--quality high] [--n 1] [--\u53C2\u8003\u56FE <\u8DEF\u5F84>] <\u63D0\u793A\u8BCD>";
33
+ /** One parsed invocation. */
34
+ export interface ImagegenArgs {
35
+ readonly model?: string;
36
+ readonly size?: string;
37
+ readonly quality?: string;
38
+ readonly n?: number;
39
+ readonly referenceImages: readonly string[];
40
+ readonly prompt: string;
41
+ }
42
+ /**
43
+ * Parse one `/生图` argument string. Tolerant on purpose: the model may be
44
+ * omitted (the config default applies), an unknown option is reported (with
45
+ * the accepted spellings — never silently ignored), and everything that is
46
+ * neither option nor model is the prompt.
47
+ * @throws Error naming the mistake and the accepted options.
48
+ */
49
+ export declare function parseImagegenArgs(text: string, knownModels?: readonly string[]): ImagegenArgs;
50
+ /**
51
+ * What the handler needs: the live model ids (for argument disambiguation),
52
+ * the generation deps, and an optional echo face for the session the command
53
+ * ran in. The echo is best-effort — the command's return value is the
54
+ * contract the host consumes; a session write is attempted only when the
55
+ * invocation carries a session that exposes one.
56
+ */
57
+ export interface ImagegenDeps {
58
+ readonly modelIds: () => readonly string[];
59
+ readonly generate: typeof generateImage;
60
+ readonly generateDeps: GenerateDeps;
61
+ /** Best-effort session echo (guarded; never throws into the command). */
62
+ readonly echo?: (invocation: unknown, text: string, filePath: string) => void;
63
+ } /** Run one parsed invocation through the shared core and shape the result. */
64
+ export declare function executeImagegen(deps: ImagegenDeps, parsed: ImagegenArgs): Promise<{
65
+ ok: true;
66
+ filePaths: readonly string[];
67
+ mime: string;
68
+ model: string;
69
+ paramsUsed: GenerateResult['paramsUsed'];
70
+ text: string;
71
+ warning?: string;
72
+ } | {
73
+ ok: false;
74
+ error: string;
75
+ }>;
76
+ /**
77
+ * The invocation face the host hands the handler, narrowed to what this
78
+ * command reads. `text` carries the arguments after the command word; the
79
+ * exact field is spelled several ways across host versions, so each common
80
+ * one is tried (in order) and the first non-empty wins.
81
+ */
82
+ export declare function invocationTextOf(invocation: unknown): string;
83
+ /** Register the command. @returns undefined when the host has no commands service. */
84
+ export declare function registerImagegenCommand(commands: CommandsServiceLike | undefined, deps: ImagegenDeps): void;
@@ -0,0 +1,150 @@
1
+ /**
2
+ * The image-generation config: `<DSH_HOME>/dsh-model-think-level/image.json`.
3
+ *
4
+ * The file holds no secrets — credential references only — which is what makes
5
+ * it safe to keep in plain text and to hand to the MCP subprocess through one
6
+ * `DSH_IMAGE_CONFIG` env var. Its `models[]` is a DERIVED SNAPSHOT: the source
7
+ * of truth is the `llm-pi-ai` settings document's `inputImageGen` rows (the
8
+ * same marker the Models page and the auto-fill write), and this file layers
9
+ * the user's per-model overrides (endpoint verdict, param abilities, picked
10
+ * size/quality/n) on top. Syncing keeps every override keyed by model id, so a
11
+ * model that leaves the settings document drops out and one that comes back
12
+ * keeps its overrides.
13
+ *
14
+ * Parsing follows `key-index.ts`: read-never-throw for absent files, defensive
15
+ * field-by-field drops for malformed content, and an atomic temp-then-rename
16
+ * write so a crash mid-write cannot leave a half-parsed config behind.
17
+ *
18
+ * @module dsh-model-think-level/image/config
19
+ */
20
+ /** Endpoint verdict of one image model. `unverified` is the honest default. */
21
+ export type EndpointStatus = 'unverified' | 'ok' | 'unsupported';
22
+ /** Wire shape the model row speaks. Only OpenAI-compatible images is wired up. */
23
+ export type ImageApi = 'images' | 'none';
24
+ /** The conservative ability table every freshly derived row starts with. */
25
+ export interface ImageParams {
26
+ readonly sizes: readonly string[];
27
+ readonly qualities: readonly string[];
28
+ readonly maxN: number;
29
+ /** How the endpoint wants its answer: b64 inline, an output_format field, or nothing. */
30
+ readonly responseFormat: 'b64_json' | 'output_format' | 'none';
31
+ }
32
+ /** One derived model row, before user overrides. */
33
+ export interface ImageModelSeed {
34
+ readonly id: string;
35
+ readonly route: string;
36
+ readonly modelId: string;
37
+ readonly label: string;
38
+ /** The route profile's `displayName` (the provider name the Models page
39
+ * shows), when the profile has one; absent when the profile does not. */
40
+ readonly providerLabel?: string;
41
+ readonly api: ImageApi;
42
+ readonly baseURL: string;
43
+ readonly keyRef?: string;
44
+ }
45
+ /** One image model as the config stores it: derived facts + user overrides. */
46
+ export interface ImageModel {
47
+ readonly id: string;
48
+ readonly route: string;
49
+ readonly modelId: string;
50
+ readonly label: string;
51
+ readonly providerLabel?: string;
52
+ readonly api: ImageApi;
53
+ readonly baseURL: string;
54
+ readonly keyRef?: string;
55
+ readonly endpoint: {
56
+ readonly kind: 'images';
57
+ readonly status: EndpointStatus;
58
+ readonly checkedAt: string | null;
59
+ };
60
+ readonly params: ImageParams;
61
+ readonly lastGoodParams: ImageParams | null;
62
+ }
63
+ /** The defaults every model row inherits when it does not override. */
64
+ export interface ImageDefaults {
65
+ readonly size: string;
66
+ readonly quality: string;
67
+ readonly n: number;
68
+ readonly timeoutMs: number;
69
+ }
70
+ /** The whole config document, exactly as it sits on disk. */
71
+ export interface ImageConfig {
72
+ readonly version: 2;
73
+ /** When `models[]` was last re-derived from the settings document. */
74
+ readonly syncedAt: string;
75
+ /** `"<route>/<modelId>"` of the default model, when the user picked one. */
76
+ readonly defaultModel: string | null;
77
+ readonly defaults: ImageDefaults;
78
+ readonly outputDir: string;
79
+ readonly models: readonly ImageModel[];
80
+ }
81
+ /** A mutable view of the config the writers build from. */
82
+ export type ImageConfigDraft = {
83
+ -readonly [K in keyof ImageConfig]: ImageConfig[K];
84
+ };
85
+ /** Conservative defaults: nothing here assumes a capability the API may not have. */
86
+ export declare const IMAGE_FALLBACK_PARAMS: ImageParams;
87
+ /** Absolute path of the image config. */
88
+ export declare function imageConfigFilePath(home?: string): string;
89
+ /** A fresh, empty config. */
90
+ export declare function emptyImageConfig(now?: () => Date): ImageConfig;
91
+ /**
92
+ * Parse an already-decoded config document. Never throws and never trusts the
93
+ * input: anything unrecognisable is dropped field by field, so a hand-edited
94
+ * or truncated file costs at most the fields it got wrong. Overrides of model
95
+ * rows this document does not know are kept — the next sync may re-derive them.
96
+ */
97
+ export declare function parseImageConfig(raw: unknown, now?: () => Date): ImageConfig;
98
+ /** Read the config; an absent or unreadable file means a fresh, empty one. */
99
+ export declare function readImageConfig(file?: string): ImageConfig;
100
+ /** Write the config at one path, atomically (sibling temp file, then rename). */
101
+ export declare function writeImageConfig(document: ImageConfig, file?: string): void;
102
+ /**
103
+ * Derive the image-model seeds from a resolved `llm-pi-ai` providers map: every
104
+ * route's `models[]` row carrying `inputImageGen === true`, with the route's
105
+ * api/baseURL/credential reference (and its displayName, the provider name the
106
+ * list shows) attached. This is the SAME marker the Models
107
+ * page editor and the auto-fill write, so both writers feed this list.
108
+ *
109
+ * A route whose protocol cannot carry an OpenAI-compatible images call still
110
+ * lists its rows — marked `api: 'none'` so the UI can badge "no compatible
111
+ * endpoint" and refuse generation.
112
+ */
113
+ export declare function deriveImageSeeds(providers: Record<string, Record<string, unknown>>): ImageModelSeed[];
114
+ /**
115
+ * Re-derive `models[]` from the settings document while keeping every stored
116
+ * override keyed by model id. A derived row starts from the conservative
117
+ * ability table; a stored row of the same id hands its overrides (endpoint
118
+ * verdict, params, lastGoodParams) forward. Rows the settings document no
119
+ * longer declares are dropped; defaultModel that points at a dropped model is
120
+ * cleared.
121
+ *
122
+ * The old per-row size/quality/n picks are gone on purpose: the pane's params
123
+ * row is the single place those are chosen, so a leftover pick from an older
124
+ * build must not quietly outrank it. They are simply not carried forward.
125
+ */
126
+ export declare function syncImageConfig(stored: ImageConfig, providers: Record<string, Record<string, unknown>>, now?: () => Date): ImageConfig;
127
+ /**
128
+ * Resolve the model a generation should use, per the design's priority:
129
+ * an explicit pick (the dialog's current model, or a call's `model` argument)
130
+ * wins; then the config's defaultModel; then the sole candidate when exactly
131
+ * one exists. `undefined` when nothing resolves.
132
+ */
133
+ export declare function resolveImageModel(config: ImageConfig, explicit?: string | undefined): ImageModel | undefined;
134
+ /**
135
+ * The params one generation uses: the call's explicit values win, then the
136
+ * config defaults (the pane's params row). `n` is additionally clamped to the
137
+ * model's ability table (a row that says maxN 2 never fires 8 requests).
138
+ * `referenceImages` never comes from config — it is per-call.
139
+ */
140
+ export declare function effectiveParams(config: ImageConfig, model: ImageModel | undefined, request: {
141
+ size?: string;
142
+ quality?: string;
143
+ n?: number;
144
+ }): {
145
+ size: string;
146
+ quality: string;
147
+ n: number;
148
+ };
149
+ /** One synchronous read-modify-write of the config file. */
150
+ export declare function updateImageConfig(mutate: (document: ImageConfig) => ImageConfig, file?: string): ImageConfig;
@@ -0,0 +1,135 @@
1
+ /**
2
+ * The image-generation core: ONE implementation of the OpenAI-compatible
3
+ * images API call + disk write, behind three entries (the `generate_image`
4
+ * native tool, the `/image-generate` route, the `/生图` host command).
5
+ * Anything about request construction, param fallback, sanitization or file
6
+ * naming lives here and nowhere else.
7
+ *
8
+ * Endpoint choice: no reference images → `POST {baseURL}/images/generations`
9
+ * (JSON); with reference images → `POST {baseURL}/images/edits` with a
10
+ * hand-built multipart/form-data body (zero dependencies — the boundary is
11
+ * constructed here, not by a library the bundle cannot carry).
12
+ *
13
+ * Failure taxonomy (v3): the GUI used to show an image-only key's `403
14
+ * permission_denied` as "API 密钥无效" because the CHAT wire produced it. This
15
+ * core never talks the chat wire, and its errors are classified — auth vs
16
+ * image-endpoint-only permission vs missing endpoint vs param — so every entry
17
+ * can show the operative sentence instead of the misleading one. Error text is
18
+ * sanitized: the key value can never appear in a message, whatever shape the
19
+ * upstream echoes back.
20
+ *
21
+ * @module dsh-model-think-level/image/generate
22
+ */
23
+ import { type ImageConfig, type ImageModel } from './config.js';
24
+ /** What a caller asks for. Everything but `prompt` is optional. */
25
+ export interface GenerateRequest {
26
+ /** `"<route>/<modelId>"`, a bare modelId, or the label; default when omitted. */
27
+ readonly model?: string;
28
+ readonly prompt: string;
29
+ /**
30
+ * The caller's cancellation (the user pressed stop while the reply stream
31
+ * was still pending). Aborts the in-flight images request too, so a stop
32
+ * never leaves a paid generation running to completion behind the UI.
33
+ */
34
+ readonly signal?: AbortSignal;
35
+ readonly size?: string;
36
+ readonly quality?: string;
37
+ readonly n?: number;
38
+ /** Local file paths; any non-empty list switches to the edits endpoint. */
39
+ readonly referenceImages?: readonly string[];
40
+ /**
41
+ * Reference images as already-decoded bytes — the attachment-backed channel:
42
+ * the native tool resolves conversation image IDs through the attachment
43
+ * store and hands the bytes over, so no temp file ever hits the disk. Any
44
+ * entry here (alone or beside `referenceImages`) switches to the edits
45
+ * endpoint.
46
+ */
47
+ readonly referenceFiles?: readonly {
48
+ readonly name: string;
49
+ readonly mime: string;
50
+ readonly bytes: Uint8Array;
51
+ }[];
52
+ /**
53
+ * Where to land the file: a path ending in `.png` is honored EXACTLY (an
54
+ * existing one gains a `-2` suffix — never overwritten), anything else is
55
+ * created as a directory and receives the slug-timestamp naming. Absent
56
+ * means the config's `outputDir`.
57
+ */
58
+ readonly outputPath?: string;
59
+ }
60
+ /** One generated image: the b64 payload the wire returned + where it landed. */
61
+ export interface GeneratedImage {
62
+ readonly filePath: string;
63
+ readonly data: string;
64
+ }
65
+ /** What a successful generation reports. */
66
+ export interface GenerateResult {
67
+ /**
68
+ * Every image the wire returned, in order, each already written to disk.
69
+ * The upstream is asked for `paramsUsed.n` images; a relay that answers
70
+ * fewer yields fewer entries — the result never invents one.
71
+ */
72
+ readonly images: readonly GeneratedImage[];
73
+ readonly mime: string;
74
+ readonly model: string;
75
+ /** The prompt this run answered (the reply's markdown alt text derives from it). */
76
+ readonly prompt: string;
77
+ readonly paramsUsed: {
78
+ readonly size: string;
79
+ readonly quality: string;
80
+ readonly n: number;
81
+ };
82
+ /**
83
+ * What the fallback chain had to change, in order — the "回退说明" the reply
84
+ * text carries. Empty when the first attempt went through untouched.
85
+ */
86
+ readonly revisions: readonly string[];
87
+ }
88
+ /** The classified failure `generateImage` throws (as `GenerateError`). */
89
+ export type GenerateFailureKind = 'config' | 'auth' | 'permission' | 'endpoint' | 'param' | 'reference' | 'upstream' | 'timeout' | 'aborted';
90
+ export declare class GenerateError extends Error {
91
+ readonly kind: GenerateFailureKind;
92
+ readonly status?: number;
93
+ constructor(kind: GenerateFailureKind, message: string, status?: number);
94
+ }
95
+ /** The faces this core needs from its host. All injectable for tests. */
96
+ export interface GenerateDeps {
97
+ /** The live config; read fresh per call (the MCP path re-reads the file). */
98
+ readonly config?: () => ImageConfig;
99
+ /** Resolve one credential reference to its value. */
100
+ readonly resolveKey: (ref: string) => Promise<string | undefined>;
101
+ /** The fetch beneath any wrapper — the images call must not be re-intercepted. */
102
+ readonly send: typeof globalThis.fetch;
103
+ /** Base dir for relative `outputDir`s (defaults to the harness home). */
104
+ readonly home?: () => string;
105
+ /** Persist `lastGoodParams` after a successful fallback (host: config file). */
106
+ readonly persistLastGood?: (modelId: string, params: ImageModel['lastGoodParams']) => void;
107
+ /** Now, for file stamps (defaults to Date.now). */
108
+ readonly now?: () => number;
109
+ /** Per-call timeout override (ms). */
110
+ readonly timeoutMs?: number;
111
+ }
112
+ /** The multipart body of an /images/edits call, hand-built (zero deps). */
113
+ export declare function buildMultipart(boundary: string, fields: Readonly<Record<string, string>>, images: readonly {
114
+ readonly name: string;
115
+ readonly bytes: Uint8Array;
116
+ readonly mime: string;
117
+ }[]): {
118
+ body: Uint8Array<ArrayBuffer>;
119
+ contentType: string;
120
+ };
121
+ /** Filesystem slug of a prompt: CJK kept, everything unsafe folded to `-`. */
122
+ export declare function promptSlug(prompt: string): string;
123
+ /**
124
+ * Where this run's file lands. An explicit `.png` path is honored exactly
125
+ * (an existing one gains a numeric suffix — the never-overwrite rule);
126
+ * anything else — an existing directory, a trailing separator, a non-png
127
+ * name — is created as a directory and receives the slug-timestamp naming.
128
+ */
129
+ export declare function resolveDestination(requested: string | undefined, fallbackDir: string, slug: string, now: () => number): string;
130
+ /**
131
+ * Run one generation. Reads the config fresh, resolves the model per the
132
+ * priority chain, merges params, calls the images endpoint (with one pass of
133
+ * the param fallback chain), decodes and writes the file.
134
+ */
135
+ export declare function generateImage(deps: GenerateDeps, request: GenerateRequest): Promise<GenerateResult>;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * One-time migration: remove the retired image-MCP server's patch entry.
3
+ *
4
+ * The v2.0.3 image tool was an stdio MCP subprocess installed by splicing a
5
+ * marker block into the current profile's `cordis.patch.yml`. That transport
6
+ * is gone — `lib/image-mcp.mjs` is no longer built — so a leftover block would
7
+ * make the loader spawn a missing file on every boot AND expose a duplicate
8
+ * `mcp__dsh-image__generate_image` beside the native tool. The cleanup runs
9
+ * unconditionally at apply(): absent block → no-op, present block → the exact
10
+ * byte range is spliced out (never a re-serialization of the whole document,
11
+ * because third-party marker blocks share this file), with a timestamped
12
+ * `.bak`, an mtime-fenced retry, and a post-write re-read.
13
+ *
14
+ * The running process keeps whatever it loaded at boot; the removal takes
15
+ * effect on the next start, which the caller's log line says.
16
+ *
17
+ * @module dsh-model-think-level/image/legacy-cleanup
18
+ */
19
+ /** Marker lines the retired installer owned inside the patch file. */
20
+ export declare const MARK_BEGIN = "# >>> dsh-model-think-level:image-mcp:begin";
21
+ export declare const MARK_END = "# <<< dsh-model-think-level:image-mcp:end";
22
+ /** How the current profile's patch file is located (the installer's own order). */
23
+ export declare function resolveLegacyPatchFile(home?: string): string;
24
+ /**
25
+ * Remove the retired MCP marker block if it is present.
26
+ * @returns the patch file that was written, or undefined when there was
27
+ * nothing to remove (absent block, absent file, or an unreadable home).
28
+ */
29
+ export declare function removeLegacyImageMcpPatch(home?: string, patchFile?: string): string | undefined;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The image-size ladder the config pane shows: three friendly tiers over the
3
+ * pixel values the endpoint actually receives.
4
+ *
5
+ * The wire stays pixel-based (`1024x1024` …) — the tiers are presentation only,
6
+ * so relaying the picked value needs no translation. Legacy sizes a config may
7
+ * still hold (`1536x1024`, `512x512`) map to the nearest tier by longest edge;
8
+ * ties keep the smaller tier so the UI never claims more pixels than stored.
9
+ *
10
+ * @module dsh-model-think-level/image/sizes
11
+ */
12
+ /** One size tier: the label the picker shows and the value the wire gets. */
13
+ export interface ImageSizeTier {
14
+ readonly label: '1K' | '2K' | '4K';
15
+ readonly value: string;
16
+ /** The longest edge in pixels; also the sort order of the ladder. */
17
+ readonly edge: number;
18
+ }
19
+ /** The ladder, smallest first. The values are the wire's `size` strings. */
20
+ export declare const IMAGE_SIZE_TIERS: readonly ImageSizeTier[];
21
+ /** The longest edge of a `WxH` size, or undefined for anything else. */
22
+ export declare function longestEdge(size: string): number | undefined;
23
+ /** The tier a stored size maps to (unparsable sizes read as the smallest). */
24
+ export declare function tierOfSize(size: string): ImageSizeTier;
25
+ /** The picker text for a stored size (`1536x1024` → `1K`). */
26
+ export declare function sizeLabel(size: string): string;
27
+ /** The canonical wire value for a stored size (`1536x1024` → `1024x1024`). */
28
+ export declare function canonicalSize(size: string): string;