@stalfh233/omc-cli 0.6.47 → 0.6.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/capability-overview.js +114 -1
- package/dist/cli-stdout.js +3 -0
- package/dist/cli.js +318 -62
- package/dist/closest-match.js +22 -3
- package/dist/command-transport.js +5 -1
- package/dist/discovery.js +193 -75
- package/dist/goal-plan.js +1296 -0
- package/dist/goal-routes.js +87 -5
- package/dist/graph.js +223 -34
- package/dist/intent/capabilities/field.js +24 -0
- package/dist/intent/plan-apply.js +10 -3
- package/dist/intent/schema.js +24 -1
- package/dist/lanes/app.js +4 -0
- package/dist/lanes/apply-changes.js +1 -0
- package/dist/lanes/b2-registration.js +24 -0
- package/dist/lanes/businessrule.js +14 -0
- package/dist/lanes/custom-page.js +8 -0
- package/dist/lanes/datarule.js +4 -0
- package/dist/lanes/dictionary.js +13 -0
- package/dist/lanes/environment.js +2 -0
- package/dist/lanes/field.js +5 -0
- package/dist/lanes/folder.js +4 -0
- package/dist/lanes/form.js +5 -0
- package/dist/lanes/list-view-contract.js +1 -1
- package/dist/lanes/list-view.js +5 -0
- package/dist/lanes/meta.js +5 -0
- package/dist/lanes/model.js +9 -0
- package/dist/lanes/online-js.js +2 -0
- package/dist/lanes/organization.js +20 -0
- package/dist/lanes/perm.js +5 -5
- package/dist/lanes/programming.js +6 -0
- package/dist/lanes/report.js +9 -0
- package/dist/lanes/rule-lifecycle.js +6 -0
- package/dist/lanes/rulelog.js +1 -0
- package/dist/lanes/runtime-data.js +39 -1
- package/dist/lanes/workflow.js +18 -0
- package/dist/mcp-graph.js +180 -41
- package/dist/package-tool.js +1 -0
- package/dist/recipes/workflow.js +1 -1
- package/dist/search-index.js +137 -0
- package/dist/tool-search.js +647 -0
- package/dist/tool-types.js +6 -0
- package/dist/tools.js +1 -0
- package/dist/write.js +2 -1
- package/docs/omc-introduction.md +5 -7
- package/package.json +6 -5
- package/skills/omc-business-configuration.md +2 -1
- package/skills/omc-capabilities.md +4 -2
- package/skills/omc-start-here.md +21 -7
- package/skills/omc-tool-selection.md +7 -15
- package/skills/omc-write-hazards.md +1 -1
|
@@ -0,0 +1,1296 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { goalRoute } from "./goal-routes.js";
|
|
4
|
+
import { capabilityRouteIndex } from "./capability-overview.js";
|
|
5
|
+
import { paramFillRuleFor } from "./search-index.js";
|
|
6
|
+
import { scoreTools } from "./tool-search.js";
|
|
7
|
+
const AUTHORED_KEYS = new Set([
|
|
8
|
+
"nodeGraph", "template", "source", "methodConfig", "serviceConfig",
|
|
9
|
+
"methodInputParameters", "methodOutputParameters", "draftViewJson", "draftAttributesJson",
|
|
10
|
+
"records", "fields", "subFields",
|
|
11
|
+
]);
|
|
12
|
+
/**
|
|
13
|
+
* Read asks (M6): rank read tools with the M1 search face, resolve the model the
|
|
14
|
+
* ask names, and hand back ONE runnable read step + what is still needed.
|
|
15
|
+
*
|
|
16
|
+
* The distinction that matters: `needs-input` here is about the QUERY SEMANTICS
|
|
17
|
+
* (which rows), not about which tool or which model — those two are answered.
|
|
18
|
+
*/
|
|
19
|
+
async function planReadAsk(registry, goal, environment, options, base, match, capability, lane) {
|
|
20
|
+
const hits = scoreTools(registry, goal).filter((hit) => registry.find((tool) => tool.name === hit.name)?.kind === "read");
|
|
21
|
+
const primary = hits[0]?.name;
|
|
22
|
+
const tool = primary === undefined ? undefined : registry.find((entry) => entry.name === primary);
|
|
23
|
+
const ambiguities = [];
|
|
24
|
+
const missing = {};
|
|
25
|
+
const warnings = [];
|
|
26
|
+
const probes = [];
|
|
27
|
+
const steps = [];
|
|
28
|
+
const blockers = [];
|
|
29
|
+
let probeFailure;
|
|
30
|
+
if (tool === undefined) {
|
|
31
|
+
return {
|
|
32
|
+
...base,
|
|
33
|
+
ready: false,
|
|
34
|
+
level: 2,
|
|
35
|
+
...(match !== undefined ? { match } : {}),
|
|
36
|
+
blockers: [{ type: "needs-input", reason: "读路径没能定位到一个具体读工具", hint: "换更具体的业务说法,或 omc commands --filter <词>" }],
|
|
37
|
+
planHash: planHash({ goal, environment, level: 2 }),
|
|
38
|
+
next: ["omc commands --filter <关键词>", "omc capabilities"],
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
// Fill what the read tool needs, from the ask + one probe.
|
|
42
|
+
const args = {};
|
|
43
|
+
if (environment !== null)
|
|
44
|
+
args.environment = environment;
|
|
45
|
+
const shape = tool.inputSchema;
|
|
46
|
+
const requiredKeys = Object.entries(shape)
|
|
47
|
+
.filter(([, node]) => typeof node?.isOptional !== "function" || node.isOptional() === false)
|
|
48
|
+
.map(([key]) => key)
|
|
49
|
+
.filter((key) => key !== "environment");
|
|
50
|
+
for (const key of requiredKeys) {
|
|
51
|
+
if (key === "schemaCode") {
|
|
52
|
+
const hint = hintFromGoal(goal, {});
|
|
53
|
+
if (options.offline === true || options.probe === undefined) {
|
|
54
|
+
probes.push(`omc call model.list --env ${environment ?? "<env>"} --args '{}'`);
|
|
55
|
+
missing[key] = { reason: "需 model.list 解析目标模型", source: "model.list → models[].schemaCode" };
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
const probed = await probeReadOnly(options.probe, "model.list");
|
|
59
|
+
if (probed.state === "uncertain") {
|
|
60
|
+
probeFailure = `model.list 探测失败:${probed.reason ?? "未返回可判定结果"}`;
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
const rows = probed.rows ?? [];
|
|
64
|
+
const resolved = resolveModelCandidate(hint, rows, goal);
|
|
65
|
+
if (resolved.state === "needs-input") {
|
|
66
|
+
ambiguities.push({ param: key, candidates: resolved.candidates ?? [], question: "目标模型有多个候选,选中哪一个?" });
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
if (resolved.state === "blocked" || resolved.code === undefined) {
|
|
70
|
+
// Zero rows is NOT "pick one from this list" — it is a scope answer, and
|
|
71
|
+
// `model.list` already explains it (the scan is clipped to one app). Asking
|
|
72
|
+
// the user to choose from an empty list is the kind of non-answer that
|
|
73
|
+
// costs a round.
|
|
74
|
+
if (rows.length === 0) {
|
|
75
|
+
blockers.push({
|
|
76
|
+
type: "blocked",
|
|
77
|
+
param: key,
|
|
78
|
+
reason: "model.list 在当前应用里没有返回任何模型(扫描被应用边界裁剪,不代表租户全集)",
|
|
79
|
+
next: environment === null
|
|
80
|
+
? "omc call app.list --env <env> --args '{}'"
|
|
81
|
+
: `omc call app.list --env ${environment} --args '{}'`,
|
|
82
|
+
});
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
ambiguities.push({ param: key, candidates: rows.slice(0, 10), question: "目标句里没有能对上平台的模型,选哪个?" });
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
args[key] = resolved.code;
|
|
89
|
+
if (resolved.warning !== undefined)
|
|
90
|
+
warnings.push(`${key}: ${resolved.warning}`);
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
missing[key] = {
|
|
94
|
+
reason: "查询条件/范围需明确(本计划只读,不替你猜语义)",
|
|
95
|
+
source: `omc describe ${tool.name} --param ${key}`,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
// Query SEMANTICS: `data.list {schemaCode}` is schema-valid and would run, but it
|
|
99
|
+
// returns the whole table — not what 「金额大于一万」 asked for. `ready=true` must
|
|
100
|
+
// not overclaim, so a stated condition with no filter set is a missing input.
|
|
101
|
+
// r60c-F5:reason 回显**问句原文里的条件短语**(≤24 字窗口),不再硬编码
|
|
102
|
+
// 「金额大于一万」——问 10 万回一万,agent 只能再跑一次真调用验证语义。
|
|
103
|
+
const statesCondition = /大于|小于|等于|超过|低于|介于|不等|包含|开头|结尾|为空|不为空|等于|是\s|不是|>|<|>=|<=|=/.test(goal);
|
|
104
|
+
const hasFilterValue = ["filter", "filters", "filterGroup", "query", "rawCondition"].some((key) => args[key] !== undefined);
|
|
105
|
+
if (statesCondition && !hasFilterValue) {
|
|
106
|
+
const target = ["filter", "filters", "filterGroup"].find((key) => key in tool.inputSchema);
|
|
107
|
+
if (target !== undefined) {
|
|
108
|
+
const conditionWindow = goal.match(/[^;;,,。]{0,20}(大于|小于|等于|超过|低于|介于|不等|包含|为空|不为空|>|<|>=|<=|=)[^;;,,。]{0,12}/);
|
|
109
|
+
const conditionEcho = conditionWindow !== null ? conditionWindow[0].trim().replace(/\s*的.*$/u, "") : "问句里的筛选条件";
|
|
110
|
+
const rangeOp = /大于|超过|>|>=|低于|小于|</.test(conditionEcho);
|
|
111
|
+
missing[target] = {
|
|
112
|
+
reason: `问句里有筛选条件,但 filter DSL 需要把「${conditionEcho}」翻译成 {op,field,value}(${rangeOp ? "大于/超过→gt、大于等于→gte、低于/小于→lt" : "等值→eq、包含→like、为空→isnull"},op 全表:eq/neq/gt/lt/gte/lte/like/notlike/in/notin/between/notbetween/isnull/isnotnull);本计划不替你猜字段 code 与取值语义`,
|
|
113
|
+
source: `omc describe ${tool.name} --example ${rangeOp ? "list-filter-equality(等值示例;op 换成上面对应的比较符即可)" : tool.executionMetadata?.recipes[0]?.id ?? "<recipe>"}`,
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
const uncertain = probeFailure !== undefined;
|
|
118
|
+
const pending = new Set(Object.keys(missing));
|
|
119
|
+
const validated = validateStep(tool, args, pending);
|
|
120
|
+
const step = {
|
|
121
|
+
id: "s1",
|
|
122
|
+
tool: tool.name,
|
|
123
|
+
kind: "read",
|
|
124
|
+
purpose: `读:${summarizeForPlan(tool.description)}`,
|
|
125
|
+
args,
|
|
126
|
+
dependsOn: [],
|
|
127
|
+
validated,
|
|
128
|
+
dryRun: { supported: false, notes: "只读步骤没有 dry-run 语义(它本身不写)" },
|
|
129
|
+
};
|
|
130
|
+
if (!uncertain)
|
|
131
|
+
steps.push(step);
|
|
132
|
+
const ready = !uncertain && Object.keys(missing).length === 0 && ambiguities.length === 0 && validated.ok;
|
|
133
|
+
return {
|
|
134
|
+
status: "ok",
|
|
135
|
+
goal,
|
|
136
|
+
environment,
|
|
137
|
+
ready,
|
|
138
|
+
level: uncertain ? 3 : ready ? 1 : 2,
|
|
139
|
+
...(match !== undefined ? { match } : {}),
|
|
140
|
+
...(capability !== undefined ? { capability } : {}),
|
|
141
|
+
...(lane !== undefined ? { lane } : {}),
|
|
142
|
+
steps,
|
|
143
|
+
missing,
|
|
144
|
+
unverified: {},
|
|
145
|
+
warnings,
|
|
146
|
+
ambiguities,
|
|
147
|
+
blockers: uncertain ? [{ type: "uncertain", reason: probeFailure }] : blockers,
|
|
148
|
+
probes,
|
|
149
|
+
planHash: planHash({ goal, environment, tool: tool.name, args, ready }),
|
|
150
|
+
next: ready
|
|
151
|
+
? [`omc call ${tool.name} --env ${environment ?? "<env>"} --args '<上面的 args>'`]
|
|
152
|
+
: [
|
|
153
|
+
...(probes.length > 0 ? probes : []),
|
|
154
|
+
...(tool.executionMetadata?.recipes[0] !== undefined ? [`omc describe ${tool.name} --example ${tool.executionMetadata.recipes[0].id}`] : [`omc describe ${tool.name}`]),
|
|
155
|
+
],
|
|
156
|
+
note: `读路径:${tool.name}(按业务说法排序命中)`,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
/** First sentence of a description, bounded — a purpose line, not prose. */
|
|
160
|
+
function summarizeForPlan(description) {
|
|
161
|
+
const collapsed = description.replace(/\s+/g, " ").trim();
|
|
162
|
+
const stop = collapsed.search(/[。;;!!??]|\.(?=\s|$)/);
|
|
163
|
+
const sentence = stop >= 0 ? collapsed.slice(0, stop) : collapsed;
|
|
164
|
+
return sentence.length > 60 ? `${sentence.slice(0, 59)}…` : sentence;
|
|
165
|
+
}
|
|
166
|
+
/** Which read tool answers each registry-resolvable placeholder (§search-index KEY_RULES). */
|
|
167
|
+
const RESOLVERS = Object.freeze({
|
|
168
|
+
schemaCode: "model.list",
|
|
169
|
+
propertyCode: "field.list",
|
|
170
|
+
workflowCode: "workflow.get_published",
|
|
171
|
+
serviceCode: "service.list",
|
|
172
|
+
sheetCode: "form.get",
|
|
173
|
+
applicationCode: "discover_environment",
|
|
174
|
+
});
|
|
175
|
+
function canonical(value) {
|
|
176
|
+
const sort = (input) => {
|
|
177
|
+
if (Array.isArray(input))
|
|
178
|
+
return input.map(sort);
|
|
179
|
+
if (input !== null && typeof input === "object") {
|
|
180
|
+
return Object.fromEntries(Object.entries(input).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => [k, sort(v)]));
|
|
181
|
+
}
|
|
182
|
+
return input;
|
|
183
|
+
};
|
|
184
|
+
return JSON.stringify(sort(value));
|
|
185
|
+
}
|
|
186
|
+
/** Every string leaf that still looks like a template placeholder. */
|
|
187
|
+
function collectPlaceholders(value, path = "") {
|
|
188
|
+
const out = [];
|
|
189
|
+
const walk = (node, at) => {
|
|
190
|
+
if (typeof node === "string") {
|
|
191
|
+
if (/^<[^<>]+>$/.test(node) || node.includes("omc_recipe_"))
|
|
192
|
+
out.push({ path: at, key: at.split(".")[0] ?? at });
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
if (Array.isArray(node)) {
|
|
196
|
+
node.forEach((entry, index) => walk(entry, `${at}[${index}]`));
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
if (node !== null && typeof node === "object") {
|
|
200
|
+
for (const [key, entry] of Object.entries(node))
|
|
201
|
+
walk(entry, at === "" ? key : `${at}.${key}`);
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
walk(value, path);
|
|
205
|
+
return out;
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* r60b-F4/F5(真机复现):配方示例值不是 `<...>` 模板,collectPlaceholders 认不出,
|
|
209
|
+
* 于是以**具体值**混进 steps 且 validated.ok=true——「给模型 r60b_leave 配两级审批流」
|
|
210
|
+
* 的 plan 里 s1 get_draft 拿着占位 workflowCode "purchaseWorkflow"、s3 的
|
|
211
|
+
* schemaCode 是 "omc_recipe_model"、participant.corpId 写死 "other"(真实 corpId 是
|
|
212
|
+
* 租户 id,照抄会写进已发布流程且 get_published 肉眼难发现)。扫描已编译步骤,
|
|
213
|
+
* 命中残留的 step 标 needsSubstitution:true 并产 warnings;不拦截 ready(有些
|
|
214
|
+
* 残留对存量环境恰好成立),但绝不静默放行。
|
|
215
|
+
*/
|
|
216
|
+
const RECIPE_EXAMPLE_RESIDUE = Object.freeze([
|
|
217
|
+
{ pattern: /purchaseWorkflow/, note: "purchaseWorkflow 是配方示例流程 code,本环境需换成真实/新建的流程 code" },
|
|
218
|
+
{ pattern: /^SYS_1000000$/, note: "SYS_1000000 是配方示例角色 code,用 org.role.list 取真实角色" },
|
|
219
|
+
{ pattern: /"corpId"\s*:\s*"other"/, note: "participant.corpId 写死 \"other\"——真实 corpId 取自 org.role.list 回执(照抄会写入错误 corpId)" },
|
|
220
|
+
{ pattern: /<[a-zA-Z][^<>]{2,60}>/, note: "串内占位符 <…>(如 <roleId-from-org.role.list>)——执行前用真实值替换" },
|
|
221
|
+
{ pattern: /omc_recipe_/, note: "omc_recipe_* 是配方占位模型 code,需先建模型再替换" },
|
|
222
|
+
]);
|
|
223
|
+
function markRecipeResidue(steps) {
|
|
224
|
+
const warnings = [];
|
|
225
|
+
const marked = steps.map((step) => {
|
|
226
|
+
const hits = [];
|
|
227
|
+
const walk = (node, at) => {
|
|
228
|
+
if (typeof node === "string") {
|
|
229
|
+
for (const residue of RECIPE_EXAMPLE_RESIDUE)
|
|
230
|
+
if (residue.pattern.test(node))
|
|
231
|
+
hits.push(`${at || "(root)"}=${node.length > 40 ? `${node.slice(0, 40)}…` : node}(${residue.note})`);
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
if (Array.isArray(node)) {
|
|
235
|
+
node.forEach((entry, index) => walk(entry, `${at}[${index}]`));
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
if (node !== null && typeof node === "object") {
|
|
239
|
+
for (const [key, entry] of Object.entries(node))
|
|
240
|
+
walk(entry, at === "" ? key : `${at}.${key}`);
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
walk(step.args, "");
|
|
244
|
+
if (hits.length === 0)
|
|
245
|
+
return step;
|
|
246
|
+
warnings.push(`${step.id} ${step.tool} 含配方示例值残留(执行前必须替换):${hits.slice(0, 4).join(";")}${hits.length > 4 ? `;等 ${hits.length} 处` : ""}`);
|
|
247
|
+
return { ...step, needsSubstitution: true };
|
|
248
|
+
});
|
|
249
|
+
return [marked, warnings];
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Type-appropriate sample for a placeholder, used ONLY to run the local schema
|
|
253
|
+
* gate: the plan must prove the shape is otherwise valid, without pretending the
|
|
254
|
+
* placeholder is a real value. Never emitted as a step argument.
|
|
255
|
+
*/
|
|
256
|
+
function sampleFor(node) {
|
|
257
|
+
if (node === null || node === undefined)
|
|
258
|
+
return "<value>";
|
|
259
|
+
const shape = node;
|
|
260
|
+
const typeName = shape._def?.typeName;
|
|
261
|
+
if (typeName === "ZodString")
|
|
262
|
+
return "<value>";
|
|
263
|
+
if (typeName === "ZodNumber")
|
|
264
|
+
return 0;
|
|
265
|
+
if (typeName === "ZodBoolean")
|
|
266
|
+
return false;
|
|
267
|
+
if (typeName === "ZodEnum")
|
|
268
|
+
return shape.options?.[0] ?? "<value>";
|
|
269
|
+
if (typeName === "ZodArray")
|
|
270
|
+
return [];
|
|
271
|
+
if (typeName === "ZodObject") {
|
|
272
|
+
// Zod exposes the shape BOTH as `shape` (property) and `_def.shape()` (fn);
|
|
273
|
+
// calling the property blindly throws "shape.shape is not a function".
|
|
274
|
+
const fields = typeof shape.shape === "function"
|
|
275
|
+
? shape.shape()
|
|
276
|
+
: (shape.shape ?? {});
|
|
277
|
+
return Object.fromEntries(Object.entries(fields).map(([key, child]) => [key, sampleFor(child)]));
|
|
278
|
+
}
|
|
279
|
+
return "<value>";
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Local schema gate (M3-6). The Zod schema is authoritative, but a placeholder is
|
|
283
|
+
* by definition not a legal value; validate the SHAPE against Zod itself with a
|
|
284
|
+
* typed sample substituted for the pending slots, so an impossible step (wrong
|
|
285
|
+
* enum, wrong shape) is caught here instead of costing a wire round.
|
|
286
|
+
*/
|
|
287
|
+
function validateStep(tool, args, pending) {
|
|
288
|
+
const issues = [];
|
|
289
|
+
const schemaKeys = new Set(Object.keys(tool.inputSchema));
|
|
290
|
+
for (const key of Object.keys(args))
|
|
291
|
+
if (!schemaKeys.has(key))
|
|
292
|
+
issues.push(`未知参数 ${key}(omc describe ${tool.name} 看合法参数)`);
|
|
293
|
+
const shape = tool.inputSchema;
|
|
294
|
+
for (const [key, node] of Object.entries(shape)) {
|
|
295
|
+
if (typeof node?.isOptional === "function" && node.isOptional())
|
|
296
|
+
continue;
|
|
297
|
+
if (!(key in args))
|
|
298
|
+
issues.push(`缺必填 ${key}`);
|
|
299
|
+
}
|
|
300
|
+
if (issues.length > 0)
|
|
301
|
+
return { ok: false, issues };
|
|
302
|
+
const filled = {};
|
|
303
|
+
for (const [key, entry] of Object.entries(args))
|
|
304
|
+
filled[key] = pending.has(key) ? sampleFor(shape[key]) : entry;
|
|
305
|
+
const parsed = z.object(tool.inputSchema).safeParse(filled);
|
|
306
|
+
if (!parsed.success) {
|
|
307
|
+
for (const issue of parsed.error.issues.slice(0, 5)) {
|
|
308
|
+
issues.push(`${issue.path.join(".") || "(root)"}: ${issue.message}`);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
return { ok: issues.length === 0, issues };
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* M4-2: a placeholder that names an earlier step's readback
|
|
315
|
+
* (`<data.save.performed.bizObjectId>`) becomes a cross-step reference.
|
|
316
|
+
*
|
|
317
|
+
* The reference is a plain string (`$s1.performed.bizObjectId`) so it survives
|
|
318
|
+
* JSON, is visible in the plan, and cannot be mistaken for a legal id — the
|
|
319
|
+
* caller substitutes it after that step succeeds.
|
|
320
|
+
*/
|
|
321
|
+
function crossStepProducer(value, byTool) {
|
|
322
|
+
if (typeof value !== "string")
|
|
323
|
+
return undefined;
|
|
324
|
+
// The authored placeholder already names the producer: `<data.save.performed.bizObjectId>`.
|
|
325
|
+
const match = /^<([A-Za-z][\w.]*)\.performed\.([A-Za-z][\w]*)[^>]*>$/.exec(value);
|
|
326
|
+
if (match === null)
|
|
327
|
+
return undefined;
|
|
328
|
+
const producer = byTool.get(match[1]);
|
|
329
|
+
if (producer === undefined)
|
|
330
|
+
return undefined;
|
|
331
|
+
return { stepId: producer.stepId, reference: `$${producer.stepId}.performed.${match[2]}` };
|
|
332
|
+
}
|
|
333
|
+
/** Replace `$<stepid>.performed.<var>` leaves after that step reports its readback. */
|
|
334
|
+
export function resolveStepReferences(args, values) {
|
|
335
|
+
const walk = (node) => {
|
|
336
|
+
if (typeof node === "string") {
|
|
337
|
+
const match = /^\$(s\d+)\.performed\.([A-Za-z][\w]*)$/.exec(node);
|
|
338
|
+
return match === null ? node : (values[`$${match[1]}.performed.${match[2]}`] ?? node);
|
|
339
|
+
}
|
|
340
|
+
if (Array.isArray(node))
|
|
341
|
+
return node.map(walk);
|
|
342
|
+
if (node !== null && typeof node === "object") {
|
|
343
|
+
return Object.fromEntries(Object.entries(node).map(([key, entry]) => [key, walk(entry)]));
|
|
344
|
+
}
|
|
345
|
+
return node;
|
|
346
|
+
};
|
|
347
|
+
return walk(args);
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* M4-3: which read tool proves a write landed.
|
|
351
|
+
*
|
|
352
|
+
* Explicit where the relationship is not mechanical (`rule.save` → `rule.get`,
|
|
353
|
+
* `data.save` → `data.load`, `programming.publish` → `programming.get`), and a
|
|
354
|
+
* mechanical `X.create → X.get|X.list` / `X.publish → X.get_published` fallback
|
|
355
|
+
* otherwise. A missing read tool yields NO verify block — an invented readback
|
|
356
|
+
* command is worse than none, because it looks like evidence.
|
|
357
|
+
*/
|
|
358
|
+
const READBACK_TOOL = Object.freeze({
|
|
359
|
+
"rule.save": "rule.get",
|
|
360
|
+
"data.save": "data.load",
|
|
361
|
+
"data.update": "data.load",
|
|
362
|
+
"data.submit": "data.load",
|
|
363
|
+
"data.delete": "data.list",
|
|
364
|
+
"field.create": "field.list",
|
|
365
|
+
"field.update": "field.list",
|
|
366
|
+
"field.delete": "field.list",
|
|
367
|
+
"field.publish": "field.list",
|
|
368
|
+
"form.publish": "form.get",
|
|
369
|
+
"form.draft": "form.get",
|
|
370
|
+
"workflow.publish": "workflow.get_published",
|
|
371
|
+
"workflow.create": "workflow.get_draft",
|
|
372
|
+
"workflow.update": "workflow.get_draft",
|
|
373
|
+
"listview.configure": "listview.get",
|
|
374
|
+
"listview.create": "listview.list",
|
|
375
|
+
"onlinejs.compose": "onlinejs.get",
|
|
376
|
+
"datarule.create": "datarule.list",
|
|
377
|
+
"datarule.update": "datarule.list",
|
|
378
|
+
"datarule.delete": "datarule.list",
|
|
379
|
+
"dictionary.save": "dictionary.get",
|
|
380
|
+
"dictionary.class.save": "dictionary.classes",
|
|
381
|
+
"service.register": "service.get",
|
|
382
|
+
"service.update": "service.get",
|
|
383
|
+
"method.create": "method.get",
|
|
384
|
+
"method.update": "method.get",
|
|
385
|
+
"programming.publish": "programming.get",
|
|
386
|
+
"programming.save": "programming.get",
|
|
387
|
+
"perm.assign": "perm.groups",
|
|
388
|
+
"perm.auth": "perm.user",
|
|
389
|
+
"perm.group": "perm.groups",
|
|
390
|
+
"rule.enable": "rule.get",
|
|
391
|
+
"rule.disable": "rule.get",
|
|
392
|
+
"model.create": "model.list",
|
|
393
|
+
"model.update": "model.list",
|
|
394
|
+
"app.create": "app.list",
|
|
395
|
+
"app.update": "app.list",
|
|
396
|
+
"folder.create": "folder.tree",
|
|
397
|
+
"folder.update": "folder.tree",
|
|
398
|
+
});
|
|
399
|
+
/** Mechanical fallback for a write tool with no explicit readback mapping. */
|
|
400
|
+
function mechanicalReadback(toolName) {
|
|
401
|
+
const [family, action] = toolName.split(".");
|
|
402
|
+
if (family === undefined || action === undefined)
|
|
403
|
+
return undefined;
|
|
404
|
+
if (action === "publish")
|
|
405
|
+
return `${family}.get_published`;
|
|
406
|
+
if (["create", "update", "save", "delete", "configure", "compose", "enable", "disable", "run"].includes(action))
|
|
407
|
+
return `${family}.get`;
|
|
408
|
+
return undefined;
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* M4-3: build the verify block for one step. The read command reuses only the
|
|
412
|
+
* identifiers the read tool actually requires (from ITS inputSchema), so the
|
|
413
|
+
* predicate is runnable rather than aspirational.
|
|
414
|
+
*/
|
|
415
|
+
function verifyFor(registry, step, expects) {
|
|
416
|
+
if (expects === undefined || Object.keys(expects).length === 0)
|
|
417
|
+
return undefined;
|
|
418
|
+
const readerName = READBACK_TOOL[step.tool] ?? mechanicalReadback(step.tool);
|
|
419
|
+
if (readerName === undefined)
|
|
420
|
+
return undefined;
|
|
421
|
+
const reader = registry.find((entry) => entry.name === readerName);
|
|
422
|
+
if (reader === undefined)
|
|
423
|
+
return undefined;
|
|
424
|
+
const readerArgs = {};
|
|
425
|
+
for (const key of Object.keys(reader.inputSchema)) {
|
|
426
|
+
if (key in step.args && step.args[key] !== undefined)
|
|
427
|
+
readerArgs[key] = step.args[key];
|
|
428
|
+
}
|
|
429
|
+
const required = Object.entries(reader.inputSchema)
|
|
430
|
+
.filter(([, node]) => typeof node?.isOptional !== "function" || node.isOptional() === false)
|
|
431
|
+
.map(([key]) => key)
|
|
432
|
+
// `environment` is filled by the CLI flag, not authored into the read args.
|
|
433
|
+
.filter((key) => key !== "environment");
|
|
434
|
+
const missing = required.filter((key) => !(key in readerArgs));
|
|
435
|
+
const note = missing.length === 0
|
|
436
|
+
? `读回:${readerName};把结果与 expects 对齐(字段缺失即写入未生效)`
|
|
437
|
+
: `读回:${readerName},但它还需要 ${missing.join("/")}(由前序步骤或调用方补)`;
|
|
438
|
+
const predicate = (expects.readback !== undefined && typeof expects.readback === "object"
|
|
439
|
+
? expects.readback
|
|
440
|
+
: expects);
|
|
441
|
+
return {
|
|
442
|
+
tool: readerName,
|
|
443
|
+
args: readerArgs,
|
|
444
|
+
expects: predicate,
|
|
445
|
+
note,
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* M4-1/M4-2: compile the authored `priorToolReferences` into real steps.
|
|
450
|
+
*
|
|
451
|
+
* They are not all "read confirmations": `workflow-backed-data-submit` names
|
|
452
|
+
* `data.save` as the step that PRODUCES bizObjectId/workflowInstanceId/
|
|
453
|
+
* workItemId. A plan that flattened them all to reads would hide a write.
|
|
454
|
+
*
|
|
455
|
+
* `captures` come from the recipe's `expectedReadback.performed.captures`, which
|
|
456
|
+
* is the only authored statement of "which values this step yields".
|
|
457
|
+
*/
|
|
458
|
+
function compilePriorSteps(registry, recipe, environment, startIndex) {
|
|
459
|
+
const captures = (recipe.expectedReadback?.performed?.captures) ?? [];
|
|
460
|
+
const steps = [];
|
|
461
|
+
const byTool = new Map();
|
|
462
|
+
const capturesByTool = new Map();
|
|
463
|
+
const priors = recipe.priorToolReferences ?? [];
|
|
464
|
+
priors.forEach((prior, offset) => {
|
|
465
|
+
const id = `s${startIndex + offset}`;
|
|
466
|
+
const tool = registry.find((entry) => entry.name === prior.tool);
|
|
467
|
+
const args = {};
|
|
468
|
+
for (const [key, value] of Object.entries(prior.args)) {
|
|
469
|
+
args[key] = value === "<environment>" ? (environment ?? "<environment>") : value;
|
|
470
|
+
}
|
|
471
|
+
const isWriter = tool?.kind === "write";
|
|
472
|
+
// The authored `captures` belong to the step that PRODUCES them: the first
|
|
473
|
+
// writing prerequisite (data.save before data.submit). A recipe whose priors
|
|
474
|
+
// are all reads (field.list) has no producing step, so no captures.
|
|
475
|
+
const produces = captureVarsFor(prior.tool, offset, priors, captures);
|
|
476
|
+
steps.push({
|
|
477
|
+
id,
|
|
478
|
+
tool: prior.tool,
|
|
479
|
+
kind: isWriter ? "write" : "read",
|
|
480
|
+
purpose: prior.purpose,
|
|
481
|
+
args,
|
|
482
|
+
dependsOn: [],
|
|
483
|
+
...(produces.length > 0 ? { captures: produces } : {}),
|
|
484
|
+
validated: tool === undefined
|
|
485
|
+
? { ok: false, issues: [`未知工具 ${prior.tool}`] }
|
|
486
|
+
: validateStep(tool, args, new Set(Object.keys(args).filter((key) => typeof args[key] === "string" && String(args[key]).includes("<")))),
|
|
487
|
+
dryRun: dryRunFor(prior.tool, args, tool),
|
|
488
|
+
...(() => {
|
|
489
|
+
const verify = verifyFor(registry, { tool: prior.tool, args }, undefined);
|
|
490
|
+
return verify === undefined ? {} : { verify };
|
|
491
|
+
})(),
|
|
492
|
+
});
|
|
493
|
+
byTool.set(prior.tool, { stepId: id, kind: isWriter ? "write" : "read" });
|
|
494
|
+
if (produces.length > 0)
|
|
495
|
+
capturesByTool.set(prior.tool, { stepId: id, vars: produces });
|
|
496
|
+
});
|
|
497
|
+
return { steps, byTool, capturesByTool };
|
|
498
|
+
}
|
|
499
|
+
/**
|
|
500
|
+
* Which variables a prior step yields. The recipe declares them once
|
|
501
|
+
* (`expectedReadback.performed.captures`); a step owns them when it is the
|
|
502
|
+
* AUTHORED producer — i.e. the prior that writes, or the one named in the
|
|
503
|
+
* placeholder path (`<data.save.performed.bizObjectId>` → tool `data.save`).
|
|
504
|
+
*/
|
|
505
|
+
function captureVarsFor(priorTool, offset, priors, captures) {
|
|
506
|
+
if (captures.length === 0)
|
|
507
|
+
return [];
|
|
508
|
+
// Ownership rule: the first prior whose action creates/saves/produces a row.
|
|
509
|
+
const producerIndex = priors.findIndex((entry) => /^(data\.save|data\.update|data\.submit|rule\.save|field\.create|field\.update|.*\.create|.*\.update|.*\.save|.*\.register|.*\.compose)$/.test(entry.tool));
|
|
510
|
+
// No producing prior: don't invent one — the captures stay unowned.
|
|
511
|
+
return producerIndex === offset && priors[offset]?.tool === priorTool ? captures : [];
|
|
512
|
+
}
|
|
513
|
+
/** M4-4: the dry-run form of one step (no wire side effects). */
|
|
514
|
+
function dryRunFor(toolName, args, tool) {
|
|
515
|
+
if (tool === undefined)
|
|
516
|
+
return { supported: false, notes: "工具不在注册表里,无法判定 dry-run" };
|
|
517
|
+
if (tool.kind !== "write")
|
|
518
|
+
return { supported: false, notes: "只读步骤没有 dry-run 语义(它本身不写)" };
|
|
519
|
+
const envFlag = typeof args.environment === "string" ? ` --env ${args.environment}` : "";
|
|
520
|
+
const payload = JSON.stringify(args);
|
|
521
|
+
// A single quote cannot ride inside `--args '<json>'`; name the safe transport.
|
|
522
|
+
const transport = payload.includes("'") ? "--args -(stdin,本步 args 含单引号)" : `--args '${payload}'`;
|
|
523
|
+
return {
|
|
524
|
+
supported: true,
|
|
525
|
+
command: `omc call ${toolName}${envFlag} --dry-run ${transport}`,
|
|
526
|
+
notes: "dry-run 只校验输入与治理,不写环境;真实结果仍需执行后读回",
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
/**
|
|
530
|
+
* Ladder merging: give one segment's steps a namespace (`p1-s2`) and rewrite its
|
|
531
|
+
* internal references, so two segments never collide on `s1`.
|
|
532
|
+
*/
|
|
533
|
+
function prefixPlanSteps(plan, prefix) {
|
|
534
|
+
const rewrite = (value) => {
|
|
535
|
+
if (typeof value === "string")
|
|
536
|
+
return value.replace(/\$s(\d+)\.performed\./g, `$${prefix}-s$1.performed.`);
|
|
537
|
+
if (Array.isArray(value))
|
|
538
|
+
return value.map(rewrite);
|
|
539
|
+
if (value !== null && typeof value === "object") {
|
|
540
|
+
return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, rewrite(entry)]));
|
|
541
|
+
}
|
|
542
|
+
return value;
|
|
543
|
+
};
|
|
544
|
+
const steps = plan.steps.map((step) => ({
|
|
545
|
+
...step,
|
|
546
|
+
id: `${prefix}-${step.id}`,
|
|
547
|
+
dependsOn: step.dependsOn.map((id) => `${prefix}-${id}`),
|
|
548
|
+
args: rewrite(step.args),
|
|
549
|
+
...(step.verify !== undefined ? { verify: { ...step.verify, args: rewrite(step.verify.args) } } : {}),
|
|
550
|
+
}));
|
|
551
|
+
return { ...plan, steps };
|
|
552
|
+
}
|
|
553
|
+
/**
|
|
554
|
+
* M4-2: re-derive `captures` from what the plan actually REFERENCES.
|
|
555
|
+
*
|
|
556
|
+
* The recipe's own `expectedReadback.performed.captures` describes its own
|
|
557
|
+
* readback; a downstream recipe (`data.submit`) holds `<data.save.performed.*>`
|
|
558
|
+
* instead. Deriving captures from those references keeps both honest without
|
|
559
|
+
* cross-reading another recipe's metadata.
|
|
560
|
+
*/
|
|
561
|
+
function attachCaptures(steps) {
|
|
562
|
+
const referenced = new Map();
|
|
563
|
+
const scan = (node) => {
|
|
564
|
+
if (typeof node === "string") {
|
|
565
|
+
const match = /^\$(s\d+)\.performed\.([A-Za-z][\w]*)$/.exec(node);
|
|
566
|
+
if (match !== null) {
|
|
567
|
+
const set = referenced.get(match[1]) ?? new Set();
|
|
568
|
+
set.add(match[2]);
|
|
569
|
+
referenced.set(match[1], set);
|
|
570
|
+
}
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
if (Array.isArray(node)) {
|
|
574
|
+
for (const entry of node)
|
|
575
|
+
scan(entry);
|
|
576
|
+
return;
|
|
577
|
+
}
|
|
578
|
+
if (node !== null && typeof node === "object")
|
|
579
|
+
for (const entry of Object.values(node))
|
|
580
|
+
scan(entry);
|
|
581
|
+
};
|
|
582
|
+
for (const step of steps)
|
|
583
|
+
scan(step.args);
|
|
584
|
+
return steps.map((step) => {
|
|
585
|
+
const vars = referenced.get(step.id);
|
|
586
|
+
if (vars === undefined || vars.size === 0)
|
|
587
|
+
return step;
|
|
588
|
+
const merged = new Set([...(step.captures ?? []), ...vars]);
|
|
589
|
+
return { ...step, captures: [...merged] };
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
/**
|
|
593
|
+
* M4-2: topological order with cycle detection. Steps come in authored order;
|
|
594
|
+
* the sort makes dependencies explicit so a caller (or `omc script`) can run the
|
|
595
|
+
* list top to bottom without reasoning about it.
|
|
596
|
+
*/
|
|
597
|
+
export function topoSort(steps) {
|
|
598
|
+
const byId = new Map(steps.map((step) => [step.id, step]));
|
|
599
|
+
const ordered = [];
|
|
600
|
+
const state = new Map();
|
|
601
|
+
const path = [];
|
|
602
|
+
const visit = (id) => {
|
|
603
|
+
const mark = state.get(id);
|
|
604
|
+
if (mark === "done")
|
|
605
|
+
return true;
|
|
606
|
+
if (mark === "visiting") {
|
|
607
|
+
path.push(id);
|
|
608
|
+
return false;
|
|
609
|
+
}
|
|
610
|
+
const step = byId.get(id);
|
|
611
|
+
if (step === undefined)
|
|
612
|
+
return true;
|
|
613
|
+
state.set(id, "visiting");
|
|
614
|
+
for (const dependency of step.dependsOn) {
|
|
615
|
+
if (!visit(dependency)) {
|
|
616
|
+
path.unshift(id);
|
|
617
|
+
return false;
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
state.set(id, "done");
|
|
621
|
+
ordered.push(step);
|
|
622
|
+
return true;
|
|
623
|
+
};
|
|
624
|
+
for (const step of steps) {
|
|
625
|
+
if (!visit(step.id))
|
|
626
|
+
return { ordered: [], cycle: path };
|
|
627
|
+
}
|
|
628
|
+
return { ordered };
|
|
629
|
+
}
|
|
630
|
+
/** Step ids that cannot run standalone (cross-step refs or failed local gate). */
|
|
631
|
+
export function selfContainedSteps(steps) {
|
|
632
|
+
return steps.filter((step) => step.dependsOn.length === 0 && step.validated.ok
|
|
633
|
+
&& JSON.stringify(step.args).includes("<") === false);
|
|
634
|
+
}
|
|
635
|
+
function planHash(parts) {
|
|
636
|
+
return createHash("sha256").update(canonical(parts)).digest("hex");
|
|
637
|
+
}
|
|
638
|
+
/** `model.list` rows → the model candidate list used by the schemaCode state machine. */
|
|
639
|
+
function modelsOf(result) {
|
|
640
|
+
const rows = Array.isArray(result?.models) ? result.models : [];
|
|
641
|
+
return rows
|
|
642
|
+
.filter((row) => typeof row.code === "string" || typeof row.schemaCode === "string")
|
|
643
|
+
.map((row) => ({ code: String(row.schemaCode ?? row.code), name: String(row.name ?? row.schemaCode ?? row.code) }));
|
|
644
|
+
}
|
|
645
|
+
/**
|
|
646
|
+
* schemaCode state machine (BIG-REFACTOR-PLAN-V2 §4.2):
|
|
647
|
+
* zero rows → blocked / one → resolved / one fuzzy → warning / many → needs-input
|
|
648
|
+
* It never guesses among candidates — that is the whole point.
|
|
649
|
+
*
|
|
650
|
+
* `goal` is used for the strongest hint a human actually gives: naming the object
|
|
651
|
+
* in the sentence («给**采购合同**加两位小数»). A candidate whose NAME or CODE
|
|
652
|
+
* appears verbatim in the goal beats any fuzzy string distance, and the longest
|
|
653
|
+
* such name wins («采购合同台账» must not be shadowed by a shorter «合同» row).
|
|
654
|
+
*/
|
|
655
|
+
export function resolveModelCandidate(hint, models, goal = "") {
|
|
656
|
+
if (models.length === 0)
|
|
657
|
+
return { state: "blocked", reason: "model-not-found" };
|
|
658
|
+
const needle = hint.trim();
|
|
659
|
+
const exact = needle === "" ? [] : models.filter((model) => model.code === needle);
|
|
660
|
+
if (exact.length === 1)
|
|
661
|
+
return { state: "resolved", code: exact[0].code };
|
|
662
|
+
const byName = needle === "" ? [] : models.filter((model) => model.name === needle);
|
|
663
|
+
if (byName.length === 1)
|
|
664
|
+
return { state: "resolved-with-warning", code: byName[0].code, warning: `按名称「${needle}」唯一匹配 ${byName[0].code}` };
|
|
665
|
+
// Named in the sentence: match the model's own strings against the goal text.
|
|
666
|
+
const mentioned = models
|
|
667
|
+
.map((model) => {
|
|
668
|
+
const hits = [model.name, model.code].filter((text) => text.length >= 2 && goal.includes(text));
|
|
669
|
+
const longest = hits.reduce((best, text) => (text.length > best.length ? text : best), "");
|
|
670
|
+
return { model, longest };
|
|
671
|
+
})
|
|
672
|
+
.filter((entry) => entry.longest !== "")
|
|
673
|
+
// Longest mention wins; a row whose name is a substring of another matched
|
|
674
|
+
// row's name is the container, not the target.
|
|
675
|
+
.filter((entry, _index, all) => !all.some((other) => other !== entry && other.longest.length > entry.longest.length && other.longest.includes(entry.longest)));
|
|
676
|
+
if (mentioned.length === 1) {
|
|
677
|
+
return { state: "resolved-with-warning", code: mentioned[0].model.code, warning: `目标句提到「${mentioned[0].longest}」,据此选中 ${mentioned[0].model.code}` };
|
|
678
|
+
}
|
|
679
|
+
if (mentioned.length > 1) {
|
|
680
|
+
return { state: "needs-input", candidates: mentioned.map((entry) => entry.model).slice(0, 10) };
|
|
681
|
+
}
|
|
682
|
+
// Nothing named anywhere: that is a question with the full shortlist, not a
|
|
683
|
+
// model-not-found (the difference decides whether the agent asks or gives up).
|
|
684
|
+
if (needle === "")
|
|
685
|
+
return { state: "needs-input", candidates: models.slice(0, 10) };
|
|
686
|
+
const fuzzy = models.filter((model) => model.code.includes(needle) || String(model.name).includes(needle));
|
|
687
|
+
if (exact.length > 1 || byName.length > 1 || fuzzy.length > 1) {
|
|
688
|
+
return { state: "needs-input", candidates: (exact.length > 1 ? exact : byName.length > 1 ? byName : fuzzy).slice(0, 10) };
|
|
689
|
+
}
|
|
690
|
+
if (fuzzy.length === 1)
|
|
691
|
+
return { state: "resolved-with-warning", code: fuzzy[0].code, warning: `「${needle}」模糊匹配到 ${fuzzy[0].code}(${fuzzy[0].name}),请核对` };
|
|
692
|
+
return { state: "blocked", reason: "model-not-found" };
|
|
693
|
+
}
|
|
694
|
+
/**
|
|
695
|
+
* Build a plan. PURE except for the injected probe runner — no writes, ever.
|
|
696
|
+
*/
|
|
697
|
+
export async function planGoal(registry, goal, options = {}) {
|
|
698
|
+
const explicit = options.target;
|
|
699
|
+
const route = explicit === undefined
|
|
700
|
+
? goalRoute(registry, goal)
|
|
701
|
+
: {
|
|
702
|
+
status: "ok",
|
|
703
|
+
goal,
|
|
704
|
+
confident: true,
|
|
705
|
+
mode: "build",
|
|
706
|
+
write: true,
|
|
707
|
+
match: { kind: "recipe", ref: explicit.recipe, tool: explicit.tool, recipe: explicit.recipe },
|
|
708
|
+
route: { capability: undefined, lane: undefined, firstCommands: [] },
|
|
709
|
+
};
|
|
710
|
+
const environment = options.environment ?? null;
|
|
711
|
+
const base = {
|
|
712
|
+
status: "ok",
|
|
713
|
+
goal,
|
|
714
|
+
environment,
|
|
715
|
+
missing: {},
|
|
716
|
+
unverified: {},
|
|
717
|
+
warnings: [],
|
|
718
|
+
ambiguities: [],
|
|
719
|
+
blockers: [],
|
|
720
|
+
probes: [],
|
|
721
|
+
steps: [],
|
|
722
|
+
};
|
|
723
|
+
// Level 4: the goal did not route. Hand back the routing faces, not a guess.
|
|
724
|
+
if (route.confident !== true || route.route === null) {
|
|
725
|
+
const plan = {
|
|
726
|
+
...base,
|
|
727
|
+
ready: false,
|
|
728
|
+
level: 4,
|
|
729
|
+
...(route.match !== undefined ? { match: route.match } : {}),
|
|
730
|
+
blockers: [{ type: "route-uncertain", reason: "目标未命中任何能力/配方", hint: route.fallback ?? "换能力词或先 omc next 看路线" }],
|
|
731
|
+
planHash: planHash({ goal, environment, level: 4 }),
|
|
732
|
+
next: [`omc next "${goal}"`, "omc capabilities", "omc commands --filter <关键词>"],
|
|
733
|
+
};
|
|
734
|
+
return plan;
|
|
735
|
+
}
|
|
736
|
+
const lane = typeof route.route.lane === "string" ? route.route.lane : undefined;
|
|
737
|
+
const capability = typeof route.route.capability === "string" ? route.route.capability : undefined;
|
|
738
|
+
const intentPrimary = route.route.primary === "intent" || route.mode === "whole-package";
|
|
739
|
+
// Level 5: the ask is a whole configuration package. The declarative intent
|
|
740
|
+
// compiler owns that; an atomic call chain would be strictly worse.
|
|
741
|
+
if (intentPrimary) {
|
|
742
|
+
return {
|
|
743
|
+
...base,
|
|
744
|
+
ready: false,
|
|
745
|
+
level: 5,
|
|
746
|
+
...(route.match !== undefined ? { match: route.match } : {}),
|
|
747
|
+
...(capability !== undefined ? { capability } : {}),
|
|
748
|
+
...(lane !== undefined ? { lane } : {}),
|
|
749
|
+
blockers: [{ type: "declarative-face", reason: "整包需求由 intent 编译器承接(模型/字段/规则/流程按依赖排序、可 readback 对账)", why: "原子 call 链无法保证顺序与幂等" }],
|
|
750
|
+
planHash: planHash({ goal, environment, level: 5 }),
|
|
751
|
+
next: ["omc intent schema", "omc intent validate <file>", "omc intent plan <file> --env <env>"],
|
|
752
|
+
};
|
|
753
|
+
}
|
|
754
|
+
const match = route.match;
|
|
755
|
+
// Composer: a CLI management face (form-default / field-add / model-scaffold …).
|
|
756
|
+
// It has no registry recipe to fill, so a plan cannot hand out copyable args —
|
|
757
|
+
// say so and hand back the composer's own `--help` instead of pretending.
|
|
758
|
+
if (match?.kind === "composer") {
|
|
759
|
+
return {
|
|
760
|
+
...base,
|
|
761
|
+
ready: false,
|
|
762
|
+
level: 2,
|
|
763
|
+
match,
|
|
764
|
+
...(capability !== undefined ? { capability } : {}),
|
|
765
|
+
...(lane !== undefined ? { lane } : {}),
|
|
766
|
+
blockers: [{
|
|
767
|
+
type: "composer",
|
|
768
|
+
composer: match.ref,
|
|
769
|
+
reason: "该目标由拼装器(CLI 管理面)承接,不是 call 工具:参数由它自己的 --help 定义",
|
|
770
|
+
...(match.command !== undefined ? { command: match.command } : {}),
|
|
771
|
+
...(route.firstAnswer?.question !== undefined ? { hint: route.firstAnswer.question } : {}),
|
|
772
|
+
}],
|
|
773
|
+
planHash: planHash({ goal, environment, level: 2, composer: match.ref }),
|
|
774
|
+
next: [
|
|
775
|
+
...(match.command !== undefined ? [match.command] : []),
|
|
776
|
+
`omc ${match.ref ?? "<composer>"} --help`,
|
|
777
|
+
],
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
const toolName = match?.tool;
|
|
781
|
+
const recipeId = match?.recipe;
|
|
782
|
+
// Ladder: the goal spans capabilities and the route is an ORDERED list of
|
|
783
|
+
// segments. M4 compiles every segment into its own steps and concatenates them
|
|
784
|
+
// in the authored order — the dependency order IS the ladder order.
|
|
785
|
+
if (match?.kind === "ladder" && Array.isArray(route.route.ladder)) {
|
|
786
|
+
const ladder = route.route.ladder;
|
|
787
|
+
const segments = ladder.filter((step) => step.recipe?.tool !== undefined && step.recipe.id !== undefined);
|
|
788
|
+
if (segments.length === 0) {
|
|
789
|
+
return {
|
|
790
|
+
...base,
|
|
791
|
+
ready: false,
|
|
792
|
+
level: 2,
|
|
793
|
+
match,
|
|
794
|
+
blockers: [{ type: "blocked", reason: "阶梯里没有可编译的配方" }],
|
|
795
|
+
planHash: planHash({ goal, environment, level: 2 }),
|
|
796
|
+
next: ["omc capabilities"],
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
// One probe cache: every segment asks `model.list`; asking per segment would
|
|
800
|
+
// multiply the wire cost without changing the answer.
|
|
801
|
+
const memo = new Map();
|
|
802
|
+
const cachedProbe = options.probe === undefined ? undefined : (tool, args) => {
|
|
803
|
+
const key = `${tool}:${JSON.stringify(args)}`;
|
|
804
|
+
const hit = memo.get(key);
|
|
805
|
+
if (hit !== undefined)
|
|
806
|
+
return hit;
|
|
807
|
+
const started = options.probe(tool, args);
|
|
808
|
+
memo.set(key, started);
|
|
809
|
+
return started;
|
|
810
|
+
};
|
|
811
|
+
const children = [];
|
|
812
|
+
for (const [index, segment] of segments.entries()) {
|
|
813
|
+
const child = await planGoal(registry, goal, {
|
|
814
|
+
...options,
|
|
815
|
+
...(cachedProbe !== undefined ? { probe: cachedProbe } : {}),
|
|
816
|
+
target: { tool: segment.recipe.tool, recipe: segment.recipe.id },
|
|
817
|
+
});
|
|
818
|
+
children.push(prefixPlanSteps(child, `p${index + 1}`));
|
|
819
|
+
}
|
|
820
|
+
const steps = children.flatMap((child) => child.steps);
|
|
821
|
+
const ready = children.length > 0 && children.every((child) => child.ready);
|
|
822
|
+
// M4-7 at ladder level: the declaration face is the better compiler for a
|
|
823
|
+
// multi-capability package whenever any segment needs authored payload.
|
|
824
|
+
const authoredSegments = segments
|
|
825
|
+
.map((segment, index) => ({ capability: segment.capability, index }))
|
|
826
|
+
.filter((entry) => entry.capability !== undefined
|
|
827
|
+
&& children[entry.index].blockers.some((blocker) => blocker.type === "needs-authoring")
|
|
828
|
+
&& capabilityHasDeclarativeFace(registry, entry.capability));
|
|
829
|
+
const intentAlternative = authoredSegments.length > 0
|
|
830
|
+
? {
|
|
831
|
+
available: true,
|
|
832
|
+
why: `${authoredSegments.map((entry) => entry.capability).join("、")} 有声明式面:整段配置写成 intent 文件后由编译器排序并 readback 对账,不必逐段手拼载荷`,
|
|
833
|
+
commands: ["omc intent schema", "omc intent validate <file>", "omc intent plan <file> --env <env>"],
|
|
834
|
+
}
|
|
835
|
+
: undefined;
|
|
836
|
+
const level = ready ? 1 : (children.some((child) => child.level === 3) ? 3 : 2);
|
|
837
|
+
return {
|
|
838
|
+
status: "ok",
|
|
839
|
+
goal,
|
|
840
|
+
environment,
|
|
841
|
+
ready,
|
|
842
|
+
level,
|
|
843
|
+
match,
|
|
844
|
+
...(capability !== undefined ? { capability } : {}),
|
|
845
|
+
...(lane !== undefined ? { lane } : {}),
|
|
846
|
+
...(intentAlternative !== undefined ? { intentAlternative } : {}),
|
|
847
|
+
steps,
|
|
848
|
+
// Segment-qualified so two segments that both need `code` stay distinguishable.
|
|
849
|
+
missing: Object.fromEntries(children.flatMap((child, index) => Object.entries(child.missing).map(([key, value]) => [`p${index + 1}.${key}`, value]))),
|
|
850
|
+
unverified: Object.fromEntries(children.flatMap((child, index) => Object.entries(child.unverified).map(([key, value]) => [`p${index + 1}.${key}`, value]))),
|
|
851
|
+
warnings: children.flatMap((child) => child.warnings),
|
|
852
|
+
ambiguities: children.flatMap((child, index) => child.ambiguities.map((entry) => ({ ...entry, param: `p${index + 1}.${entry.param}` }))),
|
|
853
|
+
blockers: children.flatMap((child) => child.blockers),
|
|
854
|
+
probes: [...new Set(children.flatMap((child) => child.probes))],
|
|
855
|
+
planHash: planHash({ goal, environment, ladder: segments.map((segment) => segment.recipe.id), steps: steps.map((step) => ({ id: step.id, tool: step.tool, args: step.args })) }),
|
|
856
|
+
next: ready
|
|
857
|
+
? [`omc plan "${goal}" --env ${environment ?? "<env>"} --ndjson`]
|
|
858
|
+
: [...new Set([...(intentAlternative !== undefined ? intentAlternative.commands : []), ...children.flatMap((child) => child.next)])],
|
|
859
|
+
note: `阶梯 ${segments.length} 段已按依赖顺序编译(${segments.map((segment) => segment.recipe.id).join(" → ")})`,
|
|
860
|
+
};
|
|
861
|
+
}
|
|
862
|
+
if (toolName === undefined || recipeId === undefined) {
|
|
863
|
+
// READ ask (M6): the route only says "this is a read across these
|
|
864
|
+
// capabilities" — it does not pick the tool. Ranking the registry with the
|
|
865
|
+
// M1 search face answers "which read tool", and resolving the model the ask
|
|
866
|
+
// names turns that into a runnable step. Returning just "give me a
|
|
867
|
+
// schemaCode" would be smaller and useless: bytes bought with rounds.
|
|
868
|
+
if (route.mode === "read" || Array.isArray(route.route.readTools)) {
|
|
869
|
+
return await planReadAsk(registry, goal, environment, options, base, match, capability, lane);
|
|
870
|
+
}
|
|
871
|
+
return {
|
|
872
|
+
...base,
|
|
873
|
+
ready: false,
|
|
874
|
+
level: 2,
|
|
875
|
+
...(match !== undefined ? { match } : {}),
|
|
876
|
+
...(capability !== undefined ? { capability } : {}),
|
|
877
|
+
...(lane !== undefined ? { lane } : {}),
|
|
878
|
+
blockers: [{ type: "needs-input", reason: "该能力没有命中配方", hint: route.firstAnswer?.question ?? "给我 schemaCode(或模型业务名,我列清单核对)" }],
|
|
879
|
+
probes: ["omc call model.list --env <env> --args '{}'"],
|
|
880
|
+
planHash: planHash({ goal, environment, level: 2 }),
|
|
881
|
+
next: ["omc call model.list --env <env> --args '{}'", ...(capability !== undefined ? [`omc capability ${capability}`] : [])],
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
const tool = registry.find((entry) => entry.name === toolName);
|
|
885
|
+
const recipe = tool?.executionMetadata?.recipes.find((entry) => entry.id === recipeId);
|
|
886
|
+
if (tool === undefined || recipe === undefined) {
|
|
887
|
+
return {
|
|
888
|
+
...base,
|
|
889
|
+
ready: false,
|
|
890
|
+
level: 4,
|
|
891
|
+
blockers: [{ type: "blocked", reason: `路由指向的配方不存在:${toolName}/${recipeId}` }],
|
|
892
|
+
planHash: planHash({ goal, environment, level: 4 }),
|
|
893
|
+
next: ["omc capabilities", `omc describe ${toolName}`],
|
|
894
|
+
};
|
|
895
|
+
}
|
|
896
|
+
const rawArgs = recipe.args;
|
|
897
|
+
// M4-1: authored prerequisites become real steps (`data.save` before
|
|
898
|
+
// `data.submit`, `field.list` before a datarule). Without this the plan called
|
|
899
|
+
// a step "blocked" merely because its identity comes from an earlier step.
|
|
900
|
+
const priorCompiled = compilePriorSteps(registry, recipe, environment, 1);
|
|
901
|
+
const mainStepId = `s${priorCompiled.steps.length + 1}`;
|
|
902
|
+
// `dependsOn` means DATA dependency (a value flows in), not sequence. Prior
|
|
903
|
+
// read confirmations are ordered by the step array; only a step that PRODUCES a
|
|
904
|
+
// referenced value is a dependency — otherwise NDJSON would drop every step
|
|
905
|
+
// that happens to follow a confirmation read.
|
|
906
|
+
const dependencies = new Set();
|
|
907
|
+
const args = {};
|
|
908
|
+
const pending = new Set();
|
|
909
|
+
const missing = {};
|
|
910
|
+
const unverified = {};
|
|
911
|
+
const warnings = [];
|
|
912
|
+
const ambiguities = [];
|
|
913
|
+
const blockers = [];
|
|
914
|
+
const probes = [];
|
|
915
|
+
let probeFailure;
|
|
916
|
+
// ---- resolve one slot at a time -------------------------------------------------
|
|
917
|
+
for (const [key, value] of Object.entries(rawArgs)) {
|
|
918
|
+
// The environment is never a probe: `--env` already is the answer, and the
|
|
919
|
+
// recipe's `<environment>` stand-in must not survive into a step.
|
|
920
|
+
if (key === "environment") {
|
|
921
|
+
if (environment !== null)
|
|
922
|
+
args.environment = environment;
|
|
923
|
+
else
|
|
924
|
+
pending.add(key);
|
|
925
|
+
continue;
|
|
926
|
+
}
|
|
927
|
+
const rule = paramFillRuleFor(tool.name, recipe.id, key);
|
|
928
|
+
const placeholders = collectPlaceholders(value, key);
|
|
929
|
+
const needsValue = placeholders.length > 0;
|
|
930
|
+
args[key] = value;
|
|
931
|
+
// A concrete value can still be WRONG for this environment: every recipe was
|
|
932
|
+
// authored against an example tenant (`schemaCode: "crm_contract"`). Registry
|
|
933
|
+
// ids are therefore verified even when they look filled.
|
|
934
|
+
if (!needsValue && rule.cls !== "registry")
|
|
935
|
+
continue;
|
|
936
|
+
// A: authored payload — the asker must design it. Never a "few params".
|
|
937
|
+
if (AUTHORED_KEYS.has(key) || (rule.cls === "user" && rule.user === "utterance" && Buffer.byteLength(JSON.stringify(value)) > 400)) {
|
|
938
|
+
if (AUTHORED_KEYS.has(key)) {
|
|
939
|
+
blockers.push({
|
|
940
|
+
type: "needs-authoring",
|
|
941
|
+
param: key,
|
|
942
|
+
reason: `${key} 是需求本体(规则图/流程拓扑/脚本/接口契约/字段清单),不是可由探测补全的参数`,
|
|
943
|
+
why: rule.source,
|
|
944
|
+
...(key === "nodeGraph" ? { next: `omc describe ${tool.name} --example <id>` } : {}),
|
|
945
|
+
});
|
|
946
|
+
}
|
|
947
|
+
else {
|
|
948
|
+
missing[key] = { reason: "需求话语需给出该配置", source: rule.source };
|
|
949
|
+
}
|
|
950
|
+
pending.add(key);
|
|
951
|
+
continue;
|
|
952
|
+
}
|
|
953
|
+
// B: registry-resolvable id — one read probe, then the state machine.
|
|
954
|
+
if (rule.cls === "registry") {
|
|
955
|
+
const resolver = RESOLVERS[key];
|
|
956
|
+
// No resolver registered for this id: keep the authored value but say it is
|
|
957
|
+
// unverified. `ready=true` is earned, never assumed.
|
|
958
|
+
if (resolver === undefined) {
|
|
959
|
+
if (needsValue) {
|
|
960
|
+
missing[key] = { reason: "需先读平台确认该标识", source: rule.source };
|
|
961
|
+
pending.add(key);
|
|
962
|
+
}
|
|
963
|
+
else {
|
|
964
|
+
unverified[key] = { reason: "沿用配方示例值,未在本环境核对", source: rule.source };
|
|
965
|
+
}
|
|
966
|
+
continue;
|
|
967
|
+
}
|
|
968
|
+
// Which value are we looking for? A placeholder means "whatever the ask
|
|
969
|
+
// names"; a concrete authored id means "confirm this one exists".
|
|
970
|
+
const hints = needsValue ? hintCandidates(goal) : [typeof value === "string" ? value : ""];
|
|
971
|
+
if (options.offline === true || options.probe === undefined) {
|
|
972
|
+
probes.push(`omc call ${resolver} --env ${environment ?? "<env>"} --args '{}'`);
|
|
973
|
+
if (needsValue) {
|
|
974
|
+
missing[key] = { reason: `需 ${resolver} 解析`, source: rule.source };
|
|
975
|
+
pending.add(key);
|
|
976
|
+
}
|
|
977
|
+
else {
|
|
978
|
+
unverified[key] = { reason: `需 ${resolver} 核对示例值 ${String(value)} 是否存在于本环境`, source: rule.source };
|
|
979
|
+
}
|
|
980
|
+
continue;
|
|
981
|
+
}
|
|
982
|
+
const probed = await probeReadOnly(options.probe, resolver);
|
|
983
|
+
if (probed.state === "uncertain") {
|
|
984
|
+
probeFailure = `${resolver} 探测失败:${probed.reason ?? "未返回可判定结果"}`;
|
|
985
|
+
pending.add(key);
|
|
986
|
+
continue;
|
|
987
|
+
}
|
|
988
|
+
const rows = probed.rows ?? [];
|
|
989
|
+
// Every candidate is tried, then the DISTINCT resolved models are compared.
|
|
990
|
+
// "First hit wins" silently picks one when the ask names two objects
|
|
991
|
+
// (「把采购合同和销售合同的金额…」) — the exact guess §4.2 forbids.
|
|
992
|
+
const resolvedByCodes = new Map();
|
|
993
|
+
let fallback = resolveModelCandidate(hints[0] ?? "", rows, goal);
|
|
994
|
+
for (const candidate of hints) {
|
|
995
|
+
const attempt = resolveModelCandidate(candidate, rows, goal);
|
|
996
|
+
if ((attempt.state === "resolved" || attempt.state === "resolved-with-warning") && attempt.code !== undefined) {
|
|
997
|
+
const row = rows.find((entry) => entry.code === attempt.code);
|
|
998
|
+
resolvedByCodes.set(attempt.code, row ?? { code: attempt.code, name: attempt.code });
|
|
999
|
+
}
|
|
1000
|
+
else if (attempt.state === "needs-input" && fallback.state !== "needs-input") {
|
|
1001
|
+
fallback = attempt;
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
const outcome = resolvedByCodes.size === 1
|
|
1005
|
+
? { state: "resolved-with-warning", code: [...resolvedByCodes.keys()][0], warning: `目标句指向 ${[...resolvedByCodes.keys()][0]}` }
|
|
1006
|
+
: resolvedByCodes.size > 1
|
|
1007
|
+
? { state: "needs-input", candidates: [...resolvedByCodes.values()].slice(0, 10) }
|
|
1008
|
+
: fallback;
|
|
1009
|
+
if (outcome.state === "needs-input") {
|
|
1010
|
+
ambiguities.push({
|
|
1011
|
+
param: key,
|
|
1012
|
+
candidates: outcome.candidates ?? [],
|
|
1013
|
+
question: needsValue ? `${key} 有多个候选,选中哪一个?` : `示例值「${hints[0]}」不唯一,选中哪一个?`,
|
|
1014
|
+
});
|
|
1015
|
+
pending.add(key);
|
|
1016
|
+
continue;
|
|
1017
|
+
}
|
|
1018
|
+
if (outcome.state === "blocked") {
|
|
1019
|
+
// A concrete authored id that is absent here is NOT "the platform has no
|
|
1020
|
+
// model": it is a plan that must ask. Fabricating it is the failure §4.2 bans.
|
|
1021
|
+
if (!needsValue) {
|
|
1022
|
+
ambiguities.push({ param: key, candidates: rows.slice(0, 10), question: `配方示例值「${hints[0]}」在本环境不存在,选哪个 ${key}?` });
|
|
1023
|
+
}
|
|
1024
|
+
else {
|
|
1025
|
+
blockers.push({ type: "blocked", param: key, reason: outcome.reason ?? "平台无匹配" });
|
|
1026
|
+
}
|
|
1027
|
+
pending.add(key);
|
|
1028
|
+
continue;
|
|
1029
|
+
}
|
|
1030
|
+
if (outcome.code === undefined) {
|
|
1031
|
+
missing[key] = { reason: `需 ${resolver} 解析`, source: rule.source };
|
|
1032
|
+
pending.add(key);
|
|
1033
|
+
continue;
|
|
1034
|
+
}
|
|
1035
|
+
// A concrete authored scalar is REPLACED by the resolved code; a template
|
|
1036
|
+
// gets every placeholder leaf rewritten. Mixing these up ships the example
|
|
1037
|
+
// tenant's code into a plan against another environment.
|
|
1038
|
+
args[key] = needsValue ? substitutePlaceholders(value, outcome.code) : outcome.code;
|
|
1039
|
+
// A unique fuzzy match is an INFERENCE, not a doubt: §4.1 requires "无歧义"
|
|
1040
|
+
// (unique), and this is unique. It is reported so the caller can check, but
|
|
1041
|
+
// it must not make `ready` unreachable.
|
|
1042
|
+
if (outcome.state === "resolved-with-warning" && outcome.warning !== undefined)
|
|
1043
|
+
warnings.push(`${key}: ${outcome.warning}`);
|
|
1044
|
+
continue;
|
|
1045
|
+
}
|
|
1046
|
+
// C: probe-produced ids (bizObjectId / workItemId).
|
|
1047
|
+
if (rule.cls === "probe") {
|
|
1048
|
+
// M4-2: if an authored prerequisite PRODUCES this value, wire a cross-step
|
|
1049
|
+
// reference instead of blocking. That is the difference between "you must
|
|
1050
|
+
// run data.save first (this plan says which step)" and "go away and replan".
|
|
1051
|
+
const producedBy = crossStepProducer(value, priorCompiled.byTool);
|
|
1052
|
+
if (producedBy !== undefined) {
|
|
1053
|
+
args[key] = producedBy.reference;
|
|
1054
|
+
dependencies.add(producedBy.stepId);
|
|
1055
|
+
continue;
|
|
1056
|
+
}
|
|
1057
|
+
blockers.push({
|
|
1058
|
+
type: "needs-input",
|
|
1059
|
+
param: key,
|
|
1060
|
+
reason: `${key} 由前序写回执产生,但本配方没有声明产出它的前置步骤`,
|
|
1061
|
+
why: rule.source,
|
|
1062
|
+
next: `先执行产生该标识的步骤,再 omc plan 重新规划`,
|
|
1063
|
+
});
|
|
1064
|
+
pending.add(key);
|
|
1065
|
+
continue;
|
|
1066
|
+
}
|
|
1067
|
+
// D: user-supplied but the asker can just say it.
|
|
1068
|
+
if (rule.cls === "user") {
|
|
1069
|
+
missing[key] = { reason: rule.user === "ask" ? "无法推断,需明确" : "需求话语需给出,或可提议后确认", source: rule.source, ...(rule.user !== undefined ? { why: rule.user } : {}) };
|
|
1070
|
+
pending.add(key);
|
|
1071
|
+
continue;
|
|
1072
|
+
}
|
|
1073
|
+
// E: unclassified — exposed as a gap, never guessed.
|
|
1074
|
+
missing[key] = { reason: "未分类参数(宁可暴露缺口,不猜)", source: rule.source };
|
|
1075
|
+
pending.add(key);
|
|
1076
|
+
}
|
|
1077
|
+
// ---- schema gate + uncertainty rule --------------------------------------------
|
|
1078
|
+
const validated = validateStep(tool, args, pending);
|
|
1079
|
+
const mainStep = {
|
|
1080
|
+
id: mainStepId,
|
|
1081
|
+
tool: tool.name,
|
|
1082
|
+
kind: tool.kind === "write" ? "write" : "read",
|
|
1083
|
+
purpose: recipe.title,
|
|
1084
|
+
args,
|
|
1085
|
+
dependsOn: [...dependencies],
|
|
1086
|
+
validated,
|
|
1087
|
+
dryRun: dryRunFor(tool.name, args, tool),
|
|
1088
|
+
...(() => {
|
|
1089
|
+
const verify = verifyFor(registry, { tool: tool.name, args }, recipe.expectedReadback);
|
|
1090
|
+
return verify === undefined ? {} : { verify };
|
|
1091
|
+
})(),
|
|
1092
|
+
// A hand-authored recipe in a test may omit authored recovery; absent is
|
|
1093
|
+
// "nothing authored", never "no refusals exist".
|
|
1094
|
+
...((recipe.refusalRecovery ?? []).length > 0
|
|
1095
|
+
? { onFailure: recipe.refusalRecovery.map((entry) => ({ code: String(entry.code ?? ""), action: String(entry.action ?? "") })) }
|
|
1096
|
+
: {}),
|
|
1097
|
+
};
|
|
1098
|
+
const uncertain = probeFailure !== undefined;
|
|
1099
|
+
// Uncertain ⇒ NOTHING executable. The risk the review called out: a plan that
|
|
1100
|
+
// half-resolved ids still looks runnable, and a write lands against the wrong model.
|
|
1101
|
+
const compiled = uncertain ? [] : [...priorCompiled.steps, mainStep];
|
|
1102
|
+
// M4-2: dependencies are declared, so the order must be PROVEN, not assumed.
|
|
1103
|
+
const sorted = topoSort(compiled);
|
|
1104
|
+
if (sorted.cycle !== undefined) {
|
|
1105
|
+
return {
|
|
1106
|
+
...base,
|
|
1107
|
+
ready: false,
|
|
1108
|
+
level: 2,
|
|
1109
|
+
...(match !== undefined ? { match } : {}),
|
|
1110
|
+
...(capability !== undefined ? { capability } : {}),
|
|
1111
|
+
...(lane !== undefined ? { lane } : {}),
|
|
1112
|
+
blockers: [{ type: "blocked", reason: `步骤依赖成环:${sorted.cycle.join(" → ")}` }],
|
|
1113
|
+
planHash: planHash({ goal, environment, level: 2, cycle: sorted.cycle }),
|
|
1114
|
+
next: [`omc describe ${tool.name} --example ${recipe.id}`],
|
|
1115
|
+
};
|
|
1116
|
+
}
|
|
1117
|
+
const steps = attachCaptures(sorted.ordered);
|
|
1118
|
+
// r60b-F4/F5:配方示例值残留标认(详见 PlanStep.needsSubstitution 注释)。
|
|
1119
|
+
const [markedSteps, residueWarnings] = markRecipeResidue(steps);
|
|
1120
|
+
warnings.push(...residueWarnings);
|
|
1121
|
+
const ready = !uncertain
|
|
1122
|
+
&& Object.keys(missing).length === 0
|
|
1123
|
+
&& Object.keys(unverified).length === 0
|
|
1124
|
+
&& ambiguities.length === 0
|
|
1125
|
+
&& blockers.length === 0
|
|
1126
|
+
&& validated.ok
|
|
1127
|
+
&& steps.every((step) => step.validated.ok);
|
|
1128
|
+
const level = uncertain ? 3 : ready ? 1 : 2;
|
|
1129
|
+
// M4-7: when the ATOMIC path is blocked on an authored payload, name the
|
|
1130
|
+
// declarative face — but only if that capability actually has one. Otherwise
|
|
1131
|
+
// the pointer is noise (and worse, it reads as "there is an easier way").
|
|
1132
|
+
const needsAuthoring = blockers.some((entry) => entry.type === "needs-authoring");
|
|
1133
|
+
const intentAlternative = needsAuthoring && capability !== undefined && capabilityHasDeclarativeFace(registry, capability)
|
|
1134
|
+
? {
|
|
1135
|
+
available: true,
|
|
1136
|
+
why: `${capability} 有声明式面:整段配置可写成 intent 文件,由编译器按依赖排序并 readback 对账,不必手拼 ${blockers.filter((entry) => entry.type === "needs-authoring").map((entry) => entry.param).join("/")}`,
|
|
1137
|
+
commands: ["omc intent schema", "omc intent validate <file>", "omc intent plan <file> --env <env>"],
|
|
1138
|
+
}
|
|
1139
|
+
: undefined;
|
|
1140
|
+
return {
|
|
1141
|
+
status: "ok",
|
|
1142
|
+
goal,
|
|
1143
|
+
environment,
|
|
1144
|
+
ready,
|
|
1145
|
+
level,
|
|
1146
|
+
...(match !== undefined ? { match } : {}),
|
|
1147
|
+
...(capability !== undefined ? { capability } : {}),
|
|
1148
|
+
...(lane !== undefined ? { lane } : {}),
|
|
1149
|
+
...(intentAlternative !== undefined ? { intentAlternative } : {}),
|
|
1150
|
+
steps: markedSteps,
|
|
1151
|
+
missing,
|
|
1152
|
+
unverified,
|
|
1153
|
+
warnings,
|
|
1154
|
+
ambiguities,
|
|
1155
|
+
blockers: uncertain ? [...blockers, { type: "uncertain", reason: probeFailure }] : blockers,
|
|
1156
|
+
probes,
|
|
1157
|
+
planHash: planHash({ goal, environment, tool: tool.name, recipe: recipe.id, args, ready, level }),
|
|
1158
|
+
next: ready
|
|
1159
|
+
? [`omc call ${tool.name} --env ${environment ?? "<env>"} --args '<上面的 args>'`, `omc describe ${tool.name}`]
|
|
1160
|
+
: [
|
|
1161
|
+
...(probes.length > 0 ? probes : []),
|
|
1162
|
+
...(intentAlternative !== undefined ? intentAlternative.commands : []),
|
|
1163
|
+
`omc describe ${tool.name} --example ${recipe.id}`,
|
|
1164
|
+
`omc describe ${tool.name}`,
|
|
1165
|
+
],
|
|
1166
|
+
...(recipe.requiresEnvironmentDerivedIds ? { note: "该配方需要环境读回派生标识;前置步骤已按配方声明编入计划" } : {}),
|
|
1167
|
+
};
|
|
1168
|
+
}
|
|
1169
|
+
/**
|
|
1170
|
+
* M4-7: does this capability have a declarative (intent) face?
|
|
1171
|
+
*
|
|
1172
|
+
* `intent.level !== "none"` is the registry's own answer — the same field
|
|
1173
|
+
* `omc capabilities` prints — so the plan never claims a declarative route the
|
|
1174
|
+
* compiler cannot take.
|
|
1175
|
+
*/
|
|
1176
|
+
export function capabilityHasDeclarativeFace(registry, capabilityId) {
|
|
1177
|
+
return capabilityRouteIndex(registry).nodeById.get(capabilityId)?.intent.level !== undefined
|
|
1178
|
+
&& capabilityRouteIndex(registry).nodeById.get(capabilityId).intent.level !== "none";
|
|
1179
|
+
}
|
|
1180
|
+
/** Replace every `<placeholder>` leaf with one resolved value; keeps nested shapes. */
|
|
1181
|
+
function substitutePlaceholders(value, code) {
|
|
1182
|
+
if (typeof value === "string")
|
|
1183
|
+
return /^<[^<>]+>$/.test(value) || value.includes("omc_recipe_") ? code : value;
|
|
1184
|
+
if (Array.isArray(value))
|
|
1185
|
+
return value.map((entry) => substitutePlaceholders(entry, code));
|
|
1186
|
+
if (value !== null && typeof value === "object") {
|
|
1187
|
+
return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, substitutePlaceholders(entry, code)]));
|
|
1188
|
+
}
|
|
1189
|
+
return value;
|
|
1190
|
+
}
|
|
1191
|
+
/**
|
|
1192
|
+
* Run one read-only resolver tool and lift its rows into the candidate shape.
|
|
1193
|
+
*
|
|
1194
|
+
* Only `model.list` is wired: it is the one probe every recipe needs and the one
|
|
1195
|
+
* the review named (schemaCode ambiguity). Other registry ids keep their authored
|
|
1196
|
+
* value and are reported as `unverified` — an honest gap, not a fabricated id.
|
|
1197
|
+
*/
|
|
1198
|
+
async function probeReadOnly(probe, resolver) {
|
|
1199
|
+
const outcome = await probe(resolver, {});
|
|
1200
|
+
if (!outcome.ok)
|
|
1201
|
+
return { state: "uncertain", reason: outcome.error ?? "probe failed" };
|
|
1202
|
+
return { state: "ok", rows: modelsOf(outcome.result) };
|
|
1203
|
+
}
|
|
1204
|
+
/**
|
|
1205
|
+
* The target object the ask names — the ONLY source of a schemaCode. Deliberately
|
|
1206
|
+
* dumb: a plan must not invent a model from a vague verb.
|
|
1207
|
+
*/
|
|
1208
|
+
function hintFromGoal(goal, rawArgs) {
|
|
1209
|
+
// An authored Latin identifier is the strongest hint there is.
|
|
1210
|
+
for (const value of Object.values(rawArgs)) {
|
|
1211
|
+
if (typeof value === "string" && !/^<[^<>]+>$/.test(value) && !value.includes("omc_recipe_") && /^[A-Za-z][\w.]*$/.test(value) && value.length >= 4)
|
|
1212
|
+
return value;
|
|
1213
|
+
}
|
|
1214
|
+
return hintCandidates(goal)[0] ?? "";
|
|
1215
|
+
}
|
|
1216
|
+
/**
|
|
1217
|
+
* Ordered model-name candidates from a Chinese ask.
|
|
1218
|
+
*
|
|
1219
|
+
* CJK has no spaces, so "the longest run" is the WHOLE sentence — useless as a
|
|
1220
|
+
* model name (「查采购申请里金额大于一万的单据」 has no terminator to split on).
|
|
1221
|
+
* This strips the leading verb, cuts at container markers (里/的/中/上) and at
|
|
1222
|
+
* punctuation/conjunctions, then trims trailing structural nouns (模型/字段/表单…).
|
|
1223
|
+
* Several candidates are returned because the ask may name the object loosely;
|
|
1224
|
+
* the caller tries each against the platform's rows and takes the first unique hit.
|
|
1225
|
+
*/
|
|
1226
|
+
export function hintCandidates(goal) {
|
|
1227
|
+
const quoted = goal.match(/[「"]([^」"]{2,20})[」"]/);
|
|
1228
|
+
const out = [];
|
|
1229
|
+
const push = (value) => {
|
|
1230
|
+
const trimmed = value.trim();
|
|
1231
|
+
if (trimmed.length >= 2 && trimmed.length <= 20 && !out.includes(trimmed))
|
|
1232
|
+
out.push(trimmed);
|
|
1233
|
+
};
|
|
1234
|
+
if (quoted)
|
|
1235
|
+
push(quoted[1]);
|
|
1236
|
+
// Longest alternatives FIRST: 「新建一个」 must be consumed before 「新建」,
|
|
1237
|
+
// otherwise the leftover 「一个」 survives into the model name.
|
|
1238
|
+
const LEADING_VERBS = /^(?:请|帮我|麻烦)?(?:查一下|查一查|查询一下|查询|查|看一下|看看|看下|看|列出|列一下|列|搜一下|搜|找一下|找|盘点|清点|统计|汇总|导出|给我一份|新建一个|创建一个|搭建一个|建一个|加一个|新建|创建|搭建|建|增加|新增|添加|加|给|把|为|在|一个|一套)/;
|
|
1239
|
+
const TRAILING_NOUNS = /(?:的)?(?:数据|记录|单据|列表|清单|模型|字段|表单|视图|规则|流程|页面|报表|字典|应用|目录|分组|服务|接口|方法|角色|部门|用户|员工|账号|权限|权限组|字段校验规则|校验规则|业务规则|列表视图|自定义页面|工作流|审批流)$/;
|
|
1240
|
+
const strip = (value) => {
|
|
1241
|
+
let current = value.trim();
|
|
1242
|
+
for (let i = 0; i < 4; i += 1) {
|
|
1243
|
+
const before = current;
|
|
1244
|
+
current = current.replace(LEADING_VERBS, "").replace(TRAILING_NOUNS, "").trim();
|
|
1245
|
+
if (current === before)
|
|
1246
|
+
break;
|
|
1247
|
+
}
|
|
1248
|
+
return current;
|
|
1249
|
+
};
|
|
1250
|
+
// Cut at container markers and at punctuation/conjunctions — the segment BEFORE
|
|
1251
|
+
// the marker is the object ("采购申请里金额…" → 采购申请; "差旅申请模型,带…" → 差旅申请).
|
|
1252
|
+
const segments = goal.split(/[里中的上下内,,、。;;::和与及或]|带|包含|要有|需要/);
|
|
1253
|
+
push(strip(goal));
|
|
1254
|
+
for (const segment of segments)
|
|
1255
|
+
push(strip(segment));
|
|
1256
|
+
// Two-to-four character prefixes of the first meaningful segment catch nouns
|
|
1257
|
+
// that carry a verb-like prefix the regex list missed.
|
|
1258
|
+
const first = strip(segments[0] ?? goal);
|
|
1259
|
+
for (const length of [4, 3, 2])
|
|
1260
|
+
if (first.length > length)
|
|
1261
|
+
push(first.slice(0, length));
|
|
1262
|
+
return out;
|
|
1263
|
+
}
|
|
1264
|
+
/**
|
|
1265
|
+
* M4-5: the NDJSON that `omc script` consumes.
|
|
1266
|
+
*
|
|
1267
|
+
* Only self-contained steps go in: a step that still holds `<…>` placeholders or
|
|
1268
|
+
* waits on an earlier step's readback cannot be expressed in NDJSON (the script
|
|
1269
|
+
* runner does no variable interpolation), and emitting it would hand the runner
|
|
1270
|
+
* a guaranteed failure. `planToNdjsonSkipped` names what was left out and why,
|
|
1271
|
+
* so the caller can chain manually instead of wondering where steps went.
|
|
1272
|
+
*/
|
|
1273
|
+
export function planToNdjson(plan) {
|
|
1274
|
+
return selfContainedSteps(plan.steps).map((step) => JSON.stringify({
|
|
1275
|
+
tool: step.tool,
|
|
1276
|
+
args: step.args,
|
|
1277
|
+
...(plan.environment !== null ? { env: plan.environment } : {}),
|
|
1278
|
+
dryRun: true,
|
|
1279
|
+
}));
|
|
1280
|
+
}
|
|
1281
|
+
/** Steps withheld from NDJSON, with the reason (M4-5). */
|
|
1282
|
+
export function planToNdjsonSkipped(plan) {
|
|
1283
|
+
const included = new Set(selfContainedSteps(plan.steps).map((step) => step.id));
|
|
1284
|
+
return plan.steps
|
|
1285
|
+
.filter((step) => !included.has(step.id))
|
|
1286
|
+
.map((step) => ({
|
|
1287
|
+
id: step.id,
|
|
1288
|
+
tool: step.tool,
|
|
1289
|
+
reason: !step.validated.ok
|
|
1290
|
+
? `本地 schema 未通过(${step.validated.issues.slice(0, 2).join(";")})`
|
|
1291
|
+
: step.dependsOn.length > 0
|
|
1292
|
+
? `依赖 ${step.dependsOn.join("、")} 的读回值(NDJSON 不做变量插值)`
|
|
1293
|
+
: "参数里仍有未解析的 <占位符>",
|
|
1294
|
+
}));
|
|
1295
|
+
}
|
|
1296
|
+
//# sourceMappingURL=goal-plan.js.map
|