dsh-cohub 0.12.0 → 0.13.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/README.md +1 -1
- package/lib/index.js +901 -39
- package/package.json +6 -4
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# dsh-cohub
|
|
2
2
|
|
|
3
|
-
> 本文对应 **v0.
|
|
3
|
+
> 本文对应 **v0.13.0**;完整变更历史见 [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;
|
|
@@ -4011,9 +4454,13 @@ async function startSubagentRunOnce(ctx, provider, spec) {
|
|
|
4011
4454
|
ctx?.logger?.warn?.("[cohub] startSubagentRun 无可用 signal:子运行不可中止(父轮停止无法回收)");
|
|
4012
4455
|
}
|
|
4013
4456
|
const prompt = spec.persona !== undefined ? [{ type: "text", text: spec.persona }, ...spec.prompt] : spec.prompt;
|
|
4014
|
-
const
|
|
4457
|
+
const activationSpec = {
|
|
4015
4458
|
provider,
|
|
4016
4459
|
label: spec.label,
|
|
4460
|
+
prompt,
|
|
4461
|
+
parent: spec.parent,
|
|
4462
|
+
...spec.agentPreset !== undefined ? { agentPreset: spec.agentPreset } : {},
|
|
4463
|
+
...spec.agentOptions !== undefined ? { agentOptions: spec.agentOptions } : {},
|
|
4017
4464
|
request: {
|
|
4018
4465
|
prompt,
|
|
4019
4466
|
parent: spec.parent,
|
|
@@ -4022,7 +4469,22 @@ async function startSubagentRunOnce(ctx, provider, spec) {
|
|
|
4022
4469
|
},
|
|
4023
4470
|
...signal !== undefined ? { signal } : {},
|
|
4024
4471
|
delivery: "caller"
|
|
4025
|
-
}
|
|
4472
|
+
};
|
|
4473
|
+
assertDualActivationSpec(activationSpec, spec.label);
|
|
4474
|
+
let receipt;
|
|
4475
|
+
try {
|
|
4476
|
+
receipt = await subagents.startActivation(activationSpec);
|
|
4477
|
+
} catch (err) {
|
|
4478
|
+
const attribution = describeActivationContractError(err);
|
|
4479
|
+
if (attribution === undefined)
|
|
4480
|
+
throw err;
|
|
4481
|
+
const original = err instanceof Error ? err.message : String(err);
|
|
4482
|
+
const wrapped = new Error(`cohub: startActivation 失败:${original}
|
|
4483
|
+
${attribution}`);
|
|
4484
|
+
if (err instanceof Error && typeof err.stack === "string")
|
|
4485
|
+
wrapped.stack = err.stack;
|
|
4486
|
+
throw wrapped;
|
|
4487
|
+
}
|
|
4026
4488
|
applyChildToolFilterDirectly(ctx, receipt.childId, spec.toolFilter, spec.degradeNotes);
|
|
4027
4489
|
return {
|
|
4028
4490
|
id: receipt.childId,
|
|
@@ -4262,6 +4724,9 @@ function resolveSkillAndRoute(requestedSkill, getRoutes, ctx, logger) {
|
|
|
4262
4724
|
const route = (getRoutes() ?? []).find((s) => s.name === requested);
|
|
4263
4725
|
return { skill, route, fallback, ...note === undefined ? {} : { note } };
|
|
4264
4726
|
}
|
|
4727
|
+
function resolveRouteOutputContract(skillName, route) {
|
|
4728
|
+
return resolveOutputContract(skillName, route?.outputContract);
|
|
4729
|
+
}
|
|
4265
4730
|
function formatSkillLabel(skill, fallback) {
|
|
4266
4731
|
return fallback ? skill.name + " (default:" + DEFAULT_FALLBACK_SKILL + ")" : skill.name;
|
|
4267
4732
|
}
|
|
@@ -4511,12 +4976,21 @@ function resolveContractText(envContract, envSig, ctx, fpOverride) {
|
|
|
4511
4976
|
` + picked.text;
|
|
4512
4977
|
return { text, source: picked.source };
|
|
4513
4978
|
}
|
|
4979
|
+
var CONTRACT_REWRITE_MAX_CHARS = 8000;
|
|
4980
|
+
function buildOutputContractBlock(schema) {
|
|
4981
|
+
return `
|
|
4982
|
+
|
|
4983
|
+
--- 输出契约(必须遵守) ---
|
|
4984
|
+
|
|
4985
|
+
` + describeContractForPrompt(schema) + `
|
|
4986
|
+
`;
|
|
4987
|
+
}
|
|
4514
4988
|
function buildDelegatePrompt(params) {
|
|
4515
4989
|
return (params.skill.brief || params.skill.content) + params.contractText + `
|
|
4516
4990
|
|
|
4517
4991
|
--- 你的具体任务 ---
|
|
4518
4992
|
|
|
4519
|
-
` + params.userPrompt + (params.retryNote ?? "");
|
|
4993
|
+
` + params.userPrompt + (params.retryNote ?? "") + (params.outputContractText ?? "");
|
|
4520
4994
|
}
|
|
4521
4995
|
function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
|
|
4522
4996
|
const envContract = createEnvContract(config);
|
|
@@ -4585,6 +5059,10 @@ function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
4585
5059
|
ctx.logger?.info?.("[cohub schedule] 生效调度参数:batch=" + (schedule?.maxParallelBatch ?? 5) + " wallMs=" + (schedule?.wallClockBudgetMs ?? WALL_CLOCK_BUDGET_MS));
|
|
4586
5060
|
const { skill, route, fallback: skillFallback, note: skillNote } = resolveSkillAndRoute(args.skill, getRoutes, ctx);
|
|
4587
5061
|
const skillTag = formatSkillLabel(skill, skillFallback);
|
|
5062
|
+
const outputContract = resolveRouteOutputContract(skill.name, route);
|
|
5063
|
+
const contractActive = outputContract.level !== "off" && outputContract.schema !== undefined;
|
|
5064
|
+
const outputContractText = contractActive && outputContract.schema !== undefined ? buildOutputContractBlock(outputContract.schema) : "";
|
|
5065
|
+
const contractState = { violated: false };
|
|
4588
5066
|
const brief = skill.brief?.trim();
|
|
4589
5067
|
if (!brief) {
|
|
4590
5068
|
ctx.logger?.warn?.('delegate: skill "' + skillTag + '" 缺少 brief,回退完整 content');
|
|
@@ -4611,7 +5089,9 @@ function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
4611
5089
|
let lastPartialBudget = "";
|
|
4612
5090
|
const stallState = { last: null };
|
|
4613
5091
|
let retries = 0;
|
|
4614
|
-
|
|
5092
|
+
let contractExtraAttempts = 0;
|
|
5093
|
+
let contractRewriteNote = "";
|
|
5094
|
+
for (let attempt = 0;attempt <= retry.maxRetries + contractExtraAttempts; attempt++) {
|
|
4615
5095
|
const attemptStartedAt = Date.now();
|
|
4616
5096
|
const attemptNo = attempt + 1;
|
|
4617
5097
|
const reportAttempt = (childSessionId, outcome, stopReason) => {
|
|
@@ -4633,14 +5113,15 @@ function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
4633
5113
|
}
|
|
4634
5114
|
};
|
|
4635
5115
|
const stallNote = stallState.last ? ";停滞诊断:" + stallState.last.diagnostics : "";
|
|
4636
|
-
const retryNote = attempt > 0 ? `
|
|
5116
|
+
const retryNote = contractRewriteNote.length > 0 ? contractRewriteNote : attempt > 0 ? `
|
|
4637
5117
|
|
|
4638
5118
|
[重试 #` + attempt + "] 上一次执行中止,原因:" + lastReason + (lastDiagnostic === undefined ? "" : ";诊断:" + lastDiagnostic) + ";已完成部分:" + (lastPartial || "(无)") + stallNote + "。请从中断处继续,不要重复已完成步骤。" : "";
|
|
4639
5119
|
const promptText = buildDelegatePrompt({
|
|
4640
5120
|
skill,
|
|
4641
5121
|
contractText,
|
|
4642
5122
|
userPrompt: args.prompt,
|
|
4643
|
-
retryNote
|
|
5123
|
+
retryNote,
|
|
5124
|
+
outputContractText
|
|
4644
5125
|
});
|
|
4645
5126
|
const ac = stall.enabled ? new AbortController : null;
|
|
4646
5127
|
let onExecAbort = null;
|
|
@@ -4772,13 +5253,33 @@ function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
4772
5253
|
}
|
|
4773
5254
|
if (outcome?.stopReason === "completed") {
|
|
4774
5255
|
reportAttempt(String(run?.id ?? ""), "completed", "completed");
|
|
4775
|
-
const
|
|
5256
|
+
const rawResult = contentText(outcome.output);
|
|
5257
|
+
let contractMark = "";
|
|
5258
|
+
if (contractActive && outputContract.schema !== undefined) {
|
|
5259
|
+
const check = validateContractText(rawResult, outputContract.schema);
|
|
5260
|
+
if (!check.ok) {
|
|
5261
|
+
if (outputContract.level === "strict" && contractExtraAttempts === 0 && rawResult.length < CONTRACT_REWRITE_MAX_CHARS && outerSignal?.aborted !== true) {
|
|
5262
|
+
contractExtraAttempts = 1;
|
|
5263
|
+
contractRewriteNote = `
|
|
5264
|
+
|
|
5265
|
+
[契约重写] 上次输出未满足以下约束:` + check.errors.join(";") + "。请重新输出一个完整合法的 JSON 对象(不要解释)。";
|
|
5266
|
+
ctx.logger?.info?.("[cohub contract] " + skill.name + " strict:输出未满足契约,重写一次");
|
|
5267
|
+
continue;
|
|
5268
|
+
}
|
|
5269
|
+
contractState.violated = true;
|
|
5270
|
+
contractMark = `
|
|
5271
|
+
|
|
5272
|
+
` + formatContractViolation(check.errors);
|
|
5273
|
+
ctx.logger?.warn?.("[cohub contract] " + skill.name + " 输出未满足契约(" + outputContract.level + "):" + check.errors.join(";"));
|
|
5274
|
+
}
|
|
5275
|
+
}
|
|
5276
|
+
const budgeted = await budgetSubagentResult(ctx, exec, rawResult, {
|
|
4776
5277
|
maxChars: resolveSkillResultMaxChars(budget, skill.name),
|
|
4777
5278
|
scope: "delegate",
|
|
4778
5279
|
label: skillTag,
|
|
4779
5280
|
enabled: budget.enabled
|
|
4780
5281
|
});
|
|
4781
|
-
return budgeted + formatDegradeNotes(degradeNotes);
|
|
5282
|
+
return budgeted + formatDegradeNotes(degradeNotes) + contractMark;
|
|
4782
5283
|
}
|
|
4783
5284
|
lastReason = String(outcome?.stopReason ?? "unknown");
|
|
4784
5285
|
lastDiagnostic = typeof outcome?.diagnostic === "string" ? outcome.diagnostic : undefined;
|
|
@@ -4914,6 +5415,11 @@ function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
4914
5415
|
}
|
|
4915
5416
|
}
|
|
4916
5417
|
const foregroundText = await runAttempts(exec.signal);
|
|
5418
|
+
if (contractState.violated) {
|
|
5419
|
+
try {
|
|
5420
|
+
exec?.onDelegateResult?.({ skill: skill.name, contractViolated: true });
|
|
5421
|
+
} catch {}
|
|
5422
|
+
}
|
|
4917
5423
|
maybeDeferTodoNudge(exec);
|
|
4918
5424
|
if (args.background === true && bgFallbackReason !== undefined) {
|
|
4919
5425
|
return foregroundText + `
|
|
@@ -5150,6 +5656,45 @@ function createCouncilTool(config, ctx) {
|
|
|
5150
5656
|
|
|
5151
5657
|
// src/delegate_batch.ts
|
|
5152
5658
|
import { defineTool as defineTool3 } from "@deepseek-ai/dsh-tools";
|
|
5659
|
+
|
|
5660
|
+
// src/granularity.ts
|
|
5661
|
+
var MAX_TASK_DEMANDS = 3;
|
|
5662
|
+
var MAX_TASK_DOMAINS = 2;
|
|
5663
|
+
function usableCount(value) {
|
|
5664
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
5665
|
+
return;
|
|
5666
|
+
const n = Math.floor(value);
|
|
5667
|
+
return n > 0 ? n : undefined;
|
|
5668
|
+
}
|
|
5669
|
+
function validateTaskScope(scope) {
|
|
5670
|
+
if (scope === undefined || scope === null || typeof scope !== "object")
|
|
5671
|
+
return { ok: true };
|
|
5672
|
+
const demands = usableCount(scope.demands);
|
|
5673
|
+
const domains = Array.isArray(scope.domains) ? scope.domains.filter((d) => typeof d === "string" && d.trim().length > 0) : undefined;
|
|
5674
|
+
const overDemands = demands !== undefined && demands > MAX_TASK_DEMANDS;
|
|
5675
|
+
const overDomains = domains !== undefined && domains.length > MAX_TASK_DOMAINS;
|
|
5676
|
+
if (!overDemands && !overDomains)
|
|
5677
|
+
return { ok: true };
|
|
5678
|
+
const parts = [];
|
|
5679
|
+
const packages = [];
|
|
5680
|
+
if (overDemands && demands !== undefined) {
|
|
5681
|
+
parts.push(`可独立判定诉求 ${demands} 项(上限 ${MAX_TASK_DEMANDS})`);
|
|
5682
|
+
packages.push(Math.ceil(demands / MAX_TASK_DEMANDS));
|
|
5683
|
+
}
|
|
5684
|
+
if (overDomains && domains !== undefined) {
|
|
5685
|
+
const shown = domains.slice(0, 6).map((d) => d.trim()).join(", ");
|
|
5686
|
+
const more = domains.length > 6 ? ` 等 ${domains.length} 个` : "";
|
|
5687
|
+
parts.push(`模块域 ${domains.length} 个(上限 ${MAX_TASK_DOMAINS}):${shown}${more}`);
|
|
5688
|
+
packages.push(Math.ceil(domains.length / MAX_TASK_DOMAINS));
|
|
5689
|
+
}
|
|
5690
|
+
const packagesNeeded = Math.max(...packages);
|
|
5691
|
+
return {
|
|
5692
|
+
ok: false,
|
|
5693
|
+
error: `任务粒度超出单包硬上限:${parts.join(";")}。` + `建议拆分为 ${packagesNeeded} 个 task 分别派发(每个 ≤${MAX_TASK_DEMANDS} 诉求、≤${MAX_TASK_DOMAINS} 模块域),` + "拆完后各 task 可独立判定、独立验收,再由主代理汇总;若确认本任务本就该整体处理," + "重发时省略 scope 字段即可跳过本校验。"
|
|
5694
|
+
};
|
|
5695
|
+
}
|
|
5696
|
+
|
|
5697
|
+
// src/delegate_batch.ts
|
|
5153
5698
|
var BATCH_TASK_ID_ECHO_MAX = 40;
|
|
5154
5699
|
var KNOWN_SKILL_NAMES = COHUB_SKILLS.map((s) => s.name);
|
|
5155
5700
|
var SKILL_NAMES_TEXT = KNOWN_SKILL_NAMES.join(", ");
|
|
@@ -5165,6 +5710,66 @@ function assertKnownSkill(raw) {
|
|
|
5165
5710
|
};
|
|
5166
5711
|
}
|
|
5167
5712
|
var MAX_BATCH_SIZE = 20;
|
|
5713
|
+
var MAX_EVENTS_PER_TASK = 5;
|
|
5714
|
+
var BATCH_EVENT_DETAIL_MAX = 120;
|
|
5715
|
+
var TIMELINE_MAX_ROWS = 20;
|
|
5716
|
+
var TIMELINE_LINE_MAX_CHARS = 120;
|
|
5717
|
+
function clampEventDetail(raw) {
|
|
5718
|
+
const oneLine = String(raw ?? "").replace(/\s+/g, " ").trim();
|
|
5719
|
+
if (oneLine.length <= BATCH_EVENT_DETAIL_MAX)
|
|
5720
|
+
return oneLine;
|
|
5721
|
+
return oneLine.slice(0, BATCH_EVENT_DETAIL_MAX - 1) + "…";
|
|
5722
|
+
}
|
|
5723
|
+
function pushBatchEvent(events, event) {
|
|
5724
|
+
if (events.length >= MAX_EVENTS_PER_TASK)
|
|
5725
|
+
return false;
|
|
5726
|
+
events.push({
|
|
5727
|
+
taskId: event.taskId,
|
|
5728
|
+
phase: event.phase,
|
|
5729
|
+
at: event.at,
|
|
5730
|
+
...event.detail === undefined ? {} : { detail: clampEventDetail(event.detail) }
|
|
5731
|
+
});
|
|
5732
|
+
return true;
|
|
5733
|
+
}
|
|
5734
|
+
function withTiming(entry, startedAt, endedAt, runId) {
|
|
5735
|
+
if (typeof startedAt !== "number" || !Number.isFinite(startedAt))
|
|
5736
|
+
return entry;
|
|
5737
|
+
return {
|
|
5738
|
+
...entry,
|
|
5739
|
+
startedAt,
|
|
5740
|
+
endedAt,
|
|
5741
|
+
durationMs: Math.max(0, endedAt - startedAt),
|
|
5742
|
+
...typeof runId === "string" && runId.length > 0 ? { runId } : {}
|
|
5743
|
+
};
|
|
5744
|
+
}
|
|
5745
|
+
function renderTaskTimeline(results, eventsByTask) {
|
|
5746
|
+
const entries = [];
|
|
5747
|
+
for (let i = 0;i < results.length; i += 1) {
|
|
5748
|
+
const r = results[i];
|
|
5749
|
+
if (r === undefined)
|
|
5750
|
+
continue;
|
|
5751
|
+
const duration = typeof r.durationMs === "number" ? r.durationMs : typeof r.startedAt === "number" && typeof r.endedAt === "number" ? Math.max(0, r.endedAt - r.startedAt) : undefined;
|
|
5752
|
+
if (duration === undefined)
|
|
5753
|
+
continue;
|
|
5754
|
+
const chain = (eventsByTask[i] ?? []).map((e) => e.phase).join("→");
|
|
5755
|
+
let line = "- [" + firstLineClamped(r.id, BATCH_TASK_ID_ECHO_MAX) + "] " + r.status + " · 耗时 " + duration + "ms" + (chain.length > 0 ? " · " + chain : "");
|
|
5756
|
+
if (line.length > TIMELINE_LINE_MAX_CHARS)
|
|
5757
|
+
line = line.slice(0, TIMELINE_LINE_MAX_CHARS - 1) + "…";
|
|
5758
|
+
entries.push({ line, startedAt: typeof r.startedAt === "number" ? r.startedAt : r.endedAt ?? 0, order: i });
|
|
5759
|
+
}
|
|
5760
|
+
if (entries.length === 0)
|
|
5761
|
+
return "";
|
|
5762
|
+
entries.sort((a, b) => a.startedAt - b.startedAt || a.order - b.order);
|
|
5763
|
+
const rows = entries.map((e) => e.line);
|
|
5764
|
+
const shown = rows.length > TIMELINE_MAX_ROWS ? rows.slice(0, TIMELINE_MAX_ROWS) : rows;
|
|
5765
|
+
const overflow = rows.length - shown.length;
|
|
5766
|
+
return `## task 时间线
|
|
5767
|
+
` + shown.join(`
|
|
5768
|
+
`) + (overflow > 0 ? `
|
|
5769
|
+
…+` + overflow : "") + `
|
|
5770
|
+
|
|
5771
|
+
`;
|
|
5772
|
+
}
|
|
5168
5773
|
function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
5169
5774
|
const envContract = createEnvContract(config);
|
|
5170
5775
|
const envSig = createEnvSig(config);
|
|
@@ -5190,7 +5795,7 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
5190
5795
|
tasks: {
|
|
5191
5796
|
type: "array",
|
|
5192
5797
|
required: true,
|
|
5193
|
-
description: "任务列表(≤maxParallelBatch)。每项仅接受
|
|
5798
|
+
description: "任务列表(≤maxParallelBatch)。每项仅接受 4 个字段:id(可选) / skill(必填) / prompt(必填) / scope(可选,任务粒度声明);出现其它字段会被参数校验拒绝。",
|
|
5194
5799
|
items: {
|
|
5195
5800
|
type: "object",
|
|
5196
5801
|
additionalProperties: false,
|
|
@@ -5201,7 +5806,20 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
5201
5806
|
required: true,
|
|
5202
5807
|
description: "必填。合法值(" + KNOWN_SKILL_NAMES.length + " 选 1):" + SKILL_NAMES_TEXT + "。注意 co-orchestrator 为主代理,通常委派用其余 " + (KNOWN_SKILL_NAMES.length - 1) + " 个。"
|
|
5203
5808
|
},
|
|
5204
|
-
prompt: { type: "string", required: true, description: "必填,给该代理的具体任务(自包含)" }
|
|
5809
|
+
prompt: { type: "string", required: true, description: "必填,给该代理的具体任务(自包含)" },
|
|
5810
|
+
scope: {
|
|
5811
|
+
type: "object",
|
|
5812
|
+
additionalProperties: false,
|
|
5813
|
+
description: "可选,任务粒度声明:demands(可独立判定诉求数,上限 3)/ domains(模块域,上限 2)。" + "超限时本 task 直接落 error 并给出拆分建议(其它 task 照常执行);不传则跳过校验。",
|
|
5814
|
+
properties: {
|
|
5815
|
+
demands: { type: "number", description: "可选,可独立判定诉求数(每个需单独拍板/验收的点算 1),上限 3" },
|
|
5816
|
+
domains: {
|
|
5817
|
+
type: "array",
|
|
5818
|
+
description: "可选,模块域(受影响的模块名),上限 2",
|
|
5819
|
+
items: { type: "string" }
|
|
5820
|
+
}
|
|
5821
|
+
}
|
|
5822
|
+
}
|
|
5205
5823
|
}
|
|
5206
5824
|
}
|
|
5207
5825
|
}
|
|
@@ -5236,8 +5854,22 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
5236
5854
|
}
|
|
5237
5855
|
return { task, taskId, requestedSkill: skillFallback ? DEFAULT_FALLBACK_SKILL : raw, skillFallback };
|
|
5238
5856
|
});
|
|
5239
|
-
const
|
|
5857
|
+
const batchEvents = normalized.map(() => []);
|
|
5858
|
+
for (let i = 0;i < normalized.length; i += 1) {
|
|
5859
|
+
const seed = normalized[i];
|
|
5860
|
+
if (seed === undefined)
|
|
5861
|
+
continue;
|
|
5862
|
+
pushBatchEvent(batchEvents[i], {
|
|
5863
|
+
taskId: seed.taskId,
|
|
5864
|
+
phase: "queued",
|
|
5865
|
+
at: batchStartedAt,
|
|
5866
|
+
detail: seed.skillFallback ? "skill 缺失,兜底 " + DEFAULT_FALLBACK_SKILL : seed.requestedSkill
|
|
5867
|
+
});
|
|
5868
|
+
}
|
|
5869
|
+
const starts = await Promise.allSettled(normalized.map(async ({ task, taskId, requestedSkill, skillFallback }, index) => {
|
|
5240
5870
|
const startedAt = Date.now();
|
|
5871
|
+
const taskEvents = batchEvents[index];
|
|
5872
|
+
pushBatchEvent(taskEvents, { taskId, phase: "started", at: startedAt });
|
|
5241
5873
|
const skillCheck = assertKnownSkill(requestedSkill);
|
|
5242
5874
|
if (!skillCheck.ok) {
|
|
5243
5875
|
ctx.logger?.warn?.('[cohub delegate_batch] task "' + taskId + '" 的 skill 名 "' + requestedSkill + '" 不在合法名单内,已按错误返回(不再静默降级为 ' + DEFAULT_FALLBACK_SKILL + ")");
|
|
@@ -5255,6 +5887,24 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
5255
5887
|
skillError: skillCheck.error
|
|
5256
5888
|
};
|
|
5257
5889
|
}
|
|
5890
|
+
const scopeCheck = validateTaskScope(task.scope);
|
|
5891
|
+
if (!scopeCheck.ok) {
|
|
5892
|
+
ctx.logger?.warn?.('[cohub delegate_batch] task "' + taskId + '" 的 scope 超出单包粒度上限(诉求 ≤' + "3 / 模块域 ≤2),已按错误返回并给出拆分建议");
|
|
5893
|
+
return {
|
|
5894
|
+
taskId,
|
|
5895
|
+
skillName: requestedSkill,
|
|
5896
|
+
skillTag: requestedSkill,
|
|
5897
|
+
task,
|
|
5898
|
+
taskNotes: [],
|
|
5899
|
+
run: undefined,
|
|
5900
|
+
ac: undefined,
|
|
5901
|
+
onExecAbort: null,
|
|
5902
|
+
startedAt,
|
|
5903
|
+
startError: undefined,
|
|
5904
|
+
skillError: undefined,
|
|
5905
|
+
scopeError: scopeCheck.error
|
|
5906
|
+
};
|
|
5907
|
+
}
|
|
5258
5908
|
const { skill, route, note: skillNote } = resolveSkillAndRoute(requestedSkill, getRoutes, ctx, ctx.logger);
|
|
5259
5909
|
const taskNotes = [];
|
|
5260
5910
|
if (skillNote !== undefined) {
|
|
@@ -5266,12 +5916,17 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
5266
5916
|
});
|
|
5267
5917
|
}
|
|
5268
5918
|
const skillTag = formatSkillLabel(skill, skillFallback);
|
|
5269
|
-
const
|
|
5919
|
+
const outputContract = resolveRouteOutputContract(skill.name, route);
|
|
5920
|
+
const contractActive = outputContract.level !== "off" && outputContract.schema !== undefined;
|
|
5921
|
+
const outputContractText = contractActive && outputContract.schema !== undefined ? buildOutputContractBlock(outputContract.schema) : "";
|
|
5922
|
+
const buildPrompt = (rewriteNote) => buildDelegatePrompt({
|
|
5270
5923
|
skill,
|
|
5271
5924
|
contractText,
|
|
5272
|
-
userPrompt: task.prompt
|
|
5925
|
+
userPrompt: task.prompt,
|
|
5926
|
+
...rewriteNote === undefined ? {} : { retryNote: rewriteNote },
|
|
5927
|
+
outputContractText
|
|
5273
5928
|
});
|
|
5274
|
-
const
|
|
5929
|
+
const promptText = buildPrompt();
|
|
5275
5930
|
const toolFilter = resolveSkillToolFilter(skill.name, toolFilterEnabled, ctx.logger);
|
|
5276
5931
|
const agentPreset = resolveSkillAgentPreset(skill.name, presetEnabled);
|
|
5277
5932
|
const ac = new AbortController;
|
|
@@ -5288,18 +5943,35 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
5288
5943
|
}
|
|
5289
5944
|
}
|
|
5290
5945
|
try {
|
|
5291
|
-
const
|
|
5946
|
+
const agentOptions = await buildAgentOptions(route, ctx, skill.name);
|
|
5947
|
+
const spawnAgain = async (text, spawnSignal) => startSubagentRun(ctx, DEFAULT_SPAWN_TRANSPORT, {
|
|
5292
5948
|
label: `delegate_batch:${taskId}:${skillTag}`,
|
|
5293
|
-
prompt: [{ type: "text", text
|
|
5949
|
+
prompt: [{ type: "text", text }],
|
|
5294
5950
|
parent,
|
|
5295
5951
|
persona: DELEGATE_PERSONA,
|
|
5296
5952
|
...toolFilter !== undefined ? { toolFilter } : {},
|
|
5297
5953
|
...agentPreset !== undefined ? { agentPreset } : {},
|
|
5298
5954
|
...agentOptions ? { agentOptions } : {},
|
|
5299
|
-
signal:
|
|
5955
|
+
signal: spawnSignal,
|
|
5300
5956
|
degradeNotes: taskNotes
|
|
5301
5957
|
});
|
|
5302
|
-
|
|
5958
|
+
const run = await spawnAgain(promptText, ac.signal);
|
|
5959
|
+
return {
|
|
5960
|
+
taskId,
|
|
5961
|
+
skillName: skill.name,
|
|
5962
|
+
skillTag,
|
|
5963
|
+
task,
|
|
5964
|
+
taskNotes,
|
|
5965
|
+
run,
|
|
5966
|
+
ac,
|
|
5967
|
+
onExecAbort,
|
|
5968
|
+
startedAt,
|
|
5969
|
+
startError: undefined,
|
|
5970
|
+
skillError: undefined,
|
|
5971
|
+
outputContract,
|
|
5972
|
+
buildPrompt,
|
|
5973
|
+
spawnAgain
|
|
5974
|
+
};
|
|
5303
5975
|
} catch (startError) {
|
|
5304
5976
|
if (onExecAbort && exec.signal) {
|
|
5305
5977
|
try {
|
|
@@ -5310,6 +5982,7 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
5310
5982
|
}
|
|
5311
5983
|
}));
|
|
5312
5984
|
const results = [];
|
|
5985
|
+
const resultEvents = [];
|
|
5313
5986
|
const runs = [];
|
|
5314
5987
|
const perTaskNotes = [];
|
|
5315
5988
|
const degradeField = (notes) => {
|
|
@@ -5317,34 +5990,100 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
5317
5990
|
return text.length > 0 ? { degrade: text } : {};
|
|
5318
5991
|
};
|
|
5319
5992
|
try {
|
|
5320
|
-
for (
|
|
5993
|
+
for (let index = 0;index < starts.length; index += 1) {
|
|
5994
|
+
const s = starts[index];
|
|
5995
|
+
if (s === undefined)
|
|
5996
|
+
continue;
|
|
5321
5997
|
if (s.status === "rejected") {
|
|
5998
|
+
const seed = normalized[index];
|
|
5999
|
+
const rejectedId = seed?.taskId ?? `task-${index}`;
|
|
6000
|
+
const rejectedNotes = [];
|
|
6001
|
+
perTaskNotes.push({ taskId: rejectedId, notes: rejectedNotes });
|
|
6002
|
+
const rejectedMessage = s.reason instanceof Error ? s.reason.message : String(s.reason);
|
|
6003
|
+
const rejectedAt = Date.now();
|
|
6004
|
+
const rejectedEvents = batchEvents[index] ?? [];
|
|
6005
|
+
pushBatchEvent(rejectedEvents, {
|
|
6006
|
+
taskId: rejectedId,
|
|
6007
|
+
phase: "failed",
|
|
6008
|
+
at: rejectedAt,
|
|
6009
|
+
detail: rejectedMessage
|
|
6010
|
+
});
|
|
6011
|
+
resultEvents.push(rejectedEvents);
|
|
6012
|
+
results.push(withTiming({
|
|
6013
|
+
id: rejectedId,
|
|
6014
|
+
skill: seed?.requestedSkill ?? DEFAULT_FALLBACK_SKILL,
|
|
6015
|
+
status: "error",
|
|
6016
|
+
error: rejectedMessage,
|
|
6017
|
+
...degradeField(rejectedNotes)
|
|
6018
|
+
}, batchStartedAt, rejectedAt));
|
|
5322
6019
|
continue;
|
|
5323
6020
|
}
|
|
5324
6021
|
const val = s.value;
|
|
6022
|
+
if (val.scopeError) {
|
|
6023
|
+
perTaskNotes.push({ taskId: val.taskId, notes: val.taskNotes ?? [] });
|
|
6024
|
+
const scopeAt = Date.now();
|
|
6025
|
+
const scopeEvents = batchEvents[index] ?? [];
|
|
6026
|
+
pushBatchEvent(scopeEvents, {
|
|
6027
|
+
taskId: val.taskId,
|
|
6028
|
+
phase: "scope-error",
|
|
6029
|
+
at: scopeAt,
|
|
6030
|
+
detail: String(val.scopeError ?? "")
|
|
6031
|
+
});
|
|
6032
|
+
resultEvents.push(scopeEvents);
|
|
6033
|
+
results.push(withTiming({
|
|
6034
|
+
id: val.taskId,
|
|
6035
|
+
skill: val.skillTag,
|
|
6036
|
+
status: "error",
|
|
6037
|
+
error: val.scopeError,
|
|
6038
|
+
...degradeField(val.taskNotes ?? [])
|
|
6039
|
+
}, val.startedAt, scopeAt));
|
|
6040
|
+
continue;
|
|
6041
|
+
}
|
|
5325
6042
|
if (val.skillError) {
|
|
5326
6043
|
perTaskNotes.push({ taskId: val.taskId, notes: val.taskNotes ?? [] });
|
|
5327
|
-
|
|
6044
|
+
const skillErrAt = Date.now();
|
|
6045
|
+
const skillErrEvents = batchEvents[index] ?? [];
|
|
6046
|
+
pushBatchEvent(skillErrEvents, {
|
|
6047
|
+
taskId: val.taskId,
|
|
6048
|
+
phase: "skill-error",
|
|
6049
|
+
at: skillErrAt,
|
|
6050
|
+
detail: String(val.skillError ?? "")
|
|
6051
|
+
});
|
|
6052
|
+
resultEvents.push(skillErrEvents);
|
|
6053
|
+
results.push(withTiming({
|
|
5328
6054
|
id: val.taskId,
|
|
5329
6055
|
skill: val.skillTag,
|
|
5330
6056
|
status: "error",
|
|
5331
6057
|
error: val.skillError,
|
|
5332
6058
|
...degradeField(val.taskNotes ?? [])
|
|
5333
|
-
});
|
|
6059
|
+
}, val.startedAt, skillErrAt));
|
|
5334
6060
|
continue;
|
|
5335
6061
|
}
|
|
5336
6062
|
if (val.startError) {
|
|
5337
6063
|
perTaskNotes.push({ taskId: val.taskId, notes: val.taskNotes ?? [] });
|
|
5338
|
-
|
|
6064
|
+
const startMessage = val.startError instanceof Error ? val.startError.message : String(val.startError);
|
|
6065
|
+
const attribution = describeActivationContractError(val.startError);
|
|
6066
|
+
const startErrAt = Date.now();
|
|
6067
|
+
const startErrEvents = batchEvents[index] ?? [];
|
|
6068
|
+
pushBatchEvent(startErrEvents, {
|
|
6069
|
+
taskId: val.taskId,
|
|
6070
|
+
phase: "failed",
|
|
6071
|
+
at: startErrAt,
|
|
6072
|
+
detail: startMessage
|
|
6073
|
+
});
|
|
6074
|
+
resultEvents.push(startErrEvents);
|
|
6075
|
+
results.push(withTiming({
|
|
5339
6076
|
id: val.taskId,
|
|
5340
6077
|
skill: val.skillTag,
|
|
5341
6078
|
status: "error",
|
|
5342
|
-
error:
|
|
6079
|
+
error: attribution === undefined ? startMessage : `${startMessage}
|
|
6080
|
+
${attribution}`,
|
|
5343
6081
|
...degradeField(val.taskNotes ?? [])
|
|
5344
|
-
});
|
|
6082
|
+
}, val.startedAt, startErrAt));
|
|
5345
6083
|
continue;
|
|
5346
6084
|
}
|
|
5347
|
-
const { run, taskId, skillName, skillTag, taskNotes, ac, onExecAbort, startedAt } = val;
|
|
6085
|
+
const { run, taskId, skillName, skillTag, taskNotes, ac, onExecAbort, startedAt, outputContract, buildPrompt, spawnAgain } = val;
|
|
6086
|
+
const taskEvents = batchEvents[index] ?? [];
|
|
5348
6087
|
let disposed = false;
|
|
5349
6088
|
const safeDispose = () => {
|
|
5350
6089
|
if (disposed)
|
|
@@ -5352,13 +6091,14 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
5352
6091
|
disposed = true;
|
|
5353
6092
|
Promise.resolve().then(() => run.dispose()).catch(() => {});
|
|
5354
6093
|
};
|
|
5355
|
-
runs.push({ run, safeDispose, taskId, skillName, skillTag, taskNotes, ac, onExecAbort, startedAt });
|
|
6094
|
+
runs.push({ run, safeDispose, taskId, skillName, skillTag, taskNotes, ac, onExecAbort, startedAt, taskEvents, outputContract, buildPrompt, spawnAgain });
|
|
5356
6095
|
perTaskNotes.push({ taskId, notes: taskNotes });
|
|
5357
6096
|
run.result.catch(() => {});
|
|
5358
6097
|
}
|
|
5359
|
-
for (const { run, safeDispose, taskId, skillName, skillTag, taskNotes, ac, startedAt } of runs) {
|
|
6098
|
+
for (const { run, safeDispose, taskId, skillName, skillTag, taskNotes, ac, startedAt, taskEvents, outputContract, buildPrompt, spawnAgain } of runs) {
|
|
5360
6099
|
let outcome;
|
|
5361
6100
|
let timer = null;
|
|
6101
|
+
const runId = typeof run?.id === "string" && run.id.length > 0 ? run.id : undefined;
|
|
5362
6102
|
const abortOffs = [];
|
|
5363
6103
|
const remainingMs = Math.max(0, wallClockBudgetMs - (Date.now() - startedAt));
|
|
5364
6104
|
const parentSignal = exec.signal;
|
|
@@ -5395,23 +6135,122 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
5395
6135
|
})
|
|
5396
6136
|
]);
|
|
5397
6137
|
if (outcome?.stopReason === "completed") {
|
|
5398
|
-
|
|
6138
|
+
let rawText = contentText(outcome.output);
|
|
6139
|
+
let contractViolated = false;
|
|
6140
|
+
let contractMark = "";
|
|
6141
|
+
if (outputContract.level !== "off" && outputContract.schema !== undefined) {
|
|
6142
|
+
let check = validateContractText(rawText, outputContract.schema);
|
|
6143
|
+
if (!check.ok && outputContract.level === "strict" && rawText.length < CONTRACT_REWRITE_MAX_CHARS && !ac.signal.aborted && exec.signal?.aborted !== true) {
|
|
6144
|
+
pushBatchEvent(taskEvents, {
|
|
6145
|
+
taskId,
|
|
6146
|
+
phase: "contract-retry",
|
|
6147
|
+
at: Date.now(),
|
|
6148
|
+
detail: check.errors[0] ?? "契约未满足"
|
|
6149
|
+
});
|
|
6150
|
+
const ac2 = new AbortController;
|
|
6151
|
+
const onParentAbort2 = () => {
|
|
6152
|
+
if (!ac2.signal.aborted)
|
|
6153
|
+
ac2.abort();
|
|
6154
|
+
};
|
|
6155
|
+
let off2 = null;
|
|
6156
|
+
if (exec.signal) {
|
|
6157
|
+
if (exec.signal.aborted)
|
|
6158
|
+
ac2.abort();
|
|
6159
|
+
else {
|
|
6160
|
+
exec.signal.addEventListener("abort", onParentAbort2, { once: true });
|
|
6161
|
+
off2 = () => {
|
|
6162
|
+
try {
|
|
6163
|
+
exec.signal.removeEventListener("abort", onParentAbort2);
|
|
6164
|
+
} catch {}
|
|
6165
|
+
};
|
|
6166
|
+
}
|
|
6167
|
+
}
|
|
6168
|
+
let run2;
|
|
6169
|
+
let timer2 = null;
|
|
6170
|
+
try {
|
|
6171
|
+
run2 = await spawnAgain(buildPrompt(`
|
|
6172
|
+
|
|
6173
|
+
[契约重写] 上次输出未满足以下约束:` + check.errors.join(";") + "。请重新输出一个完整合法的 JSON 对象(不要解释)。"), ac2.signal);
|
|
6174
|
+
run2.result.catch(() => {});
|
|
6175
|
+
const remaining2 = Math.max(0, wallClockBudgetMs - (Date.now() - startedAt));
|
|
6176
|
+
const outcome2 = await Promise.race([
|
|
6177
|
+
run2.result,
|
|
6178
|
+
new Promise((_, reject) => {
|
|
6179
|
+
timer2 = setTimeout(() => {
|
|
6180
|
+
if (!ac2.signal.aborted)
|
|
6181
|
+
ac2.abort();
|
|
6182
|
+
reject(new Error("超时:实际耗时 " + (Date.now() - startedAt) + "ms(预算 " + wallClockBudgetMs + "ms)"));
|
|
6183
|
+
}, remaining2);
|
|
6184
|
+
})
|
|
6185
|
+
]);
|
|
6186
|
+
if (outcome2?.stopReason === "completed") {
|
|
6187
|
+
const retried = contentText(outcome2.output);
|
|
6188
|
+
const recheck = validateContractText(retried, outputContract.schema);
|
|
6189
|
+
if (recheck.ok) {
|
|
6190
|
+
rawText = retried;
|
|
6191
|
+
check = { ok: true };
|
|
6192
|
+
} else {
|
|
6193
|
+
check = recheck;
|
|
6194
|
+
}
|
|
6195
|
+
}
|
|
6196
|
+
} catch (retryError) {
|
|
6197
|
+
ctx.logger?.warn?.("[cohub contract] " + taskId + " 契约重写未完成(按违约标记收口):" + (retryError instanceof Error ? retryError.message : String(retryError)));
|
|
6198
|
+
} finally {
|
|
6199
|
+
if (timer2)
|
|
6200
|
+
clearTimeout(timer2);
|
|
6201
|
+
if (off2)
|
|
6202
|
+
off2();
|
|
6203
|
+
if (!ac2.signal.aborted)
|
|
6204
|
+
ac2.abort();
|
|
6205
|
+
if (run2) {
|
|
6206
|
+
try {
|
|
6207
|
+
await run2.dispose?.();
|
|
6208
|
+
} catch {}
|
|
6209
|
+
}
|
|
6210
|
+
}
|
|
6211
|
+
}
|
|
6212
|
+
if (!check.ok) {
|
|
6213
|
+
contractViolated = true;
|
|
6214
|
+
contractMark = `
|
|
6215
|
+
|
|
6216
|
+
` + formatContractViolation(check.errors);
|
|
6217
|
+
ctx.logger?.warn?.("[cohub contract] " + taskId + " 输出未满足契约(" + outputContract.level + "):" + check.errors.join(";"));
|
|
6218
|
+
}
|
|
6219
|
+
}
|
|
6220
|
+
const endedAt = Date.now();
|
|
6221
|
+
pushBatchEvent(taskEvents, {
|
|
6222
|
+
taskId,
|
|
6223
|
+
phase: "completed",
|
|
6224
|
+
at: endedAt,
|
|
6225
|
+
detail: "stopReason: completed · 输出 " + rawText.length + " 字符" + (contractViolated ? " · 契约违约" : "")
|
|
6226
|
+
});
|
|
6227
|
+
resultEvents.push(taskEvents);
|
|
6228
|
+
const resultText = await budgetSubagentResult(ctx, exec, rawText, {
|
|
5399
6229
|
maxChars: Math.min(budget.batchTaskMaxChars, resolveSkillResultMaxChars(budget, skillName)),
|
|
5400
6230
|
scope: "batch:task",
|
|
5401
6231
|
label: taskId + ":" + skillTag,
|
|
5402
6232
|
enabled: budget.enabled,
|
|
5403
6233
|
toolName: "delegate_batch"
|
|
5404
6234
|
});
|
|
5405
|
-
results.push({
|
|
6235
|
+
results.push(withTiming({
|
|
5406
6236
|
id: taskId,
|
|
5407
6237
|
skill: skillTag,
|
|
5408
6238
|
status: "completed",
|
|
5409
|
-
result: resultText,
|
|
5410
|
-
...degradeField(taskNotes)
|
|
5411
|
-
|
|
6239
|
+
result: resultText + contractMark,
|
|
6240
|
+
...degradeField(taskNotes),
|
|
6241
|
+
...contractViolated ? { contractViolated: true } : {}
|
|
6242
|
+
}, startedAt, endedAt, runId));
|
|
5412
6243
|
} else {
|
|
6244
|
+
const endedAt = Date.now();
|
|
5413
6245
|
const diag = typeof outcome?.diagnostic === "string" ? outcome.diagnostic : undefined;
|
|
5414
|
-
|
|
6246
|
+
pushBatchEvent(taskEvents, {
|
|
6247
|
+
taskId,
|
|
6248
|
+
phase: "failed",
|
|
6249
|
+
at: endedAt,
|
|
6250
|
+
detail: "stopReason: " + (outcome?.stopReason ?? "unknown") + (diag === undefined ? "" : " · " + diag)
|
|
6251
|
+
});
|
|
6252
|
+
resultEvents.push(taskEvents);
|
|
6253
|
+
results.push(withTiming({
|
|
5415
6254
|
id: taskId,
|
|
5416
6255
|
skill: skillTag,
|
|
5417
6256
|
status: "failed",
|
|
@@ -5419,16 +6258,25 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
5419
6258
|
stopReason: outcome?.stopReason,
|
|
5420
6259
|
...diag === undefined ? {} : { diagnostic: diag },
|
|
5421
6260
|
...degradeField(taskNotes)
|
|
5422
|
-
});
|
|
6261
|
+
}, startedAt, endedAt, runId));
|
|
5423
6262
|
}
|
|
5424
6263
|
} catch (e) {
|
|
5425
|
-
|
|
6264
|
+
const endedAt = Date.now();
|
|
6265
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
6266
|
+
pushBatchEvent(taskEvents, {
|
|
6267
|
+
taskId,
|
|
6268
|
+
phase: message.startsWith("超时") ? "timeout" : "failed",
|
|
6269
|
+
at: endedAt,
|
|
6270
|
+
detail: message
|
|
6271
|
+
});
|
|
6272
|
+
resultEvents.push(taskEvents);
|
|
6273
|
+
results.push(withTiming({
|
|
5426
6274
|
id: taskId,
|
|
5427
6275
|
skill: skillTag,
|
|
5428
6276
|
status: "error",
|
|
5429
|
-
error:
|
|
6277
|
+
error: message,
|
|
5430
6278
|
...degradeField(taskNotes)
|
|
5431
|
-
});
|
|
6279
|
+
}, startedAt, endedAt, runId));
|
|
5432
6280
|
} finally {
|
|
5433
6281
|
if (timer)
|
|
5434
6282
|
clearTimeout(timer);
|
|
@@ -5506,6 +6354,7 @@ ${r.result}
|
|
|
5506
6354
|
ctx?.logger?.warn?.("[cohub budget] batch:total:拼装结果 " + fullChars + " 字符 ≈ " + approxTokens(fullChars) + " tokens 超过总预算 " + budget.batchTotalMaxChars + " 字符,已裁剪;各任务全文见各自的 locator。仅告警,不阻断。");
|
|
5507
6355
|
}
|
|
5508
6356
|
maybeDeferTodoNudge(exec);
|
|
6357
|
+
const timelineText = renderTaskTimeline(results, resultEvents);
|
|
5509
6358
|
const allNotes = [];
|
|
5510
6359
|
for (const { taskId, notes } of perTaskNotes) {
|
|
5511
6360
|
const echoTaskId = firstLineClamped(taskId, BATCH_TASK_ID_ECHO_MAX);
|
|
@@ -5513,7 +6362,19 @@ ${r.result}
|
|
|
5513
6362
|
allNotes.push({ id: note.id, what: echoTaskId + " " + note.what, effect: note.effect, reason: note.reason });
|
|
5514
6363
|
}
|
|
5515
6364
|
}
|
|
5516
|
-
|
|
6365
|
+
const finalText = statsLine + output + timelineText + formatDegradeNotes(allNotes);
|
|
6366
|
+
const allEvents = [];
|
|
6367
|
+
for (const evts of resultEvents) {
|
|
6368
|
+
for (const e of evts)
|
|
6369
|
+
allEvents.push(e);
|
|
6370
|
+
}
|
|
6371
|
+
if (allEvents.length > 0) {
|
|
6372
|
+
try {
|
|
6373
|
+
const envelope = { text: finalText, results, events: allEvents };
|
|
6374
|
+
exec?.onBatchEvents?.(envelope);
|
|
6375
|
+
} catch {}
|
|
6376
|
+
}
|
|
6377
|
+
return finalText;
|
|
5517
6378
|
}
|
|
5518
6379
|
});
|
|
5519
6380
|
}
|
|
@@ -7637,7 +8498,8 @@ var SkillRoute = z2.object({
|
|
|
7637
8498
|
provider: z2.string(),
|
|
7638
8499
|
model: z2.string(),
|
|
7639
8500
|
maxTokens: z2.number(),
|
|
7640
|
-
reasoningEffort: z2.string().description("推理强度(如 low/medium/high;留空则按模型默认档/继承规则)")
|
|
8501
|
+
reasoningEffort: z2.string().description("推理强度(如 low/medium/high;留空则按模型默认档/继承规则)"),
|
|
8502
|
+
outputContract: z2.union(["off", "lite", "strict"]).description("输出契约等级(off=不注入不校验 / lite=注入+校验+标记违约 / strict=注入+校验+重写一次;留空=off)")
|
|
7641
8503
|
});
|
|
7642
8504
|
var EnvContractConfig = z2.object({
|
|
7643
8505
|
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.0",
|
|
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",
|
|
@@ -40,9 +40,11 @@
|
|
|
40
40
|
"test:runtime": "node test/runtime-0.2.ts",
|
|
41
41
|
"test:host": "node test/host-integration.ts",
|
|
42
42
|
"test:client": "node test/client-runtime-0.2.ts",
|
|
43
|
-
"
|
|
44
|
-
"typecheck:
|
|
45
|
-
"typecheck": "
|
|
43
|
+
"test:all": "node scripts/test-all.mjs",
|
|
44
|
+
"typecheck:0.2": "bunx typescript@5.9.3 --noEmit -p test/tsconfig.runtime-0.2.json",
|
|
45
|
+
"typecheck:test": "bunx typescript@5.9.3 --noEmit -p test/tsconfig.typecheck.test.json",
|
|
46
|
+
"typecheck:src": "bunx typescript@5.9.3 --noEmit -p tsconfig.typecheck.json",
|
|
47
|
+
"typecheck": "bun run typecheck:src && bun run typecheck:0.2 && bun run typecheck:test",
|
|
46
48
|
"prepublish-check": "bun run scripts/prepublish-check.ts",
|
|
47
49
|
"prepublishOnly": "npm run build",
|
|
48
50
|
"build:client": "bun run scripts/build-client.js",
|