Skip to content

A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.

Measure show_view bytes as sent, keep __proto__ as data, record only shown cards

klarkxy7424c1ea774f
diff --git a/ds-bot/src/host/parts.js b/ds-bot/src/host/parts.js
index d7222f58..153a37b3 100644
--- a/ds-bot/src/host/parts.js
+++ b/ds-bot/src/host/parts.js
@@ -20,7 +20,7 @@ import { HANDOFF_ACK, HISTORY_TIMEOUT_MS, REPLY_KIND, SOURCE_KIND } from './cons
import { CHECKPOINT_PROMPT, STEWARD_SYSTEM, checkpointCount, checkpointTail, checkpointTailNote, checkpointText, linesFor, parseDecision, stewardRequest } from './steward.js'
import { RESUME_DELAY_MS } from './resume.js'
import { clip, createClock, escapeRegExp, estimateTokens, splitRef, textOf } from './text.js'
-import { validateViewAnswer, viewSummary } from '../shared/views.js'
+import { checkShownView, validateViewAnswer, viewSummary } from '../shared/views.js'
// An ask_user card as the user saw it. The user's reply is often just an option label,
// which means nothing without the card. Arguments the tool would refuse (no question,
@@ -39,17 +39,21 @@ export function cardText(args) {
return `[Question card] ${question}${detail ? ` (${detail})` : ''}\nOptions: ${options.join(' / ')}`
}
-// A show_view card as the user saw it. A call the tool would refuse (no title,
-// or a view that is not a component object) showed no card, so it gives no text.
+// A show_view card as the user saw it. A call the tool would refuse (an oversized
+// or invalid view, no title, a display-only card asked to wait or an interactive
+// one told not to) showed no card, so it gives no text. checkShownView runs the
+// tool's own checks, normalization included, so a wrapped card keeps its summary.
export function viewCardText(args) {
let card = args
if (typeof card === 'string') {
try { card = JSON.parse(card) } catch { return '' }
}
- const title = typeof card?.title === 'string' ? card.title.trim() : ''
- if (title === '' || card?.view === null || typeof card?.view !== 'object' || Array.isArray(card?.view)) return ''
- const summary = viewSummary(card.view)
- return summary === '' ? `[View card] ${title}` : `[View card] ${title}\n${summary}`
+ const shown = checkShownView(card?.title, card?.view)
+ if (shown.error !== undefined) return ''
+ if (!shown.interactive && card?.await_reply === true) return ''
+ if (shown.interactive && card?.await_reply === false) return ''
+ const summary = viewSummary(shown.view)
+ return summary === '' ? `[View card] ${shown.title}` : `[View card] ${shown.title}\n${summary}`
}
// What one event adds to a Bot's chat history: an answer of the Bot's (its text, or a
diff --git a/ds-bot/src/host/tools.js b/ds-bot/src/host/tools.js
index 09d71c8e..77ec175c 100644
--- a/ds-bot/src/host/tools.js
+++ b/ds-bot/src/host/tools.js
@@ -8,7 +8,7 @@ import { within } from './folders.js'
import { absoluteLinks } from './links.js'
import { unquote } from './text.js'
import { mentionSpans } from '../shared/mentions.js'
-import { normalizeView, checkShownView } from '../shared/views.js'
+import { checkShownView } from '../shared/views.js'
export const output = { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] }
export const GROUP_REF = { type: 'string', required: true, description: 'Exact group chat name from list_bots' }
@@ -636,10 +636,10 @@ export function install(rt) {
const id = exec.agent?.id
if (rt.groupOwners.has(id)) return 'View cards only work in your own chat. In a group, ask in your message instead.'
if (!rt.chatOwners.has(id)) return `Only Bots on the team can use show_view. Use ${BLOCKING_QUESTION_TOOL} if it is available in this session, or ask the user in your reply.`
- const view = normalizeView(args.view)
- const checked = checkShownView(args.title, view)
+ const checked = checkShownView(args.title, args.view)
if (checked.error !== undefined) return checked.error
const title = checked.title
+ const view = checked.view
if (!checked.interactive && args.await_reply === true) return 'This view has nothing to submit; call show_view with await_reply: false.'
if (checked.interactive && args.await_reply === false) return 'This view has controls to submit, so it waits for the user\'s answer; call show_view without await_reply: false.'
const awaitReply = args.await_reply ?? checked.interactive
diff --git a/ds-bot/src/shared/views.js b/ds-bot/src/shared/views.js
index dcbfcdb3..b9763f0e 100644
--- a/ds-bot/src/shared/views.js
+++ b/ds-bot/src/shared/views.js
@@ -28,7 +28,7 @@ const SUMMARY_PART = 40
const SUMMARY_COUNT = 8
// UTF-8 bytes of the blueprint JSON plus the title. Not a wrapped document:
// the tool rejects a show_view whose viewBytes() is over this before it
-// validates, so the number has to be the bytes the model actually sent.
+// normalizes or validates, so the number has to be the bytes the model sent.
export const VIEW_BYTE_LIMIT = 8192
const isRecord = value => value !== null && typeof value === 'object' && !Array.isArray(value)
@@ -53,8 +53,10 @@ export function normalizeView(value) {
const inner = normalizeView(value.item)
if (Array.isArray(inner)) return inner
}
+ // Define own properties: an incoming "__proto__" key must become data the
+ // validator can reject, not hit the prototype setter and vanish from the JSON.
const out = {}
- for (const key of keys) out[key] = normalizeView(value[key])
+ for (const key of keys) Object.defineProperty(out, key, { value: normalizeView(value[key]), writable: true, enumerable: true, configurable: true })
for (const field of ['value', 'percent']) {
if (typeof out[field] === 'string' && out[field].trim() !== '' && !Number.isNaN(Number(out[field]))) out[field] = Number(out[field])
}
@@ -68,16 +70,19 @@ export function validateView(view) {
}
// What show_view checks before it shows a view: the same answer on the host and
-// in the client. `view` is already normalized; the trimmed title comes back.
-export function checkShownView(title, view) {
+// in the client. The bytes are measured as sent, before normalizeView unwraps the
+// provider's encoding, or a wrapped view could shrink under the byte limit. The
+// normalized view and the trimmed title come back.
+export function checkShownView(title, sent) {
let bytes
- try { bytes = viewBytes(title, view) } catch { return { error: 'The view is not JSON data.' } }
+ try { bytes = viewBytes(title, sent) } catch { return { error: 'The view is not JSON data.' } }
if (bytes > VIEW_BYTE_LIMIT) return { error: `The view is ${bytes} bytes; the limit is ${VIEW_BYTE_LIMIT}.` }
const named = String(title ?? '').trim()
if (named === '') return { error: 'Give the view a title.' }
+ const view = normalizeView(sent)
const checked = validateView(view)
if (!checked.ok) return { error: checked.error }
- return { title: named, interactive: checked.interactive }
+ return { title: named, view, interactive: checked.interactive }
}
function checkNode(node, path, depth, ctx) {
diff --git a/ds-bot/test/history.test.js b/ds-bot/test/history.test.js
index 1aa08dbc..126bd85f 100644
--- a/ds-bot/test/history.test.js
+++ b/ds-bot/test/history.test.js
@@ -1,7 +1,8 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { termQuery } from '../src/host/chat-index.js'
-import { canonicalHeadings, cardText, historyEntry, questionReply, readReply, replyText } from '../src/host/parts.js'
+import { canonicalHeadings, cardText, historyEntry, questionReply, readReply, replyText, viewCardText } from '../src/host/parts.js'
+import { VIEW_BYTE_LIMIT, viewBytes } from '../src/shared/views.js'
test('cardText shows a question card as the user saw it', () => {
const card = { question: ' Start where? ', detail: 'pick one', options: [{ label: 'Plan' }, { label: ' ' }, { label: 'Draft' }] }
@@ -13,6 +14,29 @@ test('cardText shows a question card as the user saw it', () => {
assert.equal(cardText({ question: 'Q', options: [] }), '')
})
+test('viewCardText records only a card the tool would show', () => {
+ const meter = { type: 'metric', label: '进度', value: '70%' }
+ const choices = { type: 'options', id: 'pick', options: [{ label: 'A' }, { label: 'B' }] }
+ assert.equal(viewCardText({ title: 'Meter', view: meter }), '[View card] Meter\nmetric: 进度=70%')
+ assert.equal(viewCardText(JSON.stringify({ title: 'Pick', view: choices })), '[View card] Pick\noptions: A/B')
+ // A provider-wrapped array normalizes before the summary, as in the tool.
+ const wrapped = { title: 'Pick', view: { type: 'stack', children: { item: { item: [choices] } } } }
+ assert.equal(viewCardText(wrapped), '[View card] Pick\noptions: A/B')
+ // Calls the tool refuses showed no card: an unknown component, an empty title,
+ // a wait the card cannot honor, or too many bytes as sent.
+ assert.equal(viewCardText({ title: 'X', view: { type: 'chart' } }), '')
+ assert.equal(viewCardText({ title: ' ', view: meter }), '')
+ assert.equal(viewCardText({ title: 'Meter', view: meter, await_reply: true }), '')
+ assert.equal(viewCardText({ title: 'Pick', view: choices, await_reply: false }), '')
+ let children = [{ type: 'text', text: 'x' }]
+ while (viewBytes('', { type: 'stack', children }) <= VIEW_BYTE_LIMIT) children = { item: children }
+ assert.equal(viewCardText({ title: 'Big', view: { type: 'stack', children } }), '')
+ const shown = { type: 'tool/call', data: { name: 'show_view', arguments: { title: 'Meter', view: meter } } }
+ assert.deepEqual(historyEntry(shown, false), { answer: true, text: '[View card] Meter\nmetric: 进度=70%' })
+ const refused = { type: 'tool/call', data: { name: 'show_view', arguments: { title: 'X', view: { type: 'chart' } } } }
+ assert.equal(historyEntry(refused, false), undefined)
+})
+
const said = (text, source) => ({ type: 'user/message', data: { content: [{ type: 'text', text }], source } })
test('historyEntry keeps answers, user and Bot messages, and skips setup', () => {
diff --git a/ds-bot/test/view-reply.test.js b/ds-bot/test/view-reply.test.js
index f5c28680..8c0d4fbb 100644
--- a/ds-bot/test/view-reply.test.js
+++ b/ds-bot/test/view-reply.test.js
@@ -4,7 +4,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { test } from 'node:test'
import { apply } from '../index.js'
-import { VIEW_BYTE_LIMIT, viewBytes } from '../src/shared/views.js'
+import { normalizeView, VIEW_BYTE_LIMIT, viewBytes } from '../src/shared/views.js'
import { fakeContext } from './fake-ctx.js'
const TEAM = {
@@ -237,3 +237,18 @@ test('a user message drops the open question and the open view together', async
assert.equal(open.questions['writer-now'], undefined)
assert.equal(open.views['writer-now'], undefined)
})
+
+test('show_view measures the bytes the model sent, before unwrapping the provider encoding', async (t) => {
+ const { ctx, show, stop } = start()
+ t.after(stop)
+ await ctx.registeredTools.get('list_bots').execute({}, { agent: { id: 'chief' } })
+ // Nested { item: ... } wrappers all disappear in normalization: measured after
+ // unwrapping this card would pass with a fraction of the bytes it was sent with.
+ let children = [{ type: 'text', text: 'x' }]
+ while (viewBytes('', { type: 'stack', children }) <= VIEW_BYTE_LIMIT) children = { item: children }
+ const wrapped = { type: 'stack', children }
+ assert.ok(viewBytes('Meter', normalizeView(wrapped)) < VIEW_BYTE_LIMIT)
+ const over = await show('writer-now', { title: 'Meter', view: wrapped, await_reply: false })
+ assert.equal(over.text, `The view is ${viewBytes('Meter', wrapped)} bytes; the limit is ${VIEW_BYTE_LIMIT}.`)
+ assert.equal(over.concluded, false)
+})
diff --git a/ds-bot/test/views.test.js b/ds-bot/test/views.test.js
index 5f3762d8..b78c8df0 100644
--- a/ds-bot/test/views.test.js
+++ b/ds-bot/test/views.test.js
@@ -102,9 +102,28 @@ test('validateView enforces table, options, form, depth, node, and id limits', (
assert.equal(validateView({ type: 'form', id: 'ask', fields: [{ id: '__proto__', label: 'Name' }] }).error, 'view.fields[0].id: "__proto__" cannot be an id')
})
+test('normalizeView keeps an own "__proto__" key as data for the validator to reject', () => {
+ // Assigning into {} would hit the prototype setter: the key would vanish from
+ // the JSON while its inherited properties could still pass validation.
+ const ghost = normalizeView(JSON.parse('{"__proto__": {"type": "options", "id": "x", "options": [{"label": "A"}]}}'))
+ assert.equal(Object.getPrototypeOf(ghost), Object.prototype)
+ assert.ok(Object.hasOwn(ghost, '__proto__'))
+ assert.notEqual(JSON.stringify(ghost), '{}')
+ assert.equal(validateView(ghost).ok, false)
+ const typed = normalizeView(JSON.parse('{"type": "text", "text": "hi", "__proto__": {"polluted": true}}'))
+ assert.match(validateView(typed).error, /view\.__proto__: unknown property "__proto__"/)
+})
+
test('checkShownView runs the call\'s own checks and names the card and its kind', () => {
- assert.deepEqual(checkShownView(' Status ', text()), { title: 'Status', interactive: false })
- assert.deepEqual(checkShownView('Pick', options()), { title: 'Pick', interactive: true })
+ assert.deepEqual(checkShownView(' Status ', text()), { title: 'Status', view: text(), interactive: false })
+ assert.deepEqual(checkShownView('Pick', options()), { title: 'Pick', view: options(), interactive: true })
+ // The bytes are measured as sent, before the provider's encoding unwraps: a
+ // wrapped document cannot shrink under the limit...
+ let children = [text()]
+ while (viewBytes('', { type: 'stack', children }) <= VIEW_BYTE_LIMIT) children = { item: children }
+ assert.match(checkShownView('Big', { type: 'stack', children }).error, new RegExp(`^The view is \\d+ bytes; the limit is ${VIEW_BYTE_LIMIT}\\.$`))
+ // ...while the same card normalized fits and validates.
+ assert.deepEqual(checkShownView('Pick', { type: 'stack', children: { item: { item: [options()] } } }), { title: 'Pick', view: stack(options()), interactive: true })
assert.equal(checkShownView(' ', text()).error, 'Give the view a title.')
assert.equal(checkShownView('Card', { type: 'nope' }).error, 'view.type: unknown component "nope"; allowed: stack, text, metric, table, options, confirm, form, progress')
assert.equal(checkShownView('Card', undefined).error, 'view: expected a component object')