@kkcode-app/agent 1.1.4 → 2.0.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/README.md +40 -99
- package/dist/agent-link.js +55 -93
- package/dist/agent-link.js.map +1 -1
- package/dist/config.js +101 -69
- package/dist/config.js.map +1 -1
- package/dist/crypto.js +151 -0
- package/dist/crypto.js.map +1 -0
- package/dist/entry.js +5 -9
- package/dist/entry.js.map +1 -1
- package/dist/index.js +71 -83
- package/dist/index.js.map +1 -1
- package/dist/local-server.js +58 -27
- package/dist/local-server.js.map +1 -1
- package/dist/notification-core.js +131 -59
- package/dist/notification-core.js.map +1 -1
- package/dist/plugin.js +128 -71
- package/dist/plugin.js.map +1 -1
- package/dist/protocol.js +62 -6
- package/dist/protocol.js.map +1 -1
- package/dist/qr.js +31 -20
- package/dist/qr.js.map +1 -1
- package/dist/service.js +24 -8
- package/dist/service.js.map +1 -1
- package/dist/tunnel.js +406 -200
- package/dist/tunnel.js.map +1 -1
- package/dist/update.js +13 -5
- package/dist/update.js.map +1 -1
- package/package.json +4 -3
- package/src/config.ts +144 -0
- package/src/crypto.ts +193 -0
- package/src/entry.ts +5 -11
- package/src/notification-core.ts +139 -71
- package/src/plugin.ts +132 -67
- package/dist/plugin-v1.js +0 -136
- package/dist/plugin-v1.js.map +0 -1
- package/src/plugin-v1.ts +0 -189
package/src/notification-core.ts
CHANGED
|
@@ -1,19 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* [INPUT]: 依赖 node:fs
|
|
3
|
-
* [OUTPUT]:
|
|
4
|
-
* [POS]: cli
|
|
5
|
-
* [PROTOCOL]:
|
|
2
|
+
* [INPUT]: 依赖 node:fs、node:os、node:path、./config.ts(热读 host.json)与 ./crypto.ts(派生 hostId/relayAuth)
|
|
3
|
+
* [OUTPUT]: 提供 Notify 2.0 通知类型、UTF-8 字节安全截断、2 MiB 日志轮转及带重试的 /v2/events 上报
|
|
4
|
+
* [POS]: cli 推送插件的协议无关内核,被 OpenCode 2 插件调用,支持不开隧道独立推送
|
|
5
|
+
* [PROTOCOL]: Update this header on change, then check CLAUDE.md
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import fs from "node:fs";
|
|
9
|
-
import {
|
|
9
|
+
import { homedir } from "node:os";
|
|
10
|
+
import { dirname, join } from "node:path";
|
|
10
11
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
node_secret: string;
|
|
14
|
-
service_id: string;
|
|
15
|
-
api_url?: string;
|
|
16
|
-
};
|
|
12
|
+
import { loadHostConfig } from "./config.js";
|
|
13
|
+
import { deriveKeys } from "./crypto.js";
|
|
17
14
|
|
|
18
15
|
export type NotifyEventType =
|
|
19
16
|
| "session.completed"
|
|
@@ -22,71 +19,94 @@ export type NotifyEventType =
|
|
|
22
19
|
| "permission.asked"
|
|
23
20
|
| "question.asked";
|
|
24
21
|
|
|
25
|
-
type
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
project_label: string;
|
|
31
|
-
occurred_at: string;
|
|
32
|
-
session_title?: string;
|
|
22
|
+
type NotifyV2Payload = {
|
|
23
|
+
eventId: string;
|
|
24
|
+
sessionId: string;
|
|
25
|
+
eventType: NotifyEventType;
|
|
26
|
+
sessionTitle?: string;
|
|
33
27
|
summary?: string;
|
|
28
|
+
occurredAt: string;
|
|
34
29
|
};
|
|
35
30
|
|
|
36
31
|
export type NotificationIntent = {
|
|
37
32
|
eventID?: string;
|
|
38
33
|
sessionID: string;
|
|
39
34
|
type: NotifyEventType;
|
|
40
|
-
projectLabel: string;
|
|
41
35
|
summary?: string;
|
|
42
36
|
sessionTitle?: string;
|
|
43
37
|
occurredAt?: number;
|
|
44
38
|
};
|
|
45
39
|
|
|
46
|
-
|
|
47
|
-
|
|
40
|
+
export type ReportOptions = {
|
|
41
|
+
timeoutMs?: number;
|
|
42
|
+
retryDelaysMs?: readonly number[];
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export const DEFAULT_NOTIFY_API_URL = "https://api.kkcode.app";
|
|
46
|
+
export const MAX_SESSION_TITLE_BYTES = 200;
|
|
47
|
+
export const MAX_SUMMARY_BYTES = 480;
|
|
48
|
+
export const MAX_EVENT_ID_BYTES = 200;
|
|
49
|
+
export const MAX_DEBUG_LOG_BYTES = 2 * 1024 * 1024;
|
|
50
|
+
|
|
51
|
+
const DEFAULT_TIMEOUT_MS = 8_000;
|
|
52
|
+
const DEFAULT_RETRY_DELAYS_MS: readonly number[] = [500, 1_500];
|
|
48
53
|
|
|
49
|
-
|
|
50
|
-
return (
|
|
51
|
-
process.env.KKCODE_AGENT_CONFIG ??
|
|
52
|
-
`${process.env.XDG_CONFIG_HOME ?? `${process.env.HOME ?? "~"}/.config`}/kkcode/agent.json`
|
|
53
|
-
);
|
|
54
|
+
function configBaseDir(): string {
|
|
55
|
+
return process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config");
|
|
54
56
|
}
|
|
55
57
|
|
|
56
|
-
function debugLogPath(): string {
|
|
57
|
-
return (
|
|
58
|
-
process.env.KKCODE_DEBUG_LOG ??
|
|
59
|
-
`${process.env.XDG_CONFIG_HOME ?? `${process.env.HOME ?? "~"}/.config`}/kkcode/events-debug.log`
|
|
60
|
-
);
|
|
58
|
+
export function debugLogPath(): string {
|
|
59
|
+
return process.env.KKCODE_DEBUG_LOG ?? join(configBaseDir(), "kkcode", "events-debug.log");
|
|
61
60
|
}
|
|
62
61
|
|
|
63
62
|
export async function debugLog(message: string): Promise<void> {
|
|
64
63
|
try {
|
|
65
64
|
const path = debugLogPath();
|
|
66
65
|
await fs.promises.mkdir(dirname(path), { recursive: true });
|
|
67
|
-
|
|
66
|
+
let rotated = false;
|
|
67
|
+
try {
|
|
68
|
+
const stat = await fs.promises.stat(path);
|
|
69
|
+
if (stat.size >= MAX_DEBUG_LOG_BYTES) {
|
|
70
|
+
await fs.promises.truncate(path, 0);
|
|
71
|
+
rotated = true;
|
|
72
|
+
}
|
|
73
|
+
} catch (error) {
|
|
74
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
75
|
+
}
|
|
76
|
+
const prefix = rotated ? `[${new Date().toISOString()}] [log rotated at ${MAX_DEBUG_LOG_BYTES} bytes]\n` : "";
|
|
77
|
+
await fs.promises.appendFile(path, `${prefix}[${new Date().toISOString()}] ${message}\n`);
|
|
68
78
|
} catch {}
|
|
69
79
|
}
|
|
70
80
|
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
81
|
+
/**
|
|
82
|
+
* 折叠空白并按 UTF-8 字节上限安全截断,保证绝不截断多字节字符(如中文或 emoji)。
|
|
83
|
+
*/
|
|
84
|
+
export function truncateUtf8Bytes(value: unknown, maxBytes: number): string {
|
|
85
|
+
if (typeof value !== "string" || maxBytes <= 0) return "";
|
|
86
|
+
const normalized = value.replace(/\s+/gu, " ").trim();
|
|
87
|
+
if (!normalized) return "";
|
|
88
|
+
if (Buffer.byteLength(normalized, "utf8") <= maxBytes) return normalized;
|
|
89
|
+
|
|
90
|
+
let out = "";
|
|
91
|
+
let usedBytes = 0;
|
|
92
|
+
for (const ch of normalized) {
|
|
93
|
+
const chBytes = Buffer.byteLength(ch, "utf8");
|
|
94
|
+
if (usedBytes + chBytes > maxBytes) break;
|
|
95
|
+
out += ch;
|
|
96
|
+
usedBytes += chBytes;
|
|
78
97
|
}
|
|
98
|
+
return out;
|
|
79
99
|
}
|
|
80
100
|
|
|
81
|
-
export function compactText(value: unknown,
|
|
82
|
-
return
|
|
101
|
+
export function compactText(value: unknown, maxBytes = MAX_SUMMARY_BYTES): string {
|
|
102
|
+
return truncateUtf8Bytes(value, maxBytes);
|
|
83
103
|
}
|
|
84
104
|
|
|
85
105
|
export function errorSummary(value: unknown): string | undefined {
|
|
86
|
-
if (typeof value === "string") return compactText(value) || undefined;
|
|
106
|
+
if (typeof value === "string") return compactText(value, MAX_SUMMARY_BYTES) || undefined;
|
|
87
107
|
if (!value || typeof value !== "object") return undefined;
|
|
88
108
|
const error = value as { message?: unknown; type?: unknown; name?: unknown; data?: unknown };
|
|
89
|
-
const message = compactText(error.message);
|
|
109
|
+
const message = compactText(error.message, MAX_SUMMARY_BYTES);
|
|
90
110
|
if (message) return message;
|
|
91
111
|
const nested = errorSummary(error.data);
|
|
92
112
|
if (nested) return nested;
|
|
@@ -94,46 +114,94 @@ export function errorSummary(value: unknown): string | undefined {
|
|
|
94
114
|
return kind || undefined;
|
|
95
115
|
}
|
|
96
116
|
|
|
117
|
+
class NonRetryableHttpError extends Error {
|
|
118
|
+
constructor(
|
|
119
|
+
public readonly status: number,
|
|
120
|
+
message: string,
|
|
121
|
+
) {
|
|
122
|
+
super(message);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function sleep(ms: number): Promise<void> {
|
|
127
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
128
|
+
}
|
|
129
|
+
|
|
97
130
|
export async function reportNotification(
|
|
98
131
|
intent: NotificationIntent,
|
|
132
|
+
options?: ReportOptions,
|
|
99
133
|
): Promise<"reported" | "skipped"> {
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
await
|
|
134
|
+
let hostConfig: Awaited<ReturnType<typeof loadHostConfig>>;
|
|
135
|
+
try {
|
|
136
|
+
hostConfig = await loadHostConfig();
|
|
137
|
+
} catch (error) {
|
|
138
|
+
await debugLog(`host.json unreadable, skipping ${intent.type}: ${error}`);
|
|
139
|
+
return "skipped";
|
|
140
|
+
}
|
|
141
|
+
if (!hostConfig) {
|
|
142
|
+
await debugLog(`host.json missing, skipping ${intent.type}`);
|
|
103
143
|
return "skipped";
|
|
104
144
|
}
|
|
105
145
|
|
|
106
|
-
const
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
146
|
+
const keys = deriveKeys(hostConfig.secret);
|
|
147
|
+
const apiBase = (
|
|
148
|
+
process.env.KKCODE_NOTIFY_API_URL ??
|
|
149
|
+
hostConfig.notifyApiUrl ??
|
|
150
|
+
DEFAULT_NOTIFY_API_URL
|
|
151
|
+
).replace(/\/$/u, "");
|
|
152
|
+
|
|
153
|
+
const payload: NotifyV2Payload = {
|
|
154
|
+
eventId: truncateUtf8Bytes(intent.eventID, MAX_EVENT_ID_BYTES) || crypto.randomUUID(),
|
|
155
|
+
sessionId: intent.sessionID,
|
|
156
|
+
eventType: intent.type,
|
|
157
|
+
occurredAt: new Date(intent.occurredAt ?? Date.now()).toISOString(),
|
|
113
158
|
};
|
|
114
|
-
|
|
115
|
-
const sessionTitle =
|
|
159
|
+
|
|
160
|
+
const sessionTitle = truncateUtf8Bytes(intent.sessionTitle, MAX_SESSION_TITLE_BYTES);
|
|
161
|
+
const summary = truncateUtf8Bytes(intent.summary, MAX_SUMMARY_BYTES);
|
|
162
|
+
if (sessionTitle) payload.sessionTitle = sessionTitle;
|
|
116
163
|
if (summary) payload.summary = summary;
|
|
117
|
-
if (sessionTitle) payload.session_title = sessionTitle;
|
|
118
164
|
|
|
119
|
-
const
|
|
120
|
-
const
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
165
|
+
const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
166
|
+
const retryDelays = options?.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
|
|
167
|
+
const endpoint = `${apiBase}/v2/events`;
|
|
168
|
+
const body = JSON.stringify(payload);
|
|
169
|
+
|
|
170
|
+
let lastError: unknown;
|
|
171
|
+
for (let attempt = 0; attempt <= retryDelays.length; attempt += 1) {
|
|
172
|
+
const controller = new AbortController();
|
|
173
|
+
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
174
|
+
try {
|
|
175
|
+
const response = await fetch(endpoint, {
|
|
125
176
|
method: "POST",
|
|
126
177
|
signal: controller.signal,
|
|
127
178
|
headers: {
|
|
128
|
-
Authorization: `Bearer ${config.node_secret}`,
|
|
129
179
|
"Content-Type": "application/json",
|
|
180
|
+
"X-KKCode-Host-Id": keys.hostId,
|
|
181
|
+
"X-KKCode-Auth": keys.relayAuth,
|
|
130
182
|
},
|
|
131
|
-
body
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
183
|
+
body,
|
|
184
|
+
});
|
|
185
|
+
if (response.ok) {
|
|
186
|
+
return "reported";
|
|
187
|
+
}
|
|
188
|
+
const errMsg = `Notification API returned ${response.status}`;
|
|
189
|
+
if (response.status >= 400 && response.status < 500) {
|
|
190
|
+
throw new NonRetryableHttpError(response.status, errMsg);
|
|
191
|
+
}
|
|
192
|
+
throw new Error(errMsg);
|
|
193
|
+
} catch (error) {
|
|
194
|
+
if (error instanceof NonRetryableHttpError) {
|
|
195
|
+
throw error;
|
|
196
|
+
}
|
|
197
|
+
lastError = error;
|
|
198
|
+
if (attempt < retryDelays.length) {
|
|
199
|
+
await sleep(retryDelays[attempt]);
|
|
200
|
+
}
|
|
201
|
+
} finally {
|
|
202
|
+
clearTimeout(timeout);
|
|
203
|
+
}
|
|
138
204
|
}
|
|
205
|
+
|
|
206
|
+
throw lastError instanceof Error ? lastError : new Error(String(lastError));
|
|
139
207
|
}
|
package/src/plugin.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* [INPUT]: 依赖 OpenCode 2 Promise plugin context 的 location/session/event API 与 notification-core
|
|
3
|
-
* [OUTPUT]: 默认导出 `{ id, setup }` OpenCode 2
|
|
4
|
-
* [POS]: OpenCode 2
|
|
5
|
-
* [PROTOCOL]:
|
|
2
|
+
* [INPUT]: 依赖 OpenCode 2 Promise plugin context 的 location/session/event API 与 ./notification-core.ts
|
|
3
|
+
* [OUTPUT]: 默认导出 `{ id, setup }` OpenCode 2 插件;支持单事件会话查询缓存、上报成功后去重、订阅断流指数退避重连与全量上报调试日志
|
|
4
|
+
* [POS]: OpenCode 2 插件实现模块,由包入口 entry.ts 直接导出
|
|
5
|
+
* [PROTOCOL]: Update this header on change, then check CLAUDE.md
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import { basename, normalize } from "node:path";
|
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
compactText,
|
|
12
12
|
debugLog,
|
|
13
13
|
errorSummary,
|
|
14
|
+
MAX_SESSION_TITLE_BYTES,
|
|
14
15
|
reportNotification,
|
|
15
16
|
type NotificationIntent,
|
|
16
17
|
} from "./notification-core.js";
|
|
@@ -33,11 +34,6 @@ type V2Context = {
|
|
|
33
34
|
|
|
34
35
|
type SessionInfo = { title?: string; parentID?: string; directory?: string; workspaceID?: string };
|
|
35
36
|
|
|
36
|
-
/**
|
|
37
|
-
* 本插件打算推送的事件类型。handle() 只对这些类型写丢弃日志——流式期间
|
|
38
|
-
* session.step.* / message.updated 等高频事件数量极大,全量记录会刷爆调试日志。
|
|
39
|
-
* handle() 末尾还有一处 UNHANDLED 兜底,用于捕捉本表与分支实现之间的漂移。
|
|
40
|
-
*/
|
|
41
37
|
const NOTIFIABLE_EVENT_TYPES: readonly string[] = [
|
|
42
38
|
"session.execution.succeeded",
|
|
43
39
|
"session.execution.failed",
|
|
@@ -47,6 +43,8 @@ const NOTIFIABLE_EVENT_TYPES: readonly string[] = [
|
|
|
47
43
|
"question.v2.asked",
|
|
48
44
|
];
|
|
49
45
|
|
|
46
|
+
const RECONNECT_BACKOFF_MS: readonly number[] = [1_000, 2_000, 4_000, 10_000];
|
|
47
|
+
|
|
50
48
|
function isNotifiable(type: string): boolean {
|
|
51
49
|
return NOTIFIABLE_EVENT_TYPES.includes(type);
|
|
52
50
|
}
|
|
@@ -57,14 +55,24 @@ function record(value: unknown): Record<string, unknown> {
|
|
|
57
55
|
: {};
|
|
58
56
|
}
|
|
59
57
|
|
|
58
|
+
function sessionIDOf(event: V2Event): string | undefined {
|
|
59
|
+
const data = event.data ?? {};
|
|
60
|
+
if (typeof data.sessionID === "string") return data.sessionID;
|
|
61
|
+
const form = record(data.form);
|
|
62
|
+
return typeof form.sessionID === "string" ? form.sessionID : undefined;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function requestIDOf(event: V2Event): string | undefined {
|
|
66
|
+
const data = event.data ?? {};
|
|
67
|
+
if (typeof data.id === "string") return data.id;
|
|
68
|
+
if (typeof data.requestID === "string") return data.requestID;
|
|
69
|
+
const form = record(data.form);
|
|
70
|
+
return typeof form.id === "string" ? form.id : undefined;
|
|
71
|
+
}
|
|
72
|
+
|
|
60
73
|
/**
|
|
61
|
-
* OpenCode 2
|
|
62
|
-
*
|
|
63
|
-
* Location.Service,因此 bus.publish 不会给事件信封写 location 字段(事件数据里
|
|
64
|
-
* 只有 sessionID)。permission / form 事件在 instance 图内发布,带 location。
|
|
65
|
-
* 本插件在多项目实例间靠 location 隔离消费,遇到无 location 的 execution 事件时
|
|
66
|
-
* 回退用 ctx.session.get() 返回的会话登记 location 判定归属;会话查不到时放弃
|
|
67
|
-
* 处理并写丢弃日志,不做跨项目兜底广播。
|
|
74
|
+
* OpenCode 2 的 session.execution.* 生命周期事件由全局协调器发布,事件信封不含 location,
|
|
75
|
+
* 此时回退用会话登记的 location 判定归属;查不到时丢弃,不做跨项目广播。
|
|
68
76
|
*/
|
|
69
77
|
async function eventBelongsToLocation(
|
|
70
78
|
event: V2Event,
|
|
@@ -79,8 +87,9 @@ async function eventBelongsToLocation(
|
|
|
79
87
|
event.location?.workspaceID &&
|
|
80
88
|
location.workspaceID &&
|
|
81
89
|
event.location.workspaceID !== location.workspaceID
|
|
82
|
-
)
|
|
90
|
+
) {
|
|
83
91
|
return false;
|
|
92
|
+
}
|
|
84
93
|
return true;
|
|
85
94
|
}
|
|
86
95
|
const sessionID = sessionIDOf(event);
|
|
@@ -134,26 +143,11 @@ function questionSummary(data: Record<string, unknown>): string | undefined {
|
|
|
134
143
|
);
|
|
135
144
|
}
|
|
136
145
|
|
|
137
|
-
function
|
|
138
|
-
const data = event.data ?? {};
|
|
139
|
-
if (typeof data.sessionID === "string") return data.sessionID;
|
|
140
|
-
const form = record(data.form);
|
|
141
|
-
return typeof form.sessionID === "string" ? form.sessionID : undefined;
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
function requestIDOf(event: V2Event): string | undefined {
|
|
145
|
-
const data = event.data ?? {};
|
|
146
|
-
if (typeof data.id === "string") return data.id;
|
|
147
|
-
if (typeof data.requestID === "string") return data.requestID;
|
|
148
|
-
const form = record(data.form);
|
|
149
|
-
return typeof form.id === "string" ? form.id : undefined;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
function rememberRequest(seen: Set<string>, key: string): boolean {
|
|
153
|
-
if (seen.has(key)) return false;
|
|
146
|
+
function markRequestSeen(seen: Set<string>, key: string): void {
|
|
154
147
|
seen.add(key);
|
|
155
|
-
if (seen.size > 1_024)
|
|
156
|
-
|
|
148
|
+
if (seen.size > 1_024) {
|
|
149
|
+
seen.delete(seen.values().next().value!);
|
|
150
|
+
}
|
|
157
151
|
}
|
|
158
152
|
|
|
159
153
|
function unwrapSessionInfo(value: unknown): SessionInfo {
|
|
@@ -162,13 +156,40 @@ function unwrapSessionInfo(value: unknown): SessionInfo {
|
|
|
162
156
|
const candidate = Object.keys(wrapped).length > 0 ? wrapped : outer;
|
|
163
157
|
const location = record(candidate.location);
|
|
164
158
|
return {
|
|
165
|
-
title: compactText(candidate.title,
|
|
159
|
+
title: compactText(candidate.title, MAX_SESSION_TITLE_BYTES) || undefined,
|
|
166
160
|
parentID: typeof candidate.parentID === "string" ? candidate.parentID : undefined,
|
|
167
161
|
directory: typeof location.directory === "string" ? location.directory : undefined,
|
|
168
162
|
workspaceID: typeof location.workspaceID === "string" ? location.workspaceID : undefined,
|
|
169
163
|
};
|
|
170
164
|
}
|
|
171
165
|
|
|
166
|
+
function waitWithAbort(ms: number, signal: AbortSignal): Promise<void> {
|
|
167
|
+
if (signal.aborted || ms <= 0) return Promise.resolve();
|
|
168
|
+
return new Promise((resolve) => {
|
|
169
|
+
const timer = setTimeout(() => {
|
|
170
|
+
signal.removeEventListener("abort", onAbort);
|
|
171
|
+
resolve();
|
|
172
|
+
}, ms);
|
|
173
|
+
const onAbort = () => {
|
|
174
|
+
clearTimeout(timer);
|
|
175
|
+
resolve();
|
|
176
|
+
};
|
|
177
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function reconnectDelays(): readonly number[] {
|
|
182
|
+
const override = process.env.KKCODE_PLUGIN_RECONNECT_MS;
|
|
183
|
+
if (override) {
|
|
184
|
+
const parsed = override
|
|
185
|
+
.split(",")
|
|
186
|
+
.map((item) => Number(item.trim()))
|
|
187
|
+
.filter((n) => Number.isFinite(n) && n >= 0);
|
|
188
|
+
if (parsed.length > 0) return parsed;
|
|
189
|
+
}
|
|
190
|
+
return RECONNECT_BACKOFF_MS;
|
|
191
|
+
}
|
|
192
|
+
|
|
172
193
|
async function setup(ctx: V2Context): Promise<() => void> {
|
|
173
194
|
const controller = new AbortController();
|
|
174
195
|
const seenRequests = new Set<string>();
|
|
@@ -179,7 +200,7 @@ async function setup(ctx: V2Context): Promise<() => void> {
|
|
|
179
200
|
`v2 plugin loaded | version=${ctx.app.version ?? "unknown"} | project=${projectLabel} | directory=${ctx.location.directory ?? ""}`,
|
|
180
201
|
);
|
|
181
202
|
|
|
182
|
-
const
|
|
203
|
+
const fetchSessionInfo = async (sessionID: string): Promise<SessionInfo> => {
|
|
183
204
|
try {
|
|
184
205
|
return unwrapSessionInfo(await ctx.session.get({ sessionID }));
|
|
185
206
|
} catch (error) {
|
|
@@ -188,22 +209,35 @@ async function setup(ctx: V2Context): Promise<() => void> {
|
|
|
188
209
|
}
|
|
189
210
|
};
|
|
190
211
|
|
|
191
|
-
const report = async (event: V2Event, intent: Omit<NotificationIntent, "projectLabel">) => {
|
|
192
|
-
const info = await getSessionInfo(intent.sessionID);
|
|
193
|
-
await reportNotification({
|
|
194
|
-
...intent,
|
|
195
|
-
eventID: event.id ?? intent.eventID,
|
|
196
|
-
occurredAt: event.created ?? intent.occurredAt,
|
|
197
|
-
projectLabel,
|
|
198
|
-
sessionTitle: info.title,
|
|
199
|
-
});
|
|
200
|
-
await debugLog(`v2 ${event.type} REPORTED | ${intent.sessionID} | type=${intent.type}`);
|
|
201
|
-
};
|
|
202
|
-
|
|
203
212
|
const handle = async (event: V2Event) => {
|
|
213
|
+
// 同一事件生命周期内复用 session.get 结果,避免归属判断与上报各查一次。
|
|
214
|
+
const sessionInfoCache = new Map<string, Promise<SessionInfo>>();
|
|
215
|
+
const getSessionInfo = (sessionID: string): Promise<SessionInfo> => {
|
|
216
|
+
let pending = sessionInfoCache.get(sessionID);
|
|
217
|
+
if (!pending) {
|
|
218
|
+
pending = fetchSessionInfo(sessionID);
|
|
219
|
+
sessionInfoCache.set(sessionID, pending);
|
|
220
|
+
}
|
|
221
|
+
return pending;
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
const report = async (intent: NotificationIntent): Promise<"reported" | "skipped"> => {
|
|
225
|
+
const info = await getSessionInfo(intent.sessionID);
|
|
226
|
+
const outcome = await reportNotification({
|
|
227
|
+
...intent,
|
|
228
|
+
eventID: event.id ?? intent.eventID,
|
|
229
|
+
occurredAt: event.created ?? intent.occurredAt,
|
|
230
|
+
sessionTitle: intent.sessionTitle ?? info.title,
|
|
231
|
+
});
|
|
232
|
+
await debugLog(
|
|
233
|
+
`v2 ${event.type} ${outcome === "reported" ? "REPORTED" : "SKIPPED"} | ${intent.sessionID} | type=${intent.type}`,
|
|
234
|
+
);
|
|
235
|
+
return outcome;
|
|
236
|
+
};
|
|
237
|
+
|
|
204
238
|
const data = event.data ?? {};
|
|
205
239
|
const sessionID = sessionIDOf(event);
|
|
206
|
-
if (!await eventBelongsToLocation(event, ctx.location, getSessionInfo)) {
|
|
240
|
+
if (!(await eventBelongsToLocation(event, ctx.location, getSessionInfo))) {
|
|
207
241
|
if (isNotifiable(event.type)) {
|
|
208
242
|
await debugLog(
|
|
209
243
|
`v2 ${event.type} DROPPED | location mismatch | event=${event.location?.directory ?? (sessionID ? "session-resolved" : "none")} plugin=${ctx.location.directory ?? "none"}`,
|
|
@@ -220,18 +254,15 @@ async function setup(ctx: V2Context): Promise<() => void> {
|
|
|
220
254
|
|
|
221
255
|
if (event.type === "session.execution.succeeded") {
|
|
222
256
|
const info = await getSessionInfo(sessionID);
|
|
223
|
-
await
|
|
224
|
-
eventID: event.id,
|
|
257
|
+
await report({
|
|
225
258
|
sessionID,
|
|
226
259
|
type: info.parentID ? "sub_session.completed" : "session.completed",
|
|
227
|
-
projectLabel,
|
|
228
260
|
sessionTitle: info.title,
|
|
229
|
-
occurredAt: event.created,
|
|
230
261
|
});
|
|
231
262
|
return;
|
|
232
263
|
}
|
|
233
264
|
if (event.type === "session.execution.failed") {
|
|
234
|
-
await report(
|
|
265
|
+
await report({
|
|
235
266
|
sessionID,
|
|
236
267
|
type: "session.error",
|
|
237
268
|
summary: errorSummary(data.error) ?? "OpenCode session failed",
|
|
@@ -241,15 +272,18 @@ async function setup(ctx: V2Context): Promise<() => void> {
|
|
|
241
272
|
if (event.type === "permission.v2.asked" || event.type === "permission.asked") {
|
|
242
273
|
const requestID = requestIDOf(event) ?? event.id;
|
|
243
274
|
const key = `permission:${sessionID}:${requestID ?? ""}`;
|
|
244
|
-
if (
|
|
275
|
+
if (seenRequests.has(key)) {
|
|
245
276
|
await debugLog(`v2 ${event.type} DEDUPED | ${sessionID} | key=${key}`);
|
|
246
277
|
return;
|
|
247
278
|
}
|
|
248
|
-
await report(
|
|
279
|
+
const outcome = await report({
|
|
249
280
|
sessionID,
|
|
250
281
|
type: "permission.asked",
|
|
251
282
|
summary: permissionSummary(data),
|
|
252
283
|
});
|
|
284
|
+
if (outcome === "reported") {
|
|
285
|
+
markRequestSeen(seenRequests, key);
|
|
286
|
+
}
|
|
253
287
|
return;
|
|
254
288
|
}
|
|
255
289
|
if (event.type === "form.created") {
|
|
@@ -259,27 +293,33 @@ async function setup(ctx: V2Context): Promise<() => void> {
|
|
|
259
293
|
return;
|
|
260
294
|
}
|
|
261
295
|
const key = `question:${sessionID}:${requestIDOf(event) ?? event.id ?? ""}`;
|
|
262
|
-
if (
|
|
296
|
+
if (seenRequests.has(key)) {
|
|
263
297
|
await debugLog(`v2 form.created DEDUPED | ${sessionID} | key=${key}`);
|
|
264
298
|
return;
|
|
265
299
|
}
|
|
266
|
-
await report(
|
|
300
|
+
const outcome = await report({ sessionID, type: "question.asked", summary });
|
|
301
|
+
if (outcome === "reported") {
|
|
302
|
+
markRequestSeen(seenRequests, key);
|
|
303
|
+
}
|
|
267
304
|
return;
|
|
268
305
|
}
|
|
269
306
|
if (event.type === "question.v2.asked") {
|
|
270
307
|
const key = `question:${sessionID}:${requestIDOf(event) ?? event.id ?? ""}`;
|
|
271
|
-
if (
|
|
308
|
+
if (seenRequests.has(key)) {
|
|
272
309
|
await debugLog(`v2 ${event.type} DEDUPED | ${sessionID} | key=${key}`);
|
|
273
310
|
return;
|
|
274
311
|
}
|
|
275
312
|
const questions = Array.isArray(data.questions) ? data.questions.map(record) : [];
|
|
276
313
|
const first = questions[0] ?? {};
|
|
277
|
-
await report(
|
|
314
|
+
const outcome = await report({
|
|
278
315
|
sessionID,
|
|
279
316
|
type: "question.asked",
|
|
280
317
|
summary:
|
|
281
318
|
compactText(first.question ?? first.header, 400) || "KKCode is waiting for your answer",
|
|
282
319
|
});
|
|
320
|
+
if (outcome === "reported") {
|
|
321
|
+
markRequestSeen(seenRequests, key);
|
|
322
|
+
}
|
|
283
323
|
return;
|
|
284
324
|
}
|
|
285
325
|
if (isNotifiable(event.type)) {
|
|
@@ -288,12 +328,37 @@ async function setup(ctx: V2Context): Promise<() => void> {
|
|
|
288
328
|
};
|
|
289
329
|
|
|
290
330
|
void (async () => {
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
331
|
+
const delays = reconnectDelays();
|
|
332
|
+
let reconnectAttempt = 0;
|
|
333
|
+
|
|
334
|
+
while (!controller.signal.aborted) {
|
|
335
|
+
let receivedAny = false;
|
|
336
|
+
try {
|
|
337
|
+
for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
|
|
338
|
+
receivedAny = true;
|
|
339
|
+
reconnectAttempt = 0;
|
|
340
|
+
try {
|
|
341
|
+
await handle(event);
|
|
342
|
+
} catch (error) {
|
|
343
|
+
await debugLog(`v2 event handle FAILED | ${event.type} | ${error}`);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
if (!controller.signal.aborted) {
|
|
347
|
+
await debugLog("v2 event stream ENDED unexpectedly, reconnecting");
|
|
348
|
+
}
|
|
349
|
+
} catch (error) {
|
|
350
|
+
if (!controller.signal.aborted) {
|
|
351
|
+
await debugLog(`v2 event stream FAILED | ${error}`);
|
|
352
|
+
}
|
|
294
353
|
}
|
|
295
|
-
|
|
296
|
-
if (
|
|
354
|
+
|
|
355
|
+
if (controller.signal.aborted) break;
|
|
356
|
+
const delayMs = delays[Math.min(reconnectAttempt, delays.length - 1)];
|
|
357
|
+
if (!receivedAny || delayMs > 0) {
|
|
358
|
+
await debugLog(`v2 event stream reconnecting in ${delayMs}ms (attempt=${reconnectAttempt + 1})`);
|
|
359
|
+
await waitWithAbort(delayMs, controller.signal);
|
|
360
|
+
}
|
|
361
|
+
reconnectAttempt += 1;
|
|
297
362
|
}
|
|
298
363
|
})();
|
|
299
364
|
|