deepccc 0.1.2 → 0.1.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/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
@@ -87,6 +87,10 @@ function parseArgs(argv = process.argv.slice(2)) {
87
87
  else if (arg === "--plain") {
88
88
  plain = true;
89
89
  }
90
+ else if (arg === "--dangerously-bypass-permissions") {
91
+ // 仅保留一个 bypass 入口(对齐 chatccc 调 claude/codex 的 bypass 模式)
92
+ options.permissionMode = "bypass";
93
+ }
90
94
  else if (arg === "--help" || arg === "-h") {
91
95
  help = true;
92
96
  }
@@ -118,8 +122,16 @@ function printHelp(appConfig) {
118
122
  " --stream-json One-shot mode: write JSONL events to stdout",
119
123
  " --prompt <text> Prompt text for --stream-json",
120
124
  " --plain Force plain streaming output (no progress block renderer)",
125
+ " --dangerously-bypass-permissions Skip all permission prompts (aligns with chatccc's bypass mode)",
121
126
  " --help, -h Show help",
122
127
  "",
128
+ "Permissions:",
129
+ " Default mode asks before high-risk commands (rm -rf, git push --force, ...).",
130
+ " Answer y = allow once, a = allow always (saved to ~/.deepccc/allow.json),",
131
+ " n = deny, g = allow all for this session. Read-only tools and normal file",
132
+ " edits never prompt. In non-interactive mode (--stream-json) high-risk",
133
+ " commands are denied unless --dangerously-bypass-permissions is passed.",
134
+ "",
123
135
  "Default config source:",
124
136
  " ~/.deepccc/config.json, DEEPCCC_* environment variables, or DEEPSEEK_* aliases",
125
137
  "",
@@ -338,6 +350,37 @@ async function runRepl(args) {
338
350
  if (process.stdout.isTTY === true && !args.plain) {
339
351
  muteConsoleLogToFile(setupFileLogging(defaultLogDir(), "index").logPath);
340
352
  }
353
+ const rl = readline.createInterface({
354
+ input: process.stdin,
355
+ output: process.stdout,
356
+ prompt: `${C.green}>${C.reset} `,
357
+ });
358
+ // 权限交互:暂停过程区块渲染(恢复光标)→ readline 提问 → 恢复渲染。
359
+ // activeRenderer/activeView 由每轮 line 处理器维护,resolver 只在工具
360
+ // 执行期间被调用,此时当前轮的区块正处于运行中。
361
+ let activeRenderer = null;
362
+ let activeView = null;
363
+ const permissionResolver = async (request) => {
364
+ const renderer = activeRenderer;
365
+ const view = activeView;
366
+ if (renderer)
367
+ renderer.dispose();
368
+ process.stdout.write(`\n${C.yellow}⚠️ 高危操作需要确认${C.reset}\n`);
369
+ process.stdout.write(`${C.dim}${request.detail}${C.reset}\n`);
370
+ const answer = await new Promise((resolve) => {
371
+ rl.question(`${C.green}允许一次(y) / 永远允许(a) / 拒绝(n) / 本会话允许所有(g) >${C.reset} `, resolve);
372
+ });
373
+ if (renderer && view)
374
+ renderer.begin(view);
375
+ const v = answer.trim().toLowerCase();
376
+ if (v === "y")
377
+ return "allow";
378
+ if (v === "a")
379
+ return "allow-always";
380
+ if (v === "g")
381
+ return "allow-session";
382
+ return "deny";
383
+ };
341
384
  let session;
342
385
  try {
343
386
  session = new ChatSession(args.config, {
@@ -345,17 +388,13 @@ async function runRepl(args) {
345
388
  cwd,
346
389
  persist: true,
347
390
  sessionId: resolvedSession.sessionId,
391
+ permissionResolver,
348
392
  });
349
393
  }
350
394
  catch (err) {
351
395
  console.error(`${C.yellow}${err.message}${C.reset}`);
352
396
  process.exit(1);
353
397
  }
354
- const rl = readline.createInterface({
355
- input: process.stdin,
356
- output: process.stdout,
357
- prompt: `${C.green}>${C.reset} `,
358
- });
359
398
  let currentAbort = null;
360
399
  const ctrlCState = createCtrlCState();
361
400
  rl.prompt();
@@ -391,6 +430,8 @@ async function runRepl(args) {
391
430
  let view = null;
392
431
  if (renderer) {
393
432
  view = progressView({ headerTitle: "生成中..." });
433
+ activeRenderer = renderer;
434
+ activeView = view;
394
435
  // 先回行首换行再 begin:让过程区块从输入行下方开始,避免首帧 \r\x1b[2K
395
436
  // 清掉用户刚输入的问题行(历史文本不被刷掉)。\r\n 兼容 readline
396
437
  // 行提交后光标仍停在输入行行尾的情况。
@@ -446,6 +487,8 @@ async function runRepl(args) {
446
487
  console.error(`\n${C.yellow}[error] ${err.message}${C.reset}`);
447
488
  }
448
489
  finally {
490
+ activeRenderer = null;
491
+ activeView = null;
449
492
  if (renderer && view && !rendererEnded) {
450
493
  // 定型终态区块(完成/已停止/异常结束)留在屏幕上,恢复光标
451
494
  renderer.end(view);
@@ -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;
@@ -38,6 +39,16 @@ export interface ChatSessionOptions {
38
39
  * Defaults to ~/.codex/skills, ~/.agents/skills, <cwd>/.codex/skills.
39
40
  */
40
41
  skillsDirs?: string[];
42
+ /**
43
+ * 权限模式:ask(默认,高危命令询问)/ bypass(全部放行,等价
44
+ * --dangerously-bypass-permissions;chatccc 等无终端环境集成时使用)。
45
+ */
46
+ permissionMode?: PermissionMode;
47
+ /**
48
+ * ask 模式下高危操作的交互确认回调;缺省时非交互环境(JSONL / 程序化
49
+ * 调用)自动拒绝高危命令,常规文件操作与低危命令不受影响。
50
+ */
51
+ permissionResolver?: PermissionResolver;
41
52
  }
42
53
  /**
43
54
  * 流式响应事件
@@ -81,6 +92,7 @@ export declare class ChatSession {
81
92
  private context;
82
93
  private maxSteps?;
83
94
  private effort;
95
+ private permissionGate;
84
96
  constructor(overrides?: ChatSessionConfig, options?: ChatSessionOptions);
85
97
  chat(userMessage: string, signal?: AbortSignal): AsyncIterable<ChatEvent>;
86
98
  /** 返回当前的会话历史(只读) */
package/dist/index.js CHANGED
@@ -11,6 +11,7 @@ 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 { PermissionGate } from "./permissions.js";
14
15
  import { buildDefaultSkillDirs, buildSkillsIndexPrompt, scanSkillsDirs } from "./skills.js";
15
16
  import { applyPrivacy, applyPrivacyToJson } from "./privacy.js";
16
17
  // ---------------------------------------------------------------------------
@@ -86,6 +87,7 @@ export class ChatSession {
86
87
  context;
87
88
  maxSteps;
88
89
  effort;
90
+ permissionGate;
89
91
  constructor(overrides = {}, options = {}) {
90
92
  const apiKey = overrides.apiKey ?? appConfig.apiKey;
91
93
  if (!apiKey) {
@@ -127,6 +129,7 @@ export class ChatSession {
127
129
  compactAtTokens: options.compactAtTokens,
128
130
  keepRecentMessages: options.keepRecentMessages,
129
131
  });
132
+ this.permissionGate = new PermissionGate(options.permissionMode ?? "ask", options.permissionResolver);
130
133
  }
131
134
  async *chat(userMessage, signal) {
132
135
  this.context.appendMessage({ role: "user", content: userMessage });
@@ -160,7 +163,7 @@ export class ChatSession {
160
163
  model: this.model,
161
164
  system: this.systemPrompt,
162
165
  messages: this.context.buildModelMessages(),
163
- tools: createBuiltinFileTools(this.cwd),
166
+ tools: createBuiltinFileTools(this.cwd, { permissionGate: this.permissionGate }),
164
167
  stopWhen: maxSteps !== undefined ? stepCountIs(maxSteps) : isLoopFinished(),
165
168
  abortSignal: signal,
166
169
  // 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/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.3",
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
+ }