glmcode 0.1.6 → 0.1.8

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 CHANGED
@@ -1,9 +1,14 @@
1
1
  # Changelog
2
2
 
3
- ## 0.1.6
3
+ ## 0.1.7
4
4
 
5
- - 修复 API Key 检测:环境变量 + `~/.glmcode/auth.json`
6
- - 增加 `auth set/status/logout`
7
- - 修复没有 `termux-open-url` 时的 ENOENT 崩溃
8
- - 更新智谱 API Key 管理页面
9
- - 保留跨平台 Shell 检测与配置入口
5
+ ### Skills 路径修正
6
+
7
+ - Skills 目录改为相对于主 CLI 文件位置解析,并在启动时自动创建
8
+ - 按原版 glmcode.py 重构交互式 coding agent
9
+ - 增加流式 GLM Chat Completions
10
+ - 增加 run_shell / read_file / write_file / use_skill
11
+ - 增加 Skills 自动扫描和斜杠调用
12
+ - 输入 `/` 后提供命令补全
13
+ - 增加底部状态栏:思考、模型、技能数量、当前目录
14
+ - 保留跨平台 Shell 和 API Key 自动检测
package/README.md CHANGED
@@ -1,60 +1,58 @@
1
- # GLMCode 0.1.6
1
+ # GLMCode 0.1.7
2
+
3
+ 基于原版 `glmcode.py` 的 Node.js CLI 实现,重点保留其交互界面、斜杠命令、技能系统、流式输出和 coding-agent 工具。
4
+
5
+ ## 启动
2
6
 
3
- ## 安装
4
7
  ```bash
5
8
  npm install -g glmcode
6
- glmcode --version
9
+ glmcode
7
10
  ```
8
11
 
9
- ## API Key 自动检测
12
+ ## API Key
13
+
10
14
  检测顺序:
15
+
11
16
  1. `ZHIPU_API_KEY`
12
17
  2. `GLM_API_KEY`
13
18
  3. `~/.glmcode/auth.json`
14
19
 
15
20
  已有 Key:
21
+
16
22
  ```bash
17
23
  glmcode auth set YOUR_API_KEY
18
24
  ```
19
25
 
20
- 状态:
21
- ```bash
22
- glmcode auth status
23
- ```
26
+ ## 交互
24
27
 
25
- 没有 Key:
26
- ```bash
27
- glmcode auth login
28
- ```
28
+ 输入 `/` 后按 Tab 可补全命令;命令包括:
29
29
 
30
- GUI 环境:
31
- ```bash
32
- glmcode auth login --no-browser
33
- ```
30
+ `/help` `/clear` `/thinking` `/model` `/pwd` `/cd` `/ls` `/cat` `/run` `/exit`
34
31
 
35
- 官方 API Key 页面:
36
- https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys
32
+ Skills 目录由程序自动创建,位置固定为**主 CLI 文件所在目录的上一级目录中的 `skills` 子目录**。
37
33
 
38
- ## Shell
39
- ```bash
40
- glmcode shell
41
- glmcode shell list
42
- glmcode run "echo hello"
34
+ npm 安装后通常是:
35
+
36
+ ```text
37
+ .../glmcode/
38
+ ├── src/
39
+ │ └── cli.js
40
+ └── skills/
41
+ ├── coding/
42
+ │ └── SKILL.md
43
+ └── git/
44
+ └── SKILL.md
43
45
  ```
44
46
 
45
- 0.1.6 不再假定 `termux-open-url` 一定存在;Windows、macOS、Linux/Alpine/Android 环境分别检测可用启动器和 Shell。
47
+ 程序启动时自动创建 `skills/`,然后只检测这个目录的**直接子目录**;每个子目录中的 `SKILL.md` 会注册成一个斜杠命令,例如 `/coding`。
46
48
 
47
- ## 配置
48
- 配置:`~/.glmcode/config.json`
49
- 认证:`~/.glmcode/auth.json`
49
+ AI 可调用:
50
50
 
51
- ```bash
52
- glmcode config
53
- glmcode config set model glm-4.5
54
- ```
51
+ - `run_shell`
52
+ - `read_file`
53
+ - `write_file`
54
+ - `use_skill`
55
55
 
56
- ## 开发
57
- ```bash
58
- npm run check
59
- npm pack
60
- ```
56
+ ## 跨平台
57
+
58
+ 根据实际系统选择 Windows CMD/PowerShell、macOS/Linux/Alpine/Android 可用 Shell;打开网页登录时不会强制依赖 `termux-open-url`。
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "glmcode",
3
- "version": "0.1.6",
4
- "description": "Cross-platform GLM CLI with local authentication and shell detection.",
3
+ "version": "0.1.8",
4
+ "description": "GLM coding agent CLI with shell tools, skills, streaming chat and slash-command completion.",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "glmcode": "src/cli.js",
@@ -9,10 +9,11 @@
9
9
  "gc": "src/cli.js"
10
10
  },
11
11
  "scripts": {
12
- "check": "node --check src/cli.js && node --check src/auth.js && node --check src/config.js && node --check src/shell.js"
12
+ "check": "node --check src/cli.js && npm pack --dry-run"
13
13
  },
14
14
  "files": [
15
15
  "src/",
16
+ "skills/",
16
17
  "README.md",
17
18
  "CHANGELOG.md",
18
19
  "LICENSE"
package/src/cli.js CHANGED
@@ -1,31 +1,230 @@
1
1
  #!/usr/bin/env node
2
- import {spawnSync} from "node:child_process";
3
- import {getApiKey,saveApiKey,clearAuth,login,maskKey} from "./auth.js";
4
- import {loadConfig,saveConfig} from "./config.js";
5
- import {shellInfo,availableShells} from "./shell.js";
6
- const VERSION="0.1.6";
7
- function help(){console.log(`GLMCode ${VERSION}
8
- Usage: glmcode [command]
9
- auth login [--no-browser] 检测 Key;没有则打开官方页面
10
- auth set <API_KEY> 保存 Key 到 ~/.glmcode/auth.json
11
- auth status 查看认证状态(Key 脱敏)
12
- auth logout 删除本地 Key
13
- shell 查看 OS/CPU/Shell
14
- shell list 列出可用 Shell
15
- run <command> 使用当前 Shell 执行命令
16
- config 查看配置
17
- config set <key> <value> 修改配置
18
- skills / plugins / mcp 查看对应配置
19
- --version 显示版本`);}
20
- function runShell(command){const s=shellInfo(),win=process.platform==="win32";const f=win?(s.shell==="powershell"||s.shell==="pwsh"?s.executable:process.env.ComSpec||"cmd.exe"):s.executable;const a=win?(s.shell==="powershell"||s.shell==="pwsh"?["-NoProfile","-Command",command]:["/d","/s","/c",command]):["-lc",command];const r=spawnSync(f,a,{stdio:"inherit"});process.exitCode=r.status??1;}
21
- function value(v){if(v==="true")return true;if(v==="false")return false;if(/^-?\d+(?:\.\d+)?$/.test(v))return Number(v);try{return JSON.parse(v);}catch{return v;}}
22
- const a=process.argv.slice(2);
23
- if(!a.length){const f=getApiKey();if(!f){console.log(`GLMCode ${VERSION}\n未检测到 API Key。运行 glmcode auth login。`);process.exitCode=1;}else{const c=loadConfig();console.log(`GLMCode ${VERSION}\nProvider: ${c.provider}\nModel: ${c.model}\nAPI Key: ${maskKey(f.apiKey)} (${f.source})\n认证检测成功。`);}}
24
- else if(a[0]==="--version"||a[0]==="-v")console.log(VERSION);
25
- else if(a[0]==="--help"||a[0]==="-h"||a[0]==="help")help();
26
- else if(a[0]==="auth"){const s=a[1]||"status";if(s==="login")login({noBrowser:a.includes("--no-browser")});else if(s==="set"){if(!a[2]){console.error("用法:glmcode auth set <API_KEY>");process.exitCode=2;}else console.log(`API Key 已保存到 ${saveApiKey(a[2])}`);}else if(s==="status"){const f=getApiKey();console.log(f?`API Key: ${maskKey(f.apiKey)}\n来源: ${f.source}`:"未检测到 API Key。");}else if(s==="logout"){clearAuth();console.log("本地 API Key 已删除。");}else help();}
27
- else if(a[0]==="shell"){if(a[1]==="list")console.log(availableShells().join("\n")||"未检测到额外 Shell");else{const s=shellInfo();console.log(`OS: ${s.os}\nArchitecture: ${s.architecture}\nShell: ${s.shell}\nExecutable: ${s.executable}`);}}
28
- else if(a[0]==="run"){if(!a[1]){console.error("用法:glmcode run <command>");process.exitCode=2;}else runShell(a.slice(1).join(" "));}
29
- else if(a[0]==="config"){const c=loadConfig();if(a[1]==="set"){if(!a[2]||a[3]===undefined){console.error("用法:glmcode config set <key> <value>");process.exitCode=2;}else{c[a[2]]=value(a.slice(3).join(" "));saveConfig(c);console.log(`已设置 ${a[2]}`);}}else console.log(JSON.stringify(c,null,2));}
30
- else if(["skills","plugins","mcp"].includes(a[0]))console.log(JSON.stringify(loadConfig()[a[0]],null,2));
31
- else{console.error(`未知命令:${a[0]}`);help();process.exitCode=2;}
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import readline from "node:readline";
6
+ import {spawnSync, spawn} from "node:child_process";
7
+ import {fileURLToPath} from "node:url";
8
+
9
+ const VERSION="0.1.8";
10
+ const BASE_URL="https://open.bigmodel.cn/api/paas/v4";
11
+ const API_KEYS_URL="https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys";
12
+ const HOME=os.homedir();
13
+ const DATA_DIR=path.join(HOME,".glmcode");
14
+ const AUTH_FILE=path.join(DATA_DIR,"auth.json");
15
+ const CONFIG_FILE=path.join(DATA_DIR,"config.json");
16
+ const PACKAGE_ROOT=path.resolve(path.dirname(new URL(import.meta.url).pathname),"..");
17
+ const MAIN_FILE_DIR=path.dirname(fileURLToPath(import.meta.url));
18
+ const SKILLS_DIR=process.env.GLM_SKILLS_DIR || path.join(PACKAGE_ROOT,"skills");
19
+
20
+ const C={reset:"\x1b[0m",dim:"\x1b[2m",bold:"\x1b[1m",cyan:"\x1b[36m",cyanB:"\x1b[1;36m",green:"\x1b[32m",yellow:"\x1b[33m",red:"\x1b[31m",mag:"\x1b[35m",gray:"\x1b[90m"};
21
+ const color=(s,c)=>c+s+C.reset;
22
+
23
+ const DEFAULT_CONFIG={
24
+ provider:"zhipu", model:"glm-5.2", freeModel:"glm-5.2", baseUrl:BASE_URL,
25
+ maxTokens:4096, temperature:0.7, thinking:false, approval:"ask",
26
+ autoCompact:true, skillsDirs:[], plugins:[], mcp:{}, startupCommand:"", autoOpenLogin:true
27
+ };
28
+
29
+ let config={...DEFAULT_CONFIG};
30
+ let apiKey=null, messages=[], cwd=process.cwd(), thinkingEnabled=false, skills=new Map();
31
+ let stopping=false;
32
+
33
+ function readJson(file,fallback={}){try{return JSON.parse(fs.readFileSync(file,"utf8"));}catch{return fallback;}}
34
+ function saveJson(file,v){fs.mkdirSync(DATA_DIR,{recursive:true,mode:0o700});fs.writeFileSync(file,JSON.stringify(v,null,2)+"\n",{mode:0o600});try{fs.chmodSync(file,0o600);}catch{}}
35
+ function loadAuth(){
36
+ const env=(process.env.ZHIPU_API_KEY||process.env.GLM_API_KEY||"").trim();
37
+ if(env)return {key:env,source:"environment"};
38
+ const a=readJson(AUTH_FILE,{});
39
+ const k=(a.apiKey||a.api_key||a.key||a.token||"").trim();
40
+ return k?{key:k,source:AUTH_FILE}:null;
41
+ }
42
+ function mask(k){return k&&k.length>8?`${k.slice(0,4)}...${k.slice(-4)}`:"********";}
43
+ function loadConfig(){config={...DEFAULT_CONFIG,...readJson(CONFIG_FILE,{})};thinkingEnabled=!!config.thinking;}
44
+ function saveConfig(){saveJson(CONFIG_FILE,config);}
45
+ function shellInfo(){
46
+ if(process.platform==="win32"){
47
+ const p=process.env.PWSH||process.env.POWERSHELL;
48
+ return p?{name:"powershell",exe:p}:{name:"cmd",exe:process.env.ComSpec||"cmd.exe"};
49
+ }
50
+ const exe=process.env.SHELL||"/bin/sh"; return {name:path.basename(exe),exe};
51
+ }
52
+ function commandExists(c){try{spawnSync(process.platform==="win32"?"where":"which",[c],{stdio:"ignore"});return true;}catch{return false;}}
53
+ function openUrl(url){
54
+ const c=process.platform==="win32"?[["cmd",["/c","start","",url]]]:
55
+ process.platform==="darwin"?[["open",[url]]]:
56
+ [["xdg-open",[url]],["termux-open-url",[url]],["gio",["open",url]]];
57
+ for(const [cmd,args] of c){if(!commandExists(cmd))continue;try{const p=spawn(cmd,args,{detached:true,stdio:"ignore"});p.unref();return true;}catch{}}
58
+ return false;
59
+ }
60
+
61
+ function loadSkills(){
62
+ skills=new Map(); fs.mkdirSync(SKILLS_DIR,{recursive:true});
63
+ for(const entry of fs.readdirSync(SKILLS_DIR,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name))){
64
+ if(!entry.isDirectory())continue;
65
+ const file=path.join(SKILLS_DIR,entry.name,"SKILL.md"); if(!fs.existsSync(file))continue;
66
+ const content=fs.readFileSync(file,"utf8");
67
+ let name=entry.name, description="";
68
+ const fm=content.match(/^---\s*\n([\s\S]*?)\n---\s*\n/);
69
+ if(fm){const n=fm[1].match(/^name:\s*(.+)$/m),d=fm[1].match(/^description:\s*(.+)$/m);if(n)name=n[1].trim();if(d)description=d[1].trim();}
70
+ if(!description)description=(content.trim().split("\n")[0]||name).replace(/^#\s*/,"").slice(0,60);
71
+ skills.set(name,{name,description,content});
72
+ }
73
+ }
74
+ const BASE_COMMANDS={
75
+ "/help":"显示全部命令","/clear":"清空对话","/thinking":"切换思考模式(开/关)",
76
+ "/model":"切换模型 /model <ID>","/pwd":"显示当前目录","/cd":"切换目录 /cd <路径>",
77
+ "/ls":"列出文件","/cat":"查看文件 /cat <路径>","/run":"执行命令 /run <shell>","/install":"安装程序/依赖 /install <程序>","/exit":"退出"
78
+ };
79
+ function commands(){const d={...BASE_COMMANDS};for(const s of skills.values())d["/"+s.name]="技能: "+s.description;return d;}
80
+
81
+ function systemPrompt(){
82
+ let s="你是 GLMCode,一个运行在用户本机终端中的 coding agent。你可以使用 run_shell、write_file、read_file 和 use_skill 工具。回答简洁,执行任务时先理解当前工作目录。";
83
+ if(skills.size){s+="\n可用技能:\n";for(const x of skills.values())s+=`- ${x.name}: ${x.description}\n`;}
84
+ return s;
85
+ }
86
+ const TOOLS=[
87
+ {type:"function",function:{name:"run_shell",description:"在当前操作系统的用户 Shell 中执行命令并返回输出,限时60秒。",
88
+ parameters:{type:"object",properties:{command:{type:"string"}},required:["command"]}}},
89
+ {type:"function",function:{name:"write_file",description:"写入文本文件并自动创建父目录。",
90
+ parameters:{type:"object",properties:{path:{type:"string"},content:{type:"string"}},required:["path","content"]}}},
91
+ {type:"function",function:{name:"read_file",description:"读取文本文件内容。",
92
+ parameters:{type:"object",properties:{path:{type:"string"}},required:["path"]}}},
93
+ {type:"function",function:{name:"use_skill",description:"加载指定技能的 SKILL.md 并按其说明执行。",
94
+ parameters:{type:"object",properties:{skill_name:{type:"string"}},required:["skill_name"]}}}
95
+ ];
96
+
97
+ function execTool(name,args){
98
+ if(name==="run_shell"){
99
+ const s=shellInfo(), isWin=process.platform==="win32";
100
+ const file=isWin?s.exe:s.exe, a=isWin?(s.name==="powershell"?["-NoProfile","-Command",args.command]:["/d","/s","/c",args.command]):["-lc",args.command];
101
+ try{const r=spawnSync(file,a,{cwd,encoding:"utf8",timeout:60000});return ((r.stdout||"")+(r.stderr?"\n[stderr]\n"+r.stderr:"")).slice(0,8000)||"(无输出)";}
102
+ catch(e){return `执行失败: ${e.message}`;}
103
+ }
104
+ if(name==="write_file"){try{const p=path.resolve(cwd,args.path);fs.mkdirSync(path.dirname(p),{recursive:true});fs.writeFileSync(p,args.content);return `已写入 ${p}`;}catch(e){return `写入失败: ${e.message}`;}}
105
+ if(name==="read_file"){try{return fs.readFileSync(path.resolve(cwd,args.path),"utf8").slice(0,8000);}catch(e){return `读取失败: ${e.message}`;}}
106
+ if(name==="use_skill"){const s=skills.get(args.skill_name);return s?`技能已加载:${s.name}\n\n${s.content}`:`技能不存在:${args.skill_name}`;}
107
+ return "未知工具";
108
+ }
109
+
110
+ async function streamChat(){
111
+ const body={model:config.model,messages,stream:true,tools:TOOLS,
112
+ max_tokens:Number(config.maxTokens)||4096,temperature:Number(config.temperature)||0.7,
113
+ thinking:{type:thinkingEnabled?"enabled":"disabled"}};
114
+ let res;
115
+ try{res=await fetch(`${config.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json","Authorization":`Bearer ${apiKey}`},body:JSON.stringify(body)});}
116
+ catch(e){console.log(color(`\n[网络错误] ${e.message}`,C.red));return null;}
117
+ if(!res.ok){console.log(color(`\n[API错误 ${res.status}] ${(await res.text()).slice(0,500)}`,C.red));return null;}
118
+ let content="", calls=new Map();
119
+ console.log(color("\n◆ ",C.cyanB),{end:""});
120
+ const reader=res.body.getReader();let buf="";
121
+ while(true){
122
+ const {done,value}=await reader.read();if(done)break;
123
+ buf+=new TextDecoder().decode(value,{stream:true});
124
+ const lines=buf.split("\n");buf=lines.pop()||"";
125
+ for(let line of lines){
126
+ line=line.trim();if(!line.startsWith("data:"))continue;
127
+ const data=line.slice(5).trim();if(data==="[DONE]")continue;
128
+ try{
129
+ const d=JSON.parse(data).choices?.[0]?.delta||{};
130
+ if(d.reasoning_content&&thinkingEnabled)process.stdout.write(color(d.reasoning_content,C.gray));
131
+ if(d.content){content+=d.content;process.stdout.write(d.content);}
132
+ for(const tc of d.tool_calls||[]){
133
+ const i=tc.index??0;if(!calls.has(i))calls.set(i,{id:tc.id||"",name:"",arguments:""});
134
+ const x=calls.get(i);if(tc.function){x.name=tc.function.name||x.name;x.arguments+=tc.function.arguments||"";}
135
+ }
136
+ }catch{}
137
+ }
138
+ }
139
+ process.stdout.write("\n");
140
+ return {content,calls:[...calls.values()]};
141
+ }
142
+ async function chat(text){
143
+ if(!messages.length||messages[0].role!=="system")messages.unshift({role:"system",content:systemPrompt()});
144
+ messages.push({role:"user",content:text});
145
+ for(let n=0;n<8;n++){
146
+ const out=await streamChat();if(!out){messages.pop();return;}
147
+ if(!out.calls.length){if(out.content)messages.push({role:"assistant",content:out.content});return;}
148
+ messages.push({role:"assistant",content:out.content||null,tool_calls:out.calls.map(x=>({id:x.id,type:"function",function:{name:x.name,arguments:x.arguments}}))});
149
+ for(const t of out.calls){
150
+ let a={};try{a=JSON.parse(t.arguments||"{}");}catch{}
151
+ console.log(color(`[工具] ${t.name}`,C.gray));
152
+ const result=execTool(t.name,a);
153
+ messages.push({role:"tool",tool_call_id:t.id,content:result});
154
+ }
155
+ }
156
+ }
157
+ function handleCommand(line){
158
+ const [cmd,...rest]=line.trim().split(/\s+/), arg=rest.join(" ");
159
+ if(cmd.slice(1) && skills.has(cmd.slice(1))){const s=skills.get(cmd.slice(1));messages.push({role:"system",content:s.content});console.log(color(`已加载技能:${s.name}`,C.green));console.log(color("技能指令已注入,现在输入你的任务:",C.gray));return;}
160
+ if(cmd==="/help"){console.log("");for(const [c,d] of Object.entries(commands()))console.log(` ${color(c,C.cyanB).padEnd(24)} ${color(d,C.gray)}`);console.log("");}
161
+ else if(cmd==="/clear"){messages=[];console.log(color("已清空对话",C.green));}
162
+ else if(cmd==="/thinking"){thinkingEnabled=!thinkingEnabled;config.thinking=thinkingEnabled;saveConfig();console.log(color(`思考模式: ${thinkingEnabled?"开启":"关闭"}`,C.yellow));}
163
+ else if(cmd==="/model"){if(arg){config.model=arg;saveConfig();console.log(color(`模型已切换: ${arg}`,C.green));}else console.log(`当前模型: ${config.model}`);}
164
+ else if(cmd==="/pwd")console.log(cwd);
165
+ else if(cmd==="/cd"){try{cwd=path.resolve(cwd,arg||HOME);process.chdir(cwd);console.log(color(`-> ${cwd}`,C.green));}catch(e){console.log(color(`切换失败: ${e.message}`,C.red));}}
166
+ else if(cmd==="/ls"){try{for(const f of fs.readdirSync(cwd,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name)))console.log(` ${f.name}${f.isDirectory()?"/":""}`);}catch(e){console.log(color(e.message,C.red));}}
167
+ else if(cmd==="/cat"){try{console.log(fs.readFileSync(path.resolve(cwd,arg),"utf8").slice(0,8000));}catch(e){console.log(color(`失败: ${e.message}`,C.red));}}
168
+ else if(cmd==="/run"){if(!arg)console.log("用法: /run <命令>");else console.log(execTool("run_shell",{command:arg}));}
169
+ else if(cmd==="/install"){installProgram(arg)}
170
+ else if(cmd==="/exit"){console.log(color("再见",C.cyan));process.exit(0);}
171
+ else console.log(color(`未知命令: ${cmd}(输入 / 查看全部)`,C.red));
172
+ }
173
+
174
+ function logo(){
175
+ const rows=[" ██████╗ ██╗ ███╗ ███╗","██╔════╝ ██║ ████╗ ████║","██║ ███╗ ██║ ██╔████╔██║","██║ ██║ ██║ ██║╚██╔╝██║","╚██████╔╝ ███████╗ ██║ ╚═╝ ██║"," ╚═════╝ ╚══════╝ ╚═╝ ╚═╝"];
176
+ const W=44;console.log(color("".padStart(W),C.cyan));console.log(color("✧ GLM ✧".padStart((W+"✧ GLM ✧".length)/2),C.cyanB));for(const r of rows)console.log(color(r.padStart((W+r.length)/2),C.cyanB));console.log(color("GLM Code · Coding Agent",C.cyanB));console.log(color(`v${VERSION}`,C.gray));console.log(color("/help 查看命令 · /thinking 思考开关",C.gray));console.log("");
177
+ }
178
+ function toolbar(){return `思考:${thinkingEnabled?"开":"关"} 模型:${config.model} 技能:${skills.size} ${cwd}`;}
179
+ function completer(line){
180
+ if(!line.startsWith("/"))return [];
181
+ return Object.entries(commands()).filter(([c])=>c.startsWith(line)).map(([c,d])=>`${c} — ${d}`);
182
+ }
183
+ function promptLoop(){
184
+ const rl=readline.createInterface({input:process.stdin,output:process.stdout,completer:(line)=>{const x=completer(line);return [x,x.map(v=>v.split(" — ")[0])];}});
185
+ rl.setPrompt(color("┃ 输入消息... ┃ ",C.cyanB));rl.prompt();
186
+ rl.on("line",async line=>{
187
+ const text=line.trim();if(!text){rl.prompt();return;}
188
+ if(text.startsWith("/"))handleCommand(text);else{rl.pause();await chat(text);rl.resume();}
189
+ console.log(color(toolbar(),C.gray));rl.prompt();
190
+ });
191
+ rl.on("SIGINT",()=>{if(stopping){rl.close();process.exit(0);}stopping=true;console.log(color("\n[再次 Ctrl+C 退出]",C.yellow));setTimeout(()=>stopping=false,1200);rl.prompt();});
192
+ rl.on("close",()=>process.exit(0));
193
+ }
194
+
195
+
196
+ function detectInstaller(){
197
+ if(process.platform==="win32")return "winget";
198
+ if(process.platform==="darwin")return "brew";
199
+ for(const pm of ["apk","apt-get","apt","dnf","pacman","pkg"]){
200
+ if(spawnSync("sh",["-lc",`command -v ${pm}`],{encoding:"utf8"}).status===0)return pm;
201
+ }
202
+ return null;
203
+ }
204
+ function installProgram(name){
205
+ if(!name){console.log(color("用法: /install <程序>",C.yellow));return;}
206
+ const pm=detectInstaller();
207
+ if(!pm){console.log(color("未检测到可用的软件包管理器",C.red));return;}
208
+ const q={apk:`apk add ${name}`,"apt-get":`apt-get install -y ${name}`,apt:`apt install -y ${name}`,dnf:`dnf install -y ${name}`,pacman:`pacman -S --noconfirm ${name}`,pkg:`pkg install -y ${name}`,brew:`brew install ${name}`,winget:`winget install ${name}`}[pm];
209
+ console.log(color(`[安装] ${pm}: ${q}`,C.gray));
210
+ const r=spawnSync(q,{shell:true,stdio:"inherit",cwd:process.cwd()});
211
+ console.log(r.status===0?color("安装完成",C.green):color(`安装失败: ${r.status}`,C.red));
212
+ }
213
+ async function main(){
214
+ loadConfig();const a=loadAuth();if(!a){console.log(color("未检测到 GLM API Key。",C.red));console.log(`API Key 页面: ${API_KEYS_URL}`);console.log("获得 Key 后运行: glmcode auth set <API_KEY>");process.exit(1);}
215
+ apiKey=a.key;loadSkills();logo();console.log(color(`API: ${mask(apiKey)} (${a.source})`,C.green));console.log(color(`模型: ${config.model} 技能: ${skills.size}`,C.gray));console.log("");
216
+ promptLoop();
217
+ }
218
+ const argv=process.argv.slice(2);
219
+ if(argv[0]==="--version"||argv[0]==="-v"){console.log(VERSION);process.exit(0);}
220
+ if(argv[0]==="--help"||argv[0]==="-h"){console.log(`GLMCode ${VERSION}
221
+ 启动: glmcode
222
+ 斜杠命令: /help /clear /thinking /model /pwd /cd /ls /cat /run /exit
223
+ 认证: glmcode auth set <API_KEY> | auth status | auth logout
224
+ Shell: glmcode shell | shell list`);process.exit(0);}
225
+ if(argv[0]==="auth"){const s=argv[1]||"status";if(s==="set"){if(!argv[2]){console.error("用法: glmcode auth set <API_KEY>");process.exit(2);}saveJson(AUTH_FILE,{provider:"zhipu",apiKey:argv[2],updatedAt:new Date().toISOString()});console.log(`API Key 已保存到 ${AUTH_FILE}`);}
226
+ else if(s==="status"){const a=loadAuth();console.log(a?`API Key: ${mask(a.key)}\n来源: ${a.source}`:"未检测到 API Key。");}
227
+ else if(s==="logout"){saveJson(AUTH_FILE,{});console.log("本地 API Key 已删除。");}
228
+ else if(s==="login"){console.log(`API Key 页面: ${API_KEYS_URL}`);if(openUrl(API_KEYS_URL))console.log("已尝试打开浏览器。");else console.log("当前环境无法自动打开浏览器。");}process.exit(0);}
229
+ if(argv[0]==="shell"){const s=shellInfo();if(argv[1]==="list"){const c=process.platform==="win32"?["cmd","powershell","pwsh"]:["sh","bash","zsh","fish","ash"];console.log(c.filter(commandExists).join("\n"));}else console.log(`OS: ${process.platform}\nArchitecture: ${process.arch}\nShell: ${s.name}\nExecutable: ${s.exe}`);process.exit(0);}
230
+ await main();
package/src/auth.js DELETED
@@ -1,62 +0,0 @@
1
- import fs from "node:fs";
2
- import os from "node:os";
3
- import path from "node:path";
4
- import { execFileSync, spawn } from "node:child_process";
5
-
6
- export const CONFIG_DIR = path.join(os.homedir(), ".glmcode");
7
- export const AUTH_FILE = path.join(CONFIG_DIR, "auth.json");
8
- export const API_KEYS_URL = "https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys";
9
-
10
- function readJson(file, fallback = {}) {
11
- try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return fallback; }
12
- }
13
- function writeJson(file, value) {
14
- fs.mkdirSync(CONFIG_DIR, {recursive:true, mode:0o700});
15
- fs.writeFileSync(file, JSON.stringify(value,null,2)+"\n", {mode:0o600});
16
- try { fs.chmodSync(file,0o600); } catch {}
17
- }
18
- function key(v) { const s = v == null ? "" : String(v).trim(); return s || null; }
19
-
20
- export function getApiKey() {
21
- const env = key(process.env.ZHIPU_API_KEY) || key(process.env.GLM_API_KEY);
22
- if (env) return {apiKey:env, source:"environment"};
23
- const a = readJson(AUTH_FILE,{});
24
- const saved = key(a.apiKey) || key(a.api_key) || key(a.key) || key(a.token);
25
- return saved ? {apiKey:saved, source:AUTH_FILE} : null;
26
- }
27
- export function saveApiKey(apiKey) {
28
- const k = key(apiKey);
29
- if (!k) throw new Error("API Key 不能为空");
30
- writeJson(AUTH_FILE,{provider:"zhipu",apiKey:k,updatedAt:new Date().toISOString()});
31
- return AUTH_FILE;
32
- }
33
- export function clearAuth() { writeJson(AUTH_FILE,{}); }
34
-
35
- function exists(cmd) {
36
- try { execFileSync(process.platform==="win32" ? "where" : "which",[cmd],{stdio:"ignore"}); return true; }
37
- catch { return false; }
38
- }
39
- export function openUrl(url) {
40
- const candidates = process.platform==="win32"
41
- ? [["cmd",["/c","start","",url]]]
42
- : process.platform==="darwin"
43
- ? [["open",[url]]]
44
- : [["xdg-open",[url]],["termux-open-url",[url]],["gio",["open",url]]];
45
- for (const [cmd,args] of candidates) {
46
- if (!exists(cmd)) continue;
47
- try { const p=spawn(cmd,args,{detached:true,stdio:"ignore"}); p.unref(); return true; } catch {}
48
- }
49
- return false;
50
- }
51
- export function login({noBrowser=false}={}) {
52
- const found=getApiKey();
53
- if (found) { console.log(`已检测到 API Key(来源:${found.source}),无需重新配置。`); return found; }
54
- console.log("未检测到 GLM API Key。");
55
- console.log(`API Key 管理页面:${API_KEYS_URL}`);
56
- if (!noBrowser && openUrl(API_KEYS_URL)) console.log("已尝试打开默认浏览器。");
57
- else console.log("当前环境无法自动打开浏览器,请手动复制上面的地址。");
58
- console.log("浏览器登录不会自动把网页中的 API Key 暴露给 CLI。");
59
- console.log("获得 Key 后运行:glmcode auth set <API_KEY>");
60
- return null;
61
- }
62
- export function maskKey(k) { return k && k.length>8 ? `${k.slice(0,4)}...${k.slice(-4)}` : "********"; }
package/src/config.js DELETED
@@ -1,8 +0,0 @@
1
- import fs from "node:fs";
2
- import os from "node:os";
3
- import path from "node:path";
4
- export const CONFIG_DIR=path.join(os.homedir(),".glmcode");
5
- export const CONFIG_FILE=path.join(CONFIG_DIR,"config.json");
6
- const defaults={provider:"zhipu",model:"glm-4.5",freeModel:"glm-4.5-air",baseUrl:"https://open.bigmodel.cn/api/paas/v4",maxTokens:4096,temperature:0.7,thinking:true,approval:"ask",autoCompact:true,skillsDirs:[],plugins:[],mcp:{},startupCommand:"",autoOpenLogin:true};
7
- export function loadConfig(){try{return {...defaults,...JSON.parse(fs.readFileSync(CONFIG_FILE,"utf8"))};}catch{return {...defaults};}}
8
- export function saveConfig(c){fs.mkdirSync(CONFIG_DIR,{recursive:true,mode:0o700});fs.writeFileSync(CONFIG_FILE,JSON.stringify(c,null,2)+"\n",{mode:0o600});}
package/src/shell.js DELETED
@@ -1,5 +0,0 @@
1
- import os from "node:os";
2
- import {execFileSync} from "node:child_process";
3
- function shell(){if(process.platform==="win32"){const p=process.env.PWSH||process.env.POWERSHELL;if(p)return{name:"powershell",executable:p};return{name:"cmd",executable:process.env.ComSpec||"cmd.exe"};}const e=process.env.SHELL||"/bin/sh";return{name:e.split("/").pop()||"sh",executable:e};}
4
- export function shellInfo(){const s=shell();return{os:process.platform,architecture:process.arch,shell:s.name,executable:s.executable};}
5
- export function availableShells(){const c=process.platform==="win32"?["cmd","powershell","pwsh"]:["sh","bash","zsh","fish","ash"];return c.filter(n=>{try{execFileSync(process.platform==="win32"?"where":"which",[n],{stdio:"ignore"});return true;}catch{return false;}});}