chatccc 0.2.252 → 0.2.253
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 +1 -1
- package/bin/cccagent.mjs +12 -3
- package/bin/chatccc.mjs +15 -6
- package/deepccc-agent/os-prompts/darwin.md +8 -8
- package/deepccc-agent/os-prompts/linux.md +8 -8
- package/deepccc-agent/os-prompts/win32.md +11 -11
- package/deepccc-agent/package.json +65 -65
- package/dist/deepccc-agent/src/cli.js +634 -0
- package/dist/deepccc-agent/src/config.js +76 -0
- package/dist/deepccc-agent/src/context.js +348 -0
- package/dist/deepccc-agent/src/file-log.js +34 -0
- package/dist/deepccc-agent/src/file-tools.js +1208 -0
- package/dist/deepccc-agent/src/index.js +571 -0
- package/dist/deepccc-agent/src/permissions.js +170 -0
- package/dist/deepccc-agent/src/privacy.js +124 -0
- package/dist/deepccc-agent/src/proc-tree-kill.js +60 -0
- package/dist/deepccc-agent/src/progress/cards-helpers.js +70 -0
- package/dist/deepccc-agent/src/progress/reducer.js +102 -0
- package/dist/deepccc-agent/src/progress/terminal-renderer.js +264 -0
- package/dist/deepccc-agent/src/progress/view.js +30 -0
- package/dist/deepccc-agent/src/raw-stream-log.js +106 -0
- package/dist/deepccc-agent/src/session-search.js +276 -0
- package/dist/deepccc-agent/src/session-select.js +23 -0
- package/dist/deepccc-agent/src/sigint.js +26 -0
- package/dist/deepccc-agent/src/skills.js +178 -0
- package/dist/deepccc-agent/src/web-tools.js +246 -0
- package/dist/src/adapters/adapter-interface.js +19 -0
- package/dist/src/adapters/ccc-adapter.js +112 -0
- package/dist/src/adapters/claude-adapter.js +497 -0
- package/dist/src/adapters/claude-session-meta-store.js +92 -0
- package/dist/src/adapters/codex-adapter.js +279 -0
- package/dist/src/adapters/codex-session-meta-store.js +94 -0
- package/dist/src/adapters/cursor-adapter.js +491 -0
- package/dist/src/adapters/cursor-session-meta-store.js +116 -0
- package/dist/src/adapters/jsonl-stream.js +104 -0
- package/{src/adapters/proc-tree-kill.ts → dist/src/adapters/proc-tree-kill.js} +94 -97
- package/dist/src/adapters/raw-stream-log.js +106 -0
- package/dist/src/adapters/resource-monitor.js +113 -0
- package/dist/src/agent-activity.js +133 -0
- package/dist/src/agent-delegate-task-rpc.js +129 -0
- package/dist/src/agent-delegate-task.js +48 -0
- package/dist/src/agent-file-rpc.js +152 -0
- package/dist/src/agent-image-rpc.js +148 -0
- package/dist/src/agent-platform-routing.js +13 -0
- package/dist/src/agent-reload-config-rpc.js +23 -0
- package/dist/src/agent-rpc-body.js +87 -0
- package/dist/src/agent-stop-stuck.js +110 -0
- package/dist/src/card-action-routing.js +7 -0
- package/dist/src/card-plain-text.js +101 -0
- package/dist/src/cardkit.js +158 -0
- package/dist/src/cards.js +573 -0
- package/dist/src/chatgpt-subscription-rpc.js +18 -0
- package/dist/src/chatgpt-subscription.js +199 -0
- package/dist/src/chrome-devtools-guard.js +238 -0
- package/dist/src/claude-sdk-installer.js +249 -0
- package/dist/src/codex-reset-actions.js +143 -0
- package/dist/src/config-utils.js +149 -0
- package/dist/src/config.js +804 -0
- package/dist/src/cursor-usage.js +77 -0
- package/dist/src/exit-banner.js +28 -0
- package/dist/src/feishu-api.js +1404 -0
- package/dist/src/feishu-message-ingress.js +137 -0
- package/dist/src/feishu-platform.js +97 -0
- package/dist/src/format-message.js +252 -0
- package/dist/src/git-command.js +155 -0
- package/dist/src/im-skills.js +121 -0
- package/dist/src/index.js +833 -0
- package/dist/src/litellm-proxy.js +300 -0
- package/dist/src/orchestrator.js +2078 -0
- package/dist/src/package-root.js +26 -0
- package/dist/src/platform-adapter.js +7 -0
- package/dist/src/platform-startup.js +6 -0
- package/dist/src/privacy.js +100 -0
- package/dist/src/progress/reducer.js +102 -0
- package/dist/src/progress/terminal-renderer.js +264 -0
- package/dist/src/progress/view.js +30 -0
- package/dist/src/response-stall.js +14 -0
- package/dist/src/runtime-entry.js +13 -0
- package/dist/src/runtime-reload.js +19 -0
- package/dist/src/session-chat-binding.js +183 -0
- package/dist/src/session-name.js +7 -0
- package/dist/src/session.js +2144 -0
- package/dist/src/shared-prefix.js +16 -0
- package/dist/src/shared.js +493 -0
- package/dist/src/sim-agent.js +105 -0
- package/dist/src/sim-platform.js +142 -0
- package/dist/src/sim-store.js +231 -0
- package/dist/src/simplify.js +99 -0
- package/dist/src/startup-lifecycle.js +209 -0
- package/dist/src/stream-state.js +141 -0
- package/dist/src/terminal-error.js +100 -0
- package/dist/src/trace.js +50 -0
- package/dist/src/turn-cards.js +92 -0
- package/dist/src/update-command-guard.js +114 -0
- package/{src/web-ui.ts → dist/src/web-ui.js} +749 -823
- package/dist/src/wechat-platform.js +545 -0
- package/package.json +76 -74
- package/deepccc-agent/LICENSE +0 -201
- package/deepccc-agent/bin/deepccc.mjs +0 -26
- package/deepccc-agent/docs/cache-hit-rate-1.jpg +0 -0
- package/deepccc-agent/docs/cache-hit-rate-2.jpg +0 -0
- package/deepccc-agent/package-lock.json +0 -2027
- package/deepccc-agent/src/__tests__/chat-session.test.ts +0 -877
- package/deepccc-agent/src/__tests__/cli-json.test.ts +0 -49
- package/deepccc-agent/src/__tests__/config.test.ts +0 -34
- package/deepccc-agent/src/__tests__/context.test.ts +0 -341
- package/deepccc-agent/src/__tests__/file-tools.test.ts +0 -240
- package/deepccc-agent/src/__tests__/permissions.test.ts +0 -199
- package/deepccc-agent/src/__tests__/privacy.test.ts +0 -318
- package/deepccc-agent/src/__tests__/progress-reducer.test.ts +0 -121
- package/deepccc-agent/src/__tests__/session-search.test.ts +0 -262
- package/deepccc-agent/src/__tests__/session-select.test.ts +0 -116
- package/deepccc-agent/src/__tests__/sigint.test.ts +0 -56
- package/deepccc-agent/src/__tests__/skills.test.ts +0 -284
- package/deepccc-agent/src/__tests__/terminal-renderer.test.ts +0 -247
- package/deepccc-agent/src/__tests__/web-tools.test.ts +0 -220
- package/deepccc-agent/src/cli.ts +0 -682
- package/deepccc-agent/src/config.ts +0 -101
- package/deepccc-agent/src/context.ts +0 -465
- package/deepccc-agent/src/file-log.ts +0 -38
- package/deepccc-agent/src/file-tools.ts +0 -1493
- package/deepccc-agent/src/index.ts +0 -710
- package/deepccc-agent/src/permissions.ts +0 -226
- package/deepccc-agent/src/privacy.ts +0 -141
- package/deepccc-agent/src/proc-tree-kill.ts +0 -61
- package/deepccc-agent/src/progress/cards-helpers.ts +0 -76
- package/deepccc-agent/src/progress/reducer.ts +0 -113
- package/deepccc-agent/src/progress/terminal-renderer.ts +0 -294
- package/deepccc-agent/src/progress/view.ts +0 -77
- package/deepccc-agent/src/raw-stream-log.ts +0 -124
- package/deepccc-agent/src/session-search.ts +0 -370
- package/deepccc-agent/src/session-select.ts +0 -48
- package/deepccc-agent/src/sigint.ts +0 -50
- package/deepccc-agent/src/skills.ts +0 -205
- package/deepccc-agent/src/web-tools.ts +0 -313
- package/deepccc-agent/tsconfig.build.json +0 -13
- package/deepccc-agent/tsconfig.json +0 -13
- package/deepccc-agent/vitest.config.ts +0 -7
- package/src/__tests__/adapter-interface.test.ts +0 -152
- package/src/__tests__/agent-activity.test.ts +0 -86
- package/src/__tests__/agent-delegate-task-rpc.test.ts +0 -165
- package/src/__tests__/agent-image-rpc.test.ts +0 -34
- package/src/__tests__/agent-platform-routing.test.ts +0 -26
- package/src/__tests__/agent-reload-config-rpc.test.ts +0 -99
- package/src/__tests__/agent-rpc-body.test.ts +0 -42
- package/src/__tests__/builtin-chat-session.test.ts +0 -532
- package/src/__tests__/builtin-cli-json.test.ts +0 -39
- package/src/__tests__/builtin-config.test.ts +0 -26
- package/src/__tests__/builtin-context.test.ts +0 -319
- package/src/__tests__/builtin-file-tools.test.ts +0 -240
- package/src/__tests__/builtin-permissions.test.ts +0 -219
- package/src/__tests__/builtin-session-search.test.ts +0 -262
- package/src/__tests__/builtin-session-select.test.ts +0 -116
- package/src/__tests__/builtin-sigint.test.ts +0 -56
- package/src/__tests__/builtin-skills.test.ts +0 -284
- package/src/__tests__/builtin-web-tools.test.ts +0 -220
- package/src/__tests__/card-action-routing.test.ts +0 -18
- package/src/__tests__/card-plain-text.test.ts +0 -45
- package/src/__tests__/cardkit.test.ts +0 -60
- package/src/__tests__/cards.test.ts +0 -607
- package/src/__tests__/ccc-adapter.test.ts +0 -194
- package/src/__tests__/chatgpt-subscription-rpc.test.ts +0 -89
- package/src/__tests__/chatgpt-subscription.test.ts +0 -135
- package/src/__tests__/chrome-devtools-guard.test.ts +0 -165
- package/src/__tests__/claude-adapter.test.ts +0 -614
- package/src/__tests__/claude-raw-stream-log.test.ts +0 -96
- package/src/__tests__/claude-sdk-installer.test.ts +0 -285
- package/src/__tests__/codex-adapter.test.ts +0 -331
- package/src/__tests__/codex-raw-stream-log.test.ts +0 -170
- package/src/__tests__/codex-reset-actions.test.ts +0 -146
- package/src/__tests__/config-reload.test.ts +0 -284
- package/src/__tests__/config-sample.test.ts +0 -97
- package/src/__tests__/config-utils.test.ts +0 -40
- package/src/__tests__/config.test.ts +0 -395
- package/src/__tests__/crash-logging.test.ts +0 -360
- package/src/__tests__/cursor-adapter.test.ts +0 -890
- package/src/__tests__/cursor-session-meta-store.test.ts +0 -212
- package/src/__tests__/feishu-api.test.ts +0 -60
- package/src/__tests__/feishu-avatar.test.ts +0 -504
- package/src/__tests__/feishu-message-ingress.test.ts +0 -138
- package/src/__tests__/feishu-platform.test.ts +0 -75
- package/src/__tests__/fixtures/codex_simple_text.jsonl +0 -4
- package/src/__tests__/fixtures/codex_with_tool.jsonl +0 -6
- package/src/__tests__/fixtures/cursor_partial_only.jsonl +0 -5
- package/src/__tests__/fixtures/cursor_partial_with_final.jsonl +0 -13
- package/src/__tests__/fixtures/cursor_with_tool_call.jsonl +0 -12
- package/src/__tests__/format-message.test.ts +0 -316
- package/src/__tests__/git-command.test.ts +0 -288
- package/src/__tests__/im-skills.test.ts +0 -125
- package/src/__tests__/jsonl-stream.test.ts +0 -79
- package/src/__tests__/orchestrator.test.ts +0 -1268
- package/src/__tests__/package-files.test.ts +0 -24
- package/src/__tests__/platform-startup.test.ts +0 -19
- package/src/__tests__/privacy.test.ts +0 -198
- package/src/__tests__/proc-tree-kill.test.ts +0 -108
- package/src/__tests__/progress-reducer.test.ts +0 -121
- package/src/__tests__/raw-stream-log.test.ts +0 -106
- package/src/__tests__/response-stall.test.ts +0 -49
- package/src/__tests__/restart.test.ts +0 -232
- package/src/__tests__/session-ccc-config.test.ts +0 -66
- package/src/__tests__/session.test.ts +0 -3004
- package/src/__tests__/shared-prefix.test.ts +0 -36
- package/src/__tests__/sim-agent.test.ts +0 -174
- package/src/__tests__/sim-platform.test.ts +0 -93
- package/src/__tests__/sim-store.test.ts +0 -214
- package/src/__tests__/simplify.test.ts +0 -283
- package/src/__tests__/startup-lifecycle.test.ts +0 -231
- package/src/__tests__/stop-session.test.ts +0 -162
- package/src/__tests__/stream-state.test.ts +0 -164
- package/src/__tests__/terminal-error.test.ts +0 -54
- package/src/__tests__/terminal-renderer.test.ts +0 -247
- package/src/__tests__/update-command-guard.test.ts +0 -144
- package/src/__tests__/web-ui.test.ts +0 -438
- package/src/__tests__/wechat-platform.test.ts +0 -111
- package/src/adapters/adapter-interface.ts +0 -217
- package/src/adapters/ccc-adapter.ts +0 -150
- package/src/adapters/claude-adapter.ts +0 -673
- package/src/adapters/claude-session-meta-store.ts +0 -120
- package/src/adapters/codex-adapter.ts +0 -426
- package/src/adapters/codex-session-meta-store.ts +0 -131
- package/src/adapters/cursor-adapter.ts +0 -681
- package/src/adapters/cursor-session-meta-store.ts +0 -154
- package/src/adapters/jsonl-stream.ts +0 -157
- package/src/adapters/raw-stream-log.ts +0 -124
- package/src/adapters/resource-monitor.ts +0 -141
- package/src/agent-activity.ts +0 -175
- package/src/agent-delegate-task-rpc.ts +0 -153
- package/src/agent-delegate-task.ts +0 -91
- package/src/agent-file-rpc.ts +0 -172
- package/src/agent-image-rpc.ts +0 -168
- package/src/agent-platform-routing.ts +0 -28
- package/src/agent-reload-config-rpc.ts +0 -34
- package/src/agent-rpc-body.ts +0 -92
- package/src/agent-stop-stuck.ts +0 -129
- package/src/card-action-routing.ts +0 -14
- package/src/card-plain-text.ts +0 -108
- package/src/cardkit.ts +0 -179
- package/src/cards.ts +0 -684
- package/src/chatgpt-subscription-rpc.ts +0 -27
- package/src/chatgpt-subscription.ts +0 -299
- package/src/chrome-devtools-guard.ts +0 -318
- package/src/claude-sdk-installer.ts +0 -324
- package/src/codex-reset-actions.ts +0 -184
- package/src/config-utils.ts +0 -211
- package/src/config.ts +0 -1063
- package/src/cursor-usage.ts +0 -128
- package/src/exit-banner.ts +0 -33
- package/src/feishu-api.ts +0 -1616
- package/src/feishu-message-ingress.ts +0 -195
- package/src/feishu-platform.ts +0 -159
- package/src/format-message.ts +0 -293
- package/src/git-command.ts +0 -202
- package/src/im-skills.ts +0 -149
- package/src/index.ts +0 -1089
- package/src/litellm-proxy.ts +0 -374
- package/src/orchestrator.ts +0 -2543
- package/src/platform-adapter.ts +0 -70
- package/src/platform-startup.ts +0 -16
- package/src/privacy.ts +0 -118
- package/src/progress/reducer.ts +0 -113
- package/src/progress/terminal-renderer.ts +0 -294
- package/src/progress/view.ts +0 -77
- package/src/response-stall.ts +0 -28
- package/src/runtime-reload.ts +0 -34
- package/src/session-chat-binding.ts +0 -292
- package/src/session-name.ts +0 -8
- package/src/session.ts +0 -2659
- package/src/shared-prefix.ts +0 -29
- package/src/shared.ts +0 -552
- package/src/sim-agent.ts +0 -167
- package/src/sim-platform.ts +0 -177
- package/src/sim-store.ts +0 -317
- package/src/simplify.ts +0 -120
- package/src/startup-lifecycle.ts +0 -250
- package/src/stream-state.ts +0 -177
- package/src/terminal-error.ts +0 -129
- package/src/trace.ts +0 -51
- package/src/turn-cards.ts +0 -118
- package/src/update-command-guard.ts +0 -165
- package/src/wechat-platform.ts +0 -680
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { resolve } from "node:path";
|
|
2
|
+
import { resolveDefaultAgentTool } from "./config.js";
|
|
3
|
+
import { readUtf8JsonBody } from "./agent-rpc-body.js";
|
|
4
|
+
import { delegateAgentTask } from "./agent-delegate-task.js";
|
|
5
|
+
import { applySharedPrefix } from "./shared-prefix.js";
|
|
6
|
+
export const AGENT_DELEGATE_TASK_PATH = "/api/agent/delegate-task";
|
|
7
|
+
const MAX_REQUEST_BYTES = 128 * 1024;
|
|
8
|
+
const VALID_TOOLS = new Set(["claude", "cursor", "codex"]);
|
|
9
|
+
function jsonReply(res, status, data) {
|
|
10
|
+
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
|
|
11
|
+
res.end(JSON.stringify(data));
|
|
12
|
+
}
|
|
13
|
+
function stringValue(value) {
|
|
14
|
+
return typeof value === "string" ? value.trim() : "";
|
|
15
|
+
}
|
|
16
|
+
function normalizeOpenIds(payload) {
|
|
17
|
+
const explicitOpenId = stringValue(payload.open_id);
|
|
18
|
+
if (explicitOpenId)
|
|
19
|
+
return [explicitOpenId];
|
|
20
|
+
const rawOpenIds = Array.isArray(payload.open_ids) ? payload.open_ids : payload.openIds;
|
|
21
|
+
if (!Array.isArray(rawOpenIds))
|
|
22
|
+
return [];
|
|
23
|
+
return rawOpenIds
|
|
24
|
+
.filter((item) => typeof item === "string")
|
|
25
|
+
.map((item) => item.trim())
|
|
26
|
+
.filter(Boolean);
|
|
27
|
+
}
|
|
28
|
+
function promptFromPayload(payload) {
|
|
29
|
+
return stringValue(payload.prompt) || stringValue(payload.text) || stringValue(payload.message);
|
|
30
|
+
}
|
|
31
|
+
function validateTool(rawTool) {
|
|
32
|
+
const tool = stringValue(rawTool).toLowerCase() || resolveDefaultAgentTool();
|
|
33
|
+
if (!VALID_TOOLS.has(tool))
|
|
34
|
+
throw new Error(`unsupported tool: ${tool}`);
|
|
35
|
+
return tool;
|
|
36
|
+
}
|
|
37
|
+
function validateCwd(rawCwd) {
|
|
38
|
+
const cwd = stringValue(rawCwd);
|
|
39
|
+
if (!cwd)
|
|
40
|
+
throw new Error("cwd must be a non-empty string");
|
|
41
|
+
return resolve(cwd);
|
|
42
|
+
}
|
|
43
|
+
export async function handleAgentDelegateTaskRequest(req, res, platform) {
|
|
44
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
45
|
+
if (url.pathname !== AGENT_DELEGATE_TASK_PATH)
|
|
46
|
+
return false;
|
|
47
|
+
if (req.method !== "POST") {
|
|
48
|
+
jsonReply(res, 405, { ok: false, error: "Method not allowed" });
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
if (platform.kind !== "feishu") {
|
|
52
|
+
jsonReply(res, 409, { ok: false, error: "This endpoint currently only supports Feishu." });
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
let payload;
|
|
56
|
+
try {
|
|
57
|
+
payload = await readUtf8JsonBody(req, MAX_REQUEST_BYTES);
|
|
58
|
+
}
|
|
59
|
+
catch (err) {
|
|
60
|
+
jsonReply(res, 400, { ok: false, error: err.message || "Invalid JSON" });
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
let tool;
|
|
64
|
+
let cwd;
|
|
65
|
+
let promptText;
|
|
66
|
+
let promptNamePrefix;
|
|
67
|
+
let openIds;
|
|
68
|
+
try {
|
|
69
|
+
tool = validateTool(payload.tool);
|
|
70
|
+
cwd = validateCwd(payload.cwd);
|
|
71
|
+
const rawPrompt = promptFromPayload(payload);
|
|
72
|
+
if (!rawPrompt)
|
|
73
|
+
throw new Error("prompt must be a non-empty string");
|
|
74
|
+
const sharedPrefix = applySharedPrefix(rawPrompt);
|
|
75
|
+
promptText = sharedPrefix.text;
|
|
76
|
+
promptNamePrefix = sharedPrefix.body || rawPrompt;
|
|
77
|
+
openIds = normalizeOpenIds(payload);
|
|
78
|
+
if (openIds.length === 0)
|
|
79
|
+
throw new Error("open_id or openIds must include at least one user");
|
|
80
|
+
}
|
|
81
|
+
catch (err) {
|
|
82
|
+
jsonReply(res, 400, { ok: false, error: err.message });
|
|
83
|
+
return true;
|
|
84
|
+
}
|
|
85
|
+
try {
|
|
86
|
+
const result = await delegateAgentTask({
|
|
87
|
+
platform,
|
|
88
|
+
tool,
|
|
89
|
+
cwd,
|
|
90
|
+
promptText,
|
|
91
|
+
openIds,
|
|
92
|
+
chatNamePrefix: stringValue(payload.chat_name) || promptNamePrefix.slice(0, 10),
|
|
93
|
+
});
|
|
94
|
+
jsonReply(res, 200, {
|
|
95
|
+
ok: true,
|
|
96
|
+
chat_id: result.chatId,
|
|
97
|
+
session_id: result.sessionId,
|
|
98
|
+
tool: result.tool,
|
|
99
|
+
cwd: result.cwd,
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
catch (err) {
|
|
103
|
+
jsonReply(res, 500, { ok: false, error: err.message });
|
|
104
|
+
}
|
|
105
|
+
return true;
|
|
106
|
+
}
|
|
107
|
+
export function buildAgentDelegateTaskCapabilityPrompt(input) {
|
|
108
|
+
const lines = [
|
|
109
|
+
"[ChatCCC local capability: delegate task]",
|
|
110
|
+
"You can create a separate Feishu ChatCCC agent session and assign its first task by calling this local endpoint.",
|
|
111
|
+
"",
|
|
112
|
+
`POST ${input.url}`,
|
|
113
|
+
"Content-Type: application/json; charset=utf-8",
|
|
114
|
+
"",
|
|
115
|
+
'Body: {"tool":"codex|claude|cursor","cwd":"absolute working directory","open_id":"Feishu open_id to invite","prompt":"first task text"}',
|
|
116
|
+
"",
|
|
117
|
+
"Rules:",
|
|
118
|
+
"- Use this only when the user asks you to start a separate delegated conversation/session.",
|
|
119
|
+
"- Pass cwd explicitly as an absolute local path.",
|
|
120
|
+
"- Pass tool explicitly when the user specified a target agent.",
|
|
121
|
+
"- Use open_id for one user or open_ids/openIds for multiple users.",
|
|
122
|
+
"- The prompt is sent through the normal ChatCCC prompt path, so project prompt injection and IM skills still apply.",
|
|
123
|
+
"- Request body must be UTF-8 encoded JSON bytes. Do not call Feishu Open Platform directly.",
|
|
124
|
+
"[/ChatCCC local capability: delegate task]",
|
|
125
|
+
];
|
|
126
|
+
if (input.cwd)
|
|
127
|
+
lines.splice(2, 0, `Current working directory: ${input.cwd}`);
|
|
128
|
+
return lines.join("\n");
|
|
129
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { resolve } from "node:path";
|
|
2
|
+
import { sessionPrefixForTool, toolDisplayName, ts } from "./config.js";
|
|
3
|
+
import { setDefaultCwd } from "./config.js";
|
|
4
|
+
import { getEffectiveFastModeForTool, initClaudeSession, recordSessionRegistry, resumeAndPrompt, saveSessionTool, } from "./session.js";
|
|
5
|
+
import { bindChatToSession } from "./session-chat-binding.js";
|
|
6
|
+
import { sessionChatName } from "./session-name.js";
|
|
7
|
+
export async function delegateAgentTask(input) {
|
|
8
|
+
const cwd = resolve(input.cwd);
|
|
9
|
+
const toolLabel = toolDisplayName(input.tool);
|
|
10
|
+
const init = await initClaudeSession(input.tool, cwd);
|
|
11
|
+
const sessionId = init.sessionId;
|
|
12
|
+
const chatNamePrefix = input.chatNamePrefix?.trim() || input.promptText.slice(0, 10) || "新会话";
|
|
13
|
+
const chatName = sessionChatName(chatNamePrefix, cwd);
|
|
14
|
+
let chatId;
|
|
15
|
+
try {
|
|
16
|
+
chatId = await input.platform.createGroup(chatName, input.openIds);
|
|
17
|
+
await input.platform.updateChatInfo(chatId, chatName, `${sessionPrefixForTool(input.tool)} ${sessionId}`);
|
|
18
|
+
await setDefaultCwd(cwd, chatId);
|
|
19
|
+
bindChatToSession(sessionId, chatId);
|
|
20
|
+
await recordSessionRegistry({
|
|
21
|
+
chatId,
|
|
22
|
+
sessionId,
|
|
23
|
+
tool: input.tool,
|
|
24
|
+
chatType: "group",
|
|
25
|
+
chatName,
|
|
26
|
+
turnCount: 0,
|
|
27
|
+
startTime: Date.now(),
|
|
28
|
+
running: false,
|
|
29
|
+
});
|
|
30
|
+
await saveSessionTool(sessionId, input.tool, chatName);
|
|
31
|
+
}
|
|
32
|
+
catch (err) {
|
|
33
|
+
console.error(`[${ts()}] [AGENT-DELEGATE-TASK] create group failed: ${err.message}`);
|
|
34
|
+
throw err;
|
|
35
|
+
}
|
|
36
|
+
await input.platform.sendCard(chatId, `${toolLabel} Session Ready`, `已创建 **${toolLabel}** 会话群。\n\n` +
|
|
37
|
+
`**Session ID:** ${sessionId}\n` +
|
|
38
|
+
`**工作目录:** \`${cwd}\`\n\n` +
|
|
39
|
+
`下面会自动把任务作为第一句话发送给 ${toolLabel}。`, "green").catch(() => { });
|
|
40
|
+
const fastMode = getEffectiveFastModeForTool(input.tool, sessionId);
|
|
41
|
+
const avatarUpdate = fastMode
|
|
42
|
+
? input.platform.setChatAvatar(chatId, input.tool, "new", { fastMode: true })
|
|
43
|
+
: input.platform.setChatAvatar(chatId, input.tool, "new");
|
|
44
|
+
avatarUpdate.catch(() => { });
|
|
45
|
+
await resumeAndPrompt(sessionId, input.promptText, input.platform, chatId, input.msgTimestamp ?? Date.now(), input.tool, input.traceId);
|
|
46
|
+
console.log(`[${ts()}] [AGENT-DELEGATE-TASK] created ${toolLabel} session=${sessionId} chat=${chatId} cwd=${cwd}`);
|
|
47
|
+
return { chatId, sessionId, tool: input.tool, cwd };
|
|
48
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { extname, isAbsolute, resolve } from "node:path";
|
|
2
|
+
import { stat } from "node:fs/promises";
|
|
3
|
+
import { getTenantAccessToken, sendFileReply, sendTextReply } from "./feishu-platform.js";
|
|
4
|
+
import { ts, resolveDefaultAgentTool } from "./config.js";
|
|
5
|
+
import { readUtf8JsonBody } from "./agent-rpc-body.js";
|
|
6
|
+
import { getAdapterForTool } from "./session.js";
|
|
7
|
+
import { getChatsForSession } from "./session-chat-binding.js";
|
|
8
|
+
import { splitFeishuTargetChats } from "./agent-platform-routing.js";
|
|
9
|
+
export const AGENT_SEND_FILE_PATH = "/api/agent/send-file";
|
|
10
|
+
const MAX_REQUEST_BYTES = 64 * 1024;
|
|
11
|
+
const MAX_FILE_BYTES = 100 * 1024 * 1024;
|
|
12
|
+
const ALLOWED_FILE_EXTS = new Set([
|
|
13
|
+
".mp4", ".mov", ".avi", ".mkv", ".webm", ".flv",
|
|
14
|
+
".mp3", ".wav", ".ogg", ".aac", ".m4a",
|
|
15
|
+
".pdf", ".doc", ".docx", ".xls", ".xlsx", ".csv", ".ppt", ".pptx",
|
|
16
|
+
".txt", ".zip", ".tar", ".gz",
|
|
17
|
+
]);
|
|
18
|
+
function jsonReply(res, status, data) {
|
|
19
|
+
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
|
|
20
|
+
res.end(JSON.stringify(data));
|
|
21
|
+
}
|
|
22
|
+
async function resolveAndValidateFilePath(cwd, rawPath) {
|
|
23
|
+
if (typeof rawPath !== "string" || rawPath.trim() === "") {
|
|
24
|
+
throw new Error("path must be a non-empty string");
|
|
25
|
+
}
|
|
26
|
+
const sessionRoot = resolve(cwd);
|
|
27
|
+
const filePath = isAbsolute(rawPath)
|
|
28
|
+
? resolve(rawPath)
|
|
29
|
+
: resolve(sessionRoot, rawPath);
|
|
30
|
+
const ext = extname(filePath).toLowerCase();
|
|
31
|
+
if (!ALLOWED_FILE_EXTS.has(ext)) {
|
|
32
|
+
throw new Error(`unsupported file extension: ${ext || "(none)"}`);
|
|
33
|
+
}
|
|
34
|
+
const st = await stat(filePath);
|
|
35
|
+
if (!st.isFile())
|
|
36
|
+
throw new Error("file path is not a file");
|
|
37
|
+
if (st.size <= 0)
|
|
38
|
+
throw new Error("file is empty");
|
|
39
|
+
if (st.size > MAX_FILE_BYTES)
|
|
40
|
+
throw new Error("file is larger than 100MB");
|
|
41
|
+
return filePath;
|
|
42
|
+
}
|
|
43
|
+
export async function handleAgentFileRequest(req, res) {
|
|
44
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
45
|
+
if (url.pathname !== AGENT_SEND_FILE_PATH)
|
|
46
|
+
return false;
|
|
47
|
+
if (req.method !== "POST") {
|
|
48
|
+
jsonReply(res, 405, { ok: false, error: "Method not allowed" });
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
let payload;
|
|
52
|
+
try {
|
|
53
|
+
payload = await readUtf8JsonBody(req, MAX_REQUEST_BYTES);
|
|
54
|
+
}
|
|
55
|
+
catch (err) {
|
|
56
|
+
jsonReply(res, 400, { ok: false, error: err.message || "Invalid JSON" });
|
|
57
|
+
return true;
|
|
58
|
+
}
|
|
59
|
+
const sessionId = typeof payload.session_id === "string" ? payload.session_id : "";
|
|
60
|
+
if (!sessionId) {
|
|
61
|
+
jsonReply(res, 400, { ok: false, error: "Missing session_id" });
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
let cwd;
|
|
65
|
+
try {
|
|
66
|
+
const { getSessionTool } = await import("./session.js");
|
|
67
|
+
const tool = await getSessionTool(sessionId);
|
|
68
|
+
const adapter = getAdapterForTool(tool ?? resolveDefaultAgentTool());
|
|
69
|
+
const info = await adapter.getSessionInfo(sessionId);
|
|
70
|
+
if (!info?.cwd) {
|
|
71
|
+
jsonReply(res, 400, { ok: false, error: "Cannot determine cwd for session" });
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
cwd = info.cwd;
|
|
75
|
+
}
|
|
76
|
+
catch (err) {
|
|
77
|
+
jsonReply(res, 500, { ok: false, error: `Failed to get session info: ${err.message}` });
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
let filePath;
|
|
81
|
+
try {
|
|
82
|
+
filePath = await resolveAndValidateFilePath(cwd, payload.path);
|
|
83
|
+
}
|
|
84
|
+
catch (err) {
|
|
85
|
+
jsonReply(res, 400, { ok: false, error: err.message });
|
|
86
|
+
return true;
|
|
87
|
+
}
|
|
88
|
+
const chatIds = getChatsForSession(sessionId);
|
|
89
|
+
if (chatIds.length === 0) {
|
|
90
|
+
jsonReply(res, 404, { ok: false, error: "No chats bound to this session" });
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
93
|
+
const { getPlatformForChat } = await import("./session.js");
|
|
94
|
+
const { targetChatIds, skippedUnsupported } = splitFeishuTargetChats(chatIds, (cid) => getPlatformForChat(cid)?.kind);
|
|
95
|
+
if (targetChatIds.length === 0) {
|
|
96
|
+
jsonReply(res, 409, {
|
|
97
|
+
ok: false,
|
|
98
|
+
error: "This endpoint only sends to Feishu chats. The bound chats are WeChat chats; use the WeChat file or video helper script instead.",
|
|
99
|
+
skippedUnsupported,
|
|
100
|
+
});
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
try {
|
|
104
|
+
const token = await getTenantAccessToken();
|
|
105
|
+
const caption = typeof payload.caption === "string" ? payload.caption.trim() : "";
|
|
106
|
+
let sentCount = 0;
|
|
107
|
+
for (const cid of targetChatIds) {
|
|
108
|
+
try {
|
|
109
|
+
await sendFileReply(token, cid, filePath);
|
|
110
|
+
if (caption)
|
|
111
|
+
await sendTextReply(token, cid, caption);
|
|
112
|
+
sentCount++;
|
|
113
|
+
}
|
|
114
|
+
catch (err) {
|
|
115
|
+
console.error(`[${ts()}] [AGENT-FILE] send to ${cid} failed: ${err.message}`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
console.log(`[${ts()}] [AGENT-FILE] sent file to ${sentCount}/${targetChatIds.length} Feishu chats, session=${sessionId} path=${filePath} skippedUnsupported=${skippedUnsupported.length}`);
|
|
119
|
+
jsonReply(res, 200, { ok: true, sentTo: sentCount, total: targetChatIds.length, skippedUnsupported });
|
|
120
|
+
}
|
|
121
|
+
catch (err) {
|
|
122
|
+
console.error(`[${ts()}] [AGENT-FILE] send failed: ${err.message}`);
|
|
123
|
+
jsonReply(res, 500, { ok: false, error: err.message });
|
|
124
|
+
}
|
|
125
|
+
return true;
|
|
126
|
+
}
|
|
127
|
+
// ---------------------------------------------------------------------------
|
|
128
|
+
// 兼容旧版 buildAgentFileCapabilityPrompt(供 im-skills 使用)
|
|
129
|
+
// ---------------------------------------------------------------------------
|
|
130
|
+
export function buildAgentFileCapabilityPrompt(input) {
|
|
131
|
+
const lines = [
|
|
132
|
+
"[ChatCCC local capability: send file]",
|
|
133
|
+
"You can send a file (video, audio, document, etc.) to all chats bound to this session by calling this local endpoint.",
|
|
134
|
+
"",
|
|
135
|
+
`POST ${input.url}`,
|
|
136
|
+
"Content-Type: application/json; charset=utf-8",
|
|
137
|
+
"",
|
|
138
|
+
`Body: {"session_id":"${input.sessionId ?? "YOUR_SESSION_ID"}","path":"absolute file path","caption":"optional caption"}`,
|
|
139
|
+
"",
|
|
140
|
+
"Rules:",
|
|
141
|
+
"- Save or choose a local file first, then call the endpoint.",
|
|
142
|
+
"- Use an absolute local file path. Do not call Feishu Open Platform directly.",
|
|
143
|
+
"- Request body must be UTF-8 encoded JSON bytes; caption supports Unicode text, including Chinese.",
|
|
144
|
+
"- Only call this endpoint when the user asked for a file/video or when a file is useful to the answer.",
|
|
145
|
+
"- Max file size: 100MB.",
|
|
146
|
+
"[/ChatCCC local capability: send file]",
|
|
147
|
+
];
|
|
148
|
+
if (input.cwd) {
|
|
149
|
+
lines.splice(2, 0, `Current working directory: ${input.cwd}`);
|
|
150
|
+
}
|
|
151
|
+
return lines.join("\n");
|
|
152
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { extname, isAbsolute, resolve } from "node:path";
|
|
2
|
+
import { stat } from "node:fs/promises";
|
|
3
|
+
import { getTenantAccessToken, sendImageReply, sendTextReply } from "./feishu-platform.js";
|
|
4
|
+
import { ts, resolveDefaultAgentTool } from "./config.js";
|
|
5
|
+
import { readUtf8JsonBody } from "./agent-rpc-body.js";
|
|
6
|
+
import { getAdapterForTool } from "./session.js";
|
|
7
|
+
import { getChatsForSession } from "./session-chat-binding.js";
|
|
8
|
+
import { splitFeishuTargetChats } from "./agent-platform-routing.js";
|
|
9
|
+
export const AGENT_SEND_IMAGE_PATH = "/api/agent/send-image";
|
|
10
|
+
const MAX_REQUEST_BYTES = 64 * 1024;
|
|
11
|
+
const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
|
|
12
|
+
const ALLOWED_IMAGE_EXTS = new Set([".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp"]);
|
|
13
|
+
function jsonReply(res, status, data) {
|
|
14
|
+
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
|
|
15
|
+
res.end(JSON.stringify(data));
|
|
16
|
+
}
|
|
17
|
+
async function resolveAndValidateImagePath(cwd, rawPath) {
|
|
18
|
+
if (typeof rawPath !== "string" || rawPath.trim() === "") {
|
|
19
|
+
throw new Error("path must be a non-empty string");
|
|
20
|
+
}
|
|
21
|
+
const sessionRoot = resolve(cwd);
|
|
22
|
+
const imagePath = isAbsolute(rawPath)
|
|
23
|
+
? resolve(rawPath)
|
|
24
|
+
: resolve(sessionRoot, rawPath);
|
|
25
|
+
const ext = extname(imagePath).toLowerCase();
|
|
26
|
+
if (!ALLOWED_IMAGE_EXTS.has(ext)) {
|
|
27
|
+
throw new Error(`unsupported image extension: ${ext || "(none)"}`);
|
|
28
|
+
}
|
|
29
|
+
const st = await stat(imagePath);
|
|
30
|
+
if (!st.isFile())
|
|
31
|
+
throw new Error("image path is not a file");
|
|
32
|
+
if (st.size <= 0)
|
|
33
|
+
throw new Error("image file is empty");
|
|
34
|
+
if (st.size > MAX_IMAGE_BYTES)
|
|
35
|
+
throw new Error("image file is larger than 10MB");
|
|
36
|
+
return imagePath;
|
|
37
|
+
}
|
|
38
|
+
export async function handleAgentImageRequest(req, res) {
|
|
39
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
40
|
+
if (url.pathname !== AGENT_SEND_IMAGE_PATH)
|
|
41
|
+
return false;
|
|
42
|
+
if (req.method !== "POST") {
|
|
43
|
+
jsonReply(res, 405, { ok: false, error: "Method not allowed" });
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
let payload;
|
|
47
|
+
try {
|
|
48
|
+
payload = await readUtf8JsonBody(req, MAX_REQUEST_BYTES);
|
|
49
|
+
}
|
|
50
|
+
catch (err) {
|
|
51
|
+
jsonReply(res, 400, { ok: false, error: err.message || "Invalid JSON" });
|
|
52
|
+
return true;
|
|
53
|
+
}
|
|
54
|
+
const sessionId = typeof payload.session_id === "string" ? payload.session_id : "";
|
|
55
|
+
if (!sessionId) {
|
|
56
|
+
jsonReply(res, 400, { ok: false, error: "Missing session_id" });
|
|
57
|
+
return true;
|
|
58
|
+
}
|
|
59
|
+
// 获取 cwd 以校验路径
|
|
60
|
+
let cwd;
|
|
61
|
+
try {
|
|
62
|
+
const { getSessionTool } = await import("./session.js");
|
|
63
|
+
const tool = await getSessionTool(sessionId);
|
|
64
|
+
const adapter = getAdapterForTool(tool ?? resolveDefaultAgentTool());
|
|
65
|
+
const info = await adapter.getSessionInfo(sessionId);
|
|
66
|
+
if (!info?.cwd) {
|
|
67
|
+
jsonReply(res, 400, { ok: false, error: "Cannot determine cwd for session" });
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
cwd = info.cwd;
|
|
71
|
+
}
|
|
72
|
+
catch (err) {
|
|
73
|
+
jsonReply(res, 500, { ok: false, error: `Failed to get session info: ${err.message}` });
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
let imagePath;
|
|
77
|
+
try {
|
|
78
|
+
imagePath = await resolveAndValidateImagePath(cwd, payload.path);
|
|
79
|
+
}
|
|
80
|
+
catch (err) {
|
|
81
|
+
jsonReply(res, 400, { ok: false, error: err.message });
|
|
82
|
+
return true;
|
|
83
|
+
}
|
|
84
|
+
// 发送到所有绑定该 session 的群
|
|
85
|
+
const chatIds = getChatsForSession(sessionId);
|
|
86
|
+
if (chatIds.length === 0) {
|
|
87
|
+
jsonReply(res, 404, { ok: false, error: "No chats bound to this session" });
|
|
88
|
+
return true;
|
|
89
|
+
}
|
|
90
|
+
const { getPlatformForChat } = await import("./session.js");
|
|
91
|
+
const { targetChatIds, skippedUnsupported } = splitFeishuTargetChats(chatIds, (cid) => getPlatformForChat(cid)?.kind);
|
|
92
|
+
if (targetChatIds.length === 0) {
|
|
93
|
+
jsonReply(res, 409, {
|
|
94
|
+
ok: false,
|
|
95
|
+
error: "This endpoint only sends to Feishu chats. The bound chats are WeChat chats; use the WeChat image helper script instead.",
|
|
96
|
+
skippedUnsupported,
|
|
97
|
+
});
|
|
98
|
+
return true;
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
const token = await getTenantAccessToken();
|
|
102
|
+
const caption = typeof payload.caption === "string" ? payload.caption.trim() : "";
|
|
103
|
+
let sentCount = 0;
|
|
104
|
+
for (const cid of targetChatIds) {
|
|
105
|
+
try {
|
|
106
|
+
await sendImageReply(token, cid, imagePath);
|
|
107
|
+
if (caption)
|
|
108
|
+
await sendTextReply(token, cid, caption);
|
|
109
|
+
sentCount++;
|
|
110
|
+
}
|
|
111
|
+
catch (err) {
|
|
112
|
+
console.error(`[${ts()}] [AGENT-IMAGE] send to ${cid} failed: ${err.message}`);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
console.log(`[${ts()}] [AGENT-IMAGE] sent image to ${sentCount}/${targetChatIds.length} Feishu chats, session=${sessionId} path=${imagePath} skippedUnsupported=${skippedUnsupported.length}`);
|
|
116
|
+
jsonReply(res, 200, { ok: true, sentTo: sentCount, total: targetChatIds.length, skippedUnsupported });
|
|
117
|
+
}
|
|
118
|
+
catch (err) {
|
|
119
|
+
console.error(`[${ts()}] [AGENT-IMAGE] send failed: ${err.message}`);
|
|
120
|
+
jsonReply(res, 500, { ok: false, error: err.message });
|
|
121
|
+
}
|
|
122
|
+
return true;
|
|
123
|
+
}
|
|
124
|
+
// ---------------------------------------------------------------------------
|
|
125
|
+
// 兼容旧版 buildAgentImageCapabilityPrompt(供 im-skills 使用)
|
|
126
|
+
// ---------------------------------------------------------------------------
|
|
127
|
+
export function buildAgentImageCapabilityPrompt(input) {
|
|
128
|
+
const lines = [
|
|
129
|
+
"[ChatCCC local capability: send image]",
|
|
130
|
+
"You can send an image to all chats bound to this session by calling this local endpoint.",
|
|
131
|
+
"",
|
|
132
|
+
`POST ${input.url}`,
|
|
133
|
+
"Content-Type: application/json; charset=utf-8",
|
|
134
|
+
"",
|
|
135
|
+
`Body: {"session_id":"${input.sessionId ?? "YOUR_SESSION_ID"}","path":"absolute image file path","caption":"optional caption"}`,
|
|
136
|
+
"",
|
|
137
|
+
"Rules:",
|
|
138
|
+
"- Save or choose a local image file first, then call the endpoint.",
|
|
139
|
+
"- Use an absolute local file path. Do not call Feishu Open Platform directly.",
|
|
140
|
+
"- Request body must be UTF-8 encoded JSON bytes; caption supports Unicode text, including Chinese.",
|
|
141
|
+
"- Only call this endpoint when the user asked for an image or when an image is useful to the answer.",
|
|
142
|
+
"[/ChatCCC local capability: send image]",
|
|
143
|
+
];
|
|
144
|
+
if (input.cwd) {
|
|
145
|
+
lines.splice(2, 0, `Current working directory: ${input.cwd}`);
|
|
146
|
+
}
|
|
147
|
+
return lines.join("\n");
|
|
148
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export function splitFeishuTargetChats(chatIds, getPlatformKind) {
|
|
2
|
+
const targetChatIds = [];
|
|
3
|
+
const skippedUnsupported = [];
|
|
4
|
+
for (const chatId of chatIds) {
|
|
5
|
+
const platformKind = getPlatformKind(chatId);
|
|
6
|
+
if (platformKind === "wechat") {
|
|
7
|
+
skippedUnsupported.push({ chatId, platformKind });
|
|
8
|
+
continue;
|
|
9
|
+
}
|
|
10
|
+
targetChatIds.push(chatId);
|
|
11
|
+
}
|
|
12
|
+
return { targetChatIds, skippedUnsupported };
|
|
13
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { reloadRuntimeConfig } from "./runtime-reload.js";
|
|
2
|
+
export const AGENT_RELOAD_CONFIG_PATH = "/api/agent/reload-config";
|
|
3
|
+
function jsonReply(res, status, data) {
|
|
4
|
+
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
|
|
5
|
+
res.end(JSON.stringify(data));
|
|
6
|
+
}
|
|
7
|
+
export async function handleAgentReloadConfigRequest(req, res, reload = reloadRuntimeConfig) {
|
|
8
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
9
|
+
if (url.pathname !== AGENT_RELOAD_CONFIG_PATH)
|
|
10
|
+
return false;
|
|
11
|
+
if (req.method !== "POST") {
|
|
12
|
+
jsonReply(res, 405, { ok: false, error: "Method not allowed" });
|
|
13
|
+
return true;
|
|
14
|
+
}
|
|
15
|
+
try {
|
|
16
|
+
const result = await reload("agent-reload-api");
|
|
17
|
+
jsonReply(res, 200, { ok: true, ...result });
|
|
18
|
+
}
|
|
19
|
+
catch (err) {
|
|
20
|
+
jsonReply(res, 500, { ok: false, error: err.message });
|
|
21
|
+
}
|
|
22
|
+
return true;
|
|
23
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { TextDecoder } from "node:util";
|
|
2
|
+
// Windows 下 curl 传中文可能用 GBK 编码而非 UTF-8,按顺序尝试解码
|
|
3
|
+
const FALLBACK_ENCODINGS = ["gbk", "gb2312", "latin1"];
|
|
4
|
+
/**
|
|
5
|
+
* 检测 UTF-8 解码结果是否看起来像乱码(GBK 字节被误当 UTF-8 解析)。
|
|
6
|
+
* 典型特征:有 Latin-1 补充字符(U+0080-U+00FF)但没有 CJK 字符。
|
|
7
|
+
*/
|
|
8
|
+
function hasGarbledPattern(text) {
|
|
9
|
+
let latin1Count = 0;
|
|
10
|
+
let cjkCount = 0;
|
|
11
|
+
for (const ch of text) {
|
|
12
|
+
const code = ch.codePointAt(0) ?? 0;
|
|
13
|
+
if (code >= 0x4E00 && code <= 0x9FFF)
|
|
14
|
+
cjkCount++;
|
|
15
|
+
if (code >= 0x0080 && code <= 0x00FF)
|
|
16
|
+
latin1Count++;
|
|
17
|
+
}
|
|
18
|
+
return latin1Count > 0 && cjkCount === 0;
|
|
19
|
+
}
|
|
20
|
+
function normalizeHeaderValue(value) {
|
|
21
|
+
if (Array.isArray(value))
|
|
22
|
+
return value.join("; ");
|
|
23
|
+
return value ?? "";
|
|
24
|
+
}
|
|
25
|
+
export function getRequestCharset(req) {
|
|
26
|
+
const contentType = normalizeHeaderValue(req.headers["content-type"]);
|
|
27
|
+
const match = contentType.match(/(?:^|;)\s*charset\s*=\s*("?)([^";\s]+)\1/i);
|
|
28
|
+
return (match?.[2] ?? "utf-8").toLowerCase();
|
|
29
|
+
}
|
|
30
|
+
async function readLimitedBodyBuffer(req, maxBytes) {
|
|
31
|
+
const chunks = [];
|
|
32
|
+
let size = 0;
|
|
33
|
+
return new Promise((resolve, reject) => {
|
|
34
|
+
req.on("data", (chunk) => {
|
|
35
|
+
size += chunk.length;
|
|
36
|
+
if (size > maxBytes) {
|
|
37
|
+
reject(new Error("Request body too large"));
|
|
38
|
+
req.destroy();
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
chunks.push(chunk);
|
|
42
|
+
});
|
|
43
|
+
req.on("end", () => resolve(Buffer.concat(chunks, size)));
|
|
44
|
+
req.on("error", reject);
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
export async function readUtf8JsonBody(req, maxBytes) {
|
|
48
|
+
const charset = getRequestCharset(req);
|
|
49
|
+
if (charset !== "utf-8" && charset !== "utf8") {
|
|
50
|
+
throw new Error(`Unsupported charset: ${charset}. Use UTF-8 JSON.`);
|
|
51
|
+
}
|
|
52
|
+
const body = await readLimitedBodyBuffer(req, maxBytes);
|
|
53
|
+
// 首选 UTF-8;若 JSON 解析失败则尝试常见中文编码
|
|
54
|
+
// 注意:UTF-8 解码可能"成功"但实际是 GBK 字节被误当 UTF-8 解析,
|
|
55
|
+
// 此时 JSON 也能解析通过但中文变成乱码。通过 hasGarbledPattern 检测
|
|
56
|
+
// 这种"假成功"并回退到 GBK。
|
|
57
|
+
try {
|
|
58
|
+
const text = new TextDecoder("utf-8", { fatal: true }).decode(body);
|
|
59
|
+
const parsed = JSON.parse(text);
|
|
60
|
+
if (hasGarbledPattern(text)) {
|
|
61
|
+
// UTF-8 解码出的文本看起来像乱码,尝试 GBK
|
|
62
|
+
try {
|
|
63
|
+
const gbkText = new TextDecoder("gbk", { fatal: true }).decode(body);
|
|
64
|
+
return JSON.parse(gbkText);
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
// GBK 也不行,用 UTF-8 结果
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return parsed;
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
// UTF-8 解码失败,尝试其他编码
|
|
74
|
+
}
|
|
75
|
+
for (const enc of FALLBACK_ENCODINGS) {
|
|
76
|
+
try {
|
|
77
|
+
const text = new TextDecoder(enc, { fatal: true }).decode(body);
|
|
78
|
+
return JSON.parse(text);
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
// 解码或 JSON 解析失败,尝试下一个编码
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
const err = new Error("Request body must be valid UTF-8 JSON");
|
|
85
|
+
err.rawBody = body;
|
|
86
|
+
throw err;
|
|
87
|
+
}
|