@yiyi_zhang/laoshi 0.1.1 → 0.2.0-beta.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.
Files changed (86) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/adapters/dsh/plugin/index.mjs +1 -1
  3. package/adapters/dsh/plugin/package.json +1 -1
  4. package/adapters/mogao/adapter.ts +46 -0
  5. package/adapters/mogao/install.mjs +31 -0
  6. package/adapters/mogao/make-expert.mjs +63 -0
  7. package/adapters/mogao/mogao-runtime.ts +457 -0
  8. package/adapters/mogao/skill/setup.md +21 -0
  9. package/bin/install.mjs +8 -2
  10. package/bin/req.mjs +8 -0
  11. package/contracts/agent-runtime.md +3 -0
  12. package/docs/design/mogao-expert.md +101 -0
  13. package/engine/src/api.ts +5 -5
  14. package/engine/src/code-review.ts +2 -2
  15. package/engine/src/control.ts +6 -6
  16. package/engine/src/danger-guard.ts +7 -0
  17. package/engine/src/doctor.ts +1 -1
  18. package/engine/src/features.ts +2 -2
  19. package/engine/src/integration-cmd.ts +2 -2
  20. package/engine/src/launch.ts +44 -6
  21. package/engine/src/locations.ts +15 -1
  22. package/engine/src/main.ts +3 -0
  23. package/engine/src/permission-cmd.ts +56 -0
  24. package/engine/src/platform.ts +5 -0
  25. package/engine/src/preflight.ts +2 -2
  26. package/engine/src/runtime-loader.ts +2 -0
  27. package/engine/src/runtime.ts +5 -0
  28. package/engine/src/skills-render.ts +10 -6
  29. package/engine/src/state.ts +23 -1
  30. package/package.json +1 -1
  31. package/site-dist/404.html +2 -2
  32. package/site-dist/assets/{app.Df99UgrJ.js → app.DMAHANCl.js} +1 -1
  33. package/site-dist/assets/changelog.md.Q8QGpuBY.js +1 -0
  34. package/site-dist/assets/chunks/@localSearchIndexroot.CQdjFK3w.js +1 -0
  35. package/site-dist/assets/chunks/{VPLocalSearchBox.IEhP6Gw5.js → VPLocalSearchBox.COsLwqWS.js} +1 -1
  36. package/site-dist/assets/chunks/{theme.DHubfO7g.js → theme.CeR3HD86.js} +2 -2
  37. package/site-dist/assets/{guide_getting-started.md.BZTWiHhH.js → guide_getting-started.md.Bytaz3L8.js} +1 -1
  38. package/site-dist/assets/{guide_getting-started.md.BZTWiHhH.lean.js → guide_getting-started.md.Bytaz3L8.lean.js} +1 -1
  39. package/site-dist/assets/{reference_contracts_agent-runtime.md.Bu8q-uGl.js → reference_contracts_agent-runtime.md.TK7Lhwdf.js} +1 -1
  40. package/site-dist/changelog.html +5 -5
  41. package/site-dist/guide/dsh.html +4 -4
  42. package/site-dist/guide/getting-started.html +5 -5
  43. package/site-dist/guide/how-it-works.html +4 -4
  44. package/site-dist/guide/index.html +4 -4
  45. package/site-dist/guide/install.html +4 -4
  46. package/site-dist/guide/intranet.html +4 -4
  47. package/site-dist/guide/maintainer.html +4 -4
  48. package/site-dist/guide/phases.html +4 -4
  49. package/site-dist/guide/project.html +4 -4
  50. package/site-dist/guide/user.html +4 -4
  51. package/site-dist/hashmap.json +1 -1
  52. package/site-dist/index.html +4 -4
  53. package/site-dist/reference/adr/0001-new-repo-core-and-adapters.html +4 -4
  54. package/site-dist/reference/adr/0002-two-orchestration-modes.html +4 -4
  55. package/site-dist/reference/adr/0003-generate-once-then-lock.html +4 -4
  56. package/site-dist/reference/adr/0004-external-contracts-stay-stable.html +4 -4
  57. package/site-dist/reference/adr/0005-skill-names.html +4 -4
  58. package/site-dist/reference/adr/0006-deterministic-engine-platform-capabilities.html +4 -4
  59. package/site-dist/reference/adr/0007-one-install-many-repos.html +4 -4
  60. package/site-dist/reference/adr/0008-capability-sources-and-platform-plugin.html +4 -4
  61. package/site-dist/reference/adr/index.html +4 -4
  62. package/site-dist/reference/commands.html +4 -4
  63. package/site-dist/reference/config.html +4 -4
  64. package/site-dist/reference/contracts/agent-runtime.html +5 -5
  65. package/site-dist/reference/contracts/cli-json.html +4 -4
  66. package/site-dist/reference/contracts/feature-files.html +4 -4
  67. package/site-dist/reference/contracts/index.html +4 -4
  68. package/site-dist/reference/contracts/notifier-event.html +4 -4
  69. package/site-dist/reference/contracts/result-file.html +4 -4
  70. package/site-dist/reference/contracts/spec.html +4 -4
  71. package/site-dist/reference/contracts/state.html +4 -4
  72. package/site-dist/reference/contracts/usage-record.html +4 -4
  73. package/site-dist/reference/contracts/verify.html +4 -4
  74. package/site-dist/reference/design/adapter-guide.html +4 -4
  75. package/site-dist/reference/design/architecture.html +4 -4
  76. package/site-dist/reference/design/builtin-capabilities.html +4 -4
  77. package/site-dist/reference/design/platform-vocabulary.html +4 -4
  78. package/site-dist/reference/scope.html +4 -4
  79. package/skills/laoshi/SKILL.md +3 -0
  80. package/skills/laoshi-doctor/SKILL.md +2 -0
  81. package/skills/laoshi-retro/SKILL.md +2 -0
  82. package/skills/laoshi-setup/SKILL.md +3 -0
  83. package/site-dist/assets/changelog.md.Df8vFhjK.js +0 -1
  84. package/site-dist/assets/chunks/@localSearchIndexroot.n-0kN-N0.js +0 -1
  85. /package/site-dist/assets/{changelog.md.Df8vFhjK.lean.js → changelog.md.Q8QGpuBY.lean.js} +0 -0
  86. /package/site-dist/assets/{reference_contracts_agent-runtime.md.Bu8q-uGl.lean.js → reference_contracts_agent-runtime.md.TK7Lhwdf.lean.js} +0 -0
package/CHANGELOG.md CHANGED
@@ -2,6 +2,18 @@
2
2
 
3
3
  laoshi 的版本号遵循语义化版本,从 0.1.0 开始;每一版的标题写成 `## <版本> - <日期>`。每一版先写使用者会看到的变化,再写升级须知。laoshi 之前的历史见 paseo-req-kit 的更新记录(laoshi 从它的 1.15.0 抽出)。
4
4
 
5
+ ## 0.2.0-beta.1 - 2026-11-07
6
+
7
+ 预发布版(npm 的 `beta` 标签,`latest` 仍是 0.1.1):支持摸高,用来在摸高沙箱里验证专家。安装:`npx -y @yiyi_zhang/laoshi@beta install --platform <平台>`。
8
+
9
+ ### 使用者会看到的变化
10
+
11
+ - **支持摸高**(`laoshi install --platform mogao`):每一步是摸高的一个独立 agent(`aimax run`),审批用摸高的人工审批,工具调用和用量来自摸高的进度回调。引擎在对话的命令里运行,进展显示在命令输出里;对话轮次结束打断的运行,下一轮用继续命令接着做。
12
+ - **摸高专家**:`node adapters/mogao/make-expert.mjs` 生成提交给摸高的专家(按摸高渲染的 skill 和介绍);入口 skill 第一次使用时把 laoshi 装到工作区,并说明在摸高上命令会一直运行到停下、等待批准怎么回答、工具装在工作区。
13
+ - **安装根**:没有 `LAOSHI_HOME` 时,程序装在 `<安装根>/npm` 下就用这个安装根(每个对话轮次换机器的平台上不能依赖 `~`)。
14
+ - **`laoshi permission <需求> approve|deny [理由]`**:在对话里批准或拒绝步骤等待批准的操作,并接着运行(摸高上用)。
15
+ - **危险命令拦截**:读出凭据环境变量(如 `echo $XXX_TOKEN`、`printenv`)算作危险操作。
16
+
5
17
  ## 0.1.1 - 2026-11-05
6
18
 
7
19
  在 npm 上的包名改为 **`@yiyi_zhang/laoshi`**:`laoshi` 这个名字在 npm 上不能使用,0.1.0 只发布到了 GitHub Release,没有发布到 npm。其余内容与 0.1.0 相同。
@@ -14,7 +14,7 @@ import { channelPaths, dshHome } from "./channel.mjs";
14
14
  export const name = "laoshi-dsh";
15
15
  export const inject = ["agents", "subagents", "schedule", "approval", "sessionController", "llm"];
16
16
 
17
- const VERSION = "0.1.1";
17
+ const VERSION = "0.2.0-beta.1";
18
18
  const SHELL_TOOLS = new Set(["bash", "pwsh"]);
19
19
  const SEARCH_TOOLS = new Set(["grep", "glob"]);
20
20
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "laoshi-dsh-plugin",
3
- "version": "0.1.1",
3
+ "version": "0.2.0-beta.1",
4
4
  "private": true,
5
5
  "description": "laoshi's plugin for the DeepSeek Harness host: creates step agents under the chat, schedules messages, answers approvals by policy, and serves the laoshi engine over a local socket (ADR 0008).",
6
6
  "type": "module",
@@ -0,0 +1,46 @@
1
+ // The 摸高 adapter (docs/design/mogao-expert.md, form B1): step agents are runs of the platform's
2
+ // command line (`aimax run`), approvals are the platform's HITL answered through laoshi, tool calls
3
+ // and usage come from the platform's progress callback. Worktrees and services are laoshi's builtin
4
+ // ones. The platform keeps a chat's machine for one turn, so the engine runs in the chat's command.
5
+
6
+ import { spawnSync } from "node:child_process";
7
+ import path from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import type { PlatformAdapter } from "../../engine/src/platform.js";
10
+ import { mogaoSettings } from "./mogao-runtime.js";
11
+
12
+ export const mogaoAdapter: PlatformAdapter = {
13
+ id: "mogao",
14
+ displayName: "摸高",
15
+ createRuntime: async (input) => (await import("./mogao-runtime.js")).createRuntime(input),
16
+ capabilities: {
17
+ services: "builtin",
18
+ worktree: "builtin",
19
+ activity: "platform",
20
+ runningTool: "platform",
21
+ toolCalls: "platform",
22
+ },
23
+ originEnv: { id: "AIMAX_SESSION_ID" },
24
+ runsInChat: true,
25
+ skillSetup: path.join(path.dirname(fileURLToPath(import.meta.url)), "skill", "setup.md"),
26
+ words: {
27
+ name: "摸高",
28
+ chat: "摸高的对话",
29
+ schedule: "定时任务(摸高上没有,到时请在对话里说\"继续\")",
30
+ approvePermission: "在对话里回答\"批准\"或\"拒绝\",对话会运行 `laoshi permission <需求> approve`(或 `deny`)并接着做",
31
+ signIn: "检查摸高的模型配置",
32
+ origin: "摸高提供的 `AIMAX_SESSION_ID`",
33
+ connectFix: "确认在摸高的对话里运行,并且 `aimax` 命令可用(`aimax --version`)。",
34
+ },
35
+ doctorTitle: "摸高(aimax 命令行)",
36
+ async doctorPlatform({ config, tools }) {
37
+ const settings = mogaoSettings(config);
38
+ const r = spawnSync(settings.command, ["--version"], { encoding: "utf8", timeout: 20_000 });
39
+ if (r.error || r.status !== 0) {
40
+ tools.report("fail", `运行 ${settings.command} --version 失败:${r.error?.message ?? (r.stderr || r.stdout).trim()}`, "在摸高的对话或沙箱里运行;不在 PATH 中时在安装级配置的 platform.mogao.command 写上它的完整路径");
41
+ return;
42
+ }
43
+ tools.report("ok", `aimax ${(r.stdout || "").trim()}(数据目录 ${settings.dataDir},单次运行上限 ${settings.runTimeoutMinutes} 分钟)`);
44
+ if (!process.env.AIMAX_SESSION_ID) tools.info("没有 AIMAX_SESSION_ID:不在摸高的对话里运行,进展只写入日志");
45
+ },
46
+ };
@@ -0,0 +1,31 @@
1
+ // laoshi installer, 摸高 part (bin/install.mjs). The platform loads skills from the expert that is
2
+ // submitted to it, so the skills rendered for 摸高 go into the install root's skills directory: that
3
+ // directory is the expert's skill package. Nothing else to install: step agents use `aimax`.
4
+ import path from "node:path";
5
+
6
+ export const id = "mogao";
7
+
8
+ /** Installer options this platform reads (bin/install.mjs passes them through). */
9
+ export const options = {};
10
+
11
+ /** The install-level config's platform section for a new installation. */
12
+ export function platformConfig() {
13
+ return { adapter: "mogao", mogao: { dataDir: "/data" } };
14
+ }
15
+
16
+ /** Every step on the platform's model (`aimax run` takes the chat's). */
17
+ export const defaultAgents = { builder: { provider: "mogao/chat-model" }, reviewer: { provider: "mogao/chat-model" } };
18
+
19
+ /** The expert's skill package: <install root>/skills. */
20
+ export function skillTargets(args, config, env = process.env, home) {
21
+ const root = home ?? path.resolve(env.LAOSHI_HOME ?? path.join(env.HOME ?? "", ".laoshi"));
22
+ const dir = path.join(root, "skills");
23
+ return [{ dir, label: `专家的 skill 目录 ${dir}(提交到摸高的专家用这个目录)` }];
24
+ }
25
+
26
+ export function setup({ report }) {
27
+ report("info", "步骤 agent 用摸高的 aimax 命令运行;在摸高上请把安装根放在工作区(LAOSHI_HOME=/data/workspace/.laoshi)");
28
+ return ["把上面专家的 skill 目录提交为摸高的专家(或在对话里加载它)", "体检:laoshi doctor --no-project"];
29
+ }
30
+
31
+ export function uninstall() {}
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env node
2
+ // Builds the 摸高 expert: laoshi's skills rendered for 摸高, as they will run there (the program in
3
+ // the workspace, /data/workspace/.laoshi/npm/node_modules/<package>, installed on first use by the
4
+ // skills themselves), and a short description of the expert. The result is what is submitted to the
5
+ // platform as the expert (a directory and a zip of it).
6
+ //
7
+ // node adapters/mogao/make-expert.mjs [--out <dir>]
8
+ import { execFileSync, spawnSync } from "node:child_process";
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+ import { parseArgs } from "node:util";
13
+
14
+ const kit = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
15
+ const pkg = JSON.parse(fs.readFileSync(path.join(kit, "package.json"), "utf8"));
16
+ const { values } = parseArgs({ options: { out: { type: "string", default: path.join(kit, "dist-expert") } } });
17
+ const WORKSPACE_HOME = "/data/workspace/.laoshi";
18
+ const programRoot = `${WORKSPACE_HOME}/npm/node_modules/${pkg.name}`;
19
+ const name = `laoshi-expert-${pkg.version}`;
20
+ const out = path.resolve(values.out, name);
21
+ fs.rmSync(out, { recursive: true, force: true });
22
+ fs.mkdirSync(out, { recursive: true });
23
+
24
+ const config = path.join(out, ".render-config.json");
25
+ fs.writeFileSync(config, JSON.stringify({ platform: { adapter: "mogao" } }));
26
+ const tsx = path.join(kit, "node_modules", "tsx", "dist", "cli.mjs");
27
+ const r = spawnSync(process.execPath, [tsx, path.join(kit, "engine", "src", "skills-render.ts"), "--out", path.join(out, "skills"), "--config", config, "--root", programRoot], { encoding: "utf8" });
28
+ fs.rmSync(config);
29
+ if (r.status !== 0) {
30
+ console.error(r.stderr || r.stdout);
31
+ process.exit(1);
32
+ }
33
+
34
+ const skills = fs.readdirSync(path.join(out, "skills")).filter((d) => fs.existsSync(path.join(out, "skills", d, "SKILL.md")));
35
+ const describe = (d) => /^description:\s*(.+)$/m.exec(fs.readFileSync(path.join(out, "skills", d, "SKILL.md"), "utf8"))?.[1] ?? "";
36
+ fs.writeFileSync(
37
+ path.join(out, "EXPERT.md"),
38
+ [
39
+ `# laoshi 需求开发专家(${pkg.version})`,
40
+ "",
41
+ "给测试、产品、项目经理用:在对话里把需求谈清楚、写成需求说明并确认,之后由一组 agent 完成方案、实现、评审、验证和报告,每个要拍板的地方都停下来等人。",
42
+ "",
43
+ "- 入口:`/laoshi`(需求开发)、`/laoshi-setup`(项目接入,每个项目一次)、`/laoshi-doctor`(体检)、`/laoshi-retro`(复盘)",
44
+ `- 第一次使用时,入口 skill 会从内网 npm 镜像把 \`${pkg.name}@${pkg.version}\` 装到 \`${WORKSPACE_HOME}\`(约一分钟),之后每个对话直接使用`,
45
+ "- 每一步是摸高的一个独立 agent(`aimax run`);需要批准的操作走摸高的人工审批;进度和用量来自摸高的回调",
46
+ "",
47
+ "## 包含的 skill",
48
+ "",
49
+ "| skill | 作用 |",
50
+ "| --- | --- |",
51
+ ...skills.sort().map((d) => `| \`${d}\` | ${describe(d).replace(/\|/g, "\\|")} |`),
52
+ "",
53
+ ].join("\n"),
54
+ );
55
+
56
+ const zip = path.resolve(values.out, `${name}.zip`);
57
+ fs.rmSync(zip, { force: true });
58
+ try {
59
+ execFileSync("zip", ["-qr", zip, name], { cwd: path.resolve(values.out) });
60
+ console.log(`已生成专家:${out}\n压缩包:${zip}`);
61
+ } catch {
62
+ console.log(`已生成专家:${out}(没有 zip 命令,未打包)`);
63
+ }
@@ -0,0 +1,457 @@
1
+ // The engine's runtime for 摸高 (docs/design/mogao-expert.md, form B1). Each step agent is a run of the
2
+ // platform's command line, `aimax run` (a new agent with tools, synchronous, JSON output), continued
3
+ // with `-s <sessionId>`; approvals are the platform's HITL (`paused`, then `aimax resume`). Tool
4
+ // calls and usage come from the platform's progress callback (`--callback-url`), received here.
5
+ //
6
+ // The platform keeps a container for one chat turn only, so the engine runs in the chat's command
7
+ // and every agent's state is kept on disk (<install root>/mogao/agents/<id>/): a later turn's engine
8
+ // picks an agent up again, and continues its session when the turn ended in the middle of a run.
9
+ //
10
+ // Worktrees and services are laoshi's builtin ones; there is no scheduling and no way to send the
11
+ // chat a message, so notifications go to the chat's command output (LAOSHI_CHAT_OUT, see launch.ts).
12
+ import { type ChildProcess, spawn } from "node:child_process";
13
+ import crypto from "node:crypto";
14
+ import fs from "node:fs";
15
+ import http from "node:http";
16
+ import os from "node:os";
17
+ import path from "node:path";
18
+ import type { ToolCall } from "../../engine/src/danger-guard.js";
19
+ import { homeOf } from "../../engine/src/locations.js";
20
+ import { isAlive as engineProcessAlive } from "../../engine/src/state.js";
21
+ import type { AgentRuntime, RuntimeFactory, StepAgent, WaitOutcome } from "../../engine/src/runtime.js";
22
+ import type { RunningTool } from "../../engine/src/scan-guard.js";
23
+ import type { AgentUsage } from "../../engine/src/usage.js";
24
+
25
+ /** Settings from the install-level config's platform.mogao. */
26
+ export interface MogaoSettings {
27
+ /** The platform's command line; LAOSHI_AIMAX overrides it (tests). */
28
+ command: string;
29
+ /** The platform's data directory (`-d`), where its sessions live. */
30
+ dataDir: string;
31
+ /** Hard limit of one `aimax run`, in minutes (the engine keeps its own step limits). */
32
+ runTimeoutMinutes: number;
33
+ /** `--plugins-config` for step agents (the platform's plugins, e.g. its knowledge base), or null. */
34
+ pluginsConfig: string | null;
35
+ }
36
+
37
+ export function mogaoSettings(config: unknown, env: NodeJS.ProcessEnv = process.env): MogaoSettings {
38
+ const raw = ((config as { platform?: { mogao?: Record<string, unknown> } } | null)?.platform?.mogao ?? {}) as Record<string, unknown>;
39
+ const text = (v: unknown) => (typeof v === "string" && v.trim() ? v.trim() : null);
40
+ const minutes = typeof raw.runTimeoutMinutes === "number" && raw.runTimeoutMinutes > 0 ? raw.runTimeoutMinutes : 240;
41
+ return {
42
+ command: text(env.LAOSHI_AIMAX) ?? text(raw.command) ?? "aimax",
43
+ dataDir: text(raw.dataDir) ?? "/data",
44
+ runTimeoutMinutes: minutes,
45
+ pluginsConfig: text(raw.pluginsConfig),
46
+ };
47
+ }
48
+
49
+ /** The platform's result of a run (`--output json`), as far as the engine reads it. */
50
+ export interface RunResult {
51
+ sessionId?: string;
52
+ text?: string;
53
+ usage?: { input?: number; output?: number; total?: number } | null;
54
+ paused?: { requestId: string; kind?: string; title?: string } | null;
55
+ error?: string | null;
56
+ }
57
+
58
+ export function toAgentUsage(u: RunResult["usage"]): AgentUsage | null {
59
+ if (!u) return null;
60
+ return { inputTokens: u.input ?? 0, cachedInputTokens: 0, outputTokens: u.output ?? 0 };
61
+ }
62
+
63
+ /** Takes the JSON object out of a run's standard output (the last line that parses). */
64
+ export function parseRunOutput(stdout: string): RunResult | null {
65
+ const trimmed = stdout.trim();
66
+ if (!trimmed) return null;
67
+ try {
68
+ return JSON.parse(trimmed) as RunResult;
69
+ } catch {
70
+ for (const line of trimmed.split("\n").reverse()) {
71
+ try {
72
+ const value = JSON.parse(line.trim()) as unknown;
73
+ if (value && typeof value === "object") return value as RunResult;
74
+ } catch {
75
+ // Not this line.
76
+ }
77
+ }
78
+ return null;
79
+ }
80
+ }
81
+
82
+ /** Platform credentials and tokens are never written to laoshi's files. */
83
+ export function redact(text: string): string {
84
+ return text
85
+ .replace(/(authorization["']?\s*[:=]\s*["']?(?:bearer\s+)?)[^\s"',}]+/gi, "$1***")
86
+ .replace(/\b(bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi, "$1***")
87
+ .replace(/((?:token|secret|password|api[_-]?key|credential)[A-Za-z_]*["']?\s*[:=]\s*["']?)[^\s"',}]{4,}/gi, "$1***")
88
+ .replace(/(AIMAX_[A-Z_]*(?:TOKEN|KEY|SECRET)[A-Z_]*=)\S+/g, "$1***");
89
+ }
90
+
91
+ /** What laoshi keeps about one step agent between engine processes. */
92
+ interface AgentRecord {
93
+ id: string;
94
+ cwd: string;
95
+ title: string;
96
+ sessionId: string | null;
97
+ /** Number of runs so far (run-<n>.out is the latest's output). */
98
+ runs: number;
99
+ /** The latest run's process, and the machine (container) it ran in. */
100
+ pid: number | null;
101
+ host: string | null;
102
+ /** The HITL request a decision was sent for (decision.json), so it is answered once. */
103
+ answered: string | null;
104
+ }
105
+
106
+ /** A decision on a pending approval, written by `laoshi permission` (answerPermission). */
107
+ interface Decision {
108
+ requestId: string;
109
+ approve: boolean;
110
+ reason: string;
111
+ }
112
+
113
+ const CONTINUE_MESSAGE = "上一次运行被中断了(对话轮次结束)。请接着完成原来的任务:先看一下已经做了什么,不要重复已经完成的部分。";
114
+
115
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
116
+
117
+ const isAlive = (pid: number) => engineProcessAlive(pid);
118
+
119
+ /** The callback receiver: one local HTTP server for all step agents of this engine process. */
120
+ class CallbackServer {
121
+ private server: http.Server | null = null;
122
+ private port = 0;
123
+ constructor(private readonly onEvent: (agentId: string, event: Record<string, unknown>) => void) {}
124
+
125
+ async url(agentId: string): Promise<string> {
126
+ if (!this.server) {
127
+ this.server = http.createServer((req, res) => {
128
+ const agentId = decodeURIComponent((req.url ?? "").replace(/^\/cb\//, "").split("?")[0]);
129
+ let body = "";
130
+ req.setEncoding("utf8");
131
+ req.on("data", (chunk) => {
132
+ if (body.length < 4_000_000) body += chunk;
133
+ });
134
+ req.on("end", () => {
135
+ res.writeHead(204).end();
136
+ try {
137
+ const event = JSON.parse(body) as Record<string, unknown>;
138
+ if (agentId) this.onEvent(agentId, event);
139
+ } catch {
140
+ // Not an event.
141
+ }
142
+ });
143
+ });
144
+ await new Promise<void>((resolve) => this.server!.listen(0, "127.0.0.1", resolve));
145
+ this.port = (this.server.address() as { port: number }).port;
146
+ this.server.unref();
147
+ }
148
+ return `http://127.0.0.1:${this.port}/cb/${encodeURIComponent(agentId)}`;
149
+ }
150
+
151
+ close(): Promise<void> {
152
+ return new Promise((resolve) => (this.server ? this.server.close(() => resolve()) : resolve()));
153
+ }
154
+ }
155
+
156
+ /** An event's type and payload, whatever envelope the platform wraps them in. */
157
+ export function eventParts(event: Record<string, unknown>): { type: string; data: Record<string, unknown> } {
158
+ const type = String(event.type ?? event.event ?? "");
159
+ const data = (event.data ?? event.payload ?? event) as Record<string, unknown>;
160
+ return { type, data: data && typeof data === "object" ? data : {} };
161
+ }
162
+
163
+ export interface MogaoRuntimeOptions {
164
+ settings: MogaoSettings;
165
+ /** Where agents' records live: <install root>/mogao/agents. */
166
+ agentsDir: string;
167
+ log: (message: string) => void;
168
+ /** Where notifications for the chat go (the chat's command output); null: the log only. */
169
+ chatOut: string | null;
170
+ env?: NodeJS.ProcessEnv;
171
+ pollMs?: number;
172
+ }
173
+
174
+ export function createMogaoRuntime(options: MogaoRuntimeOptions): AgentRuntime {
175
+ const { settings, agentsDir, log } = options;
176
+ const env = options.env ?? process.env;
177
+ const pollMs = options.pollMs ?? 500;
178
+ const children = new Map<string, ChildProcess>();
179
+ const dir = (id: string) => path.join(agentsDir, id);
180
+ const recordFile = (id: string) => path.join(dir(id), "agent.json");
181
+ const read = (id: string): AgentRecord | null => {
182
+ try {
183
+ return JSON.parse(fs.readFileSync(recordFile(id), "utf8")) as AgentRecord;
184
+ } catch {
185
+ return null;
186
+ }
187
+ };
188
+ const write = (record: AgentRecord) => {
189
+ fs.mkdirSync(dir(record.id), { recursive: true });
190
+ fs.writeFileSync(recordFile(record.id), `${JSON.stringify(record, null, 2)}\n`);
191
+ };
192
+ const eventsFile = (id: string) => path.join(dir(id), "events.jsonl");
193
+
194
+ const callbacks = new CallbackServer((agentId, event) => {
195
+ if (!fs.existsSync(dir(agentId))) return;
196
+ const { type, data } = eventParts(event);
197
+ if (type === "start" && typeof data.sessionId === "string") {
198
+ const record = read(agentId);
199
+ if (record && !record.sessionId) write({ ...record, sessionId: data.sessionId });
200
+ }
201
+ // Tool output can hold anything the agent printed: keep a redacted, shortened copy.
202
+ const keep: Record<string, unknown> = { at: new Date().toISOString(), type };
203
+ if (type === "tool_start") {
204
+ const input = (data.input ?? {}) as Record<string, unknown>;
205
+ Object.assign(keep, { callId: data.toolCallId, name: data.name, command: typeof input.command === "string" ? redact(input.command) : null, riskLevel: input.riskLevel ?? null });
206
+ } else if (type === "tool_end") {
207
+ const details = (data.details ?? {}) as Record<string, unknown>;
208
+ Object.assign(keep, { callId: data.toolCallId, exitCode: details.exitCode ?? null, output: typeof data.output === "string" ? redact(data.output).slice(-2000) : null });
209
+ } else if (type === "usage") {
210
+ Object.assign(keep, { input: data.input ?? null, output: data.output ?? null, total: data.total ?? null });
211
+ } else if (type === "done") {
212
+ const result = (data.result ?? {}) as Record<string, unknown>;
213
+ Object.assign(keep, { usage: result.usage ?? null });
214
+ } else if (type !== "start" && type !== "title_updated") {
215
+ return;
216
+ }
217
+ fs.appendFileSync(eventsFile(agentId), `${JSON.stringify(keep)}\n`);
218
+ });
219
+
220
+ const events = (id: string): Array<Record<string, unknown>> => {
221
+ try {
222
+ return fs
223
+ .readFileSync(eventsFile(id), "utf8")
224
+ .split("\n")
225
+ .filter(Boolean)
226
+ .map((l) => JSON.parse(l) as Record<string, unknown>);
227
+ } catch {
228
+ return [];
229
+ }
230
+ };
231
+
232
+ const toolCalls = async (id: string): Promise<ToolCall[] | null> => {
233
+ if (!read(id)) return null;
234
+ const calls = new Map<string, ToolCall>();
235
+ for (const e of events(id)) {
236
+ const callId = String(e.callId ?? "");
237
+ if (!callId) continue;
238
+ if (e.type === "tool_start") calls.set(callId, { callId, kind: e.name === "exec" ? "shell" : String(e.name ?? "tool"), text: String(e.command ?? ""), status: "running", startedAt: String(e.at) });
239
+ else if (e.type === "tool_end" && calls.has(callId)) calls.get(callId)!.status = "completed";
240
+ }
241
+ return [...calls.values()];
242
+ };
243
+
244
+ /** Starts one `aimax` process for an agent: a new run, its continuation, or an approval's answer. */
245
+ async function launch(record: AgentRecord, args: string[]): Promise<void> {
246
+ const n = record.runs + 1;
247
+ const out = fs.openSync(path.join(dir(record.id), `run-${n}.out`), "w");
248
+ const err = fs.openSync(path.join(dir(record.id), `run-${n}.err`), "w");
249
+ const callback = await callbacks.url(record.id);
250
+ const child = spawn(settings.command, [...args, "--output", "json", "--callback-url", callback], { cwd: record.cwd, env, stdio: ["ignore", out, err], windowsHide: true });
251
+ fs.closeSync(out);
252
+ fs.closeSync(err);
253
+ children.set(record.id, child);
254
+ child.on("exit", () => children.delete(record.id));
255
+ child.on("error", (e) => {
256
+ fs.appendFileSync(path.join(dir(record.id), `run-${n}.err`), `\n${e.message}\n`);
257
+ children.delete(record.id);
258
+ });
259
+ write({ ...record, runs: n, pid: child.pid ?? null, host: os.hostname() });
260
+ }
261
+
262
+ const runArgs = (record: AgentRecord, message: string) => [
263
+ "run",
264
+ ...(record.sessionId ? ["-s", record.sessionId] : ["--project-dir", record.cwd]),
265
+ "-d",
266
+ settings.dataDir,
267
+ "--message",
268
+ message,
269
+ "--timeout",
270
+ String(settings.runTimeoutMinutes * 60_000),
271
+ ...(settings.pluginsConfig ? ["--plugins-config", settings.pluginsConfig] : []),
272
+ ];
273
+
274
+ /** The latest run's result; null while it runs (here, or in another live process of this machine). */
275
+ function finished(record: AgentRecord): { result: RunResult | null; stderr: string } | null {
276
+ if (children.has(record.id)) return null;
277
+ if (record.pid && record.host === os.hostname() && isAlive(record.pid)) return null;
278
+ const read = (suffix: string) => {
279
+ try {
280
+ return fs.readFileSync(path.join(dir(record.id), `run-${record.runs}.${suffix}`), "utf8");
281
+ } catch {
282
+ return "";
283
+ }
284
+ };
285
+ return { result: parseRunOutput(read("out")), stderr: read("err") };
286
+ }
287
+
288
+ const stepAgent = (id: string): StepAgent => ({
289
+ id,
290
+ async wait(timeoutMs: number): Promise<WaitOutcome> {
291
+ const deadline = Date.now() + timeoutMs;
292
+ const base = { error: null, lastMessage: null, pendingPermissions: [] };
293
+ for (;;) {
294
+ let record = read(id);
295
+ if (!record) return { ...base, status: "error", error: `找不到 laoshi 记录的 agent ${id}` };
296
+ const done = finished(record);
297
+ if (done) {
298
+ const { result, stderr } = done;
299
+ if (result?.sessionId && result.sessionId !== record.sessionId) {
300
+ record = { ...record, sessionId: result.sessionId };
301
+ write(record);
302
+ }
303
+ const usage = toAgentUsage(result?.usage);
304
+ if (result?.paused?.requestId) {
305
+ const decision = readDecision(id);
306
+ if (decision && decision.requestId === result.paused.requestId && record.answered !== decision.requestId && record.sessionId) {
307
+ await launch({ ...record, answered: decision.requestId }, [
308
+ "resume",
309
+ "-d",
310
+ settings.dataDir,
311
+ "-s",
312
+ record.sessionId,
313
+ "--request-id",
314
+ decision.requestId,
315
+ "--input-json",
316
+ JSON.stringify({ action: decision.approve ? "approve" : "deny", reason: decision.reason }),
317
+ ]);
318
+ continue;
319
+ }
320
+ return { ...base, usage, status: "permission", pendingPermissions: [{ id: result.paused.requestId, title: result.paused.title ?? "需要批准的操作" }] };
321
+ }
322
+ if (result && !result.error) return { ...base, usage, status: "idle", lastMessage: result.text ?? null };
323
+ if (result?.error) return { ...base, usage, status: "error", error: /timed out/i.test(result.error) ? `超过 ${settings.runTimeoutMinutes} 分钟(单次运行的上限),运行已停止` : result.error };
324
+ // No result: the run was cut off (the chat's turn ended with the container). Continue its session.
325
+ if (record.sessionId && record.host !== os.hostname()) {
326
+ log(`agent ${id} 的上一次运行被中断(没有结果),接着它的会话 ${record.sessionId} 继续`);
327
+ await launch(record, runArgs(record, CONTINUE_MESSAGE));
328
+ continue;
329
+ }
330
+ return { ...base, status: "error", error: `运行没有输出结果${stderr.trim() ? `:${redact(stderr.trim()).split("\n").slice(-3).join(" ")}` : ""}` };
331
+ }
332
+ if (Date.now() >= deadline) return { ...base, status: "timeout", usage: latestUsage(id) };
333
+ await sleep(Math.min(pollMs, Math.max(0, deadline - Date.now())));
334
+ }
335
+ },
336
+ async followUp(text: string): Promise<void> {
337
+ const record = read(id);
338
+ if (!record?.sessionId) throw new Error(`agent ${id} 还没有会话,不能追问`);
339
+ await launch(record, runArgs(record, text));
340
+ },
341
+ async archive(): Promise<void> {
342
+ // Sessions stay with the platform (aimax sessions, export-html); nothing to archive.
343
+ },
344
+ });
345
+
346
+ const readDecision = (id: string): Decision | null => {
347
+ try {
348
+ return JSON.parse(fs.readFileSync(path.join(dir(id), "decision.json"), "utf8")) as Decision;
349
+ } catch {
350
+ return null;
351
+ }
352
+ };
353
+
354
+ const latestUsage = (id: string): AgentUsage | null => {
355
+ const last = events(id).filter((e) => e.type === "usage").at(-1);
356
+ return last ? toAgentUsage({ input: Number(last.input ?? 0), output: Number(last.output ?? 0) }) : null;
357
+ };
358
+
359
+ const chat = (text: string) => {
360
+ log(`给对话的消息:${text.split("\n")[0]}`);
361
+ if (options.chatOut) fs.appendFileSync(options.chatOut, `${text}\n\n`);
362
+ };
363
+
364
+ return {
365
+ async verifyOrigin() {
366
+ // The chat runs the engine in its own command, in the repository: nothing to check across.
367
+ },
368
+
369
+ async startAgent(input) {
370
+ const record: AgentRecord = { id: `mogao-${crypto.randomBytes(6).toString("hex")}`, cwd: input.cwd, title: input.title, sessionId: null, runs: 0, pid: null, host: null, answered: null };
371
+ write(record);
372
+ const promptFile = path.join(dir(record.id), "prompt.md");
373
+ fs.writeFileSync(promptFile, input.prompt);
374
+ // One command-line argument holds at most 128 KB on Linux: a longer prompt is read from its file.
375
+ const message = Buffer.byteLength(input.prompt) <= 100_000 ? input.prompt : `请先完整阅读文件 ${promptFile},然后严格按照其中的要求完成任务。`;
376
+ await launch(record, runArgs(record, message));
377
+ return stepAgent(record.id);
378
+ },
379
+
380
+ attachAgent: (agentId) => stepAgent(agentId),
381
+
382
+ async startSessionAgent() {
383
+ throw new Error("摸高上不能为需求新开对话");
384
+ },
385
+
386
+ async notifyAgent(_agentId, text) {
387
+ chat(text);
388
+ },
389
+
390
+ async interruptAgent(agentId, text) {
391
+ const child = children.get(agentId);
392
+ const record = read(agentId);
393
+ if (child) {
394
+ child.kill("SIGTERM");
395
+ await new Promise((r) => child.once("exit", r));
396
+ } else if (record?.pid && record.host === os.hostname() && isAlive(record.pid)) {
397
+ process.kill(record.pid, "SIGTERM");
398
+ for (let i = 0; i < 50 && isAlive(record.pid); i++) await sleep(100);
399
+ }
400
+ const now = read(agentId);
401
+ if (now?.sessionId) await launch(now, runArgs(now, text));
402
+ },
403
+
404
+ agentDirectory: async () => null,
405
+ listProfiles: async () => null,
406
+ listServices: async () => null,
407
+ startServices: async () => {
408
+ throw new Error("摸高不管理服务");
409
+ },
410
+ stopServices: async () => undefined,
411
+ createWorktree: async () => {
412
+ throw new Error("摸高不提供工作区");
413
+ },
414
+ waitForWorkspaceSetup: async () => ({ status: "none", error: null }),
415
+ providerQuota: async () => null,
416
+
417
+ async recentActivity(agentId, limit) {
418
+ const calls = await toolCalls(agentId);
419
+ return calls ? calls.slice(-limit).map((c) => ({ at: c.startedAt, text: c.kind === "shell" ? `运行命令:${c.text}` : `${c.kind}:${c.text}` })) : null;
420
+ },
421
+
422
+ async runningTool(agentId): Promise<RunningTool | null> {
423
+ const running = (await toolCalls(agentId))?.filter((c) => c.status === "running").at(-1);
424
+ return running ? { kind: running.kind, text: running.text, startedAt: running.startedAt, callId: running.callId } : null;
425
+ },
426
+
427
+ toolCalls,
428
+ capabilities: async () => null,
429
+ providerStatus: async () => null,
430
+ scheduleMessage: async () => null,
431
+ scheduleNewAgent: async () => null,
432
+ cancelSchedule: async () => undefined,
433
+
434
+ async answerPermission(agentId, requestId, approve, reason) {
435
+ const record = read(agentId);
436
+ if (!record) throw new Error(`找不到 laoshi 记录的 agent ${agentId}`);
437
+ const pending = finished(record)?.result?.paused?.requestId ?? null;
438
+ const id = requestId ?? pending;
439
+ if (!id) throw new Error(`agent ${agentId}(${record.title})现在没有等待批准的操作`);
440
+ const decision: Decision = { requestId: id, approve, reason };
441
+ fs.writeFileSync(path.join(dir(agentId), "decision.json"), `${JSON.stringify(decision, null, 2)}\n`);
442
+ },
443
+
444
+ async close() {
445
+ for (const child of children.values()) child.kill("SIGTERM");
446
+ await callbacks.close();
447
+ },
448
+ };
449
+ }
450
+
451
+ export const createRuntime: RuntimeFactory = async ({ config, log }) =>
452
+ createMogaoRuntime({
453
+ settings: mogaoSettings(config),
454
+ agentsDir: path.join(homeOf().dir, "mogao", "agents"),
455
+ log,
456
+ chatOut: process.env.LAOSHI_CHAT_OUT?.trim() || null,
457
+ });
@@ -0,0 +1,21 @@
1
+ <!-- laoshi: the 摸高 sections of the entry skills (the expert). Each turn of a 摸高 chat gets a new machine; only /data/workspace lasts, so laoshi lives there and is installed on first use. -->
2
+ <!-- fragment: firstUse -->
3
+ ## 摸高上第一次使用
4
+
5
+ laoshi 装在工作区(`/data/workspace/.laoshi`),每个对话轮次的机器都是新的,但工作区里的东西会保留,所以**一个工作区只需要安装一次**。执行本 skill 里的任何命令之前,先执行下面这条(工作区里已经是这个版本时立即结束;专家换了新版本时会自动换上):
6
+
7
+ ```bash
8
+ [ "$(node -p "require('{{REQ_KIT_ROOT}}/package.json').version" 2>/dev/null)" = "{{REQ_KIT_VERSION}}" ] || { npm install --prefix /data/workspace/.laoshi/npm --no-audit --no-fund @yiyi_zhang/laoshi@{{REQ_KIT_VERSION}} && node "{{REQ_KIT_ROOT}}/bin/req.mjs" install --platform mogao --home /data/workspace/.laoshi; }
9
+ ```
10
+
11
+ 第一次大约需要一分钟(从内网 npm 镜像安装)。失败时把输出告诉用户,请开发同事看一下,不要自己改安装目录。
12
+
13
+ 本 skill 里写成 `req …` 或 `laoshi …` 的命令,在摸高上写成 `node "{{REQ_KIT_ROOT}}/bin/req.mjs" …`。
14
+ <!-- fragment: launchNote -->
15
+
16
+ **在摸高上不一样的地方:**
17
+ - "启动""继续""确认方案后继续""开始测试验证"这几条命令**不会一两秒就返回**:流水线就在这条命令里运行,进展会陆续出现在命令输出里,直到需要人决定(方案确认、业务问题、等待批准)或做完,命令才结束。这期间**不要结束这一轮对话**:命令转到后台后,持续查看它的输出,把进展用一句话转告用户,等命令结束再回复。对话结束时机器会被收回,流水线随之中断;下一轮用"继续"命令接着做,已经做完的步骤不会重做。
18
+ - 输出提示某个步骤**在等待批准**时:把要批准的操作原样告诉用户,问批准还是拒绝,然后结束这一轮。用户回答后执行 `node "{{REQ_KIT_ROOT}}/bin/req.mjs" permission <功能目录> approve`(拒绝用 `deny`,可以在后面写上理由),它会转达决定并接着运行,同样要等它结束。
19
+ - 没有定时任务:预约启动、定时提醒、自动继续都用不了。需要以后再做的事,告诉用户到时在对话里说"继续"。
20
+ <!-- fragment: toolsNote -->
21
+ - **摸高的沙箱自带的工具很少**(例如没有 mvn、gradle),机器每个对话轮次都是新的,只有工作区保留。项目要用、沙箱里没有的工具,装到 `/data/workspace/.laoshi/tools/<工具>`(例如解压 Maven 到 `/data/workspace/.laoshi/tools/maven`,本地仓库设为 `/data/workspace/.laoshi/tools/m2`),命令里写工具的完整路径(例如 `/data/workspace/.laoshi/tools/maven/bin/mvn -Dmaven.repo.local=/data/workspace/.laoshi/tools/m2 test`);`verify.md` 和 `.laoshi/services.json` 里的命令也这样写,因为每次执行时 `PATH` 都会重置。