u1s1-cli 0.18.0 → 0.19.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-setup.js +7 -2
- package/dist/workflow/templates.d.ts +11 -0
- package/dist/workflow/templates.js +175 -0
- package/dist/workflow/tool.d.ts +3 -0
- package/dist/workflow/tool.js +46 -4
- package/package.json +1 -1
package/dist/agent-setup.js
CHANGED
|
@@ -328,7 +328,12 @@ First decide whether this task really needs a workflow. Good fit: many independe
|
|
|
328
328
|
|
|
329
329
|
If it is a fit:
|
|
330
330
|
|
|
331
|
-
|
|
331
|
+
0. **Prefer a built-in template** when one matches — call \`run_workflow\` with \`template\` + \`input\` instead of writing a script:
|
|
332
|
+
- \`i18n\` — translate locale file(s) to N languages: { "langs": ["en", "ja"], "source": "src/locales/zh.json" }
|
|
333
|
+
- \`review\` — per-file review + adversarial verification: { "files": [...] } or omit for git-diff files
|
|
334
|
+
- \`research\` — parallel investigation + synthesis: { "questions": ["..."], "context": "..." }
|
|
335
|
+
- \`refactor\` — rule-first batch refactor in isolated worktrees: { "instruction": "...", "files": [...] }
|
|
336
|
+
1. Otherwise decompose the task and write a JavaScript orchestration script. Top-level await and return are allowed. The script runs in a sandbox where ONLY these are available:
|
|
332
337
|
- \`subagent(task)\` or \`subagent({ task, model })\` — runs one sub-agent, resolves to its final output text
|
|
333
338
|
- \`parallel([() => ..., ...])\` — concurrent fan-out; each thunk's error becomes \`null\`; barrier semantics
|
|
334
339
|
- \`pipeline(items, [stage1, stage2, ...])\` — each item flows through all stages independently (prefer over parallel)
|
|
@@ -337,7 +342,7 @@ If it is a fit:
|
|
|
337
342
|
- \`log(...)\`, \`setTimeout/clearTimeout\`, standard JS builtins (Promise/JSON/Math/...)
|
|
338
343
|
- NO require/import/process/fetch/fs access — the static validator rejects scripts that try
|
|
339
344
|
2. Every task string must be fully self-contained: which files to read/write, what "done" means, how to self-verify.
|
|
340
|
-
3. Call the \`run_workflow\` tool with the full source as \`script\`. Read its report carefully; on failures fix the script, or rerun with \`script_path\` + \`resume: true\` to continue from saved progress.
|
|
345
|
+
3. Call the \`run_workflow\` tool with the full source as \`script\`. Read its report carefully; on failures fix the script, or rerun with \`script_path\` + \`resume: true\` to continue from saved progress. For workflows worth rerunning (e.g. recurring i18n syncs), pass a memorable \`save_as\` name — rerun later with just \`script_path\`.
|
|
341
346
|
|
|
342
347
|
Keep scripts deterministic (same order of subagent calls every run) so resume works. Summarize the outcome to the user afterwards in their language.
|
|
343
348
|
`;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface WorkflowTemplate {
|
|
2
|
+
name: string;
|
|
3
|
+
description: string;
|
|
4
|
+
/** 生成脚本源码;input 已由调用方做过形状校验。 */
|
|
5
|
+
build: (input: Record<string, unknown>) => string;
|
|
6
|
+
/** 给模型看的 input 说明。 */
|
|
7
|
+
inputHint: string;
|
|
8
|
+
}
|
|
9
|
+
export declare const TEMPLATES: Record<string, WorkflowTemplate>;
|
|
10
|
+
/** 按模板名生成脚本;生成后自检必须过静态校验(防模板本身写出不合规代码)。 */
|
|
11
|
+
export declare function buildFromTemplate(template: string, input: Record<string, unknown>): string;
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { validateScript } from "./runner.js";
|
|
3
|
+
function str(v, fallback = "") {
|
|
4
|
+
return typeof v === "string" && v.trim() ? v.trim() : fallback;
|
|
5
|
+
}
|
|
6
|
+
function strArray(v) {
|
|
7
|
+
return Array.isArray(v)
|
|
8
|
+
? v.filter((x) => typeof x === "string" && !!x.trim()).map((x) => x.trim())
|
|
9
|
+
: [];
|
|
10
|
+
}
|
|
11
|
+
/** JSON.stringify 后内插进脚本;保证引号安全。 */
|
|
12
|
+
function lit(v) {
|
|
13
|
+
return JSON.stringify(v ?? null);
|
|
14
|
+
}
|
|
15
|
+
/** git 改动文件列表(模板构建期在主进程执行,不进沙箱)。
|
|
16
|
+
* 剔除已删除文件(评审/重构 agent 没法打开),并入未跟踪的新文件。 */
|
|
17
|
+
function gitDiffFiles() {
|
|
18
|
+
const run = (args) => {
|
|
19
|
+
const out = execFileSync("git", args, { encoding: "utf8", stdio: ["pipe", "pipe", "pipe"] });
|
|
20
|
+
return out.split("\n").map((s) => s.trim()).filter(Boolean);
|
|
21
|
+
};
|
|
22
|
+
try {
|
|
23
|
+
const changed = run(["diff", "--name-only", "--diff-filter=d", "HEAD"]);
|
|
24
|
+
const untracked = run(["ls-files", "--others", "--exclude-standard"]);
|
|
25
|
+
return [...new Set([...changed, ...untracked])];
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return [];
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
export const TEMPLATES = {
|
|
32
|
+
i18n: {
|
|
33
|
+
name: "i18n",
|
|
34
|
+
description: "批量多语言翻译:每个语言一个子 agent 并行翻译,完成后统一校验 key 对齐并自动修复",
|
|
35
|
+
inputHint: '{ "langs": ["en", "ja", "de"], "source": "src/locales/zh.json", "dir": "src/locales" } — source/dir 可省略(默认 src/locales/zh.json 与同目录)',
|
|
36
|
+
build(input) {
|
|
37
|
+
const langs = strArray(input.langs);
|
|
38
|
+
if (langs.length === 0)
|
|
39
|
+
throw new Error('i18n 模板需要 langs 数组,例如 { "langs": ["en", "ja"] }');
|
|
40
|
+
const source = str(input.source, "src/locales/zh.json");
|
|
41
|
+
const dir = str(input.dir, source.includes("/") ? source.slice(0, source.lastIndexOf("/")) : "src/locales");
|
|
42
|
+
// 用户输入一律经 lit() 进脚本,再在运行期拼接——裸内插遇到引号/反斜杠/换行会把生成的脚本弄成语法错误
|
|
43
|
+
return `
|
|
44
|
+
const langs = ${lit(langs)};
|
|
45
|
+
const source = ${lit(source)};
|
|
46
|
+
const dir = ${lit(dir)};
|
|
47
|
+
log("i18n:翻译 " + langs.length + " 个语言,源文件 " + source);
|
|
48
|
+
const results = await parallel(langs.map(lang => () =>
|
|
49
|
+
subagent({
|
|
50
|
+
task: "读取 " + source + ",把所有文案翻译成对应语言(保持所有 key 不变、输出合法 JSON、译文自然地道)," +
|
|
51
|
+
"写入 " + dir + "/" + lang + ".json。写完后重新读一遍文件,确认是合法 JSON 且 key 与源文件完全一致。" +
|
|
52
|
+
"目标语言代码:" + lang
|
|
53
|
+
})
|
|
54
|
+
));
|
|
55
|
+
const okLangs = langs.filter((_, i) => results[i] !== null);
|
|
56
|
+
if (okLangs.length > 0) {
|
|
57
|
+
await subagent({
|
|
58
|
+
task: "对照 " + source + " 检查 " + dir + "/ 目录下这些语言的翻译文件:" + okLangs.join(",") + "." +
|
|
59
|
+
"逐个核对 key 是否与源文件完全一致、JSON 是否合法、译文是否有明显机翻痕迹,发现问题直接修复。最后汇报每个语言的状态"
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
return { translated: okLangs, failed: langs.filter(l => !okLangs.includes(l)) };
|
|
63
|
+
`;
|
|
64
|
+
},
|
|
65
|
+
},
|
|
66
|
+
review: {
|
|
67
|
+
name: "review",
|
|
68
|
+
description: "全面代码审查:每个文件一个评审 agent 并行审查,发现项再交独立 agent 对抗性验证,只保留核实为真的问题",
|
|
69
|
+
inputHint: '{ "files": ["src/a.ts", "src/b.ts"] } — files 可省略,默认取 git diff --name-only HEAD 的改动文件',
|
|
70
|
+
build(input) {
|
|
71
|
+
let files = strArray(input.files);
|
|
72
|
+
if (files.length === 0)
|
|
73
|
+
files = gitDiffFiles();
|
|
74
|
+
if (files.length === 0)
|
|
75
|
+
throw new Error("review 模板需要 files 数组,或当前仓库有未提交改动");
|
|
76
|
+
return `
|
|
77
|
+
const files = ${lit(files)};
|
|
78
|
+
log("review:评审 " + files.length + " 个文件,发现项将做对抗性验证");
|
|
79
|
+
const reports = await parallel(files.map(f => () =>
|
|
80
|
+
subagent({
|
|
81
|
+
task: "通读 " + f + " 及其直接依赖,做代码审查:正确性 bug、安全漏洞、明显的性能问题。" +
|
|
82
|
+
"只报告有把握的问题,每条给出文件、行号、严重程度(高/中/低)、问题描述和建议修法。没有问题就明确说无发现。"
|
|
83
|
+
})
|
|
84
|
+
));
|
|
85
|
+
const findings = reports.filter(Boolean).join("\\n\\n---\\n\\n");
|
|
86
|
+
if (!findings.trim()) return { verified: "(所有文件均无发现)" };
|
|
87
|
+
const verified = await subagent({
|
|
88
|
+
task: "下面是一份代码审查发现列表。逐条对抗性验证:打开涉及的文件核对,剔除不成立、夸大或已过时的条目," +
|
|
89
|
+
"只保留核实为真的问题,按严重程度排序输出完整清单。\\n\\n" + findings
|
|
90
|
+
});
|
|
91
|
+
return { verified };
|
|
92
|
+
`;
|
|
93
|
+
},
|
|
94
|
+
},
|
|
95
|
+
research: {
|
|
96
|
+
name: "research",
|
|
97
|
+
description: "并行研究:每个方向一个子 agent 独立调查(可联网),最后汇总成一份综合报告",
|
|
98
|
+
inputHint: '{ "questions": ["方向一", "方向二"], "context": "可选背景" }',
|
|
99
|
+
build(input) {
|
|
100
|
+
const questions = strArray(input.questions);
|
|
101
|
+
if (questions.length === 0)
|
|
102
|
+
throw new Error('research 模板需要 questions 数组,例如 { "questions": ["竞品A的定价", "竞品B的功能"] }');
|
|
103
|
+
const context = str(input.context);
|
|
104
|
+
const contextLine = context ? `调查背景:${context}。` : "";
|
|
105
|
+
return `
|
|
106
|
+
const questions = ${lit(questions)};
|
|
107
|
+
const contextLine = ${lit(contextLine)};
|
|
108
|
+
log("research:并行调查 " + questions.length + " 个方向");
|
|
109
|
+
const reports = await parallel(questions.map(q => () =>
|
|
110
|
+
subagent({
|
|
111
|
+
task: "调查以下问题,可以用 web_search/web_fetch 联网,也可以读本地代码和文档。" +
|
|
112
|
+
"输出:关键事实(带来源)、不同观点、你的结论。" + contextLine + "问题:" + q
|
|
113
|
+
})
|
|
114
|
+
));
|
|
115
|
+
const merged = reports
|
|
116
|
+
.map((r, i) => (r ? "## 方向 " + (i + 1) + ":" + questions[i] + "\\n\\n" + r : null))
|
|
117
|
+
.filter(Boolean)
|
|
118
|
+
.join("\\n\\n");
|
|
119
|
+
if (!merged.trim()) return { synthesis: "(所有方向都失败了)", failed: questions.length };
|
|
120
|
+
const synthesis = await subagent({
|
|
121
|
+
task: "把以下几份调查报告综合成一份结论性报告:先给核心结论(不超过 5 条),再给分方向要点," +
|
|
122
|
+
"最后列分歧点和待确认项。不要编造报告里没有的信息。\\n\\n" + merged
|
|
123
|
+
});
|
|
124
|
+
return { synthesis };
|
|
125
|
+
`;
|
|
126
|
+
},
|
|
127
|
+
},
|
|
128
|
+
refactor: {
|
|
129
|
+
name: "refactor",
|
|
130
|
+
description: "批量重构/迁移:先由一个 agent 读代表文件制定统一规则,然后每个文件一个子 agent 在独立 worktree 里套用规则,互不冲突",
|
|
131
|
+
inputHint: '{ "instruction": "把所有 var 改为 const", "files": ["src/a.ts", ...] } — files 省略时用 git diff 改动文件',
|
|
132
|
+
build(input) {
|
|
133
|
+
const instruction = str(input.instruction);
|
|
134
|
+
if (!instruction)
|
|
135
|
+
throw new Error('refactor 模板需要 instruction,例如 { "instruction": "把 var 全部改为 const" }');
|
|
136
|
+
// 与 review 模板一致:构建期取 git 改动文件,不花一个 subagent 在沙箱里跑 git
|
|
137
|
+
let files = strArray(input.files);
|
|
138
|
+
if (files.length === 0)
|
|
139
|
+
files = gitDiffFiles();
|
|
140
|
+
if (files.length === 0)
|
|
141
|
+
throw new Error("refactor 模板需要 files 数组,或当前仓库有未提交改动");
|
|
142
|
+
return `
|
|
143
|
+
const instruction = ${lit(instruction)};
|
|
144
|
+
const targetFiles = ${lit(files)};
|
|
145
|
+
log("refactor:共 " + targetFiles.length + " 个文件,先制定统一规则");
|
|
146
|
+
const rule = await subagent({
|
|
147
|
+
task: "我们要对一批文件做统一重构:" + instruction + "。" +
|
|
148
|
+
"先读其中 1-2 个代表性文件了解现状,然后输出一份精确的重构规则清单(每条:什么模式改成什么、边界情况怎么处理)。" +
|
|
149
|
+
"规则要具体到可以直接照做,不要空话。涉及文件:" + targetFiles.slice(0, 10).join(",")
|
|
150
|
+
});
|
|
151
|
+
const results = await parallel(targetFiles.map(f => () =>
|
|
152
|
+
subagent({
|
|
153
|
+
task: "按以下重构规则处理文件 " + f + ",改完检查该文件语法正确(必要时运行 tsc 或构建验证)。\\n\\n重构规则:\\n" + rule,
|
|
154
|
+
worktree: true
|
|
155
|
+
})
|
|
156
|
+
));
|
|
157
|
+
const done = targetFiles.filter((_, i) => results[i] !== null);
|
|
158
|
+
return { applied: done, failed: targetFiles.filter(f => !done.includes(f)), rule };
|
|
159
|
+
`;
|
|
160
|
+
},
|
|
161
|
+
},
|
|
162
|
+
};
|
|
163
|
+
/** 按模板名生成脚本;生成后自检必须过静态校验(防模板本身写出不合规代码)。 */
|
|
164
|
+
export function buildFromTemplate(template, input) {
|
|
165
|
+
const t = TEMPLATES[template];
|
|
166
|
+
if (!t) {
|
|
167
|
+
throw new Error(`未知模板 "${template}",可用:${Object.keys(TEMPLATES).join(", ")}`);
|
|
168
|
+
}
|
|
169
|
+
const code = t.build(input ?? {});
|
|
170
|
+
const errors = validateScript(code);
|
|
171
|
+
if (errors.length > 0) {
|
|
172
|
+
throw new Error(`模板 ${template} 生成的脚本未通过静态校验(模板 bug,请反馈):${errors.join(";")}`);
|
|
173
|
+
}
|
|
174
|
+
return code;
|
|
175
|
+
}
|
package/dist/workflow/tool.d.ts
CHANGED
|
@@ -6,7 +6,10 @@ import type { ParentModelRef } from "../subagent.js";
|
|
|
6
6
|
*/
|
|
7
7
|
export declare function createRunWorkflowTool(getParentModel: () => ParentModelRef): import("@earendil-works/pi-coding-agent").ToolDefinition<Type.TObject<{
|
|
8
8
|
script: Type.TOptional<Type.TString>;
|
|
9
|
+
template: Type.TOptional<Type.TString>;
|
|
10
|
+
input: Type.TOptional<Type.TRecord<"^.*$", Type.TUnknown>>;
|
|
9
11
|
script_path: Type.TOptional<Type.TString>;
|
|
12
|
+
save_as: Type.TOptional<Type.TString>;
|
|
10
13
|
resume: Type.TOptional<Type.TBoolean>;
|
|
11
14
|
timeout_minutes: Type.TOptional<Type.TNumber>;
|
|
12
15
|
budget_tokens: Type.TOptional<Type.TNumber>;
|
package/dist/workflow/tool.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import { readFileSync } from "node:fs";
|
|
2
|
-
import { resolve } from "node:path";
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname, resolve } from "node:path";
|
|
3
3
|
import { defineTool } from "@earendil-works/pi-coding-agent";
|
|
4
4
|
import { Text } from "@earendil-works/pi-tui";
|
|
5
5
|
import { Type } from "typebox";
|
|
6
6
|
import { compactResultRender, truncate } from "../tools.js";
|
|
7
7
|
import { runWorkflow, saveWorkflowScript, validateScript, workflowsDir, WORKFLOW_DEFAULT_BUDGET_TOKENS, WORKFLOW_TIMEOUT_MS, } from "./runner.js";
|
|
8
|
+
import { buildFromTemplate, TEMPLATES } from "./templates.js";
|
|
8
9
|
/**
|
|
9
10
|
* run_workflow 工具:主 agent 把模型生成的编排脚本交给 WorkflowRunner 执行。
|
|
10
11
|
* 脚本在 vm 沙箱里跑,只能用注入的 subagent/parallel/pipeline 原语。
|
|
@@ -27,9 +28,20 @@ export function createRunWorkflowTool(getParentModel) {
|
|
|
27
28
|
],
|
|
28
29
|
parameters: Type.Object({
|
|
29
30
|
script: Type.Optional(Type.String({ description: "Full JavaScript source of the orchestration script (top-level await allowed)." })),
|
|
31
|
+
template: Type.Optional(Type.String({
|
|
32
|
+
description: `Use a built-in template instead of writing a script: ${Object.keys(TEMPLATES).join(" / ")}. ` +
|
|
33
|
+
"Provide `input` to parametrize it. Prefer this over hand-writing a script when a template fits.",
|
|
34
|
+
})),
|
|
35
|
+
input: Type.Optional(Type.Record(Type.String(), Type.Unknown(), {
|
|
36
|
+
description: 'Parameters for `template`, e.g. i18n: { "langs": ["en", "ja"] }; review/refactor: { "files": [...] } or omit for git-diff files; research: { "questions": [...] }.',
|
|
37
|
+
})),
|
|
30
38
|
script_path: Type.Optional(Type.String({
|
|
31
39
|
description: "Path to an existing workflow script under .u1s1/workflows/ — rerun it instead of passing `script`.",
|
|
32
40
|
})),
|
|
41
|
+
save_as: Type.Optional(Type.String({
|
|
42
|
+
description: 'Save this run\'s script as .u1s1/workflows/<name>.mjs (letters/digits/-/_) for easy reuse; rerun later via script_path. Fails if the name already exists. Only valid with `script` or `template`, not `script_path`.',
|
|
43
|
+
pattern: "^[a-zA-Z0-9_-]+$",
|
|
44
|
+
})),
|
|
33
45
|
resume: Type.Optional(Type.Boolean({
|
|
34
46
|
description: "Skip sub-tasks already recorded as succeeded in the progress file (for crash/interrupt recovery).",
|
|
35
47
|
})),
|
|
@@ -61,12 +73,27 @@ export function createRunWorkflowTool(getParentModel) {
|
|
|
61
73
|
async execute(_toolCallId, params, signal, onUpdate) {
|
|
62
74
|
let code = params.script?.trim();
|
|
63
75
|
let scriptPath;
|
|
76
|
+
const named = params.save_as?.trim();
|
|
77
|
+
if (named && !/^[a-zA-Z0-9_-]+$/.test(named)) {
|
|
78
|
+
throw new Error("save_as 只允许字母、数字、横线和下划线");
|
|
79
|
+
}
|
|
80
|
+
if (named && params.script_path?.trim()) {
|
|
81
|
+
throw new Error("script_path 指向的脚本已经落盘,不能再配 save_as;要另存新名字请用 script 传入源码");
|
|
82
|
+
}
|
|
64
83
|
if (code) {
|
|
65
84
|
const errors = validateScript(code);
|
|
66
85
|
if (errors.length > 0) {
|
|
67
86
|
throw new Error(`脚本未通过静态校验,请修复后重试:\n- ${errors.join("\n- ")}`);
|
|
68
87
|
}
|
|
69
|
-
|
|
88
|
+
}
|
|
89
|
+
else if (params.template?.trim()) {
|
|
90
|
+
// 内置模板:模型只填参数,脚本由模板生成(生成后自检过静态校验)
|
|
91
|
+
try {
|
|
92
|
+
code = buildFromTemplate(params.template.trim(), (params.input ?? {}));
|
|
93
|
+
}
|
|
94
|
+
catch (e) {
|
|
95
|
+
throw new Error(`${e.message}\n模板 input 说明:${TEMPLATES[params.template.trim()]?.inputHint ?? "—"}`);
|
|
96
|
+
}
|
|
70
97
|
}
|
|
71
98
|
else if (params.script_path?.trim()) {
|
|
72
99
|
scriptPath = resolve(params.script_path.trim());
|
|
@@ -78,7 +105,22 @@ export function createRunWorkflowTool(getParentModel) {
|
|
|
78
105
|
}
|
|
79
106
|
}
|
|
80
107
|
else {
|
|
81
|
-
throw new Error("script
|
|
108
|
+
throw new Error("script、template、script_path 至少填一个");
|
|
109
|
+
}
|
|
110
|
+
// 落盘:save_as 用语义化名字(同名报错防覆盖进度配对),否则时间戳名;
|
|
111
|
+
// script_path 分支上面已读入,不重复落盘
|
|
112
|
+
if (!scriptPath) {
|
|
113
|
+
if (named) {
|
|
114
|
+
scriptPath = resolve(workflowsDir(), `${named}.mjs`);
|
|
115
|
+
if (existsSync(scriptPath)) {
|
|
116
|
+
throw new Error(`工作流 "${named}" 已存在(${scriptPath})。要重跑它请用 script_path 指向该文件(可加 resume:true 续跑);要新建请换个名字`);
|
|
117
|
+
}
|
|
118
|
+
mkdirSync(dirname(scriptPath), { recursive: true });
|
|
119
|
+
writeFileSync(scriptPath, code ?? "");
|
|
120
|
+
}
|
|
121
|
+
else {
|
|
122
|
+
scriptPath = saveWorkflowScript(code ?? "");
|
|
123
|
+
}
|
|
82
124
|
}
|
|
83
125
|
const progressPath = scriptPath.replace(/\.mjs$/, ".progress.jsonl");
|
|
84
126
|
// 流式进度:onProgress 高频触发,节流到 ≥2s 一次才推给 TUI
|