deepccc 0.1.2 → 0.1.4

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/README.md CHANGED
@@ -132,6 +132,61 @@ deepccc --effort high
132
132
 
133
133
  可选值:`none` / `minimal` / `low` / `medium` / `high` / `xhigh` / `max`(留空则不传 `reasoning_effort` 请求字段)。
134
134
 
135
+ ## 权限机制
136
+
137
+ `deepccc` 内置轻量权限机制,对标主流 agent 的审批体验:**只拦截有副作用的操作**(`run_command` 与文件写操作),只读工具(`read_file` / `list_dir` / `search_code`)永不拦截,常规文件编辑默认放行不打断工作流。
138
+
139
+ 默认模式(`ask`)下,只有**命中内置危险命令库**的高危命令才会询问,例如:
140
+
141
+ - `rm -rf` / `rm -fr` / `del /s` / `rmdir /s` 等强制删除
142
+ - `git push --force` / `git reset --hard` / `git clean -f` 等破坏性 git 操作
143
+ - `format` / `diskpart` / `mkfs` / `dd of=设备` 等磁盘操作
144
+ - `shutdown` / `reboot` 等系统操作
145
+ - `drop table` / `truncate table` 等数据库操作
146
+ - `npm publish` / `npm uninstall -g` / `pip uninstall` 等发布与全局卸载
147
+
148
+ 交互模式下,高危命令会暂停并询问:
149
+
150
+ ```text
151
+ ⚠️ 高危操作需要确认
152
+ 运行命令: rm -rf node_modules
153
+ 允许一次(y) / 永远允许(a) / 拒绝(n) / 本会话允许所有(g) >
154
+ ```
155
+
156
+ - `y` — 允许本次
157
+ - `a` — 永远允许,写入 `~/.deepccc/allow.json`
158
+ - `n` — 拒绝本次
159
+ - `g` — 本会话内全部放行(不落盘)
160
+
161
+ ### 规则文件 `~/.deepccc/allow.json`
162
+
163
+ 规则格式为 `"<工具>:<模式>"`(`*` 为通配符,`*:` 匹配所有工具),支持相对/绝对路径:
164
+
165
+ ```json
166
+ {
167
+ "allow": [
168
+ "run_command:git status*",
169
+ "run_command:git push --force origin release*"
170
+ ],
171
+ "deny": [
172
+ "edit_file:node_modules/**",
173
+ "run_command:npm publish*"
174
+ ]
175
+ }
176
+ ```
177
+
178
+ `deny` 命中永远拒绝,`allow` 命中永远放行(可覆盖高危判定)。文件变更后自动热加载,无需重启。
179
+
180
+ ### 非交互模式与 bypass
181
+
182
+ `--stream-json` 或程序化调用(无终端可交互)时,高危命令**安全默认拒绝**。需要全自动场景可显式传入:
183
+
184
+ ```bash
185
+ deepccc --dangerously-bypass-permissions
186
+ ```
187
+
188
+ 该参数与 `ChatSession` 的 `permissionMode: "bypass"` 等价,也是 chatccc 集成 deepccc 时使用的模式(对齐 chatccc 调用 Claude Code / Codex 的 bypass 方式)。
189
+
135
190
  ## 终端过程区块
136
191
 
137
192
  交互模式下,每轮回复渲染为固定"过程区块":状态行(生成中/完成/已停止/异常结束)+ 折叠工具行 + 原地更新正文,不滚屏刷 JSON。生成中有心跳点号动画;完成/停止/异常后区块定型留在屏幕上。
@@ -168,9 +223,12 @@ echo "运行测试并解释失败原因" | deepccc --stream-json
168
223
 
169
224
  ## 在 ChatCCC 中使用
170
225
 
171
- ChatCCC 公有仓库:
226
+ **ChatCCC 已内置 deepccc**:ChatCCC 的 "CCC Agent" 工具直接内嵌 deepccc 的代码(`src/builtin/`),以 `permissionMode: "bypass"` 全自动运行,无需单独安装或配置本仓库。
227
+
228
+ ChatCCC 是一个把 Claude Code / Codex / Cursor / CCC Agent 聚合到飞书/企微等 IM 消息通道的本地机器人框架,提供会话管理、过程卡片、用量统计与隐私替换等能力。
172
229
 
173
- https://github.com/wzj998/ChatCCC
230
+ - 公有仓库:https://github.com/wzj998/ChatCCC
231
+ - npm 包:`chatccc`(`npm install -g chatccc`)
174
232
 
175
233
  在 ChatCCC 会话里可以使用隐藏指令创建 `deepccc` Agent 会话:
176
234
 
@@ -180,6 +238,8 @@ https://github.com/wzj998/ChatCCC
180
238
 
181
239
  这种方式适合已经在 ChatCCC 里协作的场景:ChatCCC 负责会话入口和消息通道,`deepccc` 负责本地编程 Agent 能力,包括读取项目提示词、运行命令、编辑文件和输出流式结果。
182
240
 
241
+ 如果希望让 ChatCCC 使用本仓库(deepccc-agent)最新的独立版本能力,也可以把 `src/builtin/` 与本仓库 `src/` 同步后构建。
242
+
183
243
  ## 项目提示词自动注入
184
244
 
185
245
  会话启动时,`deepccc` 会从当前工作目录读取这些文件,如果存在就注入为项目级提示词:
package/dist/cli.js CHANGED
@@ -12,12 +12,14 @@
12
12
  */
13
13
  import * as readline from "node:readline";
14
14
  import * as process from "node:process";
15
- import { appendFileSync } from "node:fs";
16
- import { resolve as resolvePath } from "node:path";
15
+ import { appendFileSync, existsSync, mkdirSync, writeFileSync } from "node:fs";
16
+ import { homedir } from "node:os";
17
+ import { join, resolve as resolvePath } from "node:path";
17
18
  import { fileURLToPath } from "node:url";
18
19
  import { listBuiltinContextSessions } from "./context.js";
19
20
  import { resolveBuiltinSession } from "./session-select.js";
20
21
  import { createCtrlCState } from "./sigint.js";
22
+ import { buildSkillTemplate } from "./skills.js";
21
23
  import { reduceProgress } from "./progress/reducer.js";
22
24
  import { TerminalProgressRenderer } from "./progress/terminal-renderer.js";
23
25
  import { progressView } from "./progress/view.js";
@@ -87,6 +89,10 @@ function parseArgs(argv = process.argv.slice(2)) {
87
89
  else if (arg === "--plain") {
88
90
  plain = true;
89
91
  }
92
+ else if (arg === "--dangerously-bypass-permissions") {
93
+ // 仅保留一个 bypass 入口(对齐 chatccc 调 claude/codex 的 bypass 模式)
94
+ options.permissionMode = "bypass";
95
+ }
90
96
  else if (arg === "--help" || arg === "-h") {
91
97
  help = true;
92
98
  }
@@ -118,8 +124,16 @@ function printHelp(appConfig) {
118
124
  " --stream-json One-shot mode: write JSONL events to stdout",
119
125
  " --prompt <text> Prompt text for --stream-json",
120
126
  " --plain Force plain streaming output (no progress block renderer)",
127
+ " --dangerously-bypass-permissions Skip all permission prompts (aligns with chatccc's bypass mode)",
121
128
  " --help, -h Show help",
122
129
  "",
130
+ "Permissions:",
131
+ " Default mode asks before high-risk commands (rm -rf, git push --force, ...).",
132
+ " Answer y = allow once, a = allow always (saved to ~/.deepccc/allow.json),",
133
+ " n = deny, g = allow all for this session. Read-only tools and normal file",
134
+ " edits never prompt. In non-interactive mode (--stream-json) high-risk",
135
+ " commands are denied unless --dangerously-bypass-permissions is passed.",
136
+ "",
123
137
  "Default config source:",
124
138
  " ~/.deepccc/config.json, DEEPCCC_* environment variables, or DEEPSEEK_* aliases",
125
139
  "",
@@ -338,6 +352,37 @@ async function runRepl(args) {
338
352
  if (process.stdout.isTTY === true && !args.plain) {
339
353
  muteConsoleLogToFile(setupFileLogging(defaultLogDir(), "index").logPath);
340
354
  }
355
+ const rl = readline.createInterface({
356
+ input: process.stdin,
357
+ output: process.stdout,
358
+ prompt: `${C.green}>${C.reset} `,
359
+ });
360
+ // 权限交互:暂停过程区块渲染(恢复光标)→ readline 提问 → 恢复渲染。
361
+ // activeRenderer/activeView 由每轮 line 处理器维护,resolver 只在工具
362
+ // 执行期间被调用,此时当前轮的区块正处于运行中。
363
+ let activeRenderer = null;
364
+ let activeView = null;
365
+ const permissionResolver = async (request) => {
366
+ const renderer = activeRenderer;
367
+ const view = activeView;
368
+ if (renderer)
369
+ renderer.dispose();
370
+ process.stdout.write(`\n${C.yellow}⚠️ 高危操作需要确认${C.reset}\n`);
371
+ process.stdout.write(`${C.dim}${request.detail}${C.reset}\n`);
372
+ const answer = await new Promise((resolve) => {
373
+ rl.question(`${C.green}允许一次(y) / 永远允许(a) / 拒绝(n) / 本会话允许所有(g) >${C.reset} `, resolve);
374
+ });
375
+ if (renderer && view)
376
+ renderer.begin(view);
377
+ const v = answer.trim().toLowerCase();
378
+ if (v === "y")
379
+ return "allow";
380
+ if (v === "a")
381
+ return "allow-always";
382
+ if (v === "g")
383
+ return "allow-session";
384
+ return "deny";
385
+ };
341
386
  let session;
342
387
  try {
343
388
  session = new ChatSession(args.config, {
@@ -345,17 +390,13 @@ async function runRepl(args) {
345
390
  cwd,
346
391
  persist: true,
347
392
  sessionId: resolvedSession.sessionId,
393
+ permissionResolver,
348
394
  });
349
395
  }
350
396
  catch (err) {
351
397
  console.error(`${C.yellow}${err.message}${C.reset}`);
352
398
  process.exit(1);
353
399
  }
354
- const rl = readline.createInterface({
355
- input: process.stdin,
356
- output: process.stdout,
357
- prompt: `${C.green}>${C.reset} `,
358
- });
359
400
  let currentAbort = null;
360
401
  const ctrlCState = createCtrlCState();
361
402
  rl.prompt();
@@ -391,6 +432,8 @@ async function runRepl(args) {
391
432
  let view = null;
392
433
  if (renderer) {
393
434
  view = progressView({ headerTitle: "生成中..." });
435
+ activeRenderer = renderer;
436
+ activeView = view;
394
437
  // 先回行首换行再 begin:让过程区块从输入行下方开始,避免首帧 \r\x1b[2K
395
438
  // 清掉用户刚输入的问题行(历史文本不被刷掉)。\r\n 兼容 readline
396
439
  // 行提交后光标仍停在输入行行尾的情况。
@@ -446,6 +489,8 @@ async function runRepl(args) {
446
489
  console.error(`\n${C.yellow}[error] ${err.message}${C.reset}`);
447
490
  }
448
491
  finally {
492
+ activeRenderer = null;
493
+ activeView = null;
449
494
  if (renderer && view && !rendererEnded) {
450
495
  // 定型终态区块(完成/已停止/异常结束)留在屏幕上,恢复光标
451
496
  renderer.end(view);
@@ -483,7 +528,56 @@ async function runRepl(args) {
483
528
  process.exit(0);
484
529
  });
485
530
  }
531
+ /**
532
+ * skill create 子命令:deepccc skill create <name> [--scope global|project] [--description "..."]
533
+ * 默认创建为全局技能(~/.deepccc/skills/<name>/SKILL.md,Codex 结构);
534
+ * --scope project 创建为项目技能(<cwd>/.deepccc/skills/<name>/SKILL.md)。
535
+ * 新技能在下一次对话自动生效(技能索引每次 chat() 前重扫)。
536
+ */
537
+ function runSkillCreate(argv) {
538
+ const positional = argv.filter((a) => !a.startsWith("--"));
539
+ const name = positional[0];
540
+ if (!name) {
541
+ console.error("usage: deepccc skill create <name> [--scope global|project] [--description \"...\"]");
542
+ process.exit(1);
543
+ }
544
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name)) {
545
+ console.error(`invalid skill name: ${name}(允许字母/数字/._-,不能以 . 或 - 开头)`);
546
+ process.exit(1);
547
+ }
548
+ const scopeIdx = argv.indexOf("--scope");
549
+ const scope = scopeIdx !== -1 && argv[scopeIdx + 1] === "project" ? "project" : "global";
550
+ const descIdx = argv.indexOf("--description");
551
+ const description = descIdx !== -1 ? (argv[descIdx + 1] ?? "") : "";
552
+ const base = scope === "project"
553
+ ? join(process.cwd(), ".deepccc", "skills")
554
+ : join(homedir(), ".deepccc", "skills");
555
+ const skillPath = join(base, name, "SKILL.md");
556
+ if (existsSync(skillPath)) {
557
+ console.error(`skill already exists: ${skillPath}`);
558
+ process.exit(1);
559
+ }
560
+ try {
561
+ mkdirSync(join(base, name), { recursive: true });
562
+ writeFileSync(skillPath, buildSkillTemplate(name, description), "utf8");
563
+ }
564
+ catch (err) {
565
+ console.error(`failed to create skill: ${err.message}`);
566
+ process.exit(1);
567
+ }
568
+ console.log(`created skill: ${skillPath}`);
569
+ console.log(`scope: ${scope === "project" ? "project(仅当前项目生效)" : "global(所有项目生效)"}`);
570
+ if (description)
571
+ console.log(`description: ${description}`);
572
+ console.log("hot reload: 下一次对话自动生效,无需重启");
573
+ }
486
574
  async function main() {
575
+ // skill create 子命令:deepccc skill create <name> [--scope global|project] [--description "..."]
576
+ // 默认创建在全局 ~/.deepccc/skills(Codex 目录结构),--scope project 创建到 <cwd>/.deepccc/skills。
577
+ if (process.argv[2] === "skill" && process.argv[3] === "create") {
578
+ runSkillCreate(process.argv.slice(4));
579
+ return;
580
+ }
487
581
  const args = parseArgs();
488
582
  if (args.streamJson) {
489
583
  const code = await runStreamJson(args);
@@ -1,4 +1,5 @@
1
1
  import { type ToolSet } from "ai";
2
+ import { type PermissionGate } from "./permissions.js";
2
3
  export interface ReadFileInput {
3
4
  path: string;
4
5
  startLine?: number;
@@ -140,4 +141,8 @@ export declare function createFileForTool(cwd: string, input: CreateFileInput):
140
141
  export declare function deleteFileForTool(cwd: string, input: DeleteFileInput): Promise<DeleteFileOutput>;
141
142
  export declare function moveFileForTool(cwd: string, input: MoveFileInput): Promise<MoveFileOutput>;
142
143
  export declare function applyPatchForTool(cwd: string, input: ApplyPatchInput): Promise<ApplyPatchOutput>;
143
- export declare function createBuiltinFileTools(cwd: string): ToolSet;
144
+ export interface BuiltinFileToolsOptions {
145
+ /** 权限门控:副作用工具(run_command/文件写操作)执行前会先经过 gate.check */
146
+ permissionGate?: PermissionGate;
147
+ }
148
+ export declare function createBuiltinFileTools(cwd: string, options?: BuiltinFileToolsOptions): ToolSet;
@@ -6,6 +6,7 @@ import { createRequire } from "node:module";
6
6
  import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
7
7
  import { createInterface } from "node:readline";
8
8
  import { jsonSchema, tool } from "ai";
9
+ import { isDangerousCommand } from "./permissions.js";
9
10
  import { killProcessTree } from "./proc-tree-kill.js";
10
11
  const MAX_READ_BYTES = 1024 * 1024;
11
12
  const MAX_LIST_ENTRIES = 200;
@@ -919,7 +920,29 @@ export async function applyPatchForTool(cwd, input) {
919
920
  }
920
921
  return { changedFiles };
921
922
  }
922
- export function createBuiltinFileTools(cwd) {
923
+ export function createBuiltinFileTools(cwd, options = {}) {
924
+ const gate = options.permissionGate;
925
+ /** 文件路径的候选匹配键:原始路径 + 绝对路径 + 相对 cwd 路径(正/反斜杠双版本,规则可任选其一) */
926
+ const pathKeys = (p) => {
927
+ const abs = resolveToolPath(cwd, p);
928
+ const rel = relative(cwd, abs);
929
+ return [
930
+ p,
931
+ abs,
932
+ rel,
933
+ rel.split(sep).join("/"),
934
+ abs.split(sep).join("/"),
935
+ ];
936
+ };
937
+ /** 副作用工具执行前的权限守卫:gate 拒绝时抛错,工具不会真正执行 */
938
+ const guard = async (request) => {
939
+ if (!gate)
940
+ return;
941
+ const decision = await gate.check(request);
942
+ if (decision === "deny") {
943
+ throw new Error(`权限拒绝:${request.detail}(已按规则或用户选择拦截;如需放行请调整 ~/.deepccc/allow.json,或使用 --dangerously-bypass-permissions)`);
944
+ }
945
+ };
923
946
  return {
924
947
  read_file: tool({
925
948
  description: "Read a UTF-8 text file from the local filesystem. Use line ranges for large files.",
@@ -973,7 +996,15 @@ export function createBuiltinFileTools(cwd) {
973
996
  },
974
997
  required: ["command"],
975
998
  }),
976
- execute: (input, options) => runCommandForTool(cwd, input, options.abortSignal),
999
+ execute: async (input, options) => {
1000
+ await guard({
1001
+ tool: "run_command",
1002
+ action: input.command,
1003
+ reason: isDangerousCommand(input.command) ? "high-risk" : "rule",
1004
+ detail: `运行命令: ${input.command}`,
1005
+ });
1006
+ return runCommandForTool(cwd, input, options.abortSignal);
1007
+ },
977
1008
  }),
978
1009
  edit_file: tool({
979
1010
  description: "Edit an existing UTF-8 text file by applying exact oldText -> newText replacements. Uses optional SHA-256 precondition to avoid overwriting concurrent edits.",
@@ -1000,7 +1031,16 @@ export function createBuiltinFileTools(cwd) {
1000
1031
  },
1001
1032
  required: ["path", "edits"],
1002
1033
  }),
1003
- execute: (input) => editFileForTool(cwd, input),
1034
+ execute: async (input) => {
1035
+ await guard({
1036
+ tool: "edit_file",
1037
+ action: input.path,
1038
+ altKeys: pathKeys(input.path),
1039
+ reason: "rule",
1040
+ detail: `编辑文件: ${input.path}`,
1041
+ });
1042
+ return editFileForTool(cwd, input);
1043
+ },
1004
1044
  }),
1005
1045
  create_file: tool({
1006
1046
  description: "Create a UTF-8 text file, or overwrite an existing one when overwrite=true.",
@@ -1015,7 +1055,16 @@ export function createBuiltinFileTools(cwd) {
1015
1055
  },
1016
1056
  required: ["path", "content"],
1017
1057
  }),
1018
- execute: (input) => createFileForTool(cwd, input),
1058
+ execute: async (input) => {
1059
+ await guard({
1060
+ tool: "create_file",
1061
+ action: input.path,
1062
+ altKeys: pathKeys(input.path),
1063
+ reason: "rule",
1064
+ detail: `创建/覆盖文件: ${input.path}`,
1065
+ });
1066
+ return createFileForTool(cwd, input);
1067
+ },
1019
1068
  }),
1020
1069
  delete_file: tool({
1021
1070
  description: "Delete an existing text file. Use expectedSha256 to avoid deleting a file that changed after reading.",
@@ -1028,7 +1077,16 @@ export function createBuiltinFileTools(cwd) {
1028
1077
  },
1029
1078
  required: ["path"],
1030
1079
  }),
1031
- execute: (input) => deleteFileForTool(cwd, input),
1080
+ execute: async (input) => {
1081
+ await guard({
1082
+ tool: "delete_file",
1083
+ action: input.path,
1084
+ altKeys: pathKeys(input.path),
1085
+ reason: "rule",
1086
+ detail: `删除文件: ${input.path}`,
1087
+ });
1088
+ return deleteFileForTool(cwd, input);
1089
+ },
1032
1090
  }),
1033
1091
  move_file: tool({
1034
1092
  description: "Move or rename an existing text file. Can overwrite an existing destination only when overwrite=true.",
@@ -1044,7 +1102,16 @@ export function createBuiltinFileTools(cwd) {
1044
1102
  },
1045
1103
  required: ["sourcePath", "destinationPath"],
1046
1104
  }),
1047
- execute: (input) => moveFileForTool(cwd, input),
1105
+ execute: async (input) => {
1106
+ await guard({
1107
+ tool: "move_file",
1108
+ action: input.sourcePath,
1109
+ altKeys: pathKeys(input.sourcePath),
1110
+ reason: "rule",
1111
+ detail: `移动/重命名文件: ${input.sourcePath} → ${input.destinationPath}`,
1112
+ });
1113
+ return moveFileForTool(cwd, input);
1114
+ },
1048
1115
  }),
1049
1116
  apply_patch: tool({
1050
1117
  description: "Apply a unified diff patch to one or more UTF-8 text files. Prefer edit_file for small targeted edits.",
@@ -1061,7 +1128,15 @@ export function createBuiltinFileTools(cwd) {
1061
1128
  },
1062
1129
  required: ["patch"],
1063
1130
  }),
1064
- execute: (input) => applyPatchForTool(cwd, input),
1131
+ execute: async (input) => {
1132
+ await guard({
1133
+ tool: "apply_patch",
1134
+ action: "patch",
1135
+ reason: "rule",
1136
+ detail: "应用 unified diff patch",
1137
+ });
1138
+ return applyPatchForTool(cwd, input);
1139
+ },
1065
1140
  }),
1066
1141
  };
1067
1142
  }
package/dist/index.d.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  *
4
4
  * ChatSession 是程序化入口,既可以被 CLI 调用,也可以被其他模块调用。
5
5
  */
6
+ import { type PermissionMode, type PermissionResolver } from "./permissions.js";
6
7
  export interface ChatSessionConfig {
7
8
  /** OpenAI-compatible service base URL. Defaults to DEEPCCC_BASE_URL/config. */
8
9
  baseURL?: string;
@@ -34,10 +35,21 @@ export interface ChatSessionOptions {
34
35
  /** Optional tool-step limit. Leave unset for no step limit. */
35
36
  maxSteps?: number;
36
37
  /**
37
- * Codex-style skill directories (<dir>/<name>/SKILL.md).
38
- * Defaults to ~/.codex/skills, ~/.agents/skills, <cwd>/.codex/skills.
38
+ * Custom skill directories (<dir>/<name>/SKILL.md). When set, these are
39
+ * scanned with the highest priority (deepccc source). Defaults to the
40
+ * combined Claude/Codex/Cursor/DeepCCC directories (see buildDefaultSkillDirs).
39
41
  */
40
42
  skillsDirs?: string[];
43
+ /**
44
+ * 权限模式:ask(默认,高危命令询问)/ bypass(全部放行,等价
45
+ * --dangerously-bypass-permissions;chatccc 等无终端环境集成时使用)。
46
+ */
47
+ permissionMode?: PermissionMode;
48
+ /**
49
+ * ask 模式下高危操作的交互确认回调;缺省时非交互环境(JSONL / 程序化
50
+ * 调用)自动拒绝高危命令,常规文件操作与低危命令不受影响。
51
+ */
52
+ permissionResolver?: PermissionResolver;
41
53
  }
42
54
  /**
43
55
  * 流式响应事件
@@ -76,12 +88,18 @@ interface ChatMessage {
76
88
  }
77
89
  export declare class ChatSession {
78
90
  private model;
79
- private systemPrompt;
80
91
  private cwd;
81
92
  private context;
82
93
  private maxSteps?;
83
94
  private effort;
95
+ private permissionGate;
96
+ private skillDirs;
97
+ private customSystemPrompt;
98
+ /** 最近一次 chat() 使用的 system prompt(供 history 等读取) */
99
+ private systemPrompt;
84
100
  constructor(overrides?: ChatSessionConfig, options?: ChatSessionOptions);
101
+ /** 组装系统提示词:固定规则 + 项目指令 + 技能索引 + 用户补充 + 运行时上下文 */
102
+ private buildSystemPrompt;
85
103
  chat(userMessage: string, signal?: AbortSignal): AsyncIterable<ChatEvent>;
86
104
  /** 返回当前的会话历史(只读) */
87
105
  get history(): ReadonlyArray<ChatMessage>;
package/dist/index.js CHANGED
@@ -11,7 +11,8 @@ import { config as appConfig, RAW_STREAM_LOGS_DIR } from "./config.js";
11
11
  import { createRawStreamLog, } from "./raw-stream-log.js";
12
12
  import { BuiltinContextManager, buildSummaryPrompt, defaultBuiltinSessionId, } from "./context.js";
13
13
  import { createBuiltinFileTools } from "./file-tools.js";
14
- import { buildDefaultSkillDirs, buildSkillsIndexPrompt, scanSkillsDirs } from "./skills.js";
14
+ import { PermissionGate } from "./permissions.js";
15
+ import { buildDefaultSkillDirs, buildSkillsIndexPrompt, scanSkillsDirs, } from "./skills.js";
15
16
  import { applyPrivacy, applyPrivacyToJson } from "./privacy.js";
16
17
  // ---------------------------------------------------------------------------
17
18
  // 系统提示词 — 编译期冻结常量(DeepCCC 英文品牌)
@@ -81,11 +82,15 @@ function normalizeMaxSteps(value) {
81
82
  }
82
83
  export class ChatSession {
83
84
  model;
84
- systemPrompt;
85
85
  cwd;
86
86
  context;
87
87
  maxSteps;
88
88
  effort;
89
+ permissionGate;
90
+ skillDirs;
91
+ customSystemPrompt;
92
+ /** 最近一次 chat() 使用的 system prompt(供 history 等读取) */
93
+ systemPrompt = "";
89
94
  constructor(overrides = {}, options = {}) {
90
95
  const apiKey = overrides.apiKey ?? appConfig.apiKey;
91
96
  if (!apiKey) {
@@ -102,31 +107,38 @@ export class ChatSession {
102
107
  this.model = provider(modelId);
103
108
  this.cwd = options.cwd ?? process.cwd();
104
109
  this.maxSteps = normalizeMaxSteps(options.maxSteps);
105
- // 构建系统提示词
110
+ this.customSystemPrompt = options.systemPrompt ?? "";
111
+ // 技能目录在构造时确定;技能内容在每次 chat() 前重新扫描(mtime 热加载),
112
+ // 因此创建/修改技能后下一次对话自动生效,无需重启。
113
+ this.skillDirs =
114
+ options.skillsDirs?.map((d) => ({ dir: d, source: "deepccc", scope: "project" })) ??
115
+ buildDefaultSkillDirs(this.cwd);
116
+ this.context = new BuiltinContextManager({
117
+ persist: options.persist ?? false,
118
+ contextDir: options.contextDir,
119
+ sessionId: options.sessionId ?? defaultBuiltinSessionId(this.cwd),
120
+ cwd: this.cwd,
121
+ compactAtTokens: options.compactAtTokens,
122
+ keepRecentMessages: options.keepRecentMessages,
123
+ });
124
+ this.permissionGate = new PermissionGate(options.permissionMode ?? "ask", options.permissionResolver);
125
+ }
126
+ /** 组装系统提示词:固定规则 + 项目指令 + 技能索引 + 用户补充 + 运行时上下文 */
127
+ buildSystemPrompt(skills) {
106
128
  const systemContent = [SYSTEM_PROMPT];
107
129
  const projectInstructions = readProjectInstructionFiles(this.cwd);
108
130
  if (projectInstructions) {
109
131
  systemContent.push("", projectInstructions);
110
132
  }
111
- // Codex-style skills 索引注入(name + description + 路径,模型按需 read_file 全文)
112
- const skills = scanSkillsDirs(options.skillsDirs ?? buildDefaultSkillDirs(this.cwd));
113
133
  const skillsPrompt = buildSkillsIndexPrompt(skills);
114
134
  if (skillsPrompt) {
115
135
  systemContent.push("", skillsPrompt);
116
136
  }
117
- if (options.systemPrompt) {
118
- systemContent.push("", options.systemPrompt);
137
+ if (this.customSystemPrompt) {
138
+ systemContent.push("", this.customSystemPrompt);
119
139
  }
120
140
  systemContent.push("", buildRuntimeWorkspacePrompt(this.cwd));
121
- this.systemPrompt = systemContent.join("\n");
122
- this.context = new BuiltinContextManager({
123
- persist: options.persist ?? false,
124
- contextDir: options.contextDir,
125
- sessionId: options.sessionId ?? defaultBuiltinSessionId(this.cwd),
126
- cwd: this.cwd,
127
- compactAtTokens: options.compactAtTokens,
128
- keepRecentMessages: options.keepRecentMessages,
129
- });
141
+ return systemContent.join("\n");
130
142
  }
131
143
  async *chat(userMessage, signal) {
132
144
  this.context.appendMessage({ role: "user", content: userMessage });
@@ -156,11 +168,16 @@ export class ChatSession {
156
168
  }
157
169
  const toolContext = [];
158
170
  const maxSteps = this.maxSteps;
171
+ // 每次对话前重新扫描技能索引(并行 + mtime 缓存,开销极小):
172
+ // 新技能/修改的技能在下一次对话自动生效(热加载)。
173
+ const skills = await scanSkillsDirs(this.skillDirs);
174
+ const system = this.buildSystemPrompt(skills);
175
+ this.systemPrompt = system;
159
176
  const result = streamText({
160
177
  model: this.model,
161
- system: this.systemPrompt,
178
+ system,
162
179
  messages: this.context.buildModelMessages(),
163
- tools: createBuiltinFileTools(this.cwd),
180
+ tools: createBuiltinFileTools(this.cwd, { permissionGate: this.permissionGate }),
164
181
  stopWhen: maxSteps !== undefined ? stepCountIs(maxSteps) : isLoopFinished(),
165
182
  abortSignal: signal,
166
183
  // DeepSeek OpenAI 兼容接口:providerOptions.deepseek.reasoningEffort
@@ -0,0 +1,42 @@
1
+ export type PermissionMode = "ask" | "bypass";
2
+ export type PermissionReason = "high-risk" | "rule";
3
+ export type PermissionAnswer = "allow" | "allow-always" | "allow-session" | "deny";
4
+ export type PermissionDecision = "allow" | "deny";
5
+ export interface PermissionRequest {
6
+ /** 工具名:run_command / edit_file / create_file / delete_file / move_file / apply_patch */
7
+ tool: string;
8
+ /** 具体操作:命令全文或文件路径 */
9
+ action: string;
10
+ /** high-risk = 命中内置危险命令库,需要询问;rule = 仅受 allow/deny 规则管控 */
11
+ reason: PermissionReason;
12
+ /** 展示给用户的说明 */
13
+ detail: string;
14
+ /** 额外匹配键(如文件相对路径),allow/deny 规则命中任一即生效 */
15
+ altKeys?: string[];
16
+ }
17
+ /** ask 模式下高危操作的交互确认回调(由 CLI 注入 readline 实现) */
18
+ export type PermissionResolver = (request: PermissionRequest) => Promise<PermissionAnswer>;
19
+ export interface AllowRules {
20
+ /** 永远允许的规则,格式 "<tool>:<pattern>" 或 "*:<pattern>",pattern 中 * 为通配符 */
21
+ allow: string[];
22
+ /** 永远拒绝的规则,格式同上 */
23
+ deny: string[];
24
+ }
25
+ export declare function isDangerousCommand(command: string): boolean;
26
+ export declare function getAllowRules(): AllowRules;
27
+ export declare function reloadAllowRules(): void;
28
+ /** 把"永远允许"的规则追加写入 allow.json 并热加载 */
29
+ export declare function appendAllowRule(rule: string): void;
30
+ /**
31
+ * 规则匹配。规则格式 "<tool>:<pattern>" 或 "*:<pattern>";
32
+ * pattern 中的 * 为通配符,其余字符按字面量匹配。
33
+ */
34
+ export declare function matchRule(rule: string, key: string): boolean;
35
+ export declare class PermissionGate {
36
+ private readonly mode;
37
+ private readonly resolver?;
38
+ private sessionAllowAll;
39
+ constructor(mode?: PermissionMode, resolver?: PermissionResolver);
40
+ getMode(): PermissionMode;
41
+ check(request: PermissionRequest): Promise<PermissionDecision>;
42
+ }
@@ -0,0 +1,170 @@
1
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { DEEPCCC_HOME } from "./config.js";
4
+ const RULES_FILE = join(DEEPCCC_HOME, "allow.json");
5
+ const EMPTY_RULES = { allow: [], deny: [] };
6
+ /**
7
+ * 内置危险命令库(命中即进入询问流程;allow 规则可覆盖)。
8
+ * 覆盖 Windows 与 Unix 常见破坏性操作:强制删除、强制推送、磁盘/分区、
9
+ * 关机重启、设备覆写、数据库 DROP、fork bomb、全局卸载、发布等。
10
+ */
11
+ const DANGEROUS_COMMAND_PATTERNS = [
12
+ /^\s*rm\s+-[a-zA-Z]*r[a-zA-Z]*f[a-zA-Z]*\b/i, // rm -rf / rm -fr
13
+ /^\s*rm\s+-[a-zA-Z]*f[a-zA-Z]*r[a-zA-Z]*\b/i,
14
+ /^\s*rmdir\s+\/s/i, // Windows rmdir /s
15
+ /^\s*(del|erase)\s+\/s/i, // Windows del /s
16
+ /^\s*git\s+(push|fetch|pull)\s+.*(--force|-f\b)/i, // git push --force
17
+ /^\s*git\s+reset\s+--hard/i,
18
+ /^\s*git\s+clean\s+(-[a-z]*f)/i,
19
+ /^\s*format\s+[a-z]:/i,
20
+ /^\s*diskpart\b/i,
21
+ /^\s*(shutdown|reboot)\b/i,
22
+ /^\s*mkfs\b/i,
23
+ /^\s*fdisk\b/i,
24
+ /^\s*dd\s+.*\bof=/i,
25
+ /^\s*sudo\s+(rm|shutdown|mkfs|dd|fdisk|diskpart)/i,
26
+ /^\s*Remove-Item\s+-Recurse/i,
27
+ /^\s*:\(\)\s*\{.*\}\s*;/i, // fork bomb
28
+ /^\s*(drop|truncate)\s+table/i,
29
+ /^\s*npm\s+(publish|unpublish)\b/i,
30
+ /^\s*npm\s+uninstall\s+-g/i,
31
+ /^\s*pip\s+uninstall\b/i,
32
+ ];
33
+ export function isDangerousCommand(command) {
34
+ return DANGEROUS_COMMAND_PATTERNS.some((re) => re.test(command));
35
+ }
36
+ // ---------------------------------------------------------------------------
37
+ // 规则加载(~/.deepccc/allow.json,热加载)
38
+ // ---------------------------------------------------------------------------
39
+ let rulesCache = null;
40
+ let rulesStamp;
41
+ function rulesFileStamp() {
42
+ if (!existsSync(RULES_FILE))
43
+ return null;
44
+ try {
45
+ const s = statSync(RULES_FILE);
46
+ return `${s.mtimeMs}:${s.size}`;
47
+ }
48
+ catch {
49
+ return null;
50
+ }
51
+ }
52
+ function sanitizeRuleList(raw) {
53
+ if (!Array.isArray(raw))
54
+ return [];
55
+ return raw.filter((item) => typeof item === "string" && item.trim().length > 0);
56
+ }
57
+ function loadRules() {
58
+ if (!existsSync(RULES_FILE))
59
+ return EMPTY_RULES;
60
+ try {
61
+ const raw = readFileSync(RULES_FILE, "utf-8").replace(/^\uFEFF/, "");
62
+ const parsed = JSON.parse(raw);
63
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
64
+ return EMPTY_RULES;
65
+ return {
66
+ allow: sanitizeRuleList(parsed.allow),
67
+ deny: sanitizeRuleList(parsed.deny),
68
+ };
69
+ }
70
+ catch (err) {
71
+ console.error(`[PERMISSIONS] failed to read allow.json: ${err.message}`);
72
+ return EMPTY_RULES;
73
+ }
74
+ }
75
+ export function getAllowRules() {
76
+ const stamp = rulesFileStamp();
77
+ if (!rulesCache || stamp !== rulesStamp) {
78
+ rulesCache = loadRules();
79
+ rulesStamp = stamp;
80
+ }
81
+ return rulesCache;
82
+ }
83
+ export function reloadAllowRules() {
84
+ rulesCache = null;
85
+ rulesStamp = undefined;
86
+ }
87
+ /** 把"永远允许"的规则追加写入 allow.json 并热加载 */
88
+ export function appendAllowRule(rule) {
89
+ const rules = getAllowRules();
90
+ if (rules.allow.includes(rule))
91
+ return;
92
+ const next = { allow: [...rules.allow, rule], deny: rules.deny };
93
+ try {
94
+ mkdirSync(dirname(RULES_FILE), { recursive: true });
95
+ writeFileSync(RULES_FILE, `${JSON.stringify(next, null, 2)}\n`, "utf-8");
96
+ reloadAllowRules();
97
+ }
98
+ catch (err) {
99
+ console.error(`[PERMISSIONS] failed to write allow.json: ${err.message}`);
100
+ }
101
+ }
102
+ function escapeRegex(s) {
103
+ return s.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
104
+ }
105
+ /**
106
+ * 规则匹配。规则格式 "<tool>:<pattern>" 或 "*:<pattern>";
107
+ * pattern 中的 * 为通配符,其余字符按字面量匹配。
108
+ */
109
+ export function matchRule(rule, key) {
110
+ const ruleColon = rule.indexOf(":");
111
+ if (ruleColon === -1)
112
+ return false;
113
+ const toolPart = rule.slice(0, ruleColon);
114
+ const pattern = rule.slice(ruleColon + 1);
115
+ const keyColon = key.indexOf(":");
116
+ if (keyColon === -1)
117
+ return false;
118
+ const keyTool = key.slice(0, keyColon);
119
+ const keyAction = key.slice(keyColon + 1);
120
+ if (toolPart !== "*" && toolPart !== keyTool)
121
+ return false;
122
+ const re = new RegExp(`^${pattern.split("*").map(escapeRegex).join(".*")}$`);
123
+ return re.test(keyAction);
124
+ }
125
+ // ---------------------------------------------------------------------------
126
+ // PermissionGate
127
+ // ---------------------------------------------------------------------------
128
+ export class PermissionGate {
129
+ mode;
130
+ resolver;
131
+ sessionAllowAll = false;
132
+ constructor(mode = "ask", resolver) {
133
+ this.mode = mode;
134
+ this.resolver = resolver;
135
+ }
136
+ getMode() {
137
+ return this.mode;
138
+ }
139
+ async check(request) {
140
+ if (this.mode === "bypass" || this.sessionAllowAll)
141
+ return "allow";
142
+ const key = `${request.tool}:${request.action}`;
143
+ const keys = [key, ...(request.altKeys ?? []).map((k) => `${request.tool}:${k}`)];
144
+ const rules = getAllowRules();
145
+ if (rules.deny.some((r) => keys.some((k) => matchRule(r, k))))
146
+ return "deny";
147
+ if (rules.allow.some((r) => keys.some((k) => matchRule(r, k))))
148
+ return "allow";
149
+ // 只有命中内置危险命令库的 run_command 才询问;文件编辑等常规操作默认放行
150
+ if (request.reason !== "high-risk")
151
+ return "allow";
152
+ // 高危且无交互能力(非 TTY / JSONL / 程序化调用)→ 安全默认拒绝
153
+ if (!this.resolver)
154
+ return "deny";
155
+ const answer = await this.resolver(request);
156
+ switch (answer) {
157
+ case "allow":
158
+ return "allow";
159
+ case "allow-session":
160
+ this.sessionAllowAll = true;
161
+ return "allow";
162
+ case "allow-always":
163
+ appendAllowRule(key);
164
+ return "allow";
165
+ case "deny":
166
+ default:
167
+ return "deny";
168
+ }
169
+ }
170
+ }
package/dist/skills.d.ts CHANGED
@@ -1,16 +1,33 @@
1
1
  /**
2
- * builtin/skills.ts — Codex-style skills 支持
2
+ * skills.ts — 多来源技能扫描(DeepCCC 统一入口)
3
3
  *
4
- * 从用户级(~/.codex/skills、~/.agents/skills)和项目级(<cwd>/.codex/skills)
5
- * 扫描 Codex 目录式 skill(<name>/SKILL.md),解析 frontmatter 中的
6
- * name + description,生成索引注入 system prompt。模型按需用 read_file
7
- * 读取 SKILL.md 全文并执行(索引注入省 token,触发靠 description + 指令)。
4
+ * 并行扫描 Claude / Codex / Cursor / DeepCCC 四套目录式技能
5
+ * (<name>/SKILL.md + YAML frontmatter,三套生态同构)。
6
+ *
7
+ * 同名优先级(高 → 低):deepccc > codex > cursor > claude;
8
+ * 同来源内:project(项目级)> global(用户级)。
9
+ * 目录列表按低 → 高排列,扫描时后者覆盖前者,天然实现优先级。
10
+ *
11
+ * 热加载:SKILL.md 内容带 mtime 缓存,文件变化时自动重读;
12
+ * 目录枚举每次都做(新技能目录立即被发现)。因此"创建技能 →
13
+ * 下一次对话自动生效",无需重启,也无需常驻 watcher。
8
14
  */
15
+ export type SkillSource = "deepccc" | "codex" | "cursor" | "claude";
16
+ export type SkillScope = "global" | "project";
9
17
  export interface BuiltinSkill {
10
18
  name: string;
11
19
  description: string;
12
20
  /** SKILL.md 的绝对路径 */
13
21
  skillPath: string;
22
+ /** 来源(优先级 deepccc > codex > cursor > claude) */
23
+ source: SkillSource;
24
+ /** global = 用户级;project = 项目级(同来源内 project > global) */
25
+ scope: SkillScope;
26
+ }
27
+ export interface SkillDirSpec {
28
+ dir: string;
29
+ source: SkillSource;
30
+ scope: SkillScope;
14
31
  }
15
32
  /** 解析 SKILL.md frontmatter(兼容 CRLF),返回 name + description;无 frontmatter 返回 null */
16
33
  export declare function parseSkillFrontmatter(content: string): {
@@ -18,21 +35,23 @@ export declare function parseSkillFrontmatter(content: string): {
18
35
  description: string;
19
36
  } | null;
20
37
  /**
21
- * 扫描多个 skill 目录,返回去重后的 skill 列表。
22
- * 同名 skill 后面的目录覆盖前面的(调用方应把项目级目录放最后)。
23
- * 隐藏目录(.system 等)和无 SKILL.md 的目录会被跳过。
38
+ * 扫描多个 skill 目录(并行读取),按 name 去重。
39
+ * 同名技能:后面的 spec(高优先级)覆盖前面的(低优先级)。
40
+ * 隐藏目录(.system 等)和无 SKILL.md 的目录会被跳过;缺失目录跳过。
24
41
  */
25
- export declare function scanSkillsDirs(dirs: string[]): BuiltinSkill[];
42
+ export declare function scanSkillsDirs(dirs: SkillDirSpec[]): Promise<BuiltinSkill[]>;
26
43
  /**
27
- * 默认 skill 扫描目录:
28
- * 1. ~/.codex/skills(Codex CLI 旧路径,用户实际在用的地方)
29
- * 2. ~/.agents/skills(Codex 标准全局目录)
30
- * 3. <cwd>/.codex/skills(项目级,优先级最高,放最后)
44
+ * 默认技能扫描目录(按优先级从低到高排列,扫描时后者覆盖前者):
45
+ * claude(global→project) < cursor(global→project) < codex(global→project) < deepccc(global→project)
46
+ * 其中 codex 全局包含 ~/.codex/skills(CLI 旧路径)与 ~/.agents/skills(标准全局目录)。
31
47
  */
32
- export declare function buildDefaultSkillDirs(cwd: string): string[];
48
+ export declare function buildDefaultSkillDirs(cwd: string): SkillDirSpec[];
33
49
  /**
34
50
  * 生成 skill 索引提示词(注入 system prompt)。
35
- * 索引只含 name + description + 路径,并指示模型在任务匹配时
36
- * 先用 read_file 读取 SKILL.md 全文再执行——这是触发率的关键。
51
+ * 索引只含 name + description + 来源 + 路径,并指示模型在任务匹配时
52
+ * 先用 read_file 读取 SKILL.md 全文再执行;同时声明"创建技能"约定
53
+ * (模型在对话中应把新技能创建到 ~/.deepccc/skills 或项目 .deepccc/skills)。
37
54
  */
38
55
  export declare function buildSkillsIndexPrompt(skills: BuiltinSkill[]): string;
56
+ /** 生成 Codex 结构的新技能 SKILL.md 模板(供 CLI skill create / 对话创建约定共用) */
57
+ export declare function buildSkillTemplate(name: string, description: string): string;
package/dist/skills.js CHANGED
@@ -1,12 +1,19 @@
1
1
  /**
2
- * builtin/skills.ts — Codex-style skills 支持
2
+ * skills.ts — 多来源技能扫描(DeepCCC 统一入口)
3
3
  *
4
- * 从用户级(~/.codex/skills、~/.agents/skills)和项目级(<cwd>/.codex/skills)
5
- * 扫描 Codex 目录式 skill(<name>/SKILL.md),解析 frontmatter 中的
6
- * name + description,生成索引注入 system prompt。模型按需用 read_file
7
- * 读取 SKILL.md 全文并执行(索引注入省 token,触发靠 description + 指令)。
4
+ * 并行扫描 Claude / Codex / Cursor / DeepCCC 四套目录式技能
5
+ * (<name>/SKILL.md + YAML frontmatter,三套生态同构)。
6
+ *
7
+ * 同名优先级(高 → 低):deepccc > codex > cursor > claude;
8
+ * 同来源内:project(项目级)> global(用户级)。
9
+ * 目录列表按低 → 高排列,扫描时后者覆盖前者,天然实现优先级。
10
+ *
11
+ * 热加载:SKILL.md 内容带 mtime 缓存,文件变化时自动重读;
12
+ * 目录枚举每次都做(新技能目录立即被发现)。因此"创建技能 →
13
+ * 下一次对话自动生效",无需重启,也无需常驻 watcher。
8
14
  */
9
- import { readFileSync, readdirSync } from "node:fs";
15
+ import { readdirSync } from "node:fs";
16
+ import { readFile, stat } from "node:fs/promises";
10
17
  import { homedir } from "node:os";
11
18
  import { join } from "node:path";
12
19
  /** 解析 SKILL.md frontmatter(兼容 CRLF),返回 name + description;无 frontmatter 返回 null */
@@ -24,72 +31,132 @@ export function parseSkillFrontmatter(content) {
24
31
  description: descMatch?.[1].trim() ?? "",
25
32
  };
26
33
  }
34
+ // ---------------------------------------------------------------------------
35
+ // mtime 热加载缓存:同一进程内重复扫描命中缓存(stat 校验),文件变化自动重读
36
+ // ---------------------------------------------------------------------------
37
+ const skillFileCache = new Map();
38
+ async function readSkillFile(skillPath) {
39
+ let st;
40
+ try {
41
+ st = await stat(skillPath);
42
+ }
43
+ catch {
44
+ return null;
45
+ }
46
+ if (!st.isFile())
47
+ return null;
48
+ const cached = skillFileCache.get(skillPath);
49
+ if (cached && cached.mtimeMs === st.mtimeMs)
50
+ return cached.content;
51
+ const content = await readFile(skillPath, "utf8");
52
+ skillFileCache.set(skillPath, { mtimeMs: st.mtimeMs, content });
53
+ return content;
54
+ }
27
55
  /**
28
- * 扫描多个 skill 目录,返回去重后的 skill 列表。
29
- * 同名 skill 后面的目录覆盖前面的(调用方应把项目级目录放最后)。
30
- * 隐藏目录(.system 等)和无 SKILL.md 的目录会被跳过。
56
+ * 扫描多个 skill 目录(并行读取),按 name 去重。
57
+ * 同名技能:后面的 spec(高优先级)覆盖前面的(低优先级)。
58
+ * 隐藏目录(.system 等)和无 SKILL.md 的目录会被跳过;缺失目录跳过。
31
59
  */
32
- export function scanSkillsDirs(dirs) {
60
+ export async function scanSkillsDirs(dirs) {
33
61
  const byName = new Map();
34
- for (const dir of dirs) {
62
+ for (const spec of dirs) {
35
63
  let entries;
36
64
  try {
37
- entries = readdirSync(dir, { withFileTypes: true });
65
+ entries = readdirSync(spec.dir, { withFileTypes: true });
38
66
  }
39
67
  catch {
40
68
  continue; // 目录不存在或不可读:跳过
41
69
  }
42
- for (const entry of entries) {
43
- if (!entry.isDirectory())
44
- continue;
45
- if (entry.name.startsWith("."))
46
- continue; // 排除 .system 等隐藏/内置目录
47
- const skillPath = join(dir, entry.name, "SKILL.md");
48
- let content;
49
- try {
50
- content = readFileSync(skillPath, "utf-8");
51
- }
52
- catch {
53
- continue; // 没有 SKILL.md 的目录不是 skill
54
- }
70
+ // 目录内所有候选 SKILL.md 并行读取(读文件是扫描的瓶颈)
71
+ const results = await Promise.all(entries
72
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith("."))
73
+ .map(async (entry) => {
74
+ const skillPath = join(spec.dir, entry.name, "SKILL.md");
75
+ const content = await readSkillFile(skillPath);
76
+ if (content === null)
77
+ return null;
55
78
  const parsed = parseSkillFrontmatter(content);
56
79
  if (!parsed)
80
+ return null;
81
+ return { ...parsed, skillPath };
82
+ }));
83
+ for (const result of results) {
84
+ if (!result)
57
85
  continue;
58
- byName.set(parsed.name, {
59
- name: parsed.name,
60
- description: parsed.description,
61
- skillPath,
86
+ byName.set(result.name, {
87
+ name: result.name,
88
+ description: result.description,
89
+ skillPath: result.skillPath,
90
+ source: spec.source,
91
+ scope: spec.scope,
62
92
  });
63
93
  }
64
94
  }
65
95
  return [...byName.values()];
66
96
  }
67
97
  /**
68
- * 默认 skill 扫描目录:
69
- * 1. ~/.codex/skills(Codex CLI 旧路径,用户实际在用的地方)
70
- * 2. ~/.agents/skills(Codex 标准全局目录)
71
- * 3. <cwd>/.codex/skills(项目级,优先级最高,放最后)
98
+ * 默认技能扫描目录(按优先级从低到高排列,扫描时后者覆盖前者):
99
+ * claude(global→project) < cursor(global→project) < codex(global→project) < deepccc(global→project)
100
+ * 其中 codex 全局包含 ~/.codex/skills(CLI 旧路径)与 ~/.agents/skills(标准全局目录)。
72
101
  */
73
102
  export function buildDefaultSkillDirs(cwd) {
103
+ const h = homedir();
74
104
  return [
75
- join(homedir(), ".codex", "skills"),
76
- join(homedir(), ".agents", "skills"),
77
- join(cwd, ".codex", "skills"),
105
+ { dir: join(h, ".claude", "skills"), source: "claude", scope: "global" },
106
+ { dir: join(cwd, ".claude", "skills"), source: "claude", scope: "project" },
107
+ { dir: join(h, ".cursor", "skills"), source: "cursor", scope: "global" },
108
+ { dir: join(cwd, ".cursor", "skills"), source: "cursor", scope: "project" },
109
+ { dir: join(h, ".codex", "skills"), source: "codex", scope: "global" },
110
+ { dir: join(h, ".agents", "skills"), source: "codex", scope: "global" },
111
+ { dir: join(cwd, ".codex", "skills"), source: "codex", scope: "project" },
112
+ { dir: join(h, ".deepccc", "skills"), source: "deepccc", scope: "global" },
113
+ { dir: join(cwd, ".deepccc", "skills"), source: "deepccc", scope: "project" },
78
114
  ];
79
115
  }
80
116
  /**
81
117
  * 生成 skill 索引提示词(注入 system prompt)。
82
- * 索引只含 name + description + 路径,并指示模型在任务匹配时
83
- * 先用 read_file 读取 SKILL.md 全文再执行——这是触发率的关键。
118
+ * 索引只含 name + description + 来源 + 路径,并指示模型在任务匹配时
119
+ * 先用 read_file 读取 SKILL.md 全文再执行;同时声明"创建技能"约定
120
+ * (模型在对话中应把新技能创建到 ~/.deepccc/skills 或项目 .deepccc/skills)。
84
121
  */
85
122
  export function buildSkillsIndexPrompt(skills) {
86
123
  if (skills.length === 0)
87
124
  return "";
88
125
  const lines = [
89
- "## Available Skills (Codex-style)",
90
- "The following Codex-style skills are available on this machine. When a user request matches a skill's description, first read its full SKILL.md with read_file, then follow the instructions in it exactly.",
126
+ "## Available Skills",
127
+ "Skills are scanned in parallel from Claude/Codex/Cursor/DeepCCC skill directories.",
128
+ "On name conflicts: DeepCCC > Codex > Cursor > Claude wins; within one source, project scope wins over global.",
129
+ "When a user request matches a skill's description, first read its full SKILL.md with read_file, then follow the instructions in it exactly.",
91
130
  "",
92
- ...skills.map((s) => `- **${s.name}** (\`${s.skillPath}\`): ${s.description || "(no description)"}`),
131
+ ...skills.map((s) => `- **${s.name}** [${s.source}:${s.scope}] (\`${s.skillPath}\`): ${s.description || "(no description)"}`),
132
+ "",
133
+ "## Creating Skills",
134
+ "When the user asks to create a skill, create it as a Codex-style directory skill at",
135
+ "~/.deepccc/skills/<name>/SKILL.md (global, default) or <cwd>/.deepccc/skills/<name>/SKILL.md (project, only when the user explicitly asks for a project-scoped skill).",
136
+ "SKILL.md format:",
137
+ "```",
138
+ "---",
139
+ "name: <skill-name>",
140
+ "description: <one-line description>",
141
+ "---",
142
+ "",
143
+ "<instructions>",
144
+ "```",
145
+ "New skills are picked up automatically on the next message (hot reload); no restart is needed.",
93
146
  ];
94
147
  return lines.join("\n");
95
148
  }
149
+ /** 生成 Codex 结构的新技能 SKILL.md 模板(供 CLI skill create / 对话创建约定共用) */
150
+ export function buildSkillTemplate(name, description) {
151
+ return [
152
+ "---",
153
+ `name: ${name}`,
154
+ `description: ${description}`,
155
+ "---",
156
+ "",
157
+ `# ${name}`,
158
+ "",
159
+ "<skill instructions>",
160
+ "",
161
+ ].join("\n");
162
+ }
package/package.json CHANGED
@@ -1,61 +1,61 @@
1
- {
2
- "name": "deepccc",
3
- "version": "0.1.2",
4
- "description": "A lightweight DeepSeek-optimized coding agent with OpenAI-compatible model support.",
5
- "license": "Apache-2.0",
6
- "keywords": [
7
- "agent",
8
- "deepseek",
9
- "coding-agent",
10
- "openai-compatible",
11
- "cli"
12
- ],
13
- "repository": {
14
- "type": "git",
15
- "url": "git+https://github.com/wzj998/deepccc-agent.git"
16
- },
17
- "bugs": {
18
- "url": "https://github.com/wzj998/deepccc-agent/issues"
19
- },
20
- "homepage": "https://github.com/wzj998/deepccc-agent#readme",
21
- "type": "module",
22
- "main": "./dist/index.js",
23
- "types": "./dist/index.d.ts",
24
- "exports": {
25
- ".": {
26
- "types": "./dist/index.d.ts",
27
- "import": "./dist/index.js"
28
- }
29
- },
30
- "bin": {
31
- "deepccc": "bin/deepccc.mjs"
32
- },
33
- "files": [
34
- "dist/",
35
- "bin/",
36
- "package.json",
37
- "README.md",
38
- "LICENSE"
39
- ],
40
- "scripts": {
41
- "build": "node node_modules/typescript/bin/tsc -p tsconfig.build.json",
42
- "prepack": "node node_modules/typescript/bin/tsc -p tsconfig.build.json",
43
- "test": "vitest run",
44
- "test:watch": "vitest",
45
- "typecheck": "node node_modules/typescript/bin/tsc --noEmit"
46
- },
47
- "dependencies": {
48
- "@ai-sdk/openai-compatible": "^2.0.47",
49
- "@vscode/ripgrep": "^1.18.0",
50
- "ai": "^6.0.184"
51
- },
52
- "devDependencies": {
53
- "@types/node": "^20.0.0",
54
- "tsx": "^4.0.0",
55
- "typescript": "^5.0.0",
56
- "vitest": "^3.2.4"
57
- },
58
- "engines": {
59
- "node": ">=20"
60
- }
61
- }
1
+ {
2
+ "name": "deepccc",
3
+ "version": "0.1.4",
4
+ "description": "A lightweight DeepSeek-optimized coding agent with OpenAI-compatible model support.",
5
+ "license": "Apache-2.0",
6
+ "keywords": [
7
+ "agent",
8
+ "deepseek",
9
+ "coding-agent",
10
+ "openai-compatible",
11
+ "cli"
12
+ ],
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/wzj998/deepccc-agent.git"
16
+ },
17
+ "bugs": {
18
+ "url": "https://github.com/wzj998/deepccc-agent/issues"
19
+ },
20
+ "homepage": "https://github.com/wzj998/deepccc-agent#readme",
21
+ "type": "module",
22
+ "main": "./dist/index.js",
23
+ "types": "./dist/index.d.ts",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "import": "./dist/index.js"
28
+ }
29
+ },
30
+ "bin": {
31
+ "deepccc": "bin/deepccc.mjs"
32
+ },
33
+ "files": [
34
+ "dist/",
35
+ "bin/",
36
+ "package.json",
37
+ "README.md",
38
+ "LICENSE"
39
+ ],
40
+ "scripts": {
41
+ "build": "node node_modules/typescript/bin/tsc -p tsconfig.build.json",
42
+ "prepack": "node node_modules/typescript/bin/tsc -p tsconfig.build.json",
43
+ "test": "vitest run",
44
+ "test:watch": "vitest",
45
+ "typecheck": "node node_modules/typescript/bin/tsc --noEmit"
46
+ },
47
+ "dependencies": {
48
+ "@ai-sdk/openai-compatible": "^2.0.47",
49
+ "@vscode/ripgrep": "^1.18.0",
50
+ "ai": "^6.0.184"
51
+ },
52
+ "devDependencies": {
53
+ "@types/node": "^20.0.0",
54
+ "tsx": "^4.0.0",
55
+ "typescript": "^5.0.0",
56
+ "vitest": "^3.2.4"
57
+ },
58
+ "engines": {
59
+ "node": ">=20"
60
+ }
61
+ }