@cydm/pie 4.3.7 → 4.3.12
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/dist/builtin/extensions/ask-user/index.js +1 -1
- package/dist/builtin/extensions/cron/index.js +112 -8
- package/dist/builtin/extensions/im-forward/README.md +17 -1
- package/dist/builtin/extensions/im-forward/index.js +918 -347
- package/dist/builtin/extensions/mcp-adapter/index.js +2 -2
- package/dist/builtin/extensions/memory/index.js +10 -3
- package/dist/builtin/extensions/pie-ipc/index.js +179 -378
- package/dist/builtin/extensions/pie-proc/index.js +36 -4
- package/dist/builtin/extensions/plan-mode/index.js +6 -5
- package/dist/builtin/extensions/subagent/index.js +15 -5
- package/dist/builtin/extensions/todo/index.js +6 -2
- package/dist/chunks/{chunk-N3BWFAMZ.js → chunk-EGNGHINP.js} +521 -161
- package/dist/chunks/{chunk-BJ4XN5VX.js → chunk-GY47MKCJ.js} +13 -8
- package/dist/chunks/{chunk-2SAFRLFJ.js → chunk-I7PBXG5Q.js} +1 -1
- package/dist/chunks/{chunk-WZLO5V2X.js → chunk-N5B5IGJ6.js} +355 -231
- package/dist/chunks/{manager-cli-QNMCCIFG.js → manager-cli-4Z6RZ7F4.js} +195 -205
- package/dist/chunks/{src-UVULNQOO.js → src-V2M7FLWY.js} +7 -1
- package/dist/cli.js +143 -20
- package/package.json +2 -2
|
@@ -2,6 +2,7 @@ import { createRequire as __createRequire } from "node:module"; const require =
|
|
|
2
2
|
import {
|
|
3
3
|
DISPATCH_PREFIX,
|
|
4
4
|
IPC_PROTOCOL_VERSION,
|
|
5
|
+
addressBookRoot,
|
|
5
6
|
assistantForwardText,
|
|
6
7
|
chunkKey,
|
|
7
8
|
chunkMarkdown,
|
|
@@ -19,131 +20,32 @@ import {
|
|
|
19
20
|
readLiveEnabled,
|
|
20
21
|
registerDispatchReceiver,
|
|
21
22
|
registerTurnImDriver,
|
|
23
|
+
resolveAddress,
|
|
22
24
|
resolveConfig,
|
|
23
25
|
resolveConfigDir,
|
|
24
26
|
resolveImForwardConfig,
|
|
25
27
|
saveLocation,
|
|
26
28
|
sessionLabel,
|
|
29
|
+
signEnvelope,
|
|
27
30
|
truncateMarkdown,
|
|
28
31
|
tryClaimConsumer,
|
|
29
32
|
writeConfig
|
|
30
|
-
} from "../../../chunks/chunk-
|
|
33
|
+
} from "../../../chunks/chunk-EGNGHINP.js";
|
|
31
34
|
import {
|
|
32
35
|
detectImageMime,
|
|
33
36
|
readImageFormat
|
|
34
37
|
} from "../../../chunks/chunk-F7EBZTZO.js";
|
|
35
|
-
import {
|
|
36
|
-
Type
|
|
37
|
-
} from "../../../chunks/chunk-XXGYUYXI.js";
|
|
38
38
|
import "../../../chunks/chunk-LZQXQOPJ.js";
|
|
39
39
|
|
|
40
40
|
// builtin/extensions/im-forward/runtime.ts
|
|
41
41
|
import * as crypto from "node:crypto";
|
|
42
42
|
import * as fs6 from "node:fs";
|
|
43
|
-
import { basename, join as pathJoin, resolve as pathResolve } from "node:path";
|
|
44
|
-
import * as
|
|
43
|
+
import { basename, join as pathJoin, resolve as pathResolve, join as join7 } from "node:path";
|
|
44
|
+
import * as os3 from "node:os";
|
|
45
45
|
|
|
46
|
-
// builtin/extensions/im-forward/
|
|
46
|
+
// builtin/extensions/im-forward/thread-registry.ts
|
|
47
47
|
import * as fs from "node:fs";
|
|
48
|
-
import * as os from "node:os";
|
|
49
48
|
import * as path from "node:path";
|
|
50
|
-
var MAX_ADDRESS_HEAD = 64;
|
|
51
|
-
function addressBookRoot() {
|
|
52
|
-
const raw = process.env.PIE_IPC_CONFIG_DIR;
|
|
53
|
-
if (raw && raw.trim()) {
|
|
54
|
-
const value = raw.trim();
|
|
55
|
-
const expanded = value === "~" ? os.homedir() : value.startsWith("~/") ? path.join(os.homedir(), value.slice(2)) : value;
|
|
56
|
-
return path.resolve(expanded);
|
|
57
|
-
}
|
|
58
|
-
return path.resolve(resolveConfigDir());
|
|
59
|
-
}
|
|
60
|
-
function pidAlive(pid) {
|
|
61
|
-
if (!Number.isInteger(pid) || pid <= 0) return true;
|
|
62
|
-
try {
|
|
63
|
-
process.kill(pid, 0);
|
|
64
|
-
return true;
|
|
65
|
-
} catch (error) {
|
|
66
|
-
return error.code === "EPERM";
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
function scanAddressBook() {
|
|
70
|
-
const names = /* @__PURE__ */ new Map();
|
|
71
|
-
let complete = true;
|
|
72
|
-
let selfPublished;
|
|
73
|
-
let dirExists = false;
|
|
74
|
-
const dir = path.join(addressBookRoot(), "run", "ipc");
|
|
75
|
-
let entries;
|
|
76
|
-
try {
|
|
77
|
-
entries = fs.readdirSync(dir);
|
|
78
|
-
dirExists = true;
|
|
79
|
-
} catch (error) {
|
|
80
|
-
if (error.code === "ENOENT") return { names, complete: true, dirExists: false };
|
|
81
|
-
return { names, complete: false, dirExists: true };
|
|
82
|
-
}
|
|
83
|
-
for (const [index, file] of entries.entries()) {
|
|
84
|
-
if (!file.endsWith(".json")) continue;
|
|
85
|
-
try {
|
|
86
|
-
const status = JSON.parse(fs.readFileSync(path.join(dir, file), "utf8"));
|
|
87
|
-
dirExists = true;
|
|
88
|
-
const name = typeof status.sessionName === "string" ? status.sessionName.trim() : "";
|
|
89
|
-
const pid = typeof status.pid === "number" ? status.pid : void 0;
|
|
90
|
-
if (!name) continue;
|
|
91
|
-
if (pid === process.pid) {
|
|
92
|
-
selfPublished = name;
|
|
93
|
-
continue;
|
|
94
|
-
}
|
|
95
|
-
if (pid !== void 0 && !pidAlive(pid)) continue;
|
|
96
|
-
const owners = names.get(name) ?? /* @__PURE__ */ new Set();
|
|
97
|
-
owners.add(pid ?? -(index + 1));
|
|
98
|
-
names.set(name, owners);
|
|
99
|
-
} catch {
|
|
100
|
-
complete = false;
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
return { names, selfPublished, complete, dirExists };
|
|
104
|
-
}
|
|
105
|
-
var SEPARATORS = [":", "\uFF1A"];
|
|
106
|
-
function matchAddressName(text, candidates) {
|
|
107
|
-
const trimmed = text.trimStart();
|
|
108
|
-
let best;
|
|
109
|
-
for (const name of candidates) {
|
|
110
|
-
const value = name?.trim();
|
|
111
|
-
if (!value) continue;
|
|
112
|
-
if (!SEPARATORS.some((sep) => trimmed.startsWith(`${value}${sep}`))) continue;
|
|
113
|
-
if (!best || value.length > best.length) best = value;
|
|
114
|
-
}
|
|
115
|
-
return best;
|
|
116
|
-
}
|
|
117
|
-
function resolveAddress(text, ownLiveName, book) {
|
|
118
|
-
if (!/[::]/.test(text)) return { kind: "none" };
|
|
119
|
-
const resolvedBook = book ?? scanAddressBook();
|
|
120
|
-
const candidates = new Set(resolvedBook.names.keys());
|
|
121
|
-
if (resolvedBook.selfPublished) candidates.add(resolvedBook.selfPublished);
|
|
122
|
-
const live = ownLiveName?.trim();
|
|
123
|
-
if (live) candidates.add(live);
|
|
124
|
-
const name = matchAddressName(text, candidates);
|
|
125
|
-
if (!name) {
|
|
126
|
-
if (!resolvedBook.complete) {
|
|
127
|
-
return { kind: "ambiguous", name: text.trim().slice(0, MAX_ADDRESS_HEAD), reason: "address book unreadable" };
|
|
128
|
-
}
|
|
129
|
-
return { kind: "none" };
|
|
130
|
-
}
|
|
131
|
-
const body = text.trimStart().slice(name.length + 1).trim();
|
|
132
|
-
const foreignOwners = resolvedBook.names.get(name);
|
|
133
|
-
if (foreignOwners && foreignOwners.size > 0) {
|
|
134
|
-
if (resolvedBook.selfPublished === name || live === name) return { kind: "ambiguous", name, reason: "duplicate live session name" };
|
|
135
|
-
return { kind: "other", name };
|
|
136
|
-
}
|
|
137
|
-
if (!resolvedBook.complete) return { kind: "ambiguous", name, reason: "address book unreadable" };
|
|
138
|
-
const acceptName = resolvedBook.selfPublished ?? (resolvedBook.dirExists ? void 0 : live);
|
|
139
|
-
if (!acceptName) return { kind: "ambiguous", name, reason: "own advertisement not published" };
|
|
140
|
-
if (name === acceptName) return { kind: "self", body };
|
|
141
|
-
return { kind: "ambiguous", name, reason: "unpublished address" };
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
// builtin/extensions/im-forward/thread-registry.ts
|
|
145
|
-
import * as fs2 from "node:fs";
|
|
146
|
-
import * as path2 from "node:path";
|
|
147
49
|
import { randomUUID } from "node:crypto";
|
|
148
50
|
var SCHEMA = 1;
|
|
149
51
|
var RUNTIME_ID = randomUUID();
|
|
@@ -152,9 +54,9 @@ function encodeThreadKey(input) {
|
|
|
152
54
|
return Buffer.from(raw, "utf8").toString("base64url");
|
|
153
55
|
}
|
|
154
56
|
function threadsDir() {
|
|
155
|
-
return
|
|
57
|
+
return path.join(addressBookRoot(), "threads");
|
|
156
58
|
}
|
|
157
|
-
function
|
|
59
|
+
function pidAlive(pid) {
|
|
158
60
|
if (!Number.isInteger(pid) || pid <= 0) return true;
|
|
159
61
|
try {
|
|
160
62
|
process.kill(pid, 0);
|
|
@@ -164,13 +66,13 @@ function pidAlive2(pid) {
|
|
|
164
66
|
}
|
|
165
67
|
}
|
|
166
68
|
function ownerPath(threadKey) {
|
|
167
|
-
return
|
|
69
|
+
return path.join(threadsDir(), `${threadKey}.json`);
|
|
168
70
|
}
|
|
169
71
|
function readOwner(threadKey) {
|
|
170
72
|
const file = ownerPath(threadKey);
|
|
171
73
|
let raw;
|
|
172
74
|
try {
|
|
173
|
-
raw = JSON.parse(
|
|
75
|
+
raw = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
174
76
|
} catch (error) {
|
|
175
77
|
const code = error.code;
|
|
176
78
|
if (code === "ENOENT") return {};
|
|
@@ -197,7 +99,7 @@ function recordFor(threadKey, sessionId) {
|
|
|
197
99
|
function takeOver(threadKey, _dead, sessionId) {
|
|
198
100
|
const file = ownerPath(threadKey);
|
|
199
101
|
try {
|
|
200
|
-
|
|
102
|
+
fs.rmSync(file, { force: true });
|
|
201
103
|
} catch {
|
|
202
104
|
return { claimed: false, reason: "thread registry unavailable", transient: true };
|
|
203
105
|
}
|
|
@@ -207,7 +109,7 @@ function decide(owner, threadKey, sessionId) {
|
|
|
207
109
|
if (owner.sessionId === sessionId && owner.runtimeId === RUNTIME_ID) {
|
|
208
110
|
return { claimed: true, ownerSessionId: sessionId };
|
|
209
111
|
}
|
|
210
|
-
if (owner.pid > 0 && !
|
|
112
|
+
if (owner.pid > 0 && !pidAlive(owner.pid)) {
|
|
211
113
|
return takeOver(threadKey, owner, sessionId);
|
|
212
114
|
}
|
|
213
115
|
return {
|
|
@@ -219,32 +121,32 @@ function decide(owner, threadKey, sessionId) {
|
|
|
219
121
|
function writeNew(threadKey, sessionId) {
|
|
220
122
|
const file = ownerPath(threadKey);
|
|
221
123
|
const record = recordFor(threadKey, sessionId);
|
|
222
|
-
const tmp =
|
|
124
|
+
const tmp = path.join(threadsDir(), `.new-${randomUUID()}.json`);
|
|
223
125
|
try {
|
|
224
|
-
const fd =
|
|
126
|
+
const fd = fs.openSync(tmp, "wx", 384);
|
|
225
127
|
try {
|
|
226
|
-
|
|
128
|
+
fs.writeFileSync(fd, JSON.stringify(record));
|
|
227
129
|
try {
|
|
228
|
-
|
|
130
|
+
fs.fsyncSync(fd);
|
|
229
131
|
} catch (error) {
|
|
230
132
|
try {
|
|
231
|
-
|
|
133
|
+
fs.closeSync(fd);
|
|
232
134
|
} catch {
|
|
233
135
|
}
|
|
234
136
|
try {
|
|
235
|
-
|
|
137
|
+
fs.rmSync(tmp, { force: true });
|
|
236
138
|
} catch {
|
|
237
139
|
}
|
|
238
140
|
return { claimed: false, reason: "thread registry unavailable", transient: true };
|
|
239
141
|
}
|
|
240
142
|
} finally {
|
|
241
|
-
|
|
143
|
+
fs.closeSync(fd);
|
|
242
144
|
}
|
|
243
145
|
} catch {
|
|
244
146
|
return { claimed: false, reason: "thread registry unavailable", transient: true };
|
|
245
147
|
}
|
|
246
148
|
try {
|
|
247
|
-
|
|
149
|
+
fs.linkSync(tmp, file);
|
|
248
150
|
return { claimed: true, ownerSessionId: sessionId };
|
|
249
151
|
} catch (error) {
|
|
250
152
|
const code = error.code;
|
|
@@ -257,7 +159,7 @@ function writeNew(threadKey, sessionId) {
|
|
|
257
159
|
return { claimed: false, reason: "thread registry unavailable", transient: true };
|
|
258
160
|
} finally {
|
|
259
161
|
try {
|
|
260
|
-
|
|
162
|
+
fs.rmSync(tmp, { force: true });
|
|
261
163
|
} catch {
|
|
262
164
|
}
|
|
263
165
|
}
|
|
@@ -267,7 +169,7 @@ function claimThreadOwnership(input, sessionId) {
|
|
|
267
169
|
const threadKey = encodeThreadKey(input);
|
|
268
170
|
let stat;
|
|
269
171
|
try {
|
|
270
|
-
stat =
|
|
172
|
+
stat = fs.statSync(threadsDir());
|
|
271
173
|
} catch (error) {
|
|
272
174
|
if (error.code !== "ENOENT") {
|
|
273
175
|
return { claimed: false, reason: "thread registry unavailable", transient: true };
|
|
@@ -276,7 +178,7 @@ function claimThreadOwnership(input, sessionId) {
|
|
|
276
178
|
}
|
|
277
179
|
if (stat && !stat.isDirectory()) return { claimed: false, reason: "thread registry unavailable", transient: true };
|
|
278
180
|
try {
|
|
279
|
-
|
|
181
|
+
fs.mkdirSync(threadsDir(), { recursive: true, mode: 448 });
|
|
280
182
|
} catch {
|
|
281
183
|
return { claimed: false, reason: "thread registry unavailable", transient: true };
|
|
282
184
|
}
|
|
@@ -294,15 +196,15 @@ function claimThreadOwnership(input, sessionId) {
|
|
|
294
196
|
}
|
|
295
197
|
}
|
|
296
198
|
function lockDirPath(threadKey) {
|
|
297
|
-
return
|
|
199
|
+
return path.join(threadsDir(), `${threadKey}.lock`);
|
|
298
200
|
}
|
|
299
201
|
function writeHolderEntry(dir, token) {
|
|
300
|
-
|
|
202
|
+
fs.writeFileSync(path.join(dir, `held.${token}`), JSON.stringify({ version: 1, pid: process.pid, createdAt: Date.now() }), { mode: 384, flag: "wx" });
|
|
301
203
|
}
|
|
302
204
|
function retireStaleLock(lock) {
|
|
303
205
|
let entries;
|
|
304
206
|
try {
|
|
305
|
-
entries =
|
|
207
|
+
entries = fs.readdirSync(lock);
|
|
306
208
|
} catch {
|
|
307
209
|
return false;
|
|
308
210
|
}
|
|
@@ -310,7 +212,7 @@ function retireStaleLock(lock) {
|
|
|
310
212
|
if (holders.length === 0) {
|
|
311
213
|
if (entries.length !== 0) return false;
|
|
312
214
|
try {
|
|
313
|
-
|
|
215
|
+
fs.rmdirSync(lock);
|
|
314
216
|
return true;
|
|
315
217
|
} catch {
|
|
316
218
|
return false;
|
|
@@ -319,7 +221,7 @@ function retireStaleLock(lock) {
|
|
|
319
221
|
for (const name of holders) {
|
|
320
222
|
let pid;
|
|
321
223
|
try {
|
|
322
|
-
const parsed = JSON.parse(
|
|
224
|
+
const parsed = JSON.parse(fs.readFileSync(path.join(lock, name), "utf8"));
|
|
323
225
|
if (parsed?.version !== 1 || !Number.isInteger(parsed.pid) || parsed.pid <= 0) return false;
|
|
324
226
|
pid = parsed.pid;
|
|
325
227
|
} catch {
|
|
@@ -334,13 +236,13 @@ function retireStaleLock(lock) {
|
|
|
334
236
|
}
|
|
335
237
|
for (const name of holders) {
|
|
336
238
|
try {
|
|
337
|
-
|
|
239
|
+
fs.unlinkSync(path.join(lock, name));
|
|
338
240
|
} catch (error) {
|
|
339
241
|
if (error.code !== "ENOENT") return false;
|
|
340
242
|
}
|
|
341
243
|
}
|
|
342
244
|
try {
|
|
343
|
-
|
|
245
|
+
fs.rmdirSync(lock);
|
|
344
246
|
return true;
|
|
345
247
|
} catch {
|
|
346
248
|
return false;
|
|
@@ -351,10 +253,10 @@ function acquireThreadLock(threadKey) {
|
|
|
351
253
|
if (acquiredLocks.has(threadKey)) return { acquired: true };
|
|
352
254
|
const lock = lockDirPath(threadKey);
|
|
353
255
|
const token = randomUUID();
|
|
354
|
-
const candidate =
|
|
256
|
+
const candidate = path.join(threadsDir(), `lock.acquire.${token}`);
|
|
355
257
|
try {
|
|
356
258
|
try {
|
|
357
|
-
|
|
259
|
+
fs.mkdirSync(candidate, { mode: 448 });
|
|
358
260
|
} catch {
|
|
359
261
|
return { acquired: false, reason: "thread registry unavailable", transient: true };
|
|
360
262
|
}
|
|
@@ -362,7 +264,7 @@ function acquireThreadLock(threadKey) {
|
|
|
362
264
|
writeHolderEntry(candidate, token);
|
|
363
265
|
} catch {
|
|
364
266
|
try {
|
|
365
|
-
|
|
267
|
+
fs.rmSync(candidate, { recursive: true, force: true });
|
|
366
268
|
} catch {
|
|
367
269
|
}
|
|
368
270
|
return { acquired: false, reason: "thread registry unavailable", transient: true };
|
|
@@ -370,7 +272,7 @@ function acquireThreadLock(threadKey) {
|
|
|
370
272
|
const deadline = Date.now() + 5e3;
|
|
371
273
|
for (; ; ) {
|
|
372
274
|
try {
|
|
373
|
-
|
|
275
|
+
fs.renameSync(candidate, lock);
|
|
374
276
|
acquiredLocks.set(threadKey, token);
|
|
375
277
|
return { acquired: true };
|
|
376
278
|
} catch (error) {
|
|
@@ -388,7 +290,7 @@ function acquireThreadLock(threadKey) {
|
|
|
388
290
|
}
|
|
389
291
|
} finally {
|
|
390
292
|
try {
|
|
391
|
-
|
|
293
|
+
fs.rmSync(candidate, { recursive: true, force: true });
|
|
392
294
|
} catch {
|
|
393
295
|
}
|
|
394
296
|
}
|
|
@@ -399,12 +301,12 @@ function releaseThreadLock(threadKey) {
|
|
|
399
301
|
acquiredLocks.delete(threadKey);
|
|
400
302
|
const lock = lockDirPath(threadKey);
|
|
401
303
|
try {
|
|
402
|
-
|
|
304
|
+
fs.unlinkSync(path.join(lock, `held.${token}`));
|
|
403
305
|
} catch {
|
|
404
306
|
}
|
|
405
307
|
try {
|
|
406
|
-
const remaining =
|
|
407
|
-
if (remaining.length === 0)
|
|
308
|
+
const remaining = fs.readdirSync(lock);
|
|
309
|
+
if (remaining.length === 0) fs.rmdirSync(lock);
|
|
408
310
|
} catch {
|
|
409
311
|
}
|
|
410
312
|
}
|
|
@@ -418,21 +320,180 @@ function threadOwner(input) {
|
|
|
418
320
|
}
|
|
419
321
|
if (read.corrupt) return { corrupt: true };
|
|
420
322
|
if (!read.owner) return {};
|
|
421
|
-
if (read.owner.pid > 0 && !
|
|
323
|
+
if (read.owner.pid > 0 && !pidAlive(read.owner.pid)) {
|
|
422
324
|
return {};
|
|
423
325
|
}
|
|
424
326
|
return { sessionId: read.owner.sessionId };
|
|
425
327
|
}
|
|
426
328
|
|
|
329
|
+
// builtin/extensions/im-forward/panel.ts
|
|
330
|
+
import * as fs2 from "node:fs";
|
|
331
|
+
import * as os2 from "node:os";
|
|
332
|
+
import * as path3 from "node:path";
|
|
333
|
+
|
|
334
|
+
// builtin/extensions/im-forward/discovery.ts
|
|
335
|
+
import * as os from "node:os";
|
|
336
|
+
import * as path2 from "node:path";
|
|
337
|
+
function ipcDiscoveryRoot() {
|
|
338
|
+
const home = os.homedir() || process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
339
|
+
const override = process.env.PIE_IPC_CONFIG_DIR;
|
|
340
|
+
const agentDir = process.env.PIE_CODING_AGENT_DIR?.trim();
|
|
341
|
+
const raw = override !== void 0 ? override : agentDir || path2.join(home, ".pie");
|
|
342
|
+
const configDir = process.platform === "win32" ? raw : path2.resolve(raw === "~" ? home : raw.startsWith("~/") ? path2.join(home, raw.slice(2)) : raw);
|
|
343
|
+
return path2.join(configDir, "run", "ipc");
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// builtin/extensions/im-forward/panel.ts
|
|
347
|
+
function parsePanelCommand(text) {
|
|
348
|
+
const trimmed = text.trim();
|
|
349
|
+
if (!trimmed.startsWith("/")) return void 0;
|
|
350
|
+
const body = trimmed.slice(1);
|
|
351
|
+
const headMatch = /^(\S+)(?:\s+(.*))?$/s.exec(body);
|
|
352
|
+
if (!headMatch) return void 0;
|
|
353
|
+
const head = headMatch[1];
|
|
354
|
+
let cmd = head;
|
|
355
|
+
let rest = headMatch[2] ?? "";
|
|
356
|
+
if (head === "card") {
|
|
357
|
+
const next = /^(\S+)(?:\s+(.*))?$/s.exec(rest);
|
|
358
|
+
cmd = next?.[1] ?? "";
|
|
359
|
+
rest = next?.[2] ?? "";
|
|
360
|
+
}
|
|
361
|
+
if (cmd !== "panel" && cmd !== "panel.refresh" && cmd !== "panel.summon" && cmd !== "panel.models" && cmd !== "panel.help" && cmd !== "\u9762\u677F") {
|
|
362
|
+
if (!/^panel\.model\.[A-Za-z0-9-]+\..+$/.test(cmd)) return void 0;
|
|
363
|
+
}
|
|
364
|
+
const leadingFlag = /^--restricted(?:\s+|$)/.exec(rest);
|
|
365
|
+
const restricted = leadingFlag !== null;
|
|
366
|
+
const payloadText = rest.slice(leadingFlag ? leadingFlag[0].length : 0).trim();
|
|
367
|
+
let payload;
|
|
368
|
+
if (payloadText.length > 0) {
|
|
369
|
+
try {
|
|
370
|
+
payload = JSON.parse(payloadText);
|
|
371
|
+
} catch {
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
return { cmd, restricted, payload };
|
|
375
|
+
}
|
|
376
|
+
function scanPeers() {
|
|
377
|
+
const out = [];
|
|
378
|
+
try {
|
|
379
|
+
const dir = ipcDiscoveryRoot();
|
|
380
|
+
for (const file of fs2.readdirSync(dir).slice(0, 64)) {
|
|
381
|
+
if (!file.endsWith(".json")) continue;
|
|
382
|
+
try {
|
|
383
|
+
const parsed = JSON.parse(fs2.readFileSync(path3.join(dir, file), "utf8"));
|
|
384
|
+
if (typeof parsed.sessionId !== "string" || typeof parsed.pid !== "number") continue;
|
|
385
|
+
if (typeof parsed.instanceId !== "string" || !parsed.instanceId) continue;
|
|
386
|
+
try {
|
|
387
|
+
process.kill(parsed.pid, 0);
|
|
388
|
+
} catch {
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
out.push({
|
|
392
|
+
name: parsed.displayName ?? parsed.sessionId.slice(0, 12),
|
|
393
|
+
instanceId: parsed.instanceId,
|
|
394
|
+
sessionId: parsed.sessionId,
|
|
395
|
+
state: typeof parsed.state === "string" ? parsed.state : "?",
|
|
396
|
+
unattended: parsed.unattended === true,
|
|
397
|
+
sessionTitle: typeof parsed.displaySessionName === "string" && parsed.displaySessionName.trim() ? parsed.displaySessionName.trim() : void 0,
|
|
398
|
+
project: typeof parsed.cwd === "string" && parsed.cwd ? parsed.cwd.split("/").filter(Boolean).at(-1) : void 0,
|
|
399
|
+
currentTool: typeof parsed.currentTool === "string" && parsed.currentTool ? parsed.currentTool : void 0,
|
|
400
|
+
model: typeof parsed.model === "string" && parsed.model ? parsed.model : void 0
|
|
401
|
+
});
|
|
402
|
+
} catch {
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
} catch {
|
|
406
|
+
}
|
|
407
|
+
return out.sort((a, b) => a.unattended === b.unattended ? a.name.localeCompare(b.name) : a.unattended ? -1 : 1);
|
|
408
|
+
}
|
|
409
|
+
function composePanel() {
|
|
410
|
+
const peers = scanPeers();
|
|
411
|
+
const rows = peers.map((p) => {
|
|
412
|
+
const title = p.sessionTitle ?? p.name;
|
|
413
|
+
const state = p.state === "working" && p.currentTool ? `working\xB7${p.currentTool}` : p.state;
|
|
414
|
+
const project = p.project && p.project !== title ? `\uFF08${p.project}\uFF09` : "";
|
|
415
|
+
return `| ${title}${project} | ${p.model ?? "\u2014"} | ${state} |
|
|
416
|
+
| \u21B3 ${p.name} | | |`;
|
|
417
|
+
});
|
|
418
|
+
const body = [
|
|
419
|
+
peers.length > 0 ? `| \u4F1A\u8BDD | \u6A21\u578B | \u72B6\u6001 |
|
|
420
|
+
|---|---|---|
|
|
421
|
+
${rows.join("\n")}` : "_\u6CA1\u6709\u5B58\u6D3B\u7684 pie \u4F1A\u8BDD_",
|
|
422
|
+
``,
|
|
423
|
+
`\u5171 ${peers.length} \u4E2A\u4F1A\u8BDD \xB7 ${(/* @__PURE__ */ new Date()).toLocaleTimeString("zh-CN", { hour12: false })}`
|
|
424
|
+
].join("\n");
|
|
425
|
+
return {
|
|
426
|
+
title: "Pie \u7BA1\u7406\u9762\u677F",
|
|
427
|
+
subtitle: `${os2.hostname()} \xB7 ${peers.length} \u4F1A\u8BDD`,
|
|
428
|
+
color: "blue",
|
|
429
|
+
body,
|
|
430
|
+
// r1-P2: only REGISTERED commands get buttons — unmapped ids would fall
|
|
431
|
+
// through to an LLM turn (a button press must never spend a model turn).
|
|
432
|
+
actions: [
|
|
433
|
+
{ id: "panel.refresh", label: "\u{1F504} \u5237\u65B0" },
|
|
434
|
+
{ id: "panel.summon", label: "\u{1F4CB} \u91CD\u65B0\u53EC\u5524" },
|
|
435
|
+
{ id: "panel.models", label: "\u{1F39A} \u5207\u6A21\u578B" },
|
|
436
|
+
{ id: "panel.help", label: "\u2753 \u547D\u4EE4" }
|
|
437
|
+
]
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
function candidateModels() {
|
|
441
|
+
const out = /* @__PURE__ */ new Set();
|
|
442
|
+
try {
|
|
443
|
+
const configRoot = path3.dirname(path3.dirname(ipcDiscoveryRoot()));
|
|
444
|
+
const config = JSON.parse(fs2.readFileSync(path3.join(configRoot, "models.json"), "utf8"));
|
|
445
|
+
const d = config.defaults ?? {};
|
|
446
|
+
if (d.provider && d.modelId) out.add(`${d.provider}/${d.modelId}`);
|
|
447
|
+
for (const cls of Object.values(d.modelClasses ?? {})) {
|
|
448
|
+
if (cls?.provider && cls?.modelId) out.add(`${cls.provider}/${cls.modelId}`);
|
|
449
|
+
}
|
|
450
|
+
} catch {
|
|
451
|
+
}
|
|
452
|
+
return [...out];
|
|
453
|
+
}
|
|
454
|
+
function executePanelCommand(input) {
|
|
455
|
+
if (input.cmd === "panel.models") {
|
|
456
|
+
const peers = scanPeers();
|
|
457
|
+
const models = candidateModels();
|
|
458
|
+
const rows = peers.map((p) => `| ${p.sessionTitle ?? p.name} | ${p.model ?? "\u2014"} |`);
|
|
459
|
+
const actions = peers.flatMap(
|
|
460
|
+
(p) => models.map((m) => ({ id: `panel.model.${p.instanceId}.${m}`, label: `${p.name.slice(0, 10)}\u2192${m.split("/")[1]?.slice(0, 14) ?? m}` }))
|
|
461
|
+
).slice(0, 18);
|
|
462
|
+
return { spec: {
|
|
463
|
+
title: "\u5207\u6362\u6A21\u578B",
|
|
464
|
+
subtitle: `${peers.length} \u4F1A\u8BDD \xD7 ${models.length} \u5019\u9009`,
|
|
465
|
+
color: "violet",
|
|
466
|
+
body: [
|
|
467
|
+
peers.length > 0 ? `| \u4F1A\u8BDD | \u5F53\u524D\u6A21\u578B |
|
|
468
|
+
|---|---|
|
|
469
|
+
${rows.join("\n")}` : "_\u6CA1\u6709\u5B58\u6D3B\u7684 pie \u4F1A\u8BDD_",
|
|
470
|
+
``,
|
|
471
|
+
`\u5019\u9009\uFF1A${models.join(" \xB7 ") || "\uFF08models.json \u4E0D\u53EF\u8BFB\uFF09"}`,
|
|
472
|
+
``,
|
|
473
|
+
"\u6309\u94AE\u683C\u5F0F\uFF1A\u4F1A\u8BDD\u2192\u6A21\u578B\u3002\u70B9\u6309\u5373\u53D1 model.set \u63A7\u5236\u5E27\uFF08\u96F6 LLM\u3001\u4E0D\u8FDB\u5BF9\u65B9\u5386\u53F2\uFF09\u3002"
|
|
474
|
+
].join("\n"),
|
|
475
|
+
actions: actions.length > 0 ? actions : [{ id: "panel.summon", label: "\u21A9\uFE0F \u8FD4\u56DE\u9762\u677F" }]
|
|
476
|
+
}, patchOrigin: false };
|
|
477
|
+
}
|
|
478
|
+
if (input.cmd === "panel.help") {
|
|
479
|
+
return { spec: {
|
|
480
|
+
title: "\u9762\u677F\u547D\u4EE4",
|
|
481
|
+
body: "`/panel` \u6216 `/\u9762\u677F` \u53EC\u5524\u72B6\u6001\u9762\u677F\u3002\u5361\u7247\u6309\u94AE\uFF1A\u{1F504} \u5237\u65B0\uFF08\u539F\u5730\u66F4\u65B0\uFF09\u3001\u{1F4CB} \u91CD\u65B0\u53EC\u5524\u3001\u{1F39A} \u5207\u6A21\u578B\u3001\u2753 \u672C\u8BF4\u660E\u3002\u7FA4\u5185\u4EFB\u4F55\u6210\u5458\u53EF\u70B9\uFF0C`--restricted` \u52A8\u4F5C\u9700 allowUsers \u767D\u540D\u5355\u3002",
|
|
482
|
+
actions: [{ id: "panel.summon", label: "\u56DE\u5230\u9762\u677F" }]
|
|
483
|
+
}, patchOrigin: false };
|
|
484
|
+
}
|
|
485
|
+
return { spec: composePanel(), patchOrigin: input.cmd === "panel.refresh" && input.originCardId !== void 0 };
|
|
486
|
+
}
|
|
487
|
+
|
|
427
488
|
// builtin/extensions/im-forward/event-dispatch.ts
|
|
428
489
|
import * as net from "node:net";
|
|
429
490
|
import * as fs3 from "node:fs";
|
|
430
|
-
import * as
|
|
491
|
+
import * as path4 from "node:path";
|
|
431
492
|
import { createHmac, randomUUID as randomUUID2 } from "node:crypto";
|
|
432
493
|
function discoveryDir() {
|
|
433
|
-
return
|
|
494
|
+
return path4.join(addressBookRoot(), "run", "ipc");
|
|
434
495
|
}
|
|
435
|
-
function
|
|
496
|
+
function pidAlive2(pid) {
|
|
436
497
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
437
498
|
try {
|
|
438
499
|
process.kill(pid, 0);
|
|
@@ -452,8 +513,8 @@ function findOwnerInstance(sessionId) {
|
|
|
452
513
|
for (const name of entries.slice(0, 256)) {
|
|
453
514
|
if (!name.endsWith(".json")) continue;
|
|
454
515
|
try {
|
|
455
|
-
const parsed = JSON.parse(fs3.readFileSync(
|
|
456
|
-
if (parsed.instanceId === name.slice(0, -".json".length) && parsed.sessionId === sessionId && parsed.port && typeof parsed.secret === "string" && parsed.protocol === IPC_PROTOCOL_VERSION &&
|
|
516
|
+
const parsed = JSON.parse(fs3.readFileSync(path4.join(discoveryDir(), name), "utf8"));
|
|
517
|
+
if (parsed.instanceId === name.slice(0, -".json".length) && parsed.sessionId === sessionId && parsed.port && typeof parsed.secret === "string" && parsed.protocol === IPC_PROTOCOL_VERSION && pidAlive2(parsed.pid ?? 0)) {
|
|
457
518
|
candidates.push({ file: parsed, startedAt: typeof parsed.startedAt === "number" ? parsed.startedAt : 0 });
|
|
458
519
|
}
|
|
459
520
|
} catch {
|
|
@@ -479,7 +540,12 @@ function deliverOnce(port, secret, text, targetSessionId, targetInstanceId) {
|
|
|
479
540
|
createdAt: Date.now(),
|
|
480
541
|
text,
|
|
481
542
|
sessionId: targetSessionId,
|
|
482
|
-
waitMs: 0
|
|
543
|
+
waitMs: 0,
|
|
544
|
+
replyTo: void 0,
|
|
545
|
+
notifyCompletion: void 0,
|
|
546
|
+
control: void 0,
|
|
547
|
+
userAssigned: void 0,
|
|
548
|
+
subscriberSession: void 0
|
|
483
549
|
};
|
|
484
550
|
const payload = [envelope.v, envelope.id, envelope.from, envelope.to, envelope.kind, envelope.createdAt, envelope.sessionId ?? null, envelope.text ?? null, envelope.replyTo ?? null, envelope.waitMs ?? null, envelope.notifyCompletion ?? null, envelope.control ?? null, envelope.userAssigned ?? null, envelope.subscriberSession ?? null];
|
|
485
551
|
const frame = JSON.stringify({ ...envelope, auth: createHmac("sha256", secret).update(JSON.stringify(payload)).digest("hex") });
|
|
@@ -540,15 +606,15 @@ async function dispatchEventToSession(sessionId, eventText) {
|
|
|
540
606
|
|
|
541
607
|
// builtin/extensions/im-forward/session-roots.ts
|
|
542
608
|
import * as fs4 from "node:fs";
|
|
543
|
-
import * as
|
|
609
|
+
import * as path5 from "node:path";
|
|
544
610
|
function rootsDir() {
|
|
545
|
-
return
|
|
611
|
+
return path5.join(addressBookRoot(), "im-forward", "roots");
|
|
546
612
|
}
|
|
547
613
|
function rootPath(provider, messageId) {
|
|
548
614
|
const safe = `${provider}:${messageId}`.replace(/[^a-zA-Z0-9._:-]/g, "_");
|
|
549
|
-
return
|
|
615
|
+
return path5.join(rootsDir(), `${safe}.json`);
|
|
550
616
|
}
|
|
551
|
-
function
|
|
617
|
+
function pidAlive3(pid) {
|
|
552
618
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
553
619
|
try {
|
|
554
620
|
process.kill(pid, 0);
|
|
@@ -572,7 +638,7 @@ function sessionRootOwner(provider, messageId) {
|
|
|
572
638
|
try {
|
|
573
639
|
const parsed = JSON.parse(fs4.readFileSync(rootPath(provider, messageId), "utf8"));
|
|
574
640
|
if (typeof parsed.sessionId === "string" && parsed.sessionId && typeof parsed.pid === "number") {
|
|
575
|
-
if (!
|
|
641
|
+
if (!pidAlive3(parsed.pid)) return void 0;
|
|
576
642
|
return { sessionId: parsed.sessionId, pid: parsed.pid, claimedAt: parsed.claimedAt ?? 0 };
|
|
577
643
|
}
|
|
578
644
|
return void 0;
|
|
@@ -583,13 +649,13 @@ function sessionRootOwner(provider, messageId) {
|
|
|
583
649
|
|
|
584
650
|
// builtin/extensions/im-forward/session-anchors.ts
|
|
585
651
|
import * as fs5 from "node:fs";
|
|
586
|
-
import * as
|
|
652
|
+
import * as path6 from "node:path";
|
|
587
653
|
function anchorsDir() {
|
|
588
|
-
return
|
|
654
|
+
return path6.join(addressBookRoot(), "im-forward", "anchors");
|
|
589
655
|
}
|
|
590
656
|
function anchorPath(sessionId) {
|
|
591
657
|
const safe = sessionId.replace(/[^a-zA-Z0-9._-]/g, "_");
|
|
592
|
-
return
|
|
658
|
+
return path6.join(anchorsDir(), `${safe}.json`);
|
|
593
659
|
}
|
|
594
660
|
function loadPersistedAnchor(sessionId, identity) {
|
|
595
661
|
try {
|
|
@@ -622,7 +688,7 @@ function savePersistedAnchor(sessionId, identity, anchor) {
|
|
|
622
688
|
anchor
|
|
623
689
|
};
|
|
624
690
|
const target = anchorPath(sessionId);
|
|
625
|
-
fs5.mkdirSync(
|
|
691
|
+
fs5.mkdirSync(path6.dirname(target), { recursive: true });
|
|
626
692
|
fs5.writeFileSync(target, `${JSON.stringify(file)}
|
|
627
693
|
`, "utf8");
|
|
628
694
|
} catch {
|
|
@@ -668,17 +734,82 @@ function hashText(input) {
|
|
|
668
734
|
}
|
|
669
735
|
return Math.abs(hash).toString(36);
|
|
670
736
|
}
|
|
671
|
-
function
|
|
672
|
-
const home =
|
|
737
|
+
function ipcDiscoveryRoot2() {
|
|
738
|
+
const home = os3.homedir() || process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
673
739
|
const override = process.env.PIE_IPC_CONFIG_DIR;
|
|
674
740
|
const raw = override !== void 0 ? override : resolveConfigDir();
|
|
675
741
|
const configDir = process.platform === "win32" ? raw : pathResolve(raw === "~" ? home : raw.startsWith("~/") ? pathJoin(home, raw.slice(2)) : raw);
|
|
676
742
|
return pathJoin(configDir, "run", "ipc");
|
|
677
743
|
}
|
|
744
|
+
async function applyModelControl(peerRef, model) {
|
|
745
|
+
const net2 = await import("node:net");
|
|
746
|
+
let target;
|
|
747
|
+
try {
|
|
748
|
+
const dir = ipcDiscoveryRoot2();
|
|
749
|
+
for (const file of fs6.readdirSync(dir).filter((f) => f.endsWith(".json"))) {
|
|
750
|
+
const parsed = JSON.parse(fs6.readFileSync(join7(dir, file), "utf8"));
|
|
751
|
+
if (!parsed.port || !parsed.secret || typeof parsed.pid !== "number" || !parsed.instanceId) continue;
|
|
752
|
+
const match = parsed.instanceId === peerRef || parsed.instanceId.startsWith(peerRef) || parsed.displayName === peerRef;
|
|
753
|
+
if (!match) continue;
|
|
754
|
+
try {
|
|
755
|
+
process.kill(parsed.pid, 0);
|
|
756
|
+
} catch {
|
|
757
|
+
continue;
|
|
758
|
+
}
|
|
759
|
+
target = { port: parsed.port, secret: parsed.secret, instanceId: parsed.instanceId };
|
|
760
|
+
break;
|
|
761
|
+
}
|
|
762
|
+
} catch {
|
|
763
|
+
}
|
|
764
|
+
if (!target) return { ok: false, detail: `\u672A\u627E\u5230\u4F1A\u8BDD\uFF1A${peerRef}` };
|
|
765
|
+
const envelope = signEnvelope({
|
|
766
|
+
v: IPC_PROTOCOL_VERSION,
|
|
767
|
+
id: `panel-model-${Date.now()}`,
|
|
768
|
+
from: "pie-panel0000000",
|
|
769
|
+
to: target.instanceId,
|
|
770
|
+
kind: "control",
|
|
771
|
+
createdAt: Date.now(),
|
|
772
|
+
text: JSON.stringify({ control: "model.set", payload: { model } })
|
|
773
|
+
}, target.secret);
|
|
774
|
+
return await new Promise((resolve4) => {
|
|
775
|
+
let settled = false;
|
|
776
|
+
const finish = (ok, detail) => {
|
|
777
|
+
if (settled) return;
|
|
778
|
+
settled = true;
|
|
779
|
+
try {
|
|
780
|
+
sock.destroy();
|
|
781
|
+
} catch {
|
|
782
|
+
}
|
|
783
|
+
resolve4({ ok, detail });
|
|
784
|
+
};
|
|
785
|
+
const sock = net2.connect({ host: "127.0.0.1", port: target.port }, () => {
|
|
786
|
+
sock.write(JSON.stringify(envelope) + "\n");
|
|
787
|
+
});
|
|
788
|
+
sock.setTimeout(6e3, () => finish(false, "\u5BF9\u7AEF 6 \u79D2\u65E0\u56DE\u6267\uFF08\u53EF\u80FD\u6B63\u91CD\u542F\uFF1B\u63A7\u5236\u5E27\u5E42\u7B49\uFF0C\u91CD\u70B9\u5B89\u5168\uFF09"));
|
|
789
|
+
sock.on("error", (error) => finish(false, `\u8FDE\u63A5\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}`));
|
|
790
|
+
sock.on("close", () => {
|
|
791
|
+
if (!settled) finish(false, "\u5BF9\u7AEF\u5173\u95ED\u4E86\u8FDE\u63A5\uFF08\u7B56\u7565\u62D2\u7EDD\u6216\u5E27\u88AB\u62D2\uFF1B\u91CD\u53D1\u5B89\u5168\uFF09");
|
|
792
|
+
});
|
|
793
|
+
sock.on("data", (buffer) => {
|
|
794
|
+
for (const line of buffer.toString("utf8").split("\n")) {
|
|
795
|
+
if (!line.trim()) continue;
|
|
796
|
+
try {
|
|
797
|
+
const parsed = JSON.parse(line);
|
|
798
|
+
if (parsed.kind === "ack" || parsed.kind === "result") {
|
|
799
|
+
const refused = /"ok"\s*:\s*false|error|拒绝|invalid|unknown|refus|denied/i.test(parsed.text ?? "");
|
|
800
|
+
finish(!refused, `\u5BF9\u7AEF\u56DE\u6267\uFF1A${parsed.text ?? "(\u7A7A)"}`);
|
|
801
|
+
return;
|
|
802
|
+
}
|
|
803
|
+
} catch {
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
});
|
|
807
|
+
});
|
|
808
|
+
}
|
|
678
809
|
function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
|
|
679
810
|
const IM_INPUT_PREFIX = connection.sourcePrefix;
|
|
680
811
|
const key = (id) => JSON.stringify([cfg.provider, id]);
|
|
681
|
-
const isManager = cfg.unattended === true;
|
|
812
|
+
const isManager = cfg.unattended === true && process.env.PIE_PROC_CURATED_NAME === "manager";
|
|
682
813
|
const scopes = /* @__PURE__ */ new Set();
|
|
683
814
|
let forwardingEnabled = cfg.enabled === true;
|
|
684
815
|
let configurationFailed = false;
|
|
@@ -697,9 +828,27 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
|
|
|
697
828
|
function updateFooterTag() {
|
|
698
829
|
ctx.ui.setStatus?.(
|
|
699
830
|
STATUS_KEY,
|
|
700
|
-
configurationFailed ? "[IM!]" : forwardingEnabled ? consumerLastExit ? "[IM!]" : consumerReady ? "[IM]" : "[IM\u2026]" : void 0
|
|
831
|
+
configurationFailed ? "[IM!]" : forwardingEnabled ? consumerLastExit ? "[IM!]" : busStale ? "[IM-DEGRADED:bus]" : consumerReady ? "[IM]" : "[IM\u2026]" : void 0
|
|
701
832
|
);
|
|
702
833
|
}
|
|
834
|
+
let busStale = false;
|
|
835
|
+
const probeBusHealth = async () => {
|
|
836
|
+
if (terminated || !connection.consumeBusHealth) return;
|
|
837
|
+
try {
|
|
838
|
+
const health = await connection.consumeBusHealth();
|
|
839
|
+
if (terminated || health === void 0) return;
|
|
840
|
+
const next = health === "stale";
|
|
841
|
+
if (next !== busStale) {
|
|
842
|
+
busStale = next;
|
|
843
|
+
if (next) {
|
|
844
|
+
ctx.log("im-forward: event bus cloud websocket stale (aged disconnect without reconnect); card callbacks will not arrive until `lark-cli event stop --force` + restart");
|
|
845
|
+
ctx.ui.notify("IM \u8F6C\u53D1\uFF1A\u4E8B\u4EF6\u603B\u7EBF\u4E91\u7AEF\u8FDE\u63A5\u7591\u4F3C\u8001\u5316\uFF08\u9762\u677F\u6309\u94AE\u53EF\u80FD\u65E0\u54CD\u5E94\uFF09\u3002\u4FEE\u590D\uFF1Alark-cli event stop --force \u540E\u91CD\u542F\u3002", "warning");
|
|
846
|
+
}
|
|
847
|
+
updateFooterTag();
|
|
848
|
+
}
|
|
849
|
+
} catch {
|
|
850
|
+
}
|
|
851
|
+
};
|
|
703
852
|
function writeEnabledToConfig(next) {
|
|
704
853
|
persistEnabled(next);
|
|
705
854
|
}
|
|
@@ -746,7 +895,7 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
|
|
|
746
895
|
if (!replyAnchor.has(sessionId)) {
|
|
747
896
|
const persisted = loadPersistedAnchor(sessionId, anchorIdentity);
|
|
748
897
|
if (persisted) {
|
|
749
|
-
replyAnchor.set(sessionId, persisted);
|
|
898
|
+
replyAnchor.set(sessionId, { messageId: persisted.messageId, threadId: persisted.threadId ?? null, at: persisted.at });
|
|
750
899
|
if (persisted.threadId) {
|
|
751
900
|
const restoredAt = Date.now();
|
|
752
901
|
routes.set(key(persisted.messageId), {
|
|
@@ -788,6 +937,27 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
|
|
|
788
937
|
let lastSendError;
|
|
789
938
|
let lastSendErrorAt = 0;
|
|
790
939
|
let lastSendFailureNotifyAt = 0;
|
|
940
|
+
function settleDelivery(requests, delivered) {
|
|
941
|
+
if (!requests || requests.size === 0) return;
|
|
942
|
+
for (const [id, meta] of requests) {
|
|
943
|
+
if (inFlightDeliveries.get(id) === meta.gen) inFlightDeliveries.delete(id);
|
|
944
|
+
if (delivered) {
|
|
945
|
+
if (meta.final) {
|
|
946
|
+
deliveredPrune();
|
|
947
|
+
deliveredRequests.set(id, Date.now());
|
|
948
|
+
sealedByGeneration.set(id, meta.gen);
|
|
949
|
+
}
|
|
950
|
+
} else {
|
|
951
|
+
if (sealedByGeneration.get(id) === meta.gen) {
|
|
952
|
+
unsealDeliveredRequest(id);
|
|
953
|
+
sealedByGeneration.delete(id);
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
const sealedByGeneration = /* @__PURE__ */ new Map();
|
|
959
|
+
const sealGenerations = /* @__PURE__ */ new Map();
|
|
960
|
+
const inFlightDeliveries = /* @__PURE__ */ new Map();
|
|
791
961
|
function notifySendFailure(error) {
|
|
792
962
|
lastSendError = error;
|
|
793
963
|
lastSendErrorAt = Date.now();
|
|
@@ -885,7 +1055,9 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
885
1055
|
const text = event.text?.trim() ?? "";
|
|
886
1056
|
if (isManager && /^\[pie-ipc\][^\n]*says:\s*\n?\[ipc-done\] requestId=[a-zA-Z0-9:-]+ (?:outcome=\S+ )?user_assigned=true(?:\s|$)/.test(text) && currentSessionId) {
|
|
887
1057
|
const requestTag = /requestId=([a-zA-Z0-9:-]+)/.exec(text)?.[1] ?? "ipc-delivery";
|
|
888
|
-
|
|
1058
|
+
if (!stampDeliveryDestinationDeduped(`ipc-done:${requestTag}`, void 0, true)) {
|
|
1059
|
+
ctx.log(`im-forward: late/duplicate wake for ${requestTag} \u2014 result already delivered; turn output stays gated`);
|
|
1060
|
+
}
|
|
889
1061
|
}
|
|
890
1062
|
if (text && !text.startsWith(IM_INPUT_PREFIX) && !text.startsWith("/") && !text.startsWith("!!") && !/@\[[^\]]+\]\(file:/.test(text) && currentSessionId) {
|
|
891
1063
|
pendingInputs.push({
|
|
@@ -899,24 +1071,60 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
899
1071
|
}
|
|
900
1072
|
return { action: "continue" };
|
|
901
1073
|
});
|
|
902
|
-
function outboundRoleAllows(attribution) {
|
|
1074
|
+
function outboundRoleAllows(attribution, consumed) {
|
|
903
1075
|
if (!isManager) return true;
|
|
904
1076
|
if (attribution !== void 0) return true;
|
|
905
1077
|
pruneDeliveryDestinations();
|
|
906
1078
|
const scope = `s:${currentSessionId}:`;
|
|
907
1079
|
const mine = [...deliveryDestinations.keys()].filter((tag) => tag.startsWith(scope));
|
|
908
1080
|
if (mine.length > 0) {
|
|
1081
|
+
let allowed = false;
|
|
1082
|
+
for (const tag of mine) {
|
|
1083
|
+
if (tag.startsWith(`${scope}ipc-done:`)) {
|
|
1084
|
+
const id = tag.slice(`${scope}ipc-done:`.length);
|
|
1085
|
+
if (inFlightDeliveries.has(id)) continue;
|
|
1086
|
+
const final = deliveryDestinations.get(tag)?.final === true;
|
|
1087
|
+
const gen = (sealGenerations.get(id) ?? 0) + 1;
|
|
1088
|
+
sealGenerations.set(id, gen);
|
|
1089
|
+
inFlightDeliveries.set(id, gen);
|
|
1090
|
+
consumed?.set(id, { gen, final });
|
|
1091
|
+
allowed = true;
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
909
1094
|
for (const tag of mine) deliveryDestinations.delete(tag);
|
|
910
|
-
return
|
|
1095
|
+
return allowed;
|
|
911
1096
|
}
|
|
912
1097
|
return false;
|
|
913
1098
|
}
|
|
914
1099
|
const deliveryDestinations = /* @__PURE__ */ new Map();
|
|
915
1100
|
const DELIVERY_TAG_TTL_MS = 60 * 60 * 1e3;
|
|
916
|
-
|
|
1101
|
+
const deliveredRequests = /* @__PURE__ */ new Map();
|
|
1102
|
+
const DELIVERED_REQUEST_TTL_MS = 6 * 60 * 60 * 1e3;
|
|
1103
|
+
function deliveredPrune(now = Date.now()) {
|
|
1104
|
+
for (const [key2, at] of deliveredRequests) {
|
|
1105
|
+
if (now - at > DELIVERED_REQUEST_TTL_MS) deliveredRequests.delete(key2);
|
|
1106
|
+
}
|
|
1107
|
+
while (deliveredRequests.size > 200) {
|
|
1108
|
+
const oldest = [...deliveredRequests.entries()].sort((a, b) => a[1] - b[1])[0];
|
|
1109
|
+
deliveredRequests.delete(oldest[0]);
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
function stampDeliveryDestinationDeduped(tag, replyTo, final) {
|
|
1113
|
+
if (tag.startsWith("ipc-done:")) {
|
|
1114
|
+
const bare = tag.slice("ipc-done:".length);
|
|
1115
|
+
deliveredPrune();
|
|
1116
|
+
if (deliveredRequests.has(bare)) return false;
|
|
1117
|
+
}
|
|
1118
|
+
stampDeliveryDestination(tag, replyTo, final);
|
|
1119
|
+
return true;
|
|
1120
|
+
}
|
|
1121
|
+
function unsealDeliveredRequest(requestId) {
|
|
1122
|
+
deliveredRequests.delete(requestId);
|
|
1123
|
+
}
|
|
1124
|
+
function stampDeliveryDestination(tag, replyTo, final) {
|
|
917
1125
|
pruneDeliveryDestinations();
|
|
918
1126
|
const scoped = `s:${currentSessionId}:${tag}`;
|
|
919
|
-
deliveryDestinations.set(scoped, { at: Date.now(), ...replyTo ? { replyTo } : {} });
|
|
1127
|
+
deliveryDestinations.set(scoped, { at: Date.now(), ...replyTo ? { replyTo } : {}, ...final !== void 0 ? { final } : {} });
|
|
920
1128
|
}
|
|
921
1129
|
function pruneDeliveryDestinations() {
|
|
922
1130
|
const now = Date.now();
|
|
@@ -947,8 +1155,12 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
947
1155
|
const wrappedNotify = stampedWake.exec(userText);
|
|
948
1156
|
if (wrappedNotify) {
|
|
949
1157
|
const requestTag = /requestId=([a-zA-Z0-9:-]+)/.exec(userText)?.[1] ?? "ipc-delivery";
|
|
950
|
-
|
|
951
|
-
|
|
1158
|
+
const isFinal = /^\[pie-ipc\][^\n]*says:\s*\n?\[ipc-(?:done|done-check)\] /.test(userText);
|
|
1159
|
+
if (!stampDeliveryDestinationDeduped(`ipc-done:${requestTag}`, void 0, isFinal)) {
|
|
1160
|
+
ctx.log(`im-forward: late/duplicate wake for ${requestTag} \u2014 result already delivered; turn output stays gated`);
|
|
1161
|
+
} else {
|
|
1162
|
+
ctx.log(`im-forward: delivery tag stamped (ipc-done:${requestTag}${isFinal ? "" : ", progress"}) \u2014 the woken turn may deliver`);
|
|
1163
|
+
}
|
|
952
1164
|
}
|
|
953
1165
|
}
|
|
954
1166
|
if (!isForwardingEnabled()) return;
|
|
@@ -961,15 +1173,17 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
961
1173
|
if (!sessionId) return;
|
|
962
1174
|
const sequence = ++forwardCounter;
|
|
963
1175
|
const attribution = resolveOutboundAttribution(sessionId);
|
|
964
|
-
|
|
1176
|
+
const deliver = /* @__PURE__ */ new Map();
|
|
1177
|
+
if (!outboundRoleAllows(attribution, deliver)) return;
|
|
965
1178
|
void forwardMessage(
|
|
966
1179
|
text,
|
|
967
1180
|
sessionId,
|
|
968
1181
|
sequence,
|
|
969
1182
|
attribution?.caption,
|
|
970
1183
|
attribution?.replyTo,
|
|
971
|
-
attribution
|
|
972
|
-
|
|
1184
|
+
attribution,
|
|
1185
|
+
deliver
|
|
1186
|
+
).catch(() => void 0);
|
|
973
1187
|
});
|
|
974
1188
|
ctx.on("turn:failed", (event) => {
|
|
975
1189
|
if (!isForwardingEnabled()) return;
|
|
@@ -978,15 +1192,18 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
978
1192
|
const reason = failureReason(event.message ?? {});
|
|
979
1193
|
const sequence = ++forwardCounter;
|
|
980
1194
|
const attribution = resolveOutboundAttribution(sessionId);
|
|
981
|
-
|
|
1195
|
+
const deliverTf = /* @__PURE__ */ new Map();
|
|
1196
|
+
if (!outboundRoleAllows(attribution, deliverTf)) return;
|
|
982
1197
|
void forwardMessage(
|
|
983
1198
|
`\u26A0\uFE0F \u4EFB\u52A1\u5931\u8D25\uFF1A${reason}`,
|
|
984
1199
|
sessionId,
|
|
985
1200
|
sequence,
|
|
986
1201
|
attribution?.caption,
|
|
987
1202
|
attribution?.replyTo,
|
|
988
|
-
attribution
|
|
989
|
-
|
|
1203
|
+
attribution,
|
|
1204
|
+
deliverTf,
|
|
1205
|
+
true
|
|
1206
|
+
).catch(() => void 0);
|
|
990
1207
|
});
|
|
991
1208
|
ctx.on("turn:cancelled", (event) => {
|
|
992
1209
|
if (!isForwardingEnabled()) return;
|
|
@@ -994,17 +1211,30 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
994
1211
|
if (!sessionId) return;
|
|
995
1212
|
const sequence = ++forwardCounter;
|
|
996
1213
|
const attribution = resolveOutboundAttribution(sessionId);
|
|
997
|
-
|
|
1214
|
+
const deliverTc = /* @__PURE__ */ new Map();
|
|
1215
|
+
if (!outboundRoleAllows(attribution, deliverTc)) return;
|
|
998
1216
|
void forwardMessage(
|
|
999
1217
|
`\u26D4\uFE0F \u4EFB\u52A1\u5DF2\u53D6\u6D88\uFF1A${event.reason}`,
|
|
1000
1218
|
sessionId,
|
|
1001
1219
|
sequence,
|
|
1002
1220
|
attribution?.caption,
|
|
1003
1221
|
attribution?.replyTo,
|
|
1004
|
-
attribution
|
|
1005
|
-
|
|
1222
|
+
attribution,
|
|
1223
|
+
deliverTc,
|
|
1224
|
+
true
|
|
1225
|
+
).catch(() => void 0);
|
|
1006
1226
|
});
|
|
1007
|
-
async function forwardMessage(text, sessionId, sequence, userInput, replyTo, attribution) {
|
|
1227
|
+
async function forwardMessage(text, sessionId, sequence, userInput, replyTo, attribution, deliverRequests, systemNotice) {
|
|
1228
|
+
let settled = false;
|
|
1229
|
+
try {
|
|
1230
|
+
return await forwardMessageInner(text, sessionId, sequence, userInput, replyTo, attribution, deliverRequests, systemNotice, () => {
|
|
1231
|
+
settled = true;
|
|
1232
|
+
});
|
|
1233
|
+
} finally {
|
|
1234
|
+
if (!settled) settleDelivery(deliverRequests, false);
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
async function forwardMessageInner(text, sessionId, sequence, userInput, replyTo, attribution, deliverRequests, systemNotice, markSettled) {
|
|
1008
1238
|
pruneState();
|
|
1009
1239
|
const sessionName = ctx.getSessionDisplayName?.() ?? ctx.getSessionName?.();
|
|
1010
1240
|
const composeMode = resolveSessionAnchor(sessionId).threadId ? "topic-reply" : "topic-root";
|
|
@@ -1015,7 +1245,10 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1015
1245
|
text,
|
|
1016
1246
|
composeMode
|
|
1017
1247
|
);
|
|
1018
|
-
if (terminated || !isForwardingEnabled())
|
|
1248
|
+
if (terminated || !isForwardingEnabled()) {
|
|
1249
|
+
settleDelivery(deliverRequests, false);
|
|
1250
|
+
return false;
|
|
1251
|
+
}
|
|
1019
1252
|
const [chunks] = chunkMarkdown(composed);
|
|
1020
1253
|
const baseKey = `pie-im-forward-${cfg.provider}-${incarnation}-${sessionId}-${sequence}-${hashText(composed)}`;
|
|
1021
1254
|
const sessionAnchor = resolveSessionAnchor(sessionId);
|
|
@@ -1116,7 +1349,8 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1116
1349
|
}
|
|
1117
1350
|
if (!stakeFlightToken && !anchor) {
|
|
1118
1351
|
ctx.log(`im-forward: fallback stake unavailable for ${sessionId}; dropping re-send`);
|
|
1119
|
-
|
|
1352
|
+
settleDelivery(deliverRequests, false);
|
|
1353
|
+
return false;
|
|
1120
1354
|
}
|
|
1121
1355
|
sent = await sendChunk(0);
|
|
1122
1356
|
}
|
|
@@ -1125,8 +1359,12 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1125
1359
|
}
|
|
1126
1360
|
if (!sent) {
|
|
1127
1361
|
notifySendFailure(`${cfg.provider} send failed`);
|
|
1128
|
-
|
|
1362
|
+
settleDelivery(deliverRequests, false);
|
|
1363
|
+
markSettled?.();
|
|
1364
|
+
return false;
|
|
1129
1365
|
}
|
|
1366
|
+
settleDelivery(deliverRequests, true);
|
|
1367
|
+
markSettled?.();
|
|
1130
1368
|
registerRoute(sent, sessionId);
|
|
1131
1369
|
const legacyUpgrade = !isManager && anchor !== void 0 && !sessionAnchor.threadId && sent.messageId !== anchor;
|
|
1132
1370
|
const stakeNeeded = stakeFlightToken !== void 0;
|
|
@@ -1196,22 +1434,22 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1196
1434
|
}
|
|
1197
1435
|
registerRoute(next, sessionId);
|
|
1198
1436
|
}
|
|
1199
|
-
if (connection.sendFile && !terminated && isForwardingEnabled()) {
|
|
1437
|
+
if (connection.sendFile && !terminated && isForwardingEnabled() && !systemNotice) {
|
|
1200
1438
|
const files = collectFileReferences(
|
|
1201
1439
|
text,
|
|
1202
1440
|
ctx.cwd,
|
|
1203
|
-
(
|
|
1441
|
+
(path12) => {
|
|
1204
1442
|
try {
|
|
1205
|
-
const stat = fs6.statSync(
|
|
1443
|
+
const stat = fs6.statSync(path12);
|
|
1206
1444
|
return { isFile: stat.isFile(), size: stat.size };
|
|
1207
1445
|
} catch {
|
|
1208
1446
|
return null;
|
|
1209
1447
|
}
|
|
1210
1448
|
},
|
|
1211
1449
|
{
|
|
1212
|
-
canonicalize: (
|
|
1450
|
+
canonicalize: (path12) => {
|
|
1213
1451
|
try {
|
|
1214
|
-
return fs6.realpathSync(
|
|
1452
|
+
return fs6.realpathSync(path12);
|
|
1215
1453
|
} catch {
|
|
1216
1454
|
return null;
|
|
1217
1455
|
}
|
|
@@ -1265,31 +1503,6 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1265
1503
|
routes.set(key(sent.messageId), route);
|
|
1266
1504
|
ctx.log(`im-forward: forwarded session=${sessionId} as ${sent.messageId}`);
|
|
1267
1505
|
}
|
|
1268
|
-
const seamRegisterRoute = (sent, sessionId) => {
|
|
1269
|
-
registerRoute(sent, sessionId ?? currentSessionId ?? "");
|
|
1270
|
-
};
|
|
1271
|
-
const seamClaimThread = (sent, sessionId) => {
|
|
1272
|
-
if (!sent.threadId) return { claimed: false, reason: "no thread" };
|
|
1273
|
-
const owner = sessionId ?? currentSessionId;
|
|
1274
|
-
if (!owner) return { claimed: false, reason: "no session" };
|
|
1275
|
-
const threadKey = key(sent.threadId);
|
|
1276
|
-
const shared = claimThreadOwnership({ provider: cfg.provider, threadId: sent.threadId }, owner);
|
|
1277
|
-
if (!shared.claimed) {
|
|
1278
|
-
ctx.log(`im-forward: relay REFUSED thread ${sent.threadId}: ${shared.reason}`);
|
|
1279
|
-
return { claimed: false, reason: shared.reason };
|
|
1280
|
-
}
|
|
1281
|
-
const route = { messageId: sent.messageId, threadId: sent.threadId, sessionId: owner, sentAt: Date.now() };
|
|
1282
|
-
threadRoutes.set(threadKey, route);
|
|
1283
|
-
routes.set(key(sent.messageId), route);
|
|
1284
|
-
sentAnchors.add(sent.messageId);
|
|
1285
|
-
ctx.log(`im-forward: relay claimed thread ${sent.threadId} for session ${owner}`);
|
|
1286
|
-
return { claimed: true };
|
|
1287
|
-
};
|
|
1288
|
-
ctx.__imRelaySeam = {
|
|
1289
|
-
registerRoute: seamRegisterRoute,
|
|
1290
|
-
claimThread: seamClaimThread,
|
|
1291
|
-
anchors: sentAnchors
|
|
1292
|
-
};
|
|
1293
1506
|
registerTurnImDriver(() => {
|
|
1294
1507
|
const sid = currentSessionId;
|
|
1295
1508
|
if (!sid) return false;
|
|
@@ -1400,20 +1613,103 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1400
1613
|
return { kind: "delivery-failed", owner: ownerSession };
|
|
1401
1614
|
}
|
|
1402
1615
|
}
|
|
1616
|
+
const panelCardOwners = /* @__PURE__ */ new Map();
|
|
1617
|
+
const rememberPanelCard = (messageId, sessionId, chatId) => {
|
|
1618
|
+
if (!messageId) return;
|
|
1619
|
+
panelCardOwners.set(messageId, { sessionId, epoch: inputEpoch, chatId });
|
|
1620
|
+
if (panelCardOwners.size > 100) {
|
|
1621
|
+
const oldest = [...panelCardOwners.keys()].slice(0, Math.ceil(panelCardOwners.size / 4));
|
|
1622
|
+
for (const k of oldest) panelCardOwners.delete(k);
|
|
1623
|
+
}
|
|
1624
|
+
};
|
|
1625
|
+
const runPanelCommand = async (panelCmd, event, sessionId, isCurrent) => {
|
|
1626
|
+
if (!isCurrent()) return;
|
|
1627
|
+
const started = Date.now();
|
|
1628
|
+
if (panelCmd.restricted && cfg.allowUsers && (!event.sender_id || !cfg.allowUsers.includes(event.sender_id))) {
|
|
1629
|
+
ctx.log(`im-forward: restricted panel action ${panelCmd.cmd} refused for ${event.sender_id ?? "unknown"} (not in allowUsers)`);
|
|
1630
|
+
try {
|
|
1631
|
+
await connection.send(event.chat_id, "\u26D4\uFE0F \u6B64\u64CD\u4F5C\u9700\u8981\u7BA1\u7406\u5458\u6743\u9650\uFF08allowUsers\uFF09\u3002", `panel-refused-${event.event_id}`);
|
|
1632
|
+
} catch {
|
|
1633
|
+
}
|
|
1634
|
+
return;
|
|
1635
|
+
}
|
|
1636
|
+
const modelAction = /^panel\.model\.([A-Za-z0-9-]+)\.(.+)$/.exec(panelCmd.cmd);
|
|
1637
|
+
if (modelAction) {
|
|
1638
|
+
const [, peerRef, model] = modelAction;
|
|
1639
|
+
const receipt = await applyModelControl(peerRef, model);
|
|
1640
|
+
if (!isCurrent()) return;
|
|
1641
|
+
const spec = {
|
|
1642
|
+
title: "\u5207\u6362\u7ED3\u679C",
|
|
1643
|
+
body: `${receipt.ok ? "\u2705" : "\u26A0\uFE0F"} ${model} \u2192 ${peerRef}
|
|
1644
|
+
|
|
1645
|
+
${receipt.detail}`,
|
|
1646
|
+
actions: [{ id: "panel.models", label: "\u21A9\uFE0F \u8FD4\u56DE\u6A21\u578B\u9762\u677F" }]
|
|
1647
|
+
};
|
|
1648
|
+
try {
|
|
1649
|
+
if (connection.sendCard) {
|
|
1650
|
+
const sent = await connection.sendCard(event.chat_id, spec, `panel-model-${event.event_id}`);
|
|
1651
|
+
if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
|
|
1652
|
+
} else await connection.send(event.chat_id, `**${spec.title}**
|
|
1653
|
+
${spec.body}`, `panel-model-${event.event_id}`);
|
|
1654
|
+
} catch {
|
|
1655
|
+
}
|
|
1656
|
+
return;
|
|
1657
|
+
}
|
|
1658
|
+
const result = executePanelCommand({ ...panelCmd, senderId: event.sender_id, originCardId: event.message_id });
|
|
1659
|
+
try {
|
|
1660
|
+
if (result.patchOrigin && connection.patch && event.message_id) {
|
|
1661
|
+
const ok = await connection.patch(event.message_id, result.spec);
|
|
1662
|
+
if (ok) {
|
|
1663
|
+
if (isCurrent()) rememberPanelCard(event.message_id, sessionId, event.chat_id);
|
|
1664
|
+
ctx.log(`im-forward: panel card patched (${panelCmd.cmd}, runtimeMs=${Date.now() - started})`);
|
|
1665
|
+
return;
|
|
1666
|
+
}
|
|
1667
|
+
ctx.log("im-forward: panel patch failed; falling back to a fresh card");
|
|
1668
|
+
}
|
|
1669
|
+
if (!isCurrent()) return;
|
|
1670
|
+
if (connection.sendCard) {
|
|
1671
|
+
const sent = await connection.sendCard(event.chat_id, result.spec, `panel-${event.event_id}`);
|
|
1672
|
+
if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
|
|
1673
|
+
ctx.log(`im-forward: panel card sent (${panelCmd.cmd})`);
|
|
1674
|
+
} else {
|
|
1675
|
+
await connection.send(event.chat_id, `**${result.spec.title ?? "\u9762\u677F"}**
|
|
1676
|
+
${result.spec.body}`, `panel-${event.event_id}`);
|
|
1677
|
+
}
|
|
1678
|
+
} catch (error) {
|
|
1679
|
+
ctx.log(`im-forward: panel command failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1680
|
+
}
|
|
1681
|
+
};
|
|
1403
1682
|
async function handleInboundEventInner(event, retry) {
|
|
1404
1683
|
const isGroup = event.chatType === "group";
|
|
1405
1684
|
if (isGroup) {
|
|
1406
|
-
if (cfg.groupAccess === "off")
|
|
1407
|
-
|
|
1685
|
+
if (cfg.groupAccess === "off") {
|
|
1686
|
+
ctx.log("im-forward: group event refused (off)");
|
|
1687
|
+
return;
|
|
1688
|
+
}
|
|
1689
|
+
if (cfg.groupAccess === "allowUsers" && (!event.sender_id || !cfg.allowUsers?.includes(event.sender_id))) {
|
|
1690
|
+
ctx.log("im-forward: group event refused (allowUsers)");
|
|
1408
1691
|
return;
|
|
1692
|
+
}
|
|
1409
1693
|
} else {
|
|
1410
1694
|
const matchesTarget = cfg.targetKind === "user" ? event.sender_id === cfg.targetId && (event.chatType === void 0 || event.chatType === "p2p") : event.chat_id === cfg.targetId || event.chatType === "p2p";
|
|
1411
1695
|
if (!matchesTarget) return;
|
|
1412
1696
|
}
|
|
1413
|
-
if (!isGroup && cfg.allowUsers && (!event.sender_id || !cfg.allowUsers.includes(event.sender_id)))
|
|
1697
|
+
if (!isGroup && cfg.allowUsers && (!event.sender_id || !cfg.allowUsers.includes(event.sender_id))) {
|
|
1698
|
+
ctx.log("im-forward: direct event refused (allowUsers)");
|
|
1414
1699
|
return;
|
|
1700
|
+
}
|
|
1415
1701
|
const messageId = event.message_id;
|
|
1416
1702
|
if (!messageId) return;
|
|
1703
|
+
const owner = panelCardOwners.get(messageId);
|
|
1704
|
+
const fastEpoch = inputEpoch;
|
|
1705
|
+
if (owner && owner.sessionId === currentSessionId && owner.epoch === fastEpoch && owner.chatId === event.chat_id && event.text?.startsWith("/card ")) {
|
|
1706
|
+
const command = parsePanelCommand(event.text);
|
|
1707
|
+
if (command) {
|
|
1708
|
+
ctx.log(`im-forward: panel fast path (${command.cmd})`);
|
|
1709
|
+
await runPanelCommand(command, event, owner.sessionId, () => !terminated && inputEpoch === fastEpoch && currentSessionId === owner.sessionId && isForwardingEnabled());
|
|
1710
|
+
return;
|
|
1711
|
+
}
|
|
1712
|
+
}
|
|
1417
1713
|
const address = resolveInboundAddress(event.text);
|
|
1418
1714
|
if (address.kind === "other") {
|
|
1419
1715
|
ctx.log(`im-forward: message addressed to "${address.name}" (another live session); ignoring here`);
|
|
@@ -1423,6 +1719,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1423
1719
|
ctx.log(`im-forward: address "${address.name}" is unresolved (${address.reason}); dropping`);
|
|
1424
1720
|
return;
|
|
1425
1721
|
}
|
|
1722
|
+
if (!currentSessionId) return;
|
|
1426
1723
|
const releaseInvalidatedEvent = () => {
|
|
1427
1724
|
if (event.event_id) seenEventIds.delete(key(event.event_id));
|
|
1428
1725
|
};
|
|
@@ -1503,7 +1800,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1503
1800
|
ctx.log(`im-forward: thread ownership unreadable for ${messageId}; dropping (fail closed)`);
|
|
1504
1801
|
return;
|
|
1505
1802
|
}
|
|
1506
|
-
if (isManager && event.chatType === "group"
|
|
1803
|
+
if (isManager && meta.threadId && (event.chatType === "group" || event.chatType === "p2p")) {
|
|
1507
1804
|
if (!scope.isCurrent()) {
|
|
1508
1805
|
releaseInvalidatedEvent();
|
|
1509
1806
|
return;
|
|
@@ -1513,7 +1810,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1513
1810
|
ctx.log(`im-forward: unowned-topic takeover lost the claim (${claim.reason}); ${messageId} dropped`);
|
|
1514
1811
|
return;
|
|
1515
1812
|
}
|
|
1516
|
-
ctx.log(`im-forward: unowned
|
|
1813
|
+
ctx.log(`im-forward: unowned ${event.chatType} topic ${meta.threadId} taken by manager (claimed)`);
|
|
1517
1814
|
await acceptRoutedMessage(
|
|
1518
1815
|
{ messageId: "", threadId: meta.threadId, sessionId, sentAt: Date.now() },
|
|
1519
1816
|
event,
|
|
@@ -1547,6 +1844,13 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1547
1844
|
const imageKeys = event.images ?? [];
|
|
1548
1845
|
const caption = address.kind === "self" ? address.body : event.text;
|
|
1549
1846
|
if (!caption && !imageKeys.length) return;
|
|
1847
|
+
{
|
|
1848
|
+
const panelCmd = parsePanelCommand(caption);
|
|
1849
|
+
if (panelCmd) {
|
|
1850
|
+
await runPanelCommand(panelCmd, event, sessionId, () => scope.isCurrent());
|
|
1851
|
+
return;
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1550
1854
|
const submitText = `${IM_INPUT_PREFIX}
|
|
1551
1855
|
${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
1552
1856
|
const accepted = imageKeys.length ? await injectImageMessage(messageId, imageKeys, submitText, scope) : await scope.submit(submitText);
|
|
@@ -1561,16 +1865,21 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
1561
1865
|
}
|
|
1562
1866
|
}
|
|
1563
1867
|
if (currentAfterSubmit) {
|
|
1868
|
+
const rejectReason = scope.lastRejectReason;
|
|
1869
|
+
const notice = rejectReason ? `\u26A0\uFE0F \u6D88\u606F\u672A\u80FD\u63D0\u4EA4\uFF1A${rejectReason}` : `\u26A0\uFE0F \u6D88\u606F\u63A5\u6536\u5931\u8D25\uFF0C\u672A\u63D0\u4EA4\u4EFB\u52A1\u3002${imageKeys.length ? "\u8BF7\u68C0\u67E5\u9644\u4EF6\u540E\u91CD\u8BD5\u3002" : "\u8BF7\u91CD\u8BD5\u3002"}`;
|
|
1564
1870
|
ctx.ui.notify(
|
|
1565
1871
|
"im-forward: message was not accepted; no input submitted.",
|
|
1566
1872
|
"warning"
|
|
1567
1873
|
);
|
|
1568
1874
|
await forwardMessage(
|
|
1569
|
-
|
|
1875
|
+
notice,
|
|
1570
1876
|
route.sessionId,
|
|
1571
1877
|
++forwardCounter,
|
|
1572
1878
|
caption,
|
|
1573
|
-
messageId
|
|
1879
|
+
messageId,
|
|
1880
|
+
void 0,
|
|
1881
|
+
void 0,
|
|
1882
|
+
true
|
|
1574
1883
|
);
|
|
1575
1884
|
}
|
|
1576
1885
|
return;
|
|
@@ -1622,7 +1931,10 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
1622
1931
|
boundSession ?? currentSessionId ?? "",
|
|
1623
1932
|
++forwardCounter,
|
|
1624
1933
|
void 0,
|
|
1625
|
-
event.message_id
|
|
1934
|
+
event.message_id,
|
|
1935
|
+
void 0,
|
|
1936
|
+
void 0,
|
|
1937
|
+
true
|
|
1626
1938
|
);
|
|
1627
1939
|
}
|
|
1628
1940
|
return;
|
|
@@ -1756,7 +2068,7 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
1756
2068
|
function residentAliveSomewhere() {
|
|
1757
2069
|
if (isManager) return false;
|
|
1758
2070
|
try {
|
|
1759
|
-
const dir =
|
|
2071
|
+
const dir = ipcDiscoveryRoot2();
|
|
1760
2072
|
const entries = fs6.readdirSync(dir);
|
|
1761
2073
|
for (const name of entries) {
|
|
1762
2074
|
if (!name.endsWith(".json")) continue;
|
|
@@ -1789,7 +2101,7 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
1789
2101
|
if (consumerLock) return true;
|
|
1790
2102
|
if (!needsCanonicalResolution()) return acquireClaimedSlot(resolveBindingKeySync());
|
|
1791
2103
|
const resolved = await resolveBindingKey();
|
|
1792
|
-
return acquireClaimedSlot(resolved);
|
|
2104
|
+
return resolved ? acquireClaimedSlot(resolved) : false;
|
|
1793
2105
|
}
|
|
1794
2106
|
function acquireClaimedSlot(binding) {
|
|
1795
2107
|
if (consumerLock) return true;
|
|
@@ -1977,9 +2289,15 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
1977
2289
|
};
|
|
1978
2290
|
};
|
|
1979
2291
|
updateFooterTag();
|
|
2292
|
+
const busHealthTimer = setInterval(() => {
|
|
2293
|
+
void probeBusHealth();
|
|
2294
|
+
}, 5 * 60 * 1e3);
|
|
2295
|
+
busHealthTimer.unref?.();
|
|
2296
|
+
void probeBusHealth();
|
|
1980
2297
|
ctx.registerCleanup?.(async () => {
|
|
1981
2298
|
inputEpoch++;
|
|
1982
2299
|
terminated = true;
|
|
2300
|
+
clearInterval(busHealthTimer);
|
|
1983
2301
|
registerDispatchReceiver(void 0);
|
|
1984
2302
|
registerTurnImDriver(void 0);
|
|
1985
2303
|
consumerLock?.release();
|
|
@@ -2072,7 +2390,7 @@ async function runSetup(ctx, dir, providers, signal, isCurrent = () => !signal.a
|
|
|
2072
2390
|
ctx.ui.notify("IM forwarding setup: invalid provider settings; nothing was saved.", "error");
|
|
2073
2391
|
return;
|
|
2074
2392
|
}
|
|
2075
|
-
const profile = typeof settings.larkCliProfile === "string" ? settings.larkCliProfile : void 0;
|
|
2393
|
+
const profile = typeof settings.larkCliProfile === "string" ? String(settings.larkCliProfile) : void 0;
|
|
2076
2394
|
const profileLine = profile ? `
|
|
2077
2395
|
lark-cli profile: ${String(profile)}` : "";
|
|
2078
2396
|
const appLine = resolved.appId ? `
|
|
@@ -2084,14 +2402,65 @@ Save location: ${saveLocation(ctx.cwd, dir)}
|
|
|
2084
2402
|
Enable forwarding and start the connection? No test message will be sent. Saving does not prove connection readiness.`, options);
|
|
2085
2403
|
if (!isCurrent() || !confirmed) return;
|
|
2086
2404
|
writeConfig(ctx.cwd, dir, { enabled: true, provider: selected.id, settings }, snapshot);
|
|
2405
|
+
if (selected.id === "feishu") {
|
|
2406
|
+
const binary = typeof settings.larkCli === "string" ? String(settings.larkCli) : void 0;
|
|
2407
|
+
void probeCardActionSubscription(ctx, ctx.cwd, binary, profile).catch(() => void 0);
|
|
2408
|
+
}
|
|
2087
2409
|
return resolveConfig(ctx.cwd, dir).config ?? void 0;
|
|
2088
2410
|
}
|
|
2411
|
+
async function probeCardActionSubscription(ctx, cwd, binaryOverride, profile) {
|
|
2412
|
+
const { spawn: spawn5 } = await import("node:child_process");
|
|
2413
|
+
const binary = binaryOverride ?? await settingsProbeBinary();
|
|
2414
|
+
if (!binary) return;
|
|
2415
|
+
await new Promise((resolve4) => {
|
|
2416
|
+
let settled = false;
|
|
2417
|
+
const done = () => {
|
|
2418
|
+
if (!settled) {
|
|
2419
|
+
settled = true;
|
|
2420
|
+
resolve4();
|
|
2421
|
+
}
|
|
2422
|
+
};
|
|
2423
|
+
const timer = setTimeout(() => {
|
|
2424
|
+
try {
|
|
2425
|
+
child.kill("SIGKILL");
|
|
2426
|
+
} catch {
|
|
2427
|
+
}
|
|
2428
|
+
done();
|
|
2429
|
+
}, 3500);
|
|
2430
|
+
timer.unref?.();
|
|
2431
|
+
const child = spawn5(binary, ["event", "consume", "card.action.trigger", "--as", "bot", ...profile ? ["--profile", profile] : []], { cwd, stdio: ["ignore", "pipe", "pipe"] });
|
|
2432
|
+
child.on("error", () => done());
|
|
2433
|
+
child.on("close", () => done());
|
|
2434
|
+
let out = "";
|
|
2435
|
+
child.stdout.on("data", (chunk) => {
|
|
2436
|
+
out += chunk.toString("utf8").slice(0, 8e3);
|
|
2437
|
+
});
|
|
2438
|
+
child.on("close", () => {
|
|
2439
|
+
const unsubscribed = /requires callbacks not subscribed/i.test(out);
|
|
2440
|
+
if (unsubscribed) {
|
|
2441
|
+
const launcher = /https:\/\/open\.feishu\.cn\/page\/launcher\?[^\s"]+/.exec(out)?.[0];
|
|
2442
|
+
ctx.ui.notify(`\u9762\u677F\u5361\u7247\u6309\u94AE\u9700\u8981\u4E00\u6B21\u6027\u8BA2\u9605 card.action.trigger\uFF08\u672A\u8BA2\u9605\u65F6\u9762\u677F\u4ECD\u53EF\u7528\uFF0C\u6309\u94AE\u964D\u7EA7\u4E3A\u6587\u5B57\u547D\u4EE4\uFF09\u3002${launcher ? `
|
|
2443
|
+
\u626B\u7801\u8BA2\u9605\uFF1A${launcher}` : "\n\u5728\u5F00\u53D1\u8005\u540E\u53F0 \u2192 \u4E8B\u4EF6\u4E0E\u56DE\u8C03 \u2192 \u8BA2\u9605 card.action.trigger\u3002"}`, "info");
|
|
2444
|
+
}
|
|
2445
|
+
});
|
|
2446
|
+
});
|
|
2447
|
+
}
|
|
2448
|
+
async function settingsProbeBinary() {
|
|
2449
|
+
try {
|
|
2450
|
+
const { spawnSync } = await import("node:child_process");
|
|
2451
|
+
const which = spawnSync(process.platform === "win32" ? "where" : "which", ["lark-cli"], { encoding: "utf8", timeout: 3e3 });
|
|
2452
|
+
const path12 = which.stdout?.split(/\r?\n/)[0]?.trim();
|
|
2453
|
+
return path12 || void 0;
|
|
2454
|
+
} catch {
|
|
2455
|
+
return void 0;
|
|
2456
|
+
}
|
|
2457
|
+
}
|
|
2089
2458
|
|
|
2090
2459
|
// builtin/extensions/im-forward/providers/feishu/index.ts
|
|
2091
2460
|
import { spawn as spawn4 } from "node:child_process";
|
|
2092
2461
|
import * as fs9 from "node:fs";
|
|
2093
|
-
import * as
|
|
2094
|
-
import * as
|
|
2462
|
+
import * as os4 from "node:os";
|
|
2463
|
+
import * as path11 from "node:path";
|
|
2095
2464
|
|
|
2096
2465
|
// builtin/extensions/im-forward/lark-cli.ts
|
|
2097
2466
|
import { spawn as spawn2 } from "node:child_process";
|
|
@@ -2100,24 +2469,24 @@ import { StringDecoder as StringDecoder2 } from "node:string_decoder";
|
|
|
2100
2469
|
// builtin/extensions/im-forward/launch.ts
|
|
2101
2470
|
import { spawn } from "node:child_process";
|
|
2102
2471
|
import * as fs7 from "node:fs";
|
|
2103
|
-
import * as
|
|
2472
|
+
import * as path7 from "node:path";
|
|
2104
2473
|
import { StringDecoder } from "node:string_decoder";
|
|
2105
2474
|
function resolveLaunchSpec(explicit, cwd = process.cwd(), platform = process.platform, env = process.env) {
|
|
2106
2475
|
const windows = platform === "win32";
|
|
2107
|
-
const candidates = explicit ? [
|
|
2476
|
+
const candidates = explicit ? [path7.resolve(cwd, explicit)] : (env.PATH ?? "").split(windows ? ";" : ":").filter(Boolean).flatMap((dir) => (windows ? ["lark-cli.exe", "lark-cli.cmd"] : ["lark-cli"]).map((name) => path7.resolve(cwd, dir, name)));
|
|
2108
2477
|
for (const candidate of candidates) {
|
|
2109
2478
|
try {
|
|
2110
2479
|
if (!fs7.statSync(candidate).isFile()) continue;
|
|
2111
|
-
const ext =
|
|
2480
|
+
const ext = path7.extname(candidate).toLowerCase();
|
|
2112
2481
|
if (ext === ".js" || ext === ".mjs") return { command: process.execPath, prefix: [candidate] };
|
|
2113
2482
|
if (windows && ext === ".cmd") {
|
|
2114
|
-
const dir =
|
|
2115
|
-
for (const root of [
|
|
2483
|
+
const dir = path7.dirname(candidate);
|
|
2484
|
+
for (const root of [path7.join(dir, "node_modules", "@larksuite", "cli"), path7.resolve(dir, "..", "@larksuite", "cli")]) {
|
|
2116
2485
|
try {
|
|
2117
|
-
const pkg = JSON.parse(fs7.readFileSync(
|
|
2486
|
+
const pkg = JSON.parse(fs7.readFileSync(path7.join(root, "package.json"), "utf8"));
|
|
2118
2487
|
const bin = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.["lark-cli"];
|
|
2119
2488
|
if (pkg.name !== "@larksuite/cli" || typeof bin !== "string" || bin.replace(/^\.\//, "") !== "scripts/run.js") continue;
|
|
2120
|
-
const entry =
|
|
2489
|
+
const entry = path7.join(root, "scripts", "run.js");
|
|
2121
2490
|
if (fs7.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
|
|
2122
2491
|
} catch {
|
|
2123
2492
|
}
|
|
@@ -2181,7 +2550,7 @@ function stopOwnedTreeInner(child, signal) {
|
|
|
2181
2550
|
}, 1500);
|
|
2182
2551
|
try {
|
|
2183
2552
|
const root = process.env.SystemRoot || process.env.windir || "C:\\Windows";
|
|
2184
|
-
killer = spawn(
|
|
2553
|
+
killer = spawn(path7.join(root, "System32", "taskkill.exe"), ["/PID", String(child.pid), "/T", "/F"], { shell: false, windowsHide: true, stdio: "ignore" });
|
|
2185
2554
|
killer.on("error", () => finish(false));
|
|
2186
2555
|
killer.on("exit", (code) => finish(code === 0));
|
|
2187
2556
|
} catch {
|
|
@@ -2382,6 +2751,62 @@ async function runLarkCli(binary, args, timeoutMs = 3e4, cwd, options = {}) {
|
|
|
2382
2751
|
});
|
|
2383
2752
|
}
|
|
2384
2753
|
|
|
2754
|
+
// builtin/extensions/im-forward/providers/feishu/card.ts
|
|
2755
|
+
var COLOR_TEMPLATE = {
|
|
2756
|
+
blue: "blue",
|
|
2757
|
+
green: "green",
|
|
2758
|
+
grey: "grey",
|
|
2759
|
+
red: "red",
|
|
2760
|
+
violet: "violet"
|
|
2761
|
+
};
|
|
2762
|
+
function compileCard(spec) {
|
|
2763
|
+
const elements = [];
|
|
2764
|
+
elements.push({ tag: "markdown", content: spec.body });
|
|
2765
|
+
for (let i = 0; i < spec.actions.length; i += 3) {
|
|
2766
|
+
const row = spec.actions.slice(i, i + 3);
|
|
2767
|
+
elements.push({
|
|
2768
|
+
tag: "column_set",
|
|
2769
|
+
flex_mode: "flow",
|
|
2770
|
+
...i === 0 ? {} : { horizontal_spacing: "medium" },
|
|
2771
|
+
columns: row.map((action) => ({
|
|
2772
|
+
tag: "column",
|
|
2773
|
+
width: "weighted",
|
|
2774
|
+
weight: 1,
|
|
2775
|
+
elements: [{
|
|
2776
|
+
tag: "button",
|
|
2777
|
+
text: { tag: "plain_text", content: action.label },
|
|
2778
|
+
type: action.style ?? "default",
|
|
2779
|
+
behaviors: [{
|
|
2780
|
+
type: "callback",
|
|
2781
|
+
// The whole neutral identity rides the callback value:
|
|
2782
|
+
// id + payload + the allowUsers marker survive the
|
|
2783
|
+
// round-trip; index.ts maps it back to a command event.
|
|
2784
|
+
value: {
|
|
2785
|
+
cmd: action.id,
|
|
2786
|
+
ru: action.requireAllowUsers === true,
|
|
2787
|
+
// explicit false: the mapper treats it as a boolean
|
|
2788
|
+
...action.payload === void 0 ? {} : { p: action.payload }
|
|
2789
|
+
}
|
|
2790
|
+
}]
|
|
2791
|
+
}]
|
|
2792
|
+
}))
|
|
2793
|
+
});
|
|
2794
|
+
}
|
|
2795
|
+
const doc = {
|
|
2796
|
+
schema: "2.0",
|
|
2797
|
+
config: { update_multi: true, width_mode: "default" },
|
|
2798
|
+
body: { elements }
|
|
2799
|
+
};
|
|
2800
|
+
if (spec.title !== void 0 || spec.subtitle !== void 0) {
|
|
2801
|
+
doc.header = {
|
|
2802
|
+
...spec.title === void 0 ? {} : { title: { tag: "plain_text", content: spec.title } },
|
|
2803
|
+
...spec.subtitle === void 0 ? {} : { subtitle: { tag: "plain_text", content: spec.subtitle } },
|
|
2804
|
+
template: COLOR_TEMPLATE[spec.color ?? "blue"] ?? "blue"
|
|
2805
|
+
};
|
|
2806
|
+
}
|
|
2807
|
+
return doc;
|
|
2808
|
+
}
|
|
2809
|
+
|
|
2385
2810
|
// builtin/extensions/im-forward/providers/feishu/helpers.ts
|
|
2386
2811
|
function parseLarkCliEnvelope(stdout) {
|
|
2387
2812
|
let parsed;
|
|
@@ -2427,16 +2852,16 @@ function extractImageKey(content) {
|
|
|
2427
2852
|
|
|
2428
2853
|
// builtin/extensions/im-forward/providers/feishu/setup.ts
|
|
2429
2854
|
import * as fs8 from "node:fs";
|
|
2430
|
-
import * as
|
|
2855
|
+
import * as path10 from "node:path";
|
|
2431
2856
|
|
|
2432
2857
|
// builtin/extensions/im-forward/browser.ts
|
|
2433
2858
|
import { spawn as spawn3 } from "node:child_process";
|
|
2434
|
-
import
|
|
2859
|
+
import path8 from "node:path";
|
|
2435
2860
|
var browserScript = "$ErrorActionPreference = 'Stop'; try { $reader = [System.IO.StreamReader]::new([Console]::OpenStandardInput(), [System.Text.Encoding]::UTF8); $url = $reader.ReadToEnd(); Start-Process -FilePath $url; exit 0 } catch { exit 1 }";
|
|
2436
2861
|
function browserLaunch(platform = process.platform, root = process.env.SystemRoot || "C:\\Windows") {
|
|
2437
2862
|
if (platform === "win32") {
|
|
2438
2863
|
if (!/^[A-Za-z]:\\/.test(root) || /[\x00-\x1f]/.test(root)) return;
|
|
2439
|
-
return { command:
|
|
2864
|
+
return { command: path8.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(browserScript, "utf16le").toString("base64")], stdin: true };
|
|
2440
2865
|
}
|
|
2441
2866
|
if (platform === "darwin") return { command: "/usr/bin/open", args: ["--"], stdin: false };
|
|
2442
2867
|
if (platform === "linux") return { command: "/usr/bin/xdg-open", args: [], stdin: false };
|
|
@@ -2495,23 +2920,23 @@ async function openBrowser(url, signal, seam = {}) {
|
|
|
2495
2920
|
}
|
|
2496
2921
|
|
|
2497
2922
|
// builtin/extensions/im-forward/existing-app-terminal.ts
|
|
2498
|
-
import
|
|
2923
|
+
import path9 from "node:path";
|
|
2499
2924
|
var existingAppInnerScript = "$ErrorActionPreference = 'Stop'; try { $payload = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PAYLOAD__')) | ConvertFrom-Json; Set-Location -LiteralPath $payload.cwd; & $payload.command @($payload.args); $code = $LASTEXITCODE; if ($null -eq $code) { exit 1 }; exit $code } catch { Write-Host 'Official setup failed. Close this window and retry from Pie.'; exit 1 }";
|
|
2500
2925
|
var existingAppOuterTemplate = "$ErrorActionPreference = 'Stop'; try { $inner = '" + existingAppInnerScript.replaceAll("'", "''") + "'; $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($inner)); $child = Start-Process -FilePath (Join-Path $PSHOME 'powershell.exe') -WindowStyle Normal -Wait -PassThru -ArgumentList @('-NoLogo', '-NoProfile', '-EncodedCommand', $encoded); exit $child.ExitCode } catch { exit 1 }";
|
|
2501
2926
|
function existingAppTerminal(binary, cwd, platform = process.platform, root = process.env.SystemRoot || "C:\\Windows") {
|
|
2502
2927
|
if (platform !== "win32" || !/^[A-Za-z]:\\/.test(root) || /[\x00-\x1f]/.test(root)) return null;
|
|
2503
2928
|
const payload = Buffer.from(JSON.stringify({ command: binary.command, args: [...binary.prefix, "config", "init", "--brand", "feishu"], cwd }), "utf8").toString("base64");
|
|
2504
2929
|
const script = existingAppOuterTemplate.replace("__PAYLOAD__", payload);
|
|
2505
|
-
return { command:
|
|
2930
|
+
return { command: path9.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), prefix: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")] };
|
|
2506
2931
|
}
|
|
2507
2932
|
|
|
2508
2933
|
// builtin/extensions/im-forward/providers/feishu/setup.ts
|
|
2509
2934
|
function findNpmCli() {
|
|
2510
|
-
const dirs = [
|
|
2511
|
-
for (const dir of dirs) for (const root of [
|
|
2935
|
+
const dirs = [path10.dirname(process.execPath), ...(process.env.PATH ?? "").split(path10.delimiter)];
|
|
2936
|
+
for (const dir of dirs) for (const root of [path10.join(dir, "node_modules", "npm"), path10.resolve(dir, "..", "lib", "node_modules", "npm")]) {
|
|
2512
2937
|
try {
|
|
2513
|
-
const pkg = JSON.parse(fs8.readFileSync(
|
|
2514
|
-
const entry =
|
|
2938
|
+
const pkg = JSON.parse(fs8.readFileSync(path10.join(root, "package.json"), "utf8"));
|
|
2939
|
+
const entry = path10.join(root, "bin", "npm-cli.js");
|
|
2515
2940
|
if (pkg.name === "npm" && pkg.bin?.npm === "bin/npm-cli.js" && fs8.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
|
|
2516
2941
|
} catch {
|
|
2517
2942
|
}
|
|
@@ -3026,7 +3451,63 @@ function normalizeEvent(line) {
|
|
|
3026
3451
|
images: extractImageKeys(raw.content)
|
|
3027
3452
|
};
|
|
3028
3453
|
}
|
|
3029
|
-
function
|
|
3454
|
+
function normalizeCardAction(line) {
|
|
3455
|
+
let raw;
|
|
3456
|
+
try {
|
|
3457
|
+
raw = JSON.parse(line);
|
|
3458
|
+
} catch {
|
|
3459
|
+
return null;
|
|
3460
|
+
}
|
|
3461
|
+
if (!isRecord(raw) || raw.type !== "card.action.trigger" || typeof raw.event_id !== "string" || typeof raw.chat_id !== "string") return null;
|
|
3462
|
+
if (typeof raw.message_id !== "string" || typeof raw.operator_id !== "string") return null;
|
|
3463
|
+
let value;
|
|
3464
|
+
try {
|
|
3465
|
+
value = typeof raw.action_value === "string" ? JSON.parse(raw.action_value) : raw.action_value;
|
|
3466
|
+
} catch {
|
|
3467
|
+
return null;
|
|
3468
|
+
}
|
|
3469
|
+
if (!isRecord(value) || typeof value.cmd !== "string") return null;
|
|
3470
|
+
const cmd = value.cmd;
|
|
3471
|
+
const parts = [`/card ${cmd}`];
|
|
3472
|
+
if (value.ru === true) parts.push("--restricted");
|
|
3473
|
+
if (value.p !== void 0) {
|
|
3474
|
+
try {
|
|
3475
|
+
parts.push(JSON.stringify(value.p));
|
|
3476
|
+
} catch {
|
|
3477
|
+
}
|
|
3478
|
+
}
|
|
3479
|
+
return {
|
|
3480
|
+
event_id: raw.event_id,
|
|
3481
|
+
message_id: raw.message_id,
|
|
3482
|
+
chat_id: raw.chat_id,
|
|
3483
|
+
sender_id: raw.operator_id,
|
|
3484
|
+
chatType: void 0,
|
|
3485
|
+
// card events do not carry chat_type; gates fall back to chat_id matching
|
|
3486
|
+
text: parts.join(" "),
|
|
3487
|
+
images: []
|
|
3488
|
+
};
|
|
3489
|
+
}
|
|
3490
|
+
function normalizeMenuEvent(line, fallbackChatId) {
|
|
3491
|
+
let raw;
|
|
3492
|
+
try {
|
|
3493
|
+
raw = JSON.parse(line);
|
|
3494
|
+
} catch {
|
|
3495
|
+
return null;
|
|
3496
|
+
}
|
|
3497
|
+
if (!isRecord(raw) || raw.type !== "application.bot.menu_v6" || typeof raw.event_id !== "string" || typeof raw.event_key !== "string") return null;
|
|
3498
|
+
const operator = typeof raw.operator_open_id === "string" && raw.operator_open_id ? raw.operator_open_id : typeof raw.operator_id === "string" ? raw.operator_id : void 0;
|
|
3499
|
+
if (!operator) return null;
|
|
3500
|
+
return {
|
|
3501
|
+
event_id: raw.event_id,
|
|
3502
|
+
message_id: `menu-${raw.event_id}`,
|
|
3503
|
+
chat_id: fallbackChatId,
|
|
3504
|
+
sender_id: operator,
|
|
3505
|
+
chatType: "p2p",
|
|
3506
|
+
text: `/${raw.event_key}`,
|
|
3507
|
+
images: []
|
|
3508
|
+
};
|
|
3509
|
+
}
|
|
3510
|
+
function connect(binary, profile, targetKind = "chat", settings = { targetId: "" }) {
|
|
3030
3511
|
const lifetime = new AbortController();
|
|
3031
3512
|
const active = /* @__PURE__ */ new Set();
|
|
3032
3513
|
const native = (...args) => {
|
|
@@ -3041,26 +3522,30 @@ function connect(binary, profile, targetKind = "chat") {
|
|
|
3041
3522
|
};
|
|
3042
3523
|
let canonicalAppIdCache = null;
|
|
3043
3524
|
let canonicalResolved = false;
|
|
3525
|
+
const BUS_RECONNECT_GRACE_MS = 10 * 60 * 1e3;
|
|
3526
|
+
async function canonicalAppIdNow() {
|
|
3527
|
+
if (canonicalResolved) return canonicalAppIdCache || void 0;
|
|
3528
|
+
if (!profile) {
|
|
3529
|
+
canonicalResolved = true;
|
|
3530
|
+
return void 0;
|
|
3531
|
+
}
|
|
3532
|
+
try {
|
|
3533
|
+
const result = await native(binary, ["profile", "list"], 1e4, void 0, { signal: lifetime.signal });
|
|
3534
|
+
const profiles = result.error ? null : parseProfiles(result.stdout);
|
|
3535
|
+
if (!profiles) return void 0;
|
|
3536
|
+
const appId = profiles.find((item) => item.name === profile)?.appId;
|
|
3537
|
+
if (!appId) return void 0;
|
|
3538
|
+
canonicalAppIdCache = appId;
|
|
3539
|
+
canonicalResolved = true;
|
|
3540
|
+
return appId;
|
|
3541
|
+
} catch {
|
|
3542
|
+
return void 0;
|
|
3543
|
+
}
|
|
3544
|
+
}
|
|
3044
3545
|
return {
|
|
3045
3546
|
sourcePrefix: "[Feishu]",
|
|
3046
3547
|
async canonicalAppId() {
|
|
3047
|
-
|
|
3048
|
-
if (!profile) {
|
|
3049
|
-
canonicalResolved = true;
|
|
3050
|
-
return void 0;
|
|
3051
|
-
}
|
|
3052
|
-
try {
|
|
3053
|
-
const result = await native(binary, ["profile", "list"], 1e4, void 0, { signal: lifetime.signal });
|
|
3054
|
-
const profiles = result.error ? null : parseProfiles(result.stdout);
|
|
3055
|
-
if (!profiles) return void 0;
|
|
3056
|
-
const appId = profiles.find((item) => item.name === profile)?.appId;
|
|
3057
|
-
if (!appId) return void 0;
|
|
3058
|
-
canonicalAppIdCache = appId;
|
|
3059
|
-
canonicalResolved = true;
|
|
3060
|
-
return canonicalAppIdCache;
|
|
3061
|
-
} catch {
|
|
3062
|
-
return void 0;
|
|
3063
|
-
}
|
|
3548
|
+
return canonicalAppIdNow();
|
|
3064
3549
|
},
|
|
3065
3550
|
async dispose() {
|
|
3066
3551
|
lifetime.abort();
|
|
@@ -3078,6 +3563,21 @@ function connect(binary, profile, targetKind = "chat") {
|
|
|
3078
3563
|
const data = await call(replyTo ? ["im", "+messages-reply", "--as", "bot", "--message-id", replyTo, ...threadFlag, "--file", file, "--idempotency-key", key] : ["im", "+messages-send", "--as", "bot", ...recipient, "--file", file, "--idempotency-key", key]);
|
|
3079
3564
|
return typeof data?.message_id === "string" ? { messageId: data.message_id, threadId: typeof data.thread_id === "string" ? data.thread_id : null } : null;
|
|
3080
3565
|
},
|
|
3566
|
+
// 4.3.10 panel cards: compile the neutral CardSpec and send it as an
|
|
3567
|
+
// interactive message. The card JSON is provider-private output of
|
|
3568
|
+
// card.ts's compiler — never hand-composed here.
|
|
3569
|
+
async sendCard(target, spec, key, replyTo) {
|
|
3570
|
+
const recipient = targetKind === "user" ? ["--user-id", target] : ["--chat-id", target];
|
|
3571
|
+
const content = JSON.stringify(compileCard(spec));
|
|
3572
|
+
const data = await call(replyTo ? ["im", "+messages-reply", "--as", "bot", "--message-id", replyTo, "--msg-type", "interactive", "--content", content, "--idempotency-key", key] : ["im", "+messages-send", "--as", "bot", ...recipient, "--msg-type", "interactive", "--content", content, "--idempotency-key", key]);
|
|
3573
|
+
return typeof data?.message_id === "string" ? { messageId: data.message_id, threadId: typeof data.thread_id === "string" ? data.thread_id : null } : null;
|
|
3574
|
+
},
|
|
3575
|
+
// 4.3.10: patch an existing card in place (admin panels refresh without
|
|
3576
|
+
// re-sending). Feishu bound: the message must be <14 days old.
|
|
3577
|
+
async patch(messageId, spec) {
|
|
3578
|
+
const data = await call(["im", "messages", "patch", "--as", "bot", "--params", JSON.stringify({ message_id: messageId }), "--data", JSON.stringify({ content: JSON.stringify(compileCard(spec)) })]);
|
|
3579
|
+
return Boolean(data);
|
|
3580
|
+
},
|
|
3081
3581
|
async acknowledge(id) {
|
|
3082
3582
|
await call(["im", "reactions", "create", "--as", "bot", "--params", JSON.stringify({ message_id: id }), "--data", JSON.stringify({ reaction_type: { emoji_type: "THUMBSUP" } })]);
|
|
3083
3583
|
},
|
|
@@ -3100,18 +3600,18 @@ function connect(binary, profile, targetKind = "chat") {
|
|
|
3100
3600
|
return Array.isArray(data?.messages) ? data.messages.flatMap((message) => isRecord(message) && typeof message.message_id === "string" ? [message.message_id] : []) : null;
|
|
3101
3601
|
},
|
|
3102
3602
|
async downloadImage(messageId, image, index) {
|
|
3103
|
-
const directory = fs9.mkdtempSync(
|
|
3603
|
+
const directory = fs9.mkdtempSync(path11.join(os4.tmpdir(), "pie-im-forward-"));
|
|
3104
3604
|
const cleanup = () => fs9.rmSync(directory, { recursive: true, force: true });
|
|
3105
3605
|
try {
|
|
3106
3606
|
const name = `image-${index + 1}.png`;
|
|
3107
3607
|
const result = await native(binary, profile ? ["im", "+messages-resources-download", "--as", "bot", "--message-id", messageId, "--file-key", image, "--type", "image", "--output", name, "--profile", profile] : ["im", "+messages-resources-download", "--as", "bot", "--message-id", messageId, "--file-key", image, "--type", "image", "--output", name], 3e4, directory, { signal: lifetime.signal });
|
|
3108
3608
|
if (result.error || !parseLarkCliEnvelope(result.stdout).ok) throw new Error("Image download failed");
|
|
3109
|
-
let target =
|
|
3609
|
+
let target = path11.join(directory, name);
|
|
3110
3610
|
if (fs9.statSync(target).size > 10 * 1024 * 1024) throw new Error("Image exceeds 10 MiB");
|
|
3111
3611
|
const detected = readImageFormat(target);
|
|
3112
3612
|
if (detected.ext === ".bin") throw new Error("Unsupported image format");
|
|
3113
3613
|
if (detected.ext !== ".png") {
|
|
3114
|
-
const corrected =
|
|
3614
|
+
const corrected = path11.join(directory, `image-${index + 1}${detected.ext}`);
|
|
3115
3615
|
fs9.renameSync(target, corrected);
|
|
3116
3616
|
target = corrected;
|
|
3117
3617
|
}
|
|
@@ -3126,19 +3626,73 @@ function connect(binary, profile, targetKind = "chat") {
|
|
|
3126
3626
|
let closed = false;
|
|
3127
3627
|
let failed = false;
|
|
3128
3628
|
let lastErrorLine = "";
|
|
3129
|
-
const
|
|
3130
|
-
const
|
|
3131
|
-
|
|
3132
|
-
|
|
3133
|
-
|
|
3629
|
+
const children = /* @__PURE__ */ new Set();
|
|
3630
|
+
const optionalRespawnAttempts = /* @__PURE__ */ new Map();
|
|
3631
|
+
const optionalRespawnTimers = /* @__PURE__ */ new Map();
|
|
3632
|
+
const optionalMaps = /* @__PURE__ */ new Map();
|
|
3633
|
+
const scheduleOptionalRespawn = (eventKey, map) => {
|
|
3634
|
+
optionalMaps.set(eventKey, map);
|
|
3635
|
+
if (stopped) return;
|
|
3636
|
+
if (optionalRespawnTimers.has(eventKey)) return;
|
|
3637
|
+
const attempt = optionalRespawnAttempts.get(eventKey) ?? 0;
|
|
3638
|
+
const delay2 = Math.min(5e3 * 2 ** attempt, 12e4);
|
|
3639
|
+
optionalRespawnAttempts.set(eventKey, attempt + 1);
|
|
3640
|
+
const timer = setTimeout(() => {
|
|
3641
|
+
optionalRespawnTimers.delete(eventKey);
|
|
3642
|
+
if (stopped) return;
|
|
3643
|
+
try {
|
|
3644
|
+
const map2 = optionalMaps.get(eventKey) ?? map;
|
|
3645
|
+
spawnConsume(eventKey, map2, false);
|
|
3646
|
+
} catch {
|
|
3647
|
+
scheduleOptionalRespawn(eventKey, map);
|
|
3648
|
+
}
|
|
3649
|
+
}, delay2);
|
|
3650
|
+
timer.unref?.();
|
|
3651
|
+
optionalRespawnTimers.set(eventKey, timer);
|
|
3652
|
+
};
|
|
3653
|
+
const spawnConsume = (eventKey, map, required) => {
|
|
3654
|
+
const child2 = spawn4(binary.command, [...binary.prefix, "event", "consume", eventKey, "--as", "bot", ...profile ? ["--profile", profile] : []], { stdio: ["pipe", "pipe", "pipe"], shell: false, windowsHide: true, detached: process.platform !== "win32" });
|
|
3655
|
+
child2.stdin?.on("error", () => void 0);
|
|
3656
|
+
const output = lineReader((line) => {
|
|
3657
|
+
if (!closed) {
|
|
3658
|
+
const event = map(line);
|
|
3659
|
+
if (event) callbacks.event(event);
|
|
3660
|
+
}
|
|
3661
|
+
});
|
|
3662
|
+
const errors = lineReader((line) => {
|
|
3663
|
+
const text = line.trim();
|
|
3664
|
+
if (!text) return;
|
|
3665
|
+
if (text.startsWith("[event] ready")) {
|
|
3666
|
+
if (!required) optionalRespawnAttempts.set(eventKey, 0);
|
|
3667
|
+
return;
|
|
3668
|
+
}
|
|
3669
|
+
if (safeErrorPatterns.some((pattern) => pattern.test(text)) && text.length <= 200) lastErrorLine = text;
|
|
3670
|
+
}, 4096);
|
|
3671
|
+
child2.stdout?.on("data", output.write);
|
|
3672
|
+
child2.stdout?.on("end", output.end);
|
|
3673
|
+
child2.stderr?.on("data", errors.write);
|
|
3674
|
+
child2.stderr?.on("end", errors.end);
|
|
3675
|
+
if (required) {
|
|
3676
|
+
child2.on("error", () => fail(`Feishu consumer spawn failed (${eventKey})`));
|
|
3677
|
+
child2.on("exit", (code, signal) => fail(`Feishu consumer code=${code} signal=${signal} (${eventKey})`));
|
|
3678
|
+
child2.on("close", (code, signal) => {
|
|
3679
|
+
closed = true;
|
|
3680
|
+
fail(`Feishu consumer code=${code} signal=${signal} (${eventKey})`);
|
|
3681
|
+
});
|
|
3682
|
+
} else {
|
|
3683
|
+
let ended = false;
|
|
3684
|
+
const endedOnce = () => {
|
|
3685
|
+
if (ended) return;
|
|
3686
|
+
ended = true;
|
|
3687
|
+
if (!stopped && !closed && !failed) scheduleOptionalRespawn(eventKey, map);
|
|
3688
|
+
};
|
|
3689
|
+
child2.on("error", endedOnce);
|
|
3690
|
+
child2.on("close", endedOnce);
|
|
3134
3691
|
}
|
|
3692
|
+
children.add(child2);
|
|
3693
|
+
child2.once("close", () => children.delete(child2));
|
|
3694
|
+
return child2;
|
|
3135
3695
|
};
|
|
3136
|
-
child.stdin?.on("error", () => void 0);
|
|
3137
|
-
const output = lineReader((line) => {
|
|
3138
|
-
if (closed) return;
|
|
3139
|
-
const event = normalizeEvent(line);
|
|
3140
|
-
if (event) callbacks.event(event);
|
|
3141
|
-
});
|
|
3142
3696
|
const safeErrorPatterns = [
|
|
3143
3697
|
/another event bus is already connected/i,
|
|
3144
3698
|
/no active profile/i,
|
|
@@ -3147,32 +3701,106 @@ function connect(binary, profile, targetKind = "chat") {
|
|
|
3147
3701
|
/permission/i,
|
|
3148
3702
|
/connect|network|dns|timeout/i
|
|
3149
3703
|
];
|
|
3150
|
-
const
|
|
3151
|
-
|
|
3152
|
-
|
|
3153
|
-
|
|
3154
|
-
if (!failed && !stopped) callbacks.ready();
|
|
3155
|
-
return;
|
|
3704
|
+
const fail = (reason) => {
|
|
3705
|
+
if (!failed && !stopped) {
|
|
3706
|
+
failed = true;
|
|
3707
|
+
callbacks.failure(lastErrorLine ? `${reason} \u2014 ${lastErrorLine}` : reason);
|
|
3156
3708
|
}
|
|
3157
|
-
|
|
3158
|
-
|
|
3159
|
-
|
|
3160
|
-
|
|
3161
|
-
|
|
3162
|
-
|
|
3163
|
-
|
|
3164
|
-
|
|
3165
|
-
|
|
3166
|
-
|
|
3167
|
-
|
|
3168
|
-
|
|
3709
|
+
};
|
|
3710
|
+
const chatTypeCache = /* @__PURE__ */ new Map();
|
|
3711
|
+
const resolveChatType = async (chatId) => {
|
|
3712
|
+
if (chatTypeCache.has(chatId)) return chatTypeCache.get(chatId);
|
|
3713
|
+
try {
|
|
3714
|
+
const data = await call(["im", "chats", "get", "--as", "bot", "--params", JSON.stringify({ chat_id: chatId })]);
|
|
3715
|
+
const mode = typeof data?.chat_mode === "string" ? data.chat_mode : void 0;
|
|
3716
|
+
const type = mode === "group" ? "group" : mode === "p2p" ? "p2p" : void 0;
|
|
3717
|
+
if (type) chatTypeCache.set(chatId, type);
|
|
3718
|
+
return type;
|
|
3719
|
+
} catch {
|
|
3720
|
+
return void 0;
|
|
3721
|
+
}
|
|
3722
|
+
};
|
|
3723
|
+
const child = spawnConsume("im.message.receive_v1", normalizeEvent, true);
|
|
3724
|
+
{
|
|
3725
|
+
const errors = lineReader((line) => {
|
|
3726
|
+
const text = line.trim();
|
|
3727
|
+
if (!text) return;
|
|
3728
|
+
if (text.startsWith("[event] ready")) {
|
|
3729
|
+
if (!failed && !stopped) callbacks.ready();
|
|
3730
|
+
return;
|
|
3731
|
+
}
|
|
3732
|
+
if (safeErrorPatterns.some((pattern) => pattern.test(text)) && text.length <= 200) lastErrorLine = text;
|
|
3733
|
+
}, 4096);
|
|
3734
|
+
child.stderr?.on("data", errors.write);
|
|
3735
|
+
}
|
|
3736
|
+
try {
|
|
3737
|
+
spawnConsume("card.action.trigger", (line) => {
|
|
3738
|
+
const ev = normalizeCardAction(line);
|
|
3739
|
+
if (!ev) return null;
|
|
3740
|
+
void resolveChatType(ev.chat_id).then((t) => {
|
|
3741
|
+
if (stopped || closed || failed) return;
|
|
3742
|
+
if (t) ev.chatType = t;
|
|
3743
|
+
callbacks.event(ev);
|
|
3744
|
+
});
|
|
3745
|
+
return null;
|
|
3746
|
+
}, false);
|
|
3747
|
+
} catch {
|
|
3748
|
+
}
|
|
3749
|
+
try {
|
|
3750
|
+
spawnConsume("application.bot.menu_v6", (line) => normalizeMenuEvent(line, settings.targetId), false);
|
|
3751
|
+
} catch {
|
|
3752
|
+
}
|
|
3169
3753
|
return { async stop() {
|
|
3170
3754
|
stopped = true;
|
|
3171
|
-
|
|
3755
|
+
for (const timer of optionalRespawnTimers.values()) clearTimeout(timer);
|
|
3756
|
+
optionalRespawnTimers.clear();
|
|
3757
|
+
await Promise.allSettled([...children].map((child2) => shutdownConsumer(child2)));
|
|
3172
3758
|
} };
|
|
3759
|
+
},
|
|
3760
|
+
// 4.3.14 bus health: read the shared daemon's log tail and decide whether
|
|
3761
|
+
// the CLOUD websocket looks dead. Signal: the LAST `[SDK] disconnected`
|
|
3762
|
+
// line older than the reconnect grace with no newer connect (measured:
|
|
3763
|
+
// healthy reconnects land within ~2min; the aged 11h case stayed
|
|
3764
|
+
// disconnected until a manual `event stop --force`). Missing/unparsed log
|
|
3765
|
+
// = undefined (no signal, not an alarm) — escalate only on a POSITIVE
|
|
3766
|
+
// stale reading.
|
|
3767
|
+
async consumeBusHealth() {
|
|
3768
|
+
const appId = await canonicalAppIdNow();
|
|
3769
|
+
if (!appId) return void 0;
|
|
3770
|
+
const larkHome = process.env.PIE_LARK_CLI_HOME && process.env.PIE_LARK_CLI_HOME.trim() ? process.env.PIE_LARK_CLI_HOME : os4.homedir();
|
|
3771
|
+
const logPath = path11.join(larkHome, ".lark-cli", "events", appId, "bus.log");
|
|
3772
|
+
let tail;
|
|
3773
|
+
try {
|
|
3774
|
+
const fd = fs9.openSync(logPath, "r");
|
|
3775
|
+
try {
|
|
3776
|
+
const size = fs9.fstatSync(fd).size;
|
|
3777
|
+
const start = Math.max(0, size - 64 * 1024);
|
|
3778
|
+
const buf = Buffer.alloc(size - start);
|
|
3779
|
+
fs9.readSync(fd, buf, 0, buf.length, start);
|
|
3780
|
+
tail = buf.toString("utf8");
|
|
3781
|
+
} finally {
|
|
3782
|
+
fs9.closeSync(fd);
|
|
3783
|
+
}
|
|
3784
|
+
} catch {
|
|
3785
|
+
return void 0;
|
|
3786
|
+
}
|
|
3787
|
+
return parseBusHealth(tail, Date.now(), BUS_RECONNECT_GRACE_MS);
|
|
3173
3788
|
}
|
|
3174
3789
|
};
|
|
3175
3790
|
}
|
|
3791
|
+
function parseBusHealth(tail, now, graceMs = 10 * 6e4) {
|
|
3792
|
+
const lines = tail.split("\n");
|
|
3793
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
3794
|
+
const line = lines[i];
|
|
3795
|
+
const m = /^(\d{4})\/(\d{2})\/(\d{2}) (\d{2}):(\d{2}):(\d{2}) \[SDK\] (connected|disconnected) to /.exec(line);
|
|
3796
|
+
if (!m) continue;
|
|
3797
|
+
const when = new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]).getTime();
|
|
3798
|
+
if (!Number.isFinite(when)) return void 0;
|
|
3799
|
+
if (m[7] === "connected") return "ok";
|
|
3800
|
+
return now - when > graceMs ? "stale" : void 0;
|
|
3801
|
+
}
|
|
3802
|
+
return void 0;
|
|
3803
|
+
}
|
|
3176
3804
|
var feishuProvider = {
|
|
3177
3805
|
id: "feishu",
|
|
3178
3806
|
label: "Feishu (Lark)",
|
|
@@ -3189,7 +3817,7 @@ var feishuProvider = {
|
|
|
3189
3817
|
connect(settings, cwd) {
|
|
3190
3818
|
const binary = resolveLaunchSpec(typeof settings.larkCli === "string" ? settings.larkCli : void 0, cwd);
|
|
3191
3819
|
const profile = typeof settings.larkCliProfile === "string" && settings.larkCliProfile.trim() ? settings.larkCliProfile.trim() : void 0;
|
|
3192
|
-
return binary ? connect(binary, profile, settings.targetKind) : null;
|
|
3820
|
+
return binary ? connect(binary, profile, settings.targetKind, settings) : null;
|
|
3193
3821
|
},
|
|
3194
3822
|
setup: setupFeishu
|
|
3195
3823
|
};
|
|
@@ -3224,13 +3852,6 @@ function initializeImForward(ctx, providers = implementedProviders) {
|
|
|
3224
3852
|
return handlers.get(name)?.(event);
|
|
3225
3853
|
});
|
|
3226
3854
|
let warnedMismatch = false;
|
|
3227
|
-
let relayConnection;
|
|
3228
|
-
let relayTargetId;
|
|
3229
|
-
let relayRegisterRoute;
|
|
3230
|
-
let relayClaimThread;
|
|
3231
|
-
let relayAnchors;
|
|
3232
|
-
let relayCurrentSession;
|
|
3233
|
-
const relayAnchorOwned = (id) => relayAnchors?.has(id) === true;
|
|
3234
3855
|
function liveEnabled(config) {
|
|
3235
3856
|
if (disposed) return false;
|
|
3236
3857
|
const live = readLiveConfig(ctx.cwd, dir);
|
|
@@ -3267,8 +3888,6 @@ function initializeImForward(ctx, providers = implementedProviders) {
|
|
|
3267
3888
|
}
|
|
3268
3889
|
activeConfig = config;
|
|
3269
3890
|
warnedMismatch = false;
|
|
3270
|
-
relayConnection = connection;
|
|
3271
|
-
relayTargetId = settings.targetId;
|
|
3272
3891
|
const bridge = Object.create(ctx);
|
|
3273
3892
|
bridge.on = (name, handler) => {
|
|
3274
3893
|
handlers.set(name, handler);
|
|
@@ -3291,11 +3910,6 @@ function initializeImForward(ctx, providers = implementedProviders) {
|
|
|
3291
3910
|
if (latest.problems.length || !latest.config || configurationIdentity(latest.config) !== configurationIdentity(config)) throw new Error("Configuration changed; setup required");
|
|
3292
3911
|
writeConfig(ctx.cwd, dir, { enabled: next });
|
|
3293
3912
|
});
|
|
3294
|
-
relayCurrentSession = () => session;
|
|
3295
|
-
const seam = bridge.__imRelaySeam;
|
|
3296
|
-
relayRegisterRoute = seam?.registerRoute;
|
|
3297
|
-
relayClaimThread = seam?.claimThread;
|
|
3298
|
-
relayAnchors = seam?.anchors;
|
|
3299
3913
|
if (session) handlers.get("session:changed")?.({ type: "session:changed", sessionId: session });
|
|
3300
3914
|
ctx.__forceInboundRetriesForTest = bridge.__forceInboundRetriesForTest;
|
|
3301
3915
|
suspendEventConsumer = bridge.suspendEventConsumer?.bind(bridge);
|
|
@@ -3310,12 +3924,6 @@ function initializeImForward(ctx, providers = implementedProviders) {
|
|
|
3310
3924
|
status = void 0;
|
|
3311
3925
|
activeConfig = void 0;
|
|
3312
3926
|
suspendEventConsumer = void 0;
|
|
3313
|
-
relayConnection = void 0;
|
|
3314
|
-
relayTargetId = void 0;
|
|
3315
|
-
relayRegisterRoute = void 0;
|
|
3316
|
-
relayClaimThread = void 0;
|
|
3317
|
-
relayAnchors = void 0;
|
|
3318
|
-
relayCurrentSession = void 0;
|
|
3319
3927
|
const cleanup = runtimeCleanup;
|
|
3320
3928
|
runtimeCleanup = void 0;
|
|
3321
3929
|
ctx.ui.setStatus?.("im-forward", void 0);
|
|
@@ -3450,43 +4058,6 @@ This does not remove the app credentials lark-cli itself stores; re-running setu
|
|
|
3450
4058
|
else if (choice === "Clear configuration\u2026") await clearConfiguration(commandCtx);
|
|
3451
4059
|
} });
|
|
3452
4060
|
}
|
|
3453
|
-
ctx.registerTool?.({
|
|
3454
|
-
name: "im_relay",
|
|
3455
|
-
label: "IM relay",
|
|
3456
|
-
description: "Send ONE explicit message to the user's IM chat on behalf of this session (multi-agent IM v2 escape hatch). Use ONLY when instructed to open a direct channel (takeover: send your previous turn's body) or to post an agreed milestone into a task thread. This is not for ordinary replies \u2014 those forward automatically. Returns the sent message id; the user replying to it opens a thread routed to THIS session.",
|
|
3457
|
-
parameters: Type.Object({
|
|
3458
|
-
text: Type.String({ description: "Message body (markdown)", maxLength: 24e3 }),
|
|
3459
|
-
replyTo: Type.Optional(Type.String({ description: "Optional message id to reply to (stay inside a task thread). Omit to post a new root message (takeover opener)." }))
|
|
3460
|
-
}),
|
|
3461
|
-
risk: { riskClass: "external_side_effect", permissionScope: "host", availableInPlanMode: false, requiresPermission: true, externalSideEffect: true, allowedForSubagentByDefault: false, concurrencySafe: false },
|
|
3462
|
-
execute: async (args) => {
|
|
3463
|
-
if (disposed || !activeConfig) return { content: [{ type: "text", text: "im_relay unavailable: IM forwarding is not configured/active here." }], isError: true };
|
|
3464
|
-
const liveConfig = readLiveConfig(ctx.cwd, dir);
|
|
3465
|
-
if (liveConfig.problems.length || !liveConfig.config) return { content: [{ type: "text", text: "im_relay unavailable: IM configuration is missing or unreadable." }], isError: true };
|
|
3466
|
-
if (liveConfig.config.enabled !== true) return { content: [{ type: "text", text: "im_relay refused: IM forwarding is currently disabled (enabled:false)." }], isError: true };
|
|
3467
|
-
if (configurationIdentity(liveConfig.config) !== configurationIdentity(activeConfig)) return { content: [{ type: "text", text: "im_relay refused: the IM configuration changed; run setup first." }], isError: true };
|
|
3468
|
-
const connection = relayConnection;
|
|
3469
|
-
if (!connection) return { content: [{ type: "text", text: "im_relay unavailable: no active provider connection." }], isError: true };
|
|
3470
|
-
if (args.replyTo !== void 0 && !relayAnchorOwned(args.replyTo)) {
|
|
3471
|
-
return { content: [{ type: "text", text: "im_relay refused: replyTo is not a message this host produced in the bound chat (unknown or foreign anchor)." }], isError: true };
|
|
3472
|
-
}
|
|
3473
|
-
try {
|
|
3474
|
-
const key = `pie-im-relay-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
3475
|
-
const sendSessionId = relayCurrentSession?.() ?? void 0;
|
|
3476
|
-
const sent = await connection.send(relayTargetId, args.text, key, args.replyTo);
|
|
3477
|
-
if (!sent) return { content: [{ type: "text", text: "im_relay: the provider send failed." }], isError: true };
|
|
3478
|
-
const claim = relayClaimThread?.(sent, sendSessionId);
|
|
3479
|
-
if (claim && !claim.claimed && claim.reason === "no thread") {
|
|
3480
|
-
relayRegisterRoute?.(sent, sendSessionId);
|
|
3481
|
-
} else if (claim && !claim.claimed) {
|
|
3482
|
-
return { content: [{ type: "text", text: `Relayed as ${sent.messageId}, but the thread was NOT claimed: ${claim.reason}. Bare speech in that thread still routes to its existing owner \u2014 do not treat this thread as yours.` }], isError: true };
|
|
3483
|
-
}
|
|
3484
|
-
return { content: [{ type: "text", text: `Relayed as ${sent.messageId}${sent.threadId ? ` (thread ${sent.threadId})` : ""}. The user's reply there routes back to this session.` }] };
|
|
3485
|
-
} catch (error) {
|
|
3486
|
-
return { content: [{ type: "text", text: `im_relay failed: ${error instanceof Error ? error.message : String(error)}` }], isError: true };
|
|
3487
|
-
}
|
|
3488
|
-
}
|
|
3489
|
-
});
|
|
3490
4061
|
ctx.registerCleanup?.(async () => {
|
|
3491
4062
|
disposed = true;
|
|
3492
4063
|
setupAbort?.abort();
|