chatccc 0.2.183 → 0.2.184

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.
@@ -0,0 +1,153 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import { resolve } from "node:path";
3
+
4
+ import { resolveDefaultAgentTool } from "./config.ts";
5
+ import { readUtf8JsonBody } from "./agent-rpc-body.ts";
6
+ import { delegateAgentTask } from "./agent-delegate-task.ts";
7
+ import type { PlatformAdapter } from "./platform-adapter.ts";
8
+ import { applySharedPrefix } from "./shared-prefix.ts";
9
+
10
+ export const AGENT_DELEGATE_TASK_PATH = "/api/agent/delegate-task";
11
+
12
+ const MAX_REQUEST_BYTES = 128 * 1024;
13
+ const VALID_TOOLS = new Set(["claude", "cursor", "codex"]);
14
+
15
+ interface AgentDelegateTaskPayload {
16
+ tool?: unknown;
17
+ cwd?: unknown;
18
+ prompt?: unknown;
19
+ text?: unknown;
20
+ message?: unknown;
21
+ open_id?: unknown;
22
+ open_ids?: unknown;
23
+ openIds?: unknown;
24
+ chat_name?: unknown;
25
+ }
26
+
27
+ function jsonReply(res: ServerResponse, status: number, data: unknown): void {
28
+ res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
29
+ res.end(JSON.stringify(data));
30
+ }
31
+
32
+ function stringValue(value: unknown): string {
33
+ return typeof value === "string" ? value.trim() : "";
34
+ }
35
+
36
+ function normalizeOpenIds(payload: AgentDelegateTaskPayload): string[] {
37
+ const explicitOpenId = stringValue(payload.open_id);
38
+ if (explicitOpenId) return [explicitOpenId];
39
+
40
+ const rawOpenIds = Array.isArray(payload.open_ids) ? payload.open_ids : payload.openIds;
41
+ if (!Array.isArray(rawOpenIds)) return [];
42
+ return rawOpenIds
43
+ .filter((item): item is string => typeof item === "string")
44
+ .map((item) => item.trim())
45
+ .filter(Boolean);
46
+ }
47
+
48
+ function promptFromPayload(payload: AgentDelegateTaskPayload): string {
49
+ return stringValue(payload.prompt) || stringValue(payload.text) || stringValue(payload.message);
50
+ }
51
+
52
+ function validateTool(rawTool: unknown): string {
53
+ const tool = stringValue(rawTool).toLowerCase() || resolveDefaultAgentTool();
54
+ if (!VALID_TOOLS.has(tool)) throw new Error(`unsupported tool: ${tool}`);
55
+ return tool;
56
+ }
57
+
58
+ function validateCwd(rawCwd: unknown): string {
59
+ const cwd = stringValue(rawCwd);
60
+ if (!cwd) throw new Error("cwd must be a non-empty string");
61
+ return resolve(cwd);
62
+ }
63
+
64
+ export async function handleAgentDelegateTaskRequest(
65
+ req: IncomingMessage,
66
+ res: ServerResponse,
67
+ platform: PlatformAdapter,
68
+ ): Promise<boolean> {
69
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
70
+ if (url.pathname !== AGENT_DELEGATE_TASK_PATH) return false;
71
+
72
+ if (req.method !== "POST") {
73
+ jsonReply(res, 405, { ok: false, error: "Method not allowed" });
74
+ return true;
75
+ }
76
+
77
+ if (platform.kind !== "feishu") {
78
+ jsonReply(res, 409, { ok: false, error: "This endpoint currently only supports Feishu." });
79
+ return true;
80
+ }
81
+
82
+ let payload: AgentDelegateTaskPayload;
83
+ try {
84
+ payload = await readUtf8JsonBody(req, MAX_REQUEST_BYTES);
85
+ } catch (err) {
86
+ jsonReply(res, 400, { ok: false, error: (err as Error).message || "Invalid JSON" });
87
+ return true;
88
+ }
89
+
90
+ let tool: string;
91
+ let cwd: string;
92
+ let promptText: string;
93
+ let promptNamePrefix: string;
94
+ let openIds: string[];
95
+ try {
96
+ tool = validateTool(payload.tool);
97
+ cwd = validateCwd(payload.cwd);
98
+ const rawPrompt = promptFromPayload(payload);
99
+ if (!rawPrompt) throw new Error("prompt must be a non-empty string");
100
+ const sharedPrefix = applySharedPrefix(rawPrompt);
101
+ promptText = sharedPrefix.text;
102
+ promptNamePrefix = sharedPrefix.body || rawPrompt;
103
+ openIds = normalizeOpenIds(payload);
104
+ if (openIds.length === 0) throw new Error("open_id or openIds must include at least one user");
105
+ } catch (err) {
106
+ jsonReply(res, 400, { ok: false, error: (err as Error).message });
107
+ return true;
108
+ }
109
+
110
+ try {
111
+ const result = await delegateAgentTask({
112
+ platform,
113
+ tool,
114
+ cwd,
115
+ promptText,
116
+ openIds,
117
+ chatNamePrefix: stringValue(payload.chat_name) || promptNamePrefix.slice(0, 10),
118
+ });
119
+ jsonReply(res, 200, {
120
+ ok: true,
121
+ chat_id: result.chatId,
122
+ session_id: result.sessionId,
123
+ tool: result.tool,
124
+ cwd: result.cwd,
125
+ });
126
+ } catch (err) {
127
+ jsonReply(res, 500, { ok: false, error: (err as Error).message });
128
+ }
129
+ return true;
130
+ }
131
+
132
+ export function buildAgentDelegateTaskCapabilityPrompt(input: { url: string; cwd?: string }): string {
133
+ const lines = [
134
+ "[ChatCCC local capability: delegate task]",
135
+ "You can create a separate Feishu ChatCCC agent session and assign its first task by calling this local endpoint.",
136
+ "",
137
+ `POST ${input.url}`,
138
+ "Content-Type: application/json; charset=utf-8",
139
+ "",
140
+ 'Body: {"tool":"codex|claude|cursor","cwd":"absolute working directory","open_id":"Feishu open_id to invite","prompt":"first task text"}',
141
+ "",
142
+ "Rules:",
143
+ "- Use this only when the user asks you to start a separate delegated conversation/session.",
144
+ "- Pass cwd explicitly as an absolute local path.",
145
+ "- Pass tool explicitly when the user specified a target agent.",
146
+ "- Use open_id for one user or open_ids/openIds for multiple users.",
147
+ "- The prompt is sent through the normal ChatCCC prompt path, so project prompt injection and IM skills still apply.",
148
+ "- Request body must be UTF-8 encoded JSON bytes. Do not call Feishu Open Platform directly.",
149
+ "[/ChatCCC local capability: delegate task]",
150
+ ];
151
+ if (input.cwd) lines.splice(2, 0, `Current working directory: ${input.cwd}`);
152
+ return lines.join("\n");
153
+ }
@@ -0,0 +1,81 @@
1
+ import { resolve } from "node:path";
2
+
3
+ import { sessionPrefixForTool, toolDisplayName, ts } from "./config.ts";
4
+ import { setDefaultCwd } from "./config.ts";
5
+ import type { PlatformAdapter } from "./platform-adapter.ts";
6
+ import { initClaudeSession, recordSessionRegistry, resumeAndPrompt, saveSessionTool } from "./session.ts";
7
+ import { bindChatToSession } from "./session-chat-binding.ts";
8
+ import { sessionChatName } from "./session-name.ts";
9
+
10
+ export interface DelegateAgentTaskInput {
11
+ platform: PlatformAdapter;
12
+ tool: string;
13
+ cwd: string;
14
+ promptText: string;
15
+ openIds: string[];
16
+ chatNamePrefix?: string;
17
+ msgTimestamp?: number;
18
+ traceId?: string;
19
+ }
20
+
21
+ export interface DelegateAgentTaskResult {
22
+ chatId: string;
23
+ sessionId: string;
24
+ tool: string;
25
+ cwd: string;
26
+ }
27
+
28
+ export async function delegateAgentTask(input: DelegateAgentTaskInput): Promise<DelegateAgentTaskResult> {
29
+ const cwd = resolve(input.cwd);
30
+ const toolLabel = toolDisplayName(input.tool);
31
+ const init = await initClaudeSession(input.tool, cwd);
32
+ const sessionId = init.sessionId;
33
+ const chatNamePrefix = input.chatNamePrefix?.trim() || input.promptText.slice(0, 10) || "新会话";
34
+ const chatName = sessionChatName(chatNamePrefix, cwd);
35
+
36
+ let chatId: string;
37
+ try {
38
+ chatId = await input.platform.createGroup(chatName, input.openIds);
39
+ await input.platform.updateChatInfo(chatId, chatName, `${sessionPrefixForTool(input.tool)} ${sessionId}`);
40
+ await setDefaultCwd(cwd, chatId);
41
+ bindChatToSession(sessionId, chatId);
42
+ await recordSessionRegistry({
43
+ chatId,
44
+ sessionId,
45
+ tool: input.tool,
46
+ chatName,
47
+ turnCount: 0,
48
+ startTime: Date.now(),
49
+ running: false,
50
+ });
51
+ await saveSessionTool(sessionId, input.tool, chatName);
52
+ } catch (err) {
53
+ console.error(`[${ts()}] [AGENT-DELEGATE-TASK] create group failed: ${(err as Error).message}`);
54
+ throw err;
55
+ }
56
+
57
+ await input.platform.sendCard(
58
+ chatId,
59
+ `${toolLabel} Session Ready`,
60
+ `已创建 **${toolLabel}** 会话群。\n\n` +
61
+ `**Session ID:** ${sessionId}\n` +
62
+ `**工作目录:** \`${cwd}\`\n\n` +
63
+ `下面会自动把任务作为第一句话发送给 ${toolLabel}。`,
64
+ "green",
65
+ ).catch(() => {});
66
+ input.platform.setChatAvatar(chatId, input.tool, "new").catch(() => {});
67
+
68
+ await resumeAndPrompt(
69
+ sessionId,
70
+ input.promptText,
71
+ input.platform,
72
+ chatId,
73
+ input.msgTimestamp ?? Date.now(),
74
+ input.tool,
75
+ input.traceId,
76
+ );
77
+
78
+ console.log(`[${ts()}] [AGENT-DELEGATE-TASK] created ${toolLabel} session=${sessionId} chat=${chatId} cwd=${cwd}`);
79
+ return { chatId, sessionId, tool: input.tool, cwd };
80
+ }
81
+
@@ -1,184 +1,184 @@
1
- import { randomUUID } from "node:crypto";
2
-
3
- import { buildCodexResetConfirmCard } from "./cards.ts";
4
- import type { CodexResetConsumeResult } from "./feishu-api.ts";
5
-
6
- type CodexResetDecision = "yes" | "no";
7
-
8
- interface PendingCodexResetRequest {
9
- chatId: string;
10
- parentMessageId: string;
11
- status: "pending" | "handled";
12
- }
13
-
14
- export interface CodexResetActionDeps {
15
- getTenantAccessToken(): Promise<string>;
16
- sendRawCard(token: string, chatId: string, cardJson: string): Promise<boolean>;
17
- sendTextReply(token: string, chatId: string, text: string): Promise<boolean>;
18
- sendCardReply(token: string, chatId: string, title: string, content: string, template?: string): Promise<boolean>;
19
- updateCardMessage(token: string, messageId: string, content: string): Promise<boolean>;
20
- recallMessage(token: string, messageId: string): Promise<boolean>;
21
- consumeCodexRateLimitResetCredit(redeemRequestId: string): Promise<CodexResetConsumeResult>;
22
- createRequestId?: () => string;
23
- }
24
-
25
- const pendingCodexResetRequests = new Map<string, PendingCodexResetRequest>();
26
-
27
- function rawEvent(data: unknown): Record<string, unknown> {
28
- return ((data as Record<string, unknown>)?.event ?? data) as Record<string, unknown>;
29
- }
30
-
31
- function actionValue(raw: Record<string, unknown>): Record<string, unknown> | null {
32
- const action = raw.action as { value?: unknown } | undefined;
33
- const value = action?.value;
34
- if (!value || typeof value !== "object") return null;
35
- return value as Record<string, unknown>;
36
- }
37
-
38
- function eventMessageId(raw: Record<string, unknown>): string {
39
- return typeof raw.open_message_id === "string"
40
- ? raw.open_message_id
41
- : typeof (raw.context as Record<string, unknown> | undefined)?.open_message_id === "string"
42
- ? (raw.context as Record<string, string>).open_message_id
43
- : typeof raw.message_id === "string"
44
- ? raw.message_id
45
- : typeof (raw.context as Record<string, unknown> | undefined)?.message_id === "string"
46
- ? (raw.context as Record<string, string>).message_id
47
- : typeof (raw.message as Record<string, unknown> | undefined)?.message_id === "string"
48
- ? (raw.message as Record<string, string>).message_id
49
- : "";
50
- }
51
-
52
- function eventChatId(raw: Record<string, unknown>): string {
53
- return typeof raw.open_chat_id === "string"
54
- ? raw.open_chat_id
55
- : typeof (raw.context as Record<string, unknown> | undefined)?.open_chat_id === "string"
56
- ? (raw.context as Record<string, string>).open_chat_id
57
- : typeof (raw.message as Record<string, unknown> | undefined)?.chat_id === "string"
58
- ? (raw.message as Record<string, string>).chat_id
59
- : "";
60
- }
61
-
62
- function collapsedCard(): string {
63
- return JSON.stringify({
64
- config: { wide_screen_mode: true },
65
- elements: [{ tag: "markdown", content: " " }],
66
- });
67
- }
68
-
69
- function resetResultMessage(result: CodexResetConsumeResult): { content: string; template: string } {
70
- if (result.code === "reset") {
71
- return {
72
- content: `重置成功。已重置 ${result.windowsReset} 个 Codex 用量窗口。`,
73
- template: "green",
74
- };
75
- }
76
- if (result.code === "nothing_to_reset") {
77
- return {
78
- content: "没有需要重置的 Codex 用量窗口。",
79
- template: "yellow",
80
- };
81
- }
82
- if (result.code === "no_credit") {
83
- return {
84
- content: "没有可用的 Codex 主动重置次数。",
85
- template: "red",
86
- };
87
- }
88
- return {
89
- content: "这次 Codex 主动重置请求已经处理过。",
90
- template: "yellow",
91
- };
92
- }
93
-
94
- async function sendResetRequestConfirmation(
95
- raw: Record<string, unknown>,
96
- value: Record<string, unknown>,
97
- deps: CodexResetActionDeps,
98
- ): Promise<boolean> {
99
- const parentMessageId = eventMessageId(raw);
100
- const chatId = eventChatId(raw);
101
- if (!parentMessageId || !chatId) return true;
102
- const availableCount = Number(value.availableCount);
103
-
104
- const requestId = (deps.createRequestId ?? randomUUID)();
105
- pendingCodexResetRequests.set(requestId, {
106
- chatId,
107
- parentMessageId,
108
- status: "pending",
109
- });
110
-
111
- const token = await deps.getTenantAccessToken();
112
- await deps.sendRawCard(token, chatId, buildCodexResetConfirmCard({
113
- availableCount: Number.isFinite(availableCount) ? Math.max(1, Math.trunc(availableCount)) : 1,
114
- parentMessageId,
115
- requestId,
116
- }));
117
- return true;
118
- }
119
-
120
- async function handleResetConfirmation(
121
- raw: Record<string, unknown>,
122
- value: Record<string, unknown>,
123
- deps: CodexResetActionDeps,
124
- ): Promise<boolean> {
125
- const decision = value.decision;
126
- const requestId = value.requestId;
127
- const parentMessageId = value.parentMessageId;
128
- if ((decision !== "yes" && decision !== "no") || typeof requestId !== "string" || typeof parentMessageId !== "string") {
129
- return true;
130
- }
131
-
132
- const token = await deps.getTenantAccessToken();
133
- const confirmMessageId = eventMessageId(raw);
134
- if (confirmMessageId) {
135
- const collapsed = await deps.updateCardMessage(token, confirmMessageId, collapsedCard());
136
- console.log(`[Codex Reset] collapse confirmation card ${collapsed ? "OK" : "FAILED"}: messageId=${confirmMessageId}`);
137
- const recalled = await deps.recallMessage(token, confirmMessageId);
138
- console.log(`[Codex Reset] recall confirmation card ${recalled ? "OK" : "FAILED"}: messageId=${confirmMessageId}`);
139
- } else {
140
- console.error("[Codex Reset] missing confirmation card message id; cannot collapse");
141
- }
142
-
143
- const pending = pendingCodexResetRequests.get(requestId);
144
- const chatId = pending?.chatId ?? eventChatId(raw);
145
- if (!chatId) return true;
146
-
147
- if (!pending || pending.status !== "pending" || pending.parentMessageId !== parentMessageId) {
148
- await deps.sendTextReply(token, chatId, "Codex 主动重置:这张确认卡片已经失效或已处理。");
149
- return true;
150
- }
151
- pending.status = "handled";
152
-
153
- if (decision === "no") {
154
- await deps.sendTextReply(token, chatId, "Codex 主动重置:用户取消了重置。");
155
- return true;
156
- }
157
-
158
- try {
159
- const result = await deps.consumeCodexRateLimitResetCredit(requestId);
160
- const message = resetResultMessage(result);
161
- await deps.sendTextReply(token, chatId, `Codex 主动重置:${message.content}`);
162
- } catch (err) {
163
- await deps.sendTextReply(token, chatId, `Codex 主动重置失败:${(err as Error).message}`);
164
- }
165
- return true;
166
- }
167
-
168
- export async function handleCodexResetCardAction(data: unknown, deps: CodexResetActionDeps): Promise<boolean> {
169
- const raw = rawEvent(data);
170
- const value = actionValue(raw);
171
- if (!value) return false;
172
- const action = value?.action;
173
- if (action === "codex_reset_request") {
174
- return sendResetRequestConfirmation(raw, value, deps);
175
- }
176
- if (action === "codex_reset_confirm") {
177
- return handleResetConfirmation(raw, value, deps);
178
- }
179
- return false;
180
- }
181
-
182
- export function _resetCodexResetRequestsForTest(): void {
183
- pendingCodexResetRequests.clear();
184
- }
1
+ import { randomUUID } from "node:crypto";
2
+
3
+ import { buildCodexResetConfirmCard } from "./cards.ts";
4
+ import type { CodexResetConsumeResult } from "./feishu-api.ts";
5
+
6
+ type CodexResetDecision = "yes" | "no";
7
+
8
+ interface PendingCodexResetRequest {
9
+ chatId: string;
10
+ parentMessageId: string;
11
+ status: "pending" | "handled";
12
+ }
13
+
14
+ export interface CodexResetActionDeps {
15
+ getTenantAccessToken(): Promise<string>;
16
+ sendRawCard(token: string, chatId: string, cardJson: string): Promise<boolean>;
17
+ sendTextReply(token: string, chatId: string, text: string): Promise<boolean>;
18
+ sendCardReply(token: string, chatId: string, title: string, content: string, template?: string): Promise<boolean>;
19
+ updateCardMessage(token: string, messageId: string, content: string): Promise<boolean>;
20
+ recallMessage(token: string, messageId: string): Promise<boolean>;
21
+ consumeCodexRateLimitResetCredit(redeemRequestId: string): Promise<CodexResetConsumeResult>;
22
+ createRequestId?: () => string;
23
+ }
24
+
25
+ const pendingCodexResetRequests = new Map<string, PendingCodexResetRequest>();
26
+
27
+ function rawEvent(data: unknown): Record<string, unknown> {
28
+ return ((data as Record<string, unknown>)?.event ?? data) as Record<string, unknown>;
29
+ }
30
+
31
+ function actionValue(raw: Record<string, unknown>): Record<string, unknown> | null {
32
+ const action = raw.action as { value?: unknown } | undefined;
33
+ const value = action?.value;
34
+ if (!value || typeof value !== "object") return null;
35
+ return value as Record<string, unknown>;
36
+ }
37
+
38
+ function eventMessageId(raw: Record<string, unknown>): string {
39
+ return typeof raw.open_message_id === "string"
40
+ ? raw.open_message_id
41
+ : typeof (raw.context as Record<string, unknown> | undefined)?.open_message_id === "string"
42
+ ? (raw.context as Record<string, string>).open_message_id
43
+ : typeof raw.message_id === "string"
44
+ ? raw.message_id
45
+ : typeof (raw.context as Record<string, unknown> | undefined)?.message_id === "string"
46
+ ? (raw.context as Record<string, string>).message_id
47
+ : typeof (raw.message as Record<string, unknown> | undefined)?.message_id === "string"
48
+ ? (raw.message as Record<string, string>).message_id
49
+ : "";
50
+ }
51
+
52
+ function eventChatId(raw: Record<string, unknown>): string {
53
+ return typeof raw.open_chat_id === "string"
54
+ ? raw.open_chat_id
55
+ : typeof (raw.context as Record<string, unknown> | undefined)?.open_chat_id === "string"
56
+ ? (raw.context as Record<string, string>).open_chat_id
57
+ : typeof (raw.message as Record<string, unknown> | undefined)?.chat_id === "string"
58
+ ? (raw.message as Record<string, string>).chat_id
59
+ : "";
60
+ }
61
+
62
+ function collapsedCard(): string {
63
+ return JSON.stringify({
64
+ config: { wide_screen_mode: true },
65
+ elements: [{ tag: "markdown", content: " " }],
66
+ });
67
+ }
68
+
69
+ function resetResultMessage(result: CodexResetConsumeResult): { content: string; template: string } {
70
+ if (result.code === "reset") {
71
+ return {
72
+ content: `重置成功。已重置 ${result.windowsReset} 个 Codex 用量窗口。`,
73
+ template: "green",
74
+ };
75
+ }
76
+ if (result.code === "nothing_to_reset") {
77
+ return {
78
+ content: "没有需要重置的 Codex 用量窗口。",
79
+ template: "yellow",
80
+ };
81
+ }
82
+ if (result.code === "no_credit") {
83
+ return {
84
+ content: "没有可用的 Codex 主动重置次数。",
85
+ template: "red",
86
+ };
87
+ }
88
+ return {
89
+ content: "这次 Codex 主动重置请求已经处理过。",
90
+ template: "yellow",
91
+ };
92
+ }
93
+
94
+ async function sendResetRequestConfirmation(
95
+ raw: Record<string, unknown>,
96
+ value: Record<string, unknown>,
97
+ deps: CodexResetActionDeps,
98
+ ): Promise<boolean> {
99
+ const parentMessageId = eventMessageId(raw);
100
+ const chatId = eventChatId(raw);
101
+ if (!parentMessageId || !chatId) return true;
102
+ const availableCount = Number(value.availableCount);
103
+
104
+ const requestId = (deps.createRequestId ?? randomUUID)();
105
+ pendingCodexResetRequests.set(requestId, {
106
+ chatId,
107
+ parentMessageId,
108
+ status: "pending",
109
+ });
110
+
111
+ const token = await deps.getTenantAccessToken();
112
+ await deps.sendRawCard(token, chatId, buildCodexResetConfirmCard({
113
+ availableCount: Number.isFinite(availableCount) ? Math.max(1, Math.trunc(availableCount)) : 1,
114
+ parentMessageId,
115
+ requestId,
116
+ }));
117
+ return true;
118
+ }
119
+
120
+ async function handleResetConfirmation(
121
+ raw: Record<string, unknown>,
122
+ value: Record<string, unknown>,
123
+ deps: CodexResetActionDeps,
124
+ ): Promise<boolean> {
125
+ const decision = value.decision;
126
+ const requestId = value.requestId;
127
+ const parentMessageId = value.parentMessageId;
128
+ if ((decision !== "yes" && decision !== "no") || typeof requestId !== "string" || typeof parentMessageId !== "string") {
129
+ return true;
130
+ }
131
+
132
+ const token = await deps.getTenantAccessToken();
133
+ const confirmMessageId = eventMessageId(raw);
134
+ if (confirmMessageId) {
135
+ const collapsed = await deps.updateCardMessage(token, confirmMessageId, collapsedCard());
136
+ console.log(`[Codex Reset] collapse confirmation card ${collapsed ? "OK" : "FAILED"}: messageId=${confirmMessageId}`);
137
+ const recalled = await deps.recallMessage(token, confirmMessageId);
138
+ console.log(`[Codex Reset] recall confirmation card ${recalled ? "OK" : "FAILED"}: messageId=${confirmMessageId}`);
139
+ } else {
140
+ console.error("[Codex Reset] missing confirmation card message id; cannot collapse");
141
+ }
142
+
143
+ const pending = pendingCodexResetRequests.get(requestId);
144
+ const chatId = pending?.chatId ?? eventChatId(raw);
145
+ if (!chatId) return true;
146
+
147
+ if (!pending || pending.status !== "pending" || pending.parentMessageId !== parentMessageId) {
148
+ await deps.sendTextReply(token, chatId, "Codex 主动重置:这张确认卡片已经失效或已处理。");
149
+ return true;
150
+ }
151
+ pending.status = "handled";
152
+
153
+ if (decision === "no") {
154
+ await deps.sendTextReply(token, chatId, "Codex 主动重置:用户取消了重置。");
155
+ return true;
156
+ }
157
+
158
+ try {
159
+ const result = await deps.consumeCodexRateLimitResetCredit(requestId);
160
+ const message = resetResultMessage(result);
161
+ await deps.sendTextReply(token, chatId, `Codex 主动重置:${message.content}`);
162
+ } catch (err) {
163
+ await deps.sendTextReply(token, chatId, `Codex 主动重置失败:${(err as Error).message}`);
164
+ }
165
+ return true;
166
+ }
167
+
168
+ export async function handleCodexResetCardAction(data: unknown, deps: CodexResetActionDeps): Promise<boolean> {
169
+ const raw = rawEvent(data);
170
+ const value = actionValue(raw);
171
+ if (!value) return false;
172
+ const action = value?.action;
173
+ if (action === "codex_reset_request") {
174
+ return sendResetRequestConfirmation(raw, value, deps);
175
+ }
176
+ if (action === "codex_reset_confirm") {
177
+ return handleResetConfirmation(raw, value, deps);
178
+ }
179
+ return false;
180
+ }
181
+
182
+ export function _resetCodexResetRequestsForTest(): void {
183
+ pendingCodexResetRequests.clear();
184
+ }