@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,3 @@
1
+ import{randomBytes as e}from"node:crypto";import{appendFile as t,mkdir as n,readFile as r,readdir as i,rm as a,stat as o,writeFile as s}from"node:fs/promises";import{dirname as c,join as l}from"node:path";import{zstdCompressSync as u,zstdDecompressSync as d}from"node:zlib";function f(e){if(e.length===0)throw Error(`cannot encode an empty path segment`);if(e===`.`)return`~002E`;if(e===`..`)return`~002E~002E`;let t=``;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n),i=String.fromCharCode(r);i!==`~`&&/^[A-Za-z0-9._-]$/.test(i)?t+=i:t+=`~`+r.toString(16).toUpperCase().padStart(4,`0`)}return t}function p(e){if(e.length===0)throw Error(`cannot encode an empty project path`);let t=``,n=!1;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r),a=String.fromCharCode(i);a===`/`||a===`\\`||a===`:`?(n||(t+=`-`),n=!0):a!==`~`&&/^[A-Za-z0-9._-]$/.test(a)?(t+=a,n=!1):(t+=`~`+i.toString(16).toUpperCase().padStart(4,`0`),n=!1)}return`--${(t.replace(/^-+/,``)||`root`).slice(0,251)}--`}function m(e,t){return t===void 0?l(e,`_no-cwd`):l(e,p(t))}function h(e,t,n){return l(m(e,t),f(n))}function g(e,t,n){return l(h(e,t,n),`tboxcode`,`llm-calls`)}function _(e){return l(e,`_tboxcode`,`orphan-llm-calls`)}const v=new Set([`authorization`,`x-api-key`,`api-key`,`cookie`,`proxy-authorization`,`x-goog-api-key`]);function y(e){return e.length<=8?e.slice(0,4):`${e.slice(0,4)}***${e.slice(-4)}`}function b(e){if(!e)return;let t=Object.fromEntries(Object.entries(e).filter(([e])=>!v.has(e.toLowerCase())));return Object.keys(t).length>0?t:void 0}function x(e){let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase(),i=Array.isArray(r)?r.join(`, `):String(r??``);t[n]=v.has(e)?y(i):i}return t}function S(e,t){if(t<=0||Buffer.byteLength(e,`utf-8`)<=t)return{text:e,truncated:!1};let n=``,r=0;for(let i of e){let e=Buffer.byteLength(i,`utf-8`);if(r+e>t)break;n+=i,r+=e}return{text:n,truncated:!0}}function C(){return e(4).toString(`hex`)}function w(e=new Date){let t=(e,t=2)=>String(e).padStart(t,`0`);return`${e.getFullYear()}${t(e.getMonth()+1)}${t(e.getDate())}-${t(e.getHours())}${t(e.getMinutes())}${t(e.getSeconds())}-${t(e.getMilliseconds(),3)}`}function T(e,t,n,r){let i;try{i=new URL(t)}catch{i={pathname:t,search:``}}let a=[`${e} ${i.pathname}${i.search??``} HTTP/1.1`];for(let[e,t]of Object.entries(n))a.push(`${e}: ${t}`);return a.push(``,r),a.join(`
2
+ `)}function E(e,t,n,r){let i=[`HTTP/1.1 ${e} ${t||``}`.trimEnd()];for(let[e,t]of Object.entries(n))i.push(`${e}: ${t}`);return i.push(``,r),i.join(`
3
+ `)}function D(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(1)}MB`}var O=class{partPath;ts;callIdShort;slug;buf=``;byteCount=0;finalized=!1;disabled=!1;finalizedFile=null;partFilename;_ioChain=Promise.resolve();done;_doneResolve;constructor(e,t,n,r,i,a,o){this.logDir=e,this.max_file_bytes=i,this.onError=o,this.ts=a,this.callIdShort=n?n.replace(/^llmc_/,``).slice(0,8):C(),this.slug=`${t}_${this.callIdShort}_${r}`,this.partFilename=`${this.ts}_${this.slug}.http.part`,this.partPath=l(e,this.partFilename);let s;this.done=new Promise(e=>{s=e}),this._doneResolve=s}finalFilename(e){return`${this.ts}_${this.slug}_${e}.http.zst`}append(e){if(!(this.finalized||this.disabled)){if(this.max_file_bytes>0){let t=this.byteCount+Buffer.byteLength(e,`utf-8`);if(this.byteCount>=this.max_file_bytes)return;if(t>this.max_file_bytes){let{text:t}=S(e,this.max_file_bytes-this.byteCount);this.buf+=t,this.buf+=`\n[truncated at ${D(this.max_file_bytes)}]\n`,this.byteCount=this.max_file_bytes;return}}this.buf+=e,this.byteCount+=this.max_file_bytes>0?Buffer.byteLength(e,`utf-8`):0}}writeMeta(e){for(let[t,n]of Object.entries(e))this.append(`# ${t}: ${n}\n`)}writeRequest(e){this.append(e),this._flushToPartAsync()}writeResponse(e,t,n){this.append(`\n######## RESPONSE (header: ${e.toFixed(0)}ms, body: ${t.toFixed(0)}ms) ########\n\n`),this.append(n)}writeTrailer(e,t,n,r,i){this.append(`\n# duration: ${e.toFixed(0)}ms\n`),this.append(`# header-ttfb: ${t.toFixed(0)}ms\n`),this.append(`# ttfb: ${n.toFixed(0)}ms\n`),this.append(`# body-size: request=${D(r)}, response=${D(i)}\n`)}async finalize(e){if(this.finalized)return this.finalizedFile;if(this.finalized=!0,!this.disabled){this._flushToPartAsync();let t=l(this.logDir,this.finalFilename(e)),n=this.partPath;await new Promise(r=>{this._ioChain=this._ioChain.then(async()=>{try{await s(t,u(Buffer.from(this.buf,`utf-8`))),await a(n,{force:!0}),this.finalizedFile=this.finalFilename(e)}catch{this.finalizedFile=this.partFilename}r()})})}return this._ioChain=this._ioChain.then(()=>this._doneResolve()),this.finalizedFile??this.partFilename}async abort(){return this.finalized?this.finalizedFile:(this.finalized=!0,this.disabled||(this._flushToPartAsync(),this.finalizedFile=this.partFilename),this._ioChain=this._ioChain.then(()=>this._doneResolve()),this.finalizedFile)}_flushToPartAsync(){if(this.buf.length===0)return;let e=this.buf,t=this.partPath;this._ioChain=this._ioChain.then(async()=>{if(!this.disabled)try{await n(c(t),{recursive:!0}),await s(t,e,`utf-8`)}catch(e){this.disabled=!0,this.onError?.(`llm-call-log: write failed, disabling for this call`,e)}})}};function k(e,t){return{file:t.file??``,time:t.time,sessionId:e.sessionId,trigger:e.trigger,callId:t.callId,attempt:t.attempt,status:t.status,durationMs:Math.round(t.durationMs),headerTtfbMs:Math.round(t.headerTtfbMs),ttfbMs:Math.round(t.ttfbMs),reqBytes:t.reqBytes,resBytes:t.resBytes,provider:e.provider_name,model:e.modelId,upstreamModel:e.upstream_model}}function A(e,r=globalThis.fetch){if(!e.enabled)return{fetch:r,drain:()=>Promise.resolve()};n(e.logDir,{recursive:!0}).catch(()=>{});let i=new Set,a=new Map,o=Promise.resolve();function s(n){let r=`${JSON.stringify(n)}\n`;o=o.then(async()=>{try{await t(l(e.logDir,`index.jsonl`),r,`utf-8`)}catch(t){e.onError?.(`llm-call-log: index append failed`,t)}})}let c=!1;return{fetch:async function(t,n){let o=process.env.TBOXCODE_LLM_LOG===`0`||process.env.TBOXCODE_LLM_LOG===`false`;if(o||c){if(o){for(let e of i)e.abort();i.clear()}return r(t,n)}let l=w(),u=globalThis.performance?.now()??Date.now(),d=e.callId,f=d?(a.get(d)??0)+1:1;d&&a.set(d,f);let p=new O(e.logDir,e.trigger,d,f,e.max_file_bytes,l,e.onError);i.add(p),p.done.then(()=>i.delete(p),()=>i.delete(p));let m=n?.method??`POST`,h,g={};typeof t==`string`||t instanceof URL?h=t instanceof URL?t.toString():t:(h=t.url,m=n?.method??t.method,g=M(t.headers)),n?.headers&&(g={...g,...M(n.headers)});let{text:_,isReal:v}=N(n?.body),y=v?Buffer.byteLength(_,`utf-8`):0,b=e.sanitize_headers?x(g):Object.fromEntries(Object.entries(g).map(([e,t])=>[e,Array.isArray(t)?t.join(`, `):String(t??``)]));p.writeMeta({time:new Date().toISOString(),session:e.sessionId,trigger:e.trigger,...e.traitsVersion===void 0?{}:{_traitsV:e.traitsVersion},...d?{call:d,attempt:String(f)}:{},provider:`${e.protocol} (${e.provider_name})`,model:e.modelId,upstreamModel:e.upstream_model}),p.writeRequest(T(m,h,b,_));let C;try{C=await r(t,n)}catch(e){throw p.writeMeta({error:`fetch failed: ${String(e)}`}),p.abort(),e}let A=(globalThis.performance?.now()??Date.now())-u,j=M(C.headers),P=e.sanitize_headers?x(j):Object.fromEntries(Object.entries(j).map(([e,t])=>[e,Array.isArray(t)?t.join(`, `):String(t??``)])),F=C.status;if(!C.body){p.writeResponse(A,A,E(F,C.statusText,P,``));let t=(globalThis.performance?.now()??Date.now())-u;return p.writeTrailer(t,A,A,y,0),s(k(e,{file:await p.finalize(F),time:l,callId:d,attempt:f,status:F,durationMs:t,headerTtfbMs:A,ttfbMs:A,reqBytes:y,resBytes:0})),C}let[I,L]=C.body.tee(),R=new Response(I,{status:C.status,statusText:C.statusText,headers:C.headers});return(async()=>{let t=0,n=0,r=[],i=0,a=!1,o=!1,c=null;try{c=L.getReader();let o=new TextDecoder;for(;;){let{done:s,value:l}=await c.read();if(s)break;if(l&&(n===0&&(n=(globalThis.performance?.now()??Date.now())-u),t+=l.byteLength,!a)){let t=o.decode(l,{stream:!0}),n=Buffer.byteLength(t,`utf-8`);i+n<=e.max_file_bytes?(r.push(t),i+=n):a=!0}}a||r.push(o.decode())}catch(e){r.push(`\n[stream interrupted: ${String(e)}]\n`),o=!0}finally{c?.releaseLock()}let{text:m,truncated:h}=S(r.join(``),e.max_file_bytes);p.writeResponse(A,n,E(F,C.statusText,P,m)),(h||a)&&p.writeMeta({note:`response body truncated at ${D(e.max_file_bytes)}`}),o&&p.writeMeta({status:`stream-interrupted`});let g=(globalThis.performance?.now()??Date.now())-u;p.writeTrailer(g,A,n,y,t),s(k(e,{file:await p.finalize(F),time:l,callId:d,attempt:f,status:F,durationMs:g,headerTtfbMs:A,ttfbMs:n,reqBytes:y,resBytes:t}))})().catch(()=>{p.abort().catch(()=>{})}),R},drain:async()=>{for(c=!0;i.size>0;){let e=[...i];await Promise.allSettled(e.map(e=>e.done))}await o}}}async function j(e){let t=await r(e);return e.endsWith(`.http.zst`)?d(t).toString(`utf-8`):t.toString(`utf-8`)}function M(e){if(!e)return{};if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}if(Array.isArray(e)){let t={};for(let n of e){let e=n[0],r=n[1]??``;e!==void 0&&(t[e]=r)}return t}if(typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=Array.isArray(r)?r.join(`, `):String(r??``);return t}return{}}function N(e){if(e==null)return{text:``,isReal:!0};if(typeof e==`string`)return{text:e,isReal:!0};if(e instanceof Uint8Array)return{text:new TextDecoder().decode(e),isReal:!0};if(typeof Buffer<`u`&&Buffer.isBuffer(e))return{text:e.toString(`utf-8`),isReal:!0};try{return{text:`[unserializable body: ${typeof e}]`,isReal:!1}}catch{return{text:`[unserializable body: ${typeof e}]`,isReal:!1}}}async function P(e,t,n=1e3){if(t<=0)return 0;let r=Date.now()-t*864e5,s=0,c=0,u=async e=>{let t;try{t=await i(e,{withFileTypes:!0})}catch{return}for(let i of t){if(c>=n)return;let t=i.name;if(i.isDirectory()||!t.endsWith(`.http.zst`)&&!t.endsWith(`.http.part`)&&!t.endsWith(`.http`)&&t!==`index.jsonl`)continue;c++;let u=l(e,t);try{(await o(u)).mtimeMs<r&&(await a(u,{force:!0}),s++)}catch{}}};try{await u(_(e));let t;try{t=await i(e,{withFileTypes:!0})}catch{t=[]}for(let r of t){if(!r.isDirectory()||c>=n||r.name===`_tboxcode`)continue;let t;try{t=await i(l(e,r.name),{withFileTypes:!0})}catch{continue}for(let i of t)!i.isDirectory()||c>=n||await u(l(e,r.name,i.name,`tboxcode`,`llm-calls`));if(c>=n)break}return s}catch{return s}}export{j as a,b as c,C as i,g as l,A as n,x as o,w as r,S as s,P as t,_ as u};
@@ -0,0 +1,120 @@
1
+ //#region src/call-log.d.ts
2
+ /**
3
+ * call-log —— LLM 调用线级日志(异步 I/O)。
4
+ *
5
+ * 移植自 openacpagent v0.9.20 `agent/llm/call-log.ts`(784 行)。包装注入
6
+ * @ai-sdk provider 工厂的 fetch:每次 LLM HTTP 调用(含重试 attempt 与 HTTP
7
+ * 错误)落盘为人类可读文件,另追加一行 JSON 摘要至 index.jsonl。
8
+ *
9
+ * 本仓收敛改造(S1a 决断,deltas 对照源):
10
+ * 1. 文件名无 `-s{step}` 段——ai-sdk adapter 无 step 可达面(S1a seam 探针)
11
+ * 与 turnId 同为 IndexEntry 恒省略字段。
12
+ * 2. 落盘为 zstd 压缩帧(node:zlib zstdCompressSync,v22.15+):进行中
13
+ * `.http.part`(明文,崩溃可裸读)→ finalize 原子改写 `.http.zst`;
14
+ * abort 保持 `.part`。读取端 readCallLogFile 按后缀分流(含存量裸
15
+ * `.http`——openacpagent 遗留布局的兼容读)。
16
+ * 3. meta 头 `_traitsV`:traits 哈希(traitsHash sha256-16hex)随请求元数据
17
+ * 落盘——golden 字节比对与 traits 版本演进的对账锚。
18
+ * 4. 两态路由由调用方解析(adapter 接线):有会话 →
19
+ * `<sessionDir>/tboxcode/llm-calls`;无(agentless / 未持久化)→
20
+ * `<root>/_tboxcode/orphan-llm-calls`(该目录禁进 session 目录扫描)。
21
+ * 5. retention 扫描本仓布局 `<root>/<projectKey>/<encodedSessionId>/
22
+ * tboxcode/llm-calls` 与 orphan 目录(源为 workspaces/sessions 两层)。
23
+ * 6. 零 logger 依赖(C1 降级先例):warn 走可选 onError 回调。
24
+ *
25
+ * 设计保留(源语义):
26
+ * - 每调用一文件:{ts}_{trigger}_{callId8}_{attempt}_{status}.http.zst
27
+ * - .part → finalize 原子改写;abort/写失败保持 .part 且 index 记实况名
28
+ * - 请求快照入队异步 I/O 链,真 fetch 立即发出——零事件循环阻塞
29
+ * - SSE 响应体 tee:SDK 一支,后台任务一支(内存受 max_file_bytes 约束)
30
+ * - 敏感头脱敏(first4+last4,core/headers 单源)
31
+ * - 全部 fs 错误就地吸纳:写失败只停用该调用日志,永不影响 LLM 调用
32
+ * - drain() 循环至 pending 清空——修在途会话提前返回缺陷
33
+ * - TBOXCODE_LLM_LOG=0|false 运行时热杀(每 fetch 检查,紧急停用旁路)
34
+ */
35
+ interface LlmCallLogConfig {
36
+ enabled: boolean;
37
+ max_file_bytes: number;
38
+ sanitize_headers: boolean;
39
+ }
40
+ interface LlmCallLogContext extends LlmCallLogConfig {
41
+ /** call-log 目录(调用方两态路由解析:会话目录或 orphan 目录)。 */
42
+ logDir: string;
43
+ sessionId: string;
44
+ trigger: 'main' | 'compact' | 'title';
45
+ /** 当前 LLM 调用 id(per streamText 调用;SDK 内部重试共享)。attempt 计数键。 */
46
+ callId?: string;
47
+ /** traits 哈希(meta 头 `_traitsV`——golden 对账锚)。 */
48
+ traitsVersion?: string;
49
+ provider_name: string;
50
+ /** config 键 modelId(catalog / index 关联)。 */
51
+ modelId: string;
52
+ /** 实际发往上游 endpoint 的 API model id。 */
53
+ upstream_model: string;
54
+ protocol: string;
55
+ /** 写失败等诊断回调(缺省静默——fs 错误永不影响 LLM 调用)。 */
56
+ onError?: (message: string, error: unknown) => void;
57
+ }
58
+ type FetchInput = Parameters<typeof fetch>[0];
59
+ type FetchInit = Parameters<typeof fetch>[1];
60
+ type HttpHeaders = Record<string, string | string[] | undefined>;
61
+ declare function sanitize_headers(headers: HttpHeaders): Record<string, string>;
62
+ /** UTF-8 安全的字节预算截断。 */
63
+ declare function truncateBody(bodyText: string, maxBytes: number): {
64
+ text: string;
65
+ truncated: boolean;
66
+ };
67
+ declare function randomHex8(): string;
68
+ declare function fileTimestamp(date?: Date): string;
69
+ /** 15 字段(收敛形态):turnId/step/interrupted 恒省略(无 adapter 可达面;
70
+ * 中断信息落文件 meta 头 status: stream-interrupted)。 */
71
+ interface IndexEntry {
72
+ file: string;
73
+ time: string;
74
+ sessionId: string;
75
+ trigger: string;
76
+ callId?: string;
77
+ attempt: number;
78
+ status: number;
79
+ durationMs: number;
80
+ /** fetch 发起到响应头的耗时(ms)。 */
81
+ headerTtfbMs: number;
82
+ /** fetch 发起到首响应体字节的耗时(ms);无体响应等于 headerTtfbMs。 */
83
+ ttfbMs: number;
84
+ reqBytes: number;
85
+ resBytes: number;
86
+ provider: string;
87
+ model: string;
88
+ upstreamModel: string;
89
+ }
90
+ interface LoggingFetchHandle {
91
+ /** 包装后的 fetch——传给 @ai-sdk provider 工厂。 */
92
+ fetch: typeof fetch;
93
+ /** await 本句柄全部在途日志写。 */
94
+ drain: () => Promise<void>;
95
+ }
96
+ /**
97
+ * 以 LLM 调用日志包装 fetch 实现。
98
+ *
99
+ * @param ctx 日志上下文(目录、会话、trigger、上限等)
100
+ * @param baseFetch 真实 fetch 委托目标。缺省 globalThis.fetch;注入自定义
101
+ * fetch 用于测试或连接策略(本仓叠装
102
+ * createSseRateLimitFetch 在内层)。
103
+ */
104
+ declare function createLoggingFetch(ctx: LlmCallLogContext, baseFetch?: typeof fetch): LoggingFetchHandle;
105
+ /**
106
+ * 读取一个 call-log 文件为明文。按后缀分流:`.http.zst` → zstd 解压;
107
+ * `.http.part` / 裸 `.http`(openacpagent 遗留布局与 abort 半成品)→ 明文直读。
108
+ */
109
+ declare function readCallLogFile(path: string): Promise<string>;
110
+ /**
111
+ * 按保留天数清理过期 call-log(本仓布局):
112
+ * - 会话目录:`<root>/<projectKey>/<encodedSessionId>/tboxcode/llm-calls`
113
+ * - orphan 目录:`<root>/_tboxcode/orphan-llm-calls`
114
+ * 清理对象:`.http.zst` / `.http.part` / `.http` 与 index.jsonl。
115
+ * 返回删除文件数(测试与调度诊断面)。调度接线归 serve-gateway(本函数为
116
+ * 纯清扫原语)。
117
+ */
118
+ declare function cleanupOldLlmLogs(sessionRoot: string, retentionDays: number, maxFiles?: number): Promise<number>;
119
+ //#endregion
120
+ export { FetchInit, FetchInput, HttpHeaders, IndexEntry, LlmCallLogConfig, LlmCallLogContext, LoggingFetchHandle, cleanupOldLlmLogs, createLoggingFetch, fileTimestamp, randomHex8, readCallLogFile, sanitize_headers, truncateBody };
@@ -0,0 +1 @@
1
+ import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./call-log-UkoWWuyZ.js";export{o as cleanupOldLlmLogs,n as createLoggingFetch,i as fileTimestamp,t as randomHex8,e as readCallLogFile,r as sanitize_headers,a as truncateBody};
package/lib/echo.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ import { GenerateOptions, LlmAdapter, LlmModelInfo, LlmResolvedModelInfo, StreamChunk } from "@deepseek-ai/dsh-llm";
2
+ import { Context } from "@deepseek-ai/cordis";
3
+
4
+ //#region src/echo.d.ts
5
+
6
+ declare const name = "tboxcode-llm-echo";
7
+ declare const inject: string[];
8
+ interface EchoConfig {
9
+ /** 每个 text-delta 之间的延迟(ms)——mid-stream 断线重连窗口靠它拉开。 */
10
+ delayMs?: number;
11
+ /** 每个 text-delta 携带的词数。 */
12
+ chunkWords?: number;
13
+ }
14
+ declare class EchoAdapter extends LlmAdapter {
15
+ #private;
16
+ constructor(config?: EchoConfig);
17
+ listModels(provider: string): Promise<readonly LlmModelInfo[]>;
18
+ resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo>;
19
+ stream(options: GenerateOptions): AsyncIterable<StreamChunk>;
20
+ }
21
+ /** cordis 插件入口:注册 echo provider 路由;apply 返回 disposer 释放注册。 */
22
+ declare function apply(ctx: Context, config?: EchoConfig): () => void;
23
+ //#endregion
24
+ export { EchoAdapter, EchoConfig, apply, inject, name };
package/lib/echo.js ADDED
@@ -0,0 +1,2 @@
1
+ import{LlmAdapter as e}from"@deepseek-ai/dsh-llm";const t=`tboxcode-llm-echo`,n=[`llm`];function r(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 i(e,t){let n=e.match(/\S+\s*/g);if(n===null)return[e];let r=[];for(let e=0;e<n.length;e+=t)r.push(n.slice(e,e+t).join(``));return r}async function a(e,t){e<=0||await new Promise((n,r)=>{let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(t.reason)},{once:!0})})}var o=class extends e{#e;#t;constructor(e={}){super(),this.#e=e.delayMs??30,this.#t=Math.max(1,Math.trunc(e.chunkWords??1))}listModels(e){return Promise.resolve([{provider:e,id:`echo`,name:`Echo`,description:`echo driver——确定性回显(测试与流式收口)`,inputModalities:[`text`]}])}async resolveModel(e,t){return{provider:e,id:t,name:t,context:{contextWindow:128e3}}}async*stream(e){let t=r(e.messages)??`echo`,n=i(t,this.#t);yield{type:`block-start`,index:0,blockType:`text`};for(let t of n)await a(this.#e,e.signal),yield{type:`text-delta`,index:0,text:t};yield{type:`block-end`,index:0,block:{type:`text`,text:t}},yield{type:`usage`,usage:{inputTokens:1,outputTokens:n.length}},yield{type:`finish`,reason:{kind:`stop`}}}};function s(e,t={}){let n=new o(t),r=e.llm.registerAdapter([`echo`],n);return()=>{r()}}export{o as EchoAdapter,s as apply,n as inject,t as name};
package/lib/index.d.ts ADDED
@@ -0,0 +1,386 @@
1
+ import { z } from "zod";
2
+ import { Context } from "@deepseek-ai/cordis";
3
+
4
+ //#region src/core/schema.d.ts
5
+
6
+ declare const ModelTraitsSchema: z.ZodObject<{
7
+ protocol: z.ZodEnum<{
8
+ openai: "openai";
9
+ "openai-compatible": "openai-compatible";
10
+ anthropic: "anthropic";
11
+ }>;
12
+ provider_name: z.ZodOptional<z.ZodString>;
13
+ upstream_model: z.ZodOptional<z.ZodString>;
14
+ reasoning: z.ZodOptional<z.ZodObject<{
15
+ field: z.ZodOptional<z.ZodEnum<{
16
+ reasoning: "reasoning";
17
+ reasoning_content: "reasoning_content";
18
+ reasoning_details: "reasoning_details";
19
+ }>>;
20
+ interleaved: z.ZodOptional<z.ZodBoolean>;
21
+ summary: z.ZodOptional<z.ZodLiteral<"auto">>;
22
+ include: z.ZodOptional<z.ZodLiteral<"encrypted">>;
23
+ effort: z.ZodOptional<z.ZodObject<{
24
+ default: z.ZodOptional<z.ZodString>;
25
+ levels: z.ZodOptional<z.ZodArray<z.ZodObject<{
26
+ id: z.ZodString;
27
+ name: z.ZodOptional<z.ZodString>;
28
+ description: z.ZodOptional<z.ZodString>;
29
+ body: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
30
+ headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
31
+ }, z.core.$strip>>>;
32
+ template: z.ZodOptional<z.ZodString>;
33
+ }, z.core.$loose>>;
34
+ }, z.core.$strip>>;
35
+ image: z.ZodOptional<z.ZodEnum<{
36
+ url: "url";
37
+ base64: "base64";
38
+ }>>;
39
+ image_max_bytes: z.ZodOptional<z.ZodNumber>;
40
+ image_max_images: z.ZodOptional<z.ZodNumber>;
41
+ image_byte_quantum: z.ZodOptional<z.ZodNumber>;
42
+ image_count_quantum: z.ZodOptional<z.ZodNumber>;
43
+ request_max_bytes: z.ZodOptional<z.ZodNumber>;
44
+ image_max_pixels: z.ZodOptional<z.ZodNumber>;
45
+ image_max_aspect_ratio: z.ZodOptional<z.ZodNumber>;
46
+ cache: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"none">, z.ZodLiteral<"anthropic">, z.ZodLiteral<"openai-compatible">, z.ZodLiteral<"bedrock">, z.ZodObject<{
47
+ mode: z.ZodEnum<{
48
+ automatic: "automatic";
49
+ explicit: "explicit";
50
+ }>;
51
+ ttl: z.ZodEnum<{
52
+ "5m": "5m";
53
+ "1h": "1h";
54
+ }>;
55
+ scope: z.ZodOptional<z.ZodArray<z.ZodEnum<{
56
+ system: "system";
57
+ tools: "tools";
58
+ messages: "messages";
59
+ }>>>;
60
+ }, z.core.$strip>]>>;
61
+ limit: z.ZodObject<{
62
+ context: z.ZodNumber;
63
+ output: z.ZodNumber;
64
+ idle_timeout_ms: z.ZodOptional<z.ZodNumber>;
65
+ }, z.core.$strip>;
66
+ body: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
67
+ body_templates: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
68
+ headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
69
+ when: z.ZodOptional<z.ZodObject<{
70
+ reasoning: z.ZodOptional<z.ZodBoolean>;
71
+ reasoning_keys: z.ZodOptional<z.ZodArray<z.ZodString>>;
72
+ }, z.core.$strip>>;
73
+ quirks: z.ZodOptional<z.ZodArray<z.ZodEnum<{
74
+ "ensure-assistant-reasoning": "ensure-assistant-reasoning";
75
+ "scrub-tool-call-id": "scrub-tool-call-id";
76
+ "done-after-tool": "done-after-tool";
77
+ "drop-empty-content": "drop-empty-content";
78
+ }>>>;
79
+ }, z.core.$loose>;
80
+ type ModelTraits = z.infer<typeof ModelTraitsSchema>;
81
+ /** box/模型目录消费名:与 dsh traits 同一形状(单一事实源)。 */
82
+ type TboxcodeDshModelTraits = ModelTraits;
83
+ /** 模型条目:protocol 可省(继承 provider)。 */
84
+ declare const ModelEntrySchema: z.ZodObject<{
85
+ provider_name: z.ZodOptional<z.ZodString>;
86
+ upstream_model: z.ZodOptional<z.ZodString>;
87
+ reasoning: z.ZodOptional<z.ZodObject<{
88
+ field: z.ZodOptional<z.ZodEnum<{
89
+ reasoning: "reasoning";
90
+ reasoning_content: "reasoning_content";
91
+ reasoning_details: "reasoning_details";
92
+ }>>;
93
+ interleaved: z.ZodOptional<z.ZodBoolean>;
94
+ summary: z.ZodOptional<z.ZodLiteral<"auto">>;
95
+ include: z.ZodOptional<z.ZodLiteral<"encrypted">>;
96
+ effort: z.ZodOptional<z.ZodObject<{
97
+ default: z.ZodOptional<z.ZodString>;
98
+ levels: z.ZodOptional<z.ZodArray<z.ZodObject<{
99
+ id: z.ZodString;
100
+ name: z.ZodOptional<z.ZodString>;
101
+ description: z.ZodOptional<z.ZodString>;
102
+ body: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
103
+ headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
104
+ }, z.core.$strip>>>;
105
+ template: z.ZodOptional<z.ZodString>;
106
+ }, z.core.$loose>>;
107
+ }, z.core.$strip>>;
108
+ image: z.ZodOptional<z.ZodEnum<{
109
+ url: "url";
110
+ base64: "base64";
111
+ }>>;
112
+ image_max_bytes: z.ZodOptional<z.ZodNumber>;
113
+ image_max_images: z.ZodOptional<z.ZodNumber>;
114
+ image_byte_quantum: z.ZodOptional<z.ZodNumber>;
115
+ image_count_quantum: z.ZodOptional<z.ZodNumber>;
116
+ request_max_bytes: z.ZodOptional<z.ZodNumber>;
117
+ image_max_pixels: z.ZodOptional<z.ZodNumber>;
118
+ image_max_aspect_ratio: z.ZodOptional<z.ZodNumber>;
119
+ cache: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"none">, z.ZodLiteral<"anthropic">, z.ZodLiteral<"openai-compatible">, z.ZodLiteral<"bedrock">, z.ZodObject<{
120
+ mode: z.ZodEnum<{
121
+ automatic: "automatic";
122
+ explicit: "explicit";
123
+ }>;
124
+ ttl: z.ZodEnum<{
125
+ "5m": "5m";
126
+ "1h": "1h";
127
+ }>;
128
+ scope: z.ZodOptional<z.ZodArray<z.ZodEnum<{
129
+ system: "system";
130
+ tools: "tools";
131
+ messages: "messages";
132
+ }>>>;
133
+ }, z.core.$strip>]>>;
134
+ limit: z.ZodObject<{
135
+ context: z.ZodNumber;
136
+ output: z.ZodNumber;
137
+ idle_timeout_ms: z.ZodOptional<z.ZodNumber>;
138
+ }, z.core.$strip>;
139
+ body: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
140
+ body_templates: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
141
+ headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
142
+ when: z.ZodOptional<z.ZodObject<{
143
+ reasoning: z.ZodOptional<z.ZodBoolean>;
144
+ reasoning_keys: z.ZodOptional<z.ZodArray<z.ZodString>>;
145
+ }, z.core.$strip>>;
146
+ quirks: z.ZodOptional<z.ZodArray<z.ZodEnum<{
147
+ "ensure-assistant-reasoning": "ensure-assistant-reasoning";
148
+ "scrub-tool-call-id": "scrub-tool-call-id";
149
+ "done-after-tool": "done-after-tool";
150
+ "drop-empty-content": "drop-empty-content";
151
+ }>>>;
152
+ protocol: z.ZodOptional<z.ZodEnum<{
153
+ openai: "openai";
154
+ "openai-compatible": "openai-compatible";
155
+ anthropic: "anthropic";
156
+ }>>;
157
+ }, z.core.$loose>;
158
+ declare const LlmConfigSchema: z.ZodObject<{
159
+ model: z.ZodOptional<z.ZodString>;
160
+ workspace: z.ZodOptional<z.ZodObject<{
161
+ init_model: z.ZodOptional<z.ZodString>;
162
+ }, z.core.$loose>>;
163
+ media_policy: z.ZodOptional<z.ZodObject<{
164
+ mode: z.ZodOptional<z.ZodEnum<{
165
+ project: "project";
166
+ offload: "offload";
167
+ }>>;
168
+ image_reserve_bytes: z.ZodOptional<z.ZodNumber>;
169
+ }, z.core.$loose>>;
170
+ provider: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
171
+ protocol: z.ZodOptional<z.ZodEnum<{
172
+ openai: "openai";
173
+ "openai-compatible": "openai-compatible";
174
+ anthropic: "anthropic";
175
+ }>>;
176
+ name: z.ZodOptional<z.ZodString>;
177
+ npm: z.ZodOptional<z.ZodString>;
178
+ api: z.ZodOptional<z.ZodString>;
179
+ options: z.ZodOptional<z.ZodObject<{
180
+ apiKey: z.ZodOptional<z.ZodString>;
181
+ baseURL: z.ZodOptional<z.ZodString>;
182
+ headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
183
+ }, z.core.$loose>>;
184
+ retry: z.ZodOptional<z.ZodObject<{
185
+ mode: z.ZodEnum<{
186
+ normal: "normal";
187
+ always: "always";
188
+ }>;
189
+ maxRetries: z.ZodOptional<z.ZodNumber>;
190
+ retryableCodes: z.ZodOptional<z.ZodArray<z.ZodString>>;
191
+ backoff: z.ZodOptional<z.ZodObject<{
192
+ initialDelayMs: z.ZodOptional<z.ZodNumber>;
193
+ maxDelayMs: z.ZodOptional<z.ZodNumber>;
194
+ jitterRatio: z.ZodOptional<z.ZodNumber>;
195
+ }, z.core.$strict>>;
196
+ }, z.core.$strict>>;
197
+ trace: z.ZodOptional<z.ZodObject<{
198
+ type: z.ZodLiteral<"sofa">;
199
+ }, z.core.$strict>>;
200
+ models: z.ZodRecord<z.ZodString, z.ZodObject<{
201
+ provider_name: z.ZodOptional<z.ZodString>;
202
+ upstream_model: z.ZodOptional<z.ZodString>;
203
+ reasoning: z.ZodOptional<z.ZodObject<{
204
+ field: z.ZodOptional<z.ZodEnum<{
205
+ reasoning: "reasoning";
206
+ reasoning_content: "reasoning_content";
207
+ reasoning_details: "reasoning_details";
208
+ }>>;
209
+ interleaved: z.ZodOptional<z.ZodBoolean>;
210
+ summary: z.ZodOptional<z.ZodLiteral<"auto">>;
211
+ include: z.ZodOptional<z.ZodLiteral<"encrypted">>;
212
+ effort: z.ZodOptional<z.ZodObject<{
213
+ default: z.ZodOptional<z.ZodString>;
214
+ levels: z.ZodOptional<z.ZodArray<z.ZodObject<{
215
+ id: z.ZodString;
216
+ name: z.ZodOptional<z.ZodString>;
217
+ description: z.ZodOptional<z.ZodString>;
218
+ body: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
219
+ headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
220
+ }, z.core.$strip>>>;
221
+ template: z.ZodOptional<z.ZodString>;
222
+ }, z.core.$loose>>;
223
+ }, z.core.$strip>>;
224
+ image: z.ZodOptional<z.ZodEnum<{
225
+ url: "url";
226
+ base64: "base64";
227
+ }>>;
228
+ image_max_bytes: z.ZodOptional<z.ZodNumber>;
229
+ image_max_images: z.ZodOptional<z.ZodNumber>;
230
+ image_byte_quantum: z.ZodOptional<z.ZodNumber>;
231
+ image_count_quantum: z.ZodOptional<z.ZodNumber>;
232
+ request_max_bytes: z.ZodOptional<z.ZodNumber>;
233
+ image_max_pixels: z.ZodOptional<z.ZodNumber>;
234
+ image_max_aspect_ratio: z.ZodOptional<z.ZodNumber>;
235
+ cache: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"none">, z.ZodLiteral<"anthropic">, z.ZodLiteral<"openai-compatible">, z.ZodLiteral<"bedrock">, z.ZodObject<{
236
+ mode: z.ZodEnum<{
237
+ automatic: "automatic";
238
+ explicit: "explicit";
239
+ }>;
240
+ ttl: z.ZodEnum<{
241
+ "5m": "5m";
242
+ "1h": "1h";
243
+ }>;
244
+ scope: z.ZodOptional<z.ZodArray<z.ZodEnum<{
245
+ system: "system";
246
+ tools: "tools";
247
+ messages: "messages";
248
+ }>>>;
249
+ }, z.core.$strip>]>>;
250
+ limit: z.ZodObject<{
251
+ context: z.ZodNumber;
252
+ output: z.ZodNumber;
253
+ idle_timeout_ms: z.ZodOptional<z.ZodNumber>;
254
+ }, z.core.$strip>;
255
+ body: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
256
+ body_templates: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
257
+ headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
258
+ when: z.ZodOptional<z.ZodObject<{
259
+ reasoning: z.ZodOptional<z.ZodBoolean>;
260
+ reasoning_keys: z.ZodOptional<z.ZodArray<z.ZodString>>;
261
+ }, z.core.$strip>>;
262
+ quirks: z.ZodOptional<z.ZodArray<z.ZodEnum<{
263
+ "ensure-assistant-reasoning": "ensure-assistant-reasoning";
264
+ "scrub-tool-call-id": "scrub-tool-call-id";
265
+ "done-after-tool": "done-after-tool";
266
+ "drop-empty-content": "drop-empty-content";
267
+ }>>>;
268
+ protocol: z.ZodOptional<z.ZodEnum<{
269
+ openai: "openai";
270
+ "openai-compatible": "openai-compatible";
271
+ anthropic: "anthropic";
272
+ }>>;
273
+ }, z.core.$loose>>;
274
+ }, z.core.$loose>>>;
275
+ enabled_providers: z.ZodOptional<z.ZodArray<z.ZodString>>;
276
+ disabled_providers: z.ZodOptional<z.ZodArray<z.ZodString>>;
277
+ effort: z.ZodOptional<z.ZodString>;
278
+ effort_templates: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
279
+ default: z.ZodOptional<z.ZodString>;
280
+ levels: z.ZodArray<z.ZodObject<{
281
+ id: z.ZodString;
282
+ name: z.ZodOptional<z.ZodString>;
283
+ description: z.ZodOptional<z.ZodString>;
284
+ body: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
285
+ headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
286
+ }, z.core.$strip>>;
287
+ }, z.core.$loose>>>;
288
+ trait_presets: z.ZodOptional<z.ZodArray<z.ZodObject<{
289
+ match: z.ZodObject<{
290
+ provider: z.ZodOptional<z.ZodString>;
291
+ protocol: z.ZodOptional<z.ZodEnum<{
292
+ openai: "openai";
293
+ "openai-compatible": "openai-compatible";
294
+ anthropic: "anthropic";
295
+ }>>;
296
+ model: z.ZodOptional<z.ZodString>;
297
+ }, z.core.$strip>;
298
+ traits: z.ZodObject<{
299
+ when: z.ZodOptional<z.ZodOptional<z.ZodObject<{
300
+ reasoning: z.ZodOptional<z.ZodBoolean>;
301
+ reasoning_keys: z.ZodOptional<z.ZodArray<z.ZodString>>;
302
+ }, z.core.$strip>>>;
303
+ body: z.ZodOptional<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
304
+ headers: z.ZodOptional<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>>;
305
+ reasoning: z.ZodOptional<z.ZodOptional<z.ZodObject<{
306
+ field: z.ZodOptional<z.ZodEnum<{
307
+ reasoning: "reasoning";
308
+ reasoning_content: "reasoning_content";
309
+ reasoning_details: "reasoning_details";
310
+ }>>;
311
+ interleaved: z.ZodOptional<z.ZodBoolean>;
312
+ summary: z.ZodOptional<z.ZodLiteral<"auto">>;
313
+ include: z.ZodOptional<z.ZodLiteral<"encrypted">>;
314
+ effort: z.ZodOptional<z.ZodObject<{
315
+ default: z.ZodOptional<z.ZodString>;
316
+ levels: z.ZodOptional<z.ZodArray<z.ZodObject<{
317
+ id: z.ZodString;
318
+ name: z.ZodOptional<z.ZodString>;
319
+ description: z.ZodOptional<z.ZodString>;
320
+ body: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
321
+ headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
322
+ }, z.core.$strip>>>;
323
+ template: z.ZodOptional<z.ZodString>;
324
+ }, z.core.$loose>>;
325
+ }, z.core.$strip>>>;
326
+ provider_name: z.ZodOptional<z.ZodOptional<z.ZodString>>;
327
+ image: z.ZodOptional<z.ZodOptional<z.ZodEnum<{
328
+ url: "url";
329
+ base64: "base64";
330
+ }>>>;
331
+ image_max_bytes: z.ZodOptional<z.ZodOptional<z.ZodNumber>>;
332
+ image_max_images: z.ZodOptional<z.ZodOptional<z.ZodNumber>>;
333
+ image_byte_quantum: z.ZodOptional<z.ZodOptional<z.ZodNumber>>;
334
+ image_count_quantum: z.ZodOptional<z.ZodOptional<z.ZodNumber>>;
335
+ request_max_bytes: z.ZodOptional<z.ZodOptional<z.ZodNumber>>;
336
+ image_max_pixels: z.ZodOptional<z.ZodOptional<z.ZodNumber>>;
337
+ image_max_aspect_ratio: z.ZodOptional<z.ZodOptional<z.ZodNumber>>;
338
+ cache: z.ZodOptional<z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"none">, z.ZodLiteral<"anthropic">, z.ZodLiteral<"openai-compatible">, z.ZodLiteral<"bedrock">, z.ZodObject<{
339
+ mode: z.ZodEnum<{
340
+ automatic: "automatic";
341
+ explicit: "explicit";
342
+ }>;
343
+ ttl: z.ZodEnum<{
344
+ "5m": "5m";
345
+ "1h": "1h";
346
+ }>;
347
+ scope: z.ZodOptional<z.ZodArray<z.ZodEnum<{
348
+ system: "system";
349
+ tools: "tools";
350
+ messages: "messages";
351
+ }>>>;
352
+ }, z.core.$strip>]>>>;
353
+ limit: z.ZodOptional<z.ZodObject<{
354
+ context: z.ZodNumber;
355
+ output: z.ZodNumber;
356
+ idle_timeout_ms: z.ZodOptional<z.ZodNumber>;
357
+ }, z.core.$strip>>;
358
+ body_templates: z.ZodOptional<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>>;
359
+ quirks: z.ZodOptional<z.ZodOptional<z.ZodArray<z.ZodEnum<{
360
+ "ensure-assistant-reasoning": "ensure-assistant-reasoning";
361
+ "scrub-tool-call-id": "scrub-tool-call-id";
362
+ "done-after-tool": "done-after-tool";
363
+ "drop-empty-content": "drop-empty-content";
364
+ }>>>>;
365
+ }, z.core.$loose>;
366
+ }, z.core.$strip>>>;
367
+ llm_log: z.ZodOptional<z.ZodObject<{
368
+ enabled: z.ZodDefault<z.ZodBoolean>;
369
+ max_file_bytes: z.ZodDefault<z.ZodNumber>;
370
+ sanitize_headers: z.ZodDefault<z.ZodBoolean>;
371
+ retention_days: z.ZodDefault<z.ZodNumber>;
372
+ }, z.core.$strip>>;
373
+ }, z.core.$loose>;
374
+ type LlmConfig = z.infer<typeof LlmConfigSchema>;
375
+ //#endregion
376
+ //#region src/index.d.ts
377
+ declare const name = "tboxcode-llm";
378
+ declare const inject: string[];
379
+ /**
380
+ * cordis 插件入口:注册全部启用 provider 路由;watcher 热载经 replace 换装。
381
+ * 待命降级(llm-shell-standby-mount):mount 失败不上抛——warn 引导 + watcher 待命,
382
+ * 配置就绪热挂(registerAdapter 原生发射 llm/adapters-updated,GUI 自刷新)。
383
+ */
384
+ declare function apply(ctx: Context): () => void;
385
+ //#endregion
386
+ export { type LlmConfig, LlmConfigSchema, ModelEntrySchema, type ModelTraits, ModelTraitsSchema, type TboxcodeDshModelTraits, apply, inject, name };