@tbox.cn/app-agent-sdk-server 1.0.0-alpha.1 → 1.0.0-alpha.7
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/dist/app-primitives-BU-_eI-T.d.ts +207 -0
- package/dist/chunk-IZOFAJNX.js +1 -0
- package/dist/chunk-NJDW5VOH.js +1 -0
- package/dist/config.d.ts +42 -0
- package/dist/config.js +1 -1
- package/dist/server/index.d.ts +133 -132
- package/dist/server/index.js +41 -41
- package/dist/testing/index.d.ts +64 -0
- package/dist/testing/index.js +1 -0
- package/package.json +10 -6
- package/dist/chunk-2M4P57DG.js +0 -1
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { CardMeta, RequestContext } from '@tbox.cn/app-contracts';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
4
|
+
import { Tool } from '@mastra/core/tools';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 工具出卡协议单源(v2)。
|
|
8
|
+
*
|
|
9
|
+
* 作者契约:工具 execute 返回 `{ ...顶层答话事实, cards: [{cardType, data, note?}] }`——
|
|
10
|
+
* `cards` 字段名为平台保留字(非出卡工具禁用此字段名承载其他语义)。
|
|
11
|
+
*
|
|
12
|
+
* capture 后模型可见面(模型上下文 / TOOL_CALL_RESULT 事件 / preTool reminder /
|
|
13
|
+
* inputs.preTools 落库)四面统一为 stripped 形态:
|
|
14
|
+
* `{ ...顶层, cards: [{id:"cN", cardType, note}] }`
|
|
15
|
+
* 同一工具同一产出,模型 tool-result 与 preTool reminder 两路所见 payload 同构——
|
|
16
|
+
* 由单点包装(wrapToolsForCardCapture)构造保证:两路执行同一 wrapped execute。
|
|
17
|
+
*
|
|
18
|
+
* 两层 id:
|
|
19
|
+
* - ref(c1..cN):线程内单调的 occurrence 引用(descriptor.id 即 ref,按设计出现在上述四个
|
|
20
|
+
* 模型可见面);不进出卡 payload(CUSTOM tbox:card)与历史快照;
|
|
21
|
+
* - 实例 id(card_<ts>_<rand>):emit 时生成(CardEmitter 现状),出卡实例身份与历史快照主键。
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/** 出参 cards 字段名(平台保留字) */
|
|
25
|
+
declare const TOOL_CARDS_FIELD = "cards";
|
|
26
|
+
/** 出卡工具 description 标注关键词(平台段预告句共享——跨文件钉死断言防漂移) */
|
|
27
|
+
declare const CARD_EMISSION_HINT_KEYWORD = "\u53EF\u5C55\u793A\u5361\u7247";
|
|
28
|
+
/** 出卡工具 description 标注句基础形(withCardEmissionHint 单源) */
|
|
29
|
+
declare const CARD_EMISSION_HINT_BASE = "\u547D\u4E2D\u6570\u636E\u65F6\u7ED3\u679C\u9644\u53EF\u5C55\u793A\u5361\u7247\uFF08cards\uFF09\u3002";
|
|
30
|
+
/** 出卡工具 description 标注句动作卡后缀(卡上承载操作入口时追加) */
|
|
31
|
+
declare const CARD_EMISSION_HINT_ACTIONS = "\u64CD\u4F5C\u5165\u53E3\u5728\u5361\u7247\u4E0A\u3002";
|
|
32
|
+
/** descriptor 形状恒定(capture 后模型可见形态;供 outputSchema 组合,可选导出) */
|
|
33
|
+
declare const TOOL_CARD_DESCRIPTOR_SCHEMA: z.ZodObject<{
|
|
34
|
+
id: z.ZodString;
|
|
35
|
+
cardType: z.ZodString;
|
|
36
|
+
note: z.ZodString;
|
|
37
|
+
}, "strip", z.ZodTypeAny, {
|
|
38
|
+
id: string;
|
|
39
|
+
cardType: string;
|
|
40
|
+
note: string;
|
|
41
|
+
}, {
|
|
42
|
+
id: string;
|
|
43
|
+
cardType: string;
|
|
44
|
+
note: string;
|
|
45
|
+
}>;
|
|
46
|
+
/** 作者侧:工具 execute 出参中的卡条目 */
|
|
47
|
+
interface ToolCardSpec {
|
|
48
|
+
cardType: string;
|
|
49
|
+
data: Record<string, unknown>;
|
|
50
|
+
note?: string;
|
|
51
|
+
}
|
|
52
|
+
/** 模型侧:stripped 出参中的卡描述符 */
|
|
53
|
+
interface ToolCardDescriptor {
|
|
54
|
+
id: string;
|
|
55
|
+
cardType: string;
|
|
56
|
+
note: string;
|
|
57
|
+
}
|
|
58
|
+
/** 池条目(不可变:每个合法 cards occurrence 都是独立候选) */
|
|
59
|
+
interface PoolEntry {
|
|
60
|
+
ref: string;
|
|
61
|
+
cardType: string;
|
|
62
|
+
data: Record<string, unknown>;
|
|
63
|
+
note: string;
|
|
64
|
+
}
|
|
65
|
+
interface CardPoolOptions {
|
|
66
|
+
/** ChatEngine 使用线程级单调 ref;缺省时池内从 c1 开始。 */
|
|
67
|
+
allocateRef?: () => string;
|
|
68
|
+
}
|
|
69
|
+
interface CardPool {
|
|
70
|
+
/** 校验 + 注入;每个合法 occurrence 都创建独立 ref,校验失败 → null */
|
|
71
|
+
add(spec: ToolCardSpec, registry: Record<string, CardMeta>): ToolCardDescriptor | null;
|
|
72
|
+
/** ref 精确查找(大小写不敏感) */
|
|
73
|
+
byRef(ref: string): PoolEntry | undefined;
|
|
74
|
+
entries(): readonly PoolEntry[];
|
|
75
|
+
size(): number;
|
|
76
|
+
}
|
|
77
|
+
/** 候选池工厂(每 run 一个;每个 occurrence 独立 ref) */
|
|
78
|
+
declare function createCardPool(options?: CardPoolOptions): CardPool;
|
|
79
|
+
/**
|
|
80
|
+
* capture:校验 + 池注入 + 剥离(单函数三合一)。
|
|
81
|
+
* - raw 非对象或无 cards 字段 → 原样返回(no-op,不出卡工具零开销);
|
|
82
|
+
* - cards 非数组 → warn + 原样返回;
|
|
83
|
+
* - 逐条校验(非对象 / cardType 非 string / 未注册 / dataSchema 失败 → skip + warn);
|
|
84
|
+
* - 有效 ≥1 → `{ ...raw, cards: descriptors }`;全无效 → 浅拷贝删除 cards 键;
|
|
85
|
+
* - 条目数 > CARDS_WARN_LIMIT → warn(不截断)。
|
|
86
|
+
*/
|
|
87
|
+
declare function captureToolCards(raw: unknown, pool: CardPool, registry: Record<string, CardMeta>): unknown;
|
|
88
|
+
/** run 级卡片池 ALS 上下文(chat/submitForm run 开始进入,finally 退出) */
|
|
89
|
+
declare const toolCardScope: AsyncLocalStorage<{
|
|
90
|
+
pool: CardPool;
|
|
91
|
+
}>;
|
|
92
|
+
/**
|
|
93
|
+
* 单点包装:浅拷贝每个 tool 仅替换 execute(禁变异原实例);无 execute 的原样保留。
|
|
94
|
+
* wrapped execute:双参 + 接收者透传(mastra 契约),产出经 captureToolCards
|
|
95
|
+
* (ALS 无池 → 引擎外直调原样返回)。模型路径(Agent.tools)与 preTool 路径
|
|
96
|
+
* (engine 按 id 替换执行体)共用同一 wrapped execute → 两路同构由构造保证。
|
|
97
|
+
*/
|
|
98
|
+
declare function wrapToolsForCardCapture(tools: Record<string, Tool>, registry: Record<string, CardMeta>): Record<string, Tool>;
|
|
99
|
+
|
|
100
|
+
/** 工具 execute 第二参的结构型投影(只声明读取器消费的形状) */
|
|
101
|
+
interface ToolExecContextLike {
|
|
102
|
+
requestContext?: {
|
|
103
|
+
get(key: string): unknown;
|
|
104
|
+
};
|
|
105
|
+
toolCallId?: string;
|
|
106
|
+
agent?: {
|
|
107
|
+
toolCallId?: string;
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
interface ToolRunMetadata {
|
|
111
|
+
runId: string;
|
|
112
|
+
threadKey: string;
|
|
113
|
+
toolCallId: string;
|
|
114
|
+
}
|
|
115
|
+
/** Read trusted producer metadata from the execute context, never from model arguments. */
|
|
116
|
+
declare function getToolRunMetadata(execCtx: ToolExecContextLike | undefined): Readonly<ToolRunMetadata> | undefined;
|
|
117
|
+
/**
|
|
118
|
+
* 从工具 execute 第二参读取运行上下文(散键组装)。
|
|
119
|
+
* 返回 undefined 当 requestContext 缺失或 identity 键缺失(引擎外直调/匿名无身份)。
|
|
120
|
+
*/
|
|
121
|
+
declare function getToolRequestContext(execCtx: ToolExecContextLike | undefined): Readonly<RequestContext> | undefined;
|
|
122
|
+
/**
|
|
123
|
+
* 严格变体:运行上下文缺失时抛 AUTH_FORBIDDEN(fail-visible——显式正确性优于静默降级)。
|
|
124
|
+
* @param toolId 诊断信息(缺失文案指明哪个工具、怎么修)
|
|
125
|
+
*/
|
|
126
|
+
/**
|
|
127
|
+
* 取工具运行上下文(身份/凭证/attributes);缺失即抛错。
|
|
128
|
+
*
|
|
129
|
+
* @agentApi state
|
|
130
|
+
*/
|
|
131
|
+
declare function requireToolRequestContext(execCtx: ToolExecContextLike | undefined, toolId?: string): Readonly<RequestContext>;
|
|
132
|
+
/**
|
|
133
|
+
* 测试/直调助手:由 plain RequestContext 构造工具 execute 第二参形态。
|
|
134
|
+
* 散键写入与引擎 buildRunRequestContext 同构(往返由 context-concurrency.test C2 锁定)。
|
|
135
|
+
*/
|
|
136
|
+
declare function createToolExecContext(reqCtx: RequestContext): ToolExecContextLike;
|
|
137
|
+
|
|
138
|
+
/** 声明一张卡:恒等返回,负责类型绑定与样例自检。 */
|
|
139
|
+
/**
|
|
140
|
+
* 声明一张卡片的服务端元数据;类型上绑定 schema,dev 下先校验样例。
|
|
141
|
+
*
|
|
142
|
+
* @agentApi card
|
|
143
|
+
*/
|
|
144
|
+
declare function defineCardMeta<S extends z.ZodTypeAny>(meta: CardMeta<S>): CardMeta<S>;
|
|
145
|
+
/** 类型化出卡条目:`data` 必须能过 meta 的 schema,`cardType` 取自 meta。 */
|
|
146
|
+
/**
|
|
147
|
+
* 组装一条出卡条目;data 必须能过 meta 的 schema。
|
|
148
|
+
*
|
|
149
|
+
* @agentApi tool-emits-card
|
|
150
|
+
*/
|
|
151
|
+
declare function cardOf<S extends z.ZodTypeAny>(meta: CardMeta<S>, data: z.input<S>, note: string): ToolCardSpec;
|
|
152
|
+
/**
|
|
153
|
+
* 按用户隔离的进程内状态。
|
|
154
|
+
*
|
|
155
|
+
* 适用边界(必须知道):
|
|
156
|
+
* - 默认进程内、重启即丢;`persist: 'file'` 落盘到应用根 `.tbox/state/<name>.json`;
|
|
157
|
+
* - 多实例各存一份;跨重启或跨实例的强一致状态做成模块用 `ctx.state`;
|
|
158
|
+
* - 无 TTL:需要过期时自己在数据里记时间戳并清理;
|
|
159
|
+
* - 幂等判断放在写副作用之前,工具可能被重试。
|
|
160
|
+
*/
|
|
161
|
+
interface UserState<T> {
|
|
162
|
+
get(userId: string): T;
|
|
163
|
+
update(userId: string, mutate: (draft: T) => T | void): T;
|
|
164
|
+
/** 测试与运维辅助:清空全部或指定用户 */
|
|
165
|
+
reset(userId?: string): void;
|
|
166
|
+
}
|
|
167
|
+
interface CreateUserStateOptions {
|
|
168
|
+
/**
|
|
169
|
+
* `'file'`:状态落盘到应用根 `<appRoot>/.tbox/state/<stateName>.json`,进程重启后恢复。
|
|
170
|
+
* 应用根 = 向上找到 `.tbox/app.json` 的目录;找不到时回落到 `process.cwd()`。
|
|
171
|
+
*/
|
|
172
|
+
persist?: 'file';
|
|
173
|
+
/** 落盘文件名(缺省 `user-state`);同名的两个 state 会互相同步,务必区分 */
|
|
174
|
+
stateName?: string;
|
|
175
|
+
}
|
|
176
|
+
/** 已注册的用户状态:构造即登记,探针与场景按登记发现,不依赖文件路径约定。 */
|
|
177
|
+
interface RegisteredUserState {
|
|
178
|
+
name: string;
|
|
179
|
+
state: UserState<unknown>;
|
|
180
|
+
}
|
|
181
|
+
/** 取全部已注册的用户状态(按创建顺序)。 */
|
|
182
|
+
declare function userStates(): RegisteredUserState[];
|
|
183
|
+
/**
|
|
184
|
+
* 按用户隔离的进程内状态;`persist: 'file'` 时落盘到应用根。
|
|
185
|
+
*
|
|
186
|
+
* 构造即登记到进程内注册表(`userStates()`),探针、场景与测试按登记发现。
|
|
187
|
+
*
|
|
188
|
+
* @agentApi state
|
|
189
|
+
*/
|
|
190
|
+
declare function createUserState<T>(init: (userId: string) => T, options?: CreateUserStateOptions): UserState<T>;
|
|
191
|
+
/**
|
|
192
|
+
* 取可信用户身份。缺失时抛带 toolId 的错误——`requireToolRequestContext` 的错误消息
|
|
193
|
+
* 已经指到正确写法,这里只补一层语义命名。
|
|
194
|
+
*/
|
|
195
|
+
/**
|
|
196
|
+
* 取可信用户身份(userId/source)。
|
|
197
|
+
*
|
|
198
|
+
* @agentApi state
|
|
199
|
+
*/
|
|
200
|
+
declare function toolUser(execCtx: ToolExecContextLike, toolId?: string): {
|
|
201
|
+
userId: string;
|
|
202
|
+
source: string;
|
|
203
|
+
displayName?: string;
|
|
204
|
+
avatar?: string;
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
export { type CardPool as C, type PoolEntry as P, type RegisteredUserState as R, TOOL_CARDS_FIELD as T, type UserState as U, CARD_EMISSION_HINT_ACTIONS as a, CARD_EMISSION_HINT_BASE as b, CARD_EMISSION_HINT_KEYWORD as c, type CardPoolOptions as d, type CreateUserStateOptions as e, TOOL_CARD_DESCRIPTOR_SCHEMA as f, type ToolCardDescriptor as g, type ToolCardSpec as h, type ToolExecContextLike as i, type ToolRunMetadata as j, captureToolCards as k, cardOf as l, createCardPool as m, createToolExecContext as n, createUserState as o, defineCardMeta as p, getToolRequestContext as q, getToolRunMetadata as r, requireToolRequestContext as s, toolCardScope as t, userStates as u, toolUser as v, wrapToolsForCardCapture as w };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{AsyncLocalStorage as _}from"async_hooks";import{createServerLogger as L,recordCall as $}from"@tbox.cn/app-sdk-server";var j=L("EARLY-TOOL"),q=Symbol("tbox.earlyExecution"),T=new _;function ie(e){let t=new Map;return{submit(r,n,o,s){if(t.has(r))return;let a=e.tools[n];if(!a||typeof a.execute!="function"||a[q]!==!0){let l=a?typeof a.execute!="function"?"no-execute":"unmarked":"unknown-tool";e.journal.emit("tool_preexec",{toolCallId:r,toolName:n,outcome:"skip",trigger:s,reason:l});return}e.journal.emit("tool_preexec",{toolCallId:r,toolName:n,outcome:"fired",trigger:s});let i=Date.now(),d={requestContext:e.requestContext,toolCallId:r,...e.signal?{abortSignal:e.signal}:{}},u=$("tool",n,()=>a.execute.call(a,o,d)).then(l=>{if(l===void 0)throw new Error(`工具 ${n} 执行完成但未返回结果(undefined)——请检查工具实现是否缺少 return`);return l});u.then(void 0,()=>{}),t.set(r,{promise:u,toolName:n,startedAt:i,trigger:s})},invalidate(r,n){let o=t.get(r);o&&(t.delete(r),e.journal.emit("tool_preexec",{toolCallId:r,toolName:o.toolName,outcome:"invalidated",trigger:o.trigger,reason:n}))},take(r){let n=t.get(r);if(n)return t.delete(r),e.journal.emit("tool_preexec",{toolCallId:r,toolName:n.toolName,outcome:"hit",trigger:n.trigger,durMs:Date.now()-n.startedAt},n.startedAt),n.promise}}}function D(e){let t=new Map,r=(o,s)=>{let a=t.get(o);if(!(!a||a.firedAt!==void 0)&&a.args.trim()!=="")try{let i=JSON.parse(a.args);if(i===null||typeof i!="object"||Array.isArray(i))return;a.firedAt=a.args,e.submit(o,a.toolName,i,s)}catch{}},n=o=>{for(let s of t.keys())r(s,o)};return new TransformStream({transform(o,s){s.enqueue(o);try{let a=T.getStore();if(!a||a!==e)return;switch(o.type){case"tool-input-start":{n("next-start"),t.set(o.id,{toolName:o.toolName,args:""});break}case"tool-input-end":{r(o.id,"input-end");break}case"tool-input-delta":{let i=t.get(o.id);if(!i)break;i.args+=o.delta,i.firedAt!==void 0&&e.invalidate(o.id,"delta-after-fire");break}case"tool-call":{let i=t.get(o.toolCallId);i?.firedAt!==void 0&&i.firedAt!==o.input&&e.invalidate(o.toolCallId,"final-mismatch");break}default:break}}catch(a){j.warn("early-execution 流分析异常(透传不受影响):",a?.message??String(a))}},flush(){let o=T.getStore();!o||o!==e||n("flush")}})}function ce(e){let t=Object.create(e);return t.doStream=(async r=>{let n=await e.doStream(r),o=T.getStore(),s=n,a=s?.stream;return!o||!a||typeof a.pipeThrough!="function"?n:{...s,stream:a.pipeThrough(D(o))}}),t}function E(e){if(!(!e||typeof e!="string"))return T.getStore()?.take(e)}import{AsyncLocalStorage as U}from"async_hooks";import{z as R}from"zod";import{createServerLogger as O,recordCall as K}from"@tbox.cn/app-sdk-server";var z=O("TOOL"),g=O("TOOLCARDS"),S="cards",F="可展示卡片",ge=`命中数据时结果附${F}(cards)。`,ye="操作入口在卡片上。",xe=R.object({id:R.string(),cardType:R.string(),note:R.string()}),C=120,A=8;function J(e){try{return JSON.parse(JSON.stringify(e??null))}catch{return}}function Y(e,t,r){e===void 0&&g.warn(`note 缺失(${r})——按 note 契约补内容摘要(主体+关键事实,≤${C} 字符,不复述顶层 facts)`);let n=e??t?.displayName??r;return n.length>C?(g.warn(`note 超长截断(${n.length} → ${C}): ${r}`),n.slice(0,C)):n}function me(e={}){let t=new Map,r=[],n=0,o=e.allocateRef??(()=>`c${++n}`);return{add(s,a){let i=a[s.cardType];if(!i)return g.warn(`跳过未知卡片类型: ${s.cardType}`),null;let d=J(s.data);if(d==null||typeof d!="object"||Array.isArray(d))return g.warn(`跳过 ${s.cardType}: data 非 JSON 对象`),null;let c=i.dataSchema.safeParse(d);if(!c.success)return g.warn(`跳过 ${s.cardType}: dataSchema 校验失败(${c.error.message})`),null;let u=c.data,l=o(),f=l.toLowerCase();if(t.has(f))throw new Error(`card ref allocator returned duplicate ref: ${l}`);let p={ref:l,cardType:s.cardType,data:u,note:Y(s.note,i,s.cardType)};return t.set(f,p),r.push(p),{id:p.ref,cardType:p.cardType,note:p.note}},byRef(s){return t.get(s.toLowerCase())},entries(){return r},size(){return r.length}}}function b(e,t,r){if(e===null||typeof e!="object"||Array.isArray(e))return e;let n=e;if(!(S in n))return e;let o=n[S];if(!Array.isArray(o))return g.warn("工具出参 cards 非数组,忽略出卡"),e;o.length>A&&g.warn(`单工具出卡 ${o.length} 条(> ${A}),观测确认是否预期`);let s=[];for(let[a,i]of o.entries()){if(i===null||typeof i!="object"||Array.isArray(i)){g.warn(`跳过 cards[${a}]:非对象`);continue}let d=i,{cardType:c,data:u,note:l}=d;if(typeof c!="string"||c.length===0){g.warn(`跳过 cards[${a}]:cardType 非法`);continue}if(u===null||typeof u!="object"||Array.isArray(u)){g.warn(`跳过 cards[${a}](${c}):data 非对象`);continue}let f=t.add({cardType:c,data:u,...typeof l=="string"?{note:l}:{}},r);f&&s.push(f)}if(s.length===0){let a={};for(let[i,d]of Object.entries(n))i!==S&&(a[i]=d);return a}return{...n,[S]:s}}var k=new U,M=Symbol("tbox.toolCardCapture");function Te(e,t){let r={};for(let[n,o]of Object.entries(e)){let s=o;if(typeof s?.execute!="function"||s[M]){r[n]=o;continue}let a=o,i=s.execute,d=Object.create(Object.getPrototypeOf(o),Object.getOwnPropertyDescriptors(o)),c=String(o.id??"unknown");d.execute=async function(u,l){let f=l,p=f?.toolCallId??f?.agent?.toolCallId,w=E(p);if(w){let y=await w,m=k.getStore()?.pool;return m?b(y,m,t):y}return K("tool",c,async()=>{let y=await i.call(a,u,l);if(y===void 0)throw new Error(`工具 ${c} 执行完成但未返回结果(undefined)——请检查工具实现是否缺少 return`);let m=k.getStore()?.pool;return m?b(y,m,t):y},{logger:z,detail:{args:u}})},d[M]=!0,r[n]=d}return r}import{RequestContext as H}from"@mastra/core/request-context";import{AuthError as X}from"@tbox.cn/app-sdk-server";var I="tbox.engine.run",P=Symbol.for("tbox.engine.runMetadata");function we(e,t){e.set(I,Object.freeze({...t,[P]:!0}))}function Ee(e){let t=e?.requestContext?.get(I),r=e?.agent?.toolCallId??e?.toolCallId;if(!(!t||t[P]!==!0||typeof t.runId!="string"||typeof t.threadKey!="string"||typeof r!="string"||!r))return Object.freeze({runId:t.runId,threadKey:t.threadKey,toolCallId:r})}function W(e){let t=e?.requestContext;if(!t)return;let r=t.get("identity");if(!r)return;let n=t.get("conversationId"),o=t.get("credentials"),s=t.get("attributes");return{identity:r,...typeof n=="string"?{conversationId:n}:{},...o?{credentials:o}:{},...s?{attributes:s}:{}}}function h(e,t){let r=W(e);if(!r)throw X.forbidden(`工具运行上下文缺失${t?`(tool=${t})`:""}:请从 execute 第二参读取(const reqCtx = requireToolRequestContext(execCtx, toolId))`);return r}function Ae(e){let t=new H;return t.set("identity",e.identity),e.conversationId&&t.set("conversationId",e.conversationId),e.credentials&&t.set("credentials",e.credentials),e.attributes&&t.set("attributes",e.attributes),{requestContext:t}}import{existsSync as N,mkdirSync as B,readFileSync as Z,writeFileSync as G}from"fs";import x from"path";import{createServerLogger as V}from"@tbox.cn/app-sdk-server";var Q=V("APP");function Pe(e){if(process.env.NODE_ENV!=="production")for(let[t,r]of[["sampleData",e.sampleData],...(e.samples??[]).map((n,o)=>[`samples[${o}]`,n.data])]){let n=e.dataSchema.safeParse(r);n.success||Q.warn(`卡片样例与 dataSchema 不匹配:${e.cardType} ${t}`,n.error.message)}return e}function he(e,t,r){return{cardType:e.cardType,data:t,note:r}}var v=new Map,ee=0;function Ne(){return[...v.entries()].map(([e,t])=>({name:e,state:t}))}function ve(e,t={}){let r=new Map,n=process.env.TBOX_STATE_MEMORY==="1",o=t.persist==="file"&&!n?re(t.stateName??"user-state"):void 0;if(o)for(let[c,u]of ne(o))r.set(c,u);let s=()=>{o&&oe(o,r)},a=c=>{let u=r.get(c);return u===void 0&&(u=e(c),r.set(c,u)),u},i=t.stateName;i||(i=`state-${++ee}`);let d={get:c=>structuredClone(a(c)),update(c,u){let l=structuredClone(a(c)),f=u(l),p=f===void 0?l:f;return r.set(c,p),s(),structuredClone(p)},reset(c){c===void 0?r.clear():r.delete(c),s()}};return v.set(i,d),d}function _e(e,t){let n=h(e,t).identity;return{userId:n.userId,source:n.source,...n.displayName!==void 0?{displayName:n.displayName}:{},...n.avatar!==void 0?{avatar:n.avatar}:{}}}function te(e=process.cwd()){let t=x.resolve(e);for(;;){if(N(x.join(t,".tbox","app.json")))return t;let r=x.dirname(t);if(r===t)return x.resolve(e);t=r}}function re(e){return x.join(te(),".tbox","state",`${e}.json`)}function ne(e){let t=new Map;try{if(!N(e))return t;let r=JSON.parse(Z(e,"utf8"));for(let[n,o]of Object.entries(r))t.set(n,o)}catch{}return t}function oe(e,t){try{B(x.dirname(e),{recursive:!0}),G(e,JSON.stringify(Object.fromEntries(t),null,2))}catch{}}export{q as a,T as b,ie as c,ce as d,S as e,F as f,ge as g,ye as h,xe as i,me as j,b as k,k as l,Te as m,we as n,Ee as o,W as p,h as q,Ae as r,Pe as s,he as t,Ne as u,ve as v,_e as w};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{z as e}from"zod";var n=e.object({enableImageUpload:e.boolean().default(!0),enableVideoUpload:e.boolean().default(!0),enableTTS:e.boolean().default(!0),enableVoiceInput:e.boolean().default(!0),defaultInputMode:e.enum(["TEXT","VOICE"]).default("TEXT"),quickCommands:e.array(e.object({label:e.string().describe("展示文案"),query:e.string().describe("点击后发送给智能体的用户消息")}).passthrough()).default([]),identity:e.object({name:e.string().describe("展示名,如品牌或智能体名"),tagline:e.string().optional().describe("一句话说明,展示在名称下方")}).optional(),welcome:e.object({title:e.string(),subtitle:e.string().optional()}).optional(),retryOnError:e.boolean().default(!0)}),r=e.strictObject({instructions:e.array(e.string()).min(1).describe("必填;逐行拼接的业务提示词,拼接后不得全为空白;不替代平台规则"),memoryInstructions:e.array(e.string()).min(1).optional().describe("装配长期记忆时追加的业务提示词;在场时拼接后不得全为空白")}),t=e.union([e.boolean(),e.literal("auto"),e.record(e.string(),e.unknown())]),o=e.union([e.boolean(),e.literal("auto")]),l=e.object({modelName:e.string().min(1).optional().describe("模型路由名;缺席时使用 APP_AI_MODEL_NAME"),thinking:t.optional().describe("true/false 控制思考;auto 不注入;对象作为网关兼容请求字段,禁止凭证"),parallelToolCalls:o.optional().describe("true/false 控制并行工具调用;auto 使用网关默认"),contentTagHygiene:e.object({off:e.array(e.enum(["think","tool-call-text"])).optional(),extraTags:e.array(e.object({name:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,31}$/),family:e.enum(["think","tool-call-text"])})).max(16).optional()}).optional()});export{n as a,r as b,t as c,o as d,l as e};
|
package/dist/config.d.ts
CHANGED
|
@@ -18,6 +18,30 @@ declare const chatConfigSchema: z.ZodObject<{
|
|
|
18
18
|
label: z.ZodString;
|
|
19
19
|
query: z.ZodString;
|
|
20
20
|
}, z.ZodTypeAny, "passthrough">>, "many">>;
|
|
21
|
+
/** 智能体身份:页头品牌区与空会话欢迎区共用(缺省回退 scope 回显的 mallName) */
|
|
22
|
+
identity: z.ZodOptional<z.ZodObject<{
|
|
23
|
+
name: z.ZodString;
|
|
24
|
+
tagline: z.ZodOptional<z.ZodString>;
|
|
25
|
+
}, "strip", z.ZodTypeAny, {
|
|
26
|
+
name: string;
|
|
27
|
+
tagline?: string | undefined;
|
|
28
|
+
}, {
|
|
29
|
+
name: string;
|
|
30
|
+
tagline?: string | undefined;
|
|
31
|
+
}>>;
|
|
32
|
+
/** 空会话欢迎区(无 home 槽时渲染) */
|
|
33
|
+
welcome: z.ZodOptional<z.ZodObject<{
|
|
34
|
+
title: z.ZodString;
|
|
35
|
+
subtitle: z.ZodOptional<z.ZodString>;
|
|
36
|
+
}, "strip", z.ZodTypeAny, {
|
|
37
|
+
title: string;
|
|
38
|
+
subtitle?: string | undefined;
|
|
39
|
+
}, {
|
|
40
|
+
title: string;
|
|
41
|
+
subtitle?: string | undefined;
|
|
42
|
+
}>>;
|
|
43
|
+
/** 出错消息是否提供「重试」入口(重发上一条用户消息),缺省 true */
|
|
44
|
+
retryOnError: z.ZodDefault<z.ZodBoolean>;
|
|
21
45
|
}, "strip", z.ZodTypeAny, {
|
|
22
46
|
enableImageUpload: boolean;
|
|
23
47
|
enableVideoUpload: boolean;
|
|
@@ -28,6 +52,15 @@ declare const chatConfigSchema: z.ZodObject<{
|
|
|
28
52
|
label: z.ZodString;
|
|
29
53
|
query: z.ZodString;
|
|
30
54
|
}, z.ZodTypeAny, "passthrough">[];
|
|
55
|
+
retryOnError: boolean;
|
|
56
|
+
identity?: {
|
|
57
|
+
name: string;
|
|
58
|
+
tagline?: string | undefined;
|
|
59
|
+
} | undefined;
|
|
60
|
+
welcome?: {
|
|
61
|
+
title: string;
|
|
62
|
+
subtitle?: string | undefined;
|
|
63
|
+
} | undefined;
|
|
31
64
|
}, {
|
|
32
65
|
enableImageUpload?: boolean | undefined;
|
|
33
66
|
enableVideoUpload?: boolean | undefined;
|
|
@@ -38,6 +71,15 @@ declare const chatConfigSchema: z.ZodObject<{
|
|
|
38
71
|
label: z.ZodString;
|
|
39
72
|
query: z.ZodString;
|
|
40
73
|
}, z.ZodTypeAny, "passthrough">[] | undefined;
|
|
74
|
+
identity?: {
|
|
75
|
+
name: string;
|
|
76
|
+
tagline?: string | undefined;
|
|
77
|
+
} | undefined;
|
|
78
|
+
welcome?: {
|
|
79
|
+
title: string;
|
|
80
|
+
subtitle?: string | undefined;
|
|
81
|
+
} | undefined;
|
|
82
|
+
retryOnError?: boolean | undefined;
|
|
41
83
|
}>;
|
|
42
84
|
declare const agentPromptFileSchema: z.ZodObject<{
|
|
43
85
|
instructions: z.ZodArray<z.ZodString, "many">;
|
package/dist/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d,e}from"./chunk-
|
|
1
|
+
import{a,b,c,d,e}from"./chunk-NJDW5VOH.js";export{b as agentPromptFileSchema,a as chatConfigSchema,e as llmProviderFileSchema,d as parallelSchema,c as thinkingSchema};
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
|
-
import { HandlerRegistry, ServerContext, HandlerResult, LocalSkill, PreToolDef, RegistryTool, PreToolHistoryTurn, PreToolRouting, WsAuthenticator, ScopeSessionRegistry, AuthRuntime, TboxTtsClient } from '@tbox.cn/app-sdk-server';
|
|
1
|
+
import { HandlerRegistry, ServerContext, HandlerResult, LocalSkill, PreToolDef, RegistryTool, PreToolHistoryTurn, PreToolRouting, WsAuthenticator, ScopeSessionRegistry, RegisteredModuleAction, AuthRuntime, TboxTtsClient } from '@tbox.cn/app-sdk-server';
|
|
2
2
|
export * from '@tbox.cn/app-sdk-server';
|
|
3
3
|
export { LocalSkill, TtsVoiceConfig } from '@tbox.cn/app-sdk-server';
|
|
4
4
|
export { InferModuleCards } from '@tbox.cn/app-sdk-core';
|
|
5
5
|
import * as _tbox_cn_app_contracts from '@tbox.cn/app-contracts';
|
|
6
|
-
import { SendMessageMediaItem, SkillRecord, ServerEvent, PreToolRecord, MemoryKind, MemoryRecord, MemoryStore, MemoryStoreCapabilities, MemoryErrorCode, RequestContext as RequestContext$1, CardMeta, CardSnapshot, Identity, ExternalCredentials, HelloAckChatConfig, TboxCardPayload } from '@tbox.cn/app-contracts';
|
|
6
|
+
import { SendMessageMediaItem, SkillRecord, ServerEvent, PreToolRecord, MemoryKind, MemoryRecord, MemoryStore, MemoryStoreCapabilities, MemoryErrorCode, RequestContext as RequestContext$1, CardMeta, CardSnapshot, Identity, ExternalCredentials, HelloAckChatConfig, CardActionResult, TboxCardPayload } from '@tbox.cn/app-contracts';
|
|
7
7
|
import * as _mastra_core_tools from '@mastra/core/tools';
|
|
8
|
-
import { Tool } from '@mastra/core/tools';
|
|
8
|
+
import { Tool, createTool } from '@mastra/core/tools';
|
|
9
9
|
export { Tool, createTool } from '@mastra/core/tools';
|
|
10
10
|
import { ObservabilityExporter, TracingEvent, SpanType } from '@mastra/core/observability';
|
|
11
11
|
import { ModelMessage, LanguageModel } from 'ai';
|
|
12
|
-
import {
|
|
12
|
+
import { P as PoolEntry, C as CardPool } from '../app-primitives-BU-_eI-T.js';
|
|
13
|
+
export { a as CARD_EMISSION_HINT_ACTIONS, b as CARD_EMISSION_HINT_BASE, c as CARD_EMISSION_HINT_KEYWORD, d as CardPoolOptions, e as CreateUserStateOptions, R as RegisteredUserState, T as TOOL_CARDS_FIELD, f as TOOL_CARD_DESCRIPTOR_SCHEMA, g as ToolCardDescriptor, h as ToolCardSpec, i as ToolExecContextLike, j as ToolRunMetadata, U as UserState, k as captureToolCards, l as cardOf, m as createCardPool, n as createToolExecContext, o as createUserState, p as defineCardMeta, q as getToolRequestContext, r as getToolRunMetadata, s as requireToolRequestContext, t as toolCardScope, v as toolUser, u as userStates, w as wrapToolsForCardCapture } from '../app-primitives-BU-_eI-T.js';
|
|
13
14
|
import { ZodTypeAny, z } from 'zod';
|
|
14
15
|
import { SkillInput } from '@mastra/core/skills';
|
|
15
16
|
import { RequestContext } from '@mastra/core/request-context';
|
|
@@ -21,6 +22,7 @@ import * as node_modules__tbox_cn_app_sdk_server_src_upstream from 'node_modules
|
|
|
21
22
|
import { Router, Express } from 'express';
|
|
22
23
|
import * as _tbox_cn_agent_plugin from '@tbox.cn/agent-plugin';
|
|
23
24
|
import { ConfiguredPluginToolReference, PluginRunResult } from '@tbox.cn/agent-plugin';
|
|
25
|
+
import 'node:async_hooks';
|
|
24
26
|
|
|
25
27
|
declare class TboxTraceExporter implements ObservabilityExporter {
|
|
26
28
|
name: string;
|
|
@@ -305,6 +307,11 @@ declare const EARLY_EXECUTION_MARKER: unique symbol;
|
|
|
305
307
|
* (单例铁律,002 §10.1)。@mastra/core 由 app-sdk 唯一持有(dependencies),
|
|
306
308
|
* 经本文件 re-export,模块只需依赖 @tbox.cn/app-sdk。
|
|
307
309
|
*/
|
|
310
|
+
/**
|
|
311
|
+
* 定义工具(mastra createTool 的公开入口)。
|
|
312
|
+
*
|
|
313
|
+
* @agentApi tool
|
|
314
|
+
*/
|
|
308
315
|
|
|
309
316
|
/**
|
|
310
317
|
* 任意具体化实例的 Mastra Tool(泛型擦除别名,agent 侧专用)。
|
|
@@ -377,6 +384,11 @@ declare function omitInternal<T extends object>(tools: Record<string, T>): Recor
|
|
|
377
384
|
* 自行描述出卡机制(标签语法/cardType 目录——机制归平台段单源)。
|
|
378
385
|
* 浅拷贝(getOwnPropertyDescriptors)不改原实例;id/execute/inputSchema 引用保持。
|
|
379
386
|
*/
|
|
387
|
+
/**
|
|
388
|
+
* 给出卡工具的 description 追加「命中数据时结果附可展示卡片(cards)。」。
|
|
389
|
+
*
|
|
390
|
+
* @agentApi tool-emits-card
|
|
391
|
+
*/
|
|
380
392
|
declare function withCardEmissionHint<T extends {
|
|
381
393
|
description?: string;
|
|
382
394
|
}>(tool: T, opts?: {
|
|
@@ -1466,100 +1478,6 @@ declare function createStreamTagEngine(specs: readonly TagSpec[], opts?: {
|
|
|
1466
1478
|
track?: TagTrack;
|
|
1467
1479
|
}): StreamTagEngine;
|
|
1468
1480
|
|
|
1469
|
-
/**
|
|
1470
|
-
* 工具出卡协议单源(v2)。
|
|
1471
|
-
*
|
|
1472
|
-
* 作者契约:工具 execute 返回 `{ ...顶层答话事实, cards: [{cardType, data, note?}] }`——
|
|
1473
|
-
* `cards` 字段名为平台保留字(非出卡工具禁用此字段名承载其他语义)。
|
|
1474
|
-
*
|
|
1475
|
-
* capture 后模型可见面(模型上下文 / TOOL_CALL_RESULT 事件 / preTool reminder /
|
|
1476
|
-
* inputs.preTools 落库)四面统一为 stripped 形态:
|
|
1477
|
-
* `{ ...顶层, cards: [{id:"cN", cardType, note}] }`
|
|
1478
|
-
* 同一工具同一产出,模型 tool-result 与 preTool reminder 两路所见 payload 同构——
|
|
1479
|
-
* 由单点包装(wrapToolsForCardCapture)构造保证:两路执行同一 wrapped execute。
|
|
1480
|
-
*
|
|
1481
|
-
* 两层 id:
|
|
1482
|
-
* - ref(c1..cN):线程内单调的 occurrence 引用(descriptor.id 即 ref,按设计出现在上述四个
|
|
1483
|
-
* 模型可见面);不进出卡 payload(CUSTOM tbox:card)与历史快照;
|
|
1484
|
-
* - 实例 id(card_<ts>_<rand>):emit 时生成(CardEmitter 现状),出卡实例身份与历史快照主键。
|
|
1485
|
-
*/
|
|
1486
|
-
|
|
1487
|
-
/** 出参 cards 字段名(平台保留字) */
|
|
1488
|
-
declare const TOOL_CARDS_FIELD = "cards";
|
|
1489
|
-
/** 出卡工具 description 标注关键词(平台段预告句共享——跨文件钉死断言防漂移) */
|
|
1490
|
-
declare const CARD_EMISSION_HINT_KEYWORD = "\u53EF\u5C55\u793A\u5361\u7247";
|
|
1491
|
-
/** 出卡工具 description 标注句基础形(withCardEmissionHint 单源) */
|
|
1492
|
-
declare const CARD_EMISSION_HINT_BASE = "\u547D\u4E2D\u6570\u636E\u65F6\u7ED3\u679C\u9644\u53EF\u5C55\u793A\u5361\u7247\uFF08cards\uFF09\u3002";
|
|
1493
|
-
/** 出卡工具 description 标注句动作卡后缀(卡上承载操作入口时追加) */
|
|
1494
|
-
declare const CARD_EMISSION_HINT_ACTIONS = "\u64CD\u4F5C\u5165\u53E3\u5728\u5361\u7247\u4E0A\u3002";
|
|
1495
|
-
/** descriptor 形状恒定(capture 后模型可见形态;供 outputSchema 组合,可选导出) */
|
|
1496
|
-
declare const TOOL_CARD_DESCRIPTOR_SCHEMA: z.ZodObject<{
|
|
1497
|
-
id: z.ZodString;
|
|
1498
|
-
cardType: z.ZodString;
|
|
1499
|
-
note: z.ZodString;
|
|
1500
|
-
}, "strip", z.ZodTypeAny, {
|
|
1501
|
-
id: string;
|
|
1502
|
-
cardType: string;
|
|
1503
|
-
note: string;
|
|
1504
|
-
}, {
|
|
1505
|
-
id: string;
|
|
1506
|
-
cardType: string;
|
|
1507
|
-
note: string;
|
|
1508
|
-
}>;
|
|
1509
|
-
/** 作者侧:工具 execute 出参中的卡条目 */
|
|
1510
|
-
interface ToolCardSpec {
|
|
1511
|
-
cardType: string;
|
|
1512
|
-
data: Record<string, unknown>;
|
|
1513
|
-
note?: string;
|
|
1514
|
-
}
|
|
1515
|
-
/** 模型侧:stripped 出参中的卡描述符 */
|
|
1516
|
-
interface ToolCardDescriptor {
|
|
1517
|
-
id: string;
|
|
1518
|
-
cardType: string;
|
|
1519
|
-
note: string;
|
|
1520
|
-
}
|
|
1521
|
-
/** 池条目(不可变:每个合法 cards occurrence 都是独立候选) */
|
|
1522
|
-
interface PoolEntry {
|
|
1523
|
-
ref: string;
|
|
1524
|
-
cardType: string;
|
|
1525
|
-
data: Record<string, unknown>;
|
|
1526
|
-
note: string;
|
|
1527
|
-
}
|
|
1528
|
-
interface CardPoolOptions {
|
|
1529
|
-
/** ChatEngine 使用线程级单调 ref;缺省时池内从 c1 开始。 */
|
|
1530
|
-
allocateRef?: () => string;
|
|
1531
|
-
}
|
|
1532
|
-
interface CardPool {
|
|
1533
|
-
/** 校验 + 注入;每个合法 occurrence 都创建独立 ref,校验失败 → null */
|
|
1534
|
-
add(spec: ToolCardSpec, registry: Record<string, CardMeta>): ToolCardDescriptor | null;
|
|
1535
|
-
/** ref 精确查找(大小写不敏感) */
|
|
1536
|
-
byRef(ref: string): PoolEntry | undefined;
|
|
1537
|
-
entries(): readonly PoolEntry[];
|
|
1538
|
-
size(): number;
|
|
1539
|
-
}
|
|
1540
|
-
/** 候选池工厂(每 run 一个;每个 occurrence 独立 ref) */
|
|
1541
|
-
declare function createCardPool(options?: CardPoolOptions): CardPool;
|
|
1542
|
-
/**
|
|
1543
|
-
* capture:校验 + 池注入 + 剥离(单函数三合一)。
|
|
1544
|
-
* - raw 非对象或无 cards 字段 → 原样返回(no-op,不出卡工具零开销);
|
|
1545
|
-
* - cards 非数组 → warn + 原样返回;
|
|
1546
|
-
* - 逐条校验(非对象 / cardType 非 string / 未注册 / dataSchema 失败 → skip + warn);
|
|
1547
|
-
* - 有效 ≥1 → `{ ...raw, cards: descriptors }`;全无效 → 浅拷贝删除 cards 键;
|
|
1548
|
-
* - 条目数 > CARDS_WARN_LIMIT → warn(不截断)。
|
|
1549
|
-
*/
|
|
1550
|
-
declare function captureToolCards(raw: unknown, pool: CardPool, registry: Record<string, CardMeta>): unknown;
|
|
1551
|
-
/** run 级卡片池 ALS 上下文(chat/submitForm run 开始进入,finally 退出) */
|
|
1552
|
-
declare const toolCardScope: AsyncLocalStorage<{
|
|
1553
|
-
pool: CardPool;
|
|
1554
|
-
}>;
|
|
1555
|
-
/**
|
|
1556
|
-
* 单点包装:浅拷贝每个 tool 仅替换 execute(禁变异原实例);无 execute 的原样保留。
|
|
1557
|
-
* wrapped execute:双参 + 接收者透传(mastra 契约),产出经 captureToolCards
|
|
1558
|
-
* (ALS 无池 → 引擎外直调原样返回)。模型路径(Agent.tools)与 preTool 路径
|
|
1559
|
-
* (engine 按 id 替换执行体)共用同一 wrapped execute → 两路同构由构造保证。
|
|
1560
|
-
*/
|
|
1561
|
-
declare function wrapToolsForCardCapture(tools: Record<string, Tool>, registry: Record<string, CardMeta>): Record<string, Tool>;
|
|
1562
|
-
|
|
1563
1481
|
/**
|
|
1564
1482
|
* 出卡决策协议(候选池 → 模型标签决策 → 多卡下发)。
|
|
1565
1483
|
*
|
|
@@ -1968,6 +1886,122 @@ interface CreateCardToolOptions<TSchema extends ZodTypeAny> {
|
|
|
1968
1886
|
}
|
|
1969
1887
|
declare function createCardTool<TSchema extends ZodTypeAny>(opts: CreateCardToolOptions<TSchema>): _mastra_core_tools.Tool<TSchema extends _mastra_core_schema.PublicSchema<any> ? _mastra_core_schema.InferPublicSchema<TSchema> : unknown, unknown, unknown, unknown, _mastra_core_tools.ToolExecutionContext<unknown, unknown, unknown>, string, unknown>;
|
|
1970
1888
|
|
|
1889
|
+
/**
|
|
1890
|
+
* 应用级卡片动作:把「点了按钮之后确定要发生什么」从模型手里拿走。
|
|
1891
|
+
*
|
|
1892
|
+
* 与工具的分工:
|
|
1893
|
+
* - 工具走模型:需要理解、需要上下文、需要多步判断;
|
|
1894
|
+
* - 动作走确定性通道:入参确定、结果确定、用户点击即执行,不经模型。
|
|
1895
|
+
*
|
|
1896
|
+
* 声明落在 `apps/server/src/actions/*.action.ts`,由 app-build 扫描进 registry,
|
|
1897
|
+
* 运行时注册到 `ctx.cardActions`;卡片上的 `invoke(actionId)` 触发,令牌由平台签发。
|
|
1898
|
+
*/
|
|
1899
|
+
|
|
1900
|
+
interface ActionDefinition<TSchema extends z.ZodTypeAny> {
|
|
1901
|
+
/** 动作 id,全局唯一;卡片按钮用同一个字符串调用 */
|
|
1902
|
+
id: string;
|
|
1903
|
+
/** 动作绑定哪张卡片(单卡或数组;出卡时按 cardType 匹配并签发令牌) */
|
|
1904
|
+
cardType: string | string[];
|
|
1905
|
+
/** 入参 schema(无参写 z.object({})) */
|
|
1906
|
+
inputSchema: TSchema;
|
|
1907
|
+
/** 按钮文案(缺省用 id) */
|
|
1908
|
+
label?: string;
|
|
1909
|
+
/** 一次性:执行成功后令牌作废,防重复提交 */
|
|
1910
|
+
singleUse?: boolean;
|
|
1911
|
+
/** 按钮样式 */
|
|
1912
|
+
style?: 'primary' | 'secondary' | 'link';
|
|
1913
|
+
/** 执行体:返回值可直接原地更新卡片(`update`)或出结果卡(`card`) */
|
|
1914
|
+
execute: (input: z.infer<TSchema>, ctx: {
|
|
1915
|
+
userId: string;
|
|
1916
|
+
cardId?: string;
|
|
1917
|
+
cardType?: string;
|
|
1918
|
+
}) => Promise<CardActionResult>;
|
|
1919
|
+
}
|
|
1920
|
+
/** 扫描与注册共用的形态:`moduleId` 固定 `app`,把声明映射成平台动作记录。 */
|
|
1921
|
+
interface DefinedAction<TSchema extends z.ZodTypeAny> extends RegisteredModuleAction {
|
|
1922
|
+
definition: ActionDefinition<TSchema>;
|
|
1923
|
+
}
|
|
1924
|
+
/**
|
|
1925
|
+
* 声明一个应用级动作。
|
|
1926
|
+
*
|
|
1927
|
+
* 迁移说明:`execute` 收到的 `ctx.userId` 来自授权令牌绑定的会话身份,
|
|
1928
|
+
* 不要在这里信任客户端传上来的 userId。
|
|
1929
|
+
*/
|
|
1930
|
+
/**
|
|
1931
|
+
* 声明一个应用级卡片动作(点击直接执行,不过模型)。
|
|
1932
|
+
*
|
|
1933
|
+
* @agentApi card-action
|
|
1934
|
+
*/
|
|
1935
|
+
declare function defineAction<TSchema extends z.ZodTypeAny>(definition: ActionDefinition<TSchema>): DefinedAction<TSchema>;
|
|
1936
|
+
|
|
1937
|
+
/**
|
|
1938
|
+
* 应用级工具的作者入口:与 `defineAction` 对称。
|
|
1939
|
+
*
|
|
1940
|
+
* 收口三件容易写错的事:
|
|
1941
|
+
* - 身份:`execute(input, { userId, identity })` 由平台注入,不需要自己拼 `requireToolRequestContext`;
|
|
1942
|
+
* - 出卡提示:声明了 `cards` 就自动补「命中数据时结果附可展示卡片(cards)」,不再手写 `Object.assign`;
|
|
1943
|
+
* - 声明式卡片清单:`cards` 同时是能力图的来源(哪个工具会出哪张卡)。
|
|
1944
|
+
*
|
|
1945
|
+
* 需要 suspend / resume 等高级能力时仍用 `createTool`。
|
|
1946
|
+
*/
|
|
1947
|
+
|
|
1948
|
+
interface DefineToolIdentity {
|
|
1949
|
+
userId: string;
|
|
1950
|
+
source: string;
|
|
1951
|
+
displayName?: string;
|
|
1952
|
+
avatar?: string;
|
|
1953
|
+
}
|
|
1954
|
+
interface DefineToolContext {
|
|
1955
|
+
userId: string;
|
|
1956
|
+
identity: DefineToolIdentity;
|
|
1957
|
+
}
|
|
1958
|
+
interface DefineToolOptions<TSchema extends z.ZodTypeAny, TOutput> {
|
|
1959
|
+
id: string;
|
|
1960
|
+
description: string;
|
|
1961
|
+
inputSchema: TSchema;
|
|
1962
|
+
/** 会出的卡片:自动补出卡提示,并作为能力图的声明来源 */
|
|
1963
|
+
cards?: readonly CardMeta<z.ZodTypeAny>[];
|
|
1964
|
+
execute: (input: z.infer<TSchema>, ctx: DefineToolContext) => Promise<TOutput>;
|
|
1965
|
+
}
|
|
1966
|
+
/**
|
|
1967
|
+
* 声明一个应用级工具。
|
|
1968
|
+
*
|
|
1969
|
+
* @agentApi tool
|
|
1970
|
+
*/
|
|
1971
|
+
declare function defineTool<TSchema extends z.ZodTypeAny, TOutput>(options: DefineToolOptions<TSchema, TOutput>): ReturnType<typeof createTool>;
|
|
1972
|
+
|
|
1973
|
+
/**
|
|
1974
|
+
* 动作结果构造器:把「本卡状态变了用 update、另一类结果用 card、只要一句提示用 notice」
|
|
1975
|
+
* 从配方里的判据变成签名——`update` / `card` 都要求对应的卡片声明,提示文字不混进两者。
|
|
1976
|
+
*
|
|
1977
|
+
* 直接返回对象字面量仍然合法,由门禁的同源校验兜底。
|
|
1978
|
+
*/
|
|
1979
|
+
|
|
1980
|
+
/** 原地刷新被点击的卡片;`data` 必须能过该卡的 schema。
|
|
1981
|
+
*
|
|
1982
|
+
* @agentApi card-action
|
|
1983
|
+
*/
|
|
1984
|
+
declare function updateResult<S extends z.ZodTypeAny>(_meta: CardMeta<S>, data: z.input<S>): CardActionResult;
|
|
1985
|
+
/** 出一张结果卡;`cardType` 取自已声明的卡片。
|
|
1986
|
+
*
|
|
1987
|
+
* @agentApi card-action
|
|
1988
|
+
*/
|
|
1989
|
+
declare function cardResult<S extends z.ZodTypeAny>(meta: CardMeta<S>, data: z.input<S>): CardActionResult;
|
|
1990
|
+
/** 只给一句提示(没有 update / card 时才会下发到界面)。
|
|
1991
|
+
*
|
|
1992
|
+
* @agentApi card-action
|
|
1993
|
+
*/
|
|
1994
|
+
declare function noticeResult(text: string): CardActionResult;
|
|
1995
|
+
/** 三种结果的构造器集合(update / card / notice)。
|
|
1996
|
+
*
|
|
1997
|
+
* @agentApi card-action
|
|
1998
|
+
*/
|
|
1999
|
+
declare const actionResult: {
|
|
2000
|
+
update: typeof updateResult;
|
|
2001
|
+
card: typeof cardResult;
|
|
2002
|
+
notice: typeof noticeResult;
|
|
2003
|
+
};
|
|
2004
|
+
|
|
1971
2005
|
/**
|
|
1972
2006
|
* 表单提交虚拟 tool 的 id。
|
|
1973
2007
|
* 单一来源,跨 chat-engine / registry / 客户端过滤逻辑共用。
|
|
@@ -2072,39 +2106,6 @@ interface LoadedAgentPromptConfig {
|
|
|
2072
2106
|
}
|
|
2073
2107
|
declare function loadAgentPromptConfig(configDir: string): LoadedAgentPromptConfig;
|
|
2074
2108
|
|
|
2075
|
-
/** 工具 execute 第二参的结构型投影(只声明读取器消费的形状) */
|
|
2076
|
-
interface ToolExecContextLike {
|
|
2077
|
-
requestContext?: {
|
|
2078
|
-
get(key: string): unknown;
|
|
2079
|
-
};
|
|
2080
|
-
toolCallId?: string;
|
|
2081
|
-
agent?: {
|
|
2082
|
-
toolCallId?: string;
|
|
2083
|
-
};
|
|
2084
|
-
}
|
|
2085
|
-
interface ToolRunMetadata {
|
|
2086
|
-
runId: string;
|
|
2087
|
-
threadKey: string;
|
|
2088
|
-
toolCallId: string;
|
|
2089
|
-
}
|
|
2090
|
-
/** Read trusted producer metadata from the execute context, never from model arguments. */
|
|
2091
|
-
declare function getToolRunMetadata(execCtx: ToolExecContextLike | undefined): Readonly<ToolRunMetadata> | undefined;
|
|
2092
|
-
/**
|
|
2093
|
-
* 从工具 execute 第二参读取运行上下文(散键组装)。
|
|
2094
|
-
* 返回 undefined 当 requestContext 缺失或 identity 键缺失(引擎外直调/匿名无身份)。
|
|
2095
|
-
*/
|
|
2096
|
-
declare function getToolRequestContext(execCtx: ToolExecContextLike | undefined): Readonly<RequestContext$1> | undefined;
|
|
2097
|
-
/**
|
|
2098
|
-
* 严格变体:运行上下文缺失时抛 AUTH_FORBIDDEN(fail-visible——显式正确性优于静默降级)。
|
|
2099
|
-
* @param toolId 诊断信息(缺失文案指明哪个工具、怎么修)
|
|
2100
|
-
*/
|
|
2101
|
-
declare function requireToolRequestContext(execCtx: ToolExecContextLike | undefined, toolId?: string): Readonly<RequestContext$1>;
|
|
2102
|
-
/**
|
|
2103
|
-
* 测试/直调助手:由 plain RequestContext 构造工具 execute 第二参形态。
|
|
2104
|
-
* 散键写入与引擎 buildRunRequestContext 同构(往返由 context-concurrency.test C2 锁定)。
|
|
2105
|
-
*/
|
|
2106
|
-
declare function createToolExecContext(reqCtx: RequestContext$1): ToolExecContextLike;
|
|
2107
|
-
|
|
2108
2109
|
interface SaveMessageParams {
|
|
2109
2110
|
conversationId: string;
|
|
2110
2111
|
agentId: string;
|
|
@@ -2330,4 +2331,4 @@ interface SampleShapeReport {
|
|
|
2330
2331
|
*/
|
|
2331
2332
|
declare function findSampleShapeViolations(meta: CardMeta): SampleShapeReport;
|
|
2332
2333
|
|
|
2333
|
-
export { type AnyTool, BROAD_ROUTING_TERMS, BUILTIN_HYGIENE_NAMES, type BootstrapMemoryKbOptions, type BootstrapMemoryKbResult, type BuildEngineOptions, CARDS_SPEC, CARD_DECISION_HOLD_LIMIT, CARD_DECISION_TAG,
|
|
2334
|
+
export { type ActionDefinition, type AnyTool, BROAD_ROUTING_TERMS, BUILTIN_HYGIENE_NAMES, type BootstrapMemoryKbOptions, type BootstrapMemoryKbResult, type BuildEngineOptions, CARDS_SPEC, CARD_DECISION_HOLD_LIMIT, CARD_DECISION_TAG, type CardDecisionPlan, type CardDecisionStripper, type CardPersistenceBackend, CardPool, type ChatEngine, type ChatEngineOptions, type ContentPart, type ContentTagHygiene, type ConversationRouterDeps, ConversationService, DECISION_HOLD_LIMIT, DEFAULT_INSTRUCTIONS, DEFAULT_KNOWLEDGE_MEMORY_CAPABILITIES, DEFAULT_LIST_TTL_MS, DEFAULT_LLM_PROVIDER_CONFIG_PATH, DEFAULT_MAX_CARDS_PER_TURN, DEFAULT_MAX_ENTRIES, DEFAULT_MAX_PRE_TOOLS_PER_RUN, DEFAULT_MEMORY_MAX_CHARS_PER_RECORD, DEFAULT_MEMORY_RECALL_TIMEOUT_MS, DEFAULT_MEMORY_TOP_K, DEFAULT_MEMORY_VALIDATE_TIMEOUT_MS, DEFAULT_PRE_TOOL_TIMEOUT_MS, DEFAULT_SKILL_MODE, DROP_BODY_SOFT_LIMIT, type DefineToolContext, type DefineToolIdentity, type DefineToolOptions, type DefinedAction, EARLY_EXECUTION_MARKER, type EngineModelStepInput, type EnginePreModelActivityAttestation, type EngineRunEndInput, type EngineRunInput, type EngineStepControlFactory, type EngineStepControlInput, type EngineStepController, type EngineStepResultInput, type EngineStepToolChoice, type EngineToolCallInput, type EngineToolResultInput, FORM_SUBMIT_TOOL_ID, FileCardPersistenceBackend, HYGIENE_TAG_NORMALIZE, type HygieneTagFamily, INTERNAL_TOOL, type InstallTboxDevDeps, type IntentRoute, KB_SCOPE_GLOBAL, KNOWLEDGE_DEFAULT_BASE_URL, KnowledgeBootstrapError, type KnowledgeMemoryStoreOptions, KnowledgeOpenapiError, type KnowledgeOpenapiTransportOptions, type KnowledgeTransport, type LoadedAgentPromptConfig, type LoadedChatConfig, type LoadedPluginTools, MEMORY_IMPORTANCE_BASE, MEMORY_KB_INDEX_COLUMNS, MEMORY_KB_SCHEMA, MEMORY_KB_SEED_CSV, MEMORY_LIST_DEFAULT_LIMIT, MEMORY_LIST_MAX_LIMIT, MEMORY_MAX_PER_USER, type MemoryEngineOptions, type MemoryFilterColumn, type MemoryGuardDeps, type MemoryGuardEnv, type MemoryPromptCaps, type MemoryRouterDeps, type MemoryStoreEnv, MemoryStoreUnsupportedError, type MemoryToolDeps, MemoryUnavailableError, type MemoryValidateMode, type MemoryValidationOutcome, MessageEmbeddedBackend, type ModelProviderOptions, PRE_TOOL_HISTORY_LIMIT, type ParallelToolCallsControl, type PlatformApiRouterDeps, type PluginIntegrationOptions, PoolEntry, type PreFilterTerm, type PreToolExecContext, PreToolTimeoutError, PreviewActionError, type QuickCommand, RAW_TOOL_INPUT_BOUNDARY, type RawToolInputBoundary, type RawToolInputBoundaryResult, type RecallCacheOptions, type RecallCacheState, type ResolvedRuntimeContextOptions, type ResolvedTagSpecs, type RuntimeContextOptions, type RuntimeTemporalContext, type RuntimeTemporalContextSnapshot, type SampleShapeBlindSpot, type SampleShapeReport, type SampleShapeViolation, type SdkRuntimeOptions, type SdkToolRuntime, type SegmentHit, type SkillInjectionDecision, type SkillMode, type SortTerm, type StoredMemoryRecord, type StreamTagEngine, DEFAULT_FILE_URL_PREFIX as TBOX_FILE_URL_PREFIX, THINK_SPECS, TOOL_CALL_TEXT_SPECS, type TagBodyPolicy, type TagEngineFinish, type TagHit, type TagSeal, type TagSource, type TagSpec, type TagTrack, TboxTraceExporter, type ThinkingControl, type TurnReminderBlocks, actionResult, applySkillReminder, bootstrapMemoryKnowledgeBase, buildCardDecisionReminder, buildInjectedUserContent, buildMemoryRecallToolCallEvents, buildMemoryReminder, buildMessageInputs, buildPlatformInstructions, buildPreToolCallEndEvents, buildPreToolCallStartEvents, buildPreToolDirectives, buildRecapUserContent, buildSkillRecapReminder, buildSkillReminder, buildSkillToolCallEvents, buildUserContent, cardResult, clampMaxCards, clampMemoryMaxChars, clampMemoryTopK, coerceStringifiedFields, composeTurnUserContent, createCardDecisionStripper, createCardTool, createChatEngine, createConversationRouter, createEngineFromContext, createGatedMemoryStore, createInMemoryMemoryStore, createIntentDispatcher, createKnowledgeMemoryStore, createKnowledgeOpenapiTransport, createMemoryRouter, createMemoryTools, createModelProvider, createPlatformApiRouter, createPluginIntegration, createRuntimeTemporalContext, createSdkToolRuntime, createStreamTagEngine, createTtsProxy, createWsServer, decideCards, decideSkillInjection, defineAction, definePreTool, defineTool, envelopeTag, executePreTool, extractImageUrls, findSampleShapeViolations, formSubmitTool, generateMemoryId, getLastRecallCacheState, getTtsClient, hardenToolsForLlm, hashContent, healthRouter, hygieneXmlTag, installTboxDev, internalTool, isCleanPreModelActivityAttestation, loadAgentPromptConfig, loadChatConfig, loadLocalSkills, loadModuleSkills, matchIntent, memoryStoreCapabilities, mergePreTools, mergeSkills, normalizePreTools, noticeResult, omitInternal, pickFallbackCard, projectHistory, recallMemories, resetTtsClient, resolveEarlyToolExecution, resolveMaxSteps, resolveMemoryEngineOptions, resolveMemoryRecallTimeout, resolveMemoryStore, resolveMemoryStoreGuarded, resolveMemoryValidateMode, resolveMemoryValidateTimeout, resolvePreToolTimeout, resolveRuntimeContextOptions, resolveSkillMode, resolveTagSpecs, resolveToolDebug, restoreCardSnapshot, sanitizeLlmToolInput, scanInjectedSkills, scopeToKey, selectPreTools, selectSkill, stableStringify, stripSystemReminderBlocks, router as tboxSessionRouter, tboxTraceExporter, toCardSnapshot, toMastraSkill, toWsChatConfig, tokenizeTagBody, updateResult, validateMemoryKnowledgeBase, withCardEmissionHint, withDeadline, withEarlyExecution, withLlmInputSanitize, withRawToolInputBoundary, withRecallCache, xmlTag, xmlTagDecision };
|