@alpacachen/dsh-kanban 1.8.0 → 1.10.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.
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,15 +9,15 @@
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: 4
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
18
- * cards: [{ id, columnId, title, note, label, priority, dueDate, createdAt, createdBy,
20
+ * cards: [{ id, columnId, title, note, label, priority, dueDate, completedAt, createdAt, createdBy,
19
21
  * comments: [{ id, content, source, createdAt }] }]
20
22
  * activities: [{ id, ts, cardId, type, source, field?, from?, to?, meta? }] // append-only log
21
23
  *
@@ -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 = 4
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,17 @@ 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
+ }),
169
+ 4: (data) => ({
170
+ ...data,
171
+ schemaVersion: 5,
172
+ // Truncated, title-based activity history cannot reliably recover completion times.
173
+ cards: Array.isArray(data.cards) ? data.cards.map((card) => isObj(card) ? { ...card, completedAt: null } : card) : data.cards,
174
+ }),
148
175
  }
149
176
 
150
177
  /**
@@ -232,9 +259,12 @@ export function validateBoard(data) {
232
259
  errors.push('duplicate card id: ' + c.id)
233
260
  break
234
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)
235
263
  if (!columnIds.has(c.columnId)) errors.push('card references missing column: ' + c.id)
236
264
  if (c.label != null && !labelNames.has(c.label)) errors.push('card references missing label: ' + c.id)
237
265
  if (c.dueDate !== null && !isDueDate(c.dueDate)) errors.push('card has invalid due date: ' + c.id)
266
+ if (c.completedAt !== null && (typeof c.completedAt !== 'string' || !Number.isFinite(Date.parse(c.completedAt)) || new Date(c.completedAt).toISOString() !== c.completedAt)) errors.push('card has invalid completion time: ' + c.id)
267
+ if (c.completedAt !== null && c.columnId !== data.completedColumnId) errors.push('incomplete card has a completion time: ' + c.id)
238
268
  if (c.priority != null && !['high', 'medium', 'low'].includes(c.priority)) errors.push('card has invalid priority: ' + c.id)
239
269
  for (const comment of c.comments) {
240
270
  if (!isObj(comment) || typeof comment.id !== 'string' || !comment.id || typeof comment.content !== 'string' || !comment.content.trim() || comment.content.length > 2000 || !['human', 'agent'].includes(comment.source) || typeof comment.createdAt !== 'string' || !comment.createdAt) {
@@ -354,6 +384,15 @@ export function apply(ctx) {
354
384
  const getFs = () => ctx.get('fs')
355
385
  const getPolicy = () => ctx.get('sandboxPolicy')
356
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
+ }
357
396
 
358
397
  const boards = new Map() // workspaceId -> { columns, labels, cards }
359
398
  const boardLoads = new Map() // workspaceId -> Promise<board>; publish only fully initialized boards
@@ -542,7 +581,7 @@ export function apply(ctx) {
542
581
  const target = await targetOf(workspace)
543
582
  const key = workspaceKey(workspace)
544
583
  const board = boards.get(key)
545
- if (!fs || !target || !board) return
584
+ if (!fs || !target || !board) return false
546
585
  try {
547
586
  await fs.writeText(
548
587
  target,
@@ -558,6 +597,7 @@ export function apply(ctx) {
558
597
  undefined,
559
598
  writePolicyFor(workspace, session),
560
599
  )
600
+ return true
561
601
  } catch (err) {
562
602
  console.log('dsh-kanban: Save failed ' + key + ': ' + ((err && err.message) || err))
563
603
  throw err
@@ -595,8 +635,10 @@ export function apply(ctx) {
595
635
  label: c.label ?? null,
596
636
  priority: c.priority ?? null,
597
637
  dueDate: c.dueDate,
638
+ completedAt: c.completedAt,
598
639
  createdAt: typeof c.createdAt === 'string' ? c.createdAt : null,
599
640
  createdBy: typeof c.createdBy === 'string' ? c.createdBy : null,
641
+ images: c.images.map(imageRef),
600
642
  comments: Array.isArray(c.comments)
601
643
  ? c.comments.map((comment) => ({
602
644
  id: comment.id,
@@ -623,7 +665,9 @@ export function apply(ctx) {
623
665
  label: c.label ?? null,
624
666
  priority: c.priority ?? null,
625
667
  dueDate: c.dueDate,
668
+ completedAt: c.completedAt,
626
669
  commentCount: c.comments.length,
670
+ imageCount: c.images.length,
627
671
  })),
628
672
  })
629
673
 
@@ -641,20 +685,56 @@ export function apply(ctx) {
641
685
  }
642
686
 
643
687
  // ---- Core operations shared by agent tools and browser HTTP ----
644
- const READ_METHODS = new Set(['get', 'getCard'])
688
+ const READ_METHODS = new Set(['get', 'getCard', '_getImage'])
645
689
  const dispatchUnlocked = async (workspace, method, args, source, session) => {
646
690
  const board = await boardOf(workspace, session)
647
691
  const a = args || {}
648
692
  const actor = source === 'agent' ? 'agent' : 'human'
649
693
  const persisted = () => persistedFlag(workspace)
650
- 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 })
651
695
  if (!READ_METHODS.has(method) && board.readOnlyReason) {
652
696
  return result({ error: board.readOnlyReason })
653
697
  }
654
698
 
655
699
  switch (method) {
656
- case 'get':
657
- 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
+ }
658
738
 
659
739
  case 'getCard': {
660
740
  const card = cloneBoard(board).cards.find((c) => c.id === str(a.id, ''))
@@ -679,7 +759,9 @@ export function apply(ctx) {
679
759
  createdAt: new Date().toISOString(),
680
760
  createdBy: actor,
681
761
  comments: [],
762
+ images: [],
682
763
  }
764
+ card.completedAt = col.id === board.completedColumnId ? card.createdAt : null
683
765
  board.cards.push(card)
684
766
  record(board, {
685
767
  cardId: card.id,
@@ -694,7 +776,7 @@ export function apply(ctx) {
694
776
  },
695
777
  })
696
778
  await save(workspace, session)
697
- return result({ message: 'Card added to "' + col.title + '"' })
779
+ return result({ cardId: card.id, message: 'Card added to "' + col.title + '"' })
698
780
  }
699
781
 
700
782
  case 'updateCard': {
@@ -778,7 +860,9 @@ export function apply(ctx) {
778
860
  if (!card || !target) return result({ error: 'Card or list not found' })
779
861
  const fromCol = findColumn(board, card.columnId)
780
862
  const fromTitle = fromCol ? fromCol.title : String(card.columnId)
863
+ const changedColumn = card.columnId !== target.id
781
864
  board.cards = board.cards.filter((c) => c.id !== card.id)
865
+ if (changedColumn) card.completedAt = target.id === board.completedColumnId ? new Date().toISOString() : null
782
866
  card.columnId = target.id
783
867
  const inCol = board.cards.filter((c) => c.columnId === target.id)
784
868
  const toIndex = typeof a.toIndex === 'number' && Number.isFinite(a.toIndex)
@@ -787,7 +871,7 @@ export function apply(ctx) {
787
871
  const anchor = inCol[toIndex]
788
872
  if (anchor) board.cards.splice(board.cards.indexOf(anchor), 0, card)
789
873
  else board.cards.push(card)
790
- if (fromTitle !== target.title) {
874
+ if (changedColumn) {
791
875
  record(board, { cardId: card.id, type: 'card_moved', source: actor, field: 'columnId', from: fromTitle, to: target.title, meta: { title: card.title } })
792
876
  }
793
877
  await save(workspace, session)
@@ -820,6 +904,8 @@ export function apply(ctx) {
820
904
  const previousId = board.completedColumnId
821
905
  if (previousId !== a.columnId) {
822
906
  board.completedColumnId = a.columnId
907
+ // Changing the definition of done does not establish when existing cards finished.
908
+ for (const card of board.cards) card.completedAt = null
823
909
  record(board, { cardId: null, type: 'board_completed_column_changed', source: actor, field: 'completedColumnId', from: previousId, to: a.columnId, meta: { fromColumn: findColumn(board, previousId)?.title ?? null, toColumn: findColumn(board, a.columnId)?.title ?? null } })
824
910
  await save(workspace, session)
825
911
  }
@@ -841,6 +927,7 @@ export function apply(ctx) {
841
927
  for (const card of board.cards) {
842
928
  if (card.columnId === id) {
843
929
  card.columnId = fallback
930
+ card.completedAt = fallback === board.completedColumnId ? new Date().toISOString() : null
844
931
  record(board, { cardId: card.id, type: 'card_moved', source: actor, field: 'columnId', from: deleted.title, to: board.columns[0].title, meta: { title: card.title } })
845
932
  }
846
933
  }
@@ -941,6 +1028,62 @@ export function apply(ctx) {
941
1028
  return run
942
1029
  }
943
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
+
944
1087
  // ---- Tool execution context and browser workspaceId resolution ----
945
1088
  const workspaceOfExec = async (exec) => {
946
1089
  const agent = exec && exec.agent
@@ -980,6 +1123,7 @@ export function apply(ctx) {
980
1123
  const r = await dispatch(workspace, method, args, 'agent', session)
981
1124
  return {
982
1125
  ok: !r.error,
1126
+ ...(r.cardId ? { cardId: r.cardId } : {}),
983
1127
  message: r.error || r.message || 'Done',
984
1128
  board: summaryOfClone(r.board),
985
1129
  warnings: Array.isArray(r.warnings) ? r.warnings : [],
@@ -1022,6 +1166,7 @@ export function apply(ctx) {
1022
1166
  const body = raw ? JSON.parse(raw) : {}
1023
1167
  if (!isObj(body)) return sendJson(400, { error: 'Expected a JSON object' })
1024
1168
  const method = typeof body.method === 'string' ? body.method : 'get'
1169
+ if (method.startsWith('_')) return sendJson(400, { error: 'Unknown kanban method' })
1025
1170
  const args = isObj(body.args) ? body.args : {}
1026
1171
  const workspaceId = typeof args.workspaceId === 'string' ? args.workspaceId : ''
1027
1172
  const workspace = workspaceId ? workspaceOfId(workspaceId) : undefined
@@ -1042,6 +1187,89 @@ export function apply(ctx) {
1042
1187
  fetch: httpHandler,
1043
1188
  }))
1044
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
+
1045
1273
  // ---- Startup checks: read each workspace board and back up corrupt files ----
1046
1274
  const runStartupCheck = async () => {
1047
1275
  const fs = getFs()
@@ -1113,6 +1341,7 @@ export function apply(ctx) {
1113
1341
  ok: { type: 'boolean' },
1114
1342
  message: { type: 'string' },
1115
1343
  board: { type: 'object' },
1344
+ cardId: { type: 'string' },
1116
1345
  warnings: { type: 'array', items: { type: 'string' } },
1117
1346
  },
1118
1347
  required: ['ok', 'message'],
@@ -1142,8 +1371,9 @@ export function apply(ctx) {
1142
1371
  (card.label ? '[' + card.label + '] ' : '') +
1143
1372
  card.title +
1144
1373
  (card.dueDate ? ' (due ' + card.dueDate + ')' : '') +
1145
- (card.columnId === b.completedColumnId ? ' [completed]' : '') +
1146
- (card.commentCount ? ' (' + card.commentCount + ' comments)' : ''),
1374
+ (card.columnId === b.completedColumnId ? ' [completed; completedAt: ' + (card.completedAt || 'unknown') + ']' : '') +
1375
+ (card.commentCount ? ' (' + card.commentCount + ' comments)' : '') +
1376
+ (card.imageCount ? ' (' + card.imageCount + ' images)' : ''),
1147
1377
  )
1148
1378
  }
1149
1379
  }
@@ -1153,10 +1383,67 @@ export function apply(ctx) {
1153
1383
  const output = (render) => ({ schema: resultSchema, render: (args, value) => render(value) })
1154
1384
 
1155
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
+
1156
1443
  {
1157
1444
  name: 'kanban_get',
1158
- description: 'Read the current state of the current project (workspace) kanban board (all lists, labels, cards with dueDate, 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. 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.',
1159
- 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.' } } },
1160
1447
  output: output(renderBoard),
1161
1448
  async execute(args, exec) {
1162
1449
  return runTool('get', args, exec)
@@ -1164,7 +1451,7 @@ export function apply(ctx) {
1164
1451
  },
1165
1452
  {
1166
1453
  name: 'kanban_get_card',
1167
- description: "Read one card's full details (title, raw Markdown description in note, label, priority, dueDate and comments), plus the board completion column ID from the current project (workspace) board by card id. Use kanban_get first to discover card ids; its summary omits note. Read this tool before editing an existing description to preserve its content and Markdown formatting.",
1454
+ description: "Read one card's full details (title, raw Markdown description in note, label, priority, dueDate, completedAt and comments), plus the board completion column ID from the current project (workspace) board by card id. completedAt is a system-managed UTC timestamp, cleared on reopening; null on a completed card means unknown. Use kanban_get first to discover card ids; its summary omits note. Read this tool before editing an existing description to preserve its content and Markdown formatting.",
1168
1455
  parameters: {
1169
1456
  type: 'object',
1170
1457
  properties: {
@@ -1198,7 +1485,9 @@ export function apply(ctx) {
1198
1485
  if (c.label) lines.push('Label: ' + c.label)
1199
1486
  if (c.dueDate) lines.push('Due date: ' + c.dueDate + ' (local calendar date)')
1200
1487
  lines.push('Completed: ' + (c.columnId === value.completedColumnId ? 'yes' : 'no'))
1488
+ if (c.columnId === value.completedColumnId) lines.push('Completed at: ' + (c.completedAt || 'unknown'))
1201
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')
1202
1491
  if (Array.isArray(c.comments) && c.comments.length > 0) {
1203
1492
  lines.push('Comments:')
1204
1493
  for (const comment of c.comments) {
@@ -1335,7 +1624,7 @@ export function apply(ctx) {
1335
1624
  },
1336
1625
  {
1337
1626
  name: 'kanban_set_completed_column',
1338
- description: 'Choose the one list that means completed for this board by its stable column id, or clear the setting with null. Cards in this list are excluded from due-today and overdue checks. Existing boards require an explicit choice; never infer completion from a list name or position. New boards default to Done.',
1627
+ description: 'Choose the one list that means completed for this board by its stable column id, or clear the setting with null. Cards in this list are excluded from due-today and overdue checks. Existing boards require an explicit choice; never infer completion from a list name or position. New boards default to Done. Changing this setting clears completion timestamps; cards already in the new completion list have unknown completion times.',
1339
1628
  parameters: {
1340
1629
  type: 'object',
1341
1630
  properties: { columnId: { oneOf: [{ type: 'string' }, { type: 'null' }], description: 'Existing list id from kanban_get, or null to clear the completion column' } },