chatccc 0.1.0
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/LICENSE +201 -0
- package/README.md +106 -0
- package/bin/chatccc.js +7 -0
- package/package.json +40 -0
- package/src/cardkit.ts +158 -0
- package/src/cards.ts +170 -0
- package/src/config.ts +70 -0
- package/src/feishu-api.ts +244 -0
- package/src/index.ts +600 -0
- package/src/session.ts +429 -0
- package/src/shared.ts +185 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
# ChatCCC
|
|
2
|
+
|
|
3
|
+
**飞书聊天控制 Claude Code,未来支持 Cursor、Codex**
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 解决的核心痛点
|
|
8
|
+
|
|
9
|
+
传统的 Claude Code(尤其是使用第三方 API 的,如 DeepSeek),需要坐在电脑桌前才能用。**离开电脑就没法用了。**
|
|
10
|
+
|
|
11
|
+
ChatCCC 把 Claude Code 接入了飞书群聊:
|
|
12
|
+
|
|
13
|
+
- **手机上也能用 Claude Code** —— 在飞书群里发消息就等于在终端输入指令,Claude 的思考和回复会流式展示在群卡片里
|
|
14
|
+
- **多会话并行** —— 一个群就是一个 Claude 会话,完全隔离、互不干扰,并行工作效率更高
|
|
15
|
+
- **流式打字机效果** —— 体验丝滑,流式输出响应迅速
|
|
16
|
+
|
|
17
|
+
一句话:**在任何设备上打开飞书,就能让 Claude 帮你写代码、排查问题、分析项目。**
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## 怎么部署
|
|
22
|
+
|
|
23
|
+
### 1. 创建飞书应用
|
|
24
|
+
|
|
25
|
+
打开 [飞书开放平台](https://open.feishu.cn),创建一个**企业自建应用**。
|
|
26
|
+
|
|
27
|
+
**添加应用能力**:开启「机器人」功能。
|
|
28
|
+
|
|
29
|
+
**权限配置**(在「权限管理」中搜索并开通以下权限):
|
|
30
|
+
|
|
31
|
+
| 权限 | 用途 |
|
|
32
|
+
|------|------|
|
|
33
|
+
| `im:chat` | 创建和管理群聊 |
|
|
34
|
+
| `im:message` | 收发消息 |
|
|
35
|
+
| `im:message:send_as_bot` | 以机器人身份发消息 |
|
|
36
|
+
| `im:message.p2p_msg:readonly` | 读取私聊消息 |
|
|
37
|
+
| `im:message.group_msg:readonly` | 读取群聊消息 |
|
|
38
|
+
|
|
39
|
+
**事件订阅**(在「事件与回调」中):订阅 `im.message.receive_v1` 和 `card.action.trigger` 事件。
|
|
40
|
+
|
|
41
|
+
**发布版本**:配置完成后创建应用版本并发布(仅企业内部可用即可)。
|
|
42
|
+
|
|
43
|
+
### 2. 获取凭证
|
|
44
|
+
|
|
45
|
+
在飞书应用详情页的「凭证与基础信息」中,复制 **App ID** 和 **App Secret**。
|
|
46
|
+
|
|
47
|
+
### 3. 配置环境变量
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
cp .env.example .env
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
编辑 `.env`,填入上一步拿到的凭证:
|
|
54
|
+
|
|
55
|
+
```env
|
|
56
|
+
FEISHU_CLAUDER_APP_ID=cli_xxxxxxxxxxxx
|
|
57
|
+
FEISHU_CLAUDER_APP_SECRET=xxxxxxxxxxxxxxxxxxxxxxxxxx
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
可选的高级配置:
|
|
61
|
+
|
|
62
|
+
```env
|
|
63
|
+
# Claude 模型(见下方优先级说明)
|
|
64
|
+
CHATCCC_ANTHROPIC_MODEL=dashscope/deepseek-v4-pro-anthropic
|
|
65
|
+
|
|
66
|
+
# 思考深度,可选值: low | medium | high | max
|
|
67
|
+
CHATCCC_ANTHROPIC_EFFORT=max
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
**`CHATCCC_ANTHROPIC_MODEL` 优先级**:环境变量设置的值 > 代码内默认值 `dashscope/deepseek-v4-pro-anthropic`。不设或设为空白时自动使用默认模型。
|
|
71
|
+
|
|
72
|
+
**`CHATCCC_ANTHROPIC_EFFORT` 优先级**:环境变量设置的值 > 代码内默认值 `max`。
|
|
73
|
+
|
|
74
|
+
> **权限说明**:目前 ChatCCC 以 `bypassPermissions` 模式运行,即跳过所有权限确认、允许所有操作。后续会考虑引入细粒度权限控制,让你可以按需放行特定操作。
|
|
75
|
+
|
|
76
|
+
> **Linux 用户注意**:不能将项目装在 `/root` 目录下运行。
|
|
77
|
+
|
|
78
|
+
### 4. 安装依赖并启动
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
# 要求 Node.js >= 20
|
|
82
|
+
npm install
|
|
83
|
+
npm run dev
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
启动后机器人通过 WebSocket 连接飞书服务器,日志会写入 `logs/` 目录。
|
|
87
|
+
|
|
88
|
+
### 5. 开始使用
|
|
89
|
+
|
|
90
|
+
在飞书中找到你的机器人,发送 `/new`,机器人会自动创建一个群聊并把你的 Claude 会话绑定到该群。之后直接在群里发消息就能和 Claude 对话。
|
|
91
|
+
|
|
92
|
+
### 可用指令
|
|
93
|
+
|
|
94
|
+
| 指令 | 作用 |
|
|
95
|
+
|------|------|
|
|
96
|
+
| `/new` | 创建新的 Claude 会话(绑定一个新群聊) |
|
|
97
|
+
| `/stop` | 停止当前正在生成的回复 |
|
|
98
|
+
| `/status` | 查看当前会话的状态(轮数、模型、上下文 token 等) |
|
|
99
|
+
| `/cd` | 查看/切换工作目录 |
|
|
100
|
+
| `/restart` | 重启机器人进程 |
|
|
101
|
+
|
|
102
|
+
---
|
|
103
|
+
|
|
104
|
+
## 技术栈
|
|
105
|
+
|
|
106
|
+
TypeScript / Node.js >= 20 / tsx / Anthropic Claude Agent SDK / 飞书 WebSocket API / CardKit
|
package/bin/chatccc.js
ADDED
package/package.json
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "chatccc",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Feishu bot bridge for Claude Code",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.ts",
|
|
7
|
+
"bin": {
|
|
8
|
+
"chatccc": "./bin/chatccc.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"src/",
|
|
12
|
+
"bin/",
|
|
13
|
+
"package.json",
|
|
14
|
+
"README.md"
|
|
15
|
+
],
|
|
16
|
+
"scripts": {
|
|
17
|
+
"dev": "tsx --env-file=.env src/index.ts",
|
|
18
|
+
"chatccc": "tsx --env-file=.env src/index.ts",
|
|
19
|
+
"start": "tsx --env-file=.env src/index.ts",
|
|
20
|
+
"demo:bot-test": "tsx --env-file=.env demo/bot_test.ts",
|
|
21
|
+
"demo:bot-test:local": "tsx --env-file=.env demo/bot_test.ts --local",
|
|
22
|
+
"demo:create-group": "tsx --env-file=.env src/index.ts",
|
|
23
|
+
"demo:create-group:local": "tsx --env-file=.env src/index.ts --local",
|
|
24
|
+
"demo:permission-check": "tsx --env-file=.env demo/permission_check.ts"
|
|
25
|
+
},
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"@anthropic-ai/claude-agent-sdk": "^0.2.133",
|
|
28
|
+
"@larksuiteoapi/node-sdk": "^1.59.0",
|
|
29
|
+
"tsx": "^4.0.0",
|
|
30
|
+
"ws": "^8.18.0"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@types/node": "^20.0.0",
|
|
34
|
+
"@types/ws": "^8.18.1",
|
|
35
|
+
"typescript": "^5.0.0"
|
|
36
|
+
},
|
|
37
|
+
"engines": {
|
|
38
|
+
"node": ">=20"
|
|
39
|
+
}
|
|
40
|
+
}
|
package/src/cardkit.ts
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { BASE_URL, fileLog, ts } from "./config.ts";
|
|
2
|
+
|
|
3
|
+
// CardKit 是飞书的卡片流式更新 API,通过 cardElement.content 端点
|
|
4
|
+
// 对卡片上指定 element_id 的元素进行增量内容更新,实现打字机效果。
|
|
5
|
+
// 与普通卡片 PATCH 的区别:PATCH 是全量替换卡片 JSON,CardKit 是
|
|
6
|
+
// 由飞书客户端自行渲染增量文本,用户看到的是逐字出现的效果。
|
|
7
|
+
// 参考: https://open.feishu.cn/document/uYjLw4iNukDO6YDN4ITM4MjM
|
|
8
|
+
|
|
9
|
+
export async function createCardKitCard(token: string, cardJson: string): Promise<string> {
|
|
10
|
+
const body = JSON.stringify({ type: "card_json", data: cardJson });
|
|
11
|
+
const resp = await fetch(`${BASE_URL}/cardkit/v1/cards`, {
|
|
12
|
+
method: "POST",
|
|
13
|
+
headers: {
|
|
14
|
+
Authorization: `Bearer ${token}`,
|
|
15
|
+
"Content-Type": "application/json",
|
|
16
|
+
},
|
|
17
|
+
body,
|
|
18
|
+
});
|
|
19
|
+
const respText = await resp.text();
|
|
20
|
+
let data: { code: number; msg?: string; data?: { card_id?: string } };
|
|
21
|
+
try {
|
|
22
|
+
data = JSON.parse(respText);
|
|
23
|
+
} catch {
|
|
24
|
+
console.error(`[${ts()}] [CARDIKT] createCard: invalid JSON response (status=${resp.status}) body=${respText.slice(0, 500)}`);
|
|
25
|
+
fileLog.flush();
|
|
26
|
+
throw new Error(`CardKit create: invalid JSON response (status=${resp.status})`);
|
|
27
|
+
}
|
|
28
|
+
if (data.code !== 0) {
|
|
29
|
+
console.error(`[${ts()}] [CARDIKT] createCard FAIL: status=${resp.status} code=${data.code} msg="${data.msg}" body=${respText.slice(0, 500)}`);
|
|
30
|
+
fileLog.flush();
|
|
31
|
+
throw new Error(`CardKit create: [${data.code}] ${data.msg}`);
|
|
32
|
+
}
|
|
33
|
+
console.log(`[${ts()}] [CARDIKT] createCard OK cardId=${data.data?.card_id ?? "(none)"}`);
|
|
34
|
+
return data.data?.card_id ?? "";
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function setCardKitSettings(
|
|
38
|
+
token: string,
|
|
39
|
+
cardId: string,
|
|
40
|
+
settings: Record<string, unknown>,
|
|
41
|
+
sequence: number
|
|
42
|
+
): Promise<void> {
|
|
43
|
+
const resp = await fetch(`${BASE_URL}/cardkit/v1/cards/${cardId}/settings`, {
|
|
44
|
+
method: "PATCH",
|
|
45
|
+
headers: {
|
|
46
|
+
Authorization: `Bearer ${token}`,
|
|
47
|
+
"Content-Type": "application/json",
|
|
48
|
+
},
|
|
49
|
+
body: JSON.stringify({ settings: JSON.stringify(settings), sequence }),
|
|
50
|
+
});
|
|
51
|
+
const respText = await resp.text();
|
|
52
|
+
let data: { code: number; msg?: string };
|
|
53
|
+
try { data = JSON.parse(respText); } catch {
|
|
54
|
+
console.error(`[${ts()}] [CARDIKT] settings FAIL: invalid JSON cardId=${cardId} seq=${sequence} status=${resp.status}`);
|
|
55
|
+
fileLog.flush();
|
|
56
|
+
throw new Error(`CardKit settings: invalid JSON (status=${resp.status})`);
|
|
57
|
+
}
|
|
58
|
+
if (data.code !== 0) {
|
|
59
|
+
console.error(`[${ts()}] [CARDIKT] settings FAIL: cardId=${cardId} seq=${sequence} status=${resp.status} code=${data.code} msg="${data.msg}"`);
|
|
60
|
+
fileLog.flush();
|
|
61
|
+
throw new Error(`CardKit settings: [${data.code}] ${data.msg}`);
|
|
62
|
+
}
|
|
63
|
+
console.log(`[${ts()}] [CARDIKT] settings OK cardId=${cardId} seq=${sequence}`);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function streamCardKitElement(
|
|
67
|
+
token: string,
|
|
68
|
+
cardId: string,
|
|
69
|
+
elementId: string,
|
|
70
|
+
content: string,
|
|
71
|
+
sequence: number
|
|
72
|
+
): Promise<void> {
|
|
73
|
+
const resp = await fetch(
|
|
74
|
+
`${BASE_URL}/cardkit/v1/cards/${cardId}/elements/${elementId}/content`,
|
|
75
|
+
{
|
|
76
|
+
method: "PUT",
|
|
77
|
+
headers: {
|
|
78
|
+
Authorization: `Bearer ${token}`,
|
|
79
|
+
"Content-Type": "application/json",
|
|
80
|
+
},
|
|
81
|
+
body: JSON.stringify({ content, sequence }),
|
|
82
|
+
}
|
|
83
|
+
);
|
|
84
|
+
const respText = await resp.text();
|
|
85
|
+
let data: { code: number; msg?: string };
|
|
86
|
+
try { data = JSON.parse(respText); } catch {
|
|
87
|
+
console.error(`[${ts()}] [CARDIKT] streamElement FAIL: invalid JSON cardId=${cardId} element=${elementId} seq=${sequence} status=${resp.status}`);
|
|
88
|
+
fileLog.flush();
|
|
89
|
+
throw new Error(`CardKit stream: invalid JSON (status=${resp.status})`);
|
|
90
|
+
}
|
|
91
|
+
if (data.code !== 0) {
|
|
92
|
+
console.error(`[${ts()}] [CARDIKT] streamElement FAIL: cardId=${cardId} element=${elementId} seq=${sequence} status=${resp.status} code=${data.code} msg="${data.msg}"`);
|
|
93
|
+
fileLog.flush();
|
|
94
|
+
throw new Error(`CardKit stream: [${data.code}] ${data.msg}`);
|
|
95
|
+
}
|
|
96
|
+
// success log is intentionally sparse — uncomment to debug streaming throughput
|
|
97
|
+
// console.log(`[${ts()}] [CARDIKT] streamElement OK cardId=${cardId} seq=${sequence}`);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export async function updateCardKitCard(
|
|
101
|
+
token: string,
|
|
102
|
+
cardId: string,
|
|
103
|
+
cardJson: string,
|
|
104
|
+
sequence: number
|
|
105
|
+
): Promise<void> {
|
|
106
|
+
const resp = await fetch(`${BASE_URL}/cardkit/v1/cards/${cardId}`, {
|
|
107
|
+
method: "PUT",
|
|
108
|
+
headers: {
|
|
109
|
+
Authorization: `Bearer ${token}`,
|
|
110
|
+
"Content-Type": "application/json",
|
|
111
|
+
},
|
|
112
|
+
body: JSON.stringify({ card: { type: "card_json", data: cardJson }, sequence }),
|
|
113
|
+
});
|
|
114
|
+
const respText = await resp.text();
|
|
115
|
+
let data: { code: number; msg?: string };
|
|
116
|
+
try { data = JSON.parse(respText); } catch {
|
|
117
|
+
console.error(`[${ts()}] [CARDIKT] updateCard FAIL: invalid JSON cardId=${cardId} seq=${sequence} status=${resp.status}`);
|
|
118
|
+
fileLog.flush();
|
|
119
|
+
throw new Error(`CardKit update: invalid JSON (status=${resp.status})`);
|
|
120
|
+
}
|
|
121
|
+
if (data.code !== 0) {
|
|
122
|
+
console.error(`[${ts()}] [CARDIKT] updateCard FAIL: cardId=${cardId} seq=${sequence} status=${resp.status} code=${data.code} msg="${data.msg}"`);
|
|
123
|
+
fileLog.flush();
|
|
124
|
+
throw new Error(`CardKit update: [${data.code}] ${data.msg}`);
|
|
125
|
+
}
|
|
126
|
+
console.log(`[${ts()}] [CARDIKT] updateCard OK cardId=${cardId} seq=${sequence}`);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export async function sendCardKitMessage(
|
|
130
|
+
token: string,
|
|
131
|
+
chatId: string,
|
|
132
|
+
cardId: string
|
|
133
|
+
): Promise<string> {
|
|
134
|
+
const payload = { receive_id: chatId, msg_type: "interactive", content: JSON.stringify({ type: "card", data: { card_id: cardId } }) };
|
|
135
|
+
const url = `${BASE_URL}/im/v1/messages?receive_id_type=chat_id`;
|
|
136
|
+
const resp = await fetch(url, {
|
|
137
|
+
method: "POST",
|
|
138
|
+
headers: {
|
|
139
|
+
Authorization: `Bearer ${token}`,
|
|
140
|
+
"Content-Type": "application/json",
|
|
141
|
+
},
|
|
142
|
+
body: JSON.stringify(payload),
|
|
143
|
+
});
|
|
144
|
+
const respText = await resp.text();
|
|
145
|
+
let data: { code: number; msg?: string; data?: { message_id?: string } };
|
|
146
|
+
try { data = JSON.parse(respText); } catch {
|
|
147
|
+
console.error(`[${ts()}] [CARDIKT] sendMessage FAIL: invalid JSON cardId=${cardId} chatId=${chatId} status=${resp.status}`);
|
|
148
|
+
fileLog.flush();
|
|
149
|
+
throw new Error(`sendCardKitMessage: invalid JSON (status=${resp.status})`);
|
|
150
|
+
}
|
|
151
|
+
if (data.code !== 0) {
|
|
152
|
+
console.error(`[${ts()}] [CARDIKT] sendMessage FAIL: status=${resp.status} code=${data.code} msg="${data.msg}" cardId=${cardId} chatId=${chatId}`);
|
|
153
|
+
fileLog.flush();
|
|
154
|
+
throw new Error(`[${data.code}] ${data.msg}`);
|
|
155
|
+
}
|
|
156
|
+
console.log(`[${ts()}] [CARDIKT] sendMessage OK cardId=${cardId} chatId=${chatId} msgId=${data.data?.message_id ?? "(none)"}`);
|
|
157
|
+
return data.data?.message_id ?? "";
|
|
158
|
+
}
|
package/src/cards.ts
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// Button helpers
|
|
3
|
+
// ---------------------------------------------------------------------------
|
|
4
|
+
|
|
5
|
+
export interface ButtonDef {
|
|
6
|
+
text: string;
|
|
7
|
+
value: string;
|
|
8
|
+
type?: "primary" | "default" | "danger";
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function buildButtons(buttons: ButtonDef[]): object {
|
|
12
|
+
return {
|
|
13
|
+
tag: "action",
|
|
14
|
+
actions: buttons.map((b) => ({
|
|
15
|
+
tag: "button",
|
|
16
|
+
text: { tag: "plain_text", content: b.text },
|
|
17
|
+
type: b.type ?? "primary",
|
|
18
|
+
value: b.value,
|
|
19
|
+
})),
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// ---------------------------------------------------------------------------
|
|
24
|
+
// Content helpers
|
|
25
|
+
// ---------------------------------------------------------------------------
|
|
26
|
+
|
|
27
|
+
export function truncateContent(text: string, maxLines = 20, maxChars = 8000): string {
|
|
28
|
+
const lines = text.split("\n");
|
|
29
|
+
let displayText: string;
|
|
30
|
+
if (lines.length > maxLines) {
|
|
31
|
+
const firstLine = lines[0];
|
|
32
|
+
const lastLines = lines.slice(-(maxLines - 1)).join("\n");
|
|
33
|
+
displayText = firstLine + "\n...\n" + lastLines;
|
|
34
|
+
} else {
|
|
35
|
+
displayText = text;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (displayText.length > maxChars) {
|
|
39
|
+
displayText = "..." + displayText.slice(-maxChars);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return displayText;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function getToolEmoji(name: string): string {
|
|
46
|
+
const n = name.toLowerCase();
|
|
47
|
+
if (n.includes("read") || n.includes("cat")) return "\u{1F4D6}"; // 📖
|
|
48
|
+
if (n.includes("write")) return "\u{270D}\u{FE0F}"; // ✍️
|
|
49
|
+
if (n.includes("edit")) return "\u{270F}\u{FE0F}"; // ✏️
|
|
50
|
+
if (n.includes("grep") || n.includes("search")) return "\u{1F50E}"; // 🔎
|
|
51
|
+
if (n.includes("glob") || n.includes("find") || n.includes("ls")) return "\u{1F4C2}"; // 📂
|
|
52
|
+
if (n.includes("bash") || n.includes("shell") || n.includes("exec")) return "\u{1F5A5}\u{FE0F}"; // 🖥️
|
|
53
|
+
if (n.includes("websearch") || n.includes("web_search")) return "\u{1F310}"; // 🌐
|
|
54
|
+
if (n.includes("webfetch") || n.includes("web_fetch") || n.includes("fetch")) return "\u{1F4E5}"; // 📥
|
|
55
|
+
if (n.includes("todo") || n.includes("task")) return "\u{2705}"; // ✅
|
|
56
|
+
if (n.includes("agent")) return "\u{1F916}"; // 🤖
|
|
57
|
+
if (n.includes("notebook")) return "\u{1F4D3}"; // 📓
|
|
58
|
+
if (n.includes("ask") || n.includes("question")) return "\u{2753}"; // ❓
|
|
59
|
+
return "\u{1F527}"; // 🔧
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// ---------------------------------------------------------------------------
|
|
63
|
+
// Card builders
|
|
64
|
+
// ---------------------------------------------------------------------------
|
|
65
|
+
|
|
66
|
+
// CardKit schema 2.0 思考卡片(带停止按钮,支持打字机流式更新)
|
|
67
|
+
export function buildThinkingCardV2(
|
|
68
|
+
thinkingText: string,
|
|
69
|
+
opts: { showStop?: boolean; headerTitle?: string; headerTemplate?: string } = {}
|
|
70
|
+
): string {
|
|
71
|
+
const { showStop = true, headerTitle = "思考中...", headerTemplate = "blue" } = opts;
|
|
72
|
+
const elements: object[] = [
|
|
73
|
+
{ tag: "markdown", content: truncateContent(thinkingText), element_id: "main_content" },
|
|
74
|
+
];
|
|
75
|
+
if (showStop) {
|
|
76
|
+
elements.push({ tag: "hr" });
|
|
77
|
+
elements.push({
|
|
78
|
+
tag: "button",
|
|
79
|
+
text: { tag: "plain_text", content: "查看状态(/status)" },
|
|
80
|
+
type: "default",
|
|
81
|
+
value: { action: "status" },
|
|
82
|
+
element_id: "action_status",
|
|
83
|
+
});
|
|
84
|
+
elements.push({
|
|
85
|
+
tag: "button",
|
|
86
|
+
text: { tag: "plain_text", content: "停止生成(/stop)" },
|
|
87
|
+
type: "danger",
|
|
88
|
+
value: { action: "stop" },
|
|
89
|
+
element_id: "action_stop",
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
return JSON.stringify({
|
|
93
|
+
schema: "2.0",
|
|
94
|
+
config: {
|
|
95
|
+
update_multi: true,
|
|
96
|
+
streaming_mode: showStop,
|
|
97
|
+
},
|
|
98
|
+
header: {
|
|
99
|
+
template: headerTemplate,
|
|
100
|
+
title: { tag: "plain_text", content: headerTitle },
|
|
101
|
+
},
|
|
102
|
+
body: {
|
|
103
|
+
direction: "vertical",
|
|
104
|
+
elements,
|
|
105
|
+
},
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function buildHelpCard(userText: string): string {
|
|
110
|
+
return JSON.stringify({
|
|
111
|
+
config: { wide_screen_mode: true },
|
|
112
|
+
header: { template: "blue", title: { content: "ChatCCC", tag: "plain_text" } },
|
|
113
|
+
elements: [
|
|
114
|
+
{ tag: "div", text: { tag: "lark_md", content: `你发送了: ${userText}` } },
|
|
115
|
+
buildButtons([
|
|
116
|
+
{ text: "新建会话(/new)", value: JSON.stringify({ cmd: "new" }), type: "primary" },
|
|
117
|
+
{ text: "重启Chat CCC(/restart)", value: JSON.stringify({ cmd: "restart" }), type: "danger" },
|
|
118
|
+
{ text: "查看/切换工作路径(/cd)", value: JSON.stringify({ cmd: "cd" }), type: "default" },
|
|
119
|
+
]),
|
|
120
|
+
],
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// 工作路径内容(/cd 命令统一使用,返回 markdown 内容字符串)
|
|
125
|
+
export function buildCdContent(
|
|
126
|
+
dirPath: string,
|
|
127
|
+
entries: { name: string; isDir: boolean }[],
|
|
128
|
+
isUpdate: boolean,
|
|
129
|
+
maxFiles = 100
|
|
130
|
+
): string {
|
|
131
|
+
const display = entries.slice(0, maxFiles);
|
|
132
|
+
const overflow = entries.length > maxFiles ? `\n...(共 ${entries.length} 个条目,仅显示前 ${maxFiles} 个)` : "";
|
|
133
|
+
const listing = display.map(e => e.isDir ? `📁 ${e.name}/` : `📄 ${e.name}`).join("\n");
|
|
134
|
+
|
|
135
|
+
const statusLine = isUpdate
|
|
136
|
+
? `**工作路径已更新为:** \`${dirPath}\``
|
|
137
|
+
: `**当前工作路径:** \`${dirPath}\``;
|
|
138
|
+
|
|
139
|
+
return [
|
|
140
|
+
statusLine,
|
|
141
|
+
``,
|
|
142
|
+
`此路径持久化在配置文件中,仅影响**新建会话**的工作路径。`,
|
|
143
|
+
``,
|
|
144
|
+
`---`,
|
|
145
|
+
`**目录内容** (最多 ${maxFiles} 个):`,
|
|
146
|
+
listing,
|
|
147
|
+
overflow,
|
|
148
|
+
].join("\n");
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// 状态卡片(带关闭按钮)
|
|
152
|
+
export function buildStatusCard(statusText: string, template = "blue"): string {
|
|
153
|
+
return JSON.stringify({
|
|
154
|
+
config: { wide_screen_mode: true },
|
|
155
|
+
header: { template, title: { content: "会话状态", tag: "plain_text" } },
|
|
156
|
+
elements: [
|
|
157
|
+
{ tag: "div", text: { tag: "lark_md", content: statusText } },
|
|
158
|
+
{ tag: "hr" },
|
|
159
|
+
{
|
|
160
|
+
tag: "action",
|
|
161
|
+
actions: [{
|
|
162
|
+
tag: "button",
|
|
163
|
+
text: { tag: "plain_text", content: "收起" },
|
|
164
|
+
type: "default",
|
|
165
|
+
value: { action: "close" },
|
|
166
|
+
}],
|
|
167
|
+
},
|
|
168
|
+
],
|
|
169
|
+
});
|
|
170
|
+
}
|