@tbox.cn/app-sdk-server 0.26.3 → 1.0.0-alpha.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.
- package/README.md +3 -1
- package/dist/app-DjQy7ben.d.ts +1355 -0
- package/dist/chunk-DVAVJ2LJ.js +1 -0
- package/dist/chunk-U2YZGGOR.js +1 -0
- package/dist/config.d.ts +151 -0
- package/dist/config.js +1 -0
- package/dist/platform/index.d.ts +219 -1
- package/dist/platform/index.js +43 -9
- package/dist/server/index.d.ts +8 -1267
- package/dist/server/index.js +3 -3
- package/package.json +10 -6
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as Y}from"./chunk-U2YZGGOR.js";import{AsyncLocalStorage as Ne}from"async_hooks";import{createCoreLogger as je,detailForLog as C,resolveLevel as Fe,setLogContextProvider as ze}from"@tbox.cn/app-sdk-core";var w=new Ne;ze(()=>w.getStore());function Lt(t,e){return w.run(t,e)}var P=()=>{};function $t(t){P=t}function X(t){return`${t}_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function M(){return new Date}function J(t){let e=t;return{message:e?.message||String(t??"unknown"),...e?.name?{type:e.name}:{},...e?.stack?{stack:e.stack}:{}}}function g(t){return{...je({tag:t,getLevel:()=>Fe(process.env.TBOX_LOG_LEVEL,"info"),getContext:()=>w.getStore()}),span(r,n){let o=w.getStore();P({spanId:X(`sp_${t.replace(/[^a-zA-Z0-9]/g,"")}`),traceId:o?.requestId??"no-req",name:r,startTime:M(),endTime:M(),...n?.metadata!==void 0?{metadata:n.metadata}:{},...n?.error!==void 0?{errorInfo:J(n.error)}:{},requestId:o?.requestId??"no-req",...o?.conversationId?{conversationId:o.conversationId}:{},...o?.threadKey?{sessionId:o.threadKey}:{}})}}}var ae=3e3;async function _t(t,e,r,n){let o=Date.now();try{let s=await r(),i=Date.now()-o;if(n?.onDone?.(i),n?.logger&&t==="tool"){let a=n.detail?.args!==void 0?` args=${C(n.detail.args)}`:"",l=` result=${C(s)}`;n.logger.info(`${e} ok durMs=${i}${a}${l}`)}else n?.logger&&t==="op"&&n.logger.info(`${e} ok durMs=${i}`);return n?.emitSpan&&se(t,e,{durMs:i}),s}catch(s){let i=Date.now()-o;if(n?.onDone?.(i),n?.logger){let a=t==="tool"?"error":"warn",l=` err=${s?.message??String(s)}`;n.logger[a](`${e} fail durMs=${i}${l}`)}throw n?.emitSpan&&se(t,e,{durMs:i,error:s}),s}}function se(t,e,r){let n=w.getStore();P({spanId:X("sp_call"),traceId:n?.requestId??"no-req",name:`${t}:${e}`,startTime:M(),endTime:M(),metadata:{durMs:r.durMs,kind:t},...r.error!==void 0?{errorInfo:J(r.error)}:{},requestId:n?.requestId??"no-req",...n?.conversationId?{conversationId:n.conversationId}:{},...n?.threadKey?{sessionId:n.threadKey}:{}})}function Ot(t,e){return t?{async request(r){t.info(`→ ${r.path} body=${C(r.body)}`);let n=Date.now(),o=w.getStore(),s=o?new Date(n):void 0;try{let i=await e.request(r),a=Date.now()-n,l=`← ${r.path} durMs=${a} body=${C(i)}`;return a>ae?t.warn(`SLOW ${l}`):t.info(l),ie(o,s,r.path,a),i}catch(i){let a=Date.now()-n;throw t.warn(`← ${r.path} durMs=${a} err=${i?.message??String(i)}`),ie(o,s,r.path,a,i),i}}}:e}function ie(t,e,r,n,o){!t||!e||P({spanId:X("sp_ext"),traceId:t.requestId??"no-req",name:"external-call",startTime:e,endTime:new Date(e.getTime()+n),metadata:{path:r,durMs:n,...n>ae?{slow:!0}:{}},...o!==void 0?{errorInfo:J(o)}:{},requestId:t.requestId??"no-req",...t.conversationId?{conversationId:t.conversationId}:{},...t.threadKey?{sessionId:t.threadKey}:{}})}var ce=g("EventBus");function de(){let t=new Map;return{on(e,r){t.has(e)||t.set(e,new Set);let n=t.get(e);return n.add(r),()=>n.delete(r)},emit(e,r){let n=t.get(e);if(n)for(let o of n)try{o(r)}catch(s){ce.error(`handler error for "${String(e)}":`,s)}},off(e,r){let n=t.get(e);n&&n.delete(r)},clear(){t.clear()},async publish(e,r){let n=t.get(e);if(!n||n.size===0)return;let o=[];for(let s of n)try{let i=s(r);i&&typeof i.then=="function"&&o.push(i)}catch(i){ce.error(`handler error for "${String(e)}":`,i)}o.length>0&&await Promise.allSettled(o)},subscribe(e,r){return this.on(e,r)}}}var Ue=g("ServiceRegistry"),E=class{services=new Map;register(e,r){this.services.has(e)&&Ue.warn(`overwriting existing service: ${e}`),this.services.set(e,r)}resolve(e){return this.services.get(e)}clear(){this.services.clear()}getAll(){return Object.fromEntries(this.services)}},Z=new E;function jt(t,e){Z.register(t,e)}function Ft(t){return Z.resolve(t)}function zt(){Z.clear()}var le=g("HandlerRegistry");function Wt(t){let e=[],r=t instanceof Map?[...t.values()]:Object.values(t);for(let o of r)for(let s of o.intents??[])e.push({id:`${o.id}:${s.patterns[0]??"intent"}`,keywords:s.patterns,handlerId:o.id,action:"intent",...s.match?{match:s.match}:{}});let n=e.filter(o=>o.match===void 0||o.match==="bm25");return n.length>0&&le.warn(`顶层意图路由非确定性档(${n.map(o=>o.id).join(", ")}):语义分类职责归 skill 路由与 LLM 工具编排——建议声明 match:"exact"/"prefix"(详见 prompt-pipeline「declaration 与 intents」)`),e}var D=class{handlers=new Map;register(e){this.handlers.has(e.id)&&le.warn(`overwriting existing handler: ${e.id}`),this.handlers.set(e.id,e)}resolve(e){return this.handlers.get(e)}getAll(){return Object.fromEntries(this.handlers)}has(e){return this.handlers.has(e)}get size(){return this.handlers.size}async dispatch(e,r,n,o,s){let i=this.handlers.get(e);return i?i.handle(r,n,o,s):{cards:[],text:`未知的服务:${e}`}}};var ue=g("ToolRegistry"),L=class{tools=new Map;disabled=new Set;disable(e){e&&(this.disabled.add(e),this.tools.delete(e))}register(e){let r=e.id;if(!r){ue.warn("tool without id skipped:",e.description);return}this.disabled.has(r)||(this.tools.has(r)&&ue.warn(`overwriting existing tool: ${r}`),this.tools.set(r,e))}registerAll(e){for(let r of e)this.register(r)}resolve(e){return this.tools.get(e)}getAll(){return Object.fromEntries(this.tools)}has(e){return this.tools.has(e)}get size(){return this.tools.size}};var $=g("CardRegistry"),_=class{cards=new Map;disabled=new Set;owners=new Map;disable(e){e&&(this.disabled.add(e),this.cards.delete(e))}register(e){if(!e.cardType){$.warn("meta without cardType skipped");return}if(this.disabled.has(e.cardType)){$.debug(`disabled cardType skipped: ${e.cardType}`);return}this.cards.has(e.cardType)&&$.warn(`overwriting existing cardType: ${e.cardType}`),this.cards.set(e.cardType,e)}registerAll(e){for(let r of e)this.register(r)}registerMap(e){for(let[r,n]of Object.entries(e))r!==n.cardType&&$.warn(`registerMap key "${r}" !== meta.cardType "${n.cardType}", registered as meta.cardType`),this.register(n)}resolve(e){return this.cards.get(e)}recordOwner(e,r){!e||!r||this.owners.set(e,r)}ownerOf(e){return this.owners.get(e)}getAll(){return Object.fromEntries(this.cards)}has(e){return this.cards.has(e)}get size(){return this.cards.size}};import{SKILL_NAME_PATTERN as ge}from"@tbox.cn/app-contracts";var Qt={description:1024,instructions:32*1024,references:64,referenceSize:32*1024};var O=g("SkillRegistry"),q=class{skills=new Map;register(e){if(!ge.test(e.name)){O.warn(`非法 skill 名 "${e.name}" 跳过(须匹配 ^[a-z0-9-]{1,64}$)`);return}for(let r of Object.keys(e.references))r.endsWith(".md")||O.warn(`skill "${e.name}" reference key "${r}" 非 .md 结尾`);this.skills.has(e.name)&&O.warn(`覆盖已注册 skill: ${e.name}`),this.skills.set(e.name,e)}registerAll(e){for(let r of e)this.register(r)}registerMap(e){for(let[r,n]of Object.entries(e))r!==n.name&&O.warn(`registerMap key "${r}" !== skill.name "${n.name}", registered as skill.name`),this.register(n)}getAll(){return[...this.skills.values()]}has(e){return this.skills.has(e)}get size(){return this.skills.size}};import{PRE_TOOL_NAME_PATTERN as Be}from"@tbox.cn/app-contracts";var H=g("PreToolRegistry"),K=class{preTools=new Map;register(e){let r=e?.tool?.id;if(!r||!Be.test(r)){H.warn(`非法 toolId "${r}" 跳过(须匹配 ^[A-Za-z0-9_-]{1,64}$)`);return}if(e.routing.mode==="keywords"&&e.routing.terms.length===0){H.warn(`keywords 路由空 terms 跳过: ${r}(恒不命中;如须每轮候选请用 always 模式)`);return}this.preTools.has(r)&&H.warn(`覆盖已注册 pre-tool: ${r}`),this.preTools.set(r,e)}registerAll(e){for(let r of e)this.register(r)}registerMap(e){for(let[r,n]of Object.entries(e)){let o=n?.tool?.id;r!==o&&H.warn(`registerMap key "${r}" !== tool.id "${o}", registered as tool.id`),this.register(n)}}getAll(){return[...this.preTools.values()]}has(e){return this.preTools.has(e)}get size(){return this.preTools.size}};import{Router as We}from"express";var pe=g("ApiRouteRegistry"),N=class{root=We();moduleIds=[];register(e,r){let n=e.replace(/^\/+|\/+$/g,"");if(!n){pe.warn("register with empty moduleId skipped");return}this.moduleIds.includes(n)&&pe.warn(`overwriting existing module: ${n}`),this.root.use(`/${n}`,r),this.moduleIds.includes(n)||this.moduleIds.push(n)}mount(){return this.root}getModuleIds(){return[...this.moduleIds]}};var j=class{store=new Map;async save(e,r){let n=this.store.get(e)??[],o=n.findIndex(s=>s.id===r.id);o>=0?n[o]=r:n.push(r),this.store.set(e,n)}async load(e){return this.store.get(e)??[]}async clear(e){this.store.delete(e)}};function fe(t){let e=0;for(let r=0;r<t.length;r++)e=e*31+t.charCodeAt(r)|0;return String(e)}var F=class{store=new Map;ttlMs;maxEntries;constructor(e){this.ttlMs=e?.ttlMs??1440*60*1e3,this.maxEntries=e?.maxEntries??1e4}async tryAcquire(e,r){let n=Date.now(),o=this.store.get(e);return o&&o.expiresAt>n?{acquired:!1,result:o.result}:(this.store.set(e,{payloadHash:r,result:void 0,expiresAt:n+this.ttlMs}),this.evict(n),{acquired:!0})}async commit(e,r){let n=this.store.get(e);this.store.set(e,{payloadHash:n?.payloadHash??"",result:r,expiresAt:n?.expiresAt??Date.now()+this.ttlMs})}getPayloadHash(e){let r=this.store.get(e);if(!(!r||r.expiresAt<=Date.now()))return r.payloadHash}release(e){this.store.delete(e)}evict(e){for(let[r,n]of this.store)n.expiresAt<=e&&this.store.delete(r);for(;this.store.size>this.maxEntries;){let r=this.store.keys().next().value;if(r===void 0)break;this.store.delete(r)}}clear(){this.store.clear()}};function me(t){try{return fe(JSON.stringify(t??{}))}catch{return fe(String(t))}}import{AUTH_ERROR_CODES as T,authCodeToStatus as Ge}from"@tbox.cn/app-contracts";var A=class t extends Error{code;status;constructor(e,r){super(r||e),this.name="AuthError",this.code=e,this.status=Ge(e)}static unauthorized(e){return new t(T.UNAUTHORIZED,e)}static tokenExpired(e){return new t(T.TOKEN_EXPIRED,e)}static forbidden(e){return new t(T.FORBIDDEN,e)}static methodRequired(e){return new t(T.METHOD_REQUIRED,e)}static browserLoginDisabled(e){return new t(T.BROWSER_LOGIN_DISABLED,e)}static externalError(e){return new t(T.EXTERNAL_ERROR,e)}static missingSecret(e){return new t(T.MISSING_SECRET,e)}};import{AsyncLocalStorage as Ve}from"async_hooks";import{networkInterfaces as Ye}from"os";import{createCoreLogger as Xe,resolveLevel as Je}from"@tbox.cn/app-sdk-core";var he="sofa-traceid",ve="sofa-rpcid",xe="traceid",Se="rpcid",ye=/^[\w.-]{1,64}$/,Ze=["tbox.cn"],B=new Ve,Qe=Xe({tag:"SOFA",getLevel:()=>Je(process.env.TBOX_LOG_LEVEL,"info"),getContext:()=>{}});function et(t){let e=t.split(".");if(e.length!==4)return"ffffffff";let r="";for(let n of e){let o=Number(n);if(!Number.isInteger(o)||o<0||o>255)return"ffffffff";let s=o.toString(16);r+=s.length===1?`0${s}`:s}return r}function tt(){try{for(let t of Object.values(Ye()))for(let e of t??[])if(e.family==="IPv4"&&!e.internal)return et(e.address)}catch{}return"ffffffff"}var rt=tt(),z=1e3;function nt(){return z=z>9e3?1e3:z+1,String(z)}function Q(){return rt+Date.now()+nt()+process.pid}function vr(){B.enterWith({traceId:Q(),parentRpcId:"0",childSeq:0})}function U(t){return Array.isArray(t)?t[0]:t}function Re(t){let e=U(t[he])??U(t[xe]),r;if(e!==void 0&&ye.test(e)){let n=U(t[ve])??U(t[Se]);r={traceId:e,parentRpcId:n!==void 0&&ye.test(n)?n:"0",childSeq:0}}else r={traceId:Q(),parentRpcId:"0",childSeq:0};return B.enterWith(r),r.traceId}function xr(){return B.getStore()?.traceId}function ot(){let t=process.env.TBOX_SOFA_TRACE_HOSTS;return t?t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0):[]}function st(t){return[...Ze,...ot()].some(r=>t===r||t.endsWith(`.${r}`))}function Sr(t){if(process.env.TBOX_SOFA_TRACE==="off")return{};let e,r;try{let i=new URL(t);e=i.hostname.toLowerCase(),r=i.pathname}catch{return{}}if(!st(e))return{};let n=B.getStore(),o=n?.traceId??Q(),s=n?`${n.parentRpcId}.${++n.childSeq}`:"0.1";return Qe.debug(`out traceId=${o} rpcId=${s} host=${e} path=${r}`),{[he]:o,[xe]:o,[ve]:s,[Se]:s}}var we=g("HTTP");function it(t){if(typeof t!="string")return;let e=t.trim();return/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:void 0}function at(){return`req_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}var Ae="tboxAuthContext";function ct(t,e){Object.defineProperty(t,Ae,{value:e,enumerable:!0,configurable:!0})}function ee(t){return t[Ae]}function Ie(t=Date.now()){return{userId:`anonymous_${t}_${Math.random().toString(36).slice(2,8)}`,source:"anonymous"}}function Ir(t,e={}){let r=e.mode??"required",n=(e.publicPaths??[]).map(s=>s.replace(/\/+$/,""));function o(s){let i=(s.originalUrl||s.url||"").split("?")[0].replace(/\/+$/,"");return n.some(a=>i===a||i.startsWith(`${a}/`))}return async(s,i,a)=>{let l=it(s.headers["x-request-id"])??at();i.setHeader?.("X-Request-ID",l),w.enterWith({requestId:l});let m=Re(s.headers),c=Date.now();if(i.on?.("finish",()=>{let d=Date.now()-c,p=`${s.method} ${s.originalUrl||s.url} ${i.statusCode} durMs=${d} sofa=${m}`,u=(s.originalUrl||s.url||"").split("?")[0];/\/health(z)?$/.test(u)?we.debug(p):we.info(p)}),o(s))return a();try{let d=s.headers.authorization,p=d?.startsWith("Bearer ")?d.slice(7).trim():void 0,u=await Te(t,p,r),f=s.body?.context,h=s.method==="POST"&&f!==void 0?be(f):void 0;if(h&&e.validateContext&&!e.validateContext(h)){i.status(403).json({error:"context validation failed",code:"AUTH_FORBIDDEN"});return}return ct(s,{identity:u.identity,...u.credentials?{credentials:u.credentials}:{},...h?{attributes:h}:{}}),a()}catch(d){if(d instanceof A){i.status(d.status).json({error:d.message,code:d.code});return}i.status(401).json({error:d.message,code:"AUTH_UNAUTHORIZED"})}}}var dt=g("AUTH");async function Te(t,e,r){if(!e){if(r==="optional")return{identity:Ie()};throw A.unauthorized("missing Bearer token")}let n=await t.verify(e);return{identity:{userId:n.sub,source:n.source},...n.external?{credentials:n.external}:{}}}var lt=4096;function be(t){if(!(!t||typeof t!="object"||Array.isArray(t)))try{let e=JSON.stringify(t);if(Buffer.byteLength(e,"utf8")>lt){dt.warn("context envelope dropped (>4KB): treated as absent (fail-soft)");return}return t}catch{return}}var Ee=g("ActionGateway");function ke(t){let e=new Map,r=t?.idempotencyStore??new F;function n(c){return{sessionId:(c?.body??{})?.sessionId??"",requestContext:c?ee(c):void 0,emit:()=>{}}}async function o(c,d){for(let p of d.checks??[]){let u=await p.check(c);if(!u.ok)return u}return null}async function s(c,d,p,u){let f=c.policy,h=f.write??!1,S=f.idempotent??!1;if(h&&S){if(!u)return{status:400,body:{success:!1,error:"Missing idempotencyKey (write action)"}};let v=me(d),R=await r.tryAcquire(u,v);if(!R.acquired){let x=r.getPayloadHash?.(u);return x&&x!==v?{status:409,body:{success:!1,error:"Idempotency key reused with different payload"}}:R.result!==void 0?{status:200,body:{...R.result,cached:!0}}:{status:200,body:{success:!0,pending:!0,cached:!0}}}try{let x=await c.handler(d,p);return await r.commit(u,x),{status:200,body:x}}catch(x){throw r.release?.(u),x}}return{status:200,body:await c.handler(d,p)}}async function i(c,d,p){if(!c||typeof c!="string")return{status:400,body:{success:!1,error:"Missing action"}};let u=e.get(c);if(!u)return{status:404,body:{success:!1,error:`Unknown action: ${c}`}};if(u.policy.write&&ee(p)?.identity?.source==="anonymous")return{status:403,body:{success:!1,error:"anonymous write is forbidden"}};let f=await o(p,u.policy);if(f)return{status:f.code??403,body:{success:!1,error:f.message}};let h=p.body??{};return s(u,d,n(p),h.idempotencyKey)}function a(){return async(c,d,p)=>{try{let u=c.body??{},f=await i(u.action,u.payload,c);d.status(f.status).json(f.body)}catch(u){Ee.error("handler error:",u),d.status(500).json({success:!1,error:u?.message||"Internal error"})}}}function l(c={}){return async(d,p,u)=>{try{let f=await o(d,c);if(f){p.status(f.code??403).json({success:!1,error:f.message});return}u()}catch(f){u(f)}}}async function m(c,d,p){let u=e.get(c);if(!u)return{success:!1,error:`Unknown action: ${c}`};let f=p?.requestContext?.identity??p?.identity;if(u.policy.write&&f?.source==="anonymous")return{success:!1,error:"anonymous write is forbidden"};let h=await o({},u.policy);return h?{success:!1,error:h.message}:(await s(u,d,{sessionId:p?.sessionId??"",requestContext:p?.requestContext?p.requestContext:p?.identity?{identity:p.identity}:void 0,emit:()=>{}},p?.idempotencyKey)).body}return{registerAction(c,d,p={}){e.has(c)&&Ee.warn(`overwriting existing action: ${c}`),e.set(c,{handler:d,policy:p})},middleware:a,validateAction:l,dispatch:m,getActions:()=>new Map(e)}}import{createHash as ut,randomUUID as qr}from"crypto";var b=(t,e)=>`${t}\0${e}`;function te(t){if(t!==null&&typeof t=="object"&&!Object.isFrozen(t)){Object.freeze(t);for(let e of Object.values(t))te(e)}return t}function Ce(t=()=>new Date){let e=new Map,r=(n,o)=>n.expiresAt===void 0||n.expiresAt>o;return{async get(n,o){let s=e.get(b(n,o));return s?r(s,t().getTime())?s.value:(e.delete(b(n,o)),null):null},async getEntry(n,o){let s=e.get(b(n,o));return s?r(s,t().getTime())?{value:s.value,revision:s.revision,expiresAt:s.expiresAt}:(e.delete(b(n,o)),null):null},async put(n,o,s,i){let a=b(n,o),l=(e.get(a)?.revision??0)+1;return e.set(a,{value:te(structuredClone(s)),revision:l,expiresAt:i>0?t().getTime()+i:void 0}),!0},async compareAndSet(n,o,s,i,a){let l=b(n,o),m=t().getTime(),c=e.get(l),d=c&&r(c,m)?c.revision:0;return d!==s?!1:(e.set(l,{value:te(structuredClone(i)),revision:d+1,expiresAt:a>0?m+a:void 0}),!0)},async consume(n,o){let s=b(n,o),i=e.get(s);return i?r(i,t().getTime())?(e.delete(s),i.value):(e.delete(s),null):null}}}function Hr(t){return ut("sha256").update(t).digest("hex").slice(0,32)}var gt=g("PROVIDER"),pt="static-headers-v1",jr="-",ft={credentialType:pt,apply(t){let e={};for(let[r,n]of Object.entries(t.credential.value))typeof n=="string"&&(e[r]=n);return e}};function Me(t=[ft]){let e=new Map;for(let r of t)e.set(r.credentialType,r);return{get:r=>e.get(r),register:r=>{e.get(r.credentialType)!==r&&(e.has(r.credentialType)&>.warn(`认证策略重复注册(后者覆盖):${r.credentialType}`),e.set(r.credentialType,r))},list:()=>[...e.values()]}}var W=g("auth-exchanges");function Pe(t){let e=new Map;for(let[n,o]of Object.entries(t??{}))e.set(n,o);let r=[];return{register(n){if(n.matches){r.includes(n)||r.push(n);return}let o=r.findIndex(s=>!s.matches&&s.provider===n.provider);if(o>=0){r[o]=n;return}r.push(n)},get(n,o){let s=r.filter(l=>l.provider===n);for(let l of s){if(!l.matches)continue;let m=!1;try{m=l.matches(o)!==!1}catch(c){W.warn(`matches threw for ${n}(谓词违约视为不命中):`,c.message)}if(m)return W.debug("resolve",n,"source=scoped"),l}let i=s.find(l=>!l.matches);if(i)return W.debug("resolve",n,"source=fallback"),i;let a=e.get(n);return W.debug("resolve",n,a?"source=builtin":"source=none",`explicit=${s.length}`),a},list(){return[...r,...e.values()]}}}import{SCOPE_ASSEMBLY_KIND as mt}from"@tbox.cn/app-contracts";var yt=g("DomainAssemblyRegistry"),G=class{assemblies=new Map;register(e,r){this.assemblies.has(e)&&yt.warn(`overwriting existing domain assembly: ${e}`),this.assemblies.set(e,r)}resolve(e){return this.assemblies.get(e)}scopeAssembly(){return this.resolve(mt)}get size(){return this.assemblies.size}};function De(t){let e=new E,r=t?.snapshotStore??new j,n=new Map,o=ke({idempotencyStore:t?.idempotencyStore}),s=new G,i=t?.scopeDefaults,a=new Proxy({},{get:(y,v)=>{if(typeof v!="string")return;let R=s.scopeAssembly()?.scopeDefaults?.[v];return R!==void 0?R:i?.[v]},has:(y,v)=>typeof v!="string"?!1:s.scopeAssembly()?.scopeDefaults?.[v]!==void 0||i?.[v]!==void 0}),l=t?.state??Ce(),m=t?.authStrategies??Me(),c=t?.authExchanges??Pe(),d=new Map,p={register:y=>{if((!y.kind||y.kind==="moduleAction")&&!y.execute)throw new Error(`moduleAction 动作缺少 execute 回调:${y.moduleId}:${y.actionId}`);d.set(y.actionId,y)},get:y=>d.get(y),getAll:()=>new Map(d)},u=y=>e.resolve(y),f=(y,v)=>n.get(y)?.[v],h=(y,v,R)=>{let x=n.get(y)??{};x[v]=R,n.set(y,x)},S=y=>{n.delete(y)};return{handlers:new D,tools:new L,cards:new _,skills:new q,preTools:new K,routes:new N,services:e,bus:de(),snapshotStore:r,actions:o,resolveService:u,flowStates:{get:f,set:h,clear:S},state:l,...t?.memory?{memory:t.memory}:{},cardActions:p,authStrategies:m,authExchanges:c,domainAssemblies:s,...t?.integrations?{integrations:t.integrations}:{},scopeDefaults:a}}import{expandEnvVars as ht}from"@tbox.cn/app-toolkit";function Le(t,e=process.env,r="<config>"){let n=ht(t,e);if(n.missing.length>0){let o={file:r,missing:n.missing};throw new Error(`配置文件 ${o.file} 引用的环境变量缺失:${o.missing.join("、")}(先 source .real-env/env.sh <vendor>[-<variant>] 或由部署链注入后重试;缺变量集中报错而非静默空值,防带错配置启动)`)}return n.text}import{readFileSync as vt}from"fs";import{join as xt}from"path";var re=g("app-config"),k={bases:{},defaults:{}};function $e(t){let e=xt(t,"knowledge.json"),r;try{r=JSON.parse(Le(vt(e,"utf8"),process.env,e))}catch(s){return s.code==="ENOENT"?(re.warn(`knowledge.json 不存在(文件:${e})——ref 引用将降级缺失(台账锚 = integrations.json 同目录,检查壳 source 传参)`),k):(re.warn(`knowledge.json 解析失败(${s.message},文件:${e})——ref 引用将降级缺失`),k)}let n=Y.safeParse(r);if(!n.success)return re.warn(`knowledge.json 校验失败(${n.error.message},文件:${e})——ref 引用将降级缺失`),k;let o={};for(let[s,i]of Object.entries(n.data.knowledge_bases??{}))o[s]={datasetId:i.datasetId,...i.retrieve_config?.topK!==void 0?{topK:i.retrieve_config.topK}:{},...i.retrieve_config?.scoreThreshold!==void 0?{scoreThreshold:i.retrieve_config.scoreThreshold}:{}};return{bases:o,defaults:{...n.data.defaults?.topK!==void 0?{topK:n.data.defaults.topK}:{},...n.data.defaults?.scoreThreshold!==void 0?{scoreThreshold:n.data.defaults.scoreThreshold}:{}}}}var ne=g("app-config"),Rn=["faq","mall-knowledge"],_e={};function Oe(t,e){if(!t)return()=>_e;let n=Object.values(t).some(s=>Object.values(s.resources??{}).some(i=>i.ref!==void 0))?$e(e):k,o=new Map;for(let[s,i]of Object.entries(t)){let a={};for(let[l,m]of Object.entries(i.resources??{})){let c=St(s,l,m,n,e);c&&(a[l]=c)}o.set(s,a)}return s=>o.get(s)??_e}function St(t,e,r,n,o){if(r.datasetId!==void 0)return r.ref!==void 0&&ne.warn(`模块 ${t} 资源 ${e} 同时声明 datasetId 与 ref——datasetId 优先,ref 忽略`),{type:"knowledge",datasetId:r.datasetId,...r.topK!==void 0?{topK:r.topK}:{},...r.scoreThreshold!==void 0?{scoreThreshold:r.scoreThreshold}:{}};if(r.ref!==void 0){let s=n.bases[r.ref];if(!s){ne.warn(`模块 ${t} 资源 ${e} ref="${r.ref}" 在 knowledge.json 注册表未命中(目录锚:${o})——资源缺失,走模块占位回退`);return}return{type:"knowledge",datasetId:s.datasetId,topK:r.topK??s.topK??n.defaults.topK,scoreThreshold:r.scoreThreshold??s.scoreThreshold??n.defaults.scoreThreshold}}ne.warn(`模块 ${t} 资源 ${e} 无 datasetId/ref(zod 已拦,防御分支)——资源缺失`)}import Rt from"path";var wt=g("app-config");async function qe(t,e){if(!t.services.resolve("app-config")){let r=t.integrations?.raw,n=r?.source?Rt.dirname(r.source):"";Object.values(r?.config.modules??{}).some(s=>Object.values(s.resources??{}).some(i=>i.ref!==void 0))&&!r?.source&&wt.warn("integrations.raw.source 未传——模块资源 ref 将按空目录锚解析(通常落空):请在 createIntegrationsRegistry({ source: <integrations.json 源路径> }) 传参"),t.services.register("app-config",Oe(r?.config.modules,n))}for(let r of e){let n={...t,logger:g(`module:${r.declaration?.moduleId??"anonymous"}`)};if("skills"in r&&r.skills&&n.skills.registerMap(r.skills),"preTools"in r&&r.preTools&&n.preTools.registerMap(r.preTools),r.declaration?.moduleId)for(let o of Object.values(r.cards))t.cards.recordOwner(o.cardType,r.declaration.moduleId);await r.register(n)}}import{AsyncLocalStorage as Tt}from"async_hooks";import{createServer as bt}from"http";import{readFile as He}from"fs/promises";import V from"path";import{randomUUID as At}from"crypto";import oe from"express";var I=class extends Error{code;status;details;constructor(e,r,n={}){super(r),this.name="AppError",this.code=e,this.status=n.status??500,this.details=n.details}},Ke=new Tt;function On(){let t=Ke.getStore();if(!t)throw new I("OUTSIDE_REQUEST_CONTEXT","serverContext() 只能在请求处理函数内调用",{status:500});return t}function It(t){let e;try{e=decodeURIComponent(t)}catch{return null}return e.includes("\0")||(e!=="/"&&e.endsWith("/")&&(e=e.slice(0,-1)),e.split("/").some(r=>r===".."))?null:e||"/"}function Et(t,e){if(!e||V.isAbsolute(e)||e.includes("\\")||e.split("/").includes(".."))return null;let r=V.resolve(t,e);return r.startsWith(V.resolve(t)+V.sep)?r:null}function kt(t){if(t instanceof I)return{status:t.status,code:t.code,message:t.message};let e=t;return e?.type==="entity.too.large"?{status:413,code:"RPC_PAYLOAD_TOO_LARGE",message:"请求体超过 1 MiB"}:e?.type==="entity.parse.failed"||e instanceof SyntaxError?{status:400,code:"RPC_BAD_REQUEST",message:"JSON 请求体不合法"}:{status:500,code:e?.code??"RPC_INTERNAL",message:"服务器内部错误"}}function Ct(t){return async(e,r,n)=>{if(e.method!=="GET"&&e.method!=="HEAD")return n();let o=It(e.path);if(!o){r.status(400).type("text/plain").send("Bad Request");return}let i=(t.getManifest?t.getManifest():t.manifest).pages.find(a=>a.path===o);if(!i)return n();try{if(t.vite){if(!t.htmlFile)throw new Error("dev 模式需要 htmlFile");let c=await He(t.htmlFile,"utf8"),d=await t.vite.transformIndexHtml(e.originalUrl,c),p=t.decorateHtml?t.decorateHtml(d,e):d;r.status(200).set({"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}).send(p);return}if(!t.clientDir)throw new Error("prod 模式需要 clientDir");let a=Et(t.clientDir,i.document);if(!a){r.status(500).type("text/plain").send("Invalid document");return}let l=await He(a,"utf8"),m=t.decorateHtml?t.decorateHtml(l,e):l;r.status(200).set({"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}).send(m)}catch(a){n(a)}}}function Mt(t,e){let r=new Set;for(let o of t.tools){if(r.has(o.id))throw new I("TOOL_ID_DUPLICATE",`工具 ID 重复: ${o.id}`);r.add(o.id),e.tools.register(o)}for(let o of t.skills)e.skills.register(o);let n=new Set;for(let[o,s]of Object.entries(t.cards??{})){if(n.has(o))throw new I("CARD_TYPE_DUPLICATE",`卡片类型重复: ${o}`);n.add(o),e.cards.register(s)}}async function qn(t){let e=oe(),r=t.logger??g("server"),n=t.ctx??De();Mt(t.registry,n),await qe(n,t.registry.modules),r.info("modules_registered",{tools:n.tools.size,skills:n.skills.size,cards:n.cards.size}),e.disable("x-powered-by"),e.use((i,a,l)=>{let m=typeof i.header("x-request-id")=="string"&&i.header("x-request-id")?i.header("x-request-id"):At();i.headers["x-request-id"]=m,a.locals.requestId=m,a.setHeader("x-request-id",m),a.setHeader("Cache-Control","no-store"),l()}),await t.beforeRoutes?.(e,n),e.get("/api/health",(i,a)=>{a.json({status:"ok"})});let o=oe.json({limit:"1mb",strict:!0});e.post("/api/fn/:id",o,async(i,a,l)=>{let m=i.params.id;if(!/^[a-z][a-z0-9]*(?:[.-][a-z][a-z0-9]*)*$/.test(m)){a.status(404).json({error:{code:"RPC_NOT_FOUND",message:`未知函数: ${m}`}});return}if(i.headers["content-type"]&&!i.is("application/json")){a.status(415).json({error:{code:"RPC_UNSUPPORTED_MEDIA_TYPE",message:"只支持 application/json"}});return}let c=t.registry.functions[m];if(!c){a.status(404).json({error:{code:"RPC_NOT_FOUND",message:`未知函数: ${m}`}});return}let d=String(a.locals.requestId),p=new AbortController,u=()=>{a.writableEnded||p.abort()};a.on("close",u);try{let f=t.resolveUser?await t.resolveUser(i):a.locals.user??null,h={requestId:d,user:f,logger:r,signal:p.signal},S=await Ke.run(h,async()=>c(i.body));if(S===void 0){a.status(204).end();return}a.status(200).json(S)}catch(f){l(f)}finally{a.off("close",u)}}),e.all("/api/fn/:id",(i,a)=>{a.status(405).json({error:{code:"RPC_METHOD_NOT_ALLOWED",message:"只支持 POST"}})}),await t.extend?.(e,n),e.use("/api",(i,a)=>{a.status(404).json({error:{code:"API_NOT_FOUND",message:"Not Found"}})}),t.mode==="prod"&&t.clientDir&&e.use(oe.static(t.clientDir,{index:!1,redirect:!1,maxAge:"1h"}));let s=Ct({manifest:t.manifest,getManifest:t.getManifest,mode:t.mode,clientDir:t.clientDir,htmlFile:t.htmlFile,vite:t.vite,decorateHtml:t.decorateHtml});return e.use(s),t.vite&&e.use(t.vite.middlewares),e.use((i,a)=>{if(i.path.startsWith("/api/")){a.status(404).json({error:{code:"API_NOT_FOUND",message:"Not Found"}});return}a.status(404).type("text/plain").send("Not Found")}),e.use((i,a,l,m)=>{if(l.headersSent)return;let c=kt(i),d=String(l.locals.requestId??"");c.status>=500?r.error("request_failed",{requestId:d,path:a.path,error:i?.stack??String(i)}):r.warn("request_rejected",{requestId:d,path:a.path,code:c.code}),l.status(c.status).json({error:{code:c.code,message:c.message}})}),e}async function Hn(t,e={}){let r=e.port??Number(process.env.PORT??8e3),n=e.host??process.env.HOST??"0.0.0.0",o=e.logger??g("server"),s=e.server??bt();return s.on("request",t),await new Promise((i,a)=>{s.once("error",a),s.listen(r,n,()=>{s.off("error",a),i()})}),o.info(`listening on http://${n}:${r}`),s}export{w as a,Lt as b,$t as c,g as d,ae as e,_t as f,Ot as g,de as h,E as i,jt as j,Ft as k,zt as l,Wt as m,D as n,L as o,_ as p,ge as q,Qt as r,q as s,K as t,N as u,j as v,F as w,me as x,A as y,Te as z,lt as A,be as B,vr as C,Re as D,xr as E,Sr as F,ct as G,ee as H,Ie as I,Ir as J,ke as K,Ce as L,Hr as M,pt as N,jr as O,ft as P,Me as Q,Pe as R,G as S,De as T,Le as U,$e as V,Rn as W,Oe as X,qe as Y,I as Z,On as _,Ct as $,qn as aa,Hn as ba};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{z as e}from"zod";var o=e.object({topK:e.number().int().positive().optional(),scoreThreshold:e.number().optional()}).passthrough(),t=e.object({datasetId:e.string().min(1).describe("平台知识库数据集 ID;knowledge_bases 的键是本地引用名"),retrieve_config:o.optional()}).passthrough(),r=e.object({defaults:o.optional(),knowledge_bases:e.record(e.string(),t).optional()}).passthrough();export{r as a};
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
/** Pure configuration contracts: shared by runtime loaders and authoring tools. */
|
|
4
|
+
|
|
5
|
+
declare const knowledgeRegistrySchema: z.ZodObject<{
|
|
6
|
+
defaults: z.ZodOptional<z.ZodObject<{
|
|
7
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
8
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
9
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
10
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
11
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
12
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
13
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
14
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
15
|
+
}, z.ZodTypeAny, "passthrough">>>;
|
|
16
|
+
knowledge_bases: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
17
|
+
datasetId: z.ZodString;
|
|
18
|
+
retrieve_config: z.ZodOptional<z.ZodObject<{
|
|
19
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
20
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
21
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
22
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
23
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
24
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
25
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
26
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
27
|
+
}, z.ZodTypeAny, "passthrough">>>;
|
|
28
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
29
|
+
datasetId: z.ZodString;
|
|
30
|
+
retrieve_config: z.ZodOptional<z.ZodObject<{
|
|
31
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
32
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
33
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
34
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
35
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
36
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
37
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
38
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
39
|
+
}, z.ZodTypeAny, "passthrough">>>;
|
|
40
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
41
|
+
datasetId: z.ZodString;
|
|
42
|
+
retrieve_config: z.ZodOptional<z.ZodObject<{
|
|
43
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
44
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
45
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
46
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
47
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
48
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
49
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
50
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
51
|
+
}, z.ZodTypeAny, "passthrough">>>;
|
|
52
|
+
}, z.ZodTypeAny, "passthrough">>>>;
|
|
53
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
54
|
+
defaults: z.ZodOptional<z.ZodObject<{
|
|
55
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
56
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
57
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
58
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
59
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
60
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
61
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
62
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
63
|
+
}, z.ZodTypeAny, "passthrough">>>;
|
|
64
|
+
knowledge_bases: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
65
|
+
datasetId: z.ZodString;
|
|
66
|
+
retrieve_config: z.ZodOptional<z.ZodObject<{
|
|
67
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
68
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
69
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
70
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
71
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
72
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
73
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
74
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
75
|
+
}, z.ZodTypeAny, "passthrough">>>;
|
|
76
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
77
|
+
datasetId: z.ZodString;
|
|
78
|
+
retrieve_config: z.ZodOptional<z.ZodObject<{
|
|
79
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
80
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
81
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
82
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
83
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
84
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
85
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
86
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
87
|
+
}, z.ZodTypeAny, "passthrough">>>;
|
|
88
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
89
|
+
datasetId: z.ZodString;
|
|
90
|
+
retrieve_config: z.ZodOptional<z.ZodObject<{
|
|
91
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
92
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
93
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
94
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
95
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
96
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
97
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
98
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
99
|
+
}, z.ZodTypeAny, "passthrough">>>;
|
|
100
|
+
}, z.ZodTypeAny, "passthrough">>>>;
|
|
101
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
102
|
+
defaults: z.ZodOptional<z.ZodObject<{
|
|
103
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
104
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
105
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
106
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
107
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
108
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
109
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
110
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
111
|
+
}, z.ZodTypeAny, "passthrough">>>;
|
|
112
|
+
knowledge_bases: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
113
|
+
datasetId: z.ZodString;
|
|
114
|
+
retrieve_config: z.ZodOptional<z.ZodObject<{
|
|
115
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
116
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
117
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
118
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
119
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
120
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
121
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
122
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
123
|
+
}, z.ZodTypeAny, "passthrough">>>;
|
|
124
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
125
|
+
datasetId: z.ZodString;
|
|
126
|
+
retrieve_config: z.ZodOptional<z.ZodObject<{
|
|
127
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
128
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
129
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
130
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
131
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
132
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
133
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
134
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
135
|
+
}, z.ZodTypeAny, "passthrough">>>;
|
|
136
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
137
|
+
datasetId: z.ZodString;
|
|
138
|
+
retrieve_config: z.ZodOptional<z.ZodObject<{
|
|
139
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
140
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
141
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
142
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
143
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
144
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
145
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
146
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
147
|
+
}, z.ZodTypeAny, "passthrough">>>;
|
|
148
|
+
}, z.ZodTypeAny, "passthrough">>>>;
|
|
149
|
+
}, z.ZodTypeAny, "passthrough">>;
|
|
150
|
+
|
|
151
|
+
export { knowledgeRegistrySchema };
|
package/dist/config.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a}from"./chunk-U2YZGGOR.js";export{a as knowledgeRegistrySchema};
|
package/dist/platform/index.d.ts
CHANGED
|
@@ -1,7 +1,13 @@
|
|
|
1
|
+
import * as express from 'express';
|
|
1
2
|
import { Express, RequestHandler } from 'express';
|
|
3
|
+
export { A as AppError, a as AppKind, b as AppManifest, c as AppServerModule, C as CreateAppOptions, P as PageEntry, R as RequestContext, S as ServerRegistry, d as StartOptions, e as createApp, f as createPageRuntime, s as serverContext, g as start } from '../app-DjQy7ben.js';
|
|
2
4
|
import { IncomingMessage, Server } from 'node:http';
|
|
3
5
|
import { Duplex } from 'node:stream';
|
|
4
6
|
import { Plugin } from 'vite';
|
|
7
|
+
import '@tbox.cn/app-contracts';
|
|
8
|
+
import 'node:async_hooks';
|
|
9
|
+
import '@tbox.cn/app-sdk-core';
|
|
10
|
+
import 'zod';
|
|
5
11
|
|
|
6
12
|
declare const RUNTIME_PATH = "/__vs_inspector__.js";
|
|
7
13
|
declare const SCRIPT_TAG = "<script src=\"/__vs_inspector__.js\" defer></script>";
|
|
@@ -9,6 +15,44 @@ declare function injectScript(html: string): string;
|
|
|
9
15
|
declare function isReady(): boolean;
|
|
10
16
|
declare function installInspector(app: Express): void;
|
|
11
17
|
|
|
18
|
+
/** 平台文档(精确 path → dist 内文档文件;如卡片预览页) */
|
|
19
|
+
interface PlatformDocument {
|
|
20
|
+
/** 精确 URL 路径(如 /_tbox/card-preview) */
|
|
21
|
+
path: string;
|
|
22
|
+
/** dist 内文档文件相对路径(如 _tbox/card-preview.html) */
|
|
23
|
+
document: string;
|
|
24
|
+
/** 生成 entry 名(= mpa 插件 ExtraDocumentSpec.inputName;dev 面服务 .tbox-gen/<inputName>.ts) */
|
|
25
|
+
inputName: string;
|
|
26
|
+
}
|
|
27
|
+
interface StrictStaticOptions {
|
|
28
|
+
/** client dist 根(文档与资产的 fs 真源) */
|
|
29
|
+
distDir: string;
|
|
30
|
+
/** 平台文档表(精确 path 服务;文件不在场 = 能力关 = 404) */
|
|
31
|
+
platformPages?: readonly PlatformDocument[];
|
|
32
|
+
/** 文档响应装饰(static 面 = SSE client 注入;生产缺省裸服务) */
|
|
33
|
+
decorateHtml?: (html: string) => string | Promise<string>;
|
|
34
|
+
/** 构建进行中(watch BUNDLE_START→END 窗口;miss 时 503 而非 404) */
|
|
35
|
+
isBuildActive?: () => boolean;
|
|
36
|
+
/** 503 等待页 body 覆盖(dev runtime 传 SSE 感知版;生产缺省 meta-refresh 版) */
|
|
37
|
+
html503?: string;
|
|
38
|
+
logger?: DevRuntimeLogger;
|
|
39
|
+
}
|
|
40
|
+
declare const STRICT_HTML_404 = "<!doctype html><html lang=\"zh-CN\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>404</title></head><body style=\"font-family:system-ui;padding:40px;color:#333\"><h1>404</h1><p>\u9875\u9762\u4E0D\u5B58\u5728</p></body></html>";
|
|
41
|
+
declare const STRICT_HTML_503 = "<!doctype html><html lang=\"zh-CN\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>503</title><meta http-equiv=\"refresh\" content=\"3\"></head><body style=\"font-family:system-ui;padding:40px;color:#333\"><h1>503</h1><p>\u6784\u5EFA\u8FDB\u884C\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u5237\u65B0</p></body></html>";
|
|
42
|
+
/** 严格面统一 HTML 响应(no-store + Content-Length;HEAD 无 body;dev-runtime strict 树共用) */
|
|
43
|
+
declare function sendStrictHtml(req: express.Request, res: express.Response, statusCode: number, body: string, extra?: Record<string, string>): void;
|
|
44
|
+
/** 路径最后一段是否含扩展名(资源判定;空段=无扩展名;dev-runtime strict 树共用) */
|
|
45
|
+
declare function lastSegmentHasExtension(pathname: string): boolean;
|
|
46
|
+
/** 根目录内安全绝对路径(防穿越;越界返回 null;dev-runtime publicDir 解析共用) */
|
|
47
|
+
declare function safeJoin(distDir: string, pathname: string): string | null;
|
|
48
|
+
declare function isFile(target: string): boolean;
|
|
49
|
+
declare function isDirectory(target: string): boolean;
|
|
50
|
+
/**
|
|
51
|
+
* 严格静态处理器:assets + 平台文档 + 文档管线 + 301 + 404/503。
|
|
52
|
+
* 非 GET/HEAD → 404(对齐既有 static 面行为)。
|
|
53
|
+
*/
|
|
54
|
+
declare function createStrictStaticHandler(options: StrictStaticOptions): RequestHandler;
|
|
55
|
+
|
|
12
56
|
/** dev 凭据 env 名(box 注入;本地缺省 = classic 模式) */
|
|
13
57
|
declare const DEV_TOKEN_ENV = "TBOX_DEV_TOKEN";
|
|
14
58
|
/** query/cookie 凭据参数名(box 302 盖戳与应用侧判定共用常量) */
|
|
@@ -58,6 +102,34 @@ interface DevRuntimeOptions {
|
|
|
58
102
|
fsAllowNarrowed?: boolean;
|
|
59
103
|
/** SSE 心跳间隔 ms(默认 15000;smoke 经 TBOX_DEV_SSE_KEEPALIVE_MS 覆盖) */
|
|
60
104
|
sseKeepaliveMs?: number;
|
|
105
|
+
/**
|
|
106
|
+
* 严格文档模式(v3.2 MPA):routes.json 在场时由模板传入(G8 模式开关)。
|
|
107
|
+
* dev/classic 面 = 平台文档表 + routes 集合 + entry src 替换 + public 目录索引;
|
|
108
|
+
* static 面 = dist 文件存在性真源(平台文档表 + 统一文档管线 + 404/503)。
|
|
109
|
+
* 缺席 = legacy SPA fallback(与历史行为等价,存量消费者零变化)。
|
|
110
|
+
*/
|
|
111
|
+
pagePolicy?: {
|
|
112
|
+
/**
|
|
113
|
+
* v1 manifest 模式:页面集合来自 app-build 生成的 .tbox-gen/manifest.json,
|
|
114
|
+
* dev 面按 manifest.page.entry 校验并交给 Vite 注入入口;static 面仍读 dist。
|
|
115
|
+
*/
|
|
116
|
+
mode?: "routes" | "manifest";
|
|
117
|
+
/** manifest.json 绝对路径(mode=manifest 时使用) */
|
|
118
|
+
manifest?: string;
|
|
119
|
+
/** routes.json 绝对路径(mode=routes 缺省;存在性由本层探测;文件损坏 = 503 fail-visible) */
|
|
120
|
+
routesModule?: string;
|
|
121
|
+
/** 根 entry script src(默认 /src/main.tsx;per-template 契约) */
|
|
122
|
+
clientEntrySrc?: string;
|
|
123
|
+
/** 生成 entry 目录名(默认 .tbox-gen;与构建插件同参) */
|
|
124
|
+
genDirName?: string;
|
|
125
|
+
/** public 目录(dev 面目录索引解析;默认 <clientRoot>/public) */
|
|
126
|
+
publicDir?: string;
|
|
127
|
+
/**
|
|
128
|
+
* 平台文档表(static/生产面 = dist 文档精确服务;dev/classic 面 = `.tbox-gen/<inputName>.ts`
|
|
129
|
+
* entry 替换 shell;能力关 = 文件不在 = 404。`inputName` 须与插件 `ExtraDocumentSpec.inputName` 一致)
|
|
130
|
+
*/
|
|
131
|
+
platformPages?: readonly PlatformDocument[];
|
|
132
|
+
};
|
|
61
133
|
}
|
|
62
134
|
interface DevRuntime {
|
|
63
135
|
/** pathless 挂载:app.use(runtime.gate())——SSE 端点 + 面裁决 */
|
|
@@ -68,6 +140,8 @@ interface DevRuntime {
|
|
|
68
140
|
handleUpgrade: (req: IncomingMessage, socket: Duplex, head: Buffer) => boolean;
|
|
69
141
|
/** watch 构建完成回调(模板 BUNDLE_END 时调用 → SSE 广播 → static 面刷新) */
|
|
70
142
|
notifyBuildEnd: () => void;
|
|
143
|
+
/** watch 构建开始回调(BUNDLE_START → 构建窗口标记 → static 面 miss 时 503 而非 404) */
|
|
144
|
+
notifyBuildStart: () => void;
|
|
71
145
|
}
|
|
72
146
|
/** env 三态解析:缺席/空串 → classic;形状合规 → protected+token;在场不合规 → protected 无 token(fail-closed) */
|
|
73
147
|
declare function resolveDevTokenFromEnv(env: NodeJS.ProcessEnv): DevTokenResolution;
|
|
@@ -77,8 +151,152 @@ interface PreviewErrorReporterOptions {
|
|
|
77
151
|
/** Minimum 5000ms. Only new, connected, error-free documents clear old snapshots. */
|
|
78
152
|
observationMs?: number;
|
|
79
153
|
enabled?: boolean;
|
|
154
|
+
/** Explicit third-party script URLs to ignore (absolute HTTP(S); query/hash are ignored). */
|
|
155
|
+
ignoredScriptUrls?: readonly string[];
|
|
80
156
|
}
|
|
81
157
|
/** Dev-only browser exception transport over the application's existing Vite HMR socket. */
|
|
82
158
|
declare function previewErrorReporter(options?: PreviewErrorReporterOptions): Plugin;
|
|
83
159
|
|
|
84
|
-
|
|
160
|
+
/**
|
|
161
|
+
* ============================================================================
|
|
162
|
+
* 🔒 平台基础设施 — MPA 路由清单契约(route-validator)
|
|
163
|
+
* ============================================================================
|
|
164
|
+
* routes.json 是应用页面清单的唯一真源(v3.2 方案):在场 ⇔ 端到端文档模式。
|
|
165
|
+
* 本模块是纯函数校验器(零 fs / 零 vite 依赖,双端可复用):
|
|
166
|
+
* - E 规则族:结构 / id / 纯静态段 / 保留命名空间 / 数量上限 / 解码归一;
|
|
167
|
+
* - 派生工具:文档输出路径(`/orders` → `orders/index.html`)、
|
|
168
|
+
* 请求路径单次解码归一(`/%75sers` ≡ `/users`,双编码保持字面区分)。
|
|
169
|
+
*
|
|
170
|
+
* fs 侧冲突族(public 树 × 生成文档 × 平台文档)在 mpa-build-plugin 内
|
|
171
|
+
* (构建期有 fs 访问);本文件只负责数据自身的一致性。
|
|
172
|
+
* ============================================================================
|
|
173
|
+
*/
|
|
174
|
+
/** 保留首段(服务端真实挂载前缀 + Vite 默认 chunk 目录;模板可追加) */
|
|
175
|
+
declare const RESERVED_ROUTE_SEGMENTS: readonly string[];
|
|
176
|
+
/** routes.json 单条目的宽松输入形状(校验前的未知字段面) */
|
|
177
|
+
interface RouteEntryInput {
|
|
178
|
+
id?: unknown;
|
|
179
|
+
path?: unknown;
|
|
180
|
+
title?: unknown;
|
|
181
|
+
meta?: unknown;
|
|
182
|
+
page?: unknown;
|
|
183
|
+
}
|
|
184
|
+
/** 校验通过后的规范条目 */
|
|
185
|
+
interface NormalizedRouteEntry {
|
|
186
|
+
id: string;
|
|
187
|
+
path: string;
|
|
188
|
+
title?: string;
|
|
189
|
+
meta?: Record<string, string>;
|
|
190
|
+
page?: string;
|
|
191
|
+
}
|
|
192
|
+
interface ValidateRoutesOptions {
|
|
193
|
+
/** 追加的保留首段(与内置集合并) */
|
|
194
|
+
reservedSegments?: readonly string[];
|
|
195
|
+
/** 路由总数上限(默认 100) */
|
|
196
|
+
maxRoutes?: number;
|
|
197
|
+
}
|
|
198
|
+
interface RouteValidationResult {
|
|
199
|
+
ok: boolean;
|
|
200
|
+
errors: string[];
|
|
201
|
+
warnings: string[];
|
|
202
|
+
/** 仅 ok 时非空 */
|
|
203
|
+
entries: NormalizedRouteEntry[];
|
|
204
|
+
}
|
|
205
|
+
/** 请求路径单次解码(失败返回 null——调用方按未命中处理;双编码保持字面) */
|
|
206
|
+
declare function decodeRoutePathname(pathname: string): string | null;
|
|
207
|
+
/** 冲突检测键:NFC 归一 + 小写(大小写不敏感文件系统上的同键判定) */
|
|
208
|
+
declare function canonicalRouteKey(pathname: string): string;
|
|
209
|
+
/**
|
|
210
|
+
* 静态路由 → 物理文档输出路径(目录索引形态)。
|
|
211
|
+
* `/` 返回 undefined(根入口恒用应用根 index.html,不生成文档)。
|
|
212
|
+
*/
|
|
213
|
+
declare function routeDocumentOutput(pathname: string): string | undefined;
|
|
214
|
+
/**
|
|
215
|
+
* 校验 routes.json 数据(E 规则族)。
|
|
216
|
+
* 错误 = 阻断(构建/启动 fail-fast);警告 = 提示(不阻断)。
|
|
217
|
+
*/
|
|
218
|
+
declare function validateRoutes(data: unknown, options?: ValidateRoutesOptions): RouteValidationResult;
|
|
219
|
+
/** 读取 + 解析 + 校验 routes.json(供 dev-runtime / 插件共用;fs 侧由调用方) */
|
|
220
|
+
declare function parseRoutesJson(text: string): RouteValidationResult;
|
|
221
|
+
|
|
222
|
+
/** 平台文档规格(能力开时由模板传入;如卡片预览页) */
|
|
223
|
+
interface ExtraDocumentSpec {
|
|
224
|
+
/** 生成 input 名(filesystem-safe:^[a-z0-9][a-z0-9-]*$) */
|
|
225
|
+
inputName: string;
|
|
226
|
+
/** dist 内文档输出相对路径(如 _tbox/card-preview.html) */
|
|
227
|
+
document: string;
|
|
228
|
+
/** mountPage 动态 import 的页面模块 id(如 @/platform/card-preview-page) */
|
|
229
|
+
entry: string;
|
|
230
|
+
/** 文档标题(缺省沿用根骨架) */
|
|
231
|
+
title?: string;
|
|
232
|
+
}
|
|
233
|
+
interface TboxMpaPluginOptions {
|
|
234
|
+
/** routes.json 绝对路径(默认 <root>/src/business/routes.json) */
|
|
235
|
+
routesModule?: string;
|
|
236
|
+
/** public 目录(默认 <root>/public;传 false 跳过冲突族检查) */
|
|
237
|
+
publicDir?: string | false;
|
|
238
|
+
/** 生成目录名(默认 .tbox-gen;位于 clientRoot 下、src 之外——typecheck/eslint 零扫描) */
|
|
239
|
+
genDirName?: string;
|
|
240
|
+
/** 应用根 entry script src(默认 /src/main.tsx;HTML 骨架替换目标,per-template 契约) */
|
|
241
|
+
clientEntrySrc?: string;
|
|
242
|
+
/** mountPage helper 模块 id(默认 @/platform/mount-page,per-template 契约) */
|
|
243
|
+
mountHelperId?: string;
|
|
244
|
+
/** 平台文档(能力开时传入;如卡片预览) */
|
|
245
|
+
extraDocuments?: readonly ExtraDocumentSpec[];
|
|
246
|
+
}
|
|
247
|
+
declare const DEFAULT_CLIENT_ENTRY_SRC = "/src/main.tsx";
|
|
248
|
+
declare const DEFAULT_GEN_DIR_NAME = ".tbox-gen";
|
|
249
|
+
declare const DEFAULT_MOUNT_HELPER_ID = "@/platform/mount-page";
|
|
250
|
+
/** 递归列出 public 目录内全部文件(posix 相对路径;含 dotfiles) */
|
|
251
|
+
declare function listPublicFiles(publicDir: string): string[];
|
|
252
|
+
/**
|
|
253
|
+
* 冲突族校验(E11):public 树 × 生成文档 × 平台文档。
|
|
254
|
+
* 理由 = Vite 构建序 emptyDir → bundle 写出 → copyDir(publicDir)——public 同名文件
|
|
255
|
+
* 会静默覆盖生成文档;canonical key(NFC + 小写)拦截大小写不敏感 fs 上的跨面 clobber;
|
|
256
|
+
* 祖先段被 public 文件占据 = fs 无法同时存在文件与目录。
|
|
257
|
+
*/
|
|
258
|
+
declare function validateRouteConflicts(entries: readonly NormalizedRouteEntry[], publicFiles: readonly string[], extraDocuments: readonly ExtraDocumentSpec[]): string[];
|
|
259
|
+
/** 生成 entry 模块源码(dev/build 双态共用的页面装配唯一实现) */
|
|
260
|
+
declare function buildEntryModule(entry: {
|
|
261
|
+
id: string;
|
|
262
|
+
page?: string;
|
|
263
|
+
}, extraImport: string | undefined, mountHelperId: string): string;
|
|
264
|
+
interface DocumentHtmlOptions {
|
|
265
|
+
/** 根 entry script src(替换目标) */
|
|
266
|
+
clientEntrySrc: string;
|
|
267
|
+
/** 本文档 entry src(root-absolute,指向 gen 目录) */
|
|
268
|
+
entrySrc: string;
|
|
269
|
+
title?: string;
|
|
270
|
+
meta?: Record<string, string>;
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* 根 entry script src 替换(dev 面经 dev-runtime 消费同一实现——I1 不变式的服务端半边)。
|
|
274
|
+
* 未匹配返回 null(调用方按契约破坏处理:build throw / dev warn 降级)。
|
|
275
|
+
*/
|
|
276
|
+
declare function replaceClientEntrySrc(html: string, clientEntrySrc: string, entrySrc: string): string | null;
|
|
277
|
+
/** 生成文档 HTML:复制根骨架 + entry src 替换 + title/meta 注入 */
|
|
278
|
+
declare function buildDocumentHtml(rootHtml: string, options: DocumentHtmlOptions): string;
|
|
279
|
+
interface GenerateFilesOptions {
|
|
280
|
+
root: string;
|
|
281
|
+
entries: readonly NormalizedRouteEntry[];
|
|
282
|
+
extraDocuments: readonly ExtraDocumentSpec[];
|
|
283
|
+
genDirName: string;
|
|
284
|
+
mountHelperId: string;
|
|
285
|
+
clientEntrySrc: string;
|
|
286
|
+
/** build = 生成 .html 文档骨架 + inputs;serve = 仅 .ts entry */
|
|
287
|
+
withHtml: boolean;
|
|
288
|
+
}
|
|
289
|
+
interface GeneratedFiles {
|
|
290
|
+
/** rollup input 键 → gen html 绝对路径(build 用;serve 为空) */
|
|
291
|
+
inputs: Record<string, string>;
|
|
292
|
+
/** gen html 文件名(root 相对 posix)→ 最终文档输出路径(generateBundle 重命名用) */
|
|
293
|
+
renames: Record<string, string>;
|
|
294
|
+
}
|
|
295
|
+
/** 清空重写 gen 目录并生成全部文件(幂等:先 rm 再全量写,结果确定) */
|
|
296
|
+
declare function generateRouteFiles(options: GenerateFilesOptions): GeneratedFiles;
|
|
297
|
+
declare function resolveStagingDir(distDir: string): string;
|
|
298
|
+
/** 原子发布:staging 就绪校验 → dist → backup → staging → dist → 清 backup;失败回滚 */
|
|
299
|
+
declare function publishStagedDist(stagingDir: string, distDir: string): void;
|
|
300
|
+
declare function tboxMpaPlugin(options?: TboxMpaPluginOptions): Plugin;
|
|
301
|
+
|
|
302
|
+
export { DEFAULT_CLIENT_ENTRY_SRC, DEFAULT_GEN_DIR_NAME, DEFAULT_MOUNT_HELPER_ID, DEV_SSE_PATH, DEV_TOKEN_ENV, DEV_TOKEN_NAME, type DevFace, type DevRuntime, type DevRuntimeLogger, type DevRuntimeOptions, type DevTokenResolution, type DocumentHtmlOptions, type ExtraDocumentSpec, type GenerateFilesOptions, type GeneratedFiles, type NormalizedRouteEntry, type PlatformDocument, type PreviewErrorReporterOptions, RESERVED_ROUTE_SEGMENTS, RUNTIME_PATH, type RouteEntryInput, type RouteValidationResult, SCRIPT_TAG, STRICT_HTML_404, STRICT_HTML_503, type StrictStaticOptions, type TboxMpaPluginOptions, type ValidateRoutesOptions, buildDocumentHtml, buildEntryModule, canonicalRouteKey, createStrictStaticHandler, createTboxDevRuntime, decodeRoutePathname, generateRouteFiles, injectScript, installInspector, isDirectory, isFile, isReady, lastSegmentHasExtension, listPublicFiles, parseRoutesJson, previewErrorReporter, publishStagedDist, replaceClientEntrySrc, resolveDevTokenFromEnv, resolveStagingDir, routeDocumentOutput, safeJoin, sendStrictHtml, tboxMpaPlugin, validateRouteConflicts, validateRoutes };
|