@yiyi_zhang/laoshi 0.2.0-beta.1 → 0.2.0-beta.3
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/CHANGELOG.md +32 -0
- package/adapters/cli/adapter.ts +53 -0
- package/adapters/cli/cli-runtime.ts +402 -0
- package/adapters/cli/drivers.ts +146 -0
- package/adapters/cli/install.mjs +28 -0
- package/adapters/cli/skill/setup.md +8 -0
- package/adapters/dsh/plugin/index.mjs +1 -1
- package/adapters/dsh/plugin/package.json +1 -1
- package/adapters/mogao/adapter.ts +1 -0
- package/adapters/mogao/install.mjs +1 -1
- package/adapters/mogao/make-expert.mjs +1 -0
- package/adapters/mogao/mogao-runtime.ts +98 -17
- package/adapters/paseo/adapter.ts +1 -1
- package/adapters/paseo/install.mjs +17 -5
- package/adapters/paseo/migrate.ts +267 -0
- package/adapters/paseo/plugin/OVERVIEW.md +9 -0
- package/adapters/paseo/plugin/client/config.tsx +216 -0
- package/adapters/paseo/plugin/client/data.ts +85 -0
- package/adapters/paseo/plugin/client/detail.tsx +342 -0
- package/adapters/paseo/plugin/client/format.ts +173 -0
- package/adapters/paseo/plugin/client/inbox.tsx +190 -0
- package/adapters/paseo/plugin/client/live.ts +161 -0
- package/adapters/paseo/plugin/client/markdown.tsx +220 -0
- package/adapters/paseo/plugin/client/models.tsx +117 -0
- package/adapters/paseo/plugin/client/nav.ts +22 -0
- package/adapters/paseo/plugin/client/overview.tsx +103 -0
- package/adapters/paseo/plugin/client/panel.tsx +56 -0
- package/adapters/paseo/plugin/client/review.tsx +80 -0
- package/adapters/paseo/plugin/client/row.tsx +63 -0
- package/adapters/paseo/plugin/client/settings.tsx +92 -0
- package/adapters/paseo/plugin/client/sidebar.tsx +27 -0
- package/adapters/paseo/plugin/client/stats.tsx +138 -0
- package/adapters/paseo/plugin/client/ui.tsx +278 -0
- package/adapters/paseo/plugin/client/web.ts +34 -0
- package/adapters/paseo/plugin/index.client.tsx +66 -0
- package/adapters/paseo/plugin/index.server.ts +61 -0
- package/adapters/paseo/plugin/package.json +22 -0
- package/adapters/paseo/plugin/paseo-plugin.json +6 -0
- package/adapters/paseo/plugin/server/handlers.ts +69 -0
- package/adapters/paseo/plugin/server/req.ts +105 -0
- package/adapters/paseo/plugin/shared/contracts.ts +286 -0
- package/adapters/paseo/plugin/shared/rk-colors.ts +35 -0
- package/adapters/paseo/plugin/tsconfig.json +16 -0
- package/adapters/paseo/plugin-cmd.mjs +233 -0
- package/bin/install.mjs +8 -7
- package/bin/req.mjs +10 -2
- package/contracts/README.md +1 -1
- package/contracts/agent-runtime.md +2 -2
- package/contracts/cli-json.md +4 -3
- package/contracts/notifier-event.md +2 -2
- package/contracts/state.md +2 -0
- package/contracts/usage-record.md +3 -3
- package/docs/design/adapter-guide.md +2 -1
- package/docs/design/cli-adapter.md +75 -0
- package/docs/design/compat-migration.md +2 -0
- package/docs/design/mogao-expert.md +3 -1
- package/docs/guide//345/234/250/346/221/270/351/253/230/344/270/212/344/275/277/347/224/250.md +132 -0
- package/docs/guide//345/256/211/350/243/205/344/270/216/345/215/207/347/272/247.md +32 -3
- package/docs/guide//347/273/264/346/212/244/350/200/205/346/214/207/345/215/227.md +4 -2
- package/docs/guide//351/241/271/347/233/256/345/256/232/345/210/266/344/270/216/350/277/220/350/241/214/350/247/204/345/210/231.md +1 -1
- package/engine/src/api.ts +4 -0
- package/engine/src/doctor.ts +3 -2
- package/engine/src/identity.ts +16 -1
- package/engine/src/main.ts +3 -1
- package/engine/src/messages.ts +1 -1
- package/engine/src/platform.ts +2 -0
- package/engine/src/runtime-loader.ts +14 -0
- package/engine/src/state.ts +2 -0
- package/engine/src/words.ts +1 -1
- package/package.json +2 -1
- package/site-dist/404.html +2 -2
- package/site-dist/assets/{app.DMAHANCl.js → app.CXydUhZx.js} +1 -1
- package/site-dist/assets/changelog.md.BU-CvyJ1.js +1 -0
- package/site-dist/assets/changelog.md.BU-CvyJ1.lean.js +1 -0
- package/site-dist/assets/chunks/@localSearchIndexroot.CfgJeQRO.js +1 -0
- package/site-dist/assets/chunks/{VPLocalSearchBox.COsLwqWS.js → VPLocalSearchBox.CIjDV0ax.js} +1 -1
- package/site-dist/assets/chunks/{theme.CeR3HD86.js → theme.CWtC1Kby.js} +2 -2
- package/site-dist/assets/guide_cli.md.BrXllHw9.js +2 -0
- package/site-dist/assets/guide_cli.md.BrXllHw9.lean.js +2 -0
- package/site-dist/assets/{guide_getting-started.md.Bytaz3L8.js → guide_getting-started.md.BxOxfic_.js} +1 -1
- package/site-dist/assets/guide_install.md.By4WxsJG.js +24 -0
- package/site-dist/assets/guide_install.md.By4WxsJG.lean.js +24 -0
- package/site-dist/assets/guide_maintainer.md.Da1ffqxm.js +1 -0
- package/site-dist/assets/guide_maintainer.md.Da1ffqxm.lean.js +1 -0
- package/site-dist/assets/guide_mogao.md.S0eln1Pr.js +10 -0
- package/site-dist/assets/guide_mogao.md.S0eln1Pr.lean.js +10 -0
- package/site-dist/assets/{guide_project.md.BIcaDhdS.js → guide_project.md.B2cmf8YF.js} +1 -1
- package/site-dist/assets/{guide_project.md.BIcaDhdS.lean.js → guide_project.md.B2cmf8YF.lean.js} +1 -1
- package/site-dist/assets/reference_contracts_agent-runtime.md.DPE2FJFc.js +1 -0
- package/site-dist/assets/{reference_contracts_agent-runtime.md.TK7Lhwdf.lean.js → reference_contracts_agent-runtime.md.DPE2FJFc.lean.js} +1 -1
- package/site-dist/assets/reference_contracts_cli-json.md.D6vfWOD9.js +1 -0
- package/site-dist/assets/reference_contracts_cli-json.md.D6vfWOD9.lean.js +1 -0
- package/site-dist/assets/{reference_contracts_index.md.dqNwNs6U.js → reference_contracts_index.md.B5P4FjRk.js} +1 -1
- package/site-dist/assets/{reference_contracts_index.md.dqNwNs6U.lean.js → reference_contracts_index.md.B5P4FjRk.lean.js} +1 -1
- package/site-dist/assets/{reference_contracts_notifier-event.md.D6we9wWS.js → reference_contracts_notifier-event.md.BeR8iODP.js} +1 -1
- package/site-dist/assets/{reference_contracts_notifier-event.md.D6we9wWS.lean.js → reference_contracts_notifier-event.md.BeR8iODP.lean.js} +1 -1
- package/site-dist/assets/reference_contracts_state.md.DLygjkfs.js +1 -0
- package/site-dist/assets/reference_contracts_usage-record.md.CgfMoYp0.js +10 -0
- package/site-dist/assets/reference_contracts_usage-record.md.CgfMoYp0.lean.js +10 -0
- package/site-dist/assets/{reference_design_adapter-guide.md.BSziZJSM.js → reference_design_adapter-guide.md.B_P-spS5.js} +2 -2
- package/site-dist/assets/{reference_design_adapter-guide.md.BSziZJSM.lean.js → reference_design_adapter-guide.md.B_P-spS5.lean.js} +2 -2
- package/site-dist/assets/reference_design_cli-adapter.md.pJy3x6Un.js +13 -0
- package/site-dist/assets/reference_design_cli-adapter.md.pJy3x6Un.lean.js +13 -0
- package/site-dist/changelog.html +5 -5
- package/site-dist/guide/cli.html +31 -0
- package/site-dist/guide/dsh.html +5 -5
- package/site-dist/guide/getting-started.html +5 -5
- package/site-dist/guide/how-it-works.html +4 -4
- package/site-dist/guide/index.html +4 -4
- package/site-dist/guide/install.html +13 -8
- package/site-dist/guide/intranet.html +5 -5
- package/site-dist/guide/maintainer.html +5 -5
- package/site-dist/guide/mogao.html +39 -0
- package/site-dist/guide/phases.html +4 -4
- package/site-dist/guide/project.html +6 -6
- package/site-dist/guide/user.html +4 -4
- package/site-dist/hashmap.json +1 -1
- package/site-dist/index.html +4 -4
- package/site-dist/reference/adr/0001-new-repo-core-and-adapters.html +4 -4
- package/site-dist/reference/adr/0002-two-orchestration-modes.html +4 -4
- package/site-dist/reference/adr/0003-generate-once-then-lock.html +4 -4
- package/site-dist/reference/adr/0004-external-contracts-stay-stable.html +4 -4
- package/site-dist/reference/adr/0005-skill-names.html +4 -4
- package/site-dist/reference/adr/0006-deterministic-engine-platform-capabilities.html +4 -4
- package/site-dist/reference/adr/0007-one-install-many-repos.html +4 -4
- package/site-dist/reference/adr/0008-capability-sources-and-platform-plugin.html +4 -4
- package/site-dist/reference/adr/index.html +4 -4
- package/site-dist/reference/commands.html +4 -4
- package/site-dist/reference/config.html +4 -4
- package/site-dist/reference/contracts/agent-runtime.html +5 -5
- package/site-dist/reference/contracts/cli-json.html +5 -5
- package/site-dist/reference/contracts/feature-files.html +4 -4
- package/site-dist/reference/contracts/index.html +5 -5
- package/site-dist/reference/contracts/notifier-event.html +6 -6
- package/site-dist/reference/contracts/result-file.html +4 -4
- package/site-dist/reference/contracts/spec.html +4 -4
- package/site-dist/reference/contracts/state.html +5 -5
- package/site-dist/reference/contracts/usage-record.html +6 -6
- package/site-dist/reference/contracts/verify.html +4 -4
- package/site-dist/reference/design/adapter-guide.html +6 -6
- package/site-dist/reference/design/architecture.html +4 -4
- package/site-dist/reference/design/builtin-capabilities.html +4 -4
- package/site-dist/reference/design/cli-adapter.html +42 -0
- package/site-dist/reference/design/platform-vocabulary.html +4 -4
- package/site-dist/reference/scope.html +4 -4
- package/site-dist/assets/changelog.md.Q8QGpuBY.js +0 -1
- package/site-dist/assets/changelog.md.Q8QGpuBY.lean.js +0 -1
- package/site-dist/assets/chunks/@localSearchIndexroot.CQdjFK3w.js +0 -1
- package/site-dist/assets/guide_install.md.D7NiiOPu.js +0 -19
- package/site-dist/assets/guide_install.md.D7NiiOPu.lean.js +0 -19
- package/site-dist/assets/guide_maintainer.md.C-Vt-DdK.js +0 -1
- package/site-dist/assets/guide_maintainer.md.C-Vt-DdK.lean.js +0 -1
- package/site-dist/assets/reference_contracts_agent-runtime.md.TK7Lhwdf.js +0 -1
- package/site-dist/assets/reference_contracts_cli-json.md.Bonk0m6-.js +0 -1
- package/site-dist/assets/reference_contracts_cli-json.md.Bonk0m6-.lean.js +0 -1
- package/site-dist/assets/reference_contracts_state.md.DVHC4opX.js +0 -1
- package/site-dist/assets/reference_contracts_usage-record.md.CQI2chqh.js +0 -10
- package/site-dist/assets/reference_contracts_usage-record.md.CQI2chqh.lean.js +0 -10
- /package/site-dist/assets/{guide_getting-started.md.Bytaz3L8.lean.js → guide_getting-started.md.BxOxfic_.lean.js} +0 -0
- /package/site-dist/assets/{reference_contracts_state.md.DVHC4opX.lean.js → reference_contracts_state.md.DLygjkfs.lean.js} +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,38 @@
|
|
|
2
2
|
|
|
3
3
|
laoshi 的版本号遵循语义化版本,从 0.1.0 开始;每一版的标题写成 `## <版本> - <日期>`。每一版先写使用者会看到的变化,再写升级须知。laoshi 之前的历史见 paseo-req-kit 的更新记录(laoshi 从它的 1.15.0 抽出)。
|
|
4
4
|
|
|
5
|
+
## 0.2.0-beta.3 - 2026-11-11
|
|
6
|
+
|
|
7
|
+
预发布版(npm 的 `beta` 标签,`latest` 仍是 0.1.1):摸高的回调按平台文档的格式解析,步骤做完后靠 `done` 及时进入下一步,工具调用和用量能收到。安装:`npx -y @yiyi_zhang/laoshi@beta install --platform <平台>`。
|
|
8
|
+
|
|
9
|
+
### 使用者会看到的变化
|
|
10
|
+
|
|
11
|
+
- **摸高:回调按平台文档的格式解析**:工具调用(包在 `progress` 事件里)现在收得到,危险命令拦截和"最近活动"在摸高上开始生效;用量从 `usage` 字段读并计入缓存命中;`error` 回调也表示运行结束;上一版启动、这一版接着等的步骤也能靠 `done` 及时结束。
|
|
12
|
+
|
|
13
|
+
### 升级须知
|
|
14
|
+
|
|
15
|
+
- 摸高:专家包要换成这个版本生成的(入口 skill 里写着要装的版本),第一次使用时会装上 0.2.0-beta.3;用 `node -p "require('/data/workspace/.laoshi/npm/node_modules/@yiyi_zhang/laoshi/package.json').version"` 确认。
|
|
16
|
+
|
|
17
|
+
## 0.2.0-beta.2 - 2026-11-10
|
|
18
|
+
|
|
19
|
+
预发布版(npm 的 `beta` 标签,`latest` 仍是 0.1.1):修复摸高上步骤做完要等很久才进入下一步的问题;新增不需要平台的命令行 agent 适配器、`laoshi migrate` 和随 laoshi 发布的 Paseo 需求插件。安装:`npx -y @yiyi_zhang/laoshi@beta install --platform <平台>`。
|
|
20
|
+
|
|
21
|
+
### 使用者会看到的变化
|
|
22
|
+
|
|
23
|
+
- **发起人**:状态文件和 `laoshi api list` 记下每个需求的发起人(`startedBy`,第一次运行时为谁运行,之后不改)。
|
|
24
|
+
- **使用者取平台给的身份**:平台提供使用者时(摸高的 `AIMAX_USER_NAME`)优先用它,`LAOSHI_USER` 仍然最优先;`laoshi doctor` 显示使用者从哪里来。
|
|
25
|
+
- **安装**:程序装在安装根的 `npm` 目录里时(摸高专家就这样安装),不再提示"需要设置环境变量 LAOSHI_HOME"。
|
|
26
|
+
- **命令行 agent(不需要平台)**(`laoshi install --platform cli`):步骤 agent 是 Claude Code(`claude -p`)或 Codex(`codex exec`)的一次运行,追问和打断用会话续接,工具调用来自命令行的事件流(危险命令拦截照常工作);进展用 `laoshi status` 查看。第一版,真实命令行上的验证待做。
|
|
27
|
+
- **摸高:步骤做完后马上进入下一步**:agent 做完但 `aimax run` 进程不退出时,以完整的输出或平台回调的 `done` 为准结束这一步,并结束残留的进程(之前要等到平台结束后台命令、再继续时才进入下一步)。
|
|
28
|
+
- **Paseo 的需求插件随 laoshi 发布**:`laoshi plugin install|status|remove`(从 paseo-req-kit 迁入,插件 id 改为 `laoshi`);安装、升级时顺带更新插件。
|
|
29
|
+
- **`laoshi migrate`**:从 paseo-req-kit 1.x 迁移本机的配置、使用记录、需求索引和需求状态;默认只预览,`--apply` 执行,`--rollback` 回滚;旧目录不动。
|
|
30
|
+
- **文档**:新增《在摸高上使用》《只用命令行 agent》。
|
|
31
|
+
|
|
32
|
+
### 升级须知
|
|
33
|
+
|
|
34
|
+
- 摸高:专家包要按这个版本重新生成(`node adapters/mogao/make-expert.mjs`),入口 skill 第一次使用时会换上这个版本。
|
|
35
|
+
- Paseo:装过 paseo-req-kit 插件的,可以改装 laoshi 插件(`laoshi plugin install`),确认可用后用 `req plugin remove` 移除旧的。
|
|
36
|
+
|
|
5
37
|
## 0.2.0-beta.1 - 2026-11-07
|
|
6
38
|
|
|
7
39
|
预发布版(npm 的 `beta` 标签,`latest` 仍是 0.1.1):支持摸高,用来在摸高沙箱里验证专家。安装:`npx -y @yiyi_zhang/laoshi@beta install --platform <平台>`。
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// The command-line adapter (docs/design/cli-adapter.md, M3): no agent platform, step agents are
|
|
2
|
+
// runs of a coding-agent command line (`claude -p`, `codex exec`). Worktrees and services are
|
|
3
|
+
// laoshi's builtin ones; tool calls come from the command line's JSON events. There is no chat to
|
|
4
|
+
// message and no scheduling: progress goes to the log, messages.log and the external notifiers.
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import type { PlatformAdapter } from "../../engine/src/platform.js";
|
|
8
|
+
import { cliSettings, versionOf } from "./cli-runtime.js";
|
|
9
|
+
import { DRIVERS } from "./drivers.js";
|
|
10
|
+
|
|
11
|
+
export const cliAdapter: PlatformAdapter = {
|
|
12
|
+
id: "cli",
|
|
13
|
+
displayName: "命令行 agent",
|
|
14
|
+
createRuntime: async (input) => (await import("./cli-runtime.js")).createRuntime(input),
|
|
15
|
+
capabilities: {
|
|
16
|
+
services: "builtin",
|
|
17
|
+
worktree: "builtin",
|
|
18
|
+
activity: "platform",
|
|
19
|
+
runningTool: "platform",
|
|
20
|
+
toolCalls: "platform",
|
|
21
|
+
},
|
|
22
|
+
// Command lines give their sessions no identifier: a pipeline started here has no origin chat
|
|
23
|
+
// unless one is passed with --origin-agent or this variable.
|
|
24
|
+
originEnv: { id: "LAOSHI_CLI_ORIGIN" },
|
|
25
|
+
skillSetup: path.join(path.dirname(fileURLToPath(import.meta.url)), "skill", "setup.md"),
|
|
26
|
+
words: {
|
|
27
|
+
name: "命令行 agent",
|
|
28
|
+
chat: "运行 laoshi 的终端或 agent 对话",
|
|
29
|
+
schedule: "定时任务(命令行上没有,到时请再运行继续命令)",
|
|
30
|
+
approvePermission: "命令行的非交互模式不会等待批准;请调整 {agent} 所用角色的 modeId",
|
|
31
|
+
signIn: "在终端里运行它,按提示登录",
|
|
32
|
+
origin: "环境变量 `LAOSHI_CLI_ORIGIN`(命令行 agent 不提供会话标识)",
|
|
33
|
+
connectFix: "确认 `claude --version` 或 `codex --version` 能在终端里运行(不在 PATH 中时在安装级配置的 platform.cli 写上完整路径)。",
|
|
34
|
+
},
|
|
35
|
+
doctorTitle: "命令行 agent(Claude Code、Codex)",
|
|
36
|
+
async doctorPlatform({ config, tools }) {
|
|
37
|
+
const settings = cliSettings(config);
|
|
38
|
+
const agents = (config as { agents?: Record<string, { provider?: string }> }).agents ?? {};
|
|
39
|
+
const used = new Set(Object.values(agents).map((p) => (p?.provider ?? "").split("/")[0]));
|
|
40
|
+
for (const id of Object.keys(DRIVERS)) {
|
|
41
|
+
const version = versionOf(settings.commands[id]);
|
|
42
|
+
const needed = used.has(id);
|
|
43
|
+
if (version) tools.report("ok", `${DRIVERS[id].label}:${settings.commands[id]} ${version}${needed ? "" : "(配置里的角色没有用它)"}`);
|
|
44
|
+
else if (needed) tools.report("fail", `${DRIVERS[id].label}:运行 ${settings.commands[id]} --version 失败`, `安装并登录 ${DRIVERS[id].label};不在 PATH 中时在安装级配置的 platform.cli.${id} 写上它的完整路径`);
|
|
45
|
+
else tools.info(`${DRIVERS[id].label}:没有安装(配置里的角色也没有用它)`);
|
|
46
|
+
}
|
|
47
|
+
for (const p of Object.values(agents)) {
|
|
48
|
+
const id = (p?.provider ?? "").split("/")[0];
|
|
49
|
+
if (p?.provider && !DRIVERS[id]) tools.report("fail", `agent "${p.provider}" 不是命令行适配器支持的命令行`, "provider 写成 claude/<模型> 或 codex/<模型>(default 表示命令行自己的默认模型)");
|
|
50
|
+
}
|
|
51
|
+
tools.info(`单次运行上限 ${settings.runTimeoutMinutes} 分钟;进展写在 <安装根>/cli/messages.log,用 laoshi status 查看`);
|
|
52
|
+
},
|
|
53
|
+
};
|
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
// The engine's runtime for coding-agent command lines (docs/design/cli-adapter.md, M3). Each step
|
|
2
|
+
// agent is a run of `claude -p` or `codex exec` (drivers.ts) in the step's directory, the prompt on
|
|
3
|
+
// standard input, JSON events on standard output; follow-ups and interrupts continue the session.
|
|
4
|
+
// There is no platform: no chat to message, no approvals, no schedules. Worktrees and services are
|
|
5
|
+
// laoshi's builtin ones; notifications go to the log, <install root>/cli/messages.log and the
|
|
6
|
+
// external notifiers.
|
|
7
|
+
//
|
|
8
|
+
// Every agent's state is on disk (<install root>/cli/agents/<id>/), so another engine process can
|
|
9
|
+
// pick it up; a run cut off without a result (the engine or the machine went away) is continued
|
|
10
|
+
// in its session instead of being done again.
|
|
11
|
+
import { type ChildProcess, spawn, spawnSync } from "node:child_process";
|
|
12
|
+
import crypto from "node:crypto";
|
|
13
|
+
import fs from "node:fs";
|
|
14
|
+
import os from "node:os";
|
|
15
|
+
import path from "node:path";
|
|
16
|
+
import type { AgentProfile } from "../../engine/src/config.js";
|
|
17
|
+
import type { ToolCall } from "../../engine/src/danger-guard.js";
|
|
18
|
+
import { homeOf } from "../../engine/src/locations.js";
|
|
19
|
+
import type { AgentRuntime, RuntimeFactory, StepAgent, WaitOutcome } from "../../engine/src/runtime.js";
|
|
20
|
+
import type { RunningTool } from "../../engine/src/scan-guard.js";
|
|
21
|
+
import { isAlive } from "../../engine/src/state.js";
|
|
22
|
+
import type { AgentUsage } from "../../engine/src/usage.js";
|
|
23
|
+
import { type Driver, DRIVERS, driverOf, type LineEvent } from "./drivers.js";
|
|
24
|
+
|
|
25
|
+
/** Settings from the install-level config's platform.cli. */
|
|
26
|
+
export interface CliSettings {
|
|
27
|
+
/** Command of each command line ("claude", "codex"); LAOSHI_CLI_CLAUDE / LAOSHI_CLI_CODEX override them (tests). */
|
|
28
|
+
commands: Record<string, string>;
|
|
29
|
+
/** Hard limit of one run, in minutes (the engine keeps its own step limits). */
|
|
30
|
+
runTimeoutMinutes: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function cliSettings(config: unknown, env: NodeJS.ProcessEnv = process.env): CliSettings {
|
|
34
|
+
const raw = ((config as { platform?: { cli?: Record<string, unknown> } } | null)?.platform?.cli ?? {}) as Record<string, unknown>;
|
|
35
|
+
const text = (v: unknown) => (typeof v === "string" && v.trim() ? v.trim() : null);
|
|
36
|
+
const commands: Record<string, string> = {};
|
|
37
|
+
for (const id of Object.keys(DRIVERS)) commands[id] = text(env[`LAOSHI_CLI_${id.toUpperCase()}`]) ?? text(raw[id]) ?? id;
|
|
38
|
+
const minutes = typeof raw.runTimeoutMinutes === "number" && raw.runTimeoutMinutes > 0 ? raw.runTimeoutMinutes : 120;
|
|
39
|
+
return { commands, runTimeoutMinutes: minutes };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Credentials and tokens are never written to laoshi's files. */
|
|
43
|
+
export function redact(text: string): string {
|
|
44
|
+
return text
|
|
45
|
+
.replace(/(authorization["']?\s*[:=]\s*["']?(?:bearer\s+)?)[^\s"',}]+/gi, "$1***")
|
|
46
|
+
.replace(/\b(bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi, "$1***")
|
|
47
|
+
.replace(/((?:token|secret|password|api[_-]?key|credential)[A-Za-z_]*["']?\s*[:=]\s*["']?)[^\s"',}]{4,}/gi, "$1***")
|
|
48
|
+
.replace(/\bsk-[A-Za-z0-9_-]{16,}/g, "sk-***");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** What laoshi keeps about one step agent between engine processes. */
|
|
52
|
+
interface AgentRecord {
|
|
53
|
+
id: string;
|
|
54
|
+
cwd: string;
|
|
55
|
+
title: string;
|
|
56
|
+
driver: string;
|
|
57
|
+
model: string | null;
|
|
58
|
+
modeId: string | null;
|
|
59
|
+
sessionId: string | null;
|
|
60
|
+
/** Number of runs so far (run-<n>.* are the latest's files). */
|
|
61
|
+
runs: number;
|
|
62
|
+
/** The latest run's process and the machine it ran on. */
|
|
63
|
+
pid: number | null;
|
|
64
|
+
host: string | null;
|
|
65
|
+
/** Times a cut-off run was continued in its session. */
|
|
66
|
+
continued: number;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The latest run's outcome, read from its output. */
|
|
70
|
+
interface RunOutcome {
|
|
71
|
+
sessionId: string | null;
|
|
72
|
+
final: LineEvent["final"] | null;
|
|
73
|
+
text: string | null;
|
|
74
|
+
usage: AgentUsage | null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const CONTINUE_MESSAGE = "上一次运行被中断了(进程意外结束)。请接着完成原来的任务:先看一下已经做了什么,不要重复已经完成的部分。";
|
|
78
|
+
const MAX_CONTINUES = 2;
|
|
79
|
+
|
|
80
|
+
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
81
|
+
|
|
82
|
+
/** Stops a run with what it started (on Windows the command line runs under cmd.exe: stop the tree). */
|
|
83
|
+
function stop(pid: number | undefined): void {
|
|
84
|
+
if (!pid) return;
|
|
85
|
+
if (process.platform === "win32") {
|
|
86
|
+
spawnSync("taskkill", ["/pid", String(pid), "/T", "/F"], { windowsHide: true });
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
try {
|
|
90
|
+
process.kill(pid, "SIGTERM");
|
|
91
|
+
} catch {
|
|
92
|
+
// Already gone.
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Each line of a run's standard output as an object; lines that are not JSON are skipped. */
|
|
97
|
+
function lines(text: string): Array<Record<string, unknown>> {
|
|
98
|
+
const out: Array<Record<string, unknown>> = [];
|
|
99
|
+
for (const line of text.split("\n")) {
|
|
100
|
+
const t = line.trim();
|
|
101
|
+
if (!t.startsWith("{")) continue;
|
|
102
|
+
try {
|
|
103
|
+
out.push(JSON.parse(t) as Record<string, unknown>);
|
|
104
|
+
} catch {
|
|
105
|
+
// Not a whole JSON line.
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function outcomeOf(driver: Driver, stdout: string): RunOutcome {
|
|
112
|
+
const outcome: RunOutcome = { sessionId: null, final: null, text: null, usage: null };
|
|
113
|
+
for (const value of lines(stdout)) {
|
|
114
|
+
const e = driver.line(value);
|
|
115
|
+
if (e.sessionId) outcome.sessionId = e.sessionId;
|
|
116
|
+
if (e.text) outcome.text = e.text;
|
|
117
|
+
if (e.usage) outcome.usage = e.usage;
|
|
118
|
+
if (e.final) outcome.final = e.final;
|
|
119
|
+
}
|
|
120
|
+
return outcome;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export interface CliRuntimeOptions {
|
|
124
|
+
settings: CliSettings;
|
|
125
|
+
/** The roles' agent settings, for a step started without its own. */
|
|
126
|
+
agents: Partial<Record<"builder" | "reviewer", AgentProfile>>;
|
|
127
|
+
/** Where agents' records live: <install root>/cli/agents. */
|
|
128
|
+
agentsDir: string;
|
|
129
|
+
/** Where messages for people go: <install root>/cli/messages.log. */
|
|
130
|
+
messagesFile: string;
|
|
131
|
+
log: (message: string) => void;
|
|
132
|
+
env?: NodeJS.ProcessEnv;
|
|
133
|
+
pollMs?: number;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function createCliRuntime(options: CliRuntimeOptions): AgentRuntime {
|
|
137
|
+
const { settings, agentsDir, log } = options;
|
|
138
|
+
const env = options.env ?? process.env;
|
|
139
|
+
const pollMs = options.pollMs ?? 500;
|
|
140
|
+
const children = new Map<string, ChildProcess>();
|
|
141
|
+
const dir = (id: string) => path.join(agentsDir, id);
|
|
142
|
+
const file = (id: string, name: string) => path.join(dir(id), name);
|
|
143
|
+
const read = (id: string): AgentRecord | null => {
|
|
144
|
+
try {
|
|
145
|
+
return JSON.parse(fs.readFileSync(file(id, "agent.json"), "utf8")) as AgentRecord;
|
|
146
|
+
} catch {
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
const write = (record: AgentRecord) => {
|
|
151
|
+
fs.mkdirSync(dir(record.id), { recursive: true });
|
|
152
|
+
fs.writeFileSync(file(record.id, "agent.json"), `${JSON.stringify(record, null, 2)}\n`);
|
|
153
|
+
};
|
|
154
|
+
const readText = (p: string) => {
|
|
155
|
+
try {
|
|
156
|
+
return fs.readFileSync(p, "utf8");
|
|
157
|
+
} catch {
|
|
158
|
+
return "";
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
/** Tool calls as they happen, with the time laoshi saw them (redacted). */
|
|
163
|
+
const recordTool = (id: string, e: LineEvent, seen: Set<string>) => {
|
|
164
|
+
const at = new Date().toISOString();
|
|
165
|
+
const events = file(id, "events.jsonl");
|
|
166
|
+
if (e.toolStart && !seen.has(`s:${e.toolStart.callId}`)) {
|
|
167
|
+
seen.add(`s:${e.toolStart.callId}`);
|
|
168
|
+
fs.appendFileSync(events, `${JSON.stringify({ at, type: "tool_start", callId: e.toolStart.callId, kind: e.toolStart.kind, text: redact(e.toolStart.text).slice(0, 2000) })}\n`);
|
|
169
|
+
}
|
|
170
|
+
if (e.toolEnd && !seen.has(`e:${e.toolEnd.callId}`)) {
|
|
171
|
+
seen.add(`e:${e.toolEnd.callId}`);
|
|
172
|
+
fs.appendFileSync(events, `${JSON.stringify({ at, type: "tool_end", callId: e.toolEnd.callId, exitCode: e.toolEnd.exitCode })}\n`);
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
/** Starts one run of the agent's command line: a new session, or a continuation of its session. */
|
|
177
|
+
function launch(record: AgentRecord, message: string): void {
|
|
178
|
+
const driver = DRIVERS[record.driver];
|
|
179
|
+
const n = record.runs + 1;
|
|
180
|
+
const out = file(record.id, `run-${n}.out`);
|
|
181
|
+
const err = file(record.id, `run-${n}.err`);
|
|
182
|
+
fs.writeFileSync(out, "");
|
|
183
|
+
fs.writeFileSync(err, "");
|
|
184
|
+
const args = driver.args({ cwd: record.cwd, model: record.model, modeId: record.modeId, sessionId: record.sessionId });
|
|
185
|
+
const child = spawn(settings.commands[record.driver], args, { cwd: record.cwd, env, stdio: ["pipe", "pipe", "pipe"], windowsHide: true, shell: process.platform === "win32" });
|
|
186
|
+
children.set(record.id, child);
|
|
187
|
+
write({ ...record, runs: n, pid: child.pid ?? null, host: os.hostname() });
|
|
188
|
+
const seen = new Set<string>();
|
|
189
|
+
let pending = "";
|
|
190
|
+
child.stdout!.setEncoding("utf8").on("data", (chunk: string) => {
|
|
191
|
+
fs.appendFileSync(out, chunk);
|
|
192
|
+
pending += chunk;
|
|
193
|
+
const parts = pending.split("\n");
|
|
194
|
+
pending = parts.pop() ?? "";
|
|
195
|
+
for (const value of lines(parts.join("\n"))) {
|
|
196
|
+
const e = driver.line(value);
|
|
197
|
+
if (e.sessionId) {
|
|
198
|
+
const now = read(record.id);
|
|
199
|
+
if (now && now.sessionId !== e.sessionId) write({ ...now, sessionId: e.sessionId });
|
|
200
|
+
}
|
|
201
|
+
recordTool(record.id, e, seen);
|
|
202
|
+
}
|
|
203
|
+
});
|
|
204
|
+
child.stderr!.setEncoding("utf8").on("data", (chunk: string) => fs.appendFileSync(err, chunk));
|
|
205
|
+
const limit = setTimeout(() => {
|
|
206
|
+
fs.writeFileSync(file(record.id, `run-${n}.timeout`), new Date().toISOString());
|
|
207
|
+
stop(child.pid);
|
|
208
|
+
}, settings.runTimeoutMinutes * 60_000);
|
|
209
|
+
limit.unref();
|
|
210
|
+
child.on("exit", (code, signal) => {
|
|
211
|
+
clearTimeout(limit);
|
|
212
|
+
fs.writeFileSync(file(record.id, `run-${n}.exit`), JSON.stringify({ code, signal }));
|
|
213
|
+
children.delete(record.id);
|
|
214
|
+
});
|
|
215
|
+
child.on("error", (e) => {
|
|
216
|
+
clearTimeout(limit);
|
|
217
|
+
fs.appendFileSync(err, `\n${e.message}\n`);
|
|
218
|
+
fs.writeFileSync(file(record.id, `run-${n}.exit`), JSON.stringify({ code: null, signal: null, error: e.message }));
|
|
219
|
+
children.delete(record.id);
|
|
220
|
+
});
|
|
221
|
+
child.stdin!.on("error", () => undefined);
|
|
222
|
+
child.stdin!.end(message);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const running = (record: AgentRecord) =>
|
|
226
|
+
children.has(record.id) || (!!record.pid && record.host === os.hostname() && !fs.existsSync(file(record.id, `run-${record.runs}.exit`)) && isAlive(record.pid));
|
|
227
|
+
|
|
228
|
+
const stepAgent = (id: string): StepAgent => ({
|
|
229
|
+
id,
|
|
230
|
+
async wait(timeoutMs: number): Promise<WaitOutcome> {
|
|
231
|
+
const deadline = Date.now() + timeoutMs;
|
|
232
|
+
const base = { error: null, lastMessage: null, pendingPermissions: [] };
|
|
233
|
+
for (;;) {
|
|
234
|
+
const record = read(id);
|
|
235
|
+
if (!record) return { ...base, status: "error", error: `找不到 laoshi 记录的 agent ${id}` };
|
|
236
|
+
if (!running(record)) {
|
|
237
|
+
const driver = DRIVERS[record.driver];
|
|
238
|
+
const done = outcomeOf(driver, readText(file(id, `run-${record.runs}.out`)));
|
|
239
|
+
if (done.sessionId && done.sessionId !== record.sessionId) write({ ...record, sessionId: done.sessionId });
|
|
240
|
+
if (done.final?.ok) return { ...base, status: "idle", usage: done.usage, lastMessage: done.final.text ?? done.text };
|
|
241
|
+
if (fs.existsSync(file(id, `run-${record.runs}.timeout`))) {
|
|
242
|
+
return { ...base, status: "error", usage: done.usage, error: `超过 ${settings.runTimeoutMinutes} 分钟(单次运行的上限),运行已停止` };
|
|
243
|
+
}
|
|
244
|
+
if (done.final) return { ...base, status: "error", usage: done.usage, error: redact(done.final.error ?? "运行出错") };
|
|
245
|
+
const exit = readText(file(id, `run-${record.runs}.exit`));
|
|
246
|
+
const sessionId = done.sessionId ?? record.sessionId;
|
|
247
|
+
// No result and no exit record: the run was cut off with the process that watched it.
|
|
248
|
+
if (!exit && sessionId && record.continued < MAX_CONTINUES) {
|
|
249
|
+
log(`agent ${id} 的上一次运行被中断(没有结果),接着它的会话 ${sessionId} 继续`);
|
|
250
|
+
const next = { ...(read(id) ?? record), sessionId, continued: record.continued + 1 };
|
|
251
|
+
write(next);
|
|
252
|
+
launch(next, CONTINUE_MESSAGE);
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
const stderr = redact(readText(file(id, `run-${record.runs}.err`)).trim()).split("\n").slice(-3).join(" ");
|
|
256
|
+
const how = exit ? (JSON.parse(exit) as { code: number | null; error?: string }) : null;
|
|
257
|
+
return { ...base, status: "error", usage: done.usage, error: `${driver.label} 没有给出结果${how?.error ? `(${how.error})` : how?.code != null ? `(退出码 ${how.code})` : ""}${stderr ? `:${stderr}` : ""}` };
|
|
258
|
+
}
|
|
259
|
+
if (Date.now() >= deadline) return { ...base, status: "timeout", usage: outcomeOf(DRIVERS[record.driver], readText(file(id, `run-${record.runs}.out`))).usage };
|
|
260
|
+
await sleep(Math.min(pollMs, Math.max(0, deadline - Date.now())));
|
|
261
|
+
}
|
|
262
|
+
},
|
|
263
|
+
async followUp(text: string): Promise<void> {
|
|
264
|
+
const record = read(id);
|
|
265
|
+
if (!record?.sessionId) throw new Error(`agent ${id} 还没有会话,不能追问`);
|
|
266
|
+
launch(record, text);
|
|
267
|
+
},
|
|
268
|
+
async archive(): Promise<void> {
|
|
269
|
+
// The command lines keep their own sessions; nothing to archive.
|
|
270
|
+
},
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
const events = (id: string): Array<Record<string, unknown>> => lines(readText(file(id, "events.jsonl")));
|
|
274
|
+
|
|
275
|
+
const toolCalls = async (id: string): Promise<ToolCall[] | null> => {
|
|
276
|
+
if (!read(id)) return null;
|
|
277
|
+
const calls = new Map<string, ToolCall>();
|
|
278
|
+
for (const e of events(id)) {
|
|
279
|
+
const callId = String(e.callId ?? "");
|
|
280
|
+
if (!callId) continue;
|
|
281
|
+
if (e.type === "tool_start") calls.set(callId, { callId, kind: String(e.kind ?? "tool"), text: String(e.text ?? ""), status: "running", startedAt: String(e.at) });
|
|
282
|
+
else if (e.type === "tool_end" && calls.has(callId)) calls.get(callId)!.status = "completed";
|
|
283
|
+
}
|
|
284
|
+
return [...calls.values()];
|
|
285
|
+
};
|
|
286
|
+
|
|
287
|
+
const message = (text: string) => {
|
|
288
|
+
log(`消息:${text.split("\n")[0]}`);
|
|
289
|
+
fs.mkdirSync(path.dirname(options.messagesFile), { recursive: true });
|
|
290
|
+
fs.appendFileSync(options.messagesFile, `[${new Date().toISOString()}]\n${text}\n\n`);
|
|
291
|
+
const chatOut = env.LAOSHI_CHAT_OUT?.trim();
|
|
292
|
+
if (chatOut) fs.appendFileSync(chatOut, `${text}\n\n`);
|
|
293
|
+
};
|
|
294
|
+
|
|
295
|
+
return {
|
|
296
|
+
async verifyOrigin() {
|
|
297
|
+
// No platform chat to check: the pipeline runs on its own and reports to the log.
|
|
298
|
+
},
|
|
299
|
+
|
|
300
|
+
async startAgent(input) {
|
|
301
|
+
const profile = input.profile ?? options.agents[input.role];
|
|
302
|
+
const { driver, model } = driverOf(profile?.provider);
|
|
303
|
+
const record: AgentRecord = {
|
|
304
|
+
id: `cli-${crypto.randomBytes(6).toString("hex")}`,
|
|
305
|
+
cwd: input.cwd,
|
|
306
|
+
title: input.title,
|
|
307
|
+
driver: driver.id,
|
|
308
|
+
model,
|
|
309
|
+
modeId: profile?.modeId ?? null,
|
|
310
|
+
sessionId: null,
|
|
311
|
+
runs: 0,
|
|
312
|
+
pid: null,
|
|
313
|
+
host: null,
|
|
314
|
+
continued: 0,
|
|
315
|
+
};
|
|
316
|
+
write(record);
|
|
317
|
+
fs.writeFileSync(file(record.id, "prompt.md"), input.prompt);
|
|
318
|
+
launch(record, input.prompt);
|
|
319
|
+
return stepAgent(record.id);
|
|
320
|
+
},
|
|
321
|
+
|
|
322
|
+
attachAgent: (agentId) => stepAgent(agentId),
|
|
323
|
+
|
|
324
|
+
async startSessionAgent() {
|
|
325
|
+
throw new Error("命令行适配器不能为需求新开对话");
|
|
326
|
+
},
|
|
327
|
+
|
|
328
|
+
async notifyAgent(_agentId, text) {
|
|
329
|
+
message(text);
|
|
330
|
+
},
|
|
331
|
+
|
|
332
|
+
async interruptAgent(agentId, text) {
|
|
333
|
+
const child = children.get(agentId);
|
|
334
|
+
const record = read(agentId);
|
|
335
|
+
if (child) {
|
|
336
|
+
const exited = new Promise((r) => child.once("exit", r));
|
|
337
|
+
stop(child.pid);
|
|
338
|
+
await exited;
|
|
339
|
+
} else if (record?.pid && record.host === os.hostname() && isAlive(record.pid)) {
|
|
340
|
+
stop(record.pid);
|
|
341
|
+
for (let i = 0; i < 50 && isAlive(record.pid); i++) await sleep(100);
|
|
342
|
+
}
|
|
343
|
+
const now = read(agentId);
|
|
344
|
+
if (now?.sessionId) launch(now, text);
|
|
345
|
+
},
|
|
346
|
+
|
|
347
|
+
agentDirectory: async (agentId) => read(agentId)?.cwd ?? null,
|
|
348
|
+
listProfiles: async () => null,
|
|
349
|
+
listServices: async () => null,
|
|
350
|
+
startServices: async () => {
|
|
351
|
+
throw new Error("命令行适配器不管理服务");
|
|
352
|
+
},
|
|
353
|
+
stopServices: async () => undefined,
|
|
354
|
+
createWorktree: async () => {
|
|
355
|
+
throw new Error("命令行适配器不提供工作区");
|
|
356
|
+
},
|
|
357
|
+
waitForWorkspaceSetup: async () => ({ status: "none", error: null }),
|
|
358
|
+
providerQuota: async () => null,
|
|
359
|
+
|
|
360
|
+
async recentActivity(agentId, limit) {
|
|
361
|
+
const calls = await toolCalls(agentId);
|
|
362
|
+
return calls ? calls.slice(-limit).map((c) => ({ at: c.startedAt, text: c.kind === "shell" ? `运行命令:${c.text}` : `${c.kind}:${c.text}` })) : null;
|
|
363
|
+
},
|
|
364
|
+
|
|
365
|
+
async runningTool(agentId): Promise<RunningTool | null> {
|
|
366
|
+
const current = (await toolCalls(agentId))?.filter((c) => c.status === "running").at(-1);
|
|
367
|
+
return current ? { kind: current.kind, text: current.text, startedAt: current.startedAt, callId: current.callId } : null;
|
|
368
|
+
},
|
|
369
|
+
|
|
370
|
+
toolCalls,
|
|
371
|
+
capabilities: async () => null,
|
|
372
|
+
|
|
373
|
+
async providerStatus() {
|
|
374
|
+
const used = new Set(Object.values(options.agents).map((p) => (p?.provider ?? "").split("/")[0]).filter((id) => DRIVERS[id]));
|
|
375
|
+
return [...used].map((id) => ({ provider: id, status: versionOf(settings.commands[id], env) ? "ready" : "missing" }));
|
|
376
|
+
},
|
|
377
|
+
|
|
378
|
+
scheduleMessage: async () => null,
|
|
379
|
+
scheduleNewAgent: async () => null,
|
|
380
|
+
cancelSchedule: async () => undefined,
|
|
381
|
+
|
|
382
|
+
async close() {
|
|
383
|
+
for (const child of children.values()) stop(child.pid);
|
|
384
|
+
},
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** `<command> --version`, or null when it does not run. */
|
|
389
|
+
export function versionOf(command: string, env: NodeJS.ProcessEnv = process.env): string | null {
|
|
390
|
+
const r = spawnSync(command, ["--version"], { encoding: "utf8", timeout: 20_000, env, windowsHide: true, shell: process.platform === "win32" });
|
|
391
|
+
if (r.error || r.status !== 0) return null;
|
|
392
|
+
return (r.stdout || r.stderr || "").trim().split("\n")[0] || "?";
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
export const createRuntime: RuntimeFactory = async ({ config, log }) =>
|
|
396
|
+
createCliRuntime({
|
|
397
|
+
settings: cliSettings(config),
|
|
398
|
+
agents: config.agents,
|
|
399
|
+
agentsDir: path.join(homeOf().dir, "cli", "agents"),
|
|
400
|
+
messagesFile: path.join(homeOf().dir, "cli", "messages.log"),
|
|
401
|
+
log,
|
|
402
|
+
});
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// The coding-agent command lines the cli adapter runs (docs/design/cli-adapter.md): how to start and
|
|
2
|
+
// continue a run, and how to read the JSON events each prints on standard output (one per line).
|
|
3
|
+
import type { AgentUsage } from "../../engine/src/usage.js";
|
|
4
|
+
|
|
5
|
+
/** What one line of a run's output says, as far as laoshi reads it. */
|
|
6
|
+
export interface LineEvent {
|
|
7
|
+
sessionId?: string;
|
|
8
|
+
toolStart?: { callId: string; kind: string; text: string };
|
|
9
|
+
toolEnd?: { callId: string; exitCode: number | null };
|
|
10
|
+
/** An assistant message (the last one is the run's reply). */
|
|
11
|
+
text?: string;
|
|
12
|
+
usage?: AgentUsage;
|
|
13
|
+
/** The run ended: ok, with the reply or the error. */
|
|
14
|
+
final?: { ok: boolean; text: string | null; error: string | null };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface RunRequest {
|
|
18
|
+
cwd: string;
|
|
19
|
+
/** null: the command line's default model. */
|
|
20
|
+
model: string | null;
|
|
21
|
+
modeId: string | null;
|
|
22
|
+
/** Continue this session (follow-up, interrupt, a cut-off run); null for a new one. */
|
|
23
|
+
sessionId: string | null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface Driver {
|
|
27
|
+
id: "claude" | "codex";
|
|
28
|
+
/** For people, e.g. in doctor. */
|
|
29
|
+
label: string;
|
|
30
|
+
/** Arguments; the prompt goes to standard input. */
|
|
31
|
+
args(request: RunRequest): string[];
|
|
32
|
+
/** One line of standard output. */
|
|
33
|
+
line(value: Record<string, unknown>): LineEvent;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const str = (v: unknown): string | null => (typeof v === "string" ? v : null);
|
|
37
|
+
const num = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) ? v : 0);
|
|
38
|
+
|
|
39
|
+
/** A tool call in one line, e.g. a shell command or the file a tool reads. */
|
|
40
|
+
function toolText(name: string, input: Record<string, unknown>): string {
|
|
41
|
+
for (const key of ["command", "file_path", "path", "pattern", "url", "query"]) {
|
|
42
|
+
const v = str(input[key]);
|
|
43
|
+
if (v) return v;
|
|
44
|
+
}
|
|
45
|
+
const json = JSON.stringify(input);
|
|
46
|
+
return `${name} ${json.length > 200 ? `${json.slice(0, 200)}…` : json}`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Claude Code: `claude -p --output-format stream-json --verbose`. */
|
|
50
|
+
export const claudeDriver: Driver = {
|
|
51
|
+
id: "claude",
|
|
52
|
+
label: "Claude Code",
|
|
53
|
+
args({ model, modeId, sessionId }) {
|
|
54
|
+
return [
|
|
55
|
+
"-p",
|
|
56
|
+
"--output-format",
|
|
57
|
+
"stream-json",
|
|
58
|
+
"--verbose",
|
|
59
|
+
"--permission-mode",
|
|
60
|
+
modeId ?? "bypassPermissions",
|
|
61
|
+
...(model ? ["--model", model] : []),
|
|
62
|
+
...(sessionId ? ["--resume", sessionId] : []),
|
|
63
|
+
];
|
|
64
|
+
},
|
|
65
|
+
line(v) {
|
|
66
|
+
const event: LineEvent = {};
|
|
67
|
+
const session = str(v.session_id);
|
|
68
|
+
if (session) event.sessionId = session;
|
|
69
|
+
const content = ((v.message as { content?: unknown } | undefined)?.content ?? []) as Array<Record<string, unknown>>;
|
|
70
|
+
if (v.type === "assistant" && Array.isArray(content)) {
|
|
71
|
+
for (const part of content) {
|
|
72
|
+
if (part.type === "tool_use") {
|
|
73
|
+
const name = str(part.name) ?? "tool";
|
|
74
|
+
event.toolStart = { callId: str(part.id) ?? "", kind: name === "Bash" ? "shell" : name.toLowerCase(), text: toolText(name, (part.input ?? {}) as Record<string, unknown>) };
|
|
75
|
+
} else if (part.type === "text" && str(part.text)) {
|
|
76
|
+
event.text = str(part.text)!;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
} else if (v.type === "user" && Array.isArray(content)) {
|
|
80
|
+
for (const part of content) {
|
|
81
|
+
if (part.type === "tool_result") event.toolEnd = { callId: str(part.tool_use_id) ?? "", exitCode: part.is_error ? 1 : 0 };
|
|
82
|
+
}
|
|
83
|
+
} else if (v.type === "result") {
|
|
84
|
+
const u = (v.usage ?? {}) as Record<string, unknown>;
|
|
85
|
+
event.usage = { inputTokens: num(u.input_tokens) + num(u.cache_read_input_tokens) + num(u.cache_creation_input_tokens), cachedInputTokens: num(u.cache_read_input_tokens), outputTokens: num(u.output_tokens), ...(typeof v.total_cost_usd === "number" ? { totalCostUsd: v.total_cost_usd } : {}) };
|
|
86
|
+
const ok = v.is_error !== true && (v.subtype === undefined || v.subtype === "success");
|
|
87
|
+
event.final = { ok, text: str(v.result), error: ok ? null : (str(v.result) ?? str(v.subtype) ?? "运行出错") };
|
|
88
|
+
}
|
|
89
|
+
return event;
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
/** Codex: `codex exec --json`, continued with `codex exec … resume <thread>`. */
|
|
94
|
+
export const codexDriver: Driver = {
|
|
95
|
+
id: "codex",
|
|
96
|
+
label: "Codex",
|
|
97
|
+
args({ cwd, model, modeId, sessionId }) {
|
|
98
|
+
const mode = modeId ?? "full-access";
|
|
99
|
+
const permissions =
|
|
100
|
+
mode === "full-access" ? ["--dangerously-bypass-approvals-and-sandbox"] : mode === "read-only" ? ["--sandbox", "read-only"] : ["--full-auto"];
|
|
101
|
+
return [
|
|
102
|
+
"exec",
|
|
103
|
+
"--json",
|
|
104
|
+
"--skip-git-repo-check",
|
|
105
|
+
...permissions,
|
|
106
|
+
...(model ? ["--model", model] : []),
|
|
107
|
+
...(sessionId ? ["resume", sessionId, "-"] : ["--cd", cwd, "-"]),
|
|
108
|
+
];
|
|
109
|
+
},
|
|
110
|
+
line(v) {
|
|
111
|
+
const event: LineEvent = {};
|
|
112
|
+
if (v.type === "thread.started" && str(v.thread_id)) event.sessionId = str(v.thread_id)!;
|
|
113
|
+
const item = (v.item ?? {}) as Record<string, unknown>;
|
|
114
|
+
if (item.type === "command_execution") {
|
|
115
|
+
const callId = str(item.id) ?? "";
|
|
116
|
+
if (v.type === "item.started") event.toolStart = { callId, kind: "shell", text: str(item.command) ?? "" };
|
|
117
|
+
else if (v.type === "item.completed") {
|
|
118
|
+
event.toolStart = { callId, kind: "shell", text: str(item.command) ?? "" };
|
|
119
|
+
event.toolEnd = { callId, exitCode: typeof item.exit_code === "number" ? item.exit_code : null };
|
|
120
|
+
}
|
|
121
|
+
} else if (item.type === "agent_message" && v.type === "item.completed" && str(item.text)) {
|
|
122
|
+
event.text = str(item.text)!;
|
|
123
|
+
}
|
|
124
|
+
if (v.type === "turn.completed") {
|
|
125
|
+
const u = (v.usage ?? {}) as Record<string, unknown>;
|
|
126
|
+
event.usage = { inputTokens: num(u.input_tokens), cachedInputTokens: num(u.cached_input_tokens), outputTokens: num(u.output_tokens) };
|
|
127
|
+
event.final = { ok: true, text: null, error: null };
|
|
128
|
+
} else if (v.type === "turn.failed") {
|
|
129
|
+
event.final = { ok: false, text: null, error: str((v.error as { message?: unknown } | undefined)?.message) ?? "运行失败" };
|
|
130
|
+
} else if (v.type === "error") {
|
|
131
|
+
event.final = { ok: false, text: null, error: str(v.message) ?? "运行出错" };
|
|
132
|
+
}
|
|
133
|
+
return event;
|
|
134
|
+
},
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
export const DRIVERS: Record<string, Driver> = { claude: claudeDriver, codex: codexDriver };
|
|
138
|
+
|
|
139
|
+
/** "claude/opus" → the Claude driver and model "opus"; "default" (or none) → the command line's own default. */
|
|
140
|
+
export function driverOf(provider: string | undefined): { driver: Driver; model: string | null } {
|
|
141
|
+
const [id, ...rest] = (provider ?? "").split("/");
|
|
142
|
+
const driver = DRIVERS[id];
|
|
143
|
+
if (!driver) throw new Error(`命令行适配器不认识 agent "${provider ?? ""}":provider 写成 claude/<模型> 或 codex/<模型>(模型写 default 表示用命令行自己的默认模型)`);
|
|
144
|
+
const model = rest.join("/").trim();
|
|
145
|
+
return { driver, model: model && model !== "default" ? model : null };
|
|
146
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// laoshi installer, command-line part (bin/install.mjs): no platform; the skills go where the
|
|
2
|
+
// interactive command lines read them (as for Paseo), and the roles use `claude` and `codex`.
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
|
|
7
|
+
export const id = "cli";
|
|
8
|
+
export const options = {};
|
|
9
|
+
|
|
10
|
+
export function platformConfig() {
|
|
11
|
+
return { adapter: "cli" };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const defaultAgents = { builder: { provider: "claude/default", modeId: "bypassPermissions" }, reviewer: { provider: "codex/default", modeId: "full-access" } };
|
|
15
|
+
|
|
16
|
+
export function skillTargets() {
|
|
17
|
+
const home = os.homedir();
|
|
18
|
+
const roots = [{ dir: path.join(home, ".agents", "skills"), label: "通用目录 ~/.agents/skills(Codex 等)" }];
|
|
19
|
+
if (fs.existsSync(path.join(home, ".claude"))) roots.push({ dir: path.join(home, ".claude", "skills"), label: "Claude Code ~/.claude/skills" });
|
|
20
|
+
return roots;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function setup({ report }) {
|
|
24
|
+
report("info", "步骤 agent 是 claude -p / codex exec 的一次运行;角色默认 builder 用 Claude Code、reviewer 用 Codex(只装了一种时,在安装级配置里把两个角色都改成它)");
|
|
25
|
+
return ["在终端运行 laoshi doctor --no-project,确认 claude、codex 能运行并已登录"];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function uninstall() {}
|