@tbox.cn/tboxcode-dsh-llm 0.0.0-stage → 0.1.0-rc.10

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,210 @@
1
+ import { GenerateOptions, LlmAdapter, LlmModelInfo, LlmResolvedModelInfo, StreamChunk } from "@deepseek-ai/dsh-llm";
2
+ import { Context } from "@deepseek-ai/cordis";
3
+
4
+ //#region src/scenario/scripted-adapter.d.ts
5
+ declare const name = "tboxcode-llm-scenario";
6
+ declare const inject: string[];
7
+ /** 行为词表(MOCK_LLM_BEHAVIORS 子集的 adapter 侧语义;字符串形态为速记)。 */
8
+ type BehaviorSpec = 'echo' | 'success' | 'empty' | {
9
+ kind: 'echo';
10
+ } | {
11
+ kind: 'success';
12
+ text?: string;
13
+ } | {
14
+ kind: 'empty';
15
+ }
16
+ /** 长活跃 turn 唯一正解(stall 会被 llm-retry 超时重试消费——spike-hmr 实证)。 */ | {
17
+ kind: 'slow_success';
18
+ chunkDelayMs: number;
19
+ chunks: number;
20
+ text?: string;
21
+ }
22
+ /** 声明式工具调用:发出 tool_call 块后以 tool-calls 收尾(驱动 client 工具循环)。 */ | {
23
+ kind: 'tool_call_success';
24
+ tool: string;
25
+ arguments?: string;
26
+ }
27
+ /** finish error 形态的限流(LlmFailure.rate_limit——经 llm-retry 消费)。 */ | {
28
+ kind: 'rate_limit';
29
+ retryAfterMs?: number;
30
+ }
31
+ /** 流中抛 TRANSPORT 码(经 llm-retry 消费)。 */ | {
32
+ kind: 'connection_reset';
33
+ }
34
+ /** finish max-tokens(截断语义)。 */ | {
35
+ kind: 'max_tokens';
36
+ text?: string;
37
+ };
38
+ type NormalizedBehavior = {
39
+ kind: 'echo';
40
+ } | {
41
+ kind: 'success';
42
+ text?: string;
43
+ } | {
44
+ kind: 'empty';
45
+ } | {
46
+ kind: 'slow_success';
47
+ chunkDelayMs: number;
48
+ chunks: number;
49
+ text?: string;
50
+ } | {
51
+ kind: 'tool_call_success';
52
+ tool: string;
53
+ arguments?: string;
54
+ } | {
55
+ kind: 'rate_limit';
56
+ retryAfterMs?: number;
57
+ } | {
58
+ kind: 'connection_reset';
59
+ } | {
60
+ kind: 'max_tokens';
61
+ text?: string;
62
+ };
63
+ /** 单请求捕获记录(JSONL 一行;messages 原样序列化——branded 字段 JSON 安全)。 */
64
+ interface ScenarioCapture {
65
+ /** 请求序号(适配器级单调递增,跨 session 连续;含辅助调用)。 */
66
+ index: number;
67
+ /** 主对话请求(purpose 空)= true;辅助调用(session-title / compaction)= false。 */
68
+ main: boolean;
69
+ messages: unknown;
70
+ system?: string;
71
+ tools?: unknown;
72
+ model?: string;
73
+ reasoningEffort?: string;
74
+ sessionId?: string;
75
+ purpose?: string;
76
+ /** 行为消耗(对照脚本序号——重试消耗语义的对账锚;辅助调用 = aux:<purpose>)。 */
77
+ behavior: string;
78
+ }
79
+ interface ScenarioDriverConfig {
80
+ /** FIFO 行为脚本(每 stream 消费一条)。 */
81
+ script: BehaviorSpec[];
82
+ /** 捕获 JSONL 落盘路径(缺省不落盘——纯进程内消费场景)。 */
83
+ captureFile?: string;
84
+ /** barrier 目录(缺省不启用 barrier 门)。 */
85
+ barrierDir?: string;
86
+ /** barrier 等待超时 ms(缺省 10s)。 */
87
+ barrierTimeoutMs?: number;
88
+ }
89
+ declare function normalizeBehavior(spec: BehaviorSpec): NormalizedBehavior;
90
+ declare function behaviorLabel(spec: BehaviorSpec): string;
91
+ /** 提取最后一条用户消息的可见文本(跳过 reminder 注入块——回显目标是人类输入)。 */
92
+ declare function lastUserText(messages: GenerateOptions['messages']): string | undefined;
93
+ declare class ScenarioAdapter extends LlmAdapter {
94
+ #private;
95
+ constructor(config: ScenarioDriverConfig);
96
+ /** 已消费行为数(进程内对账面;跨进程断言走 captureFile 的 index/behavior 字段)。 */
97
+ get consumed(): number;
98
+ listModels(provider: string): Promise<readonly LlmModelInfo[]>;
99
+ resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo>;
100
+ stream(options: GenerateOptions): AsyncIterable<StreamChunk>;
101
+ }
102
+ /** cordis 插件入口:注册 scenario provider 路由;apply 返回 disposer 释放注册。 */
103
+ declare function apply(ctx: Context, config: ScenarioDriverConfig): () => void;
104
+ //#endregion
105
+ //#region src/scenario/interpreter.d.ts
106
+ interface CaptureRecord {
107
+ index: number;
108
+ /** 主对话请求(purpose 空)= true;辅助调用(session-title / compaction)= false。 */
109
+ main?: boolean;
110
+ messages: unknown;
111
+ system?: string;
112
+ tools?: unknown;
113
+ model?: string;
114
+ reasoningEffort?: string;
115
+ sessionId?: string;
116
+ purpose?: string;
117
+ behavior: string;
118
+ }
119
+ /** 解释器 IO 面(L3 harness 实装;单测 stub)。 */
120
+ interface ScenarioIO {
121
+ /** 全量捕获记录(capture JSONL 解析,按 index 序)。 */
122
+ captured(): readonly CaptureRecord[];
123
+ /** wire 事件 type 序列(wireCollector 顺序记录)。 */
124
+ events(): readonly string[];
125
+ /** ACP 侧回显聚合文本(agent_message_chunk text 拼接)。 */
126
+ echoed(): string;
127
+ prompt(text: string): Promise<void>;
128
+ waitTurnEnd(timeoutMs: number): Promise<void>;
129
+ /** configOptions mode 通道(harness 实装 = set_config_option configId='mode')。 */
130
+ setMode(value: string): Promise<void>;
131
+ /** ACP session/cancel 通知(中止在飞 turn)。 */
132
+ cancel(): Promise<void>;
133
+ }
134
+ type AssertionSpec = {
135
+ updateSequence: readonly (string | '*')[];
136
+ } | {
137
+ captureLens: {
138
+ request: number;
139
+ path: string;
140
+ equals?: unknown;
141
+ contains?: string;
142
+ notContains?: string;
143
+ };
144
+ } | {
145
+ snapshotPath: {
146
+ file: string;
147
+ pointer: string;
148
+ equals: unknown;
149
+ };
150
+ } | {
151
+ crossCapture: {
152
+ a: {
153
+ request: number;
154
+ path: string;
155
+ };
156
+ b: {
157
+ request: number;
158
+ path: string;
159
+ };
160
+ op: 'equals' | 'prefix';
161
+ };
162
+ } | {
163
+ echoEquals: string;
164
+ } | {
165
+ negate: AssertionSpec;
166
+ };
167
+ interface AssertionResult {
168
+ pass: boolean;
169
+ detail: string;
170
+ }
171
+ /** 点路径取值:数字段 = 数组索引(负值 = 从末尾反数,-1 = 末元素);对象段 = 键。缺位返回 undefined。 */
172
+ declare function getByPath(root: unknown, path: string): unknown;
173
+ /** 连续子序列匹配:expected 按序且连续出现于 actual;`*` 通配单元素。 */
174
+ declare function matchesSubsequence(actual: readonly string[], expected: readonly (string | '*')[]): boolean;
175
+ declare function evaluateAssertion(spec: AssertionSpec, io: ScenarioIO, snapshotReader?: (file: string, pointer: string) => unknown): AssertionResult;
176
+ type ActionSpec = {
177
+ prompt: string;
178
+ } | {
179
+ waitTurnEnd: number;
180
+ } | {
181
+ pause: number;
182
+ }
183
+ /** configOptions mode 通道(C4 交付:set_config_option configId='mode')。 */ | {
184
+ setMode: string;
185
+ }
186
+ /** ACP session/cancel 通知(中止在飞 turn——llm-retry 的 abort 消费面)。 */ | {
187
+ cancel: true;
188
+ }
189
+ /** 发起 prompt 但不等待完成(cancel 场景的编排原语——流中取消)。 */ | {
190
+ promptNoWait: string;
191
+ };
192
+ interface ScenarioFixture {
193
+ name: string;
194
+ /** 驱动脚本(写入 scenario 行 config——harness 消费)。 */
195
+ script: BehaviorSpec[];
196
+ /** 场景自有 overlay 行(harness 追加 --patch;翻译覆盖 / 行禁用等)。 */
197
+ overlays?: unknown[][];
198
+ /** 场景差异 config 节(harness 拼进场景 config.jsonc——launch 全量翻译消费)。 */
199
+ configExtra?: Record<string, unknown>;
200
+ /** 开启 TBOXCODE_LLM_LOG=1(llm-calls 落盘容忍场景)。 */
201
+ llmLog?: boolean;
202
+ actions: readonly ActionSpec[];
203
+ assertions: readonly AssertionSpec[];
204
+ }
205
+ /** 动作编排执行;返回全部断言求值结果(调用方判定全绿 / 打印失败明细)。 */
206
+ declare function runScenario(fixture: ScenarioFixture, io: ScenarioIO, snapshotReader?: (file: string, pointer: string) => unknown): Promise<AssertionResult[]>;
207
+ /** capture JSONL 读取(harness 的 captured() 实装基元;文件缺位 = 空捕获)。 */
208
+ declare function readCaptureFile(file: string): Promise<CaptureRecord[]>;
209
+ //#endregion
210
+ export { type ActionSpec, type AssertionResult, type AssertionSpec, type BehaviorSpec, type CaptureRecord, type NormalizedBehavior, ScenarioAdapter, type ScenarioCapture, type ScenarioDriverConfig, type ScenarioFixture, type ScenarioIO, apply, behaviorLabel, evaluateAssertion, getByPath, inject, lastUserText, matchesSubsequence, name, normalizeBehavior, readCaptureFile, runScenario };
@@ -0,0 +1,3 @@
1
+ import{appendFile as e,mkdir as t,readFile as n,writeFile as r}from"node:fs/promises";import{join as i}from"node:path";import{LlmAdapter as a,LlmError as o}from"@deepseek-ai/dsh-llm";import{existsSync as s}from"node:fs";const c=`tboxcode-llm-scenario`,l=[`llm`];function u(e){return typeof e==`string`?{kind:e}:e}function d(e){return typeof e==`string`?e:e.kind}function f(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n?.role!==`user`||!Array.isArray(n.content))continue;let r=n.content.filter(e=>e?.type===`text`&&!e.text.includes(`<system-reminder>`)).map(e=>e.text).join(`
2
+ `).trim();if(r.length>0)return r}}function p(e,t){return e<=0?Promise.resolve():new Promise((n,r)=>{let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(t.reason)},{once:!0})})}async function m(e,n,a){await t(e,{recursive:!0}),await r(i(e,`${n}.wait`),String(Date.now()),`utf-8`);let c=i(e,`${n}.release`),l=Date.now()+a;for(;!s(c);){if(Date.now()>l)throw new o(`scenario barrier ${n} 超时(${a}ms)——release 文件未出现`,`TRANSPORT`);await p(25,void 0)}}var h=class extends a{#e;#t=0;#n=0;constructor(e){super(),this.#e=e}get consumed(){return this.#t}listModels(e){return Promise.resolve([{provider:e,id:`scenario`,name:`Scenario`,description:`scenario driver——声明式行为脚本(场景套件)`,inputModalities:[`text`]}])}async resolveModel(e,t){return{provider:e,id:t,name:t,context:{contextWindow:128e3}}}#r(){if(this.#t>=this.#e.script.length)throw new o(`scenario script 耗尽(已消费 ${this.#t}/${this.#e.script.length})——场景编排不足`,`INVALID_REQUEST`);return u(this.#e.script[this.#t++])}async#i(t,n,r,i=!0){let a={index:this.#n++,main:i,messages:t.messages,system:t.system,tools:t.tools,model:t.model,reasoningEffort:t.reasoningEffort,sessionId:t.sessionId,purpose:t.purpose,behavior:r??n.kind};this.#e.captureFile!==void 0&&await e(this.#e.captureFile,`${JSON.stringify(a)}\n`,`utf-8`)}async#a(e){this.#e.barrierDir!==void 0&&await m(this.#e.barrierDir,e,this.#e.barrierTimeoutMs??1e4)}async*stream(e){if(e.purpose!==void 0){await this.#i(e,{kind:`empty`},`aux:${e.purpose}`,!1),yield*this.#o({kind:`empty`},e);return}let t=this.#r();await this.#i(e,t,void 0,!0),await this.#a(`req-${this.#n-1}`),yield*this.#o(t,e)}async*#o(e,t){switch(e.kind){case`connection_reset`:throw new o(`scenario connection_reset——模拟传输中断`,`TRANSPORT`);case`rate_limit`:yield{type:`finish`,reason:{kind:`error`,failure:{message:`scenario rate_limit——模拟 429`,code:`RATE_LIMIT`,status:429,providerRetryAfterMs:e.retryAfterMs}}};return;case`tool_call_success`:{let t=e.arguments??`{}`;yield{type:`block-start`,index:0,blockType:`tool-call`},yield{type:`tool-call-delta`,index:0,id:`scenario-tool-${e.tool}`,name:e.tool,argumentsDelta:t},yield{type:`block-end`,index:0,block:{type:`tool-call`,id:`scenario-tool-${e.tool}`,name:e.tool,arguments:t}},yield{type:`usage`,usage:{inputTokens:1,outputTokens:1}},yield{type:`finish`,reason:{kind:`tool-calls`}};return}case`empty`:yield{type:`block-start`,index:0,blockType:`text`},yield{type:`block-end`,index:0,block:{type:`text`,text:``}},yield{type:`usage`,usage:{inputTokens:1,outputTokens:0}},yield{type:`finish`,reason:{kind:`stop`}};return;case`slow_success`:case`success`:case`max_tokens`:case`echo`:{let n=e.kind===`echo`?f(t.messages)??`echo`:e.text??f(t.messages)??`scenario`,r=e.kind===`slow_success`?Array.from({length:e.chunks},(e,t)=>n.slice(t,t+1)||`·`):[n];yield{type:`block-start`,index:0,blockType:`text`};for(let n of r)e.kind===`slow_success`&&await p(e.chunkDelayMs,t.signal),yield{type:`text-delta`,index:0,text:n};yield{type:`block-end`,index:0,block:{type:`text`,text:n}},yield{type:`usage`,usage:{inputTokens:1,outputTokens:r.length}},yield{type:`finish`,reason:e.kind===`max_tokens`?{kind:`max-tokens`}:{kind:`stop`}};return}}}};function g(e,t){let n=new h(t),r=e.llm.registerAdapter([`scenario`],n);return()=>{r()}}function _(e,t){let n=e;for(let e of t.split(`.`)){if(n==null)return;let t=Number(e);if(Array.isArray(n)){if(Number.isInteger(t)){let e=t<0?n.length+t:t;if(e<0||e>=n.length)return;n=n[e];continue}return}if(typeof n==`object`)n=n[e];else return}return n}function v(e,t){if(t.length===0)return!0;if(t.length>e.length)return!1;outer:for(let n=0;n<=e.length-t.length;n++){for(let r=0;r<t.length;r++){let i=t[r];if(i!==`*`&&i!==e[n+r])continue outer}return!0}return!1}function y(e,t){return Array.isArray(e)&&Array.isArray(t)?e.length>t.length?!1:e.every((e,n)=>JSON.stringify(e)===JSON.stringify(t[n])):JSON.stringify(e)===JSON.stringify(t)}function b(e,t,n=()=>void 0){if(`negate`in e){let r=b(e.negate,t,n);return{pass:!r.pass,detail:`negate(${r.pass?`通过→取反失败`:`失败→取反通过`}) ${r.detail}`}}if(`updateSequence`in e){let n=t.events();return{pass:v(n,e.updateSequence),detail:`updateSequence ${JSON.stringify(e.updateSequence)} vs [${n.join(`,`)}]`}}if(`captureLens`in e){let n=e.captureLens,r=t.captured(),i=r[n.request<0?r.length+n.request:n.request];if(i===void 0)return{pass:!1,detail:`captureLens 捕获 #${n.request} 不存在(共 ${r.length})`};let a=_(i,n.path);return`equals`in n&&n.equals!==void 0?{pass:JSON.stringify(a)===JSON.stringify(n.equals),detail:`captureLens ${n.path} = ${JSON.stringify(a)}(期望 ${JSON.stringify(n.equals)})`}:`contains`in n&&n.contains!==void 0?{pass:(typeof a==`string`?a:a===void 0?``:JSON.stringify(a)).includes(n.contains),detail:`captureLens ${n.path} contains("${n.contains}")`}:`notContains`in n&&n.notContains!==void 0?{pass:!(typeof a==`string`?a:a===void 0?``:JSON.stringify(a)).includes(n.notContains),detail:`captureLens ${n.path} notContains("${n.notContains}")`}:{pass:!1,detail:`captureLens 缺断言词(equals/contains/notContains 之一)`}}if(`snapshotPath`in e){let t=n(e.snapshotPath.file,e.snapshotPath.pointer);return{pass:JSON.stringify(t)===JSON.stringify(e.snapshotPath.equals),detail:`snapshotPath ${e.snapshotPath.file}#${e.snapshotPath.pointer} = ${JSON.stringify(t)}`}}if(`crossCapture`in e){let n=e.crossCapture,r=_(t.captured()[n.a.request],n.a.path),i=_(t.captured()[n.b.request],n.b.path);return{pass:n.op===`prefix`?y(r,i):JSON.stringify(r)===JSON.stringify(i),detail:`crossCapture ${n.a.request}:${n.a.path} ${n.op} ${n.b.request}:${n.b.path}`}}if(`echoEquals`in e){let n=t.echoed();return{pass:n===e.echoEquals,detail:`echoEquals "${n.slice(0,80)}"(期望 "${e.echoEquals.slice(0,80)}")`}}return{pass:!1,detail:`未知断言组合子`}}async function x(e,t,n=()=>void 0){for(let n of e.actions)`prompt`in n?await t.prompt(n.prompt):`waitTurnEnd`in n?await t.waitTurnEnd(n.waitTurnEnd):`pause`in n?await new Promise(e=>setTimeout(e,n.pause)):`setMode`in n?await t.setMode(n.setMode):`cancel`in n?await t.cancel():`promptNoWait`in n&&t.prompt(n.promptNoWait).catch(()=>{});return e.assertions.map(e=>b(e,t,n))}async function S(e){let t;try{t=await n(e,`utf-8`)}catch{return[]}return t.split(`
3
+ `).filter(e=>e.trim().length>0).map(e=>JSON.parse(e))}export{h as ScenarioAdapter,g as apply,d as behaviorLabel,b as evaluateAssertion,_ as getByPath,l as inject,f as lastUserText,v as matchesSubsequence,c as name,u as normalizeBehavior,S as readCaptureFile,x as runScenario};
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "@tbox.cn/tboxcode-dsh-llm",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0-rc.10",
4
+ "type": "module",
5
+ "description": "LlmAdapter:三协议 + traits + 限流 + call-log(zstd)+ echo / scenario driver + listModels GUI 硬规格 + adapters-updated 刷新",
6
+ "main": "lib/index.js",
7
+ "types": "lib/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./lib/index.d.ts",
11
+ "default": "./lib/index.js"
12
+ },
13
+ "./echo": {
14
+ "types": "./lib/echo.d.ts",
15
+ "default": "./lib/echo.js"
16
+ },
17
+ "./call-log": {
18
+ "types": "./lib/call-log.d.ts",
19
+ "default": "./lib/call-log.js"
20
+ },
21
+ "./scenario": {
22
+ "types": "./lib/scenario/index.d.ts",
23
+ "default": "./lib/scenario/index.js"
24
+ }
25
+ },
26
+ "files": [
27
+ "lib"
28
+ ],
29
+ "peerDependencies": {
30
+ "@deepseek-ai/dsh-attachment": "0.2.1-rc.2",
31
+ "@deepseek-ai/dsh-llm": "0.2.1-rc.2"
32
+ },
33
+ "dependencies": {
34
+ "@ai-sdk/anthropic": "3.0.85",
35
+ "@ai-sdk/openai": "3.0.74",
36
+ "@ai-sdk/openai-compatible": "2.0.51",
37
+ "ai": "6.0.208",
38
+ "zod": "4.6.7"
39
+ },
40
+ "devDependencies": {
41
+ "@deepseek-ai/cordis": "4.0.5",
42
+ "@deepseek-ai/dsh": "0.2.1-rc.2",
43
+ "@deepseek-ai/dsh-attachment": "0.2.1-rc.2",
44
+ "@deepseek-ai/dsh-llm": "0.2.1-rc.2",
45
+ "@types/ws": "^8.18.0",
46
+ "ws": "^8.19.0",
47
+ "yaml": "^2.8.0",
48
+ "@tbox.cn/tboxcode-dsh-cli": "0.1.0-rc.10",
49
+ "@tbox.cn/tboxcode-dsh-runtime": "0.1.0-rc.10"
50
+ },
51
+ "dsh": {
52
+ "bundle": {
53
+ "patch": []
54
+ }
55
+ },
56
+ "scripts": {
57
+ "build": "tsdown",
58
+ "typecheck": "tsc --noEmit -p tsconfig.json"
59
+ }
6
60
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.