dsh-image-gen 0.1.5 → 0.1.7

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/lib/index.js CHANGED
@@ -2,6 +2,9 @@ import { credentialRef } from "@deepseek-ai/dsh-credentials";
2
2
  import { installSettingsSection, settingsNamespace } from "@deepseek-ai/dsh-settings";
3
3
  import { defineTool } from "@deepseek-ai/dsh-tools";
4
4
  import z from "@deepseek-ai/schemastery";
5
+ import { randomUUID } from "node:crypto";
6
+ import { mkdir, realpath, rename, unlink, writeFile } from "node:fs/promises";
7
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
8
  //#region lib/types/shared.js
6
9
  /** Values shared by the Host and browser Bundle faces. */
7
10
  /** Browser route used by the generated-image card. */
@@ -28,6 +31,8 @@ const DEFAULT_DASHSCOPE_MODEL = "wanx2.1-t2i-turbo";
28
31
  //#endregion
29
32
  //#region lib/types/config.js
30
33
  /** User-facing configuration for supported image providers. */
34
+ /** Default workspace subfolder that receives generated image files. */
35
+ const DEFAULT_WORKSPACE_FOLDER = "dsh-image-gen";
31
36
  /** Google API credential reference. */
32
37
  const GOOGLE_API_KEY_ENV = "GEMINI_API_KEY";
33
38
  /** OpenAI Platform or compatible relay credential reference. */
@@ -46,7 +51,9 @@ const Config = z.object({
46
51
  seedreamBaseURL: z.string().default(DEFAULT_SEEDREAM_BASE_URL),
47
52
  seedreamModel: z.string().default(DEFAULT_SEEDREAM_MODEL),
48
53
  dashscopeEndpoint: z.string().default(DEFAULT_DASHSCOPE_ENDPOINT),
49
- dashscopeModel: z.string().default(DEFAULT_DASHSCOPE_MODEL)
54
+ dashscopeModel: z.string().default(DEFAULT_DASHSCOPE_MODEL),
55
+ saveToWorkspace: z.boolean().default(true),
56
+ workspaceFolder: z.string().default(DEFAULT_WORKSPACE_FOLDER)
50
57
  });
51
58
  /** Resolve exactly one provider profile for a tool call. */
52
59
  function resolveProvider(config) {
@@ -458,6 +465,122 @@ async function readBoundedBytes(response, maxBytes) {
458
465
  return joined;
459
466
  }
460
467
  //#endregion
468
+ //#region lib/types/workspace-save.js
469
+ /** Persist one generated image as a file under the session workspace. */
470
+ /** File extension for each supported image media type. */
471
+ const EXTENSION = {
472
+ "image/png": "png",
473
+ "image/jpeg": "jpg",
474
+ "image/webp": "webp",
475
+ "image/gif": "gif"
476
+ };
477
+ /**
478
+ * Build the deterministic file name for a generated image:
479
+ * `image-<digest-prefix>.<ext>`. The digest prefix comes from the
480
+ * content-addressed attachment id, so the same image bytes always map to the
481
+ * same file name regardless of when they were generated, and re-saving simply
482
+ * overwrites the previous copy in place.
483
+ * @param attachmentId - durable attachment id (`sha256:<hex>`).
484
+ * @param mediaType - verified image media type.
485
+ * @returns the file name (no directory).
486
+ */
487
+ function workspaceImageName(attachmentId, mediaType) {
488
+ return `image-${(attachmentId.startsWith("sha256:") ? attachmentId.slice(7) : attachmentId).slice(0, 8).padEnd(8, "0")}.${EXTENSION[mediaType]}`;
489
+ }
490
+ /**
491
+ * Resolve the configured image folder inside the session workspace. The
492
+ * folder may nest, but must stay inside the workspace: absolute paths and
493
+ * parent-traversal segments are rejected for both separator styles.
494
+ *
495
+ * This lexical pass is necessary but not sufficient: `saveImageToWorkspace`
496
+ * additionally verifies the on-disk resolution so symlinked folders cannot
497
+ * escape the workspace.
498
+ * @param workspaceRoot - the session workspace directory.
499
+ * @param folder - configured subfolder; empty/blank means the workspace root.
500
+ * @returns the absolute image directory.
501
+ * @throws when the folder would escape the workspace root.
502
+ */
503
+ function workspaceImageDir(workspaceRoot, folder) {
504
+ const trimmed = (folder ?? "").trim();
505
+ const root = resolve(workspaceRoot);
506
+ const dir = trimmed === "" ? root : resolve(root, trimmed);
507
+ if (!containsPath(root, dir)) throw new Error(`image workspace folder '${folder}' must stay inside the session workspace`);
508
+ return dir;
509
+ }
510
+ /** True when `child` equals `parent` or lives underneath it (lexically). */
511
+ function containsPath(parent, child) {
512
+ const rel = relative(parent, child);
513
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
514
+ }
515
+ /**
516
+ * Real path of the closest existing ancestor of `dir` (inclusive). Walking up
517
+ * lets us validate symlinked folder segments before creating anything under
518
+ * them.
519
+ */
520
+ async function nearestExistingRealPath(dir) {
521
+ let probe = dir;
522
+ for (;;) try {
523
+ return await realpath(probe);
524
+ } catch (error) {
525
+ if (error?.code !== "ENOENT") throw error;
526
+ const parent = dirname(probe);
527
+ if (parent === probe) throw error;
528
+ probe = parent;
529
+ }
530
+ }
531
+ /** Reject a directory whose on-disk resolution lands outside the workspace. */
532
+ function assertInsideWorkspace(realRoot, candidate, folder) {
533
+ if (containsPath(realRoot, candidate)) return;
534
+ throw new Error(`image workspace folder '${folder ?? ""}' must stay inside the session workspace (${candidate} resolves outside ${realRoot})`);
535
+ }
536
+ /**
537
+ * Write one generated image durably under the session workspace.
538
+ *
539
+ * Containment is enforced twice: lexically by `workspaceImageDir`, then
540
+ * against real paths, so a configured folder (or any intermediate segment)
541
+ * that is a symlink pointing outside the workspace is rejected before and
542
+ * after anything is created.
543
+ *
544
+ * The bytes are written to a same-directory staging file and renamed onto the
545
+ * target, so a crash never leaves a half-written image under its final name.
546
+ * Re-saving identical bytes rewrites the same file (the name is content-
547
+ * addressed), which keeps repeated generations idempotent. A cancellation is
548
+ * honoured up to and including the final rename: an aborted save never
549
+ * resolves successfully and never leaves the image behind under its final
550
+ * name.
551
+ * @param options - workspace root, configured folder, attachment identity, and image bytes.
552
+ * @returns the absolute path of the written file.
553
+ */
554
+ async function saveImageToWorkspace(options) {
555
+ const dir = workspaceImageDir(options.workspaceRoot, options.folder);
556
+ options.signal?.throwIfAborted();
557
+ const realRoot = await realpath(resolve(options.workspaceRoot));
558
+ assertInsideWorkspace(realRoot, await nearestExistingRealPath(dir), options.folder);
559
+ const name = workspaceImageName(options.attachmentId, options.mediaType);
560
+ const target = join(dir, name);
561
+ const staging = join(dir, `.${name}.${process.pid}-${randomUUID()}.tmp`);
562
+ await mkdir(dir, { recursive: true });
563
+ assertInsideWorkspace(realRoot, await realpath(dir), options.folder);
564
+ try {
565
+ await writeFile(staging, options.data, {
566
+ flag: "wx",
567
+ signal: options.signal
568
+ });
569
+ options.signal?.throwIfAborted();
570
+ await rename(staging, target);
571
+ } catch (error) {
572
+ await unlink(staging).catch(() => {});
573
+ throw error;
574
+ }
575
+ try {
576
+ options.signal?.throwIfAborted();
577
+ } catch (error) {
578
+ await unlink(target).catch(() => {});
579
+ throw error;
580
+ }
581
+ return target;
582
+ }
583
+ //#endregion
461
584
  //#region lib/types/index.js
462
585
  /** Cordis plugin name. */
463
586
  const name = "dsh-image-gen";
@@ -484,7 +607,7 @@ function apply(ctx, config = {}) {
484
607
  }), "dsh-image-gen: image route");
485
608
  ctx.tools.register(defineTool({
486
609
  name: "generate_image",
487
- description: "Generate one image with the configured image provider. Use when the user explicitly asks to create or draw an image. Give a complete visual prompt including subject, composition, style, lighting, and any exact text that should appear. A successful image is already attached directly to the conversation and has no local file path; do not call read, glob, or other tools to locate or verify it.",
610
+ description: "Generate one image with the configured image provider. Use when the user explicitly asks to create or draw an image. Give a complete visual prompt including subject, composition, style, lighting, and any exact text that should appear. A successful image is already attached directly to the conversation; with workspace saving enabled (the default) it is also written as a file under the session workspace, and the result's savedTo field carries that absolute file path. Do not call read, glob, or other tools to locate or verify the image.",
488
611
  parameters: {
489
612
  prompt: {
490
613
  type: "string",
@@ -562,19 +685,25 @@ function apply(ctx, config = {}) {
562
685
  output: {
563
686
  type: "string",
564
687
  required: true
565
- }
688
+ },
689
+ savedTo: { type: "string" },
690
+ saveError: { type: "string" }
566
691
  }
567
692
  },
568
- render: (_args, value) => [{
569
- type: "text",
570
- text: `Generated one image with ${value.provider}/${value.model} (${value.output}). It is already attached to the conversation with no local file path; respond to the user without reading or searching for it.`
571
- }],
693
+ render: (_args, value) => {
694
+ const saved = typeof value.savedTo === "string" ? ` It was also saved to the workspace as ${value.savedTo}.` : typeof value.saveError === "string" ? ` Saving it to the workspace failed: ${value.saveError}.` : " It has no local file path.";
695
+ return [{
696
+ type: "text",
697
+ text: `Generated one image with ${value.provider}/${value.model} (${value.output}). It is already attached to the conversation.${saved} Respond to the user without reading or searching for the image.`
698
+ }];
699
+ },
572
700
  presentationMeta: (args, value) => ({
573
701
  kind: "dsh-image-gen",
574
702
  attachment: value.attachment,
575
703
  provider: value.provider,
576
704
  model: value.model,
577
705
  output: value.output,
706
+ ...typeof value.savedTo === "string" ? { savedTo: value.savedTo } : {},
578
707
  prompt: args.prompt
579
708
  })
580
709
  },
@@ -594,7 +723,7 @@ function apply(ctx, config = {}) {
594
723
  imageSize,
595
724
  maxBytes: ctx.attachments.imageLimits.maxImageBytes,
596
725
  signal: exec.signal
597
- }), active.provider, active.model, `${aspectRatio}, ${imageSize}`);
726
+ }), active.provider, active.model, `${aspectRatio}, ${imageSize}`, current(), exec);
598
727
  }
599
728
  if (active.provider === "dashscope") {
600
729
  const size = args.size ?? active.imageSize;
@@ -606,7 +735,7 @@ function apply(ctx, config = {}) {
606
735
  size,
607
736
  maxBytes: ctx.attachments.imageLimits.maxImageBytes,
608
737
  signal: exec.signal
609
- }), active.provider, active.model, size);
738
+ }), active.provider, active.model, size, current(), exec);
610
739
  }
611
740
  const size = args.size ?? active.imageSize;
612
741
  return saveGenerated(ctx, await generateOpenAICompatibleImage({
@@ -618,23 +747,48 @@ function apply(ctx, config = {}) {
618
747
  size,
619
748
  maxBytes: ctx.attachments.imageLimits.maxImageBytes,
620
749
  signal: exec.signal
621
- }), active.provider, active.model, size);
750
+ }), active.provider, active.model, size, current(), exec);
622
751
  },
623
752
  presentResult: (_args, result) => imagePresentation(result)
624
753
  }));
625
754
  }
626
- async function saveGenerated(ctx, generated, provider, model, output) {
755
+ /**
756
+ * Persist the generated image as a durable attachment, then — when workspace
757
+ * saving is enabled — also write it as a file under the calling agent's
758
+ * session workspace. A workspace write failure never discards the generated
759
+ * attachment: it is reported through `saveError` instead.
760
+ */
761
+ async function saveGenerated(ctx, generated, provider, model, output, config, exec) {
627
762
  if (!ctx.attachments.imageLimits.mediaTypes.includes(generated.mediaType)) throw new Error(`This DSH deployment does not accept ${generated.mediaType} generated images`);
628
- return {
629
- attachment: await ctx.attachments.saveImage({
630
- data: generated.data,
631
- mediaType: generated.mediaType,
632
- name: "generated-image"
633
- }),
763
+ const attachment = await ctx.attachments.saveImage({
764
+ data: generated.data,
765
+ mediaType: generated.mediaType,
766
+ name: "generated-image"
767
+ });
768
+ const value = {
769
+ attachment,
634
770
  provider,
635
771
  model,
636
772
  output
637
773
  };
774
+ if (config.saveToWorkspace === false) return value;
775
+ const workspaceRoot = exec.agent?.session.header.cwd;
776
+ if (workspaceRoot === void 0) return value;
777
+ try {
778
+ value.savedTo = await saveImageToWorkspace({
779
+ workspaceRoot,
780
+ folder: config.workspaceFolder,
781
+ attachmentId: attachment.attachmentId,
782
+ mediaType: generated.mediaType,
783
+ data: generated.data,
784
+ signal: exec.signal
785
+ });
786
+ } catch (error) {
787
+ exec.signal.throwIfAborted();
788
+ ctx.logger.warn(`dsh-image-gen: failed to save image to workspace: ${error instanceof Error ? error.message : String(error)}`);
789
+ value.saveError = error instanceof Error ? error.message : String(error);
790
+ }
791
+ return value;
638
792
  }
639
793
  function imagePresentation(result) {
640
794
  const attachment = imageAttachmentFromMeta(result.meta);
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * Lightweight IndexedDB persistence layer for Image Generation Gallery.
3
3
  * Stores lightweight metadata indexes; image binaries remain managed by DSH Attachment service.
4
+ * Supports tombstones to ensure deleted items are never resurrected when revisiting conversations.
4
5
  */
5
6
  import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment';
6
7
  import type { ImageProvider } from '../shared.js';
@@ -22,6 +23,7 @@ type GalleryListener = () => void;
22
23
  export declare function subscribeGallery(listener: GalleryListener): () => void;
23
24
  /**
24
25
  * Save or update a gallery record by attachmentId.
26
+ * Skipped if the item was previously deleted (tombstoned).
25
27
  */
26
28
  export declare function saveGalleryItem(item: Omit<GalleryItem, 'createdAt'> & {
27
29
  createdAt?: number;
@@ -31,11 +33,11 @@ export declare function saveGalleryItem(item: Omit<GalleryItem, 'createdAt'> & {
31
33
  */
32
34
  export declare function getGalleryItems(): Promise<GalleryItem[]>;
33
35
  /**
34
- * Delete a single gallery record by ID.
36
+ * Delete a single gallery record by ID and record a tombstone.
35
37
  */
36
38
  export declare function deleteGalleryItem(id: string): Promise<void>;
37
39
  /**
38
- * Clear all gallery records.
40
+ * Clear all gallery records and reset tombstones.
39
41
  */
40
42
  export declare function clearGallery(): Promise<void>;
41
43
  export {};
@@ -17,6 +17,7 @@ declare const DICT: {
17
17
  readonly filterGoogle: "Google Gemini";
18
18
  readonly filterOpenAI: "OpenAI / 中转站";
19
19
  readonly filterSeedream: "字节 Seedream";
20
+ readonly filterDashScope: "阿里 DashScope";
20
21
  readonly emptyTitle: "暂无生图记录";
21
22
  readonly emptyDesc: "在对话中让 Agent 生图后,生成的图片会自动收录到这里。";
22
23
  readonly noMatchTitle: "未找到匹配结果";
@@ -28,6 +29,9 @@ declare const DICT: {
28
29
  readonly download: "下载图片";
29
30
  readonly copyImg: "复制图片";
30
31
  readonly copyPpt: "复制 Prompt";
32
+ readonly delete: "从画廊删除";
33
+ readonly confirmDelete: "确定要从画廊中删除这张图片吗?(不会影响原聊天记录)";
34
+ readonly deleted: "已从画廊删除";
31
35
  readonly model: "模型";
32
36
  readonly prompt: "Prompt";
33
37
  readonly close: "关闭 (Esc)";
@@ -39,6 +43,7 @@ declare const DICT: {
39
43
  readonly filterGoogle: "Google Gemini";
40
44
  readonly filterOpenAI: "OpenAI / Relay";
41
45
  readonly filterSeedream: "ByteDance Seedream";
46
+ readonly filterDashScope: "Aliyun DashScope";
42
47
  readonly emptyTitle: "No images generated yet";
43
48
  readonly emptyDesc: "Images generated during conversations will automatically appear here.";
44
49
  readonly noMatchTitle: "No matching images";
@@ -50,6 +55,9 @@ declare const DICT: {
50
55
  readonly download: "Download";
51
56
  readonly copyImg: "Copy Image";
52
57
  readonly copyPpt: "Copy Prompt";
58
+ readonly delete: "Delete from gallery";
59
+ readonly confirmDelete: "Are you sure you want to remove this image from the gallery? (Chat history will not be affected)";
60
+ readonly deleted: "Deleted from gallery";
53
61
  readonly model: "Model";
54
62
  readonly prompt: "Prompt";
55
63
  readonly close: "Close (Esc)";
@@ -15,6 +15,8 @@ interface ImageSettings {
15
15
  seedreamModel?: string;
16
16
  dashscopeEndpoint?: string;
17
17
  dashscopeModel?: string;
18
+ saveToWorkspace?: boolean;
19
+ workspaceFolder?: string;
18
20
  }
19
21
  interface SettingsFace {
20
22
  scope: SettingsScope<ImageSettings>;
@@ -2,6 +2,8 @@
2
2
  import z from '@deepseek-ai/schemastery';
3
3
  import { DEFAULT_DASHSCOPE_ENDPOINT, DEFAULT_DASHSCOPE_MODEL, DEFAULT_GOOGLE_ENDPOINT, DEFAULT_GOOGLE_MODEL, DEFAULT_OPENAI_BASE_URL, DEFAULT_OPENAI_MODEL, DEFAULT_SEEDREAM_BASE_URL, DEFAULT_SEEDREAM_MODEL, IMAGE_PROVIDERS, type ImageProvider } from './shared.js';
4
4
  export { DEFAULT_DASHSCOPE_ENDPOINT, DEFAULT_DASHSCOPE_MODEL, DEFAULT_GOOGLE_ENDPOINT, DEFAULT_GOOGLE_MODEL, DEFAULT_OPENAI_BASE_URL, DEFAULT_OPENAI_MODEL, DEFAULT_SEEDREAM_BASE_URL, DEFAULT_SEEDREAM_MODEL, IMAGE_PROVIDERS, type ImageProvider, };
5
+ /** Default workspace subfolder that receives generated image files. */
6
+ export declare const DEFAULT_WORKSPACE_FOLDER = "dsh-image-gen";
5
7
  /** Google API credential reference. */
6
8
  export declare const GOOGLE_API_KEY_ENV = "GEMINI_API_KEY";
7
9
  /** OpenAI Platform or compatible relay credential reference. */
@@ -26,6 +28,10 @@ export interface Config {
26
28
  seedreamModel?: string;
27
29
  dashscopeEndpoint?: string;
28
30
  dashscopeModel?: string;
31
+ /** Also write every generated image as a file under the session workspace. */
32
+ saveToWorkspace?: boolean;
33
+ /** Workspace subfolder for generated images; empty means the workspace root. */
34
+ workspaceFolder?: string;
29
35
  }
30
36
  /** Cordis configuration schema. */
31
37
  export declare const Config: z<Config>;
@@ -0,0 +1,52 @@
1
+ import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment';
2
+ /**
3
+ * Build the deterministic file name for a generated image:
4
+ * `image-<digest-prefix>.<ext>`. The digest prefix comes from the
5
+ * content-addressed attachment id, so the same image bytes always map to the
6
+ * same file name regardless of when they were generated, and re-saving simply
7
+ * overwrites the previous copy in place.
8
+ * @param attachmentId - durable attachment id (`sha256:<hex>`).
9
+ * @param mediaType - verified image media type.
10
+ * @returns the file name (no directory).
11
+ */
12
+ export declare function workspaceImageName(attachmentId: string, mediaType: ImageAttachmentRef['mediaType']): string;
13
+ /**
14
+ * Resolve the configured image folder inside the session workspace. The
15
+ * folder may nest, but must stay inside the workspace: absolute paths and
16
+ * parent-traversal segments are rejected for both separator styles.
17
+ *
18
+ * This lexical pass is necessary but not sufficient: `saveImageToWorkspace`
19
+ * additionally verifies the on-disk resolution so symlinked folders cannot
20
+ * escape the workspace.
21
+ * @param workspaceRoot - the session workspace directory.
22
+ * @param folder - configured subfolder; empty/blank means the workspace root.
23
+ * @returns the absolute image directory.
24
+ * @throws when the folder would escape the workspace root.
25
+ */
26
+ export declare function workspaceImageDir(workspaceRoot: string, folder: string | undefined): string;
27
+ /**
28
+ * Write one generated image durably under the session workspace.
29
+ *
30
+ * Containment is enforced twice: lexically by `workspaceImageDir`, then
31
+ * against real paths, so a configured folder (or any intermediate segment)
32
+ * that is a symlink pointing outside the workspace is rejected before and
33
+ * after anything is created.
34
+ *
35
+ * The bytes are written to a same-directory staging file and renamed onto the
36
+ * target, so a crash never leaves a half-written image under its final name.
37
+ * Re-saving identical bytes rewrites the same file (the name is content-
38
+ * addressed), which keeps repeated generations idempotent. A cancellation is
39
+ * honoured up to and including the final rename: an aborted save never
40
+ * resolves successfully and never leaves the image behind under its final
41
+ * name.
42
+ * @param options - workspace root, configured folder, attachment identity, and image bytes.
43
+ * @returns the absolute path of the written file.
44
+ */
45
+ export declare function saveImageToWorkspace(options: {
46
+ workspaceRoot: string;
47
+ folder?: string | undefined;
48
+ attachmentId: string;
49
+ mediaType: ImageAttachmentRef['mediaType'];
50
+ data: Uint8Array;
51
+ signal?: AbortSignal;
52
+ }): Promise<string>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-image-gen",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "description": "Bring ChatGPT-like image generation to DeepSeek Harness — Gemini, OpenAI, Seedream, DashScope & more.",
5
5
  "type": "module",
6
6
  "author": "shanliuling",