u1s1-cli 0.18.0 → 0.19.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.
@@ -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
- 1. Decompose the task, then write a JavaScript orchestration script. Top-level await and return are allowed. The script runs in a sandbox where ONLY these are available:
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,167 @@
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
+ function gitDiffFiles() {
17
+ try {
18
+ const out = execFileSync("git", ["diff", "--name-only", "HEAD"], { encoding: "utf8", stdio: ["pipe", "pipe", "pipe"] });
19
+ return out.split("\n").map((s) => s.trim()).filter(Boolean);
20
+ }
21
+ catch {
22
+ return [];
23
+ }
24
+ }
25
+ export const TEMPLATES = {
26
+ i18n: {
27
+ name: "i18n",
28
+ description: "批量多语言翻译:每个语言一个子 agent 并行翻译,完成后统一校验 key 对齐并自动修复",
29
+ inputHint: '{ "langs": ["en", "ja", "de"], "source": "src/locales/zh.json", "dir": "src/locales" } — source/dir 可省略(默认 src/locales/zh.json 与同目录)',
30
+ build(input) {
31
+ const langs = strArray(input.langs);
32
+ if (langs.length === 0)
33
+ throw new Error('i18n 模板需要 langs 数组,例如 { "langs": ["en", "ja"] }');
34
+ const source = str(input.source, "src/locales/zh.json");
35
+ const dir = str(input.dir, source.includes("/") ? source.slice(0, source.lastIndexOf("/")) : "src/locales");
36
+ return `
37
+ const langs = ${lit(langs)};
38
+ log("i18n:翻译 " + langs.length + " 个语言,源文件 ${source}");
39
+ const results = await parallel(langs.map(lang => () =>
40
+ subagent({
41
+ task: "读取 ${source},把所有文案翻译成对应语言(保持所有 key 不变、输出合法 JSON、译文自然地道)," +
42
+ "写入 ${dir}/" + lang + ".json。写完后重新读一遍文件,确认是合法 JSON 且 key 与源文件完全一致。" +
43
+ "目标语言代码:" + lang
44
+ })
45
+ ));
46
+ const okLangs = langs.filter((_, i) => results[i] !== null);
47
+ if (okLangs.length > 0) {
48
+ await subagent({
49
+ task: "对照 ${source} 检查 ${dir}/ 目录下这些语言的翻译文件:" + okLangs.join(",") + "." +
50
+ "逐个核对 key 是否与源文件完全一致、JSON 是否合法、译文是否有明显机翻痕迹,发现问题直接修复。最后汇报每个语言的状态"
51
+ });
52
+ }
53
+ return { translated: okLangs, failed: langs.filter(l => !okLangs.includes(l)) };
54
+ `;
55
+ },
56
+ },
57
+ review: {
58
+ name: "review",
59
+ description: "全面代码审查:每个文件一个评审 agent 并行审查,发现项再交独立 agent 对抗性验证,只保留核实为真的问题",
60
+ inputHint: '{ "files": ["src/a.ts", "src/b.ts"] } — files 可省略,默认取 git diff --name-only HEAD 的改动文件',
61
+ build(input) {
62
+ let files = strArray(input.files);
63
+ if (files.length === 0)
64
+ files = gitDiffFiles();
65
+ if (files.length === 0)
66
+ throw new Error("review 模板需要 files 数组,或当前仓库有未提交改动");
67
+ return `
68
+ const files = ${lit(files)};
69
+ log("review:评审 " + files.length + " 个文件,发现项将做对抗性验证");
70
+ const reports = await parallel(files.map(f => () =>
71
+ subagent({
72
+ task: "通读 " + f + " 及其直接依赖,做代码审查:正确性 bug、安全漏洞、明显的性能问题。" +
73
+ "只报告有把握的问题,每条给出文件、行号、严重程度(高/中/低)、问题描述和建议修法。没有问题就明确说无发现。"
74
+ })
75
+ ));
76
+ const findings = reports.filter(Boolean).join("\\n\\n---\\n\\n");
77
+ if (!findings.trim()) return { verified: "(所有文件均无发现)" };
78
+ const verified = await subagent({
79
+ task: "下面是一份代码审查发现列表。逐条对抗性验证:打开涉及的文件核对,剔除不成立、夸大或已过时的条目," +
80
+ "只保留核实为真的问题,按严重程度排序输出完整清单。\\n\\n" + findings
81
+ });
82
+ return { verified };
83
+ `;
84
+ },
85
+ },
86
+ research: {
87
+ name: "research",
88
+ description: "并行研究:每个方向一个子 agent 独立调查(可联网),最后汇总成一份综合报告",
89
+ inputHint: '{ "questions": ["方向一", "方向二"], "context": "可选背景" }',
90
+ build(input) {
91
+ const questions = strArray(input.questions);
92
+ if (questions.length === 0)
93
+ throw new Error('research 模板需要 questions 数组,例如 { "questions": ["竞品A的定价", "竞品B的功能"] }');
94
+ const context = str(input.context);
95
+ const contextLine = context ? `调查背景:${context}。` : "";
96
+ return `
97
+ const questions = ${lit(questions)};
98
+ log("research:并行调查 " + questions.length + " 个方向");
99
+ const reports = await parallel(questions.map(q => () =>
100
+ subagent({
101
+ task: "调查以下问题,可以用 web_search/web_fetch 联网,也可以读本地代码和文档。" +
102
+ "输出:关键事实(带来源)、不同观点、你的结论。${contextLine}问题:" + q
103
+ })
104
+ ));
105
+ const merged = reports
106
+ .map((r, i) => (r ? "## 方向 " + (i + 1) + ":" + questions[i] + "\\n\\n" + r : null))
107
+ .filter(Boolean)
108
+ .join("\\n\\n");
109
+ if (!merged.trim()) return { synthesis: "(所有方向都失败了)", failed: questions.length };
110
+ const synthesis = await subagent({
111
+ task: "把以下几份调查报告综合成一份结论性报告:先给核心结论(不超过 5 条),再给分方向要点," +
112
+ "最后列分歧点和待确认项。不要编造报告里没有的信息。\\n\\n" + merged
113
+ });
114
+ return { synthesis };
115
+ `;
116
+ },
117
+ },
118
+ refactor: {
119
+ name: "refactor",
120
+ description: "批量重构/迁移:先由一个 agent 读代表文件制定统一规则,然后每个文件一个子 agent 在独立 worktree 里套用规则,互不冲突",
121
+ inputHint: '{ "instruction": "把所有 var 改为 const", "files": ["src/a.ts", ...] } — files 省略时用 git diff 改动文件',
122
+ build(input) {
123
+ const instruction = str(input.instruction);
124
+ if (!instruction)
125
+ throw new Error('refactor 模板需要 instruction,例如 { "instruction": "把 var 全部改为 const" }');
126
+ const files = strArray(input.files);
127
+ return `
128
+ const instruction = ${lit(instruction)};
129
+ let targetFiles = ${lit(files)};
130
+ if (targetFiles.length === 0) {
131
+ const listed = await subagent({
132
+ task: "运行 git diff --name-only HEAD,把输出的文件路径一行一个原样返回,不要加任何其他文字。"
133
+ });
134
+ targetFiles = listed.split("\\n").map(s => s.trim()).filter(Boolean);
135
+ }
136
+ if (targetFiles.length === 0) throw new Error("没有可处理的文件:files 为空且 git 无改动");
137
+ log("refactor:共 " + targetFiles.length + " 个文件,先制定统一规则");
138
+ const rule = await subagent({
139
+ task: "我们要对一批文件做统一重构:" + instruction + "。" +
140
+ "先读其中 1-2 个代表性文件了解现状,然后输出一份精确的重构规则清单(每条:什么模式改成什么、边界情况怎么处理)。" +
141
+ "规则要具体到可以直接照做,不要空话。涉及文件:" + targetFiles.slice(0, 10).join(",")
142
+ });
143
+ const results = await parallel(targetFiles.map(f => () =>
144
+ subagent({
145
+ task: "按以下重构规则处理文件 " + f + ",改完检查该文件语法正确(必要时运行 tsc 或构建验证)。\\n\\n重构规则:\\n" + rule,
146
+ worktree: true
147
+ })
148
+ ));
149
+ const done = targetFiles.filter((_, i) => results[i] !== null);
150
+ return { applied: done, failed: targetFiles.filter(f => !done.includes(f)), rule };
151
+ `;
152
+ },
153
+ },
154
+ };
155
+ /** 按模板名生成脚本;生成后自检必须过静态校验(防模板本身写出不合规代码)。 */
156
+ export function buildFromTemplate(template, input) {
157
+ const t = TEMPLATES[template];
158
+ if (!t) {
159
+ throw new Error(`未知模板 "${template}",可用:${Object.keys(TEMPLATES).join(", ")}`);
160
+ }
161
+ const code = t.build(input ?? {});
162
+ const errors = validateScript(code);
163
+ if (errors.length > 0) {
164
+ throw new Error(`模板 ${template} 生成的脚本未通过静态校验(模板 bug,请反馈):${errors.join(";")}`);
165
+ }
166
+ return code;
167
+ }
@@ -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>;
@@ -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.',
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,24 @@ 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
+ }
64
80
  if (code) {
65
81
  const errors = validateScript(code);
66
82
  if (errors.length > 0) {
67
83
  throw new Error(`脚本未通过静态校验,请修复后重试:\n- ${errors.join("\n- ")}`);
68
84
  }
69
- scriptPath = saveWorkflowScript(code);
85
+ }
86
+ else if (params.template?.trim()) {
87
+ // 内置模板:模型只填参数,脚本由模板生成(生成后自检过静态校验)
88
+ try {
89
+ code = buildFromTemplate(params.template.trim(), (params.input ?? {}));
90
+ }
91
+ catch (e) {
92
+ throw new Error(`${e.message}\n模板 input 说明:${TEMPLATES[params.template.trim()]?.inputHint ?? "—"}`);
93
+ }
70
94
  }
71
95
  else if (params.script_path?.trim()) {
72
96
  scriptPath = resolve(params.script_path.trim());
@@ -78,7 +102,17 @@ export function createRunWorkflowTool(getParentModel) {
78
102
  }
79
103
  }
80
104
  else {
81
- throw new Error("scriptscript_path 至少填一个");
105
+ throw new Error("script、template、script_path 至少填一个");
106
+ }
107
+ // 落盘:save_as 用语义化名字(同名报错防覆盖进度配对),否则时间戳名;
108
+ // script_path 分支上面已读入,不重复落盘
109
+ if (!scriptPath) {
110
+ scriptPath = named ? resolve(workflowsDir(), `${named}.mjs`) : saveWorkflowScript(code ?? "");
111
+ if (named && existsSync(scriptPath)) {
112
+ throw new Error(`工作流 "${named}" 已存在(${scriptPath})。要重跑它请用 script_path 指向该文件(可加 resume:true 续跑);要新建请换个名字`);
113
+ }
114
+ mkdirSync(dirname(scriptPath), { recursive: true });
115
+ writeFileSync(scriptPath, code ?? "");
82
116
  }
83
117
  const progressPath = scriptPath.replace(/\.mjs$/, ".progress.jsonl");
84
118
  // 流式进度:onProgress 高频触发,节流到 ≥2s 一次才推给 TUI
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "u1s1-cli",
3
- "version": "0.18.0",
3
+ "version": "0.19.0",
4
4
  "description": "u1s1 — 有一说一,最省心的 AI 编程搭子。终端里用中文说需求,AI 帮你读文件、改代码、跑命令。",
5
5
  "type": "module",
6
6
  "bin": {