@dabuliu_wsy/dsh-im 0.0.0-stage → 0.3.0
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/LICENSE +21 -0
- package/README.md +204 -3
- package/cordis.patch.yml +4 -0
- package/dist/core/agent-state.d.ts +38 -0
- package/dist/core/agent-state.js +59 -0
- package/dist/core/arbiter-bridge.d.ts +25 -0
- package/dist/core/arbiter-bridge.js +20 -0
- package/dist/core/arbiter.d.ts +29 -0
- package/dist/core/arbiter.js +59 -0
- package/dist/core/avatar-brands.d.ts +23 -0
- package/dist/core/avatar-brands.js +75 -0
- package/dist/core/avatar-presets.d.ts +21 -0
- package/dist/core/avatar-presets.js +38 -0
- package/dist/core/avatar.d.ts +1 -0
- package/dist/core/avatar.js +18 -0
- package/dist/core/blocked.d.ts +12 -0
- package/dist/core/blocked.js +23 -0
- package/dist/core/budget-plan.d.ts +41 -0
- package/dist/core/budget-plan.js +69 -0
- package/dist/core/calibration-samples.d.ts +77 -0
- package/dist/core/calibration-samples.js +168 -0
- package/dist/core/calibrator.d.ts +57 -0
- package/dist/core/calibrator.js +125 -0
- package/dist/core/chapter-tree.d.ts +128 -0
- package/dist/core/chapter-tree.js +400 -0
- package/dist/core/consensus.d.ts +135 -0
- package/dist/core/consensus.js +394 -0
- package/dist/core/context-budget.d.ts +153 -0
- package/dist/core/context-budget.js +183 -0
- package/dist/core/curator.d.ts +28 -0
- package/dist/core/curator.js +190 -0
- package/dist/core/dual-window.d.ts +86 -0
- package/dist/core/dual-window.js +175 -0
- package/dist/core/events.d.ts +110 -0
- package/dist/core/events.js +117 -0
- package/dist/core/facts.d.ts +114 -0
- package/dist/core/facts.js +400 -0
- package/dist/core/fence.d.ts +34 -0
- package/dist/core/fence.js +129 -0
- package/dist/core/floor.d.ts +18 -0
- package/dist/core/floor.js +80 -0
- package/dist/core/ids.d.ts +11 -0
- package/dist/core/ids.js +29 -0
- package/dist/core/im.d.ts +213 -0
- package/dist/core/im.js +1640 -0
- package/dist/core/index.d.ts +34 -0
- package/dist/core/index.js +34 -0
- package/dist/core/log.d.ts +21 -0
- package/dist/core/log.js +63 -0
- package/dist/core/memory-claims.d.ts +67 -0
- package/dist/core/memory-claims.js +164 -0
- package/dist/core/memory-context.d.ts +121 -0
- package/dist/core/memory-context.js +303 -0
- package/dist/core/memory-visibility.d.ts +58 -0
- package/dist/core/memory-visibility.js +36 -0
- package/dist/core/memory.d.ts +12 -0
- package/dist/core/memory.js +73 -0
- package/dist/core/metrics.d.ts +49 -0
- package/dist/core/metrics.js +89 -0
- package/dist/core/multi-hop.d.ts +116 -0
- package/dist/core/multi-hop.js +278 -0
- package/dist/core/persist.d.ts +21 -0
- package/dist/core/persist.js +94 -0
- package/dist/core/proactive.d.ts +54 -0
- package/dist/core/proactive.js +108 -0
- package/dist/core/prompt.d.ts +82 -0
- package/dist/core/prompt.js +164 -0
- package/dist/core/receipt.d.ts +107 -0
- package/dist/core/receipt.js +86 -0
- package/dist/core/retrieval.d.ts +69 -0
- package/dist/core/retrieval.js +260 -0
- package/dist/core/role-state.d.ts +16 -0
- package/dist/core/role-state.js +65 -0
- package/dist/core/runtime.d.ts +137 -0
- package/dist/core/runtime.js +574 -0
- package/dist/core/summary.d.ts +19 -0
- package/dist/core/summary.js +96 -0
- package/dist/core/text.d.ts +10 -0
- package/dist/core/text.js +45 -0
- package/dist/core/time.d.ts +22 -0
- package/dist/core/time.js +84 -0
- package/dist/core/tool-schema.d.ts +12 -0
- package/dist/core/tool-schema.js +92 -0
- package/dist/core/tools.d.ts +137 -0
- package/dist/core/tools.js +348 -0
- package/dist/core/trash.d.ts +110 -0
- package/dist/core/trash.js +56 -0
- package/dist/core/types.d.ts +400 -0
- package/dist/core/types.js +1 -0
- package/dist/core/window.d.ts +6 -0
- package/dist/core/window.js +7 -0
- package/dist/core/workspace-node.d.ts +28 -0
- package/dist/core/workspace-node.js +232 -0
- package/dist/core/workspace.d.ts +9 -0
- package/dist/core/workspace.js +45 -0
- package/dist/host/agent-session.d.ts +296 -0
- package/dist/host/agent-session.js +964 -0
- package/dist/host/attachment-gc.d.ts +37 -0
- package/dist/host/attachment-gc.js +97 -0
- package/dist/host/calibration-samples-store.d.ts +5 -0
- package/dist/host/calibration-samples-store.js +67 -0
- package/dist/host/capabilities.d.ts +45 -0
- package/dist/host/capabilities.js +67 -0
- package/dist/host/derived-store.d.ts +36 -0
- package/dist/host/derived-store.js +199 -0
- package/dist/host/dsh-llm.d.ts +143 -0
- package/dist/host/dsh-llm.js +395 -0
- package/dist/host/event-store.d.ts +47 -0
- package/dist/host/event-store.js +154 -0
- package/dist/host/fs-atomic.d.ts +1 -0
- package/dist/host/fs-atomic.js +26 -0
- package/dist/host/group-files.d.ts +26 -0
- package/dist/host/group-files.js +142 -0
- package/dist/host/im-api.d.ts +408 -0
- package/dist/host/im-api.js +1188 -0
- package/dist/host/index.d.ts +103 -0
- package/dist/host/index.js +509 -0
- package/dist/host/media-type.d.ts +10 -0
- package/dist/host/media-type.js +39 -0
- package/dist/host/memory-index.d.ts +65 -0
- package/dist/host/memory-index.js +181 -0
- package/dist/host/metrics-store.d.ts +7 -0
- package/dist/host/metrics-store.js +104 -0
- package/dist/host/models.d.ts +39 -0
- package/dist/host/models.js +67 -0
- package/dist/host/persona-tools.d.ts +57 -0
- package/dist/host/persona-tools.js +226 -0
- package/dist/host/preflight.d.ts +31 -0
- package/dist/host/preflight.js +29 -0
- package/dist/host/receipt-store.d.ts +26 -0
- package/dist/host/receipt-store.js +68 -0
- package/dist/host/run-check.d.ts +51 -0
- package/dist/host/run-check.js +190 -0
- package/dist/host/state-roots.d.ts +50 -0
- package/dist/host/state-roots.js +163 -0
- package/dist/host/tool-cache.d.ts +25 -0
- package/dist/host/tool-cache.js +90 -0
- package/dist/host/tool-call-budget.d.ts +29 -0
- package/dist/host/tool-call-budget.js +38 -0
- package/dist/host/trash-store.d.ts +32 -0
- package/dist/host/trash-store.js +316 -0
- package/dsh-plugin.json +25 -0
- package/lib/client.inner.cjs +3933 -0
- package/lib/client.js +3941 -0
- package/package.json +86 -6
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import type { ModelContentPart, TurnStepTrace } from '../core/types.ts';
|
|
2
|
+
import { type ModelOption } from './models.ts';
|
|
3
|
+
type StreamChunk = {
|
|
4
|
+
type?: string;
|
|
5
|
+
text?: string;
|
|
6
|
+
/** block-start 的块类型:text / reasoning / tool-call…… */
|
|
7
|
+
blockType?: string;
|
|
8
|
+
block?: {
|
|
9
|
+
type?: string;
|
|
10
|
+
text?: string;
|
|
11
|
+
id?: string;
|
|
12
|
+
name?: string;
|
|
13
|
+
arguments?: string;
|
|
14
|
+
};
|
|
15
|
+
reason?: {
|
|
16
|
+
kind?: string;
|
|
17
|
+
failure?: {
|
|
18
|
+
message?: string;
|
|
19
|
+
code?: string;
|
|
20
|
+
};
|
|
21
|
+
usage?: UsageLike;
|
|
22
|
+
};
|
|
23
|
+
usage?: UsageLike;
|
|
24
|
+
meta?: {
|
|
25
|
+
usage?: UsageLike;
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
/** 宿主流里出现的用量字段(字段名不统一,两套命名都收)。 */
|
|
29
|
+
export type UsageLike = {
|
|
30
|
+
inputTokens?: number;
|
|
31
|
+
outputTokens?: number;
|
|
32
|
+
totalTokens?: number;
|
|
33
|
+
promptTokens?: number;
|
|
34
|
+
completionTokens?: number;
|
|
35
|
+
input_tokens?: number;
|
|
36
|
+
output_tokens?: number;
|
|
37
|
+
total_tokens?: number;
|
|
38
|
+
/** 推理/缓存明细(不同厂商命名不同)。 */
|
|
39
|
+
reasoningTokens?: number;
|
|
40
|
+
reasoning_tokens?: number;
|
|
41
|
+
cachedTokens?: number;
|
|
42
|
+
cached_tokens?: number;
|
|
43
|
+
completionTokensDetails?: {
|
|
44
|
+
reasoningTokens?: number;
|
|
45
|
+
reasoning_tokens?: number;
|
|
46
|
+
};
|
|
47
|
+
promptTokensDetails?: {
|
|
48
|
+
cachedTokens?: number;
|
|
49
|
+
cached_tokens?: number;
|
|
50
|
+
};
|
|
51
|
+
};
|
|
52
|
+
export interface TokenUsage {
|
|
53
|
+
inputTokens?: number;
|
|
54
|
+
outputTokens?: number;
|
|
55
|
+
totalTokens?: number;
|
|
56
|
+
/** 推理 token(是 output 的子集,不是可加项)。 */
|
|
57
|
+
reasoningTokens?: number;
|
|
58
|
+
/** 命中缓存的 input token(成本口径用;inputTokens 是否含它由 provider 语义决定)。 */
|
|
59
|
+
cachedTokens?: number;
|
|
60
|
+
}
|
|
61
|
+
/** 从 finish chunk 里取用量;取不到返回 undefined(不编造 0)。 */
|
|
62
|
+
export declare function usageInChunk(chunk: StreamChunk | undefined): TokenUsage | undefined;
|
|
63
|
+
export type LlmService = {
|
|
64
|
+
listProviders?: () => {
|
|
65
|
+
id?: string;
|
|
66
|
+
name?: string;
|
|
67
|
+
}[] | string[];
|
|
68
|
+
listConfigurableProviders?: () => {
|
|
69
|
+
provider?: string;
|
|
70
|
+
displayName?: string;
|
|
71
|
+
}[];
|
|
72
|
+
listModels?: (provider: string) => Promise<{
|
|
73
|
+
id?: string;
|
|
74
|
+
name?: string;
|
|
75
|
+
provider?: string;
|
|
76
|
+
}[]>;
|
|
77
|
+
stream?: (options: Record<string, unknown>) => AsyncIterable<StreamChunk>;
|
|
78
|
+
/** 宿主模型能力查询:真实签名是 `resolveModelInfo(provider, model, signal?)`(async)。 */
|
|
79
|
+
resolveModelInfo?: (provider: string, model: string, signal?: AbortSignal) => Promise<{
|
|
80
|
+
context?: {
|
|
81
|
+
contextWindow?: number;
|
|
82
|
+
};
|
|
83
|
+
} & Record<string, unknown>>;
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* 模型上下文窗口:只按宿主真实签名 `resolveModelInfo(provider, model)` 调用并吞掉失败。
|
|
87
|
+
*
|
|
88
|
+
* 注意:传错参数形状会让宿主适配器查不到路由(NO_ADAPTER),而它返回的是 Promise,
|
|
89
|
+
* 不 await 会变成未处理的 rejection(Electron 主进程会直接弹“应用无法启动”)。
|
|
90
|
+
* 所以这里必须 `await` + try/catch,失败一律回 undefined(走默认预算)。
|
|
91
|
+
*/
|
|
92
|
+
export declare function modelContextWindow(llm: LlmService | undefined, provider: string, model: string): Promise<number | undefined>;
|
|
93
|
+
export declare function resolveFastReasoningEffort(llm: LlmService | undefined, provider: string, model: string): Promise<string | undefined>;
|
|
94
|
+
/**
|
|
95
|
+
* 宿主 DSH 的模型目录,和 GUI 的模型选择器同源:
|
|
96
|
+
* 遍历 `listProviders()`,每个路由用 `listModels()` 取目录。
|
|
97
|
+
* 目录读不出来的提供方也保留一行(`ready: false`),由界面显示为不可选。
|
|
98
|
+
*/
|
|
99
|
+
export declare function listDshModels(llm: LlmService): Promise<ModelOption[]>;
|
|
100
|
+
/** 一次工具循环的真实统计(trace/metrics 用;数字全部来自执行,不是估算)。 */
|
|
101
|
+
export interface TurnToolStats {
|
|
102
|
+
/** 模型请求的工具调用次数(被重复抑制/超限拒绝的也算,防止换参数绕过预算)。 */
|
|
103
|
+
toolCalls: number;
|
|
104
|
+
/** 真正执行了工具的调用次数(≤ toolCalls)。 */
|
|
105
|
+
toolExecuted: number;
|
|
106
|
+
/** 工具循环轮数。 */
|
|
107
|
+
toolRounds: number;
|
|
108
|
+
/** 命中重复抑制(同一工具同参)的次数。 */
|
|
109
|
+
dedupedRepeats: number;
|
|
110
|
+
/** 是否因工具调用上限被强制收尾。 */
|
|
111
|
+
toolBudgetExhausted: boolean;
|
|
112
|
+
/** 本轮的调用上限(回执里可对照)。 */
|
|
113
|
+
toolCallLimit: number;
|
|
114
|
+
}
|
|
115
|
+
export declare function completeDshChat(input: {
|
|
116
|
+
llm: LlmService;
|
|
117
|
+
provider: string;
|
|
118
|
+
model: string;
|
|
119
|
+
system: string;
|
|
120
|
+
messages: {
|
|
121
|
+
role: 'user' | 'assistant' | 'system';
|
|
122
|
+
content: string | ModelContentPart[];
|
|
123
|
+
}[];
|
|
124
|
+
toolAllow?: string[];
|
|
125
|
+
onTool?: (name: string, args: Record<string, unknown>) => Promise<string>;
|
|
126
|
+
/** 硬顶(默认 50,仅防死循环);可用 DSH_IM_MAX_TOOL_ROUNDS 调。 */
|
|
127
|
+
maxToolRounds?: number;
|
|
128
|
+
/** 单轮工具调用上限(默认 12,`DSH_IM_MAX_TOOL_CALLS` 可调)。 */
|
|
129
|
+
maxToolCalls?: number;
|
|
130
|
+
/** 总时长预算(默认 240s,仅防挂死);可用 DSH_IM_TURN_BUDGET_MS 调。 */
|
|
131
|
+
timeBudgetMs?: number;
|
|
132
|
+
/** 注入时钟(默认 `Date.now`)。仅测试用来消除“预算按真实时间判定”的不确定性;生产不传。 */
|
|
133
|
+
now?: () => number;
|
|
134
|
+
/** 每一步执行的回调(回执/成员行为时间线用;只传截断预览)。 */
|
|
135
|
+
onStep?: (step: TurnStepTrace) => void;
|
|
136
|
+
/** 工具循环统计回调(host 写 trace/metrics:toolCalls / toolBudgetExhausted)。 */
|
|
137
|
+
onTurnStats?: (stats: TurnToolStats) => void;
|
|
138
|
+
/** 调用用途:后台抽取/整理用最低推理档,避免 20s+ 的思维链开销。 */
|
|
139
|
+
purpose?: 'reply' | 'extract' | 'curate';
|
|
140
|
+
/** 流里观察到 usage 时回调(Phase 1b:写指标 + 校准 chars/token 系数)。 */
|
|
141
|
+
onUsage?: (usage: TokenUsage) => void;
|
|
142
|
+
}): Promise<string>;
|
|
143
|
+
export {};
|
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
import { toolsForAllow } from '../core/tool-schema.js';
|
|
2
|
+
import { catalogModelId } from './models.js';
|
|
3
|
+
import { createToolCallBudget, toolCallLimitFromEnv } from './tool-call-budget.js';
|
|
4
|
+
/** 从 finish chunk 里取用量;取不到返回 undefined(不编造 0)。 */
|
|
5
|
+
export function usageInChunk(chunk) {
|
|
6
|
+
const raw = chunk?.usage ?? chunk?.reason?.usage ?? chunk?.meta?.usage;
|
|
7
|
+
if (!raw || typeof raw !== 'object')
|
|
8
|
+
return undefined;
|
|
9
|
+
const input = raw.inputTokens ?? raw.promptTokens ?? raw.input_tokens;
|
|
10
|
+
const output = raw.outputTokens ?? raw.completionTokens ?? raw.output_tokens;
|
|
11
|
+
const total = raw.totalTokens ?? raw.total_tokens;
|
|
12
|
+
const reasoning = raw.reasoningTokens ?? raw.reasoning_tokens
|
|
13
|
+
?? raw.completionTokensDetails?.reasoningTokens ?? raw.completionTokensDetails?.reasoning_tokens;
|
|
14
|
+
const cached = raw.cachedTokens ?? raw.cached_tokens
|
|
15
|
+
?? raw.promptTokensDetails?.cachedTokens ?? raw.promptTokensDetails?.cached_tokens;
|
|
16
|
+
const usage = {};
|
|
17
|
+
if (typeof input === 'number' && Number.isFinite(input))
|
|
18
|
+
usage.inputTokens = input;
|
|
19
|
+
if (typeof output === 'number' && Number.isFinite(output))
|
|
20
|
+
usage.outputTokens = output;
|
|
21
|
+
if (typeof total === 'number' && Number.isFinite(total))
|
|
22
|
+
usage.totalTokens = total;
|
|
23
|
+
if (typeof reasoning === 'number' && Number.isFinite(reasoning))
|
|
24
|
+
usage.reasoningTokens = reasoning;
|
|
25
|
+
if (typeof cached === 'number' && Number.isFinite(cached))
|
|
26
|
+
usage.cachedTokens = cached;
|
|
27
|
+
return usage.inputTokens === undefined && usage.outputTokens === undefined && usage.totalTokens === undefined
|
|
28
|
+
? undefined
|
|
29
|
+
: usage;
|
|
30
|
+
}
|
|
31
|
+
const CONTEXT_WINDOW_KEYS = [
|
|
32
|
+
'contextWindow',
|
|
33
|
+
'context_window',
|
|
34
|
+
'maxInputTokens',
|
|
35
|
+
'max_input_tokens',
|
|
36
|
+
'contextLength',
|
|
37
|
+
'context_length',
|
|
38
|
+
];
|
|
39
|
+
function contextWindowOf(info) {
|
|
40
|
+
if (!info || typeof info !== 'object')
|
|
41
|
+
return undefined;
|
|
42
|
+
const record = info;
|
|
43
|
+
// 真实 DSH 的形状:{ context: { contextWindow } };其余键名是防御性兜底。
|
|
44
|
+
const context = record.context;
|
|
45
|
+
if (context && typeof context === 'object') {
|
|
46
|
+
const value = context.contextWindow;
|
|
47
|
+
if (typeof value === 'number' && Number.isFinite(value) && value > 0)
|
|
48
|
+
return value;
|
|
49
|
+
}
|
|
50
|
+
for (const key of CONTEXT_WINDOW_KEYS) {
|
|
51
|
+
const value = record[key];
|
|
52
|
+
if (typeof value === 'number' && Number.isFinite(value) && value > 0)
|
|
53
|
+
return value;
|
|
54
|
+
}
|
|
55
|
+
const nested = record.modelInfo ?? record.info ?? record.capabilities;
|
|
56
|
+
if (nested && nested !== info)
|
|
57
|
+
return contextWindowOf(nested);
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* 模型上下文窗口:只按宿主真实签名 `resolveModelInfo(provider, model)` 调用并吞掉失败。
|
|
62
|
+
*
|
|
63
|
+
* 注意:传错参数形状会让宿主适配器查不到路由(NO_ADAPTER),而它返回的是 Promise,
|
|
64
|
+
* 不 await 会变成未处理的 rejection(Electron 主进程会直接弹“应用无法启动”)。
|
|
65
|
+
* 所以这里必须 `await` + try/catch,失败一律回 undefined(走默认预算)。
|
|
66
|
+
*/
|
|
67
|
+
export async function modelContextWindow(llm, provider, model) {
|
|
68
|
+
const resolver = llm?.resolveModelInfo;
|
|
69
|
+
if (!llm || typeof resolver !== 'function')
|
|
70
|
+
return undefined;
|
|
71
|
+
try {
|
|
72
|
+
return contextWindowOf(await resolver.call(llm, provider, model));
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* 后台结构化调用(事实抽取 / 共识整理)用的“最低推理档”。
|
|
80
|
+
* 模型能力由宿主 resolveModelInfo 暴露(reasoning.efforts[].id);取 advertised 里最低/最快的那个,
|
|
81
|
+
* 查不到就不传(保持 provider 默认),绝不猜一个可能非法的 effort id。
|
|
82
|
+
*/
|
|
83
|
+
const fastEffortCache = new Map();
|
|
84
|
+
export async function resolveFastReasoningEffort(llm, provider, model) {
|
|
85
|
+
const key = `${provider}::${model}`;
|
|
86
|
+
if (fastEffortCache.has(key))
|
|
87
|
+
return fastEffortCache.get(key);
|
|
88
|
+
const resolver = llm?.resolveModelInfo;
|
|
89
|
+
if (!llm || typeof resolver !== 'function') {
|
|
90
|
+
fastEffortCache.set(key, undefined);
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|
|
93
|
+
try {
|
|
94
|
+
const info = await resolver.call(llm, provider, model);
|
|
95
|
+
const ids = (info.reasoning?.efforts ?? [])
|
|
96
|
+
.map((effort) => effort?.id)
|
|
97
|
+
.filter((id) => typeof id === 'string' && id.length > 0);
|
|
98
|
+
const rank = (id) => (/^(minimal|low|none|off|fast)$/i.test(id) ? 0
|
|
99
|
+
: /^(medium|mid)$/i.test(id) ? 1
|
|
100
|
+
: /^(high|max)$/i.test(id) ? 2 : 3);
|
|
101
|
+
const picked = [...ids].sort((left, right) => rank(left) - rank(right))[0];
|
|
102
|
+
fastEffortCache.set(key, picked);
|
|
103
|
+
return picked;
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
fastEffortCache.set(key, undefined);
|
|
107
|
+
return undefined;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function providerId(row) {
|
|
111
|
+
if (typeof row === 'string')
|
|
112
|
+
return row;
|
|
113
|
+
return row.id || row.name || '';
|
|
114
|
+
}
|
|
115
|
+
function providerLabel(row) {
|
|
116
|
+
if (typeof row === 'string')
|
|
117
|
+
return row;
|
|
118
|
+
return row.name || row.id || '';
|
|
119
|
+
}
|
|
120
|
+
function callList(fn, llm) {
|
|
121
|
+
if (typeof fn !== 'function')
|
|
122
|
+
return undefined;
|
|
123
|
+
return fn.call(llm);
|
|
124
|
+
}
|
|
125
|
+
/** 与 DSH 模型选择器一致:账号、官方排最前,其余保持目录顺序。 */
|
|
126
|
+
const PROVIDER_ORDER = ['deepseek-account', 'deepseek-official'];
|
|
127
|
+
function providerRank(route) {
|
|
128
|
+
const index = PROVIDER_ORDER.indexOf(route);
|
|
129
|
+
return index === -1 ? PROVIDER_ORDER.length : index;
|
|
130
|
+
}
|
|
131
|
+
function errorMessage(error) {
|
|
132
|
+
return error instanceof Error ? error.message : String(error);
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* 宿主 DSH 的模型目录,和 GUI 的模型选择器同源:
|
|
136
|
+
* 遍历 `listProviders()`,每个路由用 `listModels()` 取目录。
|
|
137
|
+
* 目录读不出来的提供方也保留一行(`ready: false`),由界面显示为不可选。
|
|
138
|
+
*/
|
|
139
|
+
export async function listDshModels(llm) {
|
|
140
|
+
const providers = callList(llm.listProviders, llm) ?? [];
|
|
141
|
+
const out = [];
|
|
142
|
+
for (const row of providers) {
|
|
143
|
+
const route = providerId(row);
|
|
144
|
+
if (!route)
|
|
145
|
+
continue;
|
|
146
|
+
const group = providerLabel(row) || route;
|
|
147
|
+
try {
|
|
148
|
+
const models = (await llm.listModels?.call(llm, route)) ?? [];
|
|
149
|
+
for (const model of models) {
|
|
150
|
+
const modelId = model.id?.trim();
|
|
151
|
+
if (!modelId)
|
|
152
|
+
continue;
|
|
153
|
+
const contextWindow = await modelContextWindow(llm, route, modelId);
|
|
154
|
+
out.push({
|
|
155
|
+
id: catalogModelId(route, modelId),
|
|
156
|
+
label: model.name?.trim() || modelId,
|
|
157
|
+
provider: group,
|
|
158
|
+
route,
|
|
159
|
+
modelId,
|
|
160
|
+
ready: true,
|
|
161
|
+
...(contextWindow === undefined ? {} : { contextWindow }),
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
catch (error) {
|
|
166
|
+
out.push({
|
|
167
|
+
id: catalogModelId(route, ''),
|
|
168
|
+
label: group,
|
|
169
|
+
provider: group,
|
|
170
|
+
route,
|
|
171
|
+
modelId: '',
|
|
172
|
+
ready: false,
|
|
173
|
+
note: errorMessage(error),
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return out
|
|
178
|
+
.map((option, index) => ({ option, index }))
|
|
179
|
+
.sort((a, b) => (providerRank(a.option.route ?? '') - providerRank(b.option.route ?? '')
|
|
180
|
+
|| a.index - b.index))
|
|
181
|
+
.map((entry) => entry.option);
|
|
182
|
+
}
|
|
183
|
+
function userTurn(content) {
|
|
184
|
+
return {
|
|
185
|
+
role: 'user',
|
|
186
|
+
content: typeof content === 'string' ? [{ type: 'text', text: content }] : content,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
function contentText(content) {
|
|
190
|
+
if (typeof content === 'string')
|
|
191
|
+
return content;
|
|
192
|
+
return content.filter((part) => part.type === 'text').map((part) => part.text).join('\n');
|
|
193
|
+
}
|
|
194
|
+
/** trace 只存单行预览,避免把整份文件内容塞进 state.json。 */
|
|
195
|
+
function previewForTrace(value) {
|
|
196
|
+
const text = typeof value === 'string' ? value : JSON.stringify(value ?? '');
|
|
197
|
+
return text.replace(/\s+/g, ' ').trim().slice(0, 200);
|
|
198
|
+
}
|
|
199
|
+
function assistantTurn(provider, model, content) {
|
|
200
|
+
return {
|
|
201
|
+
id: crypto.randomUUID(),
|
|
202
|
+
role: 'assistant',
|
|
203
|
+
content,
|
|
204
|
+
source: { kind: 'model', provider, model },
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
function toolTurn(callId, text, isError = false) {
|
|
208
|
+
return {
|
|
209
|
+
id: crypto.randomUUID(),
|
|
210
|
+
role: 'tool',
|
|
211
|
+
toolCallId: callId,
|
|
212
|
+
content: [{ type: 'text', text }],
|
|
213
|
+
source: { kind: 'tool', callId },
|
|
214
|
+
isError,
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
export async function completeDshChat(input) {
|
|
218
|
+
if (!input.llm.stream)
|
|
219
|
+
throw new Error('DSH LLM 服务没有 stream');
|
|
220
|
+
// 宿主 DSH 的原生循环没有轮次预算(要限流得自己挂 agent/turn-stopping)。
|
|
221
|
+
// 这里是我们手写的简化工具循环,所以护栏改成三道,而不是一个很低的轮数上限:
|
|
222
|
+
// 1) 总时长预算(默认 240s):调研再深也不会把地板挂死;
|
|
223
|
+
// 2) 重复调用熔断:同一工具 + 同一参数反复调用 3 次 → 强制只用已有信息作答;
|
|
224
|
+
// 3) 硬顶 50 轮:只防“每次换参数无限循环”的死循环,正常调研远达不到。
|
|
225
|
+
const envRounds = Number(process.env.DSH_IM_MAX_TOOL_ROUNDS);
|
|
226
|
+
const ceiling = input.maxToolRounds
|
|
227
|
+
?? (Number.isFinite(envRounds) && envRounds > 0 ? Math.floor(envRounds) : 50);
|
|
228
|
+
const envBudget = Number(process.env.DSH_IM_TURN_BUDGET_MS);
|
|
229
|
+
const budgetMs = input.timeBudgetMs
|
|
230
|
+
?? (Number.isFinite(envBudget) && envBudget > 0 ? Math.floor(envBudget) : 240_000);
|
|
231
|
+
const now = input.now ?? Date.now;
|
|
232
|
+
const startedAt = now();
|
|
233
|
+
// 宿主 DSH 的 ToolSchema 形状就是 { name, description, parameters }。
|
|
234
|
+
const tools = toolsForAllow(input.toolAllow);
|
|
235
|
+
const history = [];
|
|
236
|
+
const dialogue = input.messages.filter((m) => m.role !== 'system' && contentText(m.content).trim());
|
|
237
|
+
if (dialogue.length) {
|
|
238
|
+
for (const turn of dialogue) {
|
|
239
|
+
if (turn.role === 'user')
|
|
240
|
+
history.push(userTurn(turn.content));
|
|
241
|
+
else
|
|
242
|
+
history.push(assistantTurn(input.provider, input.model, [{ type: 'text', text: contentText(turn.content) }]));
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
else {
|
|
246
|
+
history.push(userTurn('请发言。'));
|
|
247
|
+
}
|
|
248
|
+
const callCounts = new Map();
|
|
249
|
+
// 单轮工具调用预算:模型请求一次算一次(含被抑制的重复/超限拒绝),到上限强制作答。
|
|
250
|
+
const toolBudget = createToolCallBudget(input.maxToolCalls ?? toolCallLimitFromEnv());
|
|
251
|
+
const toolStats = {
|
|
252
|
+
toolCalls: 0,
|
|
253
|
+
toolExecuted: 0,
|
|
254
|
+
toolRounds: 0,
|
|
255
|
+
dedupedRepeats: 0,
|
|
256
|
+
toolBudgetExhausted: false,
|
|
257
|
+
toolCallLimit: toolBudget.limit,
|
|
258
|
+
};
|
|
259
|
+
// 后台抽取/整理:用模型 advertised 的最低推理档;reply 保持默认。
|
|
260
|
+
const fastEffort = input.purpose === 'extract' || input.purpose === 'curate'
|
|
261
|
+
? await resolveFastReasoningEffort(input.llm, input.provider, input.model)
|
|
262
|
+
: undefined;
|
|
263
|
+
let forceAnswer = false;
|
|
264
|
+
for (let round = 0;; round++) {
|
|
265
|
+
toolStats.toolRounds = round + 1;
|
|
266
|
+
const elapsed = now() - startedAt;
|
|
267
|
+
const lastChance = forceAnswer || round >= ceiling || elapsed >= budgetMs;
|
|
268
|
+
const remaining = Math.max(15_000, budgetMs - elapsed);
|
|
269
|
+
const signal = AbortSignal.timeout(Math.min(120_000, remaining));
|
|
270
|
+
const textParts = [];
|
|
271
|
+
const toolCalls = [];
|
|
272
|
+
let finishKind = 'stop';
|
|
273
|
+
let failure = '';
|
|
274
|
+
// DSH 的流可能同时有 text 与 reasoning 两类 block;reasoning(思维链)不能当回复落库。
|
|
275
|
+
let currentBlockType = '';
|
|
276
|
+
// 最后一次机会不再给工具,并把“直接用已有信息回答”写进系统提示:宁可给答案,不要弹中断卡。
|
|
277
|
+
const system = lastChance
|
|
278
|
+
? `${input.system}\n\n[系统提示] 工具使用已到上限(轮次/时长/重复调用),请只根据目前已经看到的信息直接作答,不要再调用工具。`
|
|
279
|
+
: input.system;
|
|
280
|
+
for await (const chunk of input.llm.stream.call(input.llm, {
|
|
281
|
+
provider: input.provider,
|
|
282
|
+
model: input.model,
|
|
283
|
+
system,
|
|
284
|
+
messages: history,
|
|
285
|
+
tools: lastChance ? undefined : (tools.length ? tools : undefined),
|
|
286
|
+
...(fastEffort ? { reasoningEffort: fastEffort } : {}),
|
|
287
|
+
signal,
|
|
288
|
+
})) {
|
|
289
|
+
if (chunk.type === 'block-start')
|
|
290
|
+
currentBlockType = chunk.blockType ?? '';
|
|
291
|
+
if (chunk.type === 'text-delta' && chunk.text && currentBlockType !== 'reasoning')
|
|
292
|
+
textParts.push(chunk.text);
|
|
293
|
+
if (chunk.type === 'block-end' && chunk.block?.type === 'text' && chunk.block.text) {
|
|
294
|
+
if (!textParts.length)
|
|
295
|
+
textParts.push(chunk.block.text);
|
|
296
|
+
}
|
|
297
|
+
if (chunk.type === 'block-end' && chunk.block?.type === 'tool-call' && chunk.block.name) {
|
|
298
|
+
toolCalls.push({
|
|
299
|
+
id: chunk.block.id || crypto.randomUUID(),
|
|
300
|
+
name: chunk.block.name,
|
|
301
|
+
arguments: chunk.block.arguments || '{}',
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
// usage 可能出现在任意 chunk(实测:/llm-probe 扫全流才看到,finish 里不一定有)。
|
|
305
|
+
const streamUsage = usageInChunk(chunk);
|
|
306
|
+
if (streamUsage)
|
|
307
|
+
input.onUsage?.(streamUsage);
|
|
308
|
+
if (chunk.type === 'finish') {
|
|
309
|
+
finishKind = chunk.reason?.kind || 'stop';
|
|
310
|
+
if (finishKind === 'error' || finishKind === 'aborted') {
|
|
311
|
+
failure = [chunk.reason?.failure?.code, chunk.reason?.failure?.message].filter(Boolean).join(': ') || finishKind;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
if (failure)
|
|
316
|
+
throw new Error(failure);
|
|
317
|
+
const text = textParts.join('').trim();
|
|
318
|
+
if ((finishKind === 'tool-calls' || toolCalls.length) && input.onTool && !lastChance) {
|
|
319
|
+
history.push(assistantTurn(input.provider, input.model, toolCalls.map((call) => ({ type: 'tool-call', id: call.id, name: call.name, arguments: call.arguments }))));
|
|
320
|
+
let repeated = false;
|
|
321
|
+
for (const call of toolCalls) {
|
|
322
|
+
const startedAt = Date.now();
|
|
323
|
+
let args = {};
|
|
324
|
+
try {
|
|
325
|
+
args = JSON.parse(call.arguments || '{}');
|
|
326
|
+
}
|
|
327
|
+
catch {
|
|
328
|
+
args = {};
|
|
329
|
+
}
|
|
330
|
+
const stepBase = {
|
|
331
|
+
step: 0,
|
|
332
|
+
kind: 'tool',
|
|
333
|
+
name: call.name,
|
|
334
|
+
args: previewForTrace(call.arguments),
|
|
335
|
+
at: startedAt,
|
|
336
|
+
};
|
|
337
|
+
// ① 单轮硬上限:超限不再执行,喂回"直接作答",并强制收尾。
|
|
338
|
+
const grant = toolBudget.tryReserve();
|
|
339
|
+
toolStats.toolCalls = toolBudget.used();
|
|
340
|
+
if (!grant.ok) {
|
|
341
|
+
toolStats.toolBudgetExhausted = true;
|
|
342
|
+
history.push(toolTurn(call.id, grant.message, true));
|
|
343
|
+
input.onStep?.({ ...stepBase, result: previewForTrace(grant.message), ok: false, ms: Date.now() - startedAt });
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
// ② 重复调用熔断:同样的工具 + 同样的参数不会产生新信息,喂回去让模型收尾。
|
|
347
|
+
const key = `${call.name}|${String(call.arguments ?? '{}').trim()}`;
|
|
348
|
+
const count = (callCounts.get(key) ?? 0) + 1;
|
|
349
|
+
callCounts.set(key, count);
|
|
350
|
+
if (count >= 3) {
|
|
351
|
+
const text = `同一工具(${call.name})用相同参数已经重复调用 ${count} 次,结果不会再变化。请停止调用工具,直接用已有信息回答。`;
|
|
352
|
+
toolStats.dedupedRepeats += 1;
|
|
353
|
+
history.push(toolTurn(call.id, text, true));
|
|
354
|
+
input.onStep?.({ ...stepBase, result: previewForTrace(text), ok: false, ms: Date.now() - startedAt });
|
|
355
|
+
repeated = true;
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
try {
|
|
359
|
+
const result = await input.onTool(call.name, args);
|
|
360
|
+
toolStats.toolExecuted += 1;
|
|
361
|
+
history.push(toolTurn(call.id, result));
|
|
362
|
+
input.onStep?.({ ...stepBase, result: previewForTrace(result), ok: true, ms: Date.now() - startedAt });
|
|
363
|
+
}
|
|
364
|
+
catch (err) {
|
|
365
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
366
|
+
history.push(toolTurn(call.id, message, true));
|
|
367
|
+
input.onStep?.({ ...stepBase, result: previewForTrace(message), ok: false, ms: Date.now() - startedAt });
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
if (repeated)
|
|
371
|
+
forceAnswer = true;
|
|
372
|
+
if (toolStats.toolBudgetExhausted)
|
|
373
|
+
forceAnswer = true;
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
376
|
+
if (!text) {
|
|
377
|
+
throw new Error(lastChance
|
|
378
|
+
? '工具使用到上限后模型仍未给出文字回复'
|
|
379
|
+
: '模型返回空内容');
|
|
380
|
+
}
|
|
381
|
+
input.onTurnStats?.({ ...toolStats });
|
|
382
|
+
input.onStep?.({
|
|
383
|
+
step: 0,
|
|
384
|
+
kind: 'reply',
|
|
385
|
+
result: previewForTrace(text),
|
|
386
|
+
ok: true,
|
|
387
|
+
at: Date.now(),
|
|
388
|
+
ms: Date.now() - startedAt,
|
|
389
|
+
toolCalls: toolStats.toolCalls,
|
|
390
|
+
toolExecuted: toolStats.toolExecuted,
|
|
391
|
+
toolBudgetExhausted: toolStats.toolBudgetExhausted,
|
|
392
|
+
});
|
|
393
|
+
return text;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { type ChatEvent, type EventInput, type LeaseStore } from '../core/events.ts';
|
|
2
|
+
/** 每群的私有目录:`.dsh-im/groups/<threadId>/` */
|
|
3
|
+
export declare function groupDir(root: string, threadId: string): string;
|
|
4
|
+
export declare function eventsPath(root: string, threadId: string): string;
|
|
5
|
+
export declare function leasePath(root: string, threadId: string): string;
|
|
6
|
+
/** 读事件日志:坏行跳过(不让一行脏数据炸整个群)。 */
|
|
7
|
+
export declare function readEvents(root: string, threadId: string): Promise<ChatEvent[]>;
|
|
8
|
+
/** 追加一条事件并落盘(只追加,不重写历史)。 */
|
|
9
|
+
export declare function appendChatEvent(root: string, threadId: string, input: EventInput): Promise<ChatEvent>;
|
|
10
|
+
/**
|
|
11
|
+
* 老 `state.json` 的 messages → 事件日志。幂等:已有事件就不动。
|
|
12
|
+
* @returns 是否真的迁移了,以及当前事件流。
|
|
13
|
+
*/
|
|
14
|
+
export declare function migrateThreadEvents(root: string, threadId: string, messages: readonly {
|
|
15
|
+
id: string;
|
|
16
|
+
kind: 'user' | 'persona' | 'system';
|
|
17
|
+
authorName: string;
|
|
18
|
+
text: string;
|
|
19
|
+
createdAt: number;
|
|
20
|
+
}[]): Promise<{
|
|
21
|
+
migrated: boolean;
|
|
22
|
+
events: ChatEvent[];
|
|
23
|
+
}>;
|
|
24
|
+
/** 文件版租约存储(host 侧;同步实现,文件很小)。 */
|
|
25
|
+
export declare function createFileLeaseStore(root: string): LeaseStore;
|
|
26
|
+
export declare function lastEventSeq(events: readonly ChatEvent[]): number;
|
|
27
|
+
/** 每个群已同步进事件日志的消息条数(双写过渡期的游标)。 */
|
|
28
|
+
export declare function syncPath(root: string, threadId: string): string;
|
|
29
|
+
export interface SyncResult {
|
|
30
|
+
appended: number;
|
|
31
|
+
rewritten: boolean;
|
|
32
|
+
/** 与 messages 一一对应的持久 seq;对不上时为空数组(不覆盖已有 seq)。 */
|
|
33
|
+
seqs: number[];
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* 把 state.json 里的 messages 增量同步进事件日志(过渡期双写,读仍以 state 为准)。
|
|
37
|
+
*
|
|
38
|
+
* 消息事件按顺序对应;`seqs` 回传每条消息在事件日志里的持久序号,
|
|
39
|
+
* saveState 用它回填 `message.seq`。非消息事件(事实/仲裁)在整份重写时保留。
|
|
40
|
+
*/
|
|
41
|
+
export declare function syncThreadEvents(root: string, threadId: string, messages: readonly {
|
|
42
|
+
id: string;
|
|
43
|
+
kind: 'user' | 'persona' | 'system';
|
|
44
|
+
authorName: string;
|
|
45
|
+
text: string;
|
|
46
|
+
createdAt: number;
|
|
47
|
+
}[]): Promise<SyncResult>;
|