Skip to content

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

Make a Bot's relative file links absolute when its text goes on

Fei24113a71010e321f
diff --git a/ds-bot/src/host/folders.js b/ds-bot/src/host/folders.js
index 4261da74..239e3d5c 100644
--- a/ds-bot/src/host/folders.js
+++ b/ds-bot/src/host/folders.js
@@ -24,6 +24,13 @@ export function install(rt) {
const workDirOf = ({ botId, roomId } = {}) => rt.roomOf(roomId)?.workDir ?? rt.botOf(botId)?.workDir
const isFolder = path => stat(path).then(info => info.isDirectory(), () => false)
const real = path => realpath(path).catch(() => resolve(path))
+ // Where a Session works: the folder DSH has for it, else the one DS Bot made it for.
+ const sessionFolder = (session) => {
+ const reported = session?.header === undefined ? undefined : ctx.get?.('workingDirectory')?.get?.(session) ?? session.header.cwd
+ if (reported !== undefined) return reported
+ const id = session?.id
+ return workDirOf({ botId: rt.selfOf?.(id), roomId: rt.groupOwners?.get(id)?.roomId }) ?? teamFolder()
+ }
// A Bot that could write where DSH or the team keeps its data could change its own
// permissions or the team, so neither those folders nor one that holds them is allowed.
@@ -131,5 +138,5 @@ export function install(rt) {
}
}
- Object.assign(rt, { teamFolder, workDirOf, isFolder, cleanWorkDir, sessionsOfBot, approveFolder, folderEndpoint })
+ Object.assign(rt, { teamFolder, workDirOf, sessionFolder, isFolder, cleanWorkDir, sessionsOfBot, approveFolder, folderEndpoint })
}
diff --git a/ds-bot/src/host/links.js b/ds-bot/src/host/links.js
new file mode 100644
index 00000000..c2e4728f
--- /dev/null
+++ b/ds-bot/src/host/links.js
@@ -0,0 +1,39 @@
+// File links in a Bot's text, read as DSH's chat reads them: a Markdown link (or image) to
+// a path, with an optional #L12 or #L12-L20. A relative path names a file in the folder of
+// the Session that wrote it, and DSH opens it from the folder of the Session that shows it.
+// Text that goes on to another Session (a group, another Bot) may land in another folder,
+// so its relative file links are made absolute first.
+import { resolve } from 'node:path'
+
+// Code is left as written: a link there is an example, not a link.
+const CODE = /(```[\s\S]*?(?:```|$)|~~~[\s\S]*?(?:~~~|$)|`[^`\n]*`)/g
+const LINK = /(!?\[[^\]\n]*\]\()(<[^<>\n]*>|[^\s()<>]+)((?:\s+"[^"\n]*")?\))/g
+const ABSOLUTE = /^(?:\/|[A-Za-z]:[\\/])/
+const SCHEME = /^[a-z][a-z\d+.-]*:/i
+
+function relativeFile(destination) {
+ const hash = destination.indexOf('#')
+ const target = hash < 0 ? destination : destination.slice(0, hash)
+ const fragment = hash < 0 ? '' : destination.slice(hash)
+ if (target === '' || target.includes('?') || (fragment !== '' && !/^#L[1-9]\d*(?:-L[1-9]\d*)?$/.test(fragment))) return undefined
+ let path
+ try {
+ path = decodeURIComponent(target)
+ } catch {
+ return undefined
+ }
+ const control = [...path].some(char => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127)
+ if (control || /^[\\/]{2}/.test(path) || ABSOLUTE.test(path) || SCHEME.test(path) || path.startsWith('~')) return undefined
+ return { path, fragment }
+}
+
+// DSH decodes the link back to the path, so `%` and what would end the link are escaped.
+const href = path => path.replace(/\\/g, '/').replace(/[%\s()<>]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`)
+
+export function absoluteLinks(text, folder) {
+ if (typeof text !== 'string' || !folder || !text.includes('](')) return text
+ return text.split(CODE).map((part, index) => (index % 2 === 1 ? part : part.replace(LINK, (whole, open, destination, close) => {
+ const file = relativeFile(destination.startsWith('<') ? destination.slice(1, -1) : destination)
+ return file === undefined ? whole : `${open}${href(resolve(folder, file.path))}${file.fragment}${close}`
+ }))).join('')
+}
diff --git a/ds-bot/src/host/tools.js b/ds-bot/src/host/tools.js
index 8a6bddf3..73d29be3 100644
--- a/ds-bot/src/host/tools.js
+++ b/ds-bot/src/host/tools.js
@@ -3,6 +3,7 @@
import { randomUUID } from 'node:crypto'
import { defineTool } from '@deepseek-ai/dsh-tools'
import { COLORS, EXTRA_COLORS, MAX_HOPS, MAX_UNATTENDED_MESSAGES, MAX_UNREAD_REQUESTS, ROOM_BOT_ROUNDS, ROOM_MODES, SOURCE_KIND } from './constants.js'
+import { absoluteLinks } from './links.js'
import { unquote } from './text.js'
export const output = { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] }
@@ -136,7 +137,8 @@ export function install(rt) {
const toUser = args.reply_to === 'user'
const working = rt.live.get(chat)?.turn !== undefined
const steer = args.when !== 'queue' && !toUser
- await rt.deliver({ fromId: sender.id, toId: target.id, text: args.message, role: 'request', hop, steer, ...(toUser ? { audience: 'user' } : callerRoom(exec)) })
+ const text = absoluteLinks(args.message, rt.sessionFolder?.(exec.agent?.session ?? exec.agent))
+ await rt.deliver({ fromId: sender.id, toId: target.id, text, role: 'request', hop, steer, ...(toUser ? { audience: 'user' } : callerRoom(exec)) })
rt.unattended.sent += 1
const sent = toUser
? `Delivered to ${target.name}. It will answer the user in its own chat; nothing comes back to you, so point the user to ${target.name}'s chat instead of relaying.`
@@ -418,7 +420,7 @@ export function install(rt) {
if (info?.role === 'room' && info.roomId === room.id) return `You are speaking in "${room.name}" right now. Write your message as your reply instead.`
const hop = nextHop(exec)
if (hop > MAX_HOPS) return CHAIN_TOO_LONG
- const text = String(args.message ?? '').trim()
+ const text = absoluteLinks(String(args.message ?? '').trim(), rt.sessionFolder?.(exec.agent?.session ?? exec.agent))
if (text === '') return 'Write a message to post.'
if ((room.botRounds ?? 0) >= ROOM_BOT_ROUNDS) return `Bots already started ${ROOM_BOT_ROUNDS} rounds in "${room.name}" since the user last spoke there. Wait for the user.`
checkUnattended()
diff --git a/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.js
index ba4bd434..8fb927e7 100644
--- a/ds-bot/src/host/turns.js
+++ b/ds-bot/src/host/turns.js
@@ -3,6 +3,7 @@
//
// Turn tracking: which turns were triggered by another Bot, and what they said.
import { HANDOFF_ACK, REFERENCE_KIND, REPLY_KIND, SOURCE_KIND } from './constants.js'
+import { absoluteLinks } from './links.js'
import { textOf } from './text.js'
import { reminderText } from './schedules.js'
@@ -429,7 +430,8 @@ export function install(rt) {
const text = textOf(content)
const called = Array.isArray(content) && content.some(block => block?.type === 'tool-call')
if (text !== '' && text !== HANDOFF_ACK) {
- entry.texts.push(text)
+ // What a turn says goes on to the group or the sender, read from other folders.
+ entry.texts.push(absoluteLinks(text, rt.sessionFolder?.(session)))
if (entry.turn !== undefined) showSteps(id, entry, called ? entry.texts.length : entry.texts.length - 1)
}
entry.lastText = text
diff --git a/ds-bot/test/links.test.js b/ds-bot/test/links.test.js
new file mode 100644
index 00000000..77a5bf2d
--- /dev/null
+++ b/ds-bot/test/links.test.js
@@ -0,0 +1,44 @@
+import assert from 'node:assert/strict'
+import { resolve } from 'node:path'
+import { test } from 'node:test'
+import { absoluteLinks } from '../src/host/links.js'
+
+const folder = resolve('/work/group folder')
+// The path DSH opens for a link, as its chat decodes the destination.
+const opened = text => decodeURIComponent(/\]\(([^)#]+)/.exec(text)[1])
+const full = path => resolve(folder, path).replace(/\\/g, '/')
+
+test('a relative file link names the file in the folder it was written in', () => {
+ assert.equal(opened(absoluteLinks('See [a.txt](sub/a.txt).', folder)), full('sub/a.txt'))
+ assert.equal(opened(absoluteLinks('[up](../notes.md)', folder)), full('../notes.md'))
+ // A line range and an image keep their form.
+ assert.match(absoluteLinks('[main](src/main.js#L12-L20)', folder), /#L12-L20\)$/)
+ assert.equal(opened(absoluteLinks('![chart](out/chart.png)', folder)), full('out/chart.png'))
+})
+
+test('a path with spaces, parentheses or a percent sign opens as written', () => {
+ assert.equal(opened(absoluteLinks('[r](<my report (v2).md>)', folder)), full('my report (v2).md'))
+ assert.equal(opened(absoluteLinks('[r](100%25.txt)', folder)), full('100%.txt'))
+})
+
+test('absolute paths, web links, anchors and code are left as they are', () => {
+ const kept = [
+ '[a](/srv/a.txt)',
+ '[a](C:/work/a.txt)',
+ '[site](https://example.com/a)',
+ '[mail](mailto:[email protected])',
+ '[top](#intro)',
+ '[q](a.txt?raw=1)',
+ '[home](~/a.txt)',
+ 'Write `[a](sub/a.txt)` for a link.',
+ '```\n[a](sub/a.txt)\n```',
+ 'No link here.',
+ ]
+ for (const text of kept) assert.equal(absoluteLinks(text, folder), text)
+ assert.equal(absoluteLinks('[a](sub/a.txt)', undefined), '[a](sub/a.txt)')
+})
+
+test('only the links outside code change', () => {
+ const text = 'Use `[x](x.md)` like [y](y.md).'
+ assert.equal(absoluteLinks(text, folder), `Use \`[x](x.md)\` like [y](${full('y.md').replace(/ /g, '%20')}).`)
+})
diff --git a/ds-bot/test/rounds.test.js b/ds-bot/test/rounds.test.js
index 495826dc..2f0b67a3 100644
--- a/ds-bot/test/rounds.test.js
+++ b/ds-bot/test/rounds.test.js
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict'
import { randomUUID } from 'node:crypto'
-import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
+import { mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { test } from 'node:test'
@@ -347,3 +347,36 @@ test('a message sent between rounds still opens a full round', async (t) => {
const result = JSON.parse(await running)
assert.deepEqual(result.replies.map(reply => reply.name ?? 'User'), ['Chief', 'Writer'])
})
+
+// #217: DSH opens a relative file link from the folder of the Session that shows it. A
+// member wrote the link in its own group Session, which works in the group's folder; the
+// group's Session and other Bots work elsewhere, so the link reaches them in full.
+test('a relative file link a member writes reaches the group, and another Bot, as a full path', async (t) => {
+ const { call, emit, userMessage, relay, answer, stop, sent, ctx, rt } = start()
+ t.after(stop)
+ const folder = realpathSync.native(mkdtempSync(join(tmpdir(), 'ds-bot-links-')))
+ t.after(() => rmSync(folder, { recursive: true, force: true }))
+ const room = await team(call, sent)
+ assert.equal((await call('update-room', { id: room.id, workDir: folder })).ok, true)
+ const full = path => join(folder, path).replace(/\\/g, '/').replace(/ /g, '%20')
+ await emit(room.id, userMessage('Where is the draft?'))
+ const running = relay(room.id, 'relay')
+ const first = await turnFor(sent)
+ await answer(first.sessionId, first.message.source.exchangeId, 'It is in [a.txt](sub/a.txt).', 1)
+ const second = await turnFor(sent, first)
+ // The next member reads it in its prompt, and the group shows it, with the full path.
+ assert.ok(second.message.content[0].text.includes(`[a.txt](${full('sub/a.txt')})`))
+ await answer(second.sessionId, second.message.source.exchangeId, 'Thanks.', 2)
+ const result = JSON.parse(await running)
+ assert.equal(result.replies[0].text, `It is in [a.txt](${full('sub/a.txt')}).`)
+
+ // A Bot that works in the folder sends the same link to another Bot.
+ const chief = rt.state.mainBotIds[0]
+ const writer = rt.state.rooms[room.id].members.find(id => id !== chief)
+ sent.length = 0
+ await ctx.registeredTools.get('message_bot').execute({ to: rt.botOf(writer).name, message: 'Read [notes](notes.md#L3)', when: 'queue' }, {
+ agent: { id: first.sessionId, session: { id: first.sessionId, header: { cwd: folder } }, inbox: { nextStep: [], nextTurn: [] } }, callId: 'c1',
+ })
+ const delivered = await waitFor(() => sent.find(entry => entry.message.source?.role === 'request'))
+ assert.ok(delivered.message.content.map(block => block.text).join('\n').includes(`[notes](${full('notes.md')}#L3)`))
+})