返回 CodeWhale
dsh-shims.ts
根目录 / crates / engine / extension-host / src / dsh / dsh-shims.ts
1 import { Service } from '@deepseek-ai/cordis'
2 import { randomBytes } from 'node:crypto'
3 import { lstat, mkdir, rename, rm, writeFile } from 'node:fs/promises'
4 import { dirname, isAbsolute, join, resolve } from 'node:path'
5 import { ErrorCode } from '../protocol.ts'
6 import { ownerStorage } from '../root.ts'
7 import { RpcError } from '../rpc.ts'
8 import { canonicalPath, insideKey, unlinkedKeyMatches } from './canonical-path.ts'
9 import compatibility from './compatibility.json' with { type: 'json' }
10 import { SettingsConflictError } from './settings.ts'
11 import { HarnessError } from './dsh-message-compat.js'
12
13 const MAX_CREDENTIAL_REF_LEN = 256
14 const MAX_ATOMIC_WRITE_BYTES = 16 * 1024 * 1024
15
16 function activeDataDir(operation: string): string {
17 const owner = ownerStorage.getStore()
18 if (!owner || typeof owner.dataDir !== 'string' || owner.dataDir.length === 0) {
19 throw new Error(`${operation} requires an active plugin owner with a scoped dataDir`)
20 }
21 return canonicalPath(owner.dataDir)
22 }
23
24 function assertNoEscapingAncestor(dataRoot: string, target: string, operation: string): void {
25 let current = target
26 while (current.length >= dataRoot.length) {
27 if (current === dataRoot) break
28 try {
29 const canonical = canonicalPath(current)
30 const key = insideKey(dataRoot, current)
31 if (key === undefined || key === '') {
32 if (canonical !== dataRoot) {
33 throw new Error(`${operation} refused symlink escaping plugin dataDir`)
34 }
35 break
36 }
37 if (!unlinkedKeyMatches(dataRoot, key, canonical)) {
38 throw new Error(`${operation} refused symlink escaping plugin dataDir`)
39 }
40 break
41 } catch (error: any) {
42 if (error?.code === 'ENOENT') {
43 const next = dirname(current)
44 if (next === current) break
45 current = next
46 continue
47 }
48 throw error
49 }
50 }
51 }
52
53 function confinePathToDataDir(targetPath: unknown, operation: string): string {
54 if (typeof targetPath !== 'string' || targetPath.length === 0 || /[\x00-\x1f\x7f]/.test(targetPath)) {
55 throw new TypeError(`${operation} requires a valid file path string`)
56 }
57 const dataRoot = activeDataDir(operation)
58 const resolved = isAbsolute(targetPath) ? resolve(targetPath) : resolve(dataRoot, targetPath)
59 const rel = insideKey(dataRoot, resolved)
60 if (rel === undefined || rel === '') {
61 throw new Error(`${operation} refused path outside plugin dataDir`)
62 }
63 assertNoEscapingAncestor(dataRoot, dirname(resolved), operation)
64 return resolved
65 }
66
67 // ---------------------------------------------------------------------------
68 // @deepseek-ai/dsh-credentials (plugin-scoped handle helpers; never host secrets)
69 // ---------------------------------------------------------------------------
70 export function credentialRef(value: unknown): string {
71 if (typeof value !== 'string') {
72 throw new TypeError('credentialRef requires a non-empty string')
73 }
74 const trimmed = value.trim()
75 if (trimmed.length === 0 || trimmed.length > MAX_CREDENTIAL_REF_LEN || /[\x00-\x1f\x7f]/.test(trimmed)) {
76 throw new TypeError('credentialRef requires a bounded printable string')
77 }
78 return trimmed
79 }
80
81 export async function resolveCredential(
82 ctx: { credentials?: { resolve(ref: string): Promise<{ value: string } | undefined> } },
83 ref: string,
84 ): Promise<{ value: string } | undefined> {
85 if (!ctx?.credentials || typeof ctx.credentials.resolve !== 'function') return undefined
86 return ctx.credentials.resolve(credentialRef(ref))
87 }
88
89 export async function describeCredential(
90 ctx: { credentials?: { describe(ref: string): Promise<{ ref: string, set: boolean, site?: string }> } },
91 ref: string,
92 ): Promise<{ ref: string, set: boolean, site?: string } | undefined> {
93 if (!ctx?.credentials || typeof ctx.credentials.describe !== 'function') return undefined
94 return ctx.credentials.describe(credentialRef(ref))
95 }
96
97 export const dshCredentialsModule = Object.freeze({
98 credentialRef,
99 resolveCredential,
100 describeCredential,
101 })
102
103 // ---------------------------------------------------------------------------
104 // @deepseek-ai/dsh-settings (backed by ctx.settings)
105 // ---------------------------------------------------------------------------
106 export function settingsNamespace(name: unknown): string {
107 if (typeof name !== 'string' || name.trim().length === 0 || name.length > 128) {
108 throw new TypeError('settingsNamespace requires a non-empty string')
109 }
110 return name.trim()
111 }
112
113 export function installSettingsSection(
114 ctx: { settings?: { describe(): unknown } },
115 ns: string,
116 _section?: unknown,
117 ): () => void {
118 settingsNamespace(ns)
119 void ctx?.settings
120 return () => undefined
121 }
122
123 export const dshSettingsModule = Object.freeze({
124 SettingsConflictError,
125 settingsNamespace,
126 installSettingsSection,
127 default: Object.freeze({
128 SettingsConflictError,
129 settingsNamespace,
130 installSettingsSection,
131 }),
132 })
133
134 // ---------------------------------------------------------------------------
135 // @deepseek-ai/dsh-home-paths (strictly confined inside owner.dataDir)
136 // ---------------------------------------------------------------------------
137 export function resolveDshHome(...segments: string[]): string {
138 const dataRoot = activeDataDir('resolveDshHome')
139 if (segments.length === 0) return dataRoot
140 for (const seg of segments) {
141 if (typeof seg !== 'string' || seg.includes('\0') || isAbsolute(seg)) {
142 throw new Error('resolveDshHome refused absolute or invalid path segment')
143 }
144 }
145 const target = resolve(dataRoot, ...segments)
146 const rel = insideKey(dataRoot, target)
147 if (rel === undefined) {
148 throw new Error('resolveDshHome refused path escaping plugin dataDir')
149 }
150 if (rel !== '') {
151 assertNoEscapingAncestor(dataRoot, target, 'resolveDshHome')
152 }
153 return target
154 }
155
156 export const dshHomePathsModule = Object.freeze({
157 resolveDshHome,
158 resolveDshPath: resolveDshHome,
159 })
160
161 // ---------------------------------------------------------------------------
162 // @deepseek-ai/dsh-atomic-write (atomic temp+rename confined to owner.dataDir)
163 // ---------------------------------------------------------------------------
164 const fileLocks = new Map<string, Promise<void>>()
165
166 export async function withFileLock<T>(targetPath: string, fn: () => Promise<T> | T): Promise<T> {
167 const confined = confinePathToDataDir(targetPath, 'withFileLock')
168 const prev = fileLocks.get(confined) ?? Promise.resolve()
169 let release!: () => void
170 const current = new Promise<void>((res) => { release = res })
171 const chain = prev.then(() => current)
172 fileLocks.set(confined, chain)
173 await prev
174 try {
175 return await fn()
176 } finally {
177 release()
178 if (fileLocks.get(confined) === chain) {
179 fileLocks.delete(confined)
180 }
181 }
182 }
183
184 export async function writeFileAtomic(
185 targetPath: string,
186 data: string | Uint8Array,
187 options?: { encoding?: BufferEncoding, mode?: number },
188 ): Promise<void> {
189 const dataRoot = activeDataDir('writeFileAtomic')
190 const confined = confinePathToDataDir(targetPath, 'writeFileAtomic')
191 const bytes = typeof data === 'string'
192 ? Buffer.from(data, options?.encoding ?? 'utf8')
193 : Buffer.from(data.buffer, data.byteOffset, data.byteLength)
194 if (bytes.byteLength > MAX_ATOMIC_WRITE_BYTES) {
195 throw new RangeError(`writeFileAtomic exceeds the ${MAX_ATOMIC_WRITE_BYTES} byte limit`)
196 }
197 try {
198 const existing = await lstat(confined)
199 if (existing.isSymbolicLink()) {
200 throw new Error('writeFileAtomic refused symlink target')
201 }
202 } catch (error: any) {
203 if (error?.code !== 'ENOENT') throw error
204 }
205 const parent = dirname(confined)
206 await mkdir(parent, { recursive: true })
207 const canonicalParent = canonicalPath(parent)
208 const parentKey = insideKey(dataRoot, parent)
209 if (parentKey === undefined || (parentKey === '' ? canonicalParent !== dataRoot : !unlinkedKeyMatches(dataRoot, parentKey, canonicalParent))) {
210 throw new Error('writeFileAtomic refused symlink escaping plugin dataDir')
211 }
212 const tmpPath = join(canonicalParent, `.cw-atomic-${process.pid}-${randomBytes(8).toString('hex')}.tmp`)
213 try {
214 await writeFile(tmpPath, bytes, {
215 flag: 'wx',
216 ...(options?.mode !== undefined ? { mode: options.mode } : {}),
217 })
218 await rename(tmpPath, confined)
219 } catch (error) {
220 await rm(tmpPath, { force: true }).catch(() => undefined)
221 throw error
222 }
223 }
224
225 export const dshAtomicWriteModule = Object.freeze({
226 writeFileAtomic,
227 withFileLock,
228 })
229
230 // ---------------------------------------------------------------------------
231 // @deepseek-ai/dsh-skill (read-only skill schema & frontmatter helpers)
232 // ---------------------------------------------------------------------------
233 export const BUNDLED_SKILL_RANK = 100
234
235 export function isModelInvocable(skill: unknown): boolean {
236 if (!skill || typeof skill !== 'object') return false
237 const s = skill as Record<string, unknown>
238 if (s.disableModelInvocation === true || s.modelInvocable === false) return false
239 return true
240 }
241
242 export function isUserInvocable(skill: unknown): boolean {
243 if (!skill || typeof skill !== 'object') return false
244 const s = skill as Record<string, unknown>
245 if (s.userInvocable === false) return false
246 return true
247 }
248
249 export function parseSkillFrontmatter(markdown: unknown): { frontmatter: Record<string, string>, body: string } {
250 if (typeof markdown !== 'string') return { frontmatter: {}, body: '' }
251 const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(markdown)
252 if (!match) return { frontmatter: {}, body: markdown }
253 const frontmatter: Record<string, string> = {}
254 for (const line of match[1].split(/\r?\n/)) {
255 const idx = line.indexOf(':')
256 if (idx <= 0) continue
257 const key = line.slice(0, idx).trim()
258 const val = line.slice(idx + 1).trim().replace(/^["']|["']$/g, '')
259 if (key) frontmatter[key] = val
260 }
261 return { frontmatter, body: match[2] }
262 }
263
264 export function renderSkillContent(skill: unknown, args?: string): string {
265 const raw = typeof skill === 'string'
266 ? skill
267 : (skill && typeof skill === 'object' && typeof (skill as { content?: unknown }).content === 'string')
268 ? (skill as { content: string }).content
269 : ''
270 const { body } = parseSkillFrontmatter(raw)
271 if (typeof args !== 'string' || args.length === 0) return body
272 return body.replaceAll('$ARGUMENTS', args)
273 }
274
275 export const dshSkillModule = Object.freeze({
276 BUNDLED_SKILL_RANK,
277 isModelInvocable,
278 isUserInvocable,
279 parseSkillFrontmatter,
280 renderSkillContent,
281 })
282
283 // ---------------------------------------------------------------------------
284 // @deepseek-ai/dsh-typert-protocol (pure protocol constants/types/codecs)
285 // ---------------------------------------------------------------------------
286 export const Remote = Object.freeze({
287 strictCodec<T = unknown>(typeSymbol: string, schema: T) {
288 return Object.freeze({
289 mode: 'strict' as const,
290 typeSymbol,
291 create: () => schema,
292 schema,
293 })
294 },
295 jsonParameter(name: string, typeSymbol: string, schema: unknown, acceptsUndefined = false) {
296 return Object.freeze({
297 name,
298 wire: name,
299 source: 'json' as const,
300 codec: Remote.strictCodec(typeSymbol, schema),
301 ...(acceptsUndefined ? { acceptsUndefined: true } : {}),
302 })
303 },
304 descriptor(def: Record<string, unknown>) {
305 return Object.freeze({ ...def })
306 },
307 })
308
309 export class TypertRemoteService extends Service {
310 readonly descriptors: readonly unknown[]
311 constructor(ctx: any, name: string, descriptors: readonly unknown[] = []) {
312 super(ctx, name)
313 this.descriptors = Object.freeze([...descriptors])
314 }
315 getDescriptors(): readonly unknown[] {
316 return this.descriptors
317 }
318 }
319
320 export const dshTypertProtocolModule = Object.freeze({
321 Remote,
322 TypertRemoteService,
323 })
324
325 // ---------------------------------------------------------------------------
326 // Additional pure DSH helper shims observed in survey tarballs
327 // ---------------------------------------------------------------------------
328 export function WorkspaceId(id: string): string {
329 return id
330 }
331
332 export const dshWorkspaceModule = Object.freeze({
333 WorkspaceId,
334 })
335
336 export function isSurfaceEligibleType(type: unknown): boolean {
337 return typeof type === 'string' && (
338 type === 'message/user'
339 || type === 'message/assistant'
340 || type === 'tool/call'
341 || type === 'tool/result'
342 )
343 }
344
345 export function foldSurface(events: readonly unknown[]): readonly unknown[] {
346 if (!Array.isArray(events)) return []
347 return events.filter((event: any) => event && typeof event === 'object' && isSurfaceEligibleType(event.type))
348 }
349
350 export const dshSessionSurfaceModule = Object.freeze({
351 foldSurface,
352 isSurfaceEligibleType,
353 })
354
355 export class SubagentError extends HarnessError {
356 constructor(message: string, code = 'SUBAGENT_ERROR', options?: ErrorOptions) {
357 super(message, code, options)
358 this.name = 'SubagentError'
359 }
360 }
361
362 export function foldSubagentDescriptor(events: readonly unknown[]): Record<string, unknown> {
363 const out: Record<string, unknown> = { status: 'idle', count: 0 }
364 if (!Array.isArray(events)) return out
365 for (const ev of events as any[]) {
366 if (!ev || typeof ev !== 'object') continue
367 if (ev.type === 'subagent/start') {
368 out.status = 'running'
369 out.count = (out.count as number) + 1
370 } else if (ev.type === 'subagent/end') {
371 out.status = 'completed'
372 }
373 }
374 return out
375 }
376
377 export function snapshotSubagentDescriptor(descriptor: unknown): Record<string, unknown> {
378 if (!descriptor || typeof descriptor !== 'object') return { status: 'idle' }
379 return structuredClone(descriptor as Record<string, unknown>)
380 }
381
382 export const dshSubagentModule = Object.freeze({
383 SubagentError,
384 foldSubagentDescriptor,
385 snapshotSubagentDescriptor,
386 })
387
388 export function assembleContextFor(messages: readonly unknown[] = []): readonly unknown[] {
389 return Array.isArray(messages) ? [...messages] : []
390 }
391
392 export function installModelSelection(_ctx: unknown, _options?: unknown): () => void {
393 return () => undefined
394 }
395
396 export const dshAgentModule = Object.freeze({
397 assembleContextFor,
398 installModelSelection,
399 })
400
401 export function getDshRuntimeVersion(): string {
402 return compatibility.target_dsh_version
403 }
404
405 export function loadProfileDirectory(): never {
406 throw new RpcError(ErrorCode.NotAvailable, 'dsh-app-boot profile directory loading is not available in Codewhale')
407 }
408
409 export function resolveBundleDir(): never {
410 throw new RpcError(ErrorCode.NotAvailable, 'dsh-app-boot bundle resolution is not available in Codewhale')
411 }
412
413 export async function createRuntimeResolution(): Promise<never> {
414 throw new RpcError(ErrorCode.NotAvailable, 'dsh-app-boot runtime resolution is not available in Codewhale')
415 }
416
417 export const dshAppBootModule = Object.freeze({
418 getDshRuntimeVersion,
419 loadProfileDirectory,
420 resolveBundleDir,
421 createRuntimeResolution,
422 })
423
423 lines TYPESCRIPT