dsh-cohub 0.12.1 → 0.13.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 +1 -1
- package/lib/index.js +935 -52
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# dsh-cohub
|
|
2
2
|
|
|
3
|
-
> 本文对应 **v0.
|
|
3
|
+
> 本文对应 **v0.13.1**;完整变更历史见 [CHANGELOG.md](./CHANGELOG.md)。
|
|
4
4
|
|
|
5
5
|
DeepSeek Harness 版(对照 [OpenCode 版](../oh-my-opencode-cohub/)):中文智能体编排插件。
|
|
6
6
|
把「纯调度模式 + 13 个技能(12 个代理编排体系 + co-cordis 组合创作)+ 多模型共识 + 运行期调度韧性」移植到 DSH 原生能力之上。
|
package/lib/index.js
CHANGED
|
@@ -3734,6 +3734,449 @@ function maybeDeferTodoNudge(exec) {
|
|
|
3734
3734
|
} catch {}
|
|
3735
3735
|
}
|
|
3736
3736
|
|
|
3737
|
+
// src/contract-probe.ts
|
|
3738
|
+
function asRecord(value) {
|
|
3739
|
+
return typeof value === "object" && value !== null ? value : undefined;
|
|
3740
|
+
}
|
|
3741
|
+
function pickParent(spec) {
|
|
3742
|
+
return spec.parent;
|
|
3743
|
+
}
|
|
3744
|
+
function pickPrompt(spec) {
|
|
3745
|
+
return spec.prompt;
|
|
3746
|
+
}
|
|
3747
|
+
function pickRequestParent(spec) {
|
|
3748
|
+
return asRecord(spec.request)?.parent;
|
|
3749
|
+
}
|
|
3750
|
+
function pickRequestPrompt(spec) {
|
|
3751
|
+
return asRecord(spec.request)?.prompt;
|
|
3752
|
+
}
|
|
3753
|
+
function assertDualActivationSpec(spec, skillName) {
|
|
3754
|
+
const subject = skillName !== undefined && skillName.length > 0 ? `(label=${skillName})` : "";
|
|
3755
|
+
const record = asRecord(spec);
|
|
3756
|
+
if (record === undefined) {
|
|
3757
|
+
throw new Error("cohub: activation 契约自检失败" + subject + "——startActivation 入参不是对象(收到 " + JSON.stringify(spec ?? null) + ")。双写兼容契约要求入参同时具备 spec 顶层与 spec.request 的 parent/prompt。");
|
|
3758
|
+
}
|
|
3759
|
+
const requirements = [
|
|
3760
|
+
{ where: "spec 顶层", pick: pickParent, what: "parent(对象且含 id)" },
|
|
3761
|
+
{ where: "spec 顶层", pick: pickPrompt, what: "prompt(非空 text 块数组)" },
|
|
3762
|
+
{ where: "spec.request", pick: pickRequestParent, what: "parent(对象且含 id)" },
|
|
3763
|
+
{ where: "spec.request", pick: pickRequestPrompt, what: "prompt(非空 text 块数组)" }
|
|
3764
|
+
];
|
|
3765
|
+
const problems = [];
|
|
3766
|
+
for (const req of requirements) {
|
|
3767
|
+
const value = req.pick(record);
|
|
3768
|
+
const isPrompt = req.what.startsWith("prompt");
|
|
3769
|
+
if (isPrompt) {
|
|
3770
|
+
if (!Array.isArray(value) || value.length === 0) {
|
|
3771
|
+
problems.push(`${req.where} 缺少 ${req.what}(实际:${describeValue(value)})`);
|
|
3772
|
+
}
|
|
3773
|
+
continue;
|
|
3774
|
+
}
|
|
3775
|
+
const parent = asRecord(value);
|
|
3776
|
+
if (parent === undefined) {
|
|
3777
|
+
problems.push(`${req.where} 缺少 ${req.what}(实际:${describeValue(value)})`);
|
|
3778
|
+
continue;
|
|
3779
|
+
}
|
|
3780
|
+
const id = parent.id;
|
|
3781
|
+
if (typeof id !== "string" || id.length === 0) {
|
|
3782
|
+
problems.push(`${req.where}.parent.id 缺失/非字符串(实际:${describeValue(id)})`);
|
|
3783
|
+
}
|
|
3784
|
+
}
|
|
3785
|
+
if (problems.length === 0)
|
|
3786
|
+
return;
|
|
3787
|
+
throw new Error("cohub: activation 契约自检失败" + subject + `——双写兼容契约被破坏,以下字段在对应位置缺失或非法:
|
|
3788
|
+
` + problems.map((p) => " - " + p).join(`
|
|
3789
|
+
`) + `
|
|
3790
|
+
` + "为什么要求双写:0.2.2-rc.1 宿主从 spec.request 读 parent/prompt,0.2.2-rc.3 宿主改从 spec 顶层读" + `(直接读 spec.parent.id),两代没有兼容分支。
|
|
3791
|
+
` + "修复:构造 startActivation 入参时,把同一份 parent/prompt 同时写进 spec 顶层与 spec.request" + "(见 delegate.ts 的 startSubagentRunOnce)。");
|
|
3792
|
+
}
|
|
3793
|
+
function describeValue(value) {
|
|
3794
|
+
if (value === undefined)
|
|
3795
|
+
return "undefined";
|
|
3796
|
+
if (value === null)
|
|
3797
|
+
return "null";
|
|
3798
|
+
if (Array.isArray(value))
|
|
3799
|
+
return `数组(length=${value.length})`;
|
|
3800
|
+
if (typeof value === "object")
|
|
3801
|
+
return "对象";
|
|
3802
|
+
if (typeof value === "string")
|
|
3803
|
+
return value.length > 40 ? `字符串(${JSON.stringify(value.slice(0, 40))}…)` : `字符串(${JSON.stringify(value)})`;
|
|
3804
|
+
return typeof value;
|
|
3805
|
+
}
|
|
3806
|
+
var CANNOT_READ_RE = /Cannot read (?:properties|property)/i;
|
|
3807
|
+
var READING_KEY_RE = /\breading ['"`]?(id|parent|prompt)\b/i;
|
|
3808
|
+
function describeActivationContractError(err) {
|
|
3809
|
+
const error = err instanceof Error ? err : undefined;
|
|
3810
|
+
if (error === undefined)
|
|
3811
|
+
return;
|
|
3812
|
+
const isTypeError = err instanceof TypeError || error.name === "TypeError";
|
|
3813
|
+
if (!isTypeError)
|
|
3814
|
+
return;
|
|
3815
|
+
const message = error.message;
|
|
3816
|
+
if (!CANNOT_READ_RE.test(message))
|
|
3817
|
+
return;
|
|
3818
|
+
const keyMatch = READING_KEY_RE.exec(message);
|
|
3819
|
+
if (keyMatch === null)
|
|
3820
|
+
return;
|
|
3821
|
+
const key = keyMatch[1] ?? "id";
|
|
3822
|
+
const layerHint = key === "id" ? "宿主读的是某层 parent 的 .id,说明它读的 parent 层级里 parent 是 undefined(第三层迁移 / 字段改名)" : key === "parent" ? "宿主读的是某层的 .parent,说明它期望的容器层不存在(例如 spec.request 或更深的 agent 层缺失)" : "宿主读的是某层的 .prompt,说明它期望的容器层不存在(prompt 未写在宿主读取的那一层)";
|
|
3823
|
+
return `宿主 activation 契约不匹配(cohub 归因):
|
|
3824
|
+
` + ` - 症状:startActivation 内读取 ${key} 时命中 undefined(原始 TypeError 如上)。
|
|
3825
|
+
` + " - 两代差异:0.2.2-rc.1 读 spec.request.parent / spec.request.prompt;" + `0.2.2-rc.3 读 spec 顶层 spec.parent / spec.prompt(直接读 spec.parent.id)。
|
|
3826
|
+
` + ` - 推断:${layerHint}。
|
|
3827
|
+
` + " - 修复指引:检查 startActivation 入参是否同时具备 spec 顶层与 spec.request 的 parent/prompt" + "(delegate.ts 的 startSubagentRunOnce 已双写;若仍报此错,说明宿主读取路径又变了," + "需对照该版本 subagent/lib/index.js 的 startActivation 实际读取路径补上第三处写入)。";
|
|
3828
|
+
}
|
|
3829
|
+
|
|
3830
|
+
// src/output-contract.ts
|
|
3831
|
+
var DEFAULT_OUTPUT_CONTRACTS = {
|
|
3832
|
+
"co-explorer": {
|
|
3833
|
+
type: "object",
|
|
3834
|
+
properties: {
|
|
3835
|
+
files: { type: "array", items: { type: "string" } },
|
|
3836
|
+
answer: { type: "string" }
|
|
3837
|
+
},
|
|
3838
|
+
required: ["files", "answer"]
|
|
3839
|
+
},
|
|
3840
|
+
"co-oracle": {
|
|
3841
|
+
type: "object",
|
|
3842
|
+
properties: {
|
|
3843
|
+
verdict: { type: "string", enum: ["pass", "fail", "unknown"] },
|
|
3844
|
+
reasons: { type: "array", items: { type: "string" } },
|
|
3845
|
+
anchors: { type: "array", items: { type: "string" } }
|
|
3846
|
+
},
|
|
3847
|
+
required: ["verdict", "reasons", "anchors"]
|
|
3848
|
+
},
|
|
3849
|
+
"co-librarian": {
|
|
3850
|
+
type: "object",
|
|
3851
|
+
properties: {
|
|
3852
|
+
sources: { type: "array", items: { type: "string" } },
|
|
3853
|
+
answer: { type: "string" }
|
|
3854
|
+
},
|
|
3855
|
+
required: ["sources", "answer"]
|
|
3856
|
+
},
|
|
3857
|
+
"co-designer": {
|
|
3858
|
+
type: "object",
|
|
3859
|
+
properties: {
|
|
3860
|
+
files: { type: "array", items: { type: "string" } },
|
|
3861
|
+
summary: { type: "string" }
|
|
3862
|
+
},
|
|
3863
|
+
required: ["files", "summary"]
|
|
3864
|
+
},
|
|
3865
|
+
"co-fixer": {
|
|
3866
|
+
type: "object",
|
|
3867
|
+
properties: {
|
|
3868
|
+
changed: { type: "array", items: { type: "string" } },
|
|
3869
|
+
verification: { type: "string" }
|
|
3870
|
+
},
|
|
3871
|
+
required: ["changed", "verification"]
|
|
3872
|
+
},
|
|
3873
|
+
"co-observer": {
|
|
3874
|
+
type: "object",
|
|
3875
|
+
properties: {
|
|
3876
|
+
findings: { type: "array", items: { type: "string" } },
|
|
3877
|
+
answer: { type: "string" }
|
|
3878
|
+
},
|
|
3879
|
+
required: ["findings", "answer"]
|
|
3880
|
+
},
|
|
3881
|
+
"co-council": {
|
|
3882
|
+
type: "object",
|
|
3883
|
+
properties: {
|
|
3884
|
+
verdict: { type: "string" },
|
|
3885
|
+
votes: { type: "array", items: { type: "string" } }
|
|
3886
|
+
},
|
|
3887
|
+
required: ["verdict", "votes"]
|
|
3888
|
+
},
|
|
3889
|
+
"co-planner": {
|
|
3890
|
+
type: "object",
|
|
3891
|
+
properties: {
|
|
3892
|
+
steps: { type: "array", items: { type: "string" } },
|
|
3893
|
+
risks: { type: "array", items: { type: "string" } }
|
|
3894
|
+
},
|
|
3895
|
+
required: ["steps", "risks"]
|
|
3896
|
+
},
|
|
3897
|
+
"co-rule-user": {
|
|
3898
|
+
type: "object",
|
|
3899
|
+
properties: {
|
|
3900
|
+
rules: { type: "array", items: { type: "string" } },
|
|
3901
|
+
conflicts: { type: "array", items: { type: "string" } }
|
|
3902
|
+
},
|
|
3903
|
+
required: ["rules", "conflicts"]
|
|
3904
|
+
},
|
|
3905
|
+
"co-rule-project": {
|
|
3906
|
+
type: "object",
|
|
3907
|
+
properties: {
|
|
3908
|
+
rules: { type: "array", items: { type: "string" } },
|
|
3909
|
+
conflicts: { type: "array", items: { type: "string" } }
|
|
3910
|
+
},
|
|
3911
|
+
required: ["rules", "conflicts"]
|
|
3912
|
+
},
|
|
3913
|
+
"co-rule-app": {
|
|
3914
|
+
type: "object",
|
|
3915
|
+
properties: {
|
|
3916
|
+
rules: { type: "array", items: { type: "string" } },
|
|
3917
|
+
conflicts: { type: "array", items: { type: "string" } }
|
|
3918
|
+
},
|
|
3919
|
+
required: ["rules", "conflicts"]
|
|
3920
|
+
},
|
|
3921
|
+
"co-orchestrator": {
|
|
3922
|
+
type: "object",
|
|
3923
|
+
properties: {
|
|
3924
|
+
summary: { type: "string" }
|
|
3925
|
+
},
|
|
3926
|
+
required: ["summary"]
|
|
3927
|
+
}
|
|
3928
|
+
};
|
|
3929
|
+
var OUTPUT_CONTRACT_PROMPT_MAX_CHARS = 400;
|
|
3930
|
+
function normalizeLevel(raw) {
|
|
3931
|
+
return raw === "lite" || raw === "strict" ? raw : "off";
|
|
3932
|
+
}
|
|
3933
|
+
function resolveOutputContract(skillName, levelOverride) {
|
|
3934
|
+
const level = normalizeLevel(levelOverride);
|
|
3935
|
+
const table = DEFAULT_OUTPUT_CONTRACTS;
|
|
3936
|
+
const key = (typeof skillName === "string" ? skillName : "").trim();
|
|
3937
|
+
let schema = table[key];
|
|
3938
|
+
if (!schema && key.length > 0 && !key.startsWith("co-"))
|
|
3939
|
+
schema = table["co-" + key];
|
|
3940
|
+
return { schema, level };
|
|
3941
|
+
}
|
|
3942
|
+
var MAX_VALIDATE_DEPTH = 32;
|
|
3943
|
+
var MAX_ERRORS = 20;
|
|
3944
|
+
function validateAgainstContract(value, schema) {
|
|
3945
|
+
const errors = [];
|
|
3946
|
+
walkContract(value, schema, "$", errors, 0);
|
|
3947
|
+
if (errors.length === 0)
|
|
3948
|
+
return { ok: true };
|
|
3949
|
+
return { ok: false, errors: errors.slice(0, MAX_ERRORS) };
|
|
3950
|
+
}
|
|
3951
|
+
function walkContract(value, schema, path, errors, depth) {
|
|
3952
|
+
if (errors.length >= MAX_ERRORS)
|
|
3953
|
+
return;
|
|
3954
|
+
if (depth > MAX_VALIDATE_DEPTH) {
|
|
3955
|
+
errors.push(path + ": 契约嵌套超过 " + MAX_VALIDATE_DEPTH + " 层,已中止校验");
|
|
3956
|
+
return;
|
|
3957
|
+
}
|
|
3958
|
+
if (schema.const !== undefined) {
|
|
3959
|
+
if (!sameLiteral(value, schema.const)) {
|
|
3960
|
+
errors.push(path + ": 期望常量 " + JSON.stringify(schema.const) + ",实际 " + describeValue2(value));
|
|
3961
|
+
return;
|
|
3962
|
+
}
|
|
3963
|
+
}
|
|
3964
|
+
if (Array.isArray(schema.enum) && schema.enum.length > 0) {
|
|
3965
|
+
if (!schema.enum.some((item) => sameLiteral(value, item))) {
|
|
3966
|
+
errors.push(path + ": 值不在 enum 白名单内(期望 " + schema.enum.map((v) => JSON.stringify(v)).join(" | ") + "),实际 " + describeValue2(value));
|
|
3967
|
+
return;
|
|
3968
|
+
}
|
|
3969
|
+
}
|
|
3970
|
+
if (Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
|
|
3971
|
+
const matched = schema.oneOf.some((branch) => validateAgainstContract(value, branch).ok);
|
|
3972
|
+
if (!matched) {
|
|
3973
|
+
errors.push(path + ": 不匹配 oneOf 的任何一支(期望 " + schema.oneOf.map((b) => typeLabel(b, 0)).join(" | ") + "),实际 " + describeValue2(value));
|
|
3974
|
+
}
|
|
3975
|
+
return;
|
|
3976
|
+
}
|
|
3977
|
+
if (schema.type !== undefined) {
|
|
3978
|
+
if (!matchesType(value, schema.type)) {
|
|
3979
|
+
errors.push(path + ": 期望 " + typeLabel(schema, 0) + ",实际 " + describeValue2(value));
|
|
3980
|
+
return;
|
|
3981
|
+
}
|
|
3982
|
+
}
|
|
3983
|
+
const props = schema.properties;
|
|
3984
|
+
const isObjectLike = props !== undefined && isPlainObject(value);
|
|
3985
|
+
if (schema.type === "object" || isObjectLike) {
|
|
3986
|
+
if (isPlainObject(value)) {
|
|
3987
|
+
for (const name of schema.required ?? []) {
|
|
3988
|
+
if (!Object.prototype.hasOwnProperty.call(value, name) || value[name] === undefined) {
|
|
3989
|
+
const child = props?.[name];
|
|
3990
|
+
errors.push(path + "." + name + ": 缺少必填字段(期望 " + (child ? typeLabel(child, 0) : "值") + ")");
|
|
3991
|
+
}
|
|
3992
|
+
}
|
|
3993
|
+
for (const [name, child] of Object.entries(props ?? {})) {
|
|
3994
|
+
if (!Object.prototype.hasOwnProperty.call(value, name) || value[name] === undefined)
|
|
3995
|
+
continue;
|
|
3996
|
+
walkContract(value[name], child, path + "." + name, errors, depth + 1);
|
|
3997
|
+
if (errors.length >= MAX_ERRORS)
|
|
3998
|
+
return;
|
|
3999
|
+
}
|
|
4000
|
+
}
|
|
4001
|
+
return;
|
|
4002
|
+
}
|
|
4003
|
+
if (schema.type === "array" && Array.isArray(value)) {
|
|
4004
|
+
const items = schema.items;
|
|
4005
|
+
if (items) {
|
|
4006
|
+
for (let i = 0;i < value.length; i++) {
|
|
4007
|
+
walkContract(value[i], items, path + "[" + i + "]", errors, depth + 1);
|
|
4008
|
+
if (errors.length >= MAX_ERRORS)
|
|
4009
|
+
return;
|
|
4010
|
+
}
|
|
4011
|
+
}
|
|
4012
|
+
}
|
|
4013
|
+
}
|
|
4014
|
+
function matchesType(value, type) {
|
|
4015
|
+
switch (type) {
|
|
4016
|
+
case "object":
|
|
4017
|
+
return isPlainObject(value);
|
|
4018
|
+
case "array":
|
|
4019
|
+
return Array.isArray(value);
|
|
4020
|
+
case "string":
|
|
4021
|
+
return typeof value === "string";
|
|
4022
|
+
case "number":
|
|
4023
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
4024
|
+
case "boolean":
|
|
4025
|
+
return typeof value === "boolean";
|
|
4026
|
+
default:
|
|
4027
|
+
return false;
|
|
4028
|
+
}
|
|
4029
|
+
}
|
|
4030
|
+
function isPlainObject(value) {
|
|
4031
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
4032
|
+
}
|
|
4033
|
+
function sameLiteral(value, literal) {
|
|
4034
|
+
return typeof value === typeof literal && value === literal;
|
|
4035
|
+
}
|
|
4036
|
+
function describeValue2(value) {
|
|
4037
|
+
if (value === null)
|
|
4038
|
+
return "null";
|
|
4039
|
+
if (Array.isArray(value))
|
|
4040
|
+
return "array(" + value.length + ")";
|
|
4041
|
+
if (typeof value === "object")
|
|
4042
|
+
return "object";
|
|
4043
|
+
if (typeof value === "string") {
|
|
4044
|
+
const text = value.length > 24 ? value.slice(0, 24) + "…" : value;
|
|
4045
|
+
return "string(" + JSON.stringify(text) + ")";
|
|
4046
|
+
}
|
|
4047
|
+
if (typeof value === "number")
|
|
4048
|
+
return "number(" + String(value) + ")";
|
|
4049
|
+
if (typeof value === "boolean")
|
|
4050
|
+
return "boolean(" + String(value) + ")";
|
|
4051
|
+
return typeof value;
|
|
4052
|
+
}
|
|
4053
|
+
function typeLabel(schema, depth) {
|
|
4054
|
+
if (depth > 6)
|
|
4055
|
+
return "…";
|
|
4056
|
+
if (schema.const !== undefined)
|
|
4057
|
+
return JSON.stringify(schema.const);
|
|
4058
|
+
if (Array.isArray(schema.enum) && schema.enum.length > 0) {
|
|
4059
|
+
return schema.enum.map((v) => JSON.stringify(v)).join("|");
|
|
4060
|
+
}
|
|
4061
|
+
if (Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
|
|
4062
|
+
return "(" + schema.oneOf.map((b) => typeLabel(b, depth + 1)).join("|") + ")";
|
|
4063
|
+
}
|
|
4064
|
+
if (schema.type === "array")
|
|
4065
|
+
return schema.items ? typeLabel(schema.items, depth + 1) + "[]" : "array";
|
|
4066
|
+
if (schema.type === "object" || schema.properties) {
|
|
4067
|
+
const names = Object.keys(schema.properties ?? {});
|
|
4068
|
+
return names.length > 0 ? "object{" + names.join(",") + "}" : "object";
|
|
4069
|
+
}
|
|
4070
|
+
return schema.type ?? "any";
|
|
4071
|
+
}
|
|
4072
|
+
function describeContractForPrompt(schema) {
|
|
4073
|
+
const required = new Set(schema.required ?? []);
|
|
4074
|
+
const props = schema.properties ?? {};
|
|
4075
|
+
const lines = [
|
|
4076
|
+
"输出契约:最终回复只输出一个合法 JSON 对象(不要代码块包裹,不要额外解释):",
|
|
4077
|
+
"示例 " + JSON.stringify(exampleValue(schema, 0)) + ""
|
|
4078
|
+
];
|
|
4079
|
+
for (const name of Object.keys(props)) {
|
|
4080
|
+
const child = props[name];
|
|
4081
|
+
lines.push("- " + name + ": " + typeLabel(child, 0) + (required.has(name) ? "(必填)" : "(可选)"));
|
|
4082
|
+
}
|
|
4083
|
+
const text = lines.join(`
|
|
4084
|
+
`);
|
|
4085
|
+
if (text.length <= OUTPUT_CONTRACT_PROMPT_MAX_CHARS)
|
|
4086
|
+
return text;
|
|
4087
|
+
return text.slice(0, OUTPUT_CONTRACT_PROMPT_MAX_CHARS - 1) + "…";
|
|
4088
|
+
}
|
|
4089
|
+
function exampleValue(schema, depth) {
|
|
4090
|
+
if (depth > 6)
|
|
4091
|
+
return null;
|
|
4092
|
+
if (schema.const !== undefined)
|
|
4093
|
+
return schema.const;
|
|
4094
|
+
if (Array.isArray(schema.enum) && schema.enum.length > 0)
|
|
4095
|
+
return schema.enum[0];
|
|
4096
|
+
if (Array.isArray(schema.oneOf) && schema.oneOf.length > 0)
|
|
4097
|
+
return exampleValue(schema.oneOf[0], depth + 1);
|
|
4098
|
+
if (schema.type === "array")
|
|
4099
|
+
return schema.items ? [exampleValue(schema.items, depth + 1)] : [];
|
|
4100
|
+
if (schema.type === "object" || schema.properties) {
|
|
4101
|
+
const out = {};
|
|
4102
|
+
for (const [name, child] of Object.entries(schema.properties ?? {})) {
|
|
4103
|
+
out[name] = exampleValue(child, depth + 1);
|
|
4104
|
+
}
|
|
4105
|
+
return out;
|
|
4106
|
+
}
|
|
4107
|
+
if (schema.type === "number")
|
|
4108
|
+
return 0;
|
|
4109
|
+
if (schema.type === "boolean")
|
|
4110
|
+
return true;
|
|
4111
|
+
return "文本";
|
|
4112
|
+
}
|
|
4113
|
+
function extractJsonCandidate(text) {
|
|
4114
|
+
const raw = typeof text === "string" ? text : "";
|
|
4115
|
+
const trimmed = raw.trim();
|
|
4116
|
+
if (trimmed.length === 0)
|
|
4117
|
+
return { ok: false, reason: "结果为空,没有可校验的 JSON" };
|
|
4118
|
+
const candidates = [trimmed];
|
|
4119
|
+
const fence = /```(?:json|JSON)?[ \t]*\r?\n?([\s\S]*?)```/.exec(raw);
|
|
4120
|
+
if (fence && typeof fence[1] === "string") {
|
|
4121
|
+
const inner = fence[1].trim();
|
|
4122
|
+
if (inner.length > 0)
|
|
4123
|
+
candidates.push(inner);
|
|
4124
|
+
}
|
|
4125
|
+
const start = raw.indexOf("{");
|
|
4126
|
+
if (start >= 0) {
|
|
4127
|
+
const balanced = balancedBraceSlice(raw, start);
|
|
4128
|
+
if (balanced !== undefined)
|
|
4129
|
+
candidates.push(balanced);
|
|
4130
|
+
}
|
|
4131
|
+
for (const candidate of candidates) {
|
|
4132
|
+
try {
|
|
4133
|
+
return { ok: true, value: JSON.parse(candidate) };
|
|
4134
|
+
} catch {}
|
|
4135
|
+
}
|
|
4136
|
+
return { ok: false, reason: "未能从结果中提取 JSON(需要纯 JSON / ```json 代码块 / 正文中的 {...})" };
|
|
4137
|
+
}
|
|
4138
|
+
function balancedBraceSlice(text, start) {
|
|
4139
|
+
const MAX_SCAN = 1048576;
|
|
4140
|
+
const limit = Math.min(text.length, start + MAX_SCAN);
|
|
4141
|
+
let depth = 0;
|
|
4142
|
+
let inString = false;
|
|
4143
|
+
let escaped = false;
|
|
4144
|
+
for (let i = start;i < limit; i++) {
|
|
4145
|
+
const ch = text[i];
|
|
4146
|
+
if (inString) {
|
|
4147
|
+
if (escaped)
|
|
4148
|
+
escaped = false;
|
|
4149
|
+
else if (ch === "\\")
|
|
4150
|
+
escaped = true;
|
|
4151
|
+
else if (ch === '"')
|
|
4152
|
+
inString = false;
|
|
4153
|
+
continue;
|
|
4154
|
+
}
|
|
4155
|
+
if (ch === '"') {
|
|
4156
|
+
inString = true;
|
|
4157
|
+
continue;
|
|
4158
|
+
}
|
|
4159
|
+
if (ch === "{")
|
|
4160
|
+
depth++;
|
|
4161
|
+
else if (ch === "}") {
|
|
4162
|
+
depth--;
|
|
4163
|
+
if (depth === 0)
|
|
4164
|
+
return text.slice(start, i + 1);
|
|
4165
|
+
}
|
|
4166
|
+
}
|
|
4167
|
+
return;
|
|
4168
|
+
}
|
|
4169
|
+
function validateContractText(text, schema) {
|
|
4170
|
+
const extracted = extractJsonCandidate(text);
|
|
4171
|
+
if (!extracted.ok)
|
|
4172
|
+
return { ok: false, errors: ["$: " + extracted.reason] };
|
|
4173
|
+
return validateAgainstContract(extracted.value, schema);
|
|
4174
|
+
}
|
|
4175
|
+
function formatContractViolation(errors) {
|
|
4176
|
+
const text = "[契约] 未满足:" + (errors.length > 0 ? errors.join(";") : "未提供错误详情");
|
|
4177
|
+
return text.length > 500 ? text.slice(0, 499) + "…" : text;
|
|
4178
|
+
}
|
|
4179
|
+
|
|
3737
4180
|
// src/delegate.ts
|
|
3738
4181
|
var PARALLEL_TOOL_DISCIPLINE = "【并行工具纪律】① 同一条消息内一次性发起全部独立只读查询,不要发一个等一个。" + "② 真并发的只读工具:read、read_image、web_search、web_fetch、subagent。" + "注意 glob、grep 虽然只读但不可并发(会被串行执行),别指望它们并行。" + "③ 可并发调用必须连续相邻,中间不要插 bash、edit、write、grep 等串行调用," + "否则其后调用另起一组、并发度归零([read, bash, read] 并发度=1,[read, read, read, bash] 并发度=3)。" + "④ 不要依赖平台真并发:需要 N 个互不依赖的子任务时,优先用 delegate_batch" + "(内部 Promise.allSettled,不依赖 agent loop 调度;该工具可用时)。";
|
|
3739
4182
|
var DELEGATE_PERSONA = "你是被委派的专职代理:严格遵循任务消息中的角色定义、关键约束、输出格式与工具指令,并完成末尾的具体任务。" + "你的首条用户消息(下方任务书)已含 `--- 你的具体任务 ---` 分隔符,即身份判据成立:不要调用 skill 工具加载 co-orchestrator 技能——技能指令已由 brief 注入。" + PARALLEL_TOOL_DISCIPLINE;
|
|
@@ -3861,6 +4304,24 @@ function upsertDegradeNote(notes, note) {
|
|
|
3861
4304
|
else
|
|
3862
4305
|
notes.push(note);
|
|
3863
4306
|
}
|
|
4307
|
+
function notifyRouteDegrade(onDegrade, note) {
|
|
4308
|
+
if (onDegrade === undefined)
|
|
4309
|
+
return;
|
|
4310
|
+
try {
|
|
4311
|
+
onDegrade(note);
|
|
4312
|
+
} catch {}
|
|
4313
|
+
}
|
|
4314
|
+
function describeAvailableProviders(available) {
|
|
4315
|
+
const ids = [...available].filter((id) => typeof id === "string" && id.length > 0);
|
|
4316
|
+
if (ids.length === 0)
|
|
4317
|
+
return "provider 注册表为空";
|
|
4318
|
+
return ids.slice(0, 8).join("/") + (ids.length > 8 ? "/…" : "");
|
|
4319
|
+
}
|
|
4320
|
+
function describeSupportedEfforts(efforts) {
|
|
4321
|
+
if (efforts === undefined || efforts.length === 0)
|
|
4322
|
+
return "该模型未暴露任何强度档位";
|
|
4323
|
+
return efforts.join("/");
|
|
4324
|
+
}
|
|
3864
4325
|
var PRESET_REJECTED = /PRESET_UNAVAILABLE|agent-preset\/(not-found|invalid)|Unknown agent preset|agent preset|preset revision|preset.*unavailable/i;
|
|
3865
4326
|
var TOOL_FILTER_REJECTED = /unknown global tool|toolFilter|tool filter|capabilit/i;
|
|
3866
4327
|
var RESTRICTABLE_NAMES_IN_ERROR = /known global tools:\s*([^\n;]*)/i;
|
|
@@ -4011,7 +4472,7 @@ async function startSubagentRunOnce(ctx, provider, spec) {
|
|
|
4011
4472
|
ctx?.logger?.warn?.("[cohub] startSubagentRun 无可用 signal:子运行不可中止(父轮停止无法回收)");
|
|
4012
4473
|
}
|
|
4013
4474
|
const prompt = spec.persona !== undefined ? [{ type: "text", text: spec.persona }, ...spec.prompt] : spec.prompt;
|
|
4014
|
-
const
|
|
4475
|
+
const activationSpec = {
|
|
4015
4476
|
provider,
|
|
4016
4477
|
label: spec.label,
|
|
4017
4478
|
prompt,
|
|
@@ -4026,7 +4487,22 @@ async function startSubagentRunOnce(ctx, provider, spec) {
|
|
|
4026
4487
|
},
|
|
4027
4488
|
...signal !== undefined ? { signal } : {},
|
|
4028
4489
|
delivery: "caller"
|
|
4029
|
-
}
|
|
4490
|
+
};
|
|
4491
|
+
assertDualActivationSpec(activationSpec, spec.label);
|
|
4492
|
+
let receipt;
|
|
4493
|
+
try {
|
|
4494
|
+
receipt = await subagents.startActivation(activationSpec);
|
|
4495
|
+
} catch (err) {
|
|
4496
|
+
const attribution = describeActivationContractError(err);
|
|
4497
|
+
if (attribution === undefined)
|
|
4498
|
+
throw err;
|
|
4499
|
+
const original = err instanceof Error ? err.message : String(err);
|
|
4500
|
+
const wrapped = new Error(`cohub: startActivation 失败:${original}
|
|
4501
|
+
${attribution}`);
|
|
4502
|
+
if (err instanceof Error && typeof err.stack === "string")
|
|
4503
|
+
wrapped.stack = err.stack;
|
|
4504
|
+
throw wrapped;
|
|
4505
|
+
}
|
|
4030
4506
|
applyChildToolFilterDirectly(ctx, receipt.childId, spec.toolFilter, spec.degradeNotes);
|
|
4031
4507
|
return {
|
|
4032
4508
|
id: receipt.childId,
|
|
@@ -4266,6 +4742,9 @@ function resolveSkillAndRoute(requestedSkill, getRoutes, ctx, logger) {
|
|
|
4266
4742
|
const route = (getRoutes() ?? []).find((s) => s.name === requested);
|
|
4267
4743
|
return { skill, route, fallback, ...note === undefined ? {} : { note } };
|
|
4268
4744
|
}
|
|
4745
|
+
function resolveRouteOutputContract(skillName, route) {
|
|
4746
|
+
return resolveOutputContract(skillName, route?.outputContract);
|
|
4747
|
+
}
|
|
4269
4748
|
function formatSkillLabel(skill, fallback) {
|
|
4270
4749
|
return fallback ? skill.name + " (default:" + DEFAULT_FALLBACK_SKILL + ")" : skill.name;
|
|
4271
4750
|
}
|
|
@@ -4287,7 +4766,7 @@ function skillTierDefaults(skillName) {
|
|
|
4287
4766
|
return;
|
|
4288
4767
|
}
|
|
4289
4768
|
}
|
|
4290
|
-
async function buildAgentOptions(route, ctx, skillName) {
|
|
4769
|
+
async function buildAgentOptions(route, ctx, skillName, onDegrade) {
|
|
4291
4770
|
const tier = skillTierDefaults(skillName);
|
|
4292
4771
|
if (!route) {
|
|
4293
4772
|
if (!tier)
|
|
@@ -4310,6 +4789,12 @@ async function buildAgentOptions(route, ctx, skillName) {
|
|
|
4310
4789
|
if (effort) {
|
|
4311
4790
|
ctx.logger?.warn?.("[cohub route] " + route.name + ' 配置的 provider "' + route.provider + '" 当前不可用,推理强度 "' + effort + '" 一并忽略(完全继承父会话)');
|
|
4312
4791
|
}
|
|
4792
|
+
notifyRouteDegrade(onDegrade, {
|
|
4793
|
+
id: "route-provider",
|
|
4794
|
+
what: "路由 provider 未注册",
|
|
4795
|
+
effect: "该 skill 的 provider/model 全部未生效,子代理继承父会话模型",
|
|
4796
|
+
reason: '配置的 provider "' + route.provider + '" 未注册(可用:' + describeAvailableProviders(available) + ")"
|
|
4797
|
+
});
|
|
4313
4798
|
return;
|
|
4314
4799
|
}
|
|
4315
4800
|
const options = { provider: route.provider };
|
|
@@ -4320,6 +4805,12 @@ async function buildAgentOptions(route, ctx, skillName) {
|
|
|
4320
4805
|
if (fallback) {
|
|
4321
4806
|
options.model = fallback;
|
|
4322
4807
|
ctx.logger?.info?.("[cohub route] " + route.name + ' 未配置 model,回退为 provider "' + route.provider + '" 的首个模型 "' + fallback + '"');
|
|
4808
|
+
notifyRouteDegrade(onDegrade, {
|
|
4809
|
+
id: "route-model",
|
|
4810
|
+
what: "路由未配置 model",
|
|
4811
|
+
effect: "该 skill 实际使用回退模型",
|
|
4812
|
+
reason: 'provider "' + route.provider + '" 未配置 model,已回退到该目录首个模型 "' + fallback + '"'
|
|
4813
|
+
});
|
|
4323
4814
|
} else {
|
|
4324
4815
|
ctx.logger?.warn?.("[cohub route] " + route.name + ' 未配置 model,且无法解析 provider "' + route.provider + '" 的可用模型;将继承父会话模型(可能因模型不属于该 provider 而失败)');
|
|
4325
4816
|
}
|
|
@@ -4331,9 +4822,17 @@ async function buildAgentOptions(route, ctx, skillName) {
|
|
|
4331
4822
|
const effectiveEffort = effort ?? normalizeReasoningEffort(tier?.reasoningEffort);
|
|
4332
4823
|
if (effectiveEffort) {
|
|
4333
4824
|
const eff = effectiveEffort;
|
|
4334
|
-
const
|
|
4335
|
-
if (supported === false) {
|
|
4825
|
+
const support = await resolveReasoningEffortSupport(route.provider, options.model, eff, ctx);
|
|
4826
|
+
if (support.supported === false) {
|
|
4336
4827
|
ctx.logger?.warn?.("[cohub route] " + route.name + ' 的模型 "' + route.provider + "/" + String(options.model) + '" 不支持推理强度 "' + eff + '",已忽略该强度(按模型默认档执行)');
|
|
4828
|
+
if ((support.efforts?.length ?? 0) > 0) {
|
|
4829
|
+
notifyRouteDegrade(onDegrade, {
|
|
4830
|
+
id: "route-effort",
|
|
4831
|
+
what: "推理强度未生效",
|
|
4832
|
+
effect: "该强度已丢弃,子代理按模型默认档执行",
|
|
4833
|
+
reason: '配置的强度 "' + eff + '" 不被模型 "' + route.provider + "/" + String(options.model) + '" 支持(支持:' + describeSupportedEfforts(support.efforts) + ")"
|
|
4834
|
+
});
|
|
4835
|
+
}
|
|
4337
4836
|
} else {
|
|
4338
4837
|
options.reasoningEffort = eff;
|
|
4339
4838
|
}
|
|
@@ -4464,20 +4963,21 @@ async function budgetSubagentResult(ctx, exec, raw, options) {
|
|
|
4464
4963
|
return text;
|
|
4465
4964
|
}
|
|
4466
4965
|
}
|
|
4467
|
-
async function
|
|
4966
|
+
async function resolveReasoningEffortSupport(provider, model, effort, ctx) {
|
|
4468
4967
|
if (!model)
|
|
4469
|
-
return;
|
|
4968
|
+
return { supported: undefined };
|
|
4470
4969
|
const resolve = ctx?.llm?.resolveModelInfo;
|
|
4471
4970
|
if (typeof resolve !== "function")
|
|
4472
|
-
return;
|
|
4971
|
+
return { supported: undefined };
|
|
4473
4972
|
try {
|
|
4474
4973
|
const info = await resolve.call(ctx.llm, provider, model);
|
|
4475
4974
|
const efforts = info?.reasoning?.efforts;
|
|
4476
4975
|
if (!Array.isArray(efforts) || efforts.length === 0)
|
|
4477
|
-
return false;
|
|
4478
|
-
|
|
4976
|
+
return { supported: false, efforts: [] };
|
|
4977
|
+
const ids = efforts.map((e) => e && typeof e.id === "string" ? e.id : "").filter((id) => id.length > 0);
|
|
4978
|
+
return { supported: ids.includes(effort), efforts: ids };
|
|
4479
4979
|
} catch {
|
|
4480
|
-
return;
|
|
4980
|
+
return { supported: undefined };
|
|
4481
4981
|
}
|
|
4482
4982
|
}
|
|
4483
4983
|
async function resolveProviderFallbackModel(provider, ctx) {
|
|
@@ -4515,12 +5015,21 @@ function resolveContractText(envContract, envSig, ctx, fpOverride) {
|
|
|
4515
5015
|
` + picked.text;
|
|
4516
5016
|
return { text, source: picked.source };
|
|
4517
5017
|
}
|
|
5018
|
+
var CONTRACT_REWRITE_MAX_CHARS = 8000;
|
|
5019
|
+
function buildOutputContractBlock(schema) {
|
|
5020
|
+
return `
|
|
5021
|
+
|
|
5022
|
+
--- 输出契约(必须遵守) ---
|
|
5023
|
+
|
|
5024
|
+
` + describeContractForPrompt(schema) + `
|
|
5025
|
+
`;
|
|
5026
|
+
}
|
|
4518
5027
|
function buildDelegatePrompt(params) {
|
|
4519
5028
|
return (params.skill.brief || params.skill.content) + params.contractText + `
|
|
4520
5029
|
|
|
4521
5030
|
--- 你的具体任务 ---
|
|
4522
5031
|
|
|
4523
|
-
` + params.userPrompt + (params.retryNote ?? "");
|
|
5032
|
+
` + params.userPrompt + (params.retryNote ?? "") + (params.outputContractText ?? "");
|
|
4524
5033
|
}
|
|
4525
5034
|
function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
|
|
4526
5035
|
const envContract = createEnvContract(config);
|
|
@@ -4589,13 +5098,17 @@ function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
4589
5098
|
ctx.logger?.info?.("[cohub schedule] 生效调度参数:batch=" + (schedule?.maxParallelBatch ?? 5) + " wallMs=" + (schedule?.wallClockBudgetMs ?? WALL_CLOCK_BUDGET_MS));
|
|
4590
5099
|
const { skill, route, fallback: skillFallback, note: skillNote } = resolveSkillAndRoute(args.skill, getRoutes, ctx);
|
|
4591
5100
|
const skillTag = formatSkillLabel(skill, skillFallback);
|
|
5101
|
+
const outputContract = resolveRouteOutputContract(skill.name, route);
|
|
5102
|
+
const contractActive = outputContract.level !== "off" && outputContract.schema !== undefined;
|
|
5103
|
+
const outputContractText = contractActive && outputContract.schema !== undefined ? buildOutputContractBlock(outputContract.schema) : "";
|
|
5104
|
+
const contractState = { violated: false };
|
|
4592
5105
|
const brief = skill.brief?.trim();
|
|
4593
5106
|
if (!brief) {
|
|
4594
5107
|
ctx.logger?.warn?.('delegate: skill "' + skillTag + '" 缺少 brief,回退完整 content');
|
|
4595
5108
|
}
|
|
4596
|
-
const agentOptions = await buildAgentOptions(route, ctx, skill.name);
|
|
4597
|
-
const toolFilter = resolveSkillToolFilter(skill.name, config.toolFilter?.enabled ?? true, ctx.logger);
|
|
4598
5109
|
const degradeNotes = [];
|
|
5110
|
+
const agentOptions = await buildAgentOptions(route, ctx, skill.name, (note) => upsertDegradeNote(degradeNotes, note));
|
|
5111
|
+
const toolFilter = resolveSkillToolFilter(skill.name, config.toolFilter?.enabled ?? true, ctx.logger);
|
|
4599
5112
|
if (skillNote !== undefined) {
|
|
4600
5113
|
upsertDegradeNote(degradeNotes, {
|
|
4601
5114
|
id: "skill",
|
|
@@ -4615,7 +5128,9 @@ function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
4615
5128
|
let lastPartialBudget = "";
|
|
4616
5129
|
const stallState = { last: null };
|
|
4617
5130
|
let retries = 0;
|
|
4618
|
-
|
|
5131
|
+
let contractExtraAttempts = 0;
|
|
5132
|
+
let contractRewriteNote = "";
|
|
5133
|
+
for (let attempt = 0;attempt <= retry.maxRetries + contractExtraAttempts; attempt++) {
|
|
4619
5134
|
const attemptStartedAt = Date.now();
|
|
4620
5135
|
const attemptNo = attempt + 1;
|
|
4621
5136
|
const reportAttempt = (childSessionId, outcome, stopReason) => {
|
|
@@ -4637,14 +5152,15 @@ function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
4637
5152
|
}
|
|
4638
5153
|
};
|
|
4639
5154
|
const stallNote = stallState.last ? ";停滞诊断:" + stallState.last.diagnostics : "";
|
|
4640
|
-
const retryNote = attempt > 0 ? `
|
|
5155
|
+
const retryNote = contractRewriteNote.length > 0 ? contractRewriteNote : attempt > 0 ? `
|
|
4641
5156
|
|
|
4642
5157
|
[重试 #` + attempt + "] 上一次执行中止,原因:" + lastReason + (lastDiagnostic === undefined ? "" : ";诊断:" + lastDiagnostic) + ";已完成部分:" + (lastPartial || "(无)") + stallNote + "。请从中断处继续,不要重复已完成步骤。" : "";
|
|
4643
5158
|
const promptText = buildDelegatePrompt({
|
|
4644
5159
|
skill,
|
|
4645
5160
|
contractText,
|
|
4646
5161
|
userPrompt: args.prompt,
|
|
4647
|
-
retryNote
|
|
5162
|
+
retryNote,
|
|
5163
|
+
outputContractText
|
|
4648
5164
|
});
|
|
4649
5165
|
const ac = stall.enabled ? new AbortController : null;
|
|
4650
5166
|
let onExecAbort = null;
|
|
@@ -4776,13 +5292,33 @@ function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
4776
5292
|
}
|
|
4777
5293
|
if (outcome?.stopReason === "completed") {
|
|
4778
5294
|
reportAttempt(String(run?.id ?? ""), "completed", "completed");
|
|
4779
|
-
const
|
|
5295
|
+
const rawResult = contentText(outcome.output);
|
|
5296
|
+
let contractMark = "";
|
|
5297
|
+
if (contractActive && outputContract.schema !== undefined) {
|
|
5298
|
+
const check = validateContractText(rawResult, outputContract.schema);
|
|
5299
|
+
if (!check.ok) {
|
|
5300
|
+
if (outputContract.level === "strict" && contractExtraAttempts === 0 && rawResult.length < CONTRACT_REWRITE_MAX_CHARS && outerSignal?.aborted !== true) {
|
|
5301
|
+
contractExtraAttempts = 1;
|
|
5302
|
+
contractRewriteNote = `
|
|
5303
|
+
|
|
5304
|
+
[契约重写] 上次输出未满足以下约束:` + check.errors.join(";") + "。请重新输出一个完整合法的 JSON 对象(不要解释)。";
|
|
5305
|
+
ctx.logger?.info?.("[cohub contract] " + skill.name + " strict:输出未满足契约,重写一次");
|
|
5306
|
+
continue;
|
|
5307
|
+
}
|
|
5308
|
+
contractState.violated = true;
|
|
5309
|
+
contractMark = `
|
|
5310
|
+
|
|
5311
|
+
` + formatContractViolation(check.errors);
|
|
5312
|
+
ctx.logger?.warn?.("[cohub contract] " + skill.name + " 输出未满足契约(" + outputContract.level + "):" + check.errors.join(";"));
|
|
5313
|
+
}
|
|
5314
|
+
}
|
|
5315
|
+
const budgeted = await budgetSubagentResult(ctx, exec, rawResult, {
|
|
4780
5316
|
maxChars: resolveSkillResultMaxChars(budget, skill.name),
|
|
4781
5317
|
scope: "delegate",
|
|
4782
5318
|
label: skillTag,
|
|
4783
5319
|
enabled: budget.enabled
|
|
4784
5320
|
});
|
|
4785
|
-
return budgeted + formatDegradeNotes(degradeNotes);
|
|
5321
|
+
return budgeted + formatDegradeNotes(degradeNotes) + contractMark;
|
|
4786
5322
|
}
|
|
4787
5323
|
lastReason = String(outcome?.stopReason ?? "unknown");
|
|
4788
5324
|
lastDiagnostic = typeof outcome?.diagnostic === "string" ? outcome.diagnostic : undefined;
|
|
@@ -4918,6 +5454,11 @@ function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
4918
5454
|
}
|
|
4919
5455
|
}
|
|
4920
5456
|
const foregroundText = await runAttempts(exec.signal);
|
|
5457
|
+
if (contractState.violated) {
|
|
5458
|
+
try {
|
|
5459
|
+
exec?.onDelegateResult?.({ skill: skill.name, contractViolated: true });
|
|
5460
|
+
} catch {}
|
|
5461
|
+
}
|
|
4921
5462
|
maybeDeferTodoNudge(exec);
|
|
4922
5463
|
if (args.background === true && bgFallbackReason !== undefined) {
|
|
4923
5464
|
return foregroundText + `
|
|
@@ -5154,6 +5695,45 @@ function createCouncilTool(config, ctx) {
|
|
|
5154
5695
|
|
|
5155
5696
|
// src/delegate_batch.ts
|
|
5156
5697
|
import { defineTool as defineTool3 } from "@deepseek-ai/dsh-tools";
|
|
5698
|
+
|
|
5699
|
+
// src/granularity.ts
|
|
5700
|
+
var MAX_TASK_DEMANDS = 3;
|
|
5701
|
+
var MAX_TASK_DOMAINS = 2;
|
|
5702
|
+
function usableCount(value) {
|
|
5703
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
5704
|
+
return;
|
|
5705
|
+
const n = Math.floor(value);
|
|
5706
|
+
return n > 0 ? n : undefined;
|
|
5707
|
+
}
|
|
5708
|
+
function validateTaskScope(scope) {
|
|
5709
|
+
if (scope === undefined || scope === null || typeof scope !== "object")
|
|
5710
|
+
return { ok: true };
|
|
5711
|
+
const demands = usableCount(scope.demands);
|
|
5712
|
+
const domains = Array.isArray(scope.domains) ? scope.domains.filter((d) => typeof d === "string" && d.trim().length > 0) : undefined;
|
|
5713
|
+
const overDemands = demands !== undefined && demands > MAX_TASK_DEMANDS;
|
|
5714
|
+
const overDomains = domains !== undefined && domains.length > MAX_TASK_DOMAINS;
|
|
5715
|
+
if (!overDemands && !overDomains)
|
|
5716
|
+
return { ok: true };
|
|
5717
|
+
const parts = [];
|
|
5718
|
+
const packages = [];
|
|
5719
|
+
if (overDemands && demands !== undefined) {
|
|
5720
|
+
parts.push(`可独立判定诉求 ${demands} 项(上限 ${MAX_TASK_DEMANDS})`);
|
|
5721
|
+
packages.push(Math.ceil(demands / MAX_TASK_DEMANDS));
|
|
5722
|
+
}
|
|
5723
|
+
if (overDomains && domains !== undefined) {
|
|
5724
|
+
const shown = domains.slice(0, 6).map((d) => d.trim()).join(", ");
|
|
5725
|
+
const more = domains.length > 6 ? ` 等 ${domains.length} 个` : "";
|
|
5726
|
+
parts.push(`模块域 ${domains.length} 个(上限 ${MAX_TASK_DOMAINS}):${shown}${more}`);
|
|
5727
|
+
packages.push(Math.ceil(domains.length / MAX_TASK_DOMAINS));
|
|
5728
|
+
}
|
|
5729
|
+
const packagesNeeded = Math.max(...packages);
|
|
5730
|
+
return {
|
|
5731
|
+
ok: false,
|
|
5732
|
+
error: `任务粒度超出单包硬上限:${parts.join(";")}。` + `建议拆分为 ${packagesNeeded} 个 task 分别派发(每个 ≤${MAX_TASK_DEMANDS} 诉求、≤${MAX_TASK_DOMAINS} 模块域),` + "拆完后各 task 可独立判定、独立验收,再由主代理汇总;若确认本任务本就该整体处理," + "重发时省略 scope 字段即可跳过本校验。"
|
|
5733
|
+
};
|
|
5734
|
+
}
|
|
5735
|
+
|
|
5736
|
+
// src/delegate_batch.ts
|
|
5157
5737
|
var BATCH_TASK_ID_ECHO_MAX = 40;
|
|
5158
5738
|
var KNOWN_SKILL_NAMES = COHUB_SKILLS.map((s) => s.name);
|
|
5159
5739
|
var SKILL_NAMES_TEXT = KNOWN_SKILL_NAMES.join(", ");
|
|
@@ -5169,6 +5749,66 @@ function assertKnownSkill(raw) {
|
|
|
5169
5749
|
};
|
|
5170
5750
|
}
|
|
5171
5751
|
var MAX_BATCH_SIZE = 20;
|
|
5752
|
+
var MAX_EVENTS_PER_TASK = 5;
|
|
5753
|
+
var BATCH_EVENT_DETAIL_MAX = 120;
|
|
5754
|
+
var TIMELINE_MAX_ROWS = 20;
|
|
5755
|
+
var TIMELINE_LINE_MAX_CHARS = 120;
|
|
5756
|
+
function clampEventDetail(raw) {
|
|
5757
|
+
const oneLine = String(raw ?? "").replace(/\s+/g, " ").trim();
|
|
5758
|
+
if (oneLine.length <= BATCH_EVENT_DETAIL_MAX)
|
|
5759
|
+
return oneLine;
|
|
5760
|
+
return oneLine.slice(0, BATCH_EVENT_DETAIL_MAX - 1) + "…";
|
|
5761
|
+
}
|
|
5762
|
+
function pushBatchEvent(events, event) {
|
|
5763
|
+
if (events.length >= MAX_EVENTS_PER_TASK)
|
|
5764
|
+
return false;
|
|
5765
|
+
events.push({
|
|
5766
|
+
taskId: event.taskId,
|
|
5767
|
+
phase: event.phase,
|
|
5768
|
+
at: event.at,
|
|
5769
|
+
...event.detail === undefined ? {} : { detail: clampEventDetail(event.detail) }
|
|
5770
|
+
});
|
|
5771
|
+
return true;
|
|
5772
|
+
}
|
|
5773
|
+
function withTiming(entry, startedAt, endedAt, runId) {
|
|
5774
|
+
if (typeof startedAt !== "number" || !Number.isFinite(startedAt))
|
|
5775
|
+
return entry;
|
|
5776
|
+
return {
|
|
5777
|
+
...entry,
|
|
5778
|
+
startedAt,
|
|
5779
|
+
endedAt,
|
|
5780
|
+
durationMs: Math.max(0, endedAt - startedAt),
|
|
5781
|
+
...typeof runId === "string" && runId.length > 0 ? { runId } : {}
|
|
5782
|
+
};
|
|
5783
|
+
}
|
|
5784
|
+
function renderTaskTimeline(results, eventsByTask) {
|
|
5785
|
+
const entries = [];
|
|
5786
|
+
for (let i = 0;i < results.length; i += 1) {
|
|
5787
|
+
const r = results[i];
|
|
5788
|
+
if (r === undefined)
|
|
5789
|
+
continue;
|
|
5790
|
+
const duration = typeof r.durationMs === "number" ? r.durationMs : typeof r.startedAt === "number" && typeof r.endedAt === "number" ? Math.max(0, r.endedAt - r.startedAt) : undefined;
|
|
5791
|
+
if (duration === undefined)
|
|
5792
|
+
continue;
|
|
5793
|
+
const chain = (eventsByTask[i] ?? []).map((e) => e.phase).join("→");
|
|
5794
|
+
let line = "- [" + firstLineClamped(r.id, BATCH_TASK_ID_ECHO_MAX) + "] " + r.status + " · 耗时 " + duration + "ms" + (chain.length > 0 ? " · " + chain : "");
|
|
5795
|
+
if (line.length > TIMELINE_LINE_MAX_CHARS)
|
|
5796
|
+
line = line.slice(0, TIMELINE_LINE_MAX_CHARS - 1) + "…";
|
|
5797
|
+
entries.push({ line, startedAt: typeof r.startedAt === "number" ? r.startedAt : r.endedAt ?? 0, order: i });
|
|
5798
|
+
}
|
|
5799
|
+
if (entries.length === 0)
|
|
5800
|
+
return "";
|
|
5801
|
+
entries.sort((a, b) => a.startedAt - b.startedAt || a.order - b.order);
|
|
5802
|
+
const rows = entries.map((e) => e.line);
|
|
5803
|
+
const shown = rows.length > TIMELINE_MAX_ROWS ? rows.slice(0, TIMELINE_MAX_ROWS) : rows;
|
|
5804
|
+
const overflow = rows.length - shown.length;
|
|
5805
|
+
return `## task 时间线
|
|
5806
|
+
` + shown.join(`
|
|
5807
|
+
`) + (overflow > 0 ? `
|
|
5808
|
+
…+` + overflow : "") + `
|
|
5809
|
+
|
|
5810
|
+
`;
|
|
5811
|
+
}
|
|
5172
5812
|
function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
5173
5813
|
const envContract = createEnvContract(config);
|
|
5174
5814
|
const envSig = createEnvSig(config);
|
|
@@ -5194,7 +5834,7 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
5194
5834
|
tasks: {
|
|
5195
5835
|
type: "array",
|
|
5196
5836
|
required: true,
|
|
5197
|
-
description: "任务列表(≤maxParallelBatch)。每项仅接受
|
|
5837
|
+
description: "任务列表(≤maxParallelBatch)。每项仅接受 4 个字段:id(可选) / skill(必填) / prompt(必填) / scope(可选,任务粒度声明);出现其它字段会被参数校验拒绝。",
|
|
5198
5838
|
items: {
|
|
5199
5839
|
type: "object",
|
|
5200
5840
|
additionalProperties: false,
|
|
@@ -5205,7 +5845,20 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
5205
5845
|
required: true,
|
|
5206
5846
|
description: "必填。合法值(" + KNOWN_SKILL_NAMES.length + " 选 1):" + SKILL_NAMES_TEXT + "。注意 co-orchestrator 为主代理,通常委派用其余 " + (KNOWN_SKILL_NAMES.length - 1) + " 个。"
|
|
5207
5847
|
},
|
|
5208
|
-
prompt: { type: "string", required: true, description: "必填,给该代理的具体任务(自包含)" }
|
|
5848
|
+
prompt: { type: "string", required: true, description: "必填,给该代理的具体任务(自包含)" },
|
|
5849
|
+
scope: {
|
|
5850
|
+
type: "object",
|
|
5851
|
+
additionalProperties: false,
|
|
5852
|
+
description: "可选,任务粒度声明:demands(可独立判定诉求数,上限 3)/ domains(模块域,上限 2)。" + "超限时本 task 直接落 error 并给出拆分建议(其它 task 照常执行);不传则跳过校验。",
|
|
5853
|
+
properties: {
|
|
5854
|
+
demands: { type: "number", description: "可选,可独立判定诉求数(每个需单独拍板/验收的点算 1),上限 3" },
|
|
5855
|
+
domains: {
|
|
5856
|
+
type: "array",
|
|
5857
|
+
description: "可选,模块域(受影响的模块名),上限 2",
|
|
5858
|
+
items: { type: "string" }
|
|
5859
|
+
}
|
|
5860
|
+
}
|
|
5861
|
+
}
|
|
5209
5862
|
}
|
|
5210
5863
|
}
|
|
5211
5864
|
}
|
|
@@ -5240,8 +5893,22 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
5240
5893
|
}
|
|
5241
5894
|
return { task, taskId, requestedSkill: skillFallback ? DEFAULT_FALLBACK_SKILL : raw, skillFallback };
|
|
5242
5895
|
});
|
|
5243
|
-
const
|
|
5896
|
+
const batchEvents = normalized.map(() => []);
|
|
5897
|
+
for (let i = 0;i < normalized.length; i += 1) {
|
|
5898
|
+
const seed = normalized[i];
|
|
5899
|
+
if (seed === undefined)
|
|
5900
|
+
continue;
|
|
5901
|
+
pushBatchEvent(batchEvents[i], {
|
|
5902
|
+
taskId: seed.taskId,
|
|
5903
|
+
phase: "queued",
|
|
5904
|
+
at: batchStartedAt,
|
|
5905
|
+
detail: seed.skillFallback ? "skill 缺失,兜底 " + DEFAULT_FALLBACK_SKILL : seed.requestedSkill
|
|
5906
|
+
});
|
|
5907
|
+
}
|
|
5908
|
+
const starts = await Promise.allSettled(normalized.map(async ({ task, taskId, requestedSkill, skillFallback }, index) => {
|
|
5244
5909
|
const startedAt = Date.now();
|
|
5910
|
+
const taskEvents = batchEvents[index];
|
|
5911
|
+
pushBatchEvent(taskEvents, { taskId, phase: "started", at: startedAt });
|
|
5245
5912
|
const skillCheck = assertKnownSkill(requestedSkill);
|
|
5246
5913
|
if (!skillCheck.ok) {
|
|
5247
5914
|
ctx.logger?.warn?.('[cohub delegate_batch] task "' + taskId + '" 的 skill 名 "' + requestedSkill + '" 不在合法名单内,已按错误返回(不再静默降级为 ' + DEFAULT_FALLBACK_SKILL + ")");
|
|
@@ -5259,6 +5926,24 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
5259
5926
|
skillError: skillCheck.error
|
|
5260
5927
|
};
|
|
5261
5928
|
}
|
|
5929
|
+
const scopeCheck = validateTaskScope(task.scope);
|
|
5930
|
+
if (!scopeCheck.ok) {
|
|
5931
|
+
ctx.logger?.warn?.('[cohub delegate_batch] task "' + taskId + '" 的 scope 超出单包粒度上限(诉求 ≤' + "3 / 模块域 ≤2),已按错误返回并给出拆分建议");
|
|
5932
|
+
return {
|
|
5933
|
+
taskId,
|
|
5934
|
+
skillName: requestedSkill,
|
|
5935
|
+
skillTag: requestedSkill,
|
|
5936
|
+
task,
|
|
5937
|
+
taskNotes: [],
|
|
5938
|
+
run: undefined,
|
|
5939
|
+
ac: undefined,
|
|
5940
|
+
onExecAbort: null,
|
|
5941
|
+
startedAt,
|
|
5942
|
+
startError: undefined,
|
|
5943
|
+
skillError: undefined,
|
|
5944
|
+
scopeError: scopeCheck.error
|
|
5945
|
+
};
|
|
5946
|
+
}
|
|
5262
5947
|
const { skill, route, note: skillNote } = resolveSkillAndRoute(requestedSkill, getRoutes, ctx, ctx.logger);
|
|
5263
5948
|
const taskNotes = [];
|
|
5264
5949
|
if (skillNote !== undefined) {
|
|
@@ -5270,11 +5955,17 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
5270
5955
|
});
|
|
5271
5956
|
}
|
|
5272
5957
|
const skillTag = formatSkillLabel(skill, skillFallback);
|
|
5273
|
-
const
|
|
5958
|
+
const outputContract = resolveRouteOutputContract(skill.name, route);
|
|
5959
|
+
const contractActive = outputContract.level !== "off" && outputContract.schema !== undefined;
|
|
5960
|
+
const outputContractText = contractActive && outputContract.schema !== undefined ? buildOutputContractBlock(outputContract.schema) : "";
|
|
5961
|
+
const buildPrompt = (rewriteNote) => buildDelegatePrompt({
|
|
5274
5962
|
skill,
|
|
5275
5963
|
contractText,
|
|
5276
|
-
userPrompt: task.prompt
|
|
5964
|
+
userPrompt: task.prompt,
|
|
5965
|
+
...rewriteNote === undefined ? {} : { retryNote: rewriteNote },
|
|
5966
|
+
outputContractText
|
|
5277
5967
|
});
|
|
5968
|
+
const promptText = buildPrompt();
|
|
5278
5969
|
const toolFilter = resolveSkillToolFilter(skill.name, toolFilterEnabled, ctx.logger);
|
|
5279
5970
|
const agentPreset = resolveSkillAgentPreset(skill.name, presetEnabled);
|
|
5280
5971
|
const ac = new AbortController;
|
|
@@ -5291,19 +5982,35 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
5291
5982
|
}
|
|
5292
5983
|
}
|
|
5293
5984
|
try {
|
|
5294
|
-
const agentOptions = await buildAgentOptions(route, ctx, skill.name);
|
|
5295
|
-
const
|
|
5985
|
+
const agentOptions = await buildAgentOptions(route, ctx, skill.name, (note) => upsertDegradeNote(taskNotes, note));
|
|
5986
|
+
const spawnAgain = async (text, spawnSignal) => startSubagentRun(ctx, DEFAULT_SPAWN_TRANSPORT, {
|
|
5296
5987
|
label: `delegate_batch:${taskId}:${skillTag}`,
|
|
5297
|
-
prompt: [{ type: "text", text
|
|
5988
|
+
prompt: [{ type: "text", text }],
|
|
5298
5989
|
parent,
|
|
5299
5990
|
persona: DELEGATE_PERSONA,
|
|
5300
5991
|
...toolFilter !== undefined ? { toolFilter } : {},
|
|
5301
5992
|
...agentPreset !== undefined ? { agentPreset } : {},
|
|
5302
5993
|
...agentOptions ? { agentOptions } : {},
|
|
5303
|
-
signal:
|
|
5994
|
+
signal: spawnSignal,
|
|
5304
5995
|
degradeNotes: taskNotes
|
|
5305
5996
|
});
|
|
5306
|
-
|
|
5997
|
+
const run = await spawnAgain(promptText, ac.signal);
|
|
5998
|
+
return {
|
|
5999
|
+
taskId,
|
|
6000
|
+
skillName: skill.name,
|
|
6001
|
+
skillTag,
|
|
6002
|
+
task,
|
|
6003
|
+
taskNotes,
|
|
6004
|
+
run,
|
|
6005
|
+
ac,
|
|
6006
|
+
onExecAbort,
|
|
6007
|
+
startedAt,
|
|
6008
|
+
startError: undefined,
|
|
6009
|
+
skillError: undefined,
|
|
6010
|
+
outputContract,
|
|
6011
|
+
buildPrompt,
|
|
6012
|
+
spawnAgain
|
|
6013
|
+
};
|
|
5307
6014
|
} catch (startError) {
|
|
5308
6015
|
if (onExecAbort && exec.signal) {
|
|
5309
6016
|
try {
|
|
@@ -5314,6 +6021,7 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
5314
6021
|
}
|
|
5315
6022
|
}));
|
|
5316
6023
|
const results = [];
|
|
6024
|
+
const resultEvents = [];
|
|
5317
6025
|
const runs = [];
|
|
5318
6026
|
const perTaskNotes = [];
|
|
5319
6027
|
const degradeField = (notes) => {
|
|
@@ -5330,39 +6038,91 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
5330
6038
|
const rejectedId = seed?.taskId ?? `task-${index}`;
|
|
5331
6039
|
const rejectedNotes = [];
|
|
5332
6040
|
perTaskNotes.push({ taskId: rejectedId, notes: rejectedNotes });
|
|
5333
|
-
|
|
6041
|
+
const rejectedMessage = s.reason instanceof Error ? s.reason.message : String(s.reason);
|
|
6042
|
+
const rejectedAt = Date.now();
|
|
6043
|
+
const rejectedEvents = batchEvents[index] ?? [];
|
|
6044
|
+
pushBatchEvent(rejectedEvents, {
|
|
6045
|
+
taskId: rejectedId,
|
|
6046
|
+
phase: "failed",
|
|
6047
|
+
at: rejectedAt,
|
|
6048
|
+
detail: rejectedMessage
|
|
6049
|
+
});
|
|
6050
|
+
resultEvents.push(rejectedEvents);
|
|
6051
|
+
results.push(withTiming({
|
|
5334
6052
|
id: rejectedId,
|
|
5335
6053
|
skill: seed?.requestedSkill ?? DEFAULT_FALLBACK_SKILL,
|
|
5336
6054
|
status: "error",
|
|
5337
|
-
error:
|
|
6055
|
+
error: rejectedMessage,
|
|
5338
6056
|
...degradeField(rejectedNotes)
|
|
5339
|
-
});
|
|
6057
|
+
}, batchStartedAt, rejectedAt));
|
|
5340
6058
|
continue;
|
|
5341
6059
|
}
|
|
5342
6060
|
const val = s.value;
|
|
6061
|
+
if (val.scopeError) {
|
|
6062
|
+
perTaskNotes.push({ taskId: val.taskId, notes: val.taskNotes ?? [] });
|
|
6063
|
+
const scopeAt = Date.now();
|
|
6064
|
+
const scopeEvents = batchEvents[index] ?? [];
|
|
6065
|
+
pushBatchEvent(scopeEvents, {
|
|
6066
|
+
taskId: val.taskId,
|
|
6067
|
+
phase: "scope-error",
|
|
6068
|
+
at: scopeAt,
|
|
6069
|
+
detail: String(val.scopeError ?? "")
|
|
6070
|
+
});
|
|
6071
|
+
resultEvents.push(scopeEvents);
|
|
6072
|
+
results.push(withTiming({
|
|
6073
|
+
id: val.taskId,
|
|
6074
|
+
skill: val.skillTag,
|
|
6075
|
+
status: "error",
|
|
6076
|
+
error: val.scopeError,
|
|
6077
|
+
...degradeField(val.taskNotes ?? [])
|
|
6078
|
+
}, val.startedAt, scopeAt));
|
|
6079
|
+
continue;
|
|
6080
|
+
}
|
|
5343
6081
|
if (val.skillError) {
|
|
5344
6082
|
perTaskNotes.push({ taskId: val.taskId, notes: val.taskNotes ?? [] });
|
|
5345
|
-
|
|
6083
|
+
const skillErrAt = Date.now();
|
|
6084
|
+
const skillErrEvents = batchEvents[index] ?? [];
|
|
6085
|
+
pushBatchEvent(skillErrEvents, {
|
|
6086
|
+
taskId: val.taskId,
|
|
6087
|
+
phase: "skill-error",
|
|
6088
|
+
at: skillErrAt,
|
|
6089
|
+
detail: String(val.skillError ?? "")
|
|
6090
|
+
});
|
|
6091
|
+
resultEvents.push(skillErrEvents);
|
|
6092
|
+
results.push(withTiming({
|
|
5346
6093
|
id: val.taskId,
|
|
5347
6094
|
skill: val.skillTag,
|
|
5348
6095
|
status: "error",
|
|
5349
6096
|
error: val.skillError,
|
|
5350
6097
|
...degradeField(val.taskNotes ?? [])
|
|
5351
|
-
});
|
|
6098
|
+
}, val.startedAt, skillErrAt));
|
|
5352
6099
|
continue;
|
|
5353
6100
|
}
|
|
5354
6101
|
if (val.startError) {
|
|
5355
6102
|
perTaskNotes.push({ taskId: val.taskId, notes: val.taskNotes ?? [] });
|
|
5356
|
-
|
|
6103
|
+
const startMessage = val.startError instanceof Error ? val.startError.message : String(val.startError);
|
|
6104
|
+
const attribution = describeActivationContractError(val.startError);
|
|
6105
|
+
const startErrAt = Date.now();
|
|
6106
|
+
const startErrEvents = batchEvents[index] ?? [];
|
|
6107
|
+
pushBatchEvent(startErrEvents, {
|
|
6108
|
+
taskId: val.taskId,
|
|
6109
|
+
phase: "failed",
|
|
6110
|
+
at: startErrAt,
|
|
6111
|
+
detail: startMessage
|
|
6112
|
+
});
|
|
6113
|
+
resultEvents.push(startErrEvents);
|
|
6114
|
+
results.push(withTiming({
|
|
5357
6115
|
id: val.taskId,
|
|
5358
6116
|
skill: val.skillTag,
|
|
5359
6117
|
status: "error",
|
|
5360
|
-
error:
|
|
6118
|
+
error: attribution === undefined ? startMessage : `${startMessage}
|
|
6119
|
+
${attribution}`,
|
|
5361
6120
|
...degradeField(val.taskNotes ?? [])
|
|
5362
|
-
});
|
|
6121
|
+
}, val.startedAt, startErrAt));
|
|
5363
6122
|
continue;
|
|
5364
6123
|
}
|
|
5365
|
-
const { run, taskId, skillName, skillTag, taskNotes, ac, onExecAbort, startedAt } = val;
|
|
6124
|
+
const { run, taskId, skillName, skillTag, taskNotes, ac, onExecAbort, startedAt, outputContract, buildPrompt, spawnAgain } = val;
|
|
6125
|
+
const taskEvents = batchEvents[index] ?? [];
|
|
5366
6126
|
let disposed = false;
|
|
5367
6127
|
const safeDispose = () => {
|
|
5368
6128
|
if (disposed)
|
|
@@ -5370,13 +6130,14 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
5370
6130
|
disposed = true;
|
|
5371
6131
|
Promise.resolve().then(() => run.dispose()).catch(() => {});
|
|
5372
6132
|
};
|
|
5373
|
-
runs.push({ run, safeDispose, taskId, skillName, skillTag, taskNotes, ac, onExecAbort, startedAt });
|
|
6133
|
+
runs.push({ run, safeDispose, taskId, skillName, skillTag, taskNotes, ac, onExecAbort, startedAt, taskEvents, outputContract, buildPrompt, spawnAgain });
|
|
5374
6134
|
perTaskNotes.push({ taskId, notes: taskNotes });
|
|
5375
6135
|
run.result.catch(() => {});
|
|
5376
6136
|
}
|
|
5377
|
-
for (const { run, safeDispose, taskId, skillName, skillTag, taskNotes, ac, startedAt } of runs) {
|
|
6137
|
+
for (const { run, safeDispose, taskId, skillName, skillTag, taskNotes, ac, startedAt, taskEvents, outputContract, buildPrompt, spawnAgain } of runs) {
|
|
5378
6138
|
let outcome;
|
|
5379
6139
|
let timer = null;
|
|
6140
|
+
const runId = typeof run?.id === "string" && run.id.length > 0 ? run.id : undefined;
|
|
5380
6141
|
const abortOffs = [];
|
|
5381
6142
|
const remainingMs = Math.max(0, wallClockBudgetMs - (Date.now() - startedAt));
|
|
5382
6143
|
const parentSignal = exec.signal;
|
|
@@ -5413,23 +6174,122 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
5413
6174
|
})
|
|
5414
6175
|
]);
|
|
5415
6176
|
if (outcome?.stopReason === "completed") {
|
|
5416
|
-
|
|
6177
|
+
let rawText = contentText(outcome.output);
|
|
6178
|
+
let contractViolated = false;
|
|
6179
|
+
let contractMark = "";
|
|
6180
|
+
if (outputContract.level !== "off" && outputContract.schema !== undefined) {
|
|
6181
|
+
let check = validateContractText(rawText, outputContract.schema);
|
|
6182
|
+
if (!check.ok && outputContract.level === "strict" && rawText.length < CONTRACT_REWRITE_MAX_CHARS && !ac.signal.aborted && exec.signal?.aborted !== true) {
|
|
6183
|
+
pushBatchEvent(taskEvents, {
|
|
6184
|
+
taskId,
|
|
6185
|
+
phase: "contract-retry",
|
|
6186
|
+
at: Date.now(),
|
|
6187
|
+
detail: check.errors[0] ?? "契约未满足"
|
|
6188
|
+
});
|
|
6189
|
+
const ac2 = new AbortController;
|
|
6190
|
+
const onParentAbort2 = () => {
|
|
6191
|
+
if (!ac2.signal.aborted)
|
|
6192
|
+
ac2.abort();
|
|
6193
|
+
};
|
|
6194
|
+
let off2 = null;
|
|
6195
|
+
if (exec.signal) {
|
|
6196
|
+
if (exec.signal.aborted)
|
|
6197
|
+
ac2.abort();
|
|
6198
|
+
else {
|
|
6199
|
+
exec.signal.addEventListener("abort", onParentAbort2, { once: true });
|
|
6200
|
+
off2 = () => {
|
|
6201
|
+
try {
|
|
6202
|
+
exec.signal.removeEventListener("abort", onParentAbort2);
|
|
6203
|
+
} catch {}
|
|
6204
|
+
};
|
|
6205
|
+
}
|
|
6206
|
+
}
|
|
6207
|
+
let run2;
|
|
6208
|
+
let timer2 = null;
|
|
6209
|
+
try {
|
|
6210
|
+
run2 = await spawnAgain(buildPrompt(`
|
|
6211
|
+
|
|
6212
|
+
[契约重写] 上次输出未满足以下约束:` + check.errors.join(";") + "。请重新输出一个完整合法的 JSON 对象(不要解释)。"), ac2.signal);
|
|
6213
|
+
run2.result.catch(() => {});
|
|
6214
|
+
const remaining2 = Math.max(0, wallClockBudgetMs - (Date.now() - startedAt));
|
|
6215
|
+
const outcome2 = await Promise.race([
|
|
6216
|
+
run2.result,
|
|
6217
|
+
new Promise((_, reject) => {
|
|
6218
|
+
timer2 = setTimeout(() => {
|
|
6219
|
+
if (!ac2.signal.aborted)
|
|
6220
|
+
ac2.abort();
|
|
6221
|
+
reject(new Error("超时:实际耗时 " + (Date.now() - startedAt) + "ms(预算 " + wallClockBudgetMs + "ms)"));
|
|
6222
|
+
}, remaining2);
|
|
6223
|
+
})
|
|
6224
|
+
]);
|
|
6225
|
+
if (outcome2?.stopReason === "completed") {
|
|
6226
|
+
const retried = contentText(outcome2.output);
|
|
6227
|
+
const recheck = validateContractText(retried, outputContract.schema);
|
|
6228
|
+
if (recheck.ok) {
|
|
6229
|
+
rawText = retried;
|
|
6230
|
+
check = { ok: true };
|
|
6231
|
+
} else {
|
|
6232
|
+
check = recheck;
|
|
6233
|
+
}
|
|
6234
|
+
}
|
|
6235
|
+
} catch (retryError) {
|
|
6236
|
+
ctx.logger?.warn?.("[cohub contract] " + taskId + " 契约重写未完成(按违约标记收口):" + (retryError instanceof Error ? retryError.message : String(retryError)));
|
|
6237
|
+
} finally {
|
|
6238
|
+
if (timer2)
|
|
6239
|
+
clearTimeout(timer2);
|
|
6240
|
+
if (off2)
|
|
6241
|
+
off2();
|
|
6242
|
+
if (!ac2.signal.aborted)
|
|
6243
|
+
ac2.abort();
|
|
6244
|
+
if (run2) {
|
|
6245
|
+
try {
|
|
6246
|
+
await run2.dispose?.();
|
|
6247
|
+
} catch {}
|
|
6248
|
+
}
|
|
6249
|
+
}
|
|
6250
|
+
}
|
|
6251
|
+
if (!check.ok) {
|
|
6252
|
+
contractViolated = true;
|
|
6253
|
+
contractMark = `
|
|
6254
|
+
|
|
6255
|
+
` + formatContractViolation(check.errors);
|
|
6256
|
+
ctx.logger?.warn?.("[cohub contract] " + taskId + " 输出未满足契约(" + outputContract.level + "):" + check.errors.join(";"));
|
|
6257
|
+
}
|
|
6258
|
+
}
|
|
6259
|
+
const endedAt = Date.now();
|
|
6260
|
+
pushBatchEvent(taskEvents, {
|
|
6261
|
+
taskId,
|
|
6262
|
+
phase: "completed",
|
|
6263
|
+
at: endedAt,
|
|
6264
|
+
detail: "stopReason: completed · 输出 " + rawText.length + " 字符" + (contractViolated ? " · 契约违约" : "")
|
|
6265
|
+
});
|
|
6266
|
+
resultEvents.push(taskEvents);
|
|
6267
|
+
const resultText = await budgetSubagentResult(ctx, exec, rawText, {
|
|
5417
6268
|
maxChars: Math.min(budget.batchTaskMaxChars, resolveSkillResultMaxChars(budget, skillName)),
|
|
5418
6269
|
scope: "batch:task",
|
|
5419
6270
|
label: taskId + ":" + skillTag,
|
|
5420
6271
|
enabled: budget.enabled,
|
|
5421
6272
|
toolName: "delegate_batch"
|
|
5422
6273
|
});
|
|
5423
|
-
results.push({
|
|
6274
|
+
results.push(withTiming({
|
|
5424
6275
|
id: taskId,
|
|
5425
6276
|
skill: skillTag,
|
|
5426
6277
|
status: "completed",
|
|
5427
|
-
result: resultText,
|
|
5428
|
-
...degradeField(taskNotes)
|
|
5429
|
-
|
|
6278
|
+
result: resultText + contractMark,
|
|
6279
|
+
...degradeField(taskNotes),
|
|
6280
|
+
...contractViolated ? { contractViolated: true } : {}
|
|
6281
|
+
}, startedAt, endedAt, runId));
|
|
5430
6282
|
} else {
|
|
6283
|
+
const endedAt = Date.now();
|
|
5431
6284
|
const diag = typeof outcome?.diagnostic === "string" ? outcome.diagnostic : undefined;
|
|
5432
|
-
|
|
6285
|
+
pushBatchEvent(taskEvents, {
|
|
6286
|
+
taskId,
|
|
6287
|
+
phase: "failed",
|
|
6288
|
+
at: endedAt,
|
|
6289
|
+
detail: "stopReason: " + (outcome?.stopReason ?? "unknown") + (diag === undefined ? "" : " · " + diag)
|
|
6290
|
+
});
|
|
6291
|
+
resultEvents.push(taskEvents);
|
|
6292
|
+
results.push(withTiming({
|
|
5433
6293
|
id: taskId,
|
|
5434
6294
|
skill: skillTag,
|
|
5435
6295
|
status: "failed",
|
|
@@ -5437,16 +6297,25 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
5437
6297
|
stopReason: outcome?.stopReason,
|
|
5438
6298
|
...diag === undefined ? {} : { diagnostic: diag },
|
|
5439
6299
|
...degradeField(taskNotes)
|
|
5440
|
-
});
|
|
6300
|
+
}, startedAt, endedAt, runId));
|
|
5441
6301
|
}
|
|
5442
6302
|
} catch (e) {
|
|
5443
|
-
|
|
6303
|
+
const endedAt = Date.now();
|
|
6304
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
6305
|
+
pushBatchEvent(taskEvents, {
|
|
6306
|
+
taskId,
|
|
6307
|
+
phase: message.startsWith("超时") ? "timeout" : "failed",
|
|
6308
|
+
at: endedAt,
|
|
6309
|
+
detail: message
|
|
6310
|
+
});
|
|
6311
|
+
resultEvents.push(taskEvents);
|
|
6312
|
+
results.push(withTiming({
|
|
5444
6313
|
id: taskId,
|
|
5445
6314
|
skill: skillTag,
|
|
5446
6315
|
status: "error",
|
|
5447
|
-
error:
|
|
6316
|
+
error: message,
|
|
5448
6317
|
...degradeField(taskNotes)
|
|
5449
|
-
});
|
|
6318
|
+
}, startedAt, endedAt, runId));
|
|
5450
6319
|
} finally {
|
|
5451
6320
|
if (timer)
|
|
5452
6321
|
clearTimeout(timer);
|
|
@@ -5524,6 +6393,7 @@ ${r.result}
|
|
|
5524
6393
|
ctx?.logger?.warn?.("[cohub budget] batch:total:拼装结果 " + fullChars + " 字符 ≈ " + approxTokens(fullChars) + " tokens 超过总预算 " + budget.batchTotalMaxChars + " 字符,已裁剪;各任务全文见各自的 locator。仅告警,不阻断。");
|
|
5525
6394
|
}
|
|
5526
6395
|
maybeDeferTodoNudge(exec);
|
|
6396
|
+
const timelineText = renderTaskTimeline(results, resultEvents);
|
|
5527
6397
|
const allNotes = [];
|
|
5528
6398
|
for (const { taskId, notes } of perTaskNotes) {
|
|
5529
6399
|
const echoTaskId = firstLineClamped(taskId, BATCH_TASK_ID_ECHO_MAX);
|
|
@@ -5531,7 +6401,19 @@ ${r.result}
|
|
|
5531
6401
|
allNotes.push({ id: note.id, what: echoTaskId + " " + note.what, effect: note.effect, reason: note.reason });
|
|
5532
6402
|
}
|
|
5533
6403
|
}
|
|
5534
|
-
|
|
6404
|
+
const finalText = statsLine + output + timelineText + formatDegradeNotes(allNotes);
|
|
6405
|
+
const allEvents = [];
|
|
6406
|
+
for (const evts of resultEvents) {
|
|
6407
|
+
for (const e of evts)
|
|
6408
|
+
allEvents.push(e);
|
|
6409
|
+
}
|
|
6410
|
+
if (allEvents.length > 0) {
|
|
6411
|
+
try {
|
|
6412
|
+
const envelope = { text: finalText, results, events: allEvents };
|
|
6413
|
+
exec?.onBatchEvents?.(envelope);
|
|
6414
|
+
} catch {}
|
|
6415
|
+
}
|
|
6416
|
+
return finalText;
|
|
5535
6417
|
}
|
|
5536
6418
|
});
|
|
5537
6419
|
}
|
|
@@ -7655,7 +8537,8 @@ var SkillRoute = z2.object({
|
|
|
7655
8537
|
provider: z2.string(),
|
|
7656
8538
|
model: z2.string(),
|
|
7657
8539
|
maxTokens: z2.number(),
|
|
7658
|
-
reasoningEffort: z2.string().description("推理强度(如 low/medium/high;留空则按模型默认档/继承规则)")
|
|
8540
|
+
reasoningEffort: z2.string().description("推理强度(如 low/medium/high;留空则按模型默认档/继承规则)"),
|
|
8541
|
+
outputContract: z2.union(["off", "lite", "strict"]).description("输出契约等级(off=不注入不校验 / lite=注入+校验+标记违约 / strict=注入+校验+重写一次;留空=off)")
|
|
7659
8542
|
});
|
|
7660
8543
|
var EnvContractConfig = z2.object({
|
|
7661
8544
|
enabled: z2.boolean().default(true),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-cohub",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.13.1",
|
|
4
4
|
"description": "DeepSeek Harness 版 CoHub:中文智能体编排——用户可选 2 种工作模式(co-orchestrator 纯调度 / cohub-cordis 创造模式)+ 13 个专职代理技能 + 多模型共识;另由 cohub-subagent-readonly / cohub-subagent-write 两个支撑 preset 实现子代理读写硬隔离(共 4 个 preset)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|