@alpacachen/dsh-kanban 1.9.0 → 1.10.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,125 @@
1
+ # 使用指南
2
+
3
+ [返回首页](../README.zh.md) · [English](guide.md)
4
+
5
+ ## 使用看板
6
+
7
+ | 操作 | 使用方式 |
8
+ | --- | --- |
9
+ | 查找任务 | 顶部搜索卡片 ID、标题、描述、评论;右侧三个按钮按优先级、标签、截止日期筛选。 |
10
+ | 管理看板 | 右上角**设置**菜单提供刷新、列编辑、标签编辑和「反馈与建议 · GitHub」。 |
11
+ | 推进任务 | 创建、编辑、删除卡片,拖动排序或移到其他列,添加彩色标签与 P0 / P1 / P2 优先级。 |
12
+ | 查看详情 | 可调整宽度的侧边抽屉,窄屏自动铺满;描述支持 Markdown 编辑与预览。 |
13
+ | 添加图片 | 文件选择、剪贴板粘贴、拖拽上传;卡片展示图片数量,详情中可预览、移除和重试。 |
14
+ | 跟踪时间 | 设置截止日期,查看今天到期或逾期任务;进入完成列后自动记录完成日期。 |
15
+ | 协作记录 | 与 Agent 互相评论,查看活动时间线,或将任务带入当前/新会话继续处理。 |
16
+
17
+ 文字和 Markdown 描述编辑后点击**保存**;**完成编辑**只切回预览。筛选条件在工具栏下方显示,点击条件的 × 或在对应菜单选择「全部」即可清除。
18
+
19
+ ### 从任意卡片继续与 Agent 协作
20
+
21
+ 打开卡片并选择 **「与 Agent 聊一聊」**,dsh-kanban 会把卡片 ID、标题、标签、截止日期和备注带入当前会话或一个新会话。已保存的图片会一起加入目标聊天框,显示为可预览、可移除的附件。文字和图片都只进入草稿,由你确认后发送,不会自动提交;读取图片失败时会保留任务详情并提示重试。
22
+
23
+ <details>
24
+ <summary>较早版本的深色模式与 Markdown 任务详情</summary>
25
+
26
+ ![查看深色模式与 Markdown 任务详情](screenshots/card-details-dark.png)
27
+
28
+ 界面示意:截图为较早版本。
29
+
30
+ </details>
31
+
32
+ ## 对话示例
33
+
34
+ 从你正在做的事开始。把下面例子里的项目名称和背景换成自己的,就可以直接发给 Agent。
35
+
36
+ **把需求拆成可验收的任务**
37
+
38
+ > 下周要上线手机号登录。先看看已有卡片,再为缺少的接口、验证码、防刷、前端交互和测试工作建卡。写清依赖关系,并在描述里用 Markdown 列出实现步骤和验收标准。影响上线的任务标为 P0,其余排好优先级。
39
+
40
+ **接手一项正在做的工作**
41
+
42
+ > 接着处理「登录后跳回登录页」。先读完整描述和评论,梳理已有结论与下一步,移到 In Progress。推进过程和测试结果记到评论,完成后移到 Review 等我验收。
43
+
44
+ <details>
45
+ <summary>更多示例:阻塞跟进、周会与职业工作流</summary>
46
+
47
+ **跟进被外部依赖卡住的事项**
48
+
49
+ > 「支付联调」还在等对方提供测试账号。建一个 Blocked 列表(已有就复用),把任务移过去,并在评论里记录阻塞原因、待确认的联系人,以及拿到账号后的下一步。
50
+
51
+ **用现有看板准备周会**
52
+
53
+ > 根据当前卡片的状态、描述和评论,整理周会提纲:已完成什么、哪些工作还在推进、有哪些阻塞需要协调。引用相关卡片,给出接下来最值得推进的三件事;信息不全的地方列成待确认项。
54
+
55
+ **为自己的职业建立工作流**
56
+
57
+ > 我是一名律师,要同时跟进合同审查和案件材料准备。帮我整理适合的阶段列表与标签,把我下面提供的事项逐一建卡,在描述里记录交付要求、材料清单和约定时间;缺少材料的放到「等待补充」。
58
+
59
+ </details>
60
+
61
+ ## 使用规则
62
+
63
+ <details>
64
+ <summary>搜索范围、图片限制与保存行为</summary>
65
+
66
+ ### 搜索任务
67
+
68
+ 搜索范围是当前工作区的卡片 ID、标题、完整描述和评论正文,按连续子串匹配,忽略大小写及首尾空格。搜索与所有已选筛选条件取交集,保留原有卡片顺序,切换工作区后清空。Agent 通过 `kanban_get` 的 `{"query":"登录"}` 参数使用相同规则。
69
+
70
+ ### 添加与查看图片
71
+
72
+ 支持 PNG、JPEG、WebP,每张最多 10 MiB,每张卡片最多 10 张;DSH Host 可进一步限制格式或大小。新建卡片时,选中的图片先保留在浏览器,点击**「保存」**成功创建任务后再上传。部分上传失败时,任务和成功的图片已保存,详情保留失败文件供重试,不会重复建卡。创建前取消不会上传。已有卡片的图片上传和移除立即保存,文字修改仍需点击**「保存」**。Host 不支持图片或工作区无法持久保存时,界面会提示无法上传。
73
+
74
+ 点击缩略图打开 DSH 原生大图预览;按 Esc、点击关闭按钮或遮罩返回任务详情。图片不会加入文字搜索范围,暂不提供 OCR。
75
+
76
+ </details>
77
+
78
+ ## 数据与备份
79
+
80
+ 卡片的 `images` 数组中,每张图片只保存 `attachmentId`、`mediaType`、`bytes`、`width`、`height` 五个字段,不保存文件名和说明。数据格式 v6 为旧卡片补充 `images: []`,迁移前备份原看板文件。工作区的 `.dsh-kanban.json` 只保存引用,图片文件保存在 DSH home 下的原生附件存储中,独立于具体工作区或会话,可被复用。备份时需要同时保留看板文件与 DSH 附件存储。移除图片或删除卡片只解除关联,不物理删除共享图片。
81
+
82
+ ## Agent 工具参考
83
+
84
+ 插件为每个工作区中的 Agent 提供 19 个工具:
85
+
86
+ | 范围 | 工具 |
87
+ | --- | --- |
88
+ | **看板** | `kanban_get`、`kanban_set_completed_column` |
89
+ | **卡片** | `kanban_get_card`、`kanban_add_comment`、`kanban_add_card`、`kanban_update_card`、`kanban_delete_card`、`kanban_move_card` |
90
+ | **图片** | `kanban_add_image`、`kanban_read_image`、`kanban_remove_image` |
91
+ | **列表** | `kanban_add_column`、`kanban_rename_column`、`kanban_delete_column`、`kanban_move_column` |
92
+ | **标签** | `kanban_get_label`、`kanban_add_label`、`kanban_update_label`、`kanban_delete_label` |
93
+
94
+ <details>
95
+ <summary>图片参数与访问范围</summary>
96
+
97
+ Agent 添加图片时,先创建卡片,再把返回的 `cardId` 作为 `id`。调用 `kanban_add_image`,参数任选一种来源:
98
+
99
+ ```json
100
+ {"id":"k1","source":{"kind":"workspace_file","path":"screenshots/login.png"}}
101
+ ```
102
+
103
+ ```json
104
+ {"id":"k1","source":{"kind":"session_attachment","attachmentId":"sha256:<实际附件哈希>"}}
105
+ ```
106
+
107
+ 文件路径必须相对于当前工作区,且不能越过工作区边界。会话附件必须真实存在于执行 Agent 的当前会话中,使用真实 ID,不猜测哈希;不传 base64 或远程 URL。重复添加同一图片不会重复关联。`kanban_get` 返回图片数量,`kanban_get_card` 返回五字段图片引用。查看图片时调用 `kanban_read_image`,参数为 `{"id":"k1","attachmentId":"sha256:<实际附件哈希>"}`;移除时用相同参数调用 `kanban_remove_image`。两者都会校验图片属于当前工作区的指定卡片。
108
+
109
+ </details>
110
+
111
+ <details>
112
+ <summary>Markdown 描述、截止日期与完成状态</summary>
113
+
114
+ `kanban_add_card` 和 `kanban_update_card` 的任务描述仍使用 `note` 字段,传入保留换行的 Markdown 原文,不传 HTML。任务详情会渲染标题、列表、表格和代码块。原文最多 2,000 字符,Markdown 标记和换行也计入长度,超出会截断并返回警告。修改已有描述前,应先调用 `kanban_get_card` 读取完整原文(`kanban_get` 只返回摘要)。传入 `note` 会替换整段描述;省略则保留原文,传空字符串则清空。评论仍为纯文本。
115
+
116
+ 完成日期在卡片进入完成列时自动记录(包括直接在完成列创建),移出时清空,再次完成时记录新时间。修改内容、评论、同列排序和列改名/排序不影响完成日期。卡片详情在截止日期旁以本地时区只读展示;两个读取工具均返回 UTC ISO 时间戳 `completedAt` 或 `null`,已完成卡片的 `null` 表示时间未知。更换或清除完成列会重置完成时间,新完成列中已有卡片显示未知;删除列引发自动移动时也遵循进入/离开完成状态的规则。从 v5 之前的数据升级时,历史完成时间保留未知,不根据活动日志推测。
117
+
118
+ `kanban_add_card` 和 `kanban_update_card` 可通过 `dueDate` 设置截止日期,值为真实有效的 `YYYY-MM-DD` 日期。省略则保留原日期(新卡片默认为无日期),传 `null` 或空字符串则清空。日期不含时间和时区:今天到期的任务到本地次日才算逾期。「本周五」等相对日期应由 Agent 按用户本地日期换算,并向用户确认具体日期,不要直接传相对文本或 UTC 时间戳。`kanban_get` 和 `kanban_get_card` 都会返回截止日期与看板的 `completedColumnId`。
119
+
120
+ 使用 `kanban_set_completed_column`,传已有的 `columnId` 指定完成列,传 `null` 清除设置。新看板默认使用 Done,已有看板需要明确选择一次。设置跟随列 ID,改名和排序不影响;删除完成列会清除设置。完成列中的卡片保留日期,但不计入「今天到期」和「已逾期」筛选,移回其他列后恢复判断。暂不包含自动提醒和按日期自动排序。
121
+
122
+ > 把「支付联调」的截止日期设为本周五,再列出今天到期和已经逾期的未完成任务,方便我安排先做哪几件事。
123
+
124
+ </details>
125
+
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,36 @@
1
+ # Validation
2
+
3
+ Use Node.js 26 and pnpm 11.8.0. The committed `lib/client.js` is the distributable client bundle.
4
+
5
+ ```sh
6
+ pnpm install --frozen-lockfile
7
+ pnpm typecheck
8
+ pnpm test
9
+ pnpm build
10
+ pnpm check:client-bundle
11
+ pnpm check:package
12
+ git diff --exit-code -- lib/client.js
13
+ ```
14
+
15
+ `pnpm test` covers unit/component contracts, schema migration and the persistence pipeline. Component tests substitute the Host UI boundary; they do not establish native desktop behavior. `pnpm build` must reproduce the committed bundle after source changes have been built and committed.
16
+
17
+ ## Native image storage
18
+
19
+ With an installed DSH runtime that provides `@deepseek-ai/dsh-fs-local`, `@deepseek-ai/dsh-attachment-local`, and `sharp`:
20
+
21
+ ```sh
22
+ DSH_RUNTIME_ROOT=/path/to/dsh/node_modules node scripts/test-agent-images-native.mjs
23
+ ```
24
+
25
+ This test creates its own temporary workspace and attachment store. It covers decoding and persistence, five-field references, real image content blocks, symlink/cross-card rejection and reloading after a fresh Cordis context. The current-session authorization controller is a fixture; no model is called.
26
+
27
+ ## Optional isolated Host checks
28
+
29
+ - `scripts/test-images-integration.mjs`: real HTTP upload/read/remove and native persistence. Requires an explicitly supplied temporary `DSH_TEST_HOME`, loopback `DSH_TEST_URL`, temporary `DSH_TEST_WORKSPACE_ID`, `DSH_TEST_LOG`, and `DSH_RUNTIME_ROOT`. Set `PLAYWRIGHT_MODULE` if Playwright is not locally resolvable. Never point it at a personal profile.
30
+ - `scripts/test-search-images-browser.mjs`: actual client bundle and Host theme with intercepted API fixtures for upload failures, retries, search, and responsive screenshots. Configure `DSH_TEST_URL`, `PLAYWRIGHT_MODULE`, and optionally `CHROME_PATH`, `DSH_TEST_LOG`, and `UI_SCREENSHOT_DIR`. It is not a real-backend test.
31
+
32
+ Keep authentication logs, generated reports, and personal-workspace screenshots out of commits.
33
+
34
+ ## Desktop acceptance
35
+
36
+ Verify the actual installed plugin: search and the three adjacent filters, Settings actions, image selection/paste/drop, native full-size preview, Escape/close/backdrop behavior, and task-draft preservation. Check both current- and new-conversation handoff: saved task images must appear as removable composer attachments without submitting the message. Use disposable test tasks for writes.
package/index.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { matchCardSearch } from './search.js'
2
+
1
3
  /**
2
4
  * dsh-kanban: DSH bundle host plugin (standard Cordis function plugin).
3
5
  *
@@ -7,11 +9,11 @@
7
9
  * Responsibilities:
8
10
  * - Workspace isolation: boards are keyed by workspaceId, one board per workspace.
9
11
  * - Persistence: ctx.fs writes <workspace.path>/.dsh-kanban.json.
10
- * - Agent tools: ctx.tools.register exposes 16 kanban_* tools.
12
+ * - Agent tools: ctx.tools.register exposes 19 kanban_* tools.
11
13
  * - Browser API: ctx.get('connection') registers the authenticated /api/kanban route.
12
14
  *
13
15
  * Per-workspace data model (disk files include schemaVersion):
14
- * schemaVersion: 5
16
+ * schemaVersion: 6
15
17
  * completedColumnId: string | null
16
18
  * columns: [{ id, title }]
17
19
  * labels: [{ name, color }] // name is the unique key and binds the color
@@ -46,7 +48,7 @@ export const inject = ['tools']
46
48
  // Back up old files before following the migration chain on first access.
47
49
  // ---------------------------------------------------------------------------
48
50
 
49
- export const SCHEMA_VERSION = 5
51
+ export const SCHEMA_VERSION = 6
50
52
  export const LEGACY_VERSION = 0
51
53
 
52
54
  // Append-only activity log persisted with the board; drop oldest events above the limit.
@@ -60,6 +62,20 @@ export const NOTE_LIMIT = 2000
60
62
  export const LABEL_LIMIT = 20
61
63
  export const COLUMN_TITLE_LIMIT = 40
62
64
  export const COMMENT_LIMIT = 2000
65
+ export const MAX_IMAGE_BYTES = 10 * 1024 * 1024
66
+ export const MAX_CARD_IMAGES = 10
67
+ const IMAGE_TYPES = ['image/png', 'image/jpeg', 'image/webp']
68
+ const imageRef = ({ attachmentId, mediaType, bytes, width, height }) => ({ attachmentId, mediaType, bytes, width, height })
69
+ const validImageRef = (image) => isObj(image)
70
+ && /^sha256:[a-f0-9]{64}$/.test(image.attachmentId)
71
+ && IMAGE_TYPES.includes(image.mediaType)
72
+ && ['bytes', 'width', 'height'].every((field) => Number.isSafeInteger(image[field]) && image[field] > 0)
73
+ const imageType = (bytes) => {
74
+ if (bytes.length >= 8 && Buffer.from(bytes.subarray(0, 8)).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return 'image/png'
75
+ if (bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return 'image/jpeg'
76
+ if (bytes.length >= 12 && Buffer.from(bytes.subarray(0, 4)).toString() === 'RIFF' && Buffer.from(bytes.subarray(8, 12)).toString() === 'WEBP') return 'image/webp'
77
+ throw new Error('Only PNG, JPEG and WebP images are supported')
78
+ }
63
79
 
64
80
  const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v)
65
81
  const strField = (v, fb) => (typeof v === 'string' && v ? v : fb)
@@ -145,6 +161,11 @@ export const MIGRATIONS = {
145
161
  completedColumnId: null,
146
162
  cards: Array.isArray(data.cards) ? data.cards.map((card) => isObj(card) ? { ...card, dueDate: null } : card) : data.cards,
147
163
  }),
164
+ 5: (data) => ({
165
+ ...data,
166
+ schemaVersion: 6,
167
+ cards: Array.isArray(data.cards) ? data.cards.map((card) => isObj(card) ? { ...card, images: [] } : card) : data.cards,
168
+ }),
148
169
  4: (data) => ({
149
170
  ...data,
150
171
  schemaVersion: 5,
@@ -238,6 +259,7 @@ export function validateBoard(data) {
238
259
  errors.push('duplicate card id: ' + c.id)
239
260
  break
240
261
  }
262
+ if (!Array.isArray(c.images) || c.images.length > MAX_CARD_IMAGES || c.images.some((image) => !validImageRef(image)) || new Set(c.images.map((image) => image.attachmentId)).size !== c.images.length) errors.push('card images contain invalid or duplicate references: ' + c.id)
241
263
  if (!columnIds.has(c.columnId)) errors.push('card references missing column: ' + c.id)
242
264
  if (c.label != null && !labelNames.has(c.label)) errors.push('card references missing label: ' + c.id)
243
265
  if (c.dueDate !== null && !isDueDate(c.dueDate)) errors.push('card has invalid due date: ' + c.id)
@@ -362,6 +384,15 @@ export function apply(ctx) {
362
384
  const getFs = () => ctx.get('fs')
363
385
  const getPolicy = () => ctx.get('sandboxPolicy')
364
386
  const getWorkspaceRegistry = () => ctx.get('workspaceRegistry')
387
+ const getAttachments = () => ctx.get('attachments')
388
+ const imageLimits = () => {
389
+ const store = getAttachments()
390
+ const limits = store?.imageLimits
391
+ if (!limits || typeof store.saveImage !== 'function' || typeof store.readImage !== 'function') return null
392
+ const mediaTypes = IMAGE_TYPES.filter((type) => limits.mediaTypes.includes(type))
393
+ const maxImageBytes = Math.min(MAX_IMAGE_BYTES, limits.maxImageBytes)
394
+ return mediaTypes.length && maxImageBytes > 0 ? { maxImageBytes, maxImagesPerCard: MAX_CARD_IMAGES, mediaTypes } : null
395
+ }
365
396
 
366
397
  const boards = new Map() // workspaceId -> { columns, labels, cards }
367
398
  const boardLoads = new Map() // workspaceId -> Promise<board>; publish only fully initialized boards
@@ -550,7 +581,7 @@ export function apply(ctx) {
550
581
  const target = await targetOf(workspace)
551
582
  const key = workspaceKey(workspace)
552
583
  const board = boards.get(key)
553
- if (!fs || !target || !board) return
584
+ if (!fs || !target || !board) return false
554
585
  try {
555
586
  await fs.writeText(
556
587
  target,
@@ -566,6 +597,7 @@ export function apply(ctx) {
566
597
  undefined,
567
598
  writePolicyFor(workspace, session),
568
599
  )
600
+ return true
569
601
  } catch (err) {
570
602
  console.log('dsh-kanban: Save failed ' + key + ': ' + ((err && err.message) || err))
571
603
  throw err
@@ -606,6 +638,7 @@ export function apply(ctx) {
606
638
  completedAt: c.completedAt,
607
639
  createdAt: typeof c.createdAt === 'string' ? c.createdAt : null,
608
640
  createdBy: typeof c.createdBy === 'string' ? c.createdBy : null,
641
+ images: c.images.map(imageRef),
609
642
  comments: Array.isArray(c.comments)
610
643
  ? c.comments.map((comment) => ({
611
644
  id: comment.id,
@@ -634,6 +667,7 @@ export function apply(ctx) {
634
667
  dueDate: c.dueDate,
635
668
  completedAt: c.completedAt,
636
669
  commentCount: c.comments.length,
670
+ imageCount: c.images.length,
637
671
  })),
638
672
  })
639
673
 
@@ -651,20 +685,56 @@ export function apply(ctx) {
651
685
  }
652
686
 
653
687
  // ---- Core operations shared by agent tools and browser HTTP ----
654
- const READ_METHODS = new Set(['get', 'getCard'])
688
+ const READ_METHODS = new Set(['get', 'getCard', '_getImage'])
655
689
  const dispatchUnlocked = async (workspace, method, args, source, session) => {
656
690
  const board = await boardOf(workspace, session)
657
691
  const a = args || {}
658
692
  const actor = source === 'agent' ? 'agent' : 'human'
659
693
  const persisted = () => persistedFlag(workspace)
660
- const result = (extra) => ({ board: cloneBoard(board), persisted: persisted(), warnings: takeWarnings(board), ...extra })
694
+ const result = (extra) => ({ board: cloneBoard(board), persisted: persisted(), imageLimits: imageLimits(), warnings: takeWarnings(board), ...extra })
661
695
  if (!READ_METHODS.has(method) && board.readOnlyReason) {
662
696
  return result({ error: board.readOnlyReason })
663
697
  }
664
698
 
665
699
  switch (method) {
666
- case 'get':
667
- return { board: cloneBoard(board), persisted: persisted(), warnings: takeWarnings(board), message: 'Board loaded' }
700
+ case 'get': {
701
+ if (a.query !== undefined && (typeof a.query !== 'string' || a.query.length > 200)) return result({ error: 'Search query must be at most 200 characters' })
702
+ const copy = cloneBoard(board)
703
+ copy.cards = copy.cards.filter((card) => matchCardSearch(card, a.query))
704
+ return result({ board: copy, message: 'Board loaded' })
705
+ }
706
+
707
+ case '_getImage': {
708
+ const card = findCard(board, a.id)
709
+ const image = card?.images.find((item) => item.attachmentId === a.attachmentId)
710
+ return image ? { image: imageRef(image) } : { error: 'Image not found on this card' }
711
+ }
712
+
713
+ case '_addImage': {
714
+ const card = findCard(board, a.id)
715
+ if (!card) return result({ error: 'Card not found: ' + str(a.id, '') })
716
+ if (!persisted()) return result({ error: 'Images require persistent workspace storage' })
717
+ if (!validImageRef(a.image)) return result({ error: 'Invalid image reference' })
718
+ if (card.images.some((image) => image.attachmentId === a.image.attachmentId)) return result({ message: 'Image already added' })
719
+ if (card.images.length >= MAX_CARD_IMAGES) return result({ error: 'A card can contain at most ' + MAX_CARD_IMAGES + ' images' })
720
+ card.images.push(imageRef(a.image))
721
+ record(board, { cardId: card.id, type: 'card_image_added', source: actor })
722
+ if (!await save(workspace, session)) throw new Error('Image association could not be persisted')
723
+ return result({ message: 'Image added' })
724
+ }
725
+
726
+ case 'removeImage': {
727
+ const card = findCard(board, a.id)
728
+ if (!card) return result({ error: 'Card not found: ' + str(a.id, '') })
729
+ if (!persisted()) return result({ error: 'Images require persistent workspace storage' })
730
+ const index = card.images.findIndex((image) => image.attachmentId === a.attachmentId)
731
+ if (index < 0) return result({ error: 'Image not found on this card' })
732
+ card.images.splice(index, 1)
733
+ // DSH objects may be shared by other cards and conversations.
734
+ record(board, { cardId: card.id, type: 'card_image_removed', source: actor })
735
+ if (!await save(workspace, session)) throw new Error('Image removal could not be persisted')
736
+ return result({ message: 'Image removed' })
737
+ }
668
738
 
669
739
  case 'getCard': {
670
740
  const card = cloneBoard(board).cards.find((c) => c.id === str(a.id, ''))
@@ -689,6 +759,7 @@ export function apply(ctx) {
689
759
  createdAt: new Date().toISOString(),
690
760
  createdBy: actor,
691
761
  comments: [],
762
+ images: [],
692
763
  }
693
764
  card.completedAt = col.id === board.completedColumnId ? card.createdAt : null
694
765
  board.cards.push(card)
@@ -705,7 +776,7 @@ export function apply(ctx) {
705
776
  },
706
777
  })
707
778
  await save(workspace, session)
708
- return result({ message: 'Card added to "' + col.title + '"' })
779
+ return result({ cardId: card.id, message: 'Card added to "' + col.title + '"' })
709
780
  }
710
781
 
711
782
  case 'updateCard': {
@@ -957,6 +1028,62 @@ export function apply(ctx) {
957
1028
  return run
958
1029
  }
959
1030
 
1031
+ const requireImages = () => {
1032
+ const limits = imageLimits()
1033
+ if (!limits) throw new Error('Image attachments require a DSH image storage service')
1034
+ return limits
1035
+ }
1036
+ const checkImageTarget = async (workspace, id, session) => {
1037
+ const board = await boardOf(workspace, session)
1038
+ if (board.readOnlyReason) throw new Error(board.readOnlyReason)
1039
+ if (!await targetOf(workspace)) throw new Error('Images require persistent workspace storage')
1040
+ if (writePolicyFor(workspace, session).mode === 'read-only') throw new Error('Workspace is read-only')
1041
+ const card = findCard(board, id)
1042
+ if (!card) throw new Error('Card not found: ' + str(id, ''))
1043
+ return card
1044
+ }
1045
+ const storeImage = async (workspace, id, data, mediaType, source, session) => {
1046
+ const limits = requireImages()
1047
+ await checkImageTarget(workspace, id, session)
1048
+ if (!limits.mediaTypes.includes(mediaType)) throw new Error('Only PNG, JPEG and WebP images are supported')
1049
+ if (!data.byteLength || data.byteLength > limits.maxImageBytes) throw new Error('Image exceeds the allowed byte limit or is empty')
1050
+ // The DSH store fully decodes and validates bytes before publishing an image reference.
1051
+ const image = await getAttachments().saveImage({ data, mediaType })
1052
+ return dispatch(workspace, '_addImage', { id, image }, source, session)
1053
+ }
1054
+ const importImage = async (workspace, args, exec) => {
1055
+ const session = exec?.agent?.session
1056
+ const limits = requireImages()
1057
+ await checkImageTarget(workspace, args.id, session)
1058
+ const source = args.source
1059
+ if (source?.kind === 'workspace_file') {
1060
+ if (typeof source.path !== 'string' || !source.path || source.path.includes('\0') || /^(?:[\\/]|[a-zA-Z]:)/.test(source.path)) throw new Error('Image path must be relative to the current workspace')
1061
+ const fs = getFs()
1062
+ if (typeof fs?.readBytes !== 'function' || typeof fs.contains !== 'function') throw new Error('This DSH filesystem cannot import images')
1063
+ const root = await fs.resolve(workspace.path)
1064
+ const target = await fs.resolve(source.path, { cwd: workspace.path })
1065
+ if (!fs.contains(root, target)) throw new Error('Image must be inside the current workspace')
1066
+ const data = await fs.readBytes(target, exec?.signal, limits.maxImageBytes)
1067
+ return storeImage(workspace, args.id, data, imageType(data), 'agent', session)
1068
+ }
1069
+ if (source?.kind === 'session_attachment') {
1070
+ const controller = ctx.get('sessionController')
1071
+ if (!session?.id || typeof controller?.attachment !== 'function') throw new Error('Current session image access is unavailable')
1072
+ // Only the current execution session can authorize an existing image reference.
1073
+ const stored = await controller.attachment({ sessionId: session.id, attachmentId: source.attachmentId })
1074
+ const image = stored.attachment
1075
+ if (!validImageRef(image) || image.bytes > limits.maxImageBytes || !limits.mediaTypes.includes(image.mediaType)) throw new Error('Session image exceeds the supported type or size limits')
1076
+ return dispatch(workspace, '_addImage', { id: args.id, image }, 'agent', session)
1077
+ }
1078
+ throw new Error('Expected a workspace_file or session_attachment image source')
1079
+ }
1080
+ const readCardImage = async (workspace, args, session, signal) => {
1081
+ requireImages()
1082
+ const result = await dispatch(workspace, '_getImage', args, 'agent', session)
1083
+ if (result.error) throw new Error(result.error)
1084
+ return getAttachments().readImage(result.image, signal)
1085
+ }
1086
+
960
1087
  // ---- Tool execution context and browser workspaceId resolution ----
961
1088
  const workspaceOfExec = async (exec) => {
962
1089
  const agent = exec && exec.agent
@@ -996,6 +1123,7 @@ export function apply(ctx) {
996
1123
  const r = await dispatch(workspace, method, args, 'agent', session)
997
1124
  return {
998
1125
  ok: !r.error,
1126
+ ...(r.cardId ? { cardId: r.cardId } : {}),
999
1127
  message: r.error || r.message || 'Done',
1000
1128
  board: summaryOfClone(r.board),
1001
1129
  warnings: Array.isArray(r.warnings) ? r.warnings : [],
@@ -1038,6 +1166,7 @@ export function apply(ctx) {
1038
1166
  const body = raw ? JSON.parse(raw) : {}
1039
1167
  if (!isObj(body)) return sendJson(400, { error: 'Expected a JSON object' })
1040
1168
  const method = typeof body.method === 'string' ? body.method : 'get'
1169
+ if (method.startsWith('_')) return sendJson(400, { error: 'Unknown kanban method' })
1041
1170
  const args = isObj(body.args) ? body.args : {}
1042
1171
  const workspaceId = typeof args.workspaceId === 'string' ? args.workspaceId : ''
1043
1172
  const workspace = workspaceId ? workspaceOfId(workspaceId) : undefined
@@ -1058,6 +1187,89 @@ export function apply(ctx) {
1058
1187
  fetch: httpHandler,
1059
1188
  }))
1060
1189
 
1190
+ const imageHttpHandler = async (req) => {
1191
+ try {
1192
+ if (!['GET', 'POST'].includes(req.method)) return sendJson(405, { error: 'Method not allowed' })
1193
+ const chunks = []
1194
+ let oversized = false
1195
+ if (req.method === 'POST' && req.body) {
1196
+ const maxBytes = imageLimits()?.maxImageBytes ?? MAX_IMAGE_BYTES
1197
+ const reader = req.body.getReader()
1198
+ let size = 0
1199
+ let timedOut = false
1200
+ const timeout = setTimeout(() => {
1201
+ timedOut = true
1202
+ void reader.cancel().catch(() => {})
1203
+ }, 30_000)
1204
+ try {
1205
+ // Connection destroys unread requests before its error response can flush; drain without buffering excess bytes.
1206
+ while (true) {
1207
+ const { done, value } = await reader.read()
1208
+ if (done) break
1209
+ if (!oversized) {
1210
+ size += value.byteLength
1211
+ oversized = size > maxBytes
1212
+ if (oversized) chunks.length = 0
1213
+ else chunks.push(value)
1214
+ }
1215
+ }
1216
+ } finally {
1217
+ clearTimeout(timeout)
1218
+ reader.releaseLock()
1219
+ }
1220
+ // shortcut: Connection may close timed-out uploads without a JSON response; revisit when its streaming bridge flushes before destroying requests.
1221
+ if (timedOut) return sendJson(408, { error: 'Image upload timed out' })
1222
+ }
1223
+ const url = new URL(req.url)
1224
+ const origin = req.headers.get('origin')
1225
+ const host = req.headers.get('host') || url.host
1226
+ if (origin) {
1227
+ let originHost = ''
1228
+ try { originHost = new URL(origin).host } catch {}
1229
+ if (originHost !== host) return sendJson(403, { error: 'Cross-origin request denied' })
1230
+ }
1231
+ const workspace = workspaceOfId(url.searchParams.get('workspaceId') || '')
1232
+ if (!workspace) return sendJson(400, { error: 'Unknown workspace' })
1233
+ const id = url.searchParams.get('cardId') || ''
1234
+ if (req.method === 'GET') {
1235
+ const attachmentId = url.searchParams.get('attachmentId') || ''
1236
+ const ref = await dispatch(workspace, '_getImage', { id, attachmentId }, 'human')
1237
+ if (ref.error) return sendJson(404, { error: ref.error })
1238
+ requireImages()
1239
+ const stored = await getAttachments().readImage(ref.image, req.signal)
1240
+ return new Response(stored.data.slice(), { headers: {
1241
+ 'Content-Type': stored.ref.mediaType,
1242
+ 'Content-Length': String(stored.data.byteLength),
1243
+ 'Cache-Control': 'private, no-store',
1244
+ 'X-Content-Type-Options': 'nosniff',
1245
+ 'Content-Security-Policy': "sandbox; default-src 'none'",
1246
+ } })
1247
+ }
1248
+ const limits = requireImages()
1249
+ const mediaType = (req.headers.get('content-type') || '').split(';', 1)[0].trim().toLowerCase()
1250
+ if (!limits.mediaTypes.includes(mediaType)) return sendJson(415, { error: 'Only PNG, JPEG and WebP images are supported' })
1251
+ if (oversized) return sendJson(413, { error: 'Image exceeds the allowed byte limit' })
1252
+ await checkImageTarget(workspace, id)
1253
+ const result = await storeImage(workspace, id, Buffer.concat(chunks), mediaType, 'human')
1254
+ return sendJson(result.error ? 400 : 200, result)
1255
+ } catch (err) {
1256
+ return sendJson(400, { error: String(err?.message || err) })
1257
+ }
1258
+ }
1259
+ // Connection's streaming bridge always supplies a body, which Fetch forbids on GET.
1260
+ ctx.inject(['connection'], (routeCtx) => routeCtx.connection.fetch.register({
1261
+ path: '/api/kanban/image',
1262
+ methods: ['GET'],
1263
+ requestBody: 'buffered',
1264
+ fetch: imageHttpHandler,
1265
+ }))
1266
+ ctx.inject(['connection'], (routeCtx) => routeCtx.connection.fetch.register({
1267
+ path: '/api/kanban/image/upload',
1268
+ methods: ['POST'],
1269
+ requestBody: 'streaming',
1270
+ fetch: imageHttpHandler,
1271
+ }))
1272
+
1061
1273
  // ---- Startup checks: read each workspace board and back up corrupt files ----
1062
1274
  const runStartupCheck = async () => {
1063
1275
  const fs = getFs()
@@ -1129,6 +1341,7 @@ export function apply(ctx) {
1129
1341
  ok: { type: 'boolean' },
1130
1342
  message: { type: 'string' },
1131
1343
  board: { type: 'object' },
1344
+ cardId: { type: 'string' },
1132
1345
  warnings: { type: 'array', items: { type: 'string' } },
1133
1346
  },
1134
1347
  required: ['ok', 'message'],
@@ -1159,7 +1372,8 @@ export function apply(ctx) {
1159
1372
  card.title +
1160
1373
  (card.dueDate ? ' (due ' + card.dueDate + ')' : '') +
1161
1374
  (card.columnId === b.completedColumnId ? ' [completed; completedAt: ' + (card.completedAt || 'unknown') + ']' : '') +
1162
- (card.commentCount ? ' (' + card.commentCount + ' comments)' : ''),
1375
+ (card.commentCount ? ' (' + card.commentCount + ' comments)' : '') +
1376
+ (card.imageCount ? ' (' + card.imageCount + ' images)' : ''),
1163
1377
  )
1164
1378
  }
1165
1379
  }
@@ -1169,10 +1383,67 @@ export function apply(ctx) {
1169
1383
  const output = (render) => ({ schema: resultSchema, render: (args, value) => render(value) })
1170
1384
 
1171
1385
  const tools = [
1386
+ {
1387
+ name: 'kanban_add_image',
1388
+ description: 'Add a PNG, JPEG or WebP image to an existing card. Supply a workspace-relative file path or an attachmentId actually present in the current session. Never send base64 or a URL. Use the cardId returned by kanban_add_card. Retries of the same image do not add duplicates.',
1389
+ parameters: {
1390
+ type: 'object',
1391
+ properties: {
1392
+ id: { type: 'string', description: 'Card id' },
1393
+ source: {
1394
+ oneOf: [
1395
+ { type: 'object', properties: { kind: { type: 'string', const: 'workspace_file' }, path: { type: 'string' } }, required: ['kind', 'path'], additionalProperties: false },
1396
+ { type: 'object', properties: { kind: { type: 'string', const: 'session_attachment' }, attachmentId: { type: 'string' } }, required: ['kind', 'attachmentId'], additionalProperties: false },
1397
+ ],
1398
+ },
1399
+ },
1400
+ required: ['id', 'source'],
1401
+ },
1402
+ output: output(renderBoard),
1403
+ async execute(args, exec) {
1404
+ try {
1405
+ const workspace = await workspaceOfExec(exec)
1406
+ if (!workspace) throw new Error('Cannot determine current workspace')
1407
+ const result = await importImage(workspace, args, exec)
1408
+ return { ok: !result.error, message: result.error || result.message, board: summaryOfClone(result.board), warnings: result.warnings || [] }
1409
+ } catch (err) {
1410
+ return { ok: false, message: String(err?.message || err), warnings: [] }
1411
+ }
1412
+ },
1413
+ },
1414
+ {
1415
+ name: 'kanban_read_image',
1416
+ description: 'Read the actual image attached to a card for visual inspection. Use an attachmentId from kanban_get_card. Only images associated with the card in the current workspace can be read.',
1417
+ parameters: { type: 'object', properties: { id: { type: 'string' }, attachmentId: { type: 'string' } }, required: ['id', 'attachmentId'] },
1418
+ output: {
1419
+ schema: { type: 'object', properties: { ok: { type: 'boolean' }, message: { type: 'string' }, image: { type: 'object' } }, required: ['ok', 'message'], additionalProperties: false },
1420
+ render: (_args, value) => value.ok && value.image
1421
+ ? [{ type: 'text', text: value.message }, { type: 'image', attachment: value.image }]
1422
+ : [{ type: 'text', text: value.message }],
1423
+ },
1424
+ async execute(args, exec) {
1425
+ try {
1426
+ const workspace = await workspaceOfExec(exec)
1427
+ if (!workspace) throw new Error('Cannot determine current workspace')
1428
+ const stored = await readCardImage(workspace, args, exec?.agent?.session, exec?.signal)
1429
+ return { ok: true, message: 'Card image', image: imageRef(stored.ref) }
1430
+ } catch (err) {
1431
+ return { ok: false, message: String(err?.message || err) }
1432
+ }
1433
+ },
1434
+ },
1435
+ {
1436
+ name: 'kanban_remove_image',
1437
+ description: 'Remove an image association from a card. The DSH object may still be used by other cards or conversations and is not physically deleted.',
1438
+ parameters: { type: 'object', properties: { id: { type: 'string' }, attachmentId: { type: 'string' } }, required: ['id', 'attachmentId'] },
1439
+ output: output(renderBoard),
1440
+ execute(args, exec) { return runTool('removeImage', args, exec) },
1441
+ },
1442
+
1172
1443
  {
1173
1444
  name: 'kanban_get',
1174
- description: 'Read the current state of the current project (workspace) kanban board (all lists, labels, cards with dueDate and completedAt, and completedColumnId). Due dates are local calendar dates, not UTC timestamps; a date becomes overdue the following day. Cards in completedColumnId are finished and excluded from due-today/overdue checks. completedAt is the latest completion UTC timestamp; null on a completed card means unknown. Resolve relative dates using the user local date and confirm the concrete YYYY-MM-DD date. Call it before planning to understand existing content and avoid duplicate cards.',
1175
- parameters: { type: 'object', properties: {} },
1445
+ description: 'Read the current state of the current project (workspace) kanban board (all lists, labels, cards optionally filtered by query, with dueDate and completedAt, and completedColumnId). Due dates are local calendar dates, not UTC timestamps; a date becomes overdue the following day. Cards in completedColumnId are finished and excluded from due-today/overdue checks. completedAt is the latest completion UTC timestamp; null on a completed card means unknown. Resolve relative dates using the user local date and confirm the concrete YYYY-MM-DD date. Call it before planning to understand existing content and avoid duplicate cards.',
1446
+ parameters: { type: 'object', properties: { query: { type: 'string', description: 'Optional text, at most 200 characters. Literal text search across card ids, titles, descriptions and comments; ignores case and surrounding whitespace.' } } },
1176
1447
  output: output(renderBoard),
1177
1448
  async execute(args, exec) {
1178
1449
  return runTool('get', args, exec)
@@ -1216,6 +1487,7 @@ export function apply(ctx) {
1216
1487
  lines.push('Completed: ' + (c.columnId === value.completedColumnId ? 'yes' : 'no'))
1217
1488
  if (c.columnId === value.completedColumnId) lines.push('Completed at: ' + (c.completedAt || 'unknown'))
1218
1489
  if (c.note) lines.push('Note: ' + c.note)
1490
+ for (const image of c.images || []) lines.push('Image: ' + image.attachmentId + ' (' + image.width + '×' + image.height + '); use kanban_read_image to view it')
1219
1491
  if (Array.isArray(c.comments) && c.comments.length > 0) {
1220
1492
  lines.push('Comments:')
1221
1493
  for (const comment of c.comments) {