@kabxx/dsh-btw 0.0.0-stage → 0.1.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/NOTICE +50 -0
- package/README.md +48 -2
- package/cordis.patch.yml +3 -0
- package/dist/client.js +2600 -0
- package/icon.svg +8 -0
- package/locale/en.json +83 -0
- package/locale/zh.json +83 -0
- package/package.json +37 -4
- package/src/host/index.js +783 -0
- package/src/host/session-store.js +79 -0
- package/src/host/typert.js +9 -0
- package/src/shared/wire.js +212 -0
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from 'node:fs/promises'
|
|
3
|
+
import { createRequire } from 'node:module'
|
|
4
|
+
import { dirname, isAbsolute, join, relative, sep } from 'node:path'
|
|
5
|
+
import { PACKAGE_NAME, parseThreadId } from '../shared/wire.js'
|
|
6
|
+
|
|
7
|
+
const { version } = createRequire(import.meta.url)('../../package.json')
|
|
8
|
+
const SCHEMA_VERSION = 1
|
|
9
|
+
const releaseDirectory = /^v\d+\.\d+\.\d+$/u
|
|
10
|
+
|
|
11
|
+
async function listDirectory(directory) {
|
|
12
|
+
try {
|
|
13
|
+
return await readdir(directory, { withFileTypes: true })
|
|
14
|
+
} catch (error) {
|
|
15
|
+
if (error?.code !== 'ENOENT') throw error
|
|
16
|
+
return []
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function sessionThreadStore(persistence, parseRecord) {
|
|
21
|
+
return {
|
|
22
|
+
async open(sessionId, signal) {
|
|
23
|
+
const snapshot = await persistence.stat(sessionId, { signal })
|
|
24
|
+
signal.throwIfAborted()
|
|
25
|
+
const location = snapshot?.location
|
|
26
|
+
if (location?.kind !== 'jsonl' || !location.path || !isAbsolute(location.path)) return undefined
|
|
27
|
+
|
|
28
|
+
const sessionDirectory = dirname(location.path)
|
|
29
|
+
const directoryInfo = await stat(sessionDirectory).catch(error => {
|
|
30
|
+
if (error.code !== 'ENOENT') throw error
|
|
31
|
+
})
|
|
32
|
+
if (!directoryInfo?.isDirectory()) return undefined
|
|
33
|
+
const root = join(sessionDirectory, 'plugins', PACKAGE_NAME)
|
|
34
|
+
const records = []
|
|
35
|
+
const files = new Map()
|
|
36
|
+
for (const release of await listDirectory(root)) {
|
|
37
|
+
if (!release.isDirectory() || !releaseDirectory.test(release.name)) continue
|
|
38
|
+
const directory = join(root, release.name, 'threads')
|
|
39
|
+
for (const entry of await listDirectory(directory)) {
|
|
40
|
+
if (!entry.isFile() || !entry.name.endsWith('.json')) continue
|
|
41
|
+
const file = join(directory, entry.name)
|
|
42
|
+
const envelope = JSON.parse(await readFile(file, { encoding: 'utf8', signal }))
|
|
43
|
+
if (envelope.schemaVersion !== SCHEMA_VERSION) continue
|
|
44
|
+
const record = parseRecord(envelope.record)
|
|
45
|
+
if (record.sessionId !== sessionId) continue
|
|
46
|
+
if (entry.name !== `${record.id}.json` || files.has(record.id)) throw new Error('Invalid BTW thread archive')
|
|
47
|
+
files.set(record.id, file)
|
|
48
|
+
records.push(record)
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
signal.throwIfAborted()
|
|
52
|
+
return {
|
|
53
|
+
records,
|
|
54
|
+
async put(record) {
|
|
55
|
+
const id = parseThreadId(record.id)
|
|
56
|
+
const file = files.get(id) ?? join(root, `v${version}`, 'threads', `${id}.json`)
|
|
57
|
+
let directory = sessionDirectory
|
|
58
|
+
for (const part of relative(sessionDirectory, dirname(file)).split(sep)) {
|
|
59
|
+
directory = join(directory, part)
|
|
60
|
+
// Start below the session root so a removed session cannot be recreated here.
|
|
61
|
+
await mkdir(directory, { mode: 0o700 }).catch(error => {
|
|
62
|
+
if (error.code !== 'EEXIST') throw error
|
|
63
|
+
})
|
|
64
|
+
}
|
|
65
|
+
const temporary = `${file}.${randomUUID()}.tmp`
|
|
66
|
+
try {
|
|
67
|
+
const envelope = { schemaVersion: SCHEMA_VERSION, record }
|
|
68
|
+
await writeFile(temporary, `${JSON.stringify(envelope)}\n`, { flag: 'wx', mode: 0o600 })
|
|
69
|
+
await rename(temporary, file)
|
|
70
|
+
} catch (error) {
|
|
71
|
+
await unlink(temporary).catch(() => {})
|
|
72
|
+
throw error
|
|
73
|
+
}
|
|
74
|
+
files.set(id, file)
|
|
75
|
+
},
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
export const PACKAGE_NAME = '@kabxx/dsh-btw'
|
|
2
|
+
export const CONTEXT_OVERFLOW = 'context-window-exceeded'
|
|
3
|
+
const STATUSES = new Set(['generating', 'completed', 'failed', 'interrupted'])
|
|
4
|
+
export const TOKEN_FIELDS = ['inputTokens', 'outputTokens', 'totalTokens', 'cacheReadTokens', 'cacheWriteTokens', 'reasoningTokens']
|
|
5
|
+
const THREAD_ID = /^btw-[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/u
|
|
6
|
+
|
|
7
|
+
function checked(value, condition, field) {
|
|
8
|
+
if (!condition) throw new TypeError(`Invalid BTW ${field}`)
|
|
9
|
+
return value
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function parseSessionId(value) {
|
|
13
|
+
return checked(value, typeof value === 'string' && value.length > 0, 'sessionId')
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function parseThreadId(value) {
|
|
17
|
+
return checked(value, typeof value === 'string' && THREAD_ID.test(value), 'id')
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function parseQuestion(value) {
|
|
21
|
+
return checked(value, typeof value === 'string' && value.trim() !== '', 'question')
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function parseVersion(value) {
|
|
25
|
+
return checked(value, Number.isSafeInteger(value) && value >= 1, 'version')
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function timestamp(value) {
|
|
29
|
+
return checked(value, Number.isSafeInteger(value) && value >= 0, 'timestamp')
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function object(value, fields) {
|
|
33
|
+
return checked(value, value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
34
|
+
&& [null, Object.prototype].includes(Object.getPrototypeOf(value))
|
|
35
|
+
&& Object.keys(value).every(key => fields.includes(key)), 'record shape')
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function common(value) {
|
|
39
|
+
return {
|
|
40
|
+
id: parseThreadId(value.id),
|
|
41
|
+
sessionId: parseSessionId(value.sessionId),
|
|
42
|
+
question: parseQuestion(value.question),
|
|
43
|
+
createdAt: timestamp(value.createdAt),
|
|
44
|
+
updatedAt: timestamp(value.updatedAt),
|
|
45
|
+
version: parseVersion(value.version),
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const commonFields = ['id', 'sessionId', 'question', 'createdAt', 'updatedAt', 'version']
|
|
50
|
+
|
|
51
|
+
function status(value) {
|
|
52
|
+
return checked(value, STATUSES.has(value), 'status')
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function parseUsage(usage) {
|
|
56
|
+
object(usage, TOKEN_FIELDS)
|
|
57
|
+
return Object.fromEntries(Object.entries(usage).map(([key, value]) => [key, parsePosition(value)]))
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function parseTiming(value) {
|
|
61
|
+
object(value, ['requestMs', 'firstTokenMs'])
|
|
62
|
+
const requestMs = timestamp(value.requestMs)
|
|
63
|
+
if (value.firstTokenMs === undefined) return { requestMs }
|
|
64
|
+
const firstTokenMs = timestamp(value.firstTokenMs)
|
|
65
|
+
return checked({ requestMs, firstTokenMs }, firstTokenMs <= requestMs, 'first token timing')
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function parseTurn(value) {
|
|
69
|
+
object(value, ['question', 'reply', 'status', 'createdAt', 'finishedAt', 'error', 'saveError', 'usage', 'timing'])
|
|
70
|
+
const turn = {
|
|
71
|
+
question: parseQuestion(value.question),
|
|
72
|
+
reply: checked(value.reply, typeof value.reply === 'string', 'reply'),
|
|
73
|
+
status: status(value.status),
|
|
74
|
+
createdAt: timestamp(value.createdAt),
|
|
75
|
+
}
|
|
76
|
+
if (turn.status !== 'generating') turn.finishedAt = timestamp(value.finishedAt)
|
|
77
|
+
else checked(value.finishedAt, value.finishedAt === undefined, 'finishedAt')
|
|
78
|
+
if (value.error !== undefined) turn.error = checked(value.error, typeof value.error === 'string', 'error')
|
|
79
|
+
if (value.saveError !== undefined) turn.saveError = checked(value.saveError, typeof value.saveError === 'string', 'saveError')
|
|
80
|
+
if (value.usage !== undefined) turn.usage = parseUsage(value.usage)
|
|
81
|
+
if (value.timing !== undefined) turn.timing = parseTiming(value.timing)
|
|
82
|
+
return turn
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function parseDetail(value) {
|
|
86
|
+
object(value, [...commonFields, 'turns'])
|
|
87
|
+
checked(value.turns, Array.isArray(value.turns) && value.turns.length > 0, 'turns')
|
|
88
|
+
return { ...common(value), turns: value.turns.map(parseTurn) }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function parseContext(value) {
|
|
92
|
+
object(value, ['contextWindow', 'estimatedTokens'])
|
|
93
|
+
const capacity = value.contextWindow
|
|
94
|
+
const contextWindow = checked(capacity, capacity === null || (Number.isSafeInteger(capacity) && capacity > 0), 'contextWindow')
|
|
95
|
+
return { contextWindow,
|
|
96
|
+
...(value.estimatedTokens !== undefined && { estimatedTokens: parsePosition(value.estimatedTokens) }),
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function parseSummaries(values) {
|
|
101
|
+
checked(values, Array.isArray(values), 'summaries')
|
|
102
|
+
return values.map(value => {
|
|
103
|
+
object(value, [...commonFields, 'status'])
|
|
104
|
+
return { ...common(value), status: status(value.status) }
|
|
105
|
+
})
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function codec(typeSymbol, parse) {
|
|
109
|
+
return Object.freeze({ mode: 'strict', typeSymbol, create: () => ({ parse }) })
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function parsePosition(value) {
|
|
113
|
+
return checked(value, Number.isSafeInteger(value) && value >= 0, 'position')
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function appendTurn(detail, receipt) {
|
|
117
|
+
if (detail.id !== receipt.id || detail.sessionId !== receipt.sessionId
|
|
118
|
+
|| receipt.turnIndex !== detail.turns.length || receipt.version <= detail.version) return detail
|
|
119
|
+
return { ...detail, updatedAt: receipt.updatedAt, version: receipt.version, turns: [...detail.turns, receipt.turn] }
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function applyReply(detail, turnIndex, update) {
|
|
123
|
+
const turn = detail.turns[turnIndex]
|
|
124
|
+
if (!turn || turn.status !== 'generating' || update.version <= detail.version) return detail
|
|
125
|
+
checked(update.offset <= turn.reply.length, 'reply offset')
|
|
126
|
+
const turns = [...detail.turns]
|
|
127
|
+
turns[turnIndex] = {
|
|
128
|
+
...turn, reply: turn.reply.slice(0, update.offset) + update.text, status: update.status,
|
|
129
|
+
...(update.finishedAt !== undefined && { finishedAt: update.finishedAt }),
|
|
130
|
+
...(update.error !== undefined && { error: update.error }),
|
|
131
|
+
...(update.saveError !== undefined && { saveError: update.saveError }),
|
|
132
|
+
...(update.usage !== undefined && { usage: update.usage }),
|
|
133
|
+
...(update.timing !== undefined && { timing: update.timing }),
|
|
134
|
+
}
|
|
135
|
+
return { ...detail, updatedAt: update.updatedAt, version: update.version, turns }
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function parseReceipt(value) {
|
|
139
|
+
object(value, ['id', 'sessionId', 'updatedAt', 'version', 'turnIndex', 'turn'])
|
|
140
|
+
return {
|
|
141
|
+
id: parseThreadId(value.id), sessionId: parseSessionId(value.sessionId), updatedAt: timestamp(value.updatedAt),
|
|
142
|
+
version: parseVersion(value.version), turnIndex: parsePosition(value.turnIndex), turn: parseTurn(value.turn),
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function parseReplyUpdate(value) {
|
|
147
|
+
object(value, ['version', 'updatedAt', 'offset', 'text', 'status', 'finishedAt', 'error', 'saveError', 'usage', 'timing'])
|
|
148
|
+
const update = {
|
|
149
|
+
version: parseVersion(value.version), updatedAt: timestamp(value.updatedAt), offset: parsePosition(value.offset),
|
|
150
|
+
text: checked(value.text, typeof value.text === 'string', 'text'), status: status(value.status),
|
|
151
|
+
}
|
|
152
|
+
if (update.status !== 'generating') update.finishedAt = timestamp(value.finishedAt)
|
|
153
|
+
else checked(value.finishedAt, value.finishedAt === undefined, 'finishedAt')
|
|
154
|
+
if (value.error !== undefined) update.error = checked(value.error, typeof value.error === 'string', 'error')
|
|
155
|
+
if (value.saveError !== undefined) update.saveError = checked(value.saveError, typeof value.saveError === 'string', 'saveError')
|
|
156
|
+
if (value.usage !== undefined) update.usage = parseUsage(value.usage)
|
|
157
|
+
if (value.timing !== undefined) update.timing = parseTiming(value.timing)
|
|
158
|
+
return update
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const detail = codec(`${PACKAGE_NAME}#Detail`, parseDetail)
|
|
162
|
+
const receipt = codec(`${PACKAGE_NAME}#FollowupReceipt`, parseReceipt)
|
|
163
|
+
const replyUpdate = codec(`${PACKAGE_NAME}#ReplyUpdate`, parseReplyUpdate)
|
|
164
|
+
const summaryList = codec(`${PACKAGE_NAME}#SummaryList`, parseSummaries)
|
|
165
|
+
const agent = Object.freeze({
|
|
166
|
+
name: 'agent',
|
|
167
|
+
wire: 'agentId',
|
|
168
|
+
source: 'lookup',
|
|
169
|
+
lookup: 'agent',
|
|
170
|
+
codec: codec('@deepseek-ai/dsh-session/types#SessionId', parseSessionId),
|
|
171
|
+
})
|
|
172
|
+
|
|
173
|
+
function parameter(name, parse, acceptsUndefined) {
|
|
174
|
+
return Object.freeze({
|
|
175
|
+
name,
|
|
176
|
+
wire: name,
|
|
177
|
+
source: 'json',
|
|
178
|
+
codec: codec(`${PACKAGE_NAME}#${name}`, parse),
|
|
179
|
+
...(acceptsUndefined ? { acceptsUndefined: true } : {}),
|
|
180
|
+
})
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const id = parameter('id', parseThreadId)
|
|
184
|
+
const question = parameter('question', parseQuestion)
|
|
185
|
+
const version = parameter('version', value => value == null ? undefined : parseVersion(value), true)
|
|
186
|
+
|
|
187
|
+
function descriptor(method, parameters, result, stream = false) {
|
|
188
|
+
return Object.freeze({
|
|
189
|
+
id: `${PACKAGE_NAME}#btw/${method}`,
|
|
190
|
+
service: 'btw',
|
|
191
|
+
namespace: 'btw',
|
|
192
|
+
method,
|
|
193
|
+
invocation: { kind: 'direct' },
|
|
194
|
+
parameters: Object.freeze([agent, ...parameters]),
|
|
195
|
+
cancellation: { parameter: 'signal' },
|
|
196
|
+
result,
|
|
197
|
+
...(stream ? { mode: 'stream' } : {}),
|
|
198
|
+
})
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export const descriptors = Object.freeze([
|
|
202
|
+
descriptor('create', [question], detail),
|
|
203
|
+
descriptor('list', [], summaryList),
|
|
204
|
+
descriptor('get', [id], detail),
|
|
205
|
+
descriptor('followup', [id, question], receipt),
|
|
206
|
+
descriptor('watch', [id, version], detail, true),
|
|
207
|
+
descriptor('watchReply', [id, parameter('turnIndex', parsePosition), version], replyUpdate, true),
|
|
208
|
+
])
|
|
209
|
+
|
|
210
|
+
export const contextDescriptor = descriptor('contextCapacity', [id], codec(`${PACKAGE_NAME}#ContextWindow`, parseContext))
|
|
211
|
+
export const TYPERT_REMOTE = Object.freeze({ package: PACKAGE_NAME, descriptors: Object.freeze([...descriptors, contextDescriptor]) })
|
|
212
|
+
export const createBtwContribution = () => TYPERT_REMOTE
|