@allbluecn/dsh-compat 0.0.0-stage → 0.0.1

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.
@@ -0,0 +1,135 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ import { describe, expect, it } from 'vitest'
3
+ import type { AnyChatMiddleware } from '@tanstack/ai'
4
+ import { CordisEventBus, DSH_EVENT_TO_HOOK, KNOWN_DSH_EVENTS } from '../events'
5
+
6
+ /** 造一个 CordisEventBus + 已 drain 的 middleware 映射。 */
7
+ function busWithHandlers(
8
+ register: (bus: CordisEventBus) => void,
9
+ ): { bus: CordisEventBus; middleware: Array<AnyChatMiddleware> } {
10
+ const bus = new CordisEventBus()
11
+ register(bus)
12
+ return { bus, middleware: bus.drainMiddleware() }
13
+ }
14
+
15
+ describe('事件映射表', () => {
16
+ it('已知事件映射到正确 middleware 钩子', () => {
17
+ expect(DSH_EVENT_TO_HOOK['pre-execute']).toBe('onBeforeToolCall')
18
+ expect(DSH_EVENT_TO_HOOK['post-execute']).toBe('onAfterToolCall')
19
+ expect(DSH_EVENT_TO_HOOK.llm).toBe('onChunk')
20
+ expect(DSH_EVENT_TO_HOOK.stream).toBe('onChunk')
21
+ expect(DSH_EVENT_TO_HOOK['turn-stopping']).toBe('onShouldContinue')
22
+ expect(KNOWN_DSH_EVENTS.has('pre-execute')).toBe(true)
23
+ expect(KNOWN_DSH_EVENTS.has('unknown-thing')).toBe(false)
24
+ })
25
+ })
26
+
27
+ describe('已知事件 → middleware 钩子', () => {
28
+ it('pre-execute → onBeforeToolCall;skip 决策翻译成 { type: skip, result }', () => {
29
+ const { middleware } = busWithHandlers((bus) => {
30
+ bus.on('pre-execute', (hookCtx) => {
31
+ const name = (hookCtx as { toolName: string }).toolName
32
+ return name === 'danger' ? { type: 'skip', result: { blocked: true } } : undefined
33
+ })
34
+ })
35
+ const mw = middleware[0]
36
+ expect(mw.onBeforeToolCall).toBeTypeOf('function')
37
+ const decision = mw.onBeforeToolCall?.({} as never, {
38
+ toolName: 'danger',
39
+ args: {},
40
+ } as never)
41
+ expect(decision).toEqual({ type: 'skip', result: { blocked: true } })
42
+ // 非 danger 工具:undefined(放行)
43
+ const pass = mw.onBeforeToolCall?.({} as never, { toolName: 'safe' } as never)
44
+ expect(pass).toBeUndefined()
45
+ })
46
+
47
+ it('post-execute → onAfterToolCall;replaceResult 语义', () => {
48
+ const { middleware } = busWithHandlers((bus) => {
49
+ bus.on('post-execute', () => ({ type: 'replaceResult', result: { patched: 1 } }))
50
+ })
51
+ const mw = middleware[0]
52
+ const decision = mw.onAfterToolCall?.({} as never, {
53
+ toolName: 't',
54
+ result: { original: 0 },
55
+ } as never)
56
+ expect(decision).toEqual({ type: 'replaceResult', result: { patched: 1 } })
57
+ })
58
+
59
+ it('llm / stream → onChunk(每个 chunk 派发)', () => {
60
+ const seenLlm: Array<unknown> = []
61
+ const seenStream: Array<unknown> = []
62
+ const { middleware } = busWithHandlers((bus) => {
63
+ bus.on('llm', (chunk) => {
64
+ seenLlm.push(chunk)
65
+ })
66
+ bus.on('stream', (chunk) => {
67
+ seenStream.push(chunk)
68
+ })
69
+ })
70
+ const chunk = { type: 'TEXT_MESSAGE_CONTENT', delta: 'hi' }
71
+ for (const mw of middleware) mw.onChunk?.({} as never, chunk as never)
72
+ expect(seenLlm).toContain(chunk)
73
+ expect(seenStream).toContain(chunk)
74
+ // onChunk 返回 undefined → chunk 原样透传(不改写流)
75
+ expect(middleware.every((mw) => mw.onChunk?.({} as never, chunk as never) === undefined)).toBe(true)
76
+ })
77
+
78
+ it('turn-stopping → onShouldContinue;stop 语义返回 false 终止 loop', () => {
79
+ const { middleware } = busWithHandlers((bus) => {
80
+ bus.on('turn-stopping', () => 'stop')
81
+ })
82
+ const mw = middleware[0]
83
+ expect(mw.onShouldContinue?.({} as never, {} as never)).toBe(false)
84
+ })
85
+
86
+ it('turn-stopping:非 stop 返回值不终止(undefined)', () => {
87
+ const { middleware } = busWithHandlers((bus) => {
88
+ bus.on('turn-stopping', () => 'continue')
89
+ })
90
+ expect(middleware[0].onShouldContinue?.({} as never, {} as never)).toBeUndefined()
91
+ })
92
+
93
+ it('无已知事件处理器 → drainMiddleware 不产出空 middleware', () => {
94
+ const bus = new CordisEventBus()
95
+ bus.on('unknown-thing', () => {})
96
+ expect(bus.drainMiddleware()).toEqual([])
97
+ })
98
+ })
99
+
100
+ describe('未知事件 → 包内互通总线', () => {
101
+ it('emit 派发给所有 on 订阅者', () => {
102
+ const bus = new CordisEventBus()
103
+ const got: Array<unknown> = []
104
+ bus.on('dsh:custom', (v) => got.push(v))
105
+ bus.on('dsh:custom', (v) => got.push(`second:${String(v)}`))
106
+ bus.emit('dsh:custom', 42)
107
+ expect(got).toEqual([42, 'second:42'])
108
+ })
109
+
110
+ it('off 注销后不再接收', () => {
111
+ const bus = new CordisEventBus()
112
+ const got: Array<unknown> = []
113
+ const off = bus.on('dsh:custom', (v) => got.push(v))
114
+ off()
115
+ bus.emit('dsh:custom', 1)
116
+ expect(got).toEqual([])
117
+ })
118
+
119
+ it('waterfall 依次过订阅者,每层返回值作为下一层入参', () => {
120
+ const bus = new CordisEventBus()
121
+ bus.on('pipe', (v) => (typeof v === 'number' ? v + 1 : v))
122
+ bus.on('pipe', (v) => (typeof v === 'number' ? v * 2 : v))
123
+ expect(bus.waterfall('pipe', 3)).toBe(8) // (3+1)*2
124
+ // 无订阅者:原值返回
125
+ expect(bus.waterfall('nobody', 'x')).toBe('x')
126
+ })
127
+
128
+ it('已知事件也可经包内总线在插件间互通(ctx.on 订阅)', () => {
129
+ const bus = new CordisEventBus()
130
+ const got: Array<unknown> = []
131
+ bus.on('pre-execute', (v) => got.push(v))
132
+ bus.emit('pre-execute', 'direct')
133
+ expect(got).toEqual(['direct'])
134
+ })
135
+ })
@@ -0,0 +1,157 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ import { describe, expect, it } from 'vitest'
3
+ import type { CordisToolDef } from '../context'
4
+ import {
5
+ adapterNotes,
6
+ dshToolToTanStack,
7
+ sanitizeJsonSchema,
8
+ } from '../tool-adapter'
9
+
10
+ describe('sanitizeJsonSchema(provider 不认关键字净化)', () => {
11
+ it('剥离 draft-04 exclusiveMinimum/Maximum 与冷门关键字,保留通用关键字', () => {
12
+ const schema = {
13
+ type: 'object',
14
+ properties: {
15
+ age: { type: 'number', minimum: 0, exclusiveMinimum: 0 },
16
+ score: { type: 'number', maximum: 100, exclusiveMaximum: 100 },
17
+ tag: { type: 'string', contains: 'x' },
18
+ },
19
+ required: ['age'],
20
+ $schema: 'http://json-schema.org/draft-04/schema#',
21
+ }
22
+ const out = sanitizeJsonSchema(schema) as Record<string, any>
23
+ expect(out.$schema).toBeUndefined()
24
+ expect(out.type).toBe('object')
25
+ expect(out.required).toEqual(['age'])
26
+ expect(out.properties.age).toEqual({ type: 'number', minimum: 0 })
27
+ expect(out.properties.score).toEqual({ type: 'number', maximum: 100 })
28
+ expect(out.properties.tag).toEqual({ type: 'string' })
29
+ })
30
+
31
+ it('递归净化嵌套 items / 不改动入参', () => {
32
+ const schema = {
33
+ type: 'array',
34
+ items: { type: 'number', exclusiveMinimum: 5, description: 'd' },
35
+ }
36
+ const out = sanitizeJsonSchema(schema) as Record<string, any>
37
+ expect(out.items).toEqual({ type: 'number', description: 'd' })
38
+ // 入参未被改动
39
+ expect((schema.items as any).exclusiveMinimum).toBe(5)
40
+ })
41
+ })
42
+
43
+ function baseDef(over: Partial<CordisToolDef> = {}): CordisToolDef {
44
+ return {
45
+ name: 'dsh_deploy',
46
+ description: 'Deploy and render a card.',
47
+ parameters: {
48
+ type: 'object',
49
+ properties: { region: { type: 'string', exclusiveMinimum: 0 } },
50
+ required: ['region'],
51
+ },
52
+ execute: () => ({ ok: true }),
53
+ ...over,
54
+ }
55
+ }
56
+
57
+ describe('dshToolToTanStack', () => {
58
+ it('parameters → inputSchema 直传(净化后),description 透传', () => {
59
+ const tool = dshToolToTanStack(baseDef())
60
+ expect(tool.name).toBe('dsh_deploy')
61
+ expect(tool.description).toBe('Deploy and render a card.')
62
+ const schema = tool.inputSchema as Record<string, any>
63
+ expect(schema.type).toBe('object')
64
+ expect(schema.required).toEqual(['region'])
65
+ // 净化生效:exclusiveMinimum 被剥掉
66
+ expect(schema.properties.region).toEqual({ type: 'string' })
67
+ })
68
+
69
+ it('output.schema → outputSchema', () => {
70
+ const tool = dshToolToTanStack(
71
+ baseDef({ output: { schema: { type: 'object' } } }),
72
+ )
73
+ expect(tool.outputSchema).toEqual({ type: 'object' })
74
+ })
75
+
76
+ it('deferLoading → lazy: true;否则无 lazy', () => {
77
+ expect(dshToolToTanStack(baseDef({ deferLoading: true })).lazy).toBe(true)
78
+ expect(dshToolToTanStack(baseDef()).lazy).toBeUndefined()
79
+ })
80
+
81
+ it('execute 适配上下文:abortSignal/runId → CordisToolRunContext', async () => {
82
+ let seen: unknown
83
+ const controller = new AbortController()
84
+ const def = baseDef({
85
+ execute: (args, ctx) => {
86
+ seen = ctx
87
+ return { ok: true, region: (args as { region: string }).region }
88
+ },
89
+ })
90
+ const tool = dshToolToTanStack(def)
91
+ const result = (await tool.execute?.(
92
+ { region: 'cn-north-1' },
93
+ { abortSignal: controller.signal, runId: 'run-9', emitCustomEvent: () => {} } as never,
94
+ )) as Record<string, unknown>
95
+ expect(result.ok).toBe(true)
96
+ expect(seen).toEqual({ signal: controller.signal, caller: 'run-9' })
97
+ })
98
+
99
+ it('presenter 产出 __dshView(通道 A)', async () => {
100
+ const VIEW = { kind: 'card', title: 't', rows: [] }
101
+ const def = baseDef({
102
+ execute: () => ({ ok: true }),
103
+ presentResult: () => VIEW,
104
+ })
105
+ const tool = dshToolToTanStack(def)
106
+ const result = (await tool.execute?.({ region: 'x' })) as Record<string, unknown>
107
+ expect(result.__dshView).toEqual(VIEW)
108
+ expect(result.ok).toBe(true)
109
+ })
110
+
111
+ it('presenter 抛错 → 无 __dshView(视图缺省,软校验)', async () => {
112
+ const def = baseDef({
113
+ execute: () => ({ ok: true }),
114
+ presentResult: () => {
115
+ throw new Error('presenter boom')
116
+ },
117
+ })
118
+ const tool = dshToolToTanStack(def)
119
+ const result = (await tool.execute?.({ region: 'x' })) as Record<string, unknown>
120
+ expect(result.__dshView).toBeUndefined()
121
+ expect(result.ok).toBe(true)
122
+ })
123
+
124
+ it('timeoutMs 超时 → execute reject', async () => {
125
+ const def = baseDef({
126
+ timeoutMs: 20,
127
+ execute: () =>
128
+ new Promise((_resolve) => setTimeout(() => _resolve({ ok: 1 }), 5000)),
129
+ })
130
+ const tool = dshToolToTanStack(def)
131
+ await expect(tool.execute?.({ region: 'x' })).rejects.toThrow(/timed out/)
132
+ })
133
+
134
+ it('DSH execute 抛错 → 官方 execute reject(工具失败,模型收到 error)', async () => {
135
+ const def = baseDef({
136
+ execute: () => {
137
+ throw new Error('dsh boom')
138
+ },
139
+ })
140
+ const tool = dshToolToTanStack(def)
141
+ await expect(tool.execute?.({ region: 'x' })).rejects.toThrow('dsh boom')
142
+ })
143
+
144
+ it('adapterNotes 记录官方无对应字段', () => {
145
+ const notes = adapterNotes(
146
+ baseDef({
147
+ isConcurrencySafe: true,
148
+ projectContent: {},
149
+ presentCall: () => ({}),
150
+ }),
151
+ )
152
+ expect(notes).toContain('isConcurrencySafe')
153
+ expect(notes).toContain('projectContent')
154
+ expect(notes.some((n) => n.startsWith('presentCall'))).toBe(true)
155
+ expect(adapterNotes(baseDef())).toEqual([])
156
+ })
157
+ })
@@ -0,0 +1,166 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ import { describe, expect, it } from 'vitest'
3
+ import type { AnyChatMiddleware, ModelMessage } from '@tanstack/ai'
4
+ import {
5
+ MAX_DSH_VIEW_JSON_BYTES,
6
+ attachView,
7
+ dshViewField,
8
+ stripDshViewMiddleware,
9
+ } from '../view-bridge'
10
+
11
+ const VIEW = { kind: 'card', title: '部署完成', rows: [{ label: 'r', value: 'v' }] }
12
+
13
+ describe('attachView(通道 A 挂载)', () => {
14
+ it('对象 result 挂 __dshView', () => {
15
+ const out = attachView(() => VIEW, { region: 'cn' }, { ok: true }) as Record<
16
+ string,
17
+ unknown
18
+ >
19
+ expect(out.__dshView).toEqual(VIEW)
20
+ expect(out.ok).toBe(true)
21
+ })
22
+
23
+ it('带 name 的视图挂到 __dshView_<name>(多视图并存 key)', () => {
24
+ const named = { ...VIEW, name: 'sidebar' }
25
+ expect(dshViewField(named)).toBe('__dshView_sidebar')
26
+ const out = attachView(() => named, {}, { ok: 1 }) as Record<string, unknown>
27
+ expect(out.__dshView_sidebar).toEqual(named)
28
+ expect(out.__dshView).toBeUndefined()
29
+ })
30
+
31
+ it('非对象 result 包装成 { value, __dshView }', () => {
32
+ const out = attachView(() => VIEW, {}, 'plain-text') as Record<string, unknown>
33
+ expect(out.value).toBe('plain-text')
34
+ expect(out.__dshView).toEqual(VIEW)
35
+ })
36
+
37
+ it('presenter 未定义 → 原样返回,不挂', () => {
38
+ const result = { ok: true }
39
+ expect(attachView(undefined, {}, result)).toBe(result)
40
+ })
41
+
42
+ it('presenter 抛错 → 视图缺省不挂(软校验,不 fail turn)', () => {
43
+ const result = { ok: true }
44
+ const out = attachView(
45
+ () => {
46
+ throw new Error('presenter boom')
47
+ },
48
+ {},
49
+ result,
50
+ )
51
+ expect(out).toBe(result)
52
+ expect((out as Record<string, unknown>).__dshView).toBeUndefined()
53
+ })
54
+
55
+ it('presenter 产出非法视图(标量/数组)→ 不挂', () => {
56
+ expect((attachView(() => 'nope', {}, { ok: 1 }) as Record<string, unknown>).__dshView).toBeUndefined()
57
+ expect((attachView(() => [1, 2], {}, { ok: 1 }) as Record<string, unknown>).__dshView).toBeUndefined()
58
+ })
59
+
60
+ it('超大视图截断为占位(不挂原始大对象)', () => {
61
+ const big = { kind: 'card', title: 'x'.repeat(MAX_DSH_VIEW_JSON_BYTES + 10) }
62
+ const out = attachView(() => big, {}, { ok: 1 }) as Record<string, unknown>
63
+ const attached = out.__dshView as Record<string, unknown>
64
+ expect(attached.kind).toBe('dsh-view-truncated')
65
+ expect(attached.__dshViewTruncated).toBe(true)
66
+ })
67
+ })
68
+
69
+ /** 造一条带 __dshView 的 tool 消息 + 若干前缀消息。 */
70
+ function messagesWithView(): Array<ModelMessage> {
71
+ return [
72
+ { role: 'user', content: 'deploy to cn-north-1' },
73
+ {
74
+ role: 'assistant',
75
+ content: '',
76
+ // 简化:assistant 工具调用消息在本测试里用文本占位,前缀一致性只关心 user/assistant 不被剥除改写。
77
+ },
78
+ {
79
+ role: 'tool',
80
+ content: JSON.stringify({ ok: true, region: 'cn-north-1', __dshView: VIEW }),
81
+ toolCallId: 'call-1',
82
+ toolName: 'dsh_deploy',
83
+ } as ModelMessage,
84
+ ]
85
+ }
86
+
87
+ describe('stripDshViewMiddleware(通道 A 剥除)', () => {
88
+ const mw = stripDshViewMiddleware()
89
+
90
+ function runOnConfig(messages: Array<ModelMessage>) {
91
+ const captured: Array<ReadonlyArray<ModelMessage>> = []
92
+ const capture: AnyChatMiddleware = {
93
+ name: 'capture',
94
+ onConfig: (_ctx, config) => {
95
+ captured.push(config.providerMessages ?? config.messages)
96
+ return undefined
97
+ },
98
+ }
99
+ // 直接同步调用 onConfig:先剥除 middleware,再 capture 观察剥除后的 providerMessages。
100
+ const config = { messages, providerMessages: messages } as never
101
+ const partial = mw.onConfig?.({} as never, config)
102
+ const stripped = (partial as { providerMessages?: Array<ModelMessage> } | undefined)
103
+ ?.providerMessages
104
+ // 把剥除结果喂给 capture,模拟链式 onConfig。
105
+ capture.onConfig?.({} as never, {
106
+ messages,
107
+ providerMessages: stripped ?? messages,
108
+ } as never)
109
+ return { partial, stripped: stripped ?? messages, seen: captured[0] ?? [] }
110
+ }
111
+
112
+ it('只返回 providerMessages(canonical messages 不动)', () => {
113
+ const messages = messagesWithView()
114
+ const { partial } = runOnConfig(messages)
115
+ const keys = Object.keys((partial as Record<string, unknown>) ?? {})
116
+ expect(keys).toEqual(['providerMessages'])
117
+ })
118
+
119
+ it('剥除后 tool 消息不含 __dshView,非 tool 消息原样', () => {
120
+ const messages = messagesWithView()
121
+ const { stripped } = runOnConfig(messages)
122
+ const toolMsg = stripped.find((m) => m.role === 'tool')
123
+ expect(String(toolMsg?.content)).not.toContain('__dshView')
124
+ expect(JSON.parse(String(toolMsg?.content))).toEqual({ ok: true, region: 'cn-north-1' })
125
+ expect(stripped[0]).toBe(messages[0]) // user 消息引用不变(前缀未被改写)
126
+ })
127
+
128
+ it('多视图并存:剥除 __dshView 与 __dshView_<name> 全部字段', () => {
129
+ const messages: Array<ModelMessage> = [
130
+ {
131
+ role: 'tool',
132
+ content: JSON.stringify({
133
+ ok: 1,
134
+ __dshView: VIEW,
135
+ __dshView_sidebar: { ...VIEW, name: 'sidebar' },
136
+ }),
137
+ toolCallId: 'c',
138
+ toolName: 't',
139
+ } as ModelMessage,
140
+ ]
141
+ const { stripped } = runOnConfig(messages)
142
+ expect(JSON.parse(String(stripped[0].content))).toEqual({ ok: 1 })
143
+ })
144
+
145
+ it('carry-forward 前缀一致性:剥除只动后缀,prefix(剥除前 tool 消息之前的消息)逐字节不变', () => {
146
+ const messages = messagesWithView()
147
+ const prefix = messages.slice(0, 2) // user + assistant,位于带 __dshView 的 tool 消息之前
148
+ const { stripped } = runOnConfig(messages)
149
+ const strippedPrefix = stripped.slice(0, 2)
150
+ // 前缀逐条 deep-equal(同一引用,未被改写)→ 跨回合 prompt cache 前缀稳定。
151
+ expect(strippedPrefix).toEqual(prefix)
152
+ expect(strippedPrefix[0]).toBe(prefix[0])
153
+ expect(strippedPrefix[1]).toBe(prefix[1])
154
+ // 变化只落在 tool 消息(后缀),且只是去掉 __dshView 字段
155
+ expect(stripped[2].role).toBe('tool')
156
+ expect(String(stripped[2].content)).not.toContain('__dshView')
157
+ })
158
+
159
+ it('无 __dshView 时 onConfig 返回 undefined(不触碰 providerMessages)', () => {
160
+ const messages: Array<ModelMessage> = [
161
+ { role: 'tool', content: JSON.stringify({ ok: true }), toolCallId: 'c', toolName: 't' } as ModelMessage,
162
+ ]
163
+ const partial = mw.onConfig?.({} as never, { messages } as never)
164
+ expect(partial).toBeUndefined()
165
+ })
166
+ })