@cydm/pie 4.6.1 → 4.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/builtin/extensions/cron/index.js +53 -20
- package/dist/builtin/extensions/im-forward/README.md +57 -0
- package/dist/builtin/extensions/im-forward/index.js +2147 -605
- package/dist/builtin/extensions/pie-ipc/index.js +193 -23
- package/dist/builtin/extensions/pie-proc/index.js +260 -37
- package/dist/builtin/skills/chrome-devtools-axi/SKILL.md +10 -1
- package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +236 -46
- package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
- package/dist/builtin/skills/chrome-devtools-axi/{chunk-WOGAQ4P5.js → chunk-Z2A5LA5A.js} +8 -0
- package/dist/builtin/skills/chrome-devtools-axi/{cli-NLPMVDGG.js → cli-ZE754CTH.js} +1464 -436
- package/dist/builtin/skills/computer-use-axi/SKILL.md +1 -0
- package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +172 -19
- package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +73 -20
- package/dist/chunks/{chunk-2CJIENLY.js → chunk-EGZ5TZRM.js} +25 -6
- package/dist/chunks/{manager-cli-7ZIDGDMI.js → manager-cli-NEZA46M5.js} +18 -5
- package/dist/chunks/read-file-understanding-FMPXR6EJ.js +1 -1
- package/dist/cli.js +356 -158
- package/package.json +2 -2
- package/dist/chunks/{manager-upgrade-LSTOHBUV.js → manager-upgrade-CTU3ISCW.js} +3 -3
|
@@ -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
|
+
IpcTransport,
|
|
5
6
|
addressBookRoot,
|
|
6
7
|
assistantForwardText,
|
|
7
8
|
chunkKey,
|
|
@@ -12,6 +13,7 @@ import {
|
|
|
12
13
|
configSnapshot,
|
|
13
14
|
configurationIdentity,
|
|
14
15
|
currentConsumer,
|
|
16
|
+
currentIpcRuntime,
|
|
15
17
|
estimatePostRequestBytes,
|
|
16
18
|
failureReason,
|
|
17
19
|
hasConfigLayers,
|
|
@@ -28,22 +30,27 @@ import {
|
|
|
28
30
|
resolveImForwardConfig,
|
|
29
31
|
saveLocation,
|
|
30
32
|
sessionLabel,
|
|
31
|
-
signEnvelope,
|
|
32
33
|
truncateMarkdown,
|
|
33
34
|
tryClaimConsumer,
|
|
34
35
|
writeConfig
|
|
35
|
-
} from "../../../chunks/chunk-
|
|
36
|
+
} from "../../../chunks/chunk-EGZ5TZRM.js";
|
|
37
|
+
import {
|
|
38
|
+
readProcessCommandLine
|
|
39
|
+
} from "../../../chunks/chunk-7RJXKN7N.js";
|
|
36
40
|
import {
|
|
37
41
|
detectImageMime,
|
|
38
42
|
readImageFormat
|
|
39
43
|
} from "../../../chunks/chunk-F7EBZTZO.js";
|
|
40
44
|
import "../../../chunks/chunk-ZPJ3BNQB.js";
|
|
45
|
+
import {
|
|
46
|
+
Type
|
|
47
|
+
} from "../../../chunks/chunk-XXGYUYXI.js";
|
|
41
48
|
import "../../../chunks/chunk-LZQXQOPJ.js";
|
|
42
49
|
|
|
43
50
|
// builtin/extensions/im-forward/runtime.ts
|
|
44
51
|
import * as crypto from "node:crypto";
|
|
45
|
-
import * as
|
|
46
|
-
import { basename, join as pathJoin, resolve as pathResolve, join as
|
|
52
|
+
import * as fs8 from "node:fs";
|
|
53
|
+
import { basename, join as pathJoin, resolve as pathResolve, join as join9, dirname as pathDirname } from "node:path";
|
|
47
54
|
import * as os3 from "node:os";
|
|
48
55
|
|
|
49
56
|
// builtin/extensions/im-forward/thread-registry.ts
|
|
@@ -101,18 +108,46 @@ function recordFor(threadKey, sessionId) {
|
|
|
101
108
|
}
|
|
102
109
|
function takeOver(threadKey, _dead, sessionId) {
|
|
103
110
|
const file = ownerPath(threadKey);
|
|
111
|
+
const tmp = path.join(threadsDir(), `.new-${randomUUID()}.json`);
|
|
112
|
+
const record = recordFor(threadKey, sessionId);
|
|
113
|
+
try {
|
|
114
|
+
const fd = fs.openSync(tmp, "wx", 384);
|
|
115
|
+
try {
|
|
116
|
+
fs.writeFileSync(fd, JSON.stringify(record));
|
|
117
|
+
fs.fsyncSync(fd);
|
|
118
|
+
} finally {
|
|
119
|
+
fs.closeSync(fd);
|
|
120
|
+
}
|
|
121
|
+
} catch {
|
|
122
|
+
try {
|
|
123
|
+
fs.rmSync(tmp, { force: true });
|
|
124
|
+
} catch {
|
|
125
|
+
}
|
|
126
|
+
return { claimed: false, reason: "thread registry unavailable", transient: true };
|
|
127
|
+
}
|
|
104
128
|
try {
|
|
105
|
-
fs.
|
|
129
|
+
fs.renameSync(tmp, file);
|
|
130
|
+
return { claimed: true, ownerSessionId: sessionId };
|
|
106
131
|
} catch {
|
|
132
|
+
try {
|
|
133
|
+
fs.rmSync(tmp, { force: true });
|
|
134
|
+
} catch {
|
|
135
|
+
}
|
|
107
136
|
return { claimed: false, reason: "thread registry unavailable", transient: true };
|
|
108
137
|
}
|
|
109
|
-
return writeNew(threadKey, sessionId);
|
|
110
138
|
}
|
|
111
139
|
function decide(owner, threadKey, sessionId) {
|
|
112
140
|
if (owner.sessionId === sessionId && owner.runtimeId === RUNTIME_ID) {
|
|
113
141
|
return { claimed: true, ownerSessionId: sessionId };
|
|
114
142
|
}
|
|
115
143
|
if (owner.pid > 0 && !pidAlive(owner.pid)) {
|
|
144
|
+
if (owner.sessionId !== sessionId) {
|
|
145
|
+
return {
|
|
146
|
+
claimed: false,
|
|
147
|
+
reason: `thread owned by session ${owner.sessionId} (owner offline)`,
|
|
148
|
+
ownerSessionId: owner.sessionId
|
|
149
|
+
};
|
|
150
|
+
}
|
|
116
151
|
return takeOver(threadKey, owner, sessionId);
|
|
117
152
|
}
|
|
118
153
|
return {
|
|
@@ -283,68 +318,1208 @@ function acquireThreadLock(threadKey) {
|
|
|
283
318
|
if (code !== "EEXIST" && code !== "ENOTEMPTY" && code !== "EPERM" && code !== "ENOTDIR") {
|
|
284
319
|
return { acquired: false, reason: "thread registry unavailable", transient: true };
|
|
285
320
|
}
|
|
286
|
-
if (Date.now() > deadline) return { acquired: false, reason: "thread lock busy", transient: true };
|
|
287
|
-
try {
|
|
288
|
-
retireStaleLock(lock);
|
|
289
|
-
} catch {
|
|
321
|
+
if (Date.now() > deadline) return { acquired: false, reason: "thread lock busy", transient: true };
|
|
322
|
+
try {
|
|
323
|
+
retireStaleLock(lock);
|
|
324
|
+
} catch {
|
|
325
|
+
}
|
|
326
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1 + Math.floor(Math.random() * 3));
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
} finally {
|
|
330
|
+
try {
|
|
331
|
+
fs.rmSync(candidate, { recursive: true, force: true });
|
|
332
|
+
} catch {
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
function releaseThreadLock(threadKey) {
|
|
337
|
+
const token = acquiredLocks.get(threadKey);
|
|
338
|
+
if (token === void 0) return;
|
|
339
|
+
acquiredLocks.delete(threadKey);
|
|
340
|
+
const lock = lockDirPath(threadKey);
|
|
341
|
+
try {
|
|
342
|
+
fs.unlinkSync(path.join(lock, `held.${token}`));
|
|
343
|
+
} catch {
|
|
344
|
+
}
|
|
345
|
+
try {
|
|
346
|
+
const remaining = fs.readdirSync(lock);
|
|
347
|
+
if (remaining.length === 0) fs.rmdirSync(lock);
|
|
348
|
+
} catch {
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
function threadOwner(input) {
|
|
352
|
+
const threadKey = encodeThreadKey(input);
|
|
353
|
+
let read;
|
|
354
|
+
try {
|
|
355
|
+
read = readOwner(threadKey);
|
|
356
|
+
} catch {
|
|
357
|
+
return { unavailable: true };
|
|
358
|
+
}
|
|
359
|
+
if (read.corrupt) return { corrupt: true };
|
|
360
|
+
if (!read.owner) return {};
|
|
361
|
+
if (read.owner.pid > 0 && !pidAlive(read.owner.pid)) {
|
|
362
|
+
return { sessionId: read.owner.sessionId, ownerOffline: true };
|
|
363
|
+
}
|
|
364
|
+
return { sessionId: read.owner.sessionId };
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// builtin/extensions/im-forward/panel.ts
|
|
368
|
+
import * as fs4 from "node:fs";
|
|
369
|
+
import * as os2 from "node:os";
|
|
370
|
+
import * as path5 from "node:path";
|
|
371
|
+
import { fileURLToPath } from "node:url";
|
|
372
|
+
|
|
373
|
+
// builtin/extensions/im-forward/discovery.ts
|
|
374
|
+
import * as os from "node:os";
|
|
375
|
+
import * as path2 from "node:path";
|
|
376
|
+
function ipcDiscoveryRoot() {
|
|
377
|
+
const home = os.homedir() || process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
378
|
+
const override = process.env.PIE_IPC_CONFIG_DIR;
|
|
379
|
+
const agentDir = process.env.PIE_CODING_AGENT_DIR?.trim();
|
|
380
|
+
const raw = override !== void 0 ? override : agentDir || path2.join(home, ".pie");
|
|
381
|
+
const configDir = process.platform === "win32" ? raw : path2.resolve(raw === "~" ? home : raw.startsWith("~/") ? path2.join(home, raw.slice(2)) : raw);
|
|
382
|
+
return path2.join(configDir, "run", "ipc");
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// builtin/extensions/im-forward/panel-actions.ts
|
|
386
|
+
import { execFile, spawn as spawn3 } from "node:child_process";
|
|
387
|
+
import { randomBytes } from "node:crypto";
|
|
388
|
+
import { StringDecoder as StringDecoder3 } from "node:string_decoder";
|
|
389
|
+
import * as fs3 from "node:fs";
|
|
390
|
+
import * as path4 from "node:path";
|
|
391
|
+
|
|
392
|
+
// builtin/extensions/im-forward/lark-cli.ts
|
|
393
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
394
|
+
import { StringDecoder as StringDecoder2 } from "node:string_decoder";
|
|
395
|
+
|
|
396
|
+
// builtin/extensions/im-forward/launch.ts
|
|
397
|
+
import { spawn } from "node:child_process";
|
|
398
|
+
import * as fs2 from "node:fs";
|
|
399
|
+
import * as path3 from "node:path";
|
|
400
|
+
import { StringDecoder } from "node:string_decoder";
|
|
401
|
+
function resolveLaunchSpec(explicit, cwd = process.cwd(), platform = process.platform, env = process.env) {
|
|
402
|
+
const windows = platform === "win32";
|
|
403
|
+
const candidates = explicit ? [path3.resolve(cwd, explicit)] : (env.PATH ?? "").split(windows ? ";" : ":").filter(Boolean).flatMap((dir) => (windows ? ["lark-cli.exe", "lark-cli.cmd"] : ["lark-cli"]).map((name) => path3.resolve(cwd, dir, name)));
|
|
404
|
+
for (const candidate of candidates) {
|
|
405
|
+
try {
|
|
406
|
+
if (!fs2.statSync(candidate).isFile()) continue;
|
|
407
|
+
const ext = path3.extname(candidate).toLowerCase();
|
|
408
|
+
if (ext === ".js" || ext === ".mjs") return { command: process.execPath, prefix: [candidate] };
|
|
409
|
+
if (windows && ext === ".cmd") {
|
|
410
|
+
const dir = path3.dirname(candidate);
|
|
411
|
+
for (const root of [path3.join(dir, "node_modules", "@larksuite", "cli"), path3.resolve(dir, "..", "@larksuite", "cli")]) {
|
|
412
|
+
try {
|
|
413
|
+
const pkg = JSON.parse(fs2.readFileSync(path3.join(root, "package.json"), "utf8"));
|
|
414
|
+
const bin = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.["lark-cli"];
|
|
415
|
+
if (pkg.name !== "@larksuite/cli" || typeof bin !== "string" || bin.replace(/^\.\//, "") !== "scripts/run.js") continue;
|
|
416
|
+
const entry = path3.join(root, "scripts", "run.js");
|
|
417
|
+
if (fs2.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
|
|
418
|
+
} catch {
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
continue;
|
|
422
|
+
}
|
|
423
|
+
if (windows && ext !== ".exe") continue;
|
|
424
|
+
fs2.accessSync(candidate, fs2.constants.X_OK);
|
|
425
|
+
return { command: candidate, prefix: [] };
|
|
426
|
+
} catch {
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
return null;
|
|
430
|
+
}
|
|
431
|
+
var treeStops = /* @__PURE__ */ new WeakMap();
|
|
432
|
+
var hasExited = (child) => child.exitCode != null || child.signalCode != null;
|
|
433
|
+
function stopOwnedTree(child, signal) {
|
|
434
|
+
const existing = treeStops.get(child);
|
|
435
|
+
if (existing) return existing;
|
|
436
|
+
if (process.platform === "win32" && hasExited(child)) return Promise.resolve(false);
|
|
437
|
+
const pending = stopOwnedTreeInner(child, signal);
|
|
438
|
+
treeStops.set(child, pending);
|
|
439
|
+
void pending.finally(() => treeStops.delete(child));
|
|
440
|
+
return pending;
|
|
441
|
+
}
|
|
442
|
+
function stopOwnedTreeInner(child, signal) {
|
|
443
|
+
if (process.platform !== "win32" || !child.pid) {
|
|
444
|
+
try {
|
|
445
|
+
if (child.pid) process.kill(-child.pid, signal);
|
|
446
|
+
else child.kill(signal);
|
|
447
|
+
return Promise.resolve(true);
|
|
448
|
+
} catch {
|
|
449
|
+
try {
|
|
450
|
+
return Promise.resolve(child.kill(signal));
|
|
451
|
+
} catch {
|
|
452
|
+
return Promise.resolve(false);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
return new Promise((resolve6) => {
|
|
457
|
+
let done = false;
|
|
458
|
+
let killer;
|
|
459
|
+
const finish = (ok) => {
|
|
460
|
+
if (done) return;
|
|
461
|
+
done = true;
|
|
462
|
+
clearTimeout(timer);
|
|
463
|
+
if (!ok && !hasExited(child)) {
|
|
464
|
+
try {
|
|
465
|
+
child.kill(signal);
|
|
466
|
+
} catch {
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
resolve6(ok);
|
|
470
|
+
};
|
|
471
|
+
const timer = setTimeout(() => {
|
|
472
|
+
try {
|
|
473
|
+
killer?.kill();
|
|
474
|
+
} catch {
|
|
475
|
+
}
|
|
476
|
+
finish(false);
|
|
477
|
+
}, 1500);
|
|
478
|
+
try {
|
|
479
|
+
const root = process.env.SystemRoot || process.env.windir || "C:\\Windows";
|
|
480
|
+
killer = spawn(path3.join(root, "System32", "taskkill.exe"), ["/PID", String(child.pid), "/T", "/F"], { shell: false, windowsHide: true, stdio: "ignore" });
|
|
481
|
+
killer.on("error", () => finish(false));
|
|
482
|
+
killer.on("exit", (code) => finish(code === 0));
|
|
483
|
+
} catch {
|
|
484
|
+
finish(false);
|
|
485
|
+
}
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
function lineReader(onLine, max = 1024 * 1024) {
|
|
489
|
+
const decoder = new StringDecoder("utf8");
|
|
490
|
+
let pending = "";
|
|
491
|
+
let dropping = false;
|
|
492
|
+
const accept = (text) => {
|
|
493
|
+
for (const [i, part] of text.split("\n").entries()) {
|
|
494
|
+
if (i) {
|
|
495
|
+
if (!dropping) onLine(pending);
|
|
496
|
+
pending = "";
|
|
497
|
+
dropping = false;
|
|
498
|
+
}
|
|
499
|
+
if (!dropping) {
|
|
500
|
+
pending += part;
|
|
501
|
+
if (pending.length > max) {
|
|
502
|
+
pending = "";
|
|
503
|
+
dropping = true;
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
};
|
|
508
|
+
return { write: (chunk) => accept(decoder.write(chunk)), end() {
|
|
509
|
+
accept(decoder.end());
|
|
510
|
+
if (pending && !dropping) onLine(pending);
|
|
511
|
+
pending = "";
|
|
512
|
+
} };
|
|
513
|
+
}
|
|
514
|
+
var shutdowns = /* @__PURE__ */ new WeakMap();
|
|
515
|
+
function shutdownConsumer(child) {
|
|
516
|
+
const existing = shutdowns.get(child);
|
|
517
|
+
if (existing) return existing;
|
|
518
|
+
const pending = shutdownConsumerInner(child);
|
|
519
|
+
shutdowns.set(child, pending);
|
|
520
|
+
return pending;
|
|
521
|
+
}
|
|
522
|
+
async function shutdownConsumerInner(child) {
|
|
523
|
+
let closed = false;
|
|
524
|
+
const close = new Promise((resolve6) => child.once("close", () => {
|
|
525
|
+
closed = true;
|
|
526
|
+
resolve6();
|
|
527
|
+
}));
|
|
528
|
+
const wait = async (ms) => {
|
|
529
|
+
let timer;
|
|
530
|
+
await Promise.race([close, new Promise((resolve6) => {
|
|
531
|
+
timer = setTimeout(resolve6, ms);
|
|
532
|
+
})]);
|
|
533
|
+
clearTimeout(timer);
|
|
534
|
+
};
|
|
535
|
+
try {
|
|
536
|
+
child.stdin?.end();
|
|
537
|
+
} catch {
|
|
538
|
+
}
|
|
539
|
+
await wait(500);
|
|
540
|
+
if (!closed) {
|
|
541
|
+
await stopOwnedTree(child, "SIGTERM");
|
|
542
|
+
await wait(500);
|
|
543
|
+
}
|
|
544
|
+
if (!closed) {
|
|
545
|
+
await stopOwnedTree(child, "SIGKILL");
|
|
546
|
+
await wait(500);
|
|
547
|
+
}
|
|
548
|
+
child.stdin?.destroy();
|
|
549
|
+
child.stdout?.destroy();
|
|
550
|
+
child.stderr?.destroy();
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
// builtin/extensions/im-forward/lark-cli.ts
|
|
554
|
+
async function runLarkCli(binary, args, timeoutMs = 3e4, cwd, options = {}) {
|
|
555
|
+
return new Promise((resolve6) => {
|
|
556
|
+
if (options.signal?.aborted) {
|
|
557
|
+
resolve6({ stdout: "", error: "cancelled" });
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
let child;
|
|
561
|
+
try {
|
|
562
|
+
const spec = typeof binary === "string" ? resolveLaunchSpec(binary) ?? (options.spawn ? { command: binary, prefix: [] } : null) : binary;
|
|
563
|
+
if (!spec) throw new Error("unsupported executable");
|
|
564
|
+
child = (options.spawn ?? spawn2)(spec.command, [...spec.prefix, ...args], {
|
|
565
|
+
shell: false,
|
|
566
|
+
windowsHide: true,
|
|
567
|
+
stdio: [options.stdin ?? "ignore", "pipe", "pipe"],
|
|
568
|
+
detached: process.platform !== "win32",
|
|
569
|
+
...cwd ? { cwd } : {}
|
|
570
|
+
});
|
|
571
|
+
} catch {
|
|
572
|
+
resolve6({ stdout: "", error: "spawn failed" });
|
|
573
|
+
return;
|
|
574
|
+
}
|
|
575
|
+
let stdout = "";
|
|
576
|
+
let stderr = "";
|
|
577
|
+
let settled = false;
|
|
578
|
+
let closed = false;
|
|
579
|
+
let termination;
|
|
580
|
+
let treeStopped = false;
|
|
581
|
+
let killTimer;
|
|
582
|
+
let closeTimer;
|
|
583
|
+
const finish = (result) => {
|
|
584
|
+
if (settled) return;
|
|
585
|
+
settled = true;
|
|
586
|
+
clearTimeout(timer);
|
|
587
|
+
clearTimeout(killTimer);
|
|
588
|
+
clearTimeout(closeTimer);
|
|
589
|
+
options.signal?.removeEventListener("abort", abort);
|
|
590
|
+
resolve6(result);
|
|
591
|
+
};
|
|
592
|
+
const terminatedResult = () => ({ stdout: termination?.startsWith("timeout") ? stdout : "", error: termination });
|
|
593
|
+
const stop = (signal) => {
|
|
594
|
+
try {
|
|
595
|
+
return stopOwnedTree(child, signal);
|
|
596
|
+
} catch {
|
|
597
|
+
return Promise.resolve();
|
|
598
|
+
}
|
|
599
|
+
};
|
|
600
|
+
const kill = () => {
|
|
601
|
+
const stopped = () => {
|
|
602
|
+
treeStopped = true;
|
|
603
|
+
if (settled) return;
|
|
604
|
+
if (closed) {
|
|
605
|
+
finish(terminatedResult());
|
|
606
|
+
return;
|
|
607
|
+
}
|
|
608
|
+
closeTimer = setTimeout(() => {
|
|
609
|
+
child.stdout?.destroy();
|
|
610
|
+
child.stderr?.destroy();
|
|
611
|
+
finish(terminatedResult());
|
|
612
|
+
}, options.closeGraceMs ?? 1e3);
|
|
613
|
+
};
|
|
614
|
+
void stop("SIGKILL").then(stopped, stopped);
|
|
615
|
+
};
|
|
616
|
+
const terminate = (reason, graceful = false) => {
|
|
617
|
+
if (settled || termination) return;
|
|
618
|
+
termination = reason;
|
|
619
|
+
clearTimeout(timer);
|
|
620
|
+
if (graceful) {
|
|
621
|
+
const stopped = () => {
|
|
622
|
+
if (closed) {
|
|
623
|
+
treeStopped = true;
|
|
624
|
+
finish(terminatedResult());
|
|
625
|
+
}
|
|
626
|
+
};
|
|
627
|
+
void stop("SIGTERM").then(stopped, stopped);
|
|
628
|
+
if (!settled) killTimer = setTimeout(kill, options.killGraceMs ?? 1e3);
|
|
629
|
+
} else kill();
|
|
630
|
+
};
|
|
631
|
+
const timer = setTimeout(() => terminate(`timeout after ${timeoutMs}ms`, true), timeoutMs);
|
|
632
|
+
const abort = () => terminate("cancelled");
|
|
633
|
+
options.signal?.addEventListener("abort", abort, { once: true });
|
|
634
|
+
if (options.signal?.aborted) abort();
|
|
635
|
+
const deliverLine = (line) => {
|
|
636
|
+
if (settled || termination) return;
|
|
637
|
+
try {
|
|
638
|
+
options.onLine?.(line);
|
|
639
|
+
} catch {
|
|
640
|
+
terminate("output callback failed");
|
|
641
|
+
}
|
|
642
|
+
};
|
|
643
|
+
const lines = options.onLine ? lineReader(deliverLine, 16384) : void 0;
|
|
644
|
+
const errorLines = options.onLine ? lineReader(deliverLine, 16384) : void 0;
|
|
645
|
+
const outDecoder = new StringDecoder2("utf8");
|
|
646
|
+
const errDecoder = new StringDecoder2("utf8");
|
|
647
|
+
child.stdout?.on("data", (chunk) => {
|
|
648
|
+
if (settled || termination) return;
|
|
649
|
+
lines?.write(chunk);
|
|
650
|
+
if (termination) return;
|
|
651
|
+
stdout += outDecoder.write(chunk);
|
|
652
|
+
if (stdout.length > 8 * 1024 * 1024) {
|
|
653
|
+
stdout = "";
|
|
654
|
+
terminate("stdout exceeds 8 MiB limit");
|
|
655
|
+
}
|
|
656
|
+
});
|
|
657
|
+
child.stderr?.on("data", (chunk) => {
|
|
658
|
+
if (settled || termination) return;
|
|
659
|
+
errorLines?.write(chunk);
|
|
660
|
+
stderr = (stderr + errDecoder.write(chunk)).slice(-4096);
|
|
661
|
+
});
|
|
662
|
+
child.on("error", () => terminate("spawn error"));
|
|
663
|
+
child.on("close", (code) => {
|
|
664
|
+
closed = true;
|
|
665
|
+
if (settled) return;
|
|
666
|
+
if (termination) {
|
|
667
|
+
if (treeStopped) finish(terminatedResult());
|
|
668
|
+
return;
|
|
669
|
+
}
|
|
670
|
+
stdout += outDecoder.end();
|
|
671
|
+
stderr += errDecoder.end();
|
|
672
|
+
lines?.end();
|
|
673
|
+
errorLines?.end();
|
|
674
|
+
if (termination) return;
|
|
675
|
+
if (code === 0 && (stdout.trim() || options.allowEmpty)) finish({ stdout });
|
|
676
|
+
else finish({ stdout, error: `exit ${code}${stderr ? `: ${stderr.slice(-300).trim()}` : ""}` });
|
|
677
|
+
});
|
|
678
|
+
});
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
// builtin/extensions/im-forward/panel-actions.ts
|
|
682
|
+
function panelActionsRoot() {
|
|
683
|
+
return path4.join(path4.dirname(path4.dirname(ipcDiscoveryRoot())), "panel-actions");
|
|
684
|
+
}
|
|
685
|
+
function registryFile() {
|
|
686
|
+
return path4.join(panelActionsRoot(), "registry.json");
|
|
687
|
+
}
|
|
688
|
+
function auditFile() {
|
|
689
|
+
return path4.join(panelActionsRoot(), "audit.jsonl");
|
|
690
|
+
}
|
|
691
|
+
function logsDir() {
|
|
692
|
+
return path4.join(panelActionsRoot(), "logs");
|
|
693
|
+
}
|
|
694
|
+
function locksDir() {
|
|
695
|
+
return path4.join(panelActionsRoot(), "locks");
|
|
696
|
+
}
|
|
697
|
+
function nameCacheFile() {
|
|
698
|
+
return path4.join(panelActionsRoot(), "name-cache.json");
|
|
699
|
+
}
|
|
700
|
+
function expandTilde(p) {
|
|
701
|
+
const home = process.env.HOME ?? process.env.USERPROFILE ?? "/tmp";
|
|
702
|
+
return p === "~" ? home : p.startsWith("~/") ? path4.join(home, p.slice(2)) : p;
|
|
703
|
+
}
|
|
704
|
+
function readRegistry() {
|
|
705
|
+
let raw;
|
|
706
|
+
try {
|
|
707
|
+
raw = fs3.readFileSync(registryFile(), "utf8");
|
|
708
|
+
} catch {
|
|
709
|
+
return { actions: [] };
|
|
710
|
+
}
|
|
711
|
+
try {
|
|
712
|
+
const parsed = JSON.parse(raw);
|
|
713
|
+
if (!Array.isArray(parsed.actions)) throw new Error("actions must be an array");
|
|
714
|
+
const actions = parsed.actions.filter((a) => {
|
|
715
|
+
const r = a;
|
|
716
|
+
return typeof r?.id === "string" && typeof r?.label === "string" && typeof r?.script === "string" && typeof r?.scope === "string" && typeof r?.createdAt === "number" && typeof r?.runs === "number";
|
|
717
|
+
});
|
|
718
|
+
return { actions };
|
|
719
|
+
} catch (error) {
|
|
720
|
+
return { actions: [], error: `panel-actions registry unreadable: ${error instanceof Error ? error.message : String(error)}` };
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
function writeRegistry(reg) {
|
|
724
|
+
fs3.mkdirSync(panelActionsRoot(), { recursive: true });
|
|
725
|
+
const target = registryFile();
|
|
726
|
+
const tmp = `${target}.${process.pid}.${Date.now().toString(36)}.tmp`;
|
|
727
|
+
fs3.writeFileSync(tmp, JSON.stringify(reg, null, " "));
|
|
728
|
+
fs3.renameSync(tmp, target);
|
|
729
|
+
}
|
|
730
|
+
var ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/;
|
|
731
|
+
function slugifyActionId(label, existing) {
|
|
732
|
+
const base = label.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 28).replace(/^-+|-+$/g, "") || "action";
|
|
733
|
+
const ascii = base.replace(/[\u4e00-\u9fff]+/g, "x").replace(/[^a-z0-9-]/g, "").replace(/^-+|-+$/g, "") || "action";
|
|
734
|
+
let id = ascii;
|
|
735
|
+
for (let n = 2; existing.some((a) => a.id === id); n += 1) id = `${ascii}-${n}`;
|
|
736
|
+
return id.slice(0, 32);
|
|
737
|
+
}
|
|
738
|
+
function isValidScope(scope) {
|
|
739
|
+
return scope === "manager" || scope === "worker" || /^worker:[a-z0-9][a-z0-9-_]{0,47}$/i.test(scope);
|
|
740
|
+
}
|
|
741
|
+
function addAction(input) {
|
|
742
|
+
const label = input.label.trim();
|
|
743
|
+
if (!label) throw new Error("panel action label must not be empty");
|
|
744
|
+
if (label.length > 40) throw new Error(`panel action label too long (${label.length} chars, max 40)`);
|
|
745
|
+
if (!isValidScope(input.scope)) throw new Error(`invalid scope "${input.scope}" (manager | worker | worker:<name>)`);
|
|
746
|
+
const script = path4.resolve(expandTilde(input.script.trim()));
|
|
747
|
+
if (!fs3.existsSync(script) || !fs3.statSync(script).isFile()) {
|
|
748
|
+
throw new Error(`script not found: ${script} (the worker must deliver a tested script BEFORE the button is registered)`);
|
|
749
|
+
}
|
|
750
|
+
const cwd = input.cwd !== void 0 ? path4.resolve(expandTilde(input.cwd.trim())) : void 0;
|
|
751
|
+
if (cwd !== void 0 && (!fs3.existsSync(cwd) || !fs3.statSync(cwd).isDirectory())) {
|
|
752
|
+
throw new Error(`cwd not found: ${cwd}`);
|
|
753
|
+
}
|
|
754
|
+
const timeoutMs = input.timeoutMs !== void 0 ? Math.min(Math.max(Math.floor(input.timeoutMs), 5e3), 36e5) : void 0;
|
|
755
|
+
if (input.payload !== void 0) {
|
|
756
|
+
try {
|
|
757
|
+
JSON.stringify(input.payload);
|
|
758
|
+
} catch {
|
|
759
|
+
throw new Error("payload must be JSON-serializable");
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
const { actions, error } = readRegistry();
|
|
763
|
+
if (error) throw new Error(error);
|
|
764
|
+
const id = input.id !== void 0 ? input.id.trim() : slugifyActionId(label, actions);
|
|
765
|
+
if (!ID_PATTERN.test(id)) throw new Error(`invalid action id "${id}" ([a-z0-9-], max 32)`);
|
|
766
|
+
if (actions.some((a) => a.id === id)) throw new Error(`action id "${id}" already exists`);
|
|
767
|
+
const action = {
|
|
768
|
+
id,
|
|
769
|
+
label,
|
|
770
|
+
script,
|
|
771
|
+
...cwd !== void 0 ? { cwd } : {},
|
|
772
|
+
...input.payload !== void 0 ? { payload: input.payload } : {},
|
|
773
|
+
...timeoutMs !== void 0 ? { timeoutMs } : {},
|
|
774
|
+
scope: input.scope,
|
|
775
|
+
...input.creator ? { creator: input.creator } : {},
|
|
776
|
+
createdAt: Date.now(),
|
|
777
|
+
runs: 0
|
|
778
|
+
};
|
|
779
|
+
writeRegistry({ version: 1, actions: [...actions, action] });
|
|
780
|
+
return action;
|
|
781
|
+
}
|
|
782
|
+
function removeAction(id) {
|
|
783
|
+
const { actions, error } = readRegistry();
|
|
784
|
+
if (error) throw new Error(error);
|
|
785
|
+
const found = actions.find((a) => a.id === id);
|
|
786
|
+
if (!found) return void 0;
|
|
787
|
+
writeRegistry({ version: 1, actions: actions.filter((a) => a.id !== id) });
|
|
788
|
+
return found;
|
|
789
|
+
}
|
|
790
|
+
function managerActions() {
|
|
791
|
+
return readRegistry().actions.filter((a) => a.scope === "manager").sort((a, b) => b.runs - a.runs || a.createdAt - b.createdAt);
|
|
792
|
+
}
|
|
793
|
+
function workerActions(workerName) {
|
|
794
|
+
const pinned = `worker:${workerName}`;
|
|
795
|
+
return readRegistry().actions.filter((a) => a.scope === "worker" || a.scope.toLowerCase() === pinned.toLowerCase()).sort((a, b) => b.runs - a.runs || a.createdAt - b.createdAt);
|
|
796
|
+
}
|
|
797
|
+
function findAction(id) {
|
|
798
|
+
return readRegistry().actions.find((a) => a.id === id);
|
|
799
|
+
}
|
|
800
|
+
function bumpRunStats(id, byName) {
|
|
801
|
+
try {
|
|
802
|
+
const { actions, error } = readRegistry();
|
|
803
|
+
if (error) return;
|
|
804
|
+
const found = actions.find((a) => a.id === id);
|
|
805
|
+
if (!found) return;
|
|
806
|
+
found.runs += 1;
|
|
807
|
+
found.lastRunAt = Date.now();
|
|
808
|
+
found.lastRunBy = byName;
|
|
809
|
+
writeRegistry({ version: 1, actions });
|
|
810
|
+
} catch {
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
function appendAudit(entry) {
|
|
814
|
+
try {
|
|
815
|
+
fs3.mkdirSync(panelActionsRoot(), { recursive: true });
|
|
816
|
+
fs3.appendFileSync(auditFile(), `${JSON.stringify(entry)}
|
|
817
|
+
`);
|
|
818
|
+
} catch {
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
function readNameCache() {
|
|
822
|
+
try {
|
|
823
|
+
const parsed = JSON.parse(fs3.readFileSync(nameCacheFile(), "utf8"));
|
|
824
|
+
const out = {};
|
|
825
|
+
for (const [k, v] of Object.entries(parsed)) if (typeof v === "string" && v) out[k] = v;
|
|
826
|
+
return out;
|
|
827
|
+
} catch {
|
|
828
|
+
return {};
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
function fallbackName(openId) {
|
|
832
|
+
if (!openId) return "unknown";
|
|
833
|
+
return openId.length > 10 ? `ou\u2026${openId.slice(-6)}` : openId;
|
|
834
|
+
}
|
|
835
|
+
function peekNameCache(openId) {
|
|
836
|
+
if (!openId) return void 0;
|
|
837
|
+
return readNameCache()[openId];
|
|
838
|
+
}
|
|
839
|
+
async function resolveUserName(openId, opts = {}) {
|
|
840
|
+
if (!openId) return "unknown";
|
|
841
|
+
const cache = readNameCache();
|
|
842
|
+
const hit = cache[openId];
|
|
843
|
+
if (hit) return hit;
|
|
844
|
+
try {
|
|
845
|
+
const args = ["contact", "+get-user", "--user-id", openId, "--as", "bot"];
|
|
846
|
+
if (opts.profile) args.push("--profile", opts.profile);
|
|
847
|
+
const binary = resolveLaunchSpec(opts.binary, opts.cwd);
|
|
848
|
+
if (!binary) return fallbackName(openId);
|
|
849
|
+
const { stdout, error } = await runLarkCli(binary, args, 1e4, opts.cwd, { signal: opts.signal });
|
|
850
|
+
if (!opts.signal?.aborted && !error && stdout.trim()) {
|
|
851
|
+
const parsed = JSON.parse(stdout);
|
|
852
|
+
const name = typeof parsed?.data?.user?.name === "string" ? parsed.data.user.name : typeof parsed.name === "string" ? parsed.name : void 0;
|
|
853
|
+
if (name) {
|
|
854
|
+
cache[openId] = name;
|
|
855
|
+
try {
|
|
856
|
+
fs3.mkdirSync(panelActionsRoot(), { recursive: true });
|
|
857
|
+
fs3.writeFileSync(nameCacheFile(), JSON.stringify(cache, null, " "));
|
|
858
|
+
} catch {
|
|
859
|
+
}
|
|
860
|
+
return name;
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
} catch {
|
|
864
|
+
}
|
|
865
|
+
return fallbackName(openId);
|
|
866
|
+
}
|
|
867
|
+
function lockDirFor(actionId) {
|
|
868
|
+
return path4.join(locksDir(), `${actionId}.lck`);
|
|
869
|
+
}
|
|
870
|
+
function lockInfoPath(dir) {
|
|
871
|
+
return path4.join(dir, "info.json");
|
|
872
|
+
}
|
|
873
|
+
function renewPath(dir) {
|
|
874
|
+
return path4.join(dir, "renew.json");
|
|
875
|
+
}
|
|
876
|
+
var birthtimeProbe;
|
|
877
|
+
function birthtimeUsable() {
|
|
878
|
+
if (birthtimeProbe !== void 0) return birthtimeProbe;
|
|
879
|
+
try {
|
|
880
|
+
fs3.mkdirSync(locksDir(), { recursive: true });
|
|
881
|
+
const probe = fs3.mkdtempSync(path4.join(locksDir(), ".probe-"));
|
|
882
|
+
try {
|
|
883
|
+
const b1 = fs3.statSync(probe).birthtimeMs;
|
|
884
|
+
fs3.writeFileSync(path4.join(probe, "x"), "x");
|
|
885
|
+
const b2 = fs3.statSync(probe).birthtimeMs;
|
|
886
|
+
birthtimeProbe = b1 > 0 && b1 === b2;
|
|
887
|
+
} finally {
|
|
888
|
+
fs3.rmSync(probe, { recursive: true, force: true });
|
|
889
|
+
}
|
|
890
|
+
} catch {
|
|
891
|
+
birthtimeProbe = false;
|
|
892
|
+
}
|
|
893
|
+
return birthtimeProbe;
|
|
894
|
+
}
|
|
895
|
+
function dirGeneration(dir) {
|
|
896
|
+
try {
|
|
897
|
+
const st = fs3.statSync(dir);
|
|
898
|
+
return birthtimeUsable() ? `${st.ino}:${st.birthtimeMs}` : `ino:${st.ino}`;
|
|
899
|
+
} catch {
|
|
900
|
+
return void 0;
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
function readLockInfo(dir) {
|
|
904
|
+
try {
|
|
905
|
+
const parsed = JSON.parse(fs3.readFileSync(lockInfoPath(dir), "utf8"));
|
|
906
|
+
if (typeof parsed?.token !== "string" || typeof parsed?.startedAt !== "number" || typeof parsed?.deadlineAt !== "number" || typeof parsed?.pid !== "number") {
|
|
907
|
+
return { malformed: true };
|
|
908
|
+
}
|
|
909
|
+
return { info: parsed, malformed: false };
|
|
910
|
+
} catch {
|
|
911
|
+
return { malformed: true };
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
function effectiveLock(dir) {
|
|
915
|
+
const { info, malformed } = readLockInfo(dir);
|
|
916
|
+
if (!info) return { malformed };
|
|
917
|
+
let deadlineAt = info.deadlineAt;
|
|
918
|
+
let childPid;
|
|
919
|
+
try {
|
|
920
|
+
const renew = JSON.parse(fs3.readFileSync(renewPath(dir), "utf8"));
|
|
921
|
+
if (renew?.token === info.token && typeof renew.deadlineAt === "number") {
|
|
922
|
+
deadlineAt = renew.deadlineAt;
|
|
923
|
+
if (typeof renew.childPid === "number") childPid = renew.childPid;
|
|
924
|
+
}
|
|
925
|
+
} catch {
|
|
926
|
+
}
|
|
927
|
+
return { info, deadlineAt, childPid, malformed: false };
|
|
928
|
+
}
|
|
929
|
+
function publishLockInfoCas(dir, info) {
|
|
930
|
+
const tmp = path4.join(locksDir(), `.info-${info.token}.tmp`);
|
|
931
|
+
try {
|
|
932
|
+
fs3.writeFileSync(tmp, JSON.stringify(info));
|
|
933
|
+
try {
|
|
934
|
+
fs3.linkSync(tmp, lockInfoPath(dir));
|
|
935
|
+
} catch {
|
|
936
|
+
return false;
|
|
937
|
+
}
|
|
938
|
+
return true;
|
|
939
|
+
} catch {
|
|
940
|
+
return false;
|
|
941
|
+
} finally {
|
|
942
|
+
try {
|
|
943
|
+
fs3.rmSync(tmp, { force: true });
|
|
944
|
+
} catch {
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
function publishRenew(dir, renew) {
|
|
949
|
+
const tmp = path4.join(locksDir(), `.renew-${renew.token}-${Date.now().toString(36)}.tmp`);
|
|
950
|
+
fs3.writeFileSync(tmp, JSON.stringify(renew));
|
|
951
|
+
fs3.renameSync(tmp, renewPath(dir));
|
|
952
|
+
}
|
|
953
|
+
function pidAlive2(pid) {
|
|
954
|
+
try {
|
|
955
|
+
process.kill(pid, 0);
|
|
956
|
+
return true;
|
|
957
|
+
} catch {
|
|
958
|
+
return false;
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
async function fenceChild(childPid, marker) {
|
|
962
|
+
if (childPid === void 0 || !Number.isInteger(childPid) || childPid <= 1) return "not-running";
|
|
963
|
+
if (!marker) return "unknown";
|
|
964
|
+
if (!pidAlive2(childPid)) {
|
|
965
|
+
if (process.platform === "win32") return "unknown";
|
|
966
|
+
try {
|
|
967
|
+
process.kill(-childPid, 0);
|
|
968
|
+
return "unknown";
|
|
969
|
+
} catch (error) {
|
|
970
|
+
return error.code === "ESRCH" ? "not-running" : "unknown";
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
const cmd = readProcessCommandLine(childPid);
|
|
974
|
+
if (cmd === void 0 || !cmd.includes(marker)) return "unknown";
|
|
975
|
+
if (process.platform === "win32") {
|
|
976
|
+
return await new Promise((resolve6) => {
|
|
977
|
+
let killer;
|
|
978
|
+
try {
|
|
979
|
+
killer = spawn3("taskkill", ["/T", "/F", "/PID", String(childPid)], { stdio: "ignore", windowsHide: true });
|
|
980
|
+
} catch {
|
|
981
|
+
resolve6("unknown");
|
|
982
|
+
return;
|
|
983
|
+
}
|
|
984
|
+
killer.on("error", () => resolve6("unknown"));
|
|
985
|
+
const deadline = Date.now() + 5e3;
|
|
986
|
+
const poll = () => {
|
|
987
|
+
if (!pidAlive2(childPid)) {
|
|
988
|
+
resolve6("fenced");
|
|
989
|
+
return;
|
|
990
|
+
}
|
|
991
|
+
if (Date.now() >= deadline) {
|
|
992
|
+
resolve6("unknown");
|
|
993
|
+
return;
|
|
994
|
+
}
|
|
995
|
+
setTimeout(poll, 100).unref?.();
|
|
996
|
+
};
|
|
997
|
+
setTimeout(poll, 100).unref?.();
|
|
998
|
+
});
|
|
999
|
+
}
|
|
1000
|
+
let signaled = false;
|
|
1001
|
+
try {
|
|
1002
|
+
process.kill(-childPid, "SIGKILL");
|
|
1003
|
+
signaled = true;
|
|
1004
|
+
} catch {
|
|
1005
|
+
}
|
|
1006
|
+
if (!signaled) {
|
|
1007
|
+
try {
|
|
1008
|
+
process.kill(childPid, "SIGKILL");
|
|
1009
|
+
signaled = true;
|
|
1010
|
+
} catch {
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
return signaled ? "fenced" : "unknown";
|
|
1014
|
+
}
|
|
1015
|
+
async function claimReap(dir, token, expectedStaleToken, reapMarginMs, childMarker) {
|
|
1016
|
+
const cur = effectiveLock(dir);
|
|
1017
|
+
if (cur.info?.token !== expectedStaleToken) return "busy";
|
|
1018
|
+
if (pidAlive2(cur.info.pid) && Date.now() <= (cur.deadlineAt ?? 0) + reapMarginMs) return "busy";
|
|
1019
|
+
const fenced = await fenceChild(cur.childPid, childMarker);
|
|
1020
|
+
if (fenced === "unknown") return "unfenceable";
|
|
1021
|
+
const recheck = effectiveLock(dir);
|
|
1022
|
+
if (recheck.info?.token !== expectedStaleToken) return "busy";
|
|
1023
|
+
if (recheck.malformed) return "busy";
|
|
1024
|
+
if (pidAlive2(recheck.info.pid) && Date.now() <= (recheck.deadlineAt ?? 0) + reapMarginMs) return "busy";
|
|
1025
|
+
const aside = `${dir}.reap-${token}`;
|
|
1026
|
+
try {
|
|
1027
|
+
fs3.renameSync(dir, aside);
|
|
1028
|
+
} catch {
|
|
1029
|
+
return "busy";
|
|
1030
|
+
}
|
|
1031
|
+
try {
|
|
1032
|
+
fs3.rmSync(aside, { recursive: true, force: true });
|
|
1033
|
+
} catch {
|
|
1034
|
+
}
|
|
1035
|
+
return "reaped";
|
|
1036
|
+
}
|
|
1037
|
+
async function acquireLock(actionId, triggerName, timeoutMs = DEFAULT_TIMEOUT_MS, childMarker) {
|
|
1038
|
+
fs3.mkdirSync(locksDir(), { recursive: true });
|
|
1039
|
+
try {
|
|
1040
|
+
for (const entry of fs3.readdirSync(locksDir())) {
|
|
1041
|
+
if (!entry.includes(".reap-") && !(entry.startsWith(".info-") && entry.endsWith(".tmp"))) continue;
|
|
1042
|
+
try {
|
|
1043
|
+
const stale = path4.join(locksDir(), entry);
|
|
1044
|
+
if (Date.now() - fs3.statSync(stale).mtimeMs > 36e5) fs3.rmSync(stale, { recursive: true, force: true });
|
|
1045
|
+
} catch {
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
} catch {
|
|
1049
|
+
}
|
|
1050
|
+
const dir = lockDirFor(actionId);
|
|
1051
|
+
const token = `${process.pid}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
1052
|
+
const startedAt = Date.now();
|
|
1053
|
+
const info = { pid: process.pid, token, triggerName, startedAt, deadlineAt: startedAt + timeoutMs };
|
|
1054
|
+
const reapMarginMs = 6e4;
|
|
1055
|
+
const malformedFreshMs = 12e4;
|
|
1056
|
+
for (let attempt = 0; attempt < 4; attempt += 1) {
|
|
1057
|
+
try {
|
|
1058
|
+
fs3.mkdirSync(dir);
|
|
1059
|
+
if (!publishLockInfoCas(dir, info)) continue;
|
|
1060
|
+
const myGeneration = dirGeneration(dir);
|
|
1061
|
+
if (myGeneration === void 0 || readLockInfo(dir).info?.token !== token) {
|
|
1062
|
+
continue;
|
|
1063
|
+
}
|
|
1064
|
+
let released = false;
|
|
1065
|
+
return {
|
|
1066
|
+
ok: true,
|
|
1067
|
+
token,
|
|
1068
|
+
stillOwned: () => readLockInfo(dir).info?.token === token,
|
|
1069
|
+
rearm: (ms) => {
|
|
1070
|
+
if (dirGeneration(dir) !== myGeneration) return false;
|
|
1071
|
+
const cur = readLockInfo(dir);
|
|
1072
|
+
if (cur.info?.token !== token) return false;
|
|
1073
|
+
try {
|
|
1074
|
+
publishRenew(dir, { token, deadlineAt: Date.now() + ms, at: Date.now() });
|
|
1075
|
+
} catch {
|
|
1076
|
+
return false;
|
|
1077
|
+
}
|
|
1078
|
+
return dirGeneration(dir) === myGeneration;
|
|
1079
|
+
},
|
|
1080
|
+
announceChild: (pid) => {
|
|
1081
|
+
if (dirGeneration(dir) !== myGeneration) return false;
|
|
1082
|
+
const cur = effectiveLock(dir);
|
|
1083
|
+
if (cur.info?.token !== token) return false;
|
|
1084
|
+
try {
|
|
1085
|
+
publishRenew(dir, { token, deadlineAt: cur.deadlineAt ?? Date.now(), childPid: pid, at: Date.now() });
|
|
1086
|
+
} catch {
|
|
1087
|
+
return false;
|
|
1088
|
+
}
|
|
1089
|
+
return dirGeneration(dir) === myGeneration;
|
|
1090
|
+
},
|
|
1091
|
+
// Ownership-checked release (r2) + generation check (r5): a
|
|
1092
|
+
// reaped-then-reacquired lock belongs to the NEW holder — a late
|
|
1093
|
+
// release() from the old owner must not delete it.
|
|
1094
|
+
release: () => {
|
|
1095
|
+
if (released) return;
|
|
1096
|
+
released = true;
|
|
1097
|
+
if (readLockInfo(dir).info?.token !== token) return;
|
|
1098
|
+
if (dirGeneration(dir) !== myGeneration) return;
|
|
1099
|
+
try {
|
|
1100
|
+
fs3.rmSync(dir, { recursive: true, force: true });
|
|
1101
|
+
} catch {
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
};
|
|
1105
|
+
} catch (error) {
|
|
1106
|
+
if (error.code !== "EEXIST") throw error;
|
|
1107
|
+
const observedGeneration = dirGeneration(dir);
|
|
1108
|
+
const { info: existing, malformed } = readLockInfo(dir);
|
|
1109
|
+
if (malformed || !existing) {
|
|
1110
|
+
let mtime = 0;
|
|
1111
|
+
try {
|
|
1112
|
+
mtime = fs3.statSync(dir).mtimeMs;
|
|
1113
|
+
} catch {
|
|
1114
|
+
continue;
|
|
1115
|
+
}
|
|
1116
|
+
if (Date.now() - mtime < malformedFreshMs) {
|
|
1117
|
+
return { ok: false, holder: { triggerName: "unknown", startedAt: 0 } };
|
|
1118
|
+
}
|
|
1119
|
+
const recheck = readLockInfo(dir);
|
|
1120
|
+
if (!recheck.malformed && recheck.info) continue;
|
|
1121
|
+
if (dirGeneration(dir) !== observedGeneration) continue;
|
|
1122
|
+
const aside = `${dir}.reap-${token}`;
|
|
1123
|
+
try {
|
|
1124
|
+
fs3.renameSync(dir, aside);
|
|
1125
|
+
} catch {
|
|
1126
|
+
continue;
|
|
1127
|
+
}
|
|
1128
|
+
try {
|
|
1129
|
+
fs3.rmSync(aside, { recursive: true, force: true });
|
|
1130
|
+
} catch {
|
|
1131
|
+
}
|
|
1132
|
+
continue;
|
|
1133
|
+
}
|
|
1134
|
+
const effective = effectiveLock(dir);
|
|
1135
|
+
const wedged = pidAlive2(existing.pid) && Date.now() > (effective.deadlineAt ?? existing.deadlineAt) + reapMarginMs;
|
|
1136
|
+
if (pidAlive2(existing.pid) && !wedged) {
|
|
1137
|
+
return {
|
|
1138
|
+
ok: false,
|
|
1139
|
+
holder: { triggerName: existing.triggerName, startedAt: existing.startedAt }
|
|
1140
|
+
};
|
|
1141
|
+
}
|
|
1142
|
+
const reapOutcome = await claimReap(dir, token, existing.token, reapMarginMs, childMarker);
|
|
1143
|
+
if (reapOutcome === "unfenceable") {
|
|
1144
|
+
return {
|
|
1145
|
+
ok: false,
|
|
1146
|
+
holder: {
|
|
1147
|
+
triggerName: existing.triggerName,
|
|
1148
|
+
startedAt: existing.startedAt,
|
|
1149
|
+
note: `\u4E0A\u4E00\u6B21\u6267\u884C\u7684\u8FDB\u7A0B\u8EAB\u4EFD\u65E0\u6CD5\u786E\u8BA4\uFF08\u53EF\u80FD\u7528\u4E86 exec \u5305\u88C5\u6539\u53D8\u4E86 argv\uFF09\u3002\u4E3A\u5B89\u5168\u8D77\u89C1\u4E0D\u81EA\u52A8\u91CA\u653E\u3002\u4EBA\u5DE5\u786E\u8BA4\u65E7\u8FDB\u7A0B\u5DF2\u505C\u6B62\u540E\uFF0C\u5220\u9664 ${dir} \u5373\u53EF\u6062\u590D\u3002`
|
|
1150
|
+
}
|
|
1151
|
+
};
|
|
1152
|
+
}
|
|
1153
|
+
if (reapOutcome === "busy") continue;
|
|
1154
|
+
continue;
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
return { ok: false, holder: { triggerName: "unknown", startedAt: 0 } };
|
|
1158
|
+
}
|
|
1159
|
+
var DEFAULT_TIMEOUT_MS = 3e5;
|
|
1160
|
+
var CAPTURE_CAP_BYTES = 1e6;
|
|
1161
|
+
var KILL_GRACE_MS = 3e3;
|
|
1162
|
+
function interpreterFor(script) {
|
|
1163
|
+
const ext = path4.extname(script).toLowerCase();
|
|
1164
|
+
if (ext === ".mjs" || ext === ".js" || ext === ".cjs") return { command: process.execPath, prefix: [script] };
|
|
1165
|
+
if (ext === ".sh") return { command: "bash", prefix: [script] };
|
|
1166
|
+
if (ext === ".py") return { command: "python3", prefix: [script] };
|
|
1167
|
+
return { command: script, prefix: [] };
|
|
1168
|
+
}
|
|
1169
|
+
var ACTION_LAUNCH_ID_ENV = "PIE_ACTION_LAUNCH_ID";
|
|
1170
|
+
function scriptEnv(req, launchId) {
|
|
1171
|
+
const env = {};
|
|
1172
|
+
for (const key of ["PATH", "HOME", "LANG", "LC_ALL", "TERM", "TMPDIR", "USER", "LOGNAME", "SHELL"]) {
|
|
1173
|
+
const value = process.env[key];
|
|
1174
|
+
if (value !== void 0) env[key] = value;
|
|
1175
|
+
}
|
|
1176
|
+
env[ACTION_LAUNCH_ID_ENV] = launchId;
|
|
1177
|
+
env.PIE_ACTION_ID = req.action.id;
|
|
1178
|
+
env.PIE_ACTION_TRIGGER_NAME = req.trigger.name;
|
|
1179
|
+
if (req.trigger.openId) env.PIE_ACTION_TRIGGER_OPEN_ID = req.trigger.openId;
|
|
1180
|
+
env.PIE_ACTION_CHAT_ID = req.chatId;
|
|
1181
|
+
if (req.action.payload !== void 0) {
|
|
1182
|
+
try {
|
|
1183
|
+
env.PIE_ACTION_PAYLOAD = JSON.stringify(req.action.payload);
|
|
1184
|
+
} catch {
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
if (req.worker) {
|
|
1188
|
+
env.PIE_ACTION_WORKER = req.worker.name;
|
|
1189
|
+
if (req.worker.dir) env.PIE_ACTION_WORKER_DIR = req.worker.dir;
|
|
1190
|
+
}
|
|
1191
|
+
return env;
|
|
1192
|
+
}
|
|
1193
|
+
function execFileText(file, args) {
|
|
1194
|
+
return new Promise((resolve6) => {
|
|
1195
|
+
execFile(file, args, { encoding: "utf8", timeout: 1500, maxBuffer: 512 * 1024, windowsHide: true }, (error, stdout) => {
|
|
1196
|
+
resolve6(error ? void 0 : stdout);
|
|
1197
|
+
});
|
|
1198
|
+
});
|
|
1199
|
+
}
|
|
1200
|
+
async function processHasLaunchId(pid, launchId) {
|
|
1201
|
+
const marker = `${ACTION_LAUNCH_ID_ENV}=${launchId}`;
|
|
1202
|
+
if (process.platform === "linux") {
|
|
1203
|
+
let handle;
|
|
1204
|
+
try {
|
|
1205
|
+
handle = await fs3.promises.open(`/proc/${pid}/environ`, "r");
|
|
1206
|
+
const buf = Buffer.allocUnsafe(128 * 1024);
|
|
1207
|
+
const { bytesRead } = await handle.read(buf, 0, buf.length, 0);
|
|
1208
|
+
const fields = buf.subarray(0, bytesRead).toString("utf8").split("\0");
|
|
1209
|
+
return fields.includes(marker);
|
|
1210
|
+
} catch (error) {
|
|
1211
|
+
if (error.code === "ENOENT") return false;
|
|
1212
|
+
return void 0;
|
|
1213
|
+
} finally {
|
|
1214
|
+
await handle?.close().catch(() => {
|
|
1215
|
+
});
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
const out = await execFileText("ps", ["eww", "-p", String(pid), "-o", "command="]);
|
|
1219
|
+
return out === void 0 ? void 0 : out.split(/\s+/).includes(marker);
|
|
1220
|
+
}
|
|
1221
|
+
async function inspectPosixGroup(pgid, launchId) {
|
|
1222
|
+
const out = await execFileText("ps", ["-axo", "pid=,pgid=,stat="]);
|
|
1223
|
+
if (out === void 0) return "unknown";
|
|
1224
|
+
const members = [];
|
|
1225
|
+
for (const line of out.split("\n")) {
|
|
1226
|
+
const match = line.trim().match(/^(\d+)\s+(\d+)\s+(\S+)/);
|
|
1227
|
+
if (!match || Number(match[2]) !== pgid) continue;
|
|
1228
|
+
members.push({ pid: Number(match[1]), zombie: match[3].startsWith("Z") });
|
|
1229
|
+
}
|
|
1230
|
+
const live = members.filter((member) => !member.zombie);
|
|
1231
|
+
if (live.length === 0) return "gone";
|
|
1232
|
+
const identities = await Promise.all(live.map((member) => processHasLaunchId(member.pid, launchId)));
|
|
1233
|
+
return identities.every((identity) => identity === true) ? "owned" : "unknown";
|
|
1234
|
+
}
|
|
1235
|
+
async function executeAction(req) {
|
|
1236
|
+
const started = Date.now();
|
|
1237
|
+
const { action } = req;
|
|
1238
|
+
const timeoutMs = action.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
1239
|
+
const script = path4.resolve(expandTilde(action.script));
|
|
1240
|
+
const cwd = action.cwd !== void 0 ? path4.resolve(expandTilde(action.cwd)) : path4.dirname(script);
|
|
1241
|
+
const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
|
1242
|
+
const logFile = path4.join(logsDir(), `${action.id}-${stamp}-${Math.random().toString(36).slice(2, 6)}.log`);
|
|
1243
|
+
let stdout = "";
|
|
1244
|
+
let stderrTail = "";
|
|
1245
|
+
let stdoutTruncated = false;
|
|
1246
|
+
let stderrTruncated = false;
|
|
1247
|
+
let timedOut = false;
|
|
1248
|
+
let cancelled = false;
|
|
1249
|
+
const LOG_CAP_BYTES = 50 * 1024 * 1024;
|
|
1250
|
+
let logFd;
|
|
1251
|
+
let logBytes = 0;
|
|
1252
|
+
let logDegraded = false;
|
|
1253
|
+
const logWrite = (chunk) => {
|
|
1254
|
+
if (logFd === void 0 || logDegraded) return;
|
|
1255
|
+
const buf = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk;
|
|
1256
|
+
try {
|
|
1257
|
+
let offset = 0;
|
|
1258
|
+
while (offset < buf.length) {
|
|
1259
|
+
const remaining = LOG_CAP_BYTES - logBytes;
|
|
1260
|
+
if (remaining <= 0) {
|
|
1261
|
+
logDegraded = true;
|
|
1262
|
+
const marker = Buffer.from(`
|
|
1263
|
+
[panel-actions] log budget ${LOG_CAP_BYTES} bytes exceeded; further output dropped
|
|
1264
|
+
`, "utf8");
|
|
1265
|
+
try {
|
|
1266
|
+
fs3.writeSync(logFd, marker, 0, marker.length, null);
|
|
1267
|
+
} catch {
|
|
1268
|
+
}
|
|
1269
|
+
return;
|
|
1270
|
+
}
|
|
1271
|
+
const want = Math.min(buf.length - offset, remaining);
|
|
1272
|
+
const written = fs3.writeSync(logFd, buf, offset, want, null);
|
|
1273
|
+
if (written <= 0) throw new Error("zero-progress write");
|
|
1274
|
+
offset += written;
|
|
1275
|
+
logBytes += written;
|
|
1276
|
+
}
|
|
1277
|
+
} catch {
|
|
1278
|
+
logDegraded = true;
|
|
1279
|
+
}
|
|
1280
|
+
};
|
|
1281
|
+
try {
|
|
1282
|
+
fs3.mkdirSync(logsDir(), { recursive: true });
|
|
1283
|
+
logFd = fs3.openSync(logFile, "w");
|
|
1284
|
+
} catch {
|
|
1285
|
+
logFd = void 0;
|
|
1286
|
+
logDegraded = true;
|
|
1287
|
+
}
|
|
1288
|
+
logWrite([
|
|
1289
|
+
`action: ${action.id} (${action.label})`,
|
|
1290
|
+
`script: ${script}`,
|
|
1291
|
+
`cwd: ${cwd}`,
|
|
1292
|
+
`trigger: ${req.trigger.name}${req.trigger.openId ? ` <${req.trigger.openId}>` : ""}`,
|
|
1293
|
+
`chat: ${req.chatId}`,
|
|
1294
|
+
req.worker ? `worker: ${req.worker.name}${req.worker.dir ? ` (${req.worker.dir})` : ""}` : void 0,
|
|
1295
|
+
`started: ${new Date(started).toISOString()}`,
|
|
1296
|
+
"=".repeat(60)
|
|
1297
|
+
].filter((line) => line !== void 0).join("\n") + "\n");
|
|
1298
|
+
const launchId = randomBytes(24).toString("hex");
|
|
1299
|
+
const exitCode = await new Promise((resolve6) => {
|
|
1300
|
+
if (req.signal?.aborted) {
|
|
1301
|
+
cancelled = true;
|
|
1302
|
+
resolve6(null);
|
|
1303
|
+
return;
|
|
1304
|
+
}
|
|
1305
|
+
const { command, prefix } = interpreterFor(script);
|
|
1306
|
+
let child;
|
|
1307
|
+
try {
|
|
1308
|
+
child = spawn3(command, prefix, {
|
|
1309
|
+
cwd,
|
|
1310
|
+
env: scriptEnv(req, launchId),
|
|
1311
|
+
detached: process.platform !== "win32",
|
|
1312
|
+
// own process group: timeout kills the TREE
|
|
1313
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1314
|
+
windowsHide: true
|
|
1315
|
+
});
|
|
1316
|
+
} catch (error) {
|
|
1317
|
+
logWrite(`[spawn error] ${error instanceof Error ? error.message : String(error)}
|
|
1318
|
+
`);
|
|
1319
|
+
resolve6(null);
|
|
1320
|
+
return;
|
|
1321
|
+
}
|
|
1322
|
+
if (typeof child.pid === "number") {
|
|
1323
|
+
let announced = true;
|
|
1324
|
+
try {
|
|
1325
|
+
announced = req.onChildSpawn?.(child.pid) ?? true;
|
|
1326
|
+
} catch {
|
|
1327
|
+
announced = false;
|
|
1328
|
+
}
|
|
1329
|
+
if (!announced) {
|
|
1330
|
+
cancelled = true;
|
|
1331
|
+
logWrite("[panel-actions] ownership lost before child registration; killing the child at birth\n");
|
|
1332
|
+
void stopOwnedTree(child, "SIGKILL");
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
const outDecoder = new StringDecoder3("utf8");
|
|
1336
|
+
const errDecoder = new StringDecoder3("utf8");
|
|
1337
|
+
child.stdout?.on("data", (chunk) => {
|
|
1338
|
+
logWrite(chunk);
|
|
1339
|
+
if (stdoutTruncated) return;
|
|
1340
|
+
stdout += outDecoder.write(chunk);
|
|
1341
|
+
if (stdout.length > CAPTURE_CAP_BYTES) {
|
|
1342
|
+
stdout = stdout.slice(0, CAPTURE_CAP_BYTES);
|
|
1343
|
+
stdoutTruncated = true;
|
|
1344
|
+
}
|
|
1345
|
+
});
|
|
1346
|
+
child.stderr?.on("data", (chunk) => {
|
|
1347
|
+
logWrite(chunk);
|
|
1348
|
+
const next = stderrTail + errDecoder.write(chunk);
|
|
1349
|
+
if (next.length > 8e3) stderrTruncated = true;
|
|
1350
|
+
stderrTail = next.slice(-8e3);
|
|
1351
|
+
});
|
|
1352
|
+
let settled = false;
|
|
1353
|
+
let stopping = false;
|
|
1354
|
+
let killGrace;
|
|
1355
|
+
let windowsFinalDeadline;
|
|
1356
|
+
let groupPoll;
|
|
1357
|
+
let termSent = false;
|
|
1358
|
+
let termProbeRunning = false;
|
|
1359
|
+
const settle = (code) => {
|
|
1360
|
+
if (settled) return;
|
|
1361
|
+
settled = true;
|
|
1362
|
+
clearTimeout(timeoutTimer);
|
|
1363
|
+
if (killGrace) clearTimeout(killGrace);
|
|
1364
|
+
if (windowsFinalDeadline) clearTimeout(windowsFinalDeadline);
|
|
1365
|
+
if (groupPoll) clearTimeout(groupPoll);
|
|
1366
|
+
req.signal?.removeEventListener("abort", abortRun);
|
|
1367
|
+
for (const stream of [child.stdout, child.stderr]) {
|
|
1368
|
+
stream?.removeAllListeners("data");
|
|
1369
|
+
try {
|
|
1370
|
+
stream?.destroy();
|
|
1371
|
+
} catch {
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
try {
|
|
1375
|
+
const rest = outDecoder.end();
|
|
1376
|
+
if (rest && !stdoutTruncated) {
|
|
1377
|
+
stdout += rest;
|
|
1378
|
+
if (stdout.length > CAPTURE_CAP_BYTES) {
|
|
1379
|
+
stdout = stdout.slice(0, CAPTURE_CAP_BYTES);
|
|
1380
|
+
stdoutTruncated = true;
|
|
1381
|
+
}
|
|
1382
|
+
}
|
|
1383
|
+
const errRest = errDecoder.end();
|
|
1384
|
+
if (errRest) {
|
|
1385
|
+
const next = stderrTail + errRest;
|
|
1386
|
+
if (next.length > 8e3) stderrTruncated = true;
|
|
1387
|
+
stderrTail = next.slice(-8e3);
|
|
290
1388
|
}
|
|
291
|
-
|
|
1389
|
+
} catch {
|
|
1390
|
+
}
|
|
1391
|
+
resolve6(code);
|
|
1392
|
+
};
|
|
1393
|
+
const scheduleGroupProbe = (delayMs, probe) => {
|
|
1394
|
+
if (settled) return;
|
|
1395
|
+
if (groupPoll) clearTimeout(groupPoll);
|
|
1396
|
+
groupPoll = setTimeout(() => {
|
|
1397
|
+
groupPoll = void 0;
|
|
1398
|
+
void probe();
|
|
1399
|
+
}, delayMs);
|
|
1400
|
+
groupPoll.unref?.();
|
|
1401
|
+
};
|
|
1402
|
+
let escalate = false;
|
|
1403
|
+
const awaitOwnedGroupExit = async () => {
|
|
1404
|
+
if (settled || typeof child.pid !== "number") return;
|
|
1405
|
+
const state = escalate ? await signalPosixGroup("SIGKILL") : await inspectPosixGroup(child.pid, launchId);
|
|
1406
|
+
if (settled) return;
|
|
1407
|
+
if (state === "gone") {
|
|
1408
|
+
settle(null);
|
|
1409
|
+
return;
|
|
1410
|
+
}
|
|
1411
|
+
scheduleGroupProbe(state === "unknown" ? 1e3 : 100, awaitOwnedGroupExit);
|
|
1412
|
+
};
|
|
1413
|
+
const signalPosixGroup = async (signal) => {
|
|
1414
|
+
if (typeof child.pid !== "number") return "gone";
|
|
1415
|
+
const state = await inspectPosixGroup(child.pid, launchId);
|
|
1416
|
+
if (settled || state !== "owned") return settled ? "gone" : state;
|
|
1417
|
+
try {
|
|
1418
|
+
process.kill(-child.pid, signal);
|
|
1419
|
+
} catch (error) {
|
|
1420
|
+
if (error.code === "ESRCH") return "gone";
|
|
1421
|
+
return "unknown";
|
|
1422
|
+
}
|
|
1423
|
+
return "owned";
|
|
1424
|
+
};
|
|
1425
|
+
const attemptPosixTerm = async () => {
|
|
1426
|
+
if (settled || termSent || termProbeRunning) return;
|
|
1427
|
+
termProbeRunning = true;
|
|
1428
|
+
const state = await signalPosixGroup("SIGTERM");
|
|
1429
|
+
termProbeRunning = false;
|
|
1430
|
+
if (settled) return;
|
|
1431
|
+
if (state === "gone") {
|
|
1432
|
+
settle(null);
|
|
1433
|
+
return;
|
|
1434
|
+
}
|
|
1435
|
+
if (state === "unknown") {
|
|
1436
|
+
scheduleGroupProbe(1e3, attemptPosixTerm);
|
|
1437
|
+
return;
|
|
1438
|
+
}
|
|
1439
|
+
termSent = true;
|
|
1440
|
+
killGrace = setTimeout(() => {
|
|
1441
|
+
if (settled) return;
|
|
1442
|
+
logWrite("[panel-actions] verifying ownership before SIGKILL\n");
|
|
1443
|
+
escalate = true;
|
|
1444
|
+
void awaitOwnedGroupExit();
|
|
1445
|
+
}, KILL_GRACE_MS);
|
|
1446
|
+
killGrace.unref?.();
|
|
1447
|
+
};
|
|
1448
|
+
const beginStop = (reason) => {
|
|
1449
|
+
if (stopping || settled) return;
|
|
1450
|
+
stopping = true;
|
|
1451
|
+
if (reason === "timeout") timedOut = true;
|
|
1452
|
+
else cancelled = true;
|
|
1453
|
+
logWrite(`[panel-actions] ${reason === "timeout" ? `timeout ${timeoutMs}ms exceeded` : "runtime retired"}; verifying ownership before SIGTERM
|
|
1454
|
+
`);
|
|
1455
|
+
if (process.platform === "win32") {
|
|
1456
|
+
void stopOwnedTree(child, "SIGTERM").then(() => {
|
|
1457
|
+
if (settled) return;
|
|
1458
|
+
killGrace = setTimeout(() => {
|
|
1459
|
+
if (settled) return;
|
|
1460
|
+
void stopOwnedTree(child, "SIGKILL").then(() => {
|
|
1461
|
+
windowsFinalDeadline = setTimeout(() => settle(null), 2e3);
|
|
1462
|
+
windowsFinalDeadline.unref?.();
|
|
1463
|
+
});
|
|
1464
|
+
}, KILL_GRACE_MS);
|
|
1465
|
+
killGrace.unref?.();
|
|
1466
|
+
});
|
|
1467
|
+
return;
|
|
1468
|
+
}
|
|
1469
|
+
void attemptPosixTerm();
|
|
1470
|
+
};
|
|
1471
|
+
const abortRun = () => beginStop("retirement");
|
|
1472
|
+
child.on("error", (error) => {
|
|
1473
|
+
logWrite(`[spawn error] ${error.message}
|
|
1474
|
+
`);
|
|
1475
|
+
settle(null);
|
|
1476
|
+
});
|
|
1477
|
+
child.on("close", (code) => {
|
|
1478
|
+
if (!stopping && !cancelled) settle(code);
|
|
1479
|
+
else if (cancelled && !stopping && process.platform !== "win32") void awaitOwnedGroupExit();
|
|
1480
|
+
else if (process.platform === "win32") settle(code);
|
|
1481
|
+
else {
|
|
1482
|
+
if (termSent) void awaitOwnedGroupExit();
|
|
1483
|
+
else void attemptPosixTerm();
|
|
292
1484
|
}
|
|
1485
|
+
});
|
|
1486
|
+
const timeoutTimer = setTimeout(() => beginStop("timeout"), timeoutMs);
|
|
1487
|
+
timeoutTimer.unref?.();
|
|
1488
|
+
if (req.signal?.aborted) abortRun();
|
|
1489
|
+
else req.signal?.addEventListener("abort", abortRun, { once: true });
|
|
1490
|
+
if (cancelled && !req.signal?.aborted) {
|
|
1491
|
+
const cancelDeadline = setTimeout(() => {
|
|
1492
|
+
if (process.platform === "win32") settle(null);
|
|
1493
|
+
else void awaitOwnedGroupExit();
|
|
1494
|
+
}, 3e3);
|
|
1495
|
+
cancelDeadline.unref?.();
|
|
293
1496
|
}
|
|
294
|
-
}
|
|
1497
|
+
});
|
|
1498
|
+
const durationMs = Date.now() - started;
|
|
1499
|
+
logWrite(`
|
|
1500
|
+
${"=".repeat(60)}
|
|
1501
|
+
[exit] code=${exitCode === null ? "(none)" : exitCode}${timedOut ? " TIMED OUT" : ""} durationMs=${durationMs}
|
|
1502
|
+
`);
|
|
1503
|
+
if (logFd !== void 0) {
|
|
295
1504
|
try {
|
|
296
|
-
|
|
1505
|
+
fs3.closeSync(logFd);
|
|
297
1506
|
} catch {
|
|
298
1507
|
}
|
|
1508
|
+
logFd = void 0;
|
|
299
1509
|
}
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
} catch {
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
function threadOwner(input) {
|
|
317
|
-
const threadKey = encodeThreadKey(input);
|
|
318
|
-
let read;
|
|
319
|
-
try {
|
|
320
|
-
read = readOwner(threadKey);
|
|
321
|
-
} catch {
|
|
322
|
-
return { unavailable: true };
|
|
323
|
-
}
|
|
324
|
-
if (read.corrupt) return { corrupt: true };
|
|
325
|
-
if (!read.owner) return {};
|
|
326
|
-
if (read.owner.pid > 0 && !pidAlive(read.owner.pid)) {
|
|
327
|
-
return {};
|
|
328
|
-
}
|
|
329
|
-
return { sessionId: read.owner.sessionId };
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
// builtin/extensions/im-forward/panel.ts
|
|
333
|
-
import * as fs2 from "node:fs";
|
|
334
|
-
import * as os2 from "node:os";
|
|
335
|
-
import * as path3 from "node:path";
|
|
336
|
-
import { fileURLToPath } from "node:url";
|
|
337
|
-
|
|
338
|
-
// builtin/extensions/im-forward/discovery.ts
|
|
339
|
-
import * as os from "node:os";
|
|
340
|
-
import * as path2 from "node:path";
|
|
341
|
-
function ipcDiscoveryRoot() {
|
|
342
|
-
const home = os.homedir() || process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
343
|
-
const override = process.env.PIE_IPC_CONFIG_DIR;
|
|
344
|
-
const agentDir = process.env.PIE_CODING_AGENT_DIR?.trim();
|
|
345
|
-
const raw = override !== void 0 ? override : agentDir || path2.join(home, ".pie");
|
|
346
|
-
const configDir = process.platform === "win32" ? raw : path2.resolve(raw === "~" ? home : raw.startsWith("~/") ? path2.join(home, raw.slice(2)) : raw);
|
|
347
|
-
return path2.join(configDir, "run", "ipc");
|
|
1510
|
+
return {
|
|
1511
|
+
ok: !timedOut && !cancelled && exitCode === 0,
|
|
1512
|
+
timedOut,
|
|
1513
|
+
cancelled,
|
|
1514
|
+
exitCode,
|
|
1515
|
+
stdout,
|
|
1516
|
+
stderrTail,
|
|
1517
|
+
stdoutTruncated,
|
|
1518
|
+
stderrTruncated,
|
|
1519
|
+
logDegraded,
|
|
1520
|
+
durationMs,
|
|
1521
|
+
logFile
|
|
1522
|
+
};
|
|
348
1523
|
}
|
|
349
1524
|
|
|
350
1525
|
// builtin/extensions/im-forward/panel.ts
|
|
@@ -362,8 +1537,8 @@ function parsePanelCommand(text) {
|
|
|
362
1537
|
cmd = next?.[1] ?? "";
|
|
363
1538
|
rest = next?.[2] ?? "";
|
|
364
1539
|
}
|
|
365
|
-
if (cmd !== "panel" && cmd !== "panel.refresh" && cmd !== "panel.summon" && cmd !== "panel.models" && cmd !== "panel.upgrade" && cmd !== "panel.upgrade.confirm" && cmd !== "panel.help" && cmd !== "\u9762\u677F") {
|
|
366
|
-
if (!/^panel\.model\.[A-Za-z0-9-]+\..+$/.test(cmd)) return void 0;
|
|
1540
|
+
if (cmd !== "panel" && cmd !== "panel.refresh" && cmd !== "panel.summon" && cmd !== "panel.models" && cmd !== "panel.context" && cmd !== "panel.compact" && cmd !== "panel.upgrade" && cmd !== "panel.upgrade.confirm" && cmd !== "panel.help" && cmd !== "panel.actions" && cmd !== "\u9762\u677F") {
|
|
1541
|
+
if (!/^panel\.model\.[A-Za-z0-9-]+\..+$/.test(cmd) && !/^panel\.(context|compact)\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.peek(?:\.refresh)?\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.worker\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.action\.[a-z0-9][a-z0-9-]{0,31}$/.test(cmd)) return void 0;
|
|
367
1542
|
}
|
|
368
1543
|
const leadingFlag = /^--restricted(?:\s+|$)/.exec(rest);
|
|
369
1544
|
const restricted = leadingFlag !== null;
|
|
@@ -377,14 +1552,27 @@ function parsePanelCommand(text) {
|
|
|
377
1552
|
}
|
|
378
1553
|
return { cmd, restricted, payload };
|
|
379
1554
|
}
|
|
1555
|
+
function findPeerByName(name) {
|
|
1556
|
+
const needle = name.trim().toLowerCase();
|
|
1557
|
+
if (!needle) return void 0;
|
|
1558
|
+
const matches = scanPeers().filter((p) => !p.isManager && p.name.toLowerCase() === needle);
|
|
1559
|
+
if (matches.length > 1) return "ambiguous";
|
|
1560
|
+
return matches[0];
|
|
1561
|
+
}
|
|
1562
|
+
function findPeerByInstanceId(instanceId) {
|
|
1563
|
+
if (!instanceId) return void 0;
|
|
1564
|
+
const peer = scanPeers().find((p) => p.instanceId === instanceId);
|
|
1565
|
+
if (!peer || peer.isManager) return void 0;
|
|
1566
|
+
return peer;
|
|
1567
|
+
}
|
|
380
1568
|
function scanPeers() {
|
|
381
1569
|
const out = [];
|
|
382
1570
|
try {
|
|
383
1571
|
const dir = ipcDiscoveryRoot();
|
|
384
|
-
for (const file of
|
|
1572
|
+
for (const file of fs4.readdirSync(dir).slice(0, 64)) {
|
|
385
1573
|
if (!file.endsWith(".json")) continue;
|
|
386
1574
|
try {
|
|
387
|
-
const parsed = JSON.parse(
|
|
1575
|
+
const parsed = JSON.parse(fs4.readFileSync(path5.join(dir, file), "utf8"));
|
|
388
1576
|
if (typeof parsed.sessionId !== "string" || typeof parsed.pid !== "number") continue;
|
|
389
1577
|
if (typeof parsed.instanceId !== "string" || !parsed.instanceId) continue;
|
|
390
1578
|
try {
|
|
@@ -398,8 +1586,12 @@ function scanPeers() {
|
|
|
398
1586
|
sessionId: parsed.sessionId,
|
|
399
1587
|
state: typeof parsed.state === "string" ? parsed.state : "?",
|
|
400
1588
|
unattended: parsed.unattended === true,
|
|
1589
|
+
sessionControls: parsed.sessionControls === true,
|
|
1590
|
+
workerPeek: parsed.workerPeek === true,
|
|
401
1591
|
sessionTitle: typeof parsed.displaySessionName === "string" && parsed.displaySessionName.trim() ? parsed.displaySessionName.trim() : void 0,
|
|
402
1592
|
project: typeof parsed.cwd === "string" && parsed.cwd ? parsed.cwd.split("/").filter(Boolean).at(-1) : void 0,
|
|
1593
|
+
cwd: typeof parsed.cwd === "string" && parsed.cwd ? parsed.cwd : void 0,
|
|
1594
|
+
isManager: parsed.isManager === true,
|
|
403
1595
|
currentTool: typeof parsed.currentTool === "string" && parsed.currentTool ? parsed.currentTool : void 0,
|
|
404
1596
|
model: typeof parsed.model === "string" && parsed.model ? parsed.model : void 0,
|
|
405
1597
|
version: typeof parsed.version === "string" && parsed.version ? parsed.version : void 0
|
|
@@ -429,6 +1621,22 @@ ${rows.join("\n")}` : "_No live pie sessions_",
|
|
|
429
1621
|
upgradeLine,
|
|
430
1622
|
`${peers.length} session(s) \xB7 ${(/* @__PURE__ */ new Date()).toLocaleTimeString("en-GB", { hour12: false })}`
|
|
431
1623
|
].filter((line) => line !== void 0).join("\n");
|
|
1624
|
+
const fixed = [
|
|
1625
|
+
{ id: "panel.refresh", label: "\u{1F504} Refresh" },
|
|
1626
|
+
{ id: "panel.summon", label: "\u{1F4CB} Resummon" },
|
|
1627
|
+
{ id: "panel.models", label: "\u{1F39A} Model" },
|
|
1628
|
+
{ id: "panel.context", label: "\u{1F4CA} Context" },
|
|
1629
|
+
{ id: "panel.compact", label: "\u{1F9F9} Compact" },
|
|
1630
|
+
{ id: "panel.upgrade", label: "\u2B06\uFE0F Upgrade" },
|
|
1631
|
+
{ id: "panel.help", label: "\u2753 Help" }
|
|
1632
|
+
];
|
|
1633
|
+
const CARD_ACTION_BUDGET = 18;
|
|
1634
|
+
const workerEntries = peers.filter((p) => !p.isManager).slice(0, 6).map((p) => ({ id: `panel.worker.${p.instanceId}`, label: `\u{1F4C2} ${(p.sessionTitle ?? p.name).slice(0, 12)}` }));
|
|
1635
|
+
const custom = managerActions();
|
|
1636
|
+
const slots = Math.max(0, CARD_ACTION_BUDGET - fixed.length - workerEntries.length);
|
|
1637
|
+
const inline = custom.length <= slots ? custom : custom.slice(0, Math.max(0, slots - 1));
|
|
1638
|
+
const customButtons = inline.map((a) => ({ id: `panel.action.${a.id}`, label: a.label.slice(0, 20) }));
|
|
1639
|
+
if (custom.length > inline.length) customButtons.push({ id: "panel.actions", label: `\u26A1 \u5168\u90E8\u52A8\u4F5C (${custom.length})` });
|
|
432
1640
|
return {
|
|
433
1641
|
title: "Pie Panel",
|
|
434
1642
|
subtitle: `${os2.hostname()} \xB7 ${peers.length} session(s) \xB7 pie ${pieVersion()}`,
|
|
@@ -436,22 +1644,16 @@ ${rows.join("\n")}` : "_No live pie sessions_",
|
|
|
436
1644
|
body,
|
|
437
1645
|
// r1-P2: only REGISTERED commands get buttons — unmapped ids would fall
|
|
438
1646
|
// through to an LLM turn (a button press must never spend a model turn).
|
|
439
|
-
actions: [
|
|
440
|
-
{ id: "panel.refresh", label: "\u{1F504} Refresh" },
|
|
441
|
-
{ id: "panel.summon", label: "\u{1F4CB} Resummon" },
|
|
442
|
-
{ id: "panel.models", label: "\u{1F39A} Model" },
|
|
443
|
-
{ id: "panel.upgrade", label: "\u2B06\uFE0F Upgrade" },
|
|
444
|
-
{ id: "panel.help", label: "\u2753 Help" }
|
|
445
|
-
]
|
|
1647
|
+
actions: [...fixed, ...workerEntries, ...customButtons]
|
|
446
1648
|
};
|
|
447
1649
|
}
|
|
448
1650
|
function pieVersion() {
|
|
449
1651
|
try {
|
|
450
|
-
const here =
|
|
1652
|
+
const here = path5.dirname(fileURLToPath(import.meta.url));
|
|
451
1653
|
for (const up of [3, 4, 5, 6]) {
|
|
452
|
-
const pkgPath =
|
|
453
|
-
if (!
|
|
454
|
-
const parsed = JSON.parse(
|
|
1654
|
+
const pkgPath = path5.resolve(here, ...Array(up).fill(".."), "package.json");
|
|
1655
|
+
if (!fs4.existsSync(pkgPath)) continue;
|
|
1656
|
+
const parsed = JSON.parse(fs4.readFileSync(pkgPath, "utf8"));
|
|
455
1657
|
if (parsed.name === "@cydm/pie" && typeof parsed.version === "string") return parsed.version;
|
|
456
1658
|
}
|
|
457
1659
|
} catch {
|
|
@@ -460,8 +1662,8 @@ function pieVersion() {
|
|
|
460
1662
|
}
|
|
461
1663
|
function readUpgradeSnapshot() {
|
|
462
1664
|
try {
|
|
463
|
-
const configRoot =
|
|
464
|
-
return JSON.parse(
|
|
1665
|
+
const configRoot = path5.dirname(path5.dirname(ipcDiscoveryRoot()));
|
|
1666
|
+
return JSON.parse(fs4.readFileSync(path5.join(configRoot, "manager", "upgrade.json"), "utf8"));
|
|
465
1667
|
} catch {
|
|
466
1668
|
return void 0;
|
|
467
1669
|
}
|
|
@@ -480,8 +1682,8 @@ function upgradeSummaryLine() {
|
|
|
480
1682
|
function candidateModels() {
|
|
481
1683
|
const out = /* @__PURE__ */ new Set();
|
|
482
1684
|
try {
|
|
483
|
-
const configRoot =
|
|
484
|
-
const config = JSON.parse(
|
|
1685
|
+
const configRoot = path5.dirname(path5.dirname(ipcDiscoveryRoot()));
|
|
1686
|
+
const config = JSON.parse(fs4.readFileSync(path5.join(configRoot, "models.json"), "utf8"));
|
|
485
1687
|
const d = config.defaults ?? {};
|
|
486
1688
|
if (d.provider && d.modelId) out.add(`${d.provider}/${d.modelId}`);
|
|
487
1689
|
for (const cls of Object.values(d.modelClasses ?? {})) {
|
|
@@ -515,6 +1717,124 @@ ${rows.join("\n")}` : "_No live pie sessions_",
|
|
|
515
1717
|
actions: actions.length > 0 ? actions : [{ id: "panel.summon", label: "\u21A9\uFE0F Back to panel" }]
|
|
516
1718
|
}, patchOrigin: false };
|
|
517
1719
|
}
|
|
1720
|
+
if (input.cmd === "panel.context") {
|
|
1721
|
+
const peers = scanPeers().filter((p) => p.sessionControls);
|
|
1722
|
+
const rows = peers.map((p) => `| ${p.sessionTitle ?? p.name} | ${p.model ?? "\u2014"} | ${p.state} |`);
|
|
1723
|
+
const actions = peers.map((p) => ({ id: `panel.context.${p.instanceId}`, label: `\u{1F4CA} ${p.name.slice(0, 12)}` })).slice(0, 18);
|
|
1724
|
+
return { spec: {
|
|
1725
|
+
title: "Context Report",
|
|
1726
|
+
subtitle: `${peers.length} session(s) \xB7 pick a session to read its context estimate`,
|
|
1727
|
+
color: "violet",
|
|
1728
|
+
body: [
|
|
1729
|
+
peers.length > 0 ? `| Session | Model | State |
|
|
1730
|
+
|---|---|---|
|
|
1731
|
+
${rows.join("\n")}` : "_No live sessions advertise this control_",
|
|
1732
|
+
``,
|
|
1733
|
+
"Each button asks the target host for its context ESTIMATE (same figures the TUI /debugs/context report shows). Only sessions advertising this control are listed."
|
|
1734
|
+
].join("\n"),
|
|
1735
|
+
actions: actions.length > 0 ? actions : [{ id: "panel.summon", label: "\u21A9\uFE0F Back to panel" }]
|
|
1736
|
+
}, patchOrigin: false };
|
|
1737
|
+
}
|
|
1738
|
+
if (input.cmd === "panel.compact") {
|
|
1739
|
+
const peers = scanPeers().filter((p) => p.sessionControls);
|
|
1740
|
+
const rows = peers.map((p) => `| ${p.sessionTitle ?? p.name} | ${p.model ?? "\u2014"} | ${p.state} |`);
|
|
1741
|
+
const actions = peers.map((p) => ({ id: `panel.compact.${p.instanceId}`, label: `\u{1F9F9} ${p.name.slice(0, 12)}`, requireAllowUsers: true })).slice(0, 18);
|
|
1742
|
+
return { spec: {
|
|
1743
|
+
title: "Compact Context",
|
|
1744
|
+
subtitle: `${peers.length} session(s) \xB7 manual compaction replaces history with a checkpoint summary`,
|
|
1745
|
+
color: "violet",
|
|
1746
|
+
body: [
|
|
1747
|
+
peers.length > 0 ? `| Session | Model | State |
|
|
1748
|
+
|---|---|---|
|
|
1749
|
+
${rows.join("\n")}` : "_No live sessions advertise this control_",
|
|
1750
|
+
``,
|
|
1751
|
+
"Compaction summarizes the session's history and keeps a retained tail. It runs on the target host through the same pipeline as /sessions/compact. **Refused while the session is working or has queued input** \u2014 retry when idle. The confirm requires allowUsers membership."
|
|
1752
|
+
].join("\n"),
|
|
1753
|
+
actions: actions.length > 0 ? actions : [{ id: "panel.summon", label: "\u21A9\uFE0F Back to panel" }]
|
|
1754
|
+
}, patchOrigin: false };
|
|
1755
|
+
}
|
|
1756
|
+
if (input.cmd === "panel.actions") {
|
|
1757
|
+
const all = managerActions();
|
|
1758
|
+
const PAGE_SIZE = 15;
|
|
1759
|
+
const totalPages = Math.max(1, Math.ceil(all.length / PAGE_SIZE));
|
|
1760
|
+
const rawPage = input.payload?.page;
|
|
1761
|
+
const requested = typeof rawPage === "number" && Number.isFinite(rawPage) ? Math.floor(rawPage) : 1;
|
|
1762
|
+
const page = Math.min(Math.max(1, requested), totalPages);
|
|
1763
|
+
const slice = all.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);
|
|
1764
|
+
const rows = slice.map((a) => `| ${a.label} | ${a.runs} | ${a.lastRunBy ?? "\u2014"} | ${a.creator?.name ?? "\u2014"} |`);
|
|
1765
|
+
const nav = [];
|
|
1766
|
+
if (page > 1) nav.push({ id: "panel.actions", label: `\u2190 \u7B2C ${page - 1} \u9875`, payload: { page: page - 1 } });
|
|
1767
|
+
if (page < totalPages) nav.push({ id: "panel.actions", label: `\u7B2C ${page + 1} \u9875 \u2192`, payload: { page: page + 1 } });
|
|
1768
|
+
return { spec: {
|
|
1769
|
+
title: "\u5168\u90E8\u52A8\u4F5C",
|
|
1770
|
+
subtitle: `${all.length} registered \xB7 page ${page}/${totalPages} \xB7 click to run (zero LLM \u2014 the script executes directly)`,
|
|
1771
|
+
color: "violet",
|
|
1772
|
+
body: [
|
|
1773
|
+
all.length > 0 ? `| Action | Runs | Last by | Created by |
|
|
1774
|
+
|---|---|---|---|
|
|
1775
|
+
${rows.join("\n")}` : '_No custom actions yet \u2014 ask the manager to build one ("\u5E2E\u6211\u505A\u4E2A\u6309\u94AE,\u80FD\u2026")_',
|
|
1776
|
+
``,
|
|
1777
|
+
"Every run is bylined with its triggerer and appended to the audit log."
|
|
1778
|
+
].join("\n"),
|
|
1779
|
+
actions: [
|
|
1780
|
+
...slice.map((a) => ({ id: `panel.action.${a.id}`, label: a.label.slice(0, 20) })),
|
|
1781
|
+
...nav,
|
|
1782
|
+
{ id: "panel.summon", label: "\u21A9\uFE0F Back to panel" }
|
|
1783
|
+
].slice(0, 18)
|
|
1784
|
+
}, patchOrigin: false };
|
|
1785
|
+
}
|
|
1786
|
+
const workerView = /^panel\.worker\.([A-Za-z0-9-]+)$/.exec(input.cmd);
|
|
1787
|
+
if (workerView) {
|
|
1788
|
+
const peerId = workerView[1];
|
|
1789
|
+
const peer = scanPeers().find((p) => p.instanceId === peerId);
|
|
1790
|
+
if (!peer) {
|
|
1791
|
+
return { spec: {
|
|
1792
|
+
title: "Worker \u4E0D\u5728\u7EBF",
|
|
1793
|
+
body: "\u8BE5 session \u5DF2\u9000\u51FA\uFF08worker \u6709 TTL \u56DE\u6536\uFF09\u3002\u5B83\u7684\u901A\u7528\u6309\u94AE\u5728\u5176\u4ED6\u5728\u7EBF worker \u7684\u5361\u4E0A\u4ECD\u53EF\u7528\u3002",
|
|
1794
|
+
actions: [{ id: "panel.summon", label: "\u21A9\uFE0F Back to panel" }]
|
|
1795
|
+
}, patchOrigin: false };
|
|
1796
|
+
}
|
|
1797
|
+
const wActions = workerActions(peer.name);
|
|
1798
|
+
const workerCtx = { worker: { name: peer.name, ref: peer.instanceId } };
|
|
1799
|
+
const peekCtx = { peek: { ref: peer.instanceId, session: peer.sessionId } };
|
|
1800
|
+
const fixedActions = [
|
|
1801
|
+
...peer.workerPeek ? [{ id: `panel.peek.${peer.instanceId}`, label: "\u{1F440} Peek", payload: peekCtx }] : [],
|
|
1802
|
+
...peer.sessionControls ? [
|
|
1803
|
+
{ id: `panel.context.${peer.instanceId}`, label: "\u{1F4CA} Context" },
|
|
1804
|
+
{ id: `panel.compact.${peer.instanceId}`, label: "\u{1F9F9} Compact", requireAllowUsers: true }
|
|
1805
|
+
] : []
|
|
1806
|
+
];
|
|
1807
|
+
const title = peer.sessionTitle ?? peer.name;
|
|
1808
|
+
const state = peer.state === "working" && peer.currentTool ? `working\xB7${peer.currentTool}` : peer.state;
|
|
1809
|
+
return { spec: {
|
|
1810
|
+
title: `\u{1F527} ${title}`,
|
|
1811
|
+
subtitle: `${peer.project ?? "\u2014"} \xB7 ${peer.model ?? "\u2014"} \xB7 ${state}`,
|
|
1812
|
+
color: "green",
|
|
1813
|
+
body: [
|
|
1814
|
+
`| Field | Value |
|
|
1815
|
+
|---|---|
|
|
1816
|
+
| name | ${peer.name} |
|
|
1817
|
+
| state | ${state} |
|
|
1818
|
+
| model | ${peer.model ?? "\u2014"} |
|
|
1819
|
+
| version | ${peer.version ?? "\u2014"} |${peer.cwd ? `
|
|
1820
|
+
| cwd | ${peer.cwd} |` : ""}`,
|
|
1821
|
+
``,
|
|
1822
|
+
wActions.length > 0 ? `**\u26A1 \u52A8\u4F5C**\uFF08\u70B9\u7684\u54EA\u4E2A worker \u7684\u5361\u5C31\u5E26\u54EA\u4E2A worker \u7684\u4E0A\u4E0B\u6587\u8DD1\uFF09
|
|
1823
|
+
| Action | Runs | Last by |
|
|
1824
|
+
|---|---|---|
|
|
1825
|
+
${wActions.map((a) => `| ${a.label} | ${a.runs} | ${a.lastRunBy ?? "\u2014"} |`).join("\n")}${wActions.length > 15 ? `
|
|
1826
|
+
|
|
1827
|
+
_\u6309\u94AE\u53D6\u524D 15 \u4E2A\u6700\u5E38\u7528\u7684\uFF1B\u5176\u4F59\u53EF\u590D\u5236\u547D\u4EE4\u89E6\u53D1\uFF08\u5E26\u7CBE\u786E worker \u5730\u5740\uFF09\uFF1A_
|
|
1828
|
+
${wActions.slice(15).map((a) => `\`/card panel.action.${a.id} ${JSON.stringify({ worker: { ref: peer.instanceId } })}\``).join("\n")}` : ""}` : "_No worker actions yet \u2014 generic actions (scope=worker) appear on every worker card_"
|
|
1829
|
+
].join("\n"),
|
|
1830
|
+
// Variable actions yield to fixed controls; Back is always slot 18.
|
|
1831
|
+
actions: [
|
|
1832
|
+
...fixedActions,
|
|
1833
|
+
...wActions.slice(0, Math.max(0, 17 - fixedActions.length)).map((a) => ({ id: `panel.action.${a.id}`, label: a.label.slice(0, 20), payload: workerCtx })),
|
|
1834
|
+
{ id: "panel.summon", label: "\u21A9\uFE0F Back" }
|
|
1835
|
+
]
|
|
1836
|
+
}, patchOrigin: false };
|
|
1837
|
+
}
|
|
518
1838
|
if (input.cmd === "panel.upgrade") {
|
|
519
1839
|
const snap = readUpgradeSnapshot();
|
|
520
1840
|
const current = pieVersion();
|
|
@@ -543,7 +1863,7 @@ ${rows.join("\n")}` : "_No live pie sessions_",
|
|
|
543
1863
|
if (input.cmd === "panel.help") {
|
|
544
1864
|
return { spec: {
|
|
545
1865
|
title: "Panel Commands",
|
|
546
|
-
body: "`/panel` summons the status panel. Card buttons: \u{1F504} Refresh (in-place update), \u{1F4CB} Resummon, \u{1F39A} Model, \u2B06\uFE0F Upgrade (npm install + manager restart), \u2753 Help. Any group member may tap; `--restricted` actions require the allowUsers whitelist.",
|
|
1866
|
+
body: "`/panel` summons the status panel. Card buttons: \u{1F504} Refresh (in-place update), \u{1F4CB} Resummon, \u{1F39A} Model, \u{1F4CA} Context (per-session context estimate), \u{1F9F9} Compact (per-session manual compaction), \u2B06\uFE0F Upgrade (npm install + manager restart), \u2753 Help. Any group member may tap; `--restricted` actions (compact, upgrade confirm) require the allowUsers whitelist.",
|
|
547
1867
|
actions: [{ id: "panel.summon", label: "Back to panel" }]
|
|
548
1868
|
}, patchOrigin: false };
|
|
549
1869
|
}
|
|
@@ -552,13 +1872,13 @@ ${rows.join("\n")}` : "_No live pie sessions_",
|
|
|
552
1872
|
|
|
553
1873
|
// builtin/extensions/im-forward/event-dispatch.ts
|
|
554
1874
|
import * as net from "node:net";
|
|
555
|
-
import * as
|
|
556
|
-
import * as
|
|
1875
|
+
import * as fs5 from "node:fs";
|
|
1876
|
+
import * as path6 from "node:path";
|
|
557
1877
|
import { createHmac, randomUUID as randomUUID2 } from "node:crypto";
|
|
558
1878
|
function discoveryDir() {
|
|
559
|
-
return
|
|
1879
|
+
return path6.join(addressBookRoot(), "run", "ipc");
|
|
560
1880
|
}
|
|
561
|
-
function
|
|
1881
|
+
function pidAlive3(pid) {
|
|
562
1882
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
563
1883
|
try {
|
|
564
1884
|
process.kill(pid, 0);
|
|
@@ -570,7 +1890,7 @@ function pidAlive2(pid) {
|
|
|
570
1890
|
function findOwnerInstance(sessionId) {
|
|
571
1891
|
let entries;
|
|
572
1892
|
try {
|
|
573
|
-
entries =
|
|
1893
|
+
entries = fs5.readdirSync(discoveryDir());
|
|
574
1894
|
} catch {
|
|
575
1895
|
return void 0;
|
|
576
1896
|
}
|
|
@@ -578,8 +1898,8 @@ function findOwnerInstance(sessionId) {
|
|
|
578
1898
|
for (const name of entries.slice(0, 256)) {
|
|
579
1899
|
if (!name.endsWith(".json")) continue;
|
|
580
1900
|
try {
|
|
581
|
-
const parsed = JSON.parse(
|
|
582
|
-
if (parsed.instanceId === name.slice(0, -".json".length) && parsed.sessionId === sessionId && parsed.port && typeof parsed.secret === "string" && parsed.protocol === IPC_PROTOCOL_VERSION &&
|
|
1901
|
+
const parsed = JSON.parse(fs5.readFileSync(path6.join(discoveryDir(), name), "utf8"));
|
|
1902
|
+
if (parsed.instanceId === name.slice(0, -".json".length) && parsed.sessionId === sessionId && parsed.port && typeof parsed.secret === "string" && parsed.protocol === IPC_PROTOCOL_VERSION && pidAlive3(parsed.pid ?? 0)) {
|
|
583
1903
|
candidates.push({ file: parsed, startedAt: typeof parsed.startedAt === "number" ? parsed.startedAt : 0 });
|
|
584
1904
|
}
|
|
585
1905
|
} catch {
|
|
@@ -592,7 +1912,7 @@ function findOwnerInstance(sessionId) {
|
|
|
592
1912
|
function findNamedOwnerInstance(name, binding) {
|
|
593
1913
|
let entries;
|
|
594
1914
|
try {
|
|
595
|
-
entries =
|
|
1915
|
+
entries = fs5.readdirSync(discoveryDir()).filter((entry) => entry.endsWith(".json"));
|
|
596
1916
|
} catch {
|
|
597
1917
|
return void 0;
|
|
598
1918
|
}
|
|
@@ -600,8 +1920,8 @@ function findNamedOwnerInstance(name, binding) {
|
|
|
600
1920
|
const matches = [];
|
|
601
1921
|
for (const entry of entries) {
|
|
602
1922
|
try {
|
|
603
|
-
const peer = JSON.parse(
|
|
604
|
-
if (peer.sessionName?.trim() !== name || !
|
|
1923
|
+
const peer = JSON.parse(fs5.readFileSync(path6.join(discoveryDir(), entry), "utf8"));
|
|
1924
|
+
if (peer.sessionName?.trim() !== name || !pidAlive3(peer.pid)) continue;
|
|
605
1925
|
matches.push(peer);
|
|
606
1926
|
} catch {
|
|
607
1927
|
return void 0;
|
|
@@ -622,7 +1942,7 @@ var SYNTHETIC_SENDER = (() => {
|
|
|
622
1942
|
return `pie-${hex.slice(0, 12)}`;
|
|
623
1943
|
})();
|
|
624
1944
|
function deliverOnce(port, secret, text, targetSessionId, targetInstanceId) {
|
|
625
|
-
return new Promise((
|
|
1945
|
+
return new Promise((resolve6) => {
|
|
626
1946
|
const id = randomUUID2();
|
|
627
1947
|
const envelope = {
|
|
628
1948
|
v: IPC_PROTOCOL_VERSION,
|
|
@@ -650,7 +1970,7 @@ function deliverOnce(port, secret, text, targetSessionId, targetInstanceId) {
|
|
|
650
1970
|
settled = true;
|
|
651
1971
|
clearTimeout(timer);
|
|
652
1972
|
socket.destroy();
|
|
653
|
-
|
|
1973
|
+
resolve6(ok);
|
|
654
1974
|
};
|
|
655
1975
|
const timer = setTimeout(() => finish(false), 5e3);
|
|
656
1976
|
socket.once("error", () => finish(false));
|
|
@@ -698,16 +2018,16 @@ async function dispatchEventToSession(sessionId, eventText) {
|
|
|
698
2018
|
}
|
|
699
2019
|
|
|
700
2020
|
// builtin/extensions/im-forward/session-roots.ts
|
|
701
|
-
import * as
|
|
702
|
-
import * as
|
|
2021
|
+
import * as fs6 from "node:fs";
|
|
2022
|
+
import * as path7 from "node:path";
|
|
703
2023
|
function rootsDir() {
|
|
704
|
-
return
|
|
2024
|
+
return path7.join(addressBookRoot(), "im-forward", "roots");
|
|
705
2025
|
}
|
|
706
2026
|
function rootPath(provider, messageId) {
|
|
707
2027
|
const safe = `${provider}:${messageId}`.replace(/[^a-zA-Z0-9._:-]/g, "_");
|
|
708
|
-
return
|
|
2028
|
+
return path7.join(rootsDir(), `${safe}.json`);
|
|
709
2029
|
}
|
|
710
|
-
function
|
|
2030
|
+
function pidAlive4(pid) {
|
|
711
2031
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
712
2032
|
try {
|
|
713
2033
|
process.kill(pid, 0);
|
|
@@ -721,17 +2041,17 @@ function claimSessionRoot(provider, messageId, sessionId) {
|
|
|
721
2041
|
try {
|
|
722
2042
|
const record = { sessionId, pid: process.pid, claimedAt: Date.now() };
|
|
723
2043
|
const target = rootPath(provider, messageId);
|
|
724
|
-
|
|
725
|
-
|
|
2044
|
+
fs6.mkdirSync(rootsDir(), { recursive: true, mode: 448 });
|
|
2045
|
+
fs6.writeFileSync(target, `${JSON.stringify(record)}
|
|
726
2046
|
`);
|
|
727
2047
|
} catch {
|
|
728
2048
|
}
|
|
729
2049
|
}
|
|
730
2050
|
function sessionRootOwner(provider, messageId) {
|
|
731
2051
|
try {
|
|
732
|
-
const parsed = JSON.parse(
|
|
2052
|
+
const parsed = JSON.parse(fs6.readFileSync(rootPath(provider, messageId), "utf8"));
|
|
733
2053
|
if (typeof parsed.sessionId === "string" && parsed.sessionId && typeof parsed.pid === "number") {
|
|
734
|
-
if (!
|
|
2054
|
+
if (!pidAlive4(parsed.pid)) return { sessionId: parsed.sessionId, pid: parsed.pid, claimedAt: parsed.claimedAt ?? 0, ownerOffline: true };
|
|
735
2055
|
return { sessionId: parsed.sessionId, pid: parsed.pid, claimedAt: parsed.claimedAt ?? 0 };
|
|
736
2056
|
}
|
|
737
2057
|
return void 0;
|
|
@@ -741,18 +2061,18 @@ function sessionRootOwner(provider, messageId) {
|
|
|
741
2061
|
}
|
|
742
2062
|
|
|
743
2063
|
// builtin/extensions/im-forward/session-anchors.ts
|
|
744
|
-
import * as
|
|
745
|
-
import * as
|
|
2064
|
+
import * as fs7 from "node:fs";
|
|
2065
|
+
import * as path8 from "node:path";
|
|
746
2066
|
function anchorsDir() {
|
|
747
|
-
return
|
|
2067
|
+
return path8.join(addressBookRoot(), "im-forward", "anchors");
|
|
748
2068
|
}
|
|
749
2069
|
function anchorPath(sessionId) {
|
|
750
2070
|
const safe = sessionId.replace(/[^a-zA-Z0-9._-]/g, "_");
|
|
751
|
-
return
|
|
2071
|
+
return path8.join(anchorsDir(), `${safe}.json`);
|
|
752
2072
|
}
|
|
753
2073
|
function loadPersistedAnchor(sessionId, identity) {
|
|
754
2074
|
try {
|
|
755
|
-
const raw =
|
|
2075
|
+
const raw = fs7.readFileSync(anchorPath(sessionId), "utf8");
|
|
756
2076
|
const parsed = JSON.parse(raw);
|
|
757
2077
|
if (typeof parsed.anchor?.messageId === "string" && parsed.anchor.messageId && typeof parsed.anchor.at === "number" && parsed.provider === identity.provider && // v2 group-home (11-12): the home is the APP'S WHOLE PRESENCE, so an
|
|
758
2078
|
// anchor may live in ANY room — a group chat id differs from the
|
|
@@ -781,8 +2101,8 @@ function savePersistedAnchor(sessionId, identity, anchor) {
|
|
|
781
2101
|
anchor
|
|
782
2102
|
};
|
|
783
2103
|
const target = anchorPath(sessionId);
|
|
784
|
-
|
|
785
|
-
|
|
2104
|
+
fs7.mkdirSync(path8.dirname(target), { recursive: true });
|
|
2105
|
+
fs7.writeFileSync(target, `${JSON.stringify(file)}
|
|
786
2106
|
`, "utf8");
|
|
787
2107
|
} catch {
|
|
788
2108
|
}
|
|
@@ -796,7 +2116,7 @@ var RESTART_BACKOFF_MIN_MS = 5e3;
|
|
|
796
2116
|
var RESTART_BACKOFF_MAX_MS = 6e4;
|
|
797
2117
|
var SEND_FAILURE_NOTIFY_THROTTLE_MS = 5 * 60 * 1e3;
|
|
798
2118
|
var CHUNK_RETRY_DELAY_MS = 2e3;
|
|
799
|
-
var delay = (ms) => new Promise((
|
|
2119
|
+
var delay = (ms) => new Promise((resolve6) => setTimeout(resolve6, ms));
|
|
800
2120
|
var MAX_INBOUND_RETRIES = 3;
|
|
801
2121
|
var DEFAULT_INBOUND_RETRY_BACKOFF_MS = 5e3;
|
|
802
2122
|
var MAX_PENDING_IM_INPUTS = 50;
|
|
@@ -836,10 +2156,10 @@ function ipcDiscoveryRoot2() {
|
|
|
836
2156
|
}
|
|
837
2157
|
function liveManagerForBinding(binding) {
|
|
838
2158
|
try {
|
|
839
|
-
for (const file of
|
|
2159
|
+
for (const file of fs8.readdirSync(ipcDiscoveryRoot2())) {
|
|
840
2160
|
if (!file.endsWith(".json")) continue;
|
|
841
2161
|
try {
|
|
842
|
-
const peer = JSON.parse(
|
|
2162
|
+
const peer = JSON.parse(fs8.readFileSync(pathJoin(ipcDiscoveryRoot2(), file), "utf8"));
|
|
843
2163
|
if (peer.pid === process.pid || peer.isManager !== true || peer.imBinding !== binding || !Number.isInteger(peer.pid) || !peer.pid || peer.pid <= 0) continue;
|
|
844
2164
|
try {
|
|
845
2165
|
process.kill(peer.pid, 0);
|
|
@@ -854,13 +2174,17 @@ function liveManagerForBinding(binding) {
|
|
|
854
2174
|
}
|
|
855
2175
|
return false;
|
|
856
2176
|
}
|
|
857
|
-
async function
|
|
858
|
-
const
|
|
2177
|
+
async function applyPeerControl(peerRef, control, payload, expected) {
|
|
2178
|
+
const runtime = currentIpcRuntime(ipcDiscoveryRoot2());
|
|
2179
|
+
if (runtime) return runtime.sendBoundControl(peerRef, control, payload, expected, 6e3);
|
|
2180
|
+
return applyPeerControlDirect(peerRef, control, payload, expected);
|
|
2181
|
+
}
|
|
2182
|
+
async function applyPeerControlDirect(peerRef, control, payload, expected) {
|
|
859
2183
|
let target;
|
|
860
2184
|
try {
|
|
861
2185
|
const dir = ipcDiscoveryRoot2();
|
|
862
|
-
for (const file of
|
|
863
|
-
const parsed = JSON.parse(
|
|
2186
|
+
for (const file of fs8.readdirSync(dir).filter((f) => f.endsWith(".json"))) {
|
|
2187
|
+
const parsed = JSON.parse(fs8.readFileSync(join9(dir, file), "utf8"));
|
|
864
2188
|
if (!parsed.port || !parsed.secret || typeof parsed.pid !== "number" || !parsed.instanceId || typeof parsed.sessionId !== "string" || !parsed.sessionId) continue;
|
|
865
2189
|
const match = parsed.instanceId === peerRef || parsed.instanceId.startsWith(peerRef) || parsed.displayName === peerRef;
|
|
866
2190
|
if (!match) continue;
|
|
@@ -875,56 +2199,110 @@ async function applyModelControl(peerRef, model) {
|
|
|
875
2199
|
} catch {
|
|
876
2200
|
}
|
|
877
2201
|
if (!target) return { ok: false, detail: `Session not found: ${peerRef}` };
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
if (settled) return;
|
|
892
|
-
settled = true;
|
|
893
|
-
try {
|
|
894
|
-
sock.destroy();
|
|
895
|
-
} catch {
|
|
896
|
-
}
|
|
897
|
-
resolve5({ ok, detail });
|
|
898
|
-
};
|
|
899
|
-
const sock = net2.connect({ host: "127.0.0.1", port: target.port }, () => {
|
|
900
|
-
sock.write(JSON.stringify(envelope) + "\n");
|
|
901
|
-
});
|
|
902
|
-
sock.setTimeout(6e3, () => finish(false, "Peer gave no receipt within 6s (it may be restarting; the control frame is idempotent \u2014 resending is safe)"));
|
|
903
|
-
sock.on("error", (error) => finish(false, `Connection failed: ${error instanceof Error ? error.message : String(error)}`));
|
|
904
|
-
sock.on("close", () => {
|
|
905
|
-
if (!settled) finish(false, "Peer closed the connection (policy refusal or rejected frame; resending is safe)");
|
|
906
|
-
});
|
|
907
|
-
sock.on("data", (buffer) => {
|
|
908
|
-
for (const line of buffer.toString("utf8").split("\n")) {
|
|
909
|
-
if (!line.trim()) continue;
|
|
910
|
-
try {
|
|
911
|
-
const parsed = JSON.parse(line);
|
|
912
|
-
if (parsed.kind === "ack" || parsed.kind === "result") {
|
|
913
|
-
const refused = /"ok"\s*:\s*false|error|拒绝|invalid|unknown|refus|denied/i.test(parsed.text ?? "");
|
|
914
|
-
finish(!refused, `Peer receipt: ${parsed.text ?? "(empty)"}`);
|
|
915
|
-
return;
|
|
916
|
-
}
|
|
917
|
-
} catch {
|
|
918
|
-
}
|
|
919
|
-
}
|
|
2202
|
+
if (expected && (target.instanceId !== expected.instanceId || target.sessionId !== expected.sessionId)) {
|
|
2203
|
+
return { ok: false, detail: `Target session changed: ${peerRef} now serves ${target.sessionId}` };
|
|
2204
|
+
}
|
|
2205
|
+
const peer = target;
|
|
2206
|
+
const client = new IpcTransport({ instanceId: "pie-panel0000000", resolveSecret: () => peer.secret, onEnvelope() {
|
|
2207
|
+
} });
|
|
2208
|
+
try {
|
|
2209
|
+
const reply = await client.send(peer.instanceId, peer.port, "control", {
|
|
2210
|
+
sessionId: peer.sessionId,
|
|
2211
|
+
text: JSON.stringify({ control, payload }),
|
|
2212
|
+
awaitAck: true,
|
|
2213
|
+
waitMs: 6e3,
|
|
2214
|
+
replyKinds: /* @__PURE__ */ new Set(["ack"])
|
|
920
2215
|
});
|
|
921
|
-
|
|
2216
|
+
if (reply?.text) {
|
|
2217
|
+
const ack = JSON.parse(reply.text);
|
|
2218
|
+
if (typeof ack?.ok === "boolean") return { ok: ack.ok, detail: `Peer receipt: ${reply.text}` };
|
|
2219
|
+
}
|
|
2220
|
+
} catch {
|
|
2221
|
+
} finally {
|
|
2222
|
+
client.close();
|
|
2223
|
+
}
|
|
2224
|
+
return { ok: false, unknown: true, detail: "No verified receipt. The request may already have been applied." };
|
|
2225
|
+
}
|
|
2226
|
+
async function applyModelControl(peerRef, model) {
|
|
2227
|
+
return applyPeerControl(peerRef, "model.set", { model });
|
|
2228
|
+
}
|
|
2229
|
+
function renderPeekReceipt(peer, receipt) {
|
|
2230
|
+
if (!receipt.ok) return receipt.unknown ? `\u26A0\uFE0F ${peer}
|
|
2231
|
+
|
|
2232
|
+
No verified live response. The worker may still be healthy or busy; silence/timeout is not evidence that it is dead.` : `\u26A0\uFE0F ${peer}
|
|
2233
|
+
|
|
2234
|
+
${receipt.detail}`;
|
|
2235
|
+
try {
|
|
2236
|
+
const ack = JSON.parse(receipt.detail.slice(receipt.detail.indexOf("{")));
|
|
2237
|
+
if (ack.ok !== true || typeof ack.message !== "string") throw new Error("bad ack");
|
|
2238
|
+
const report = JSON.parse(ack.message);
|
|
2239
|
+
const now = Date.now();
|
|
2240
|
+
const age = (at) => {
|
|
2241
|
+
if (typeof at !== "number" || !Number.isFinite(at)) return "age unknown";
|
|
2242
|
+
const seconds = Math.max(0, Math.floor((now - at) / 1e3));
|
|
2243
|
+
if (seconds < 2) return "now";
|
|
2244
|
+
if (seconds < 60) return `${seconds}s ago`;
|
|
2245
|
+
const minutes = Math.floor(seconds / 60);
|
|
2246
|
+
return minutes < 60 ? `${minutes}m ago` : `${Math.floor(minutes / 60)}h ago`;
|
|
2247
|
+
};
|
|
2248
|
+
const items = Array.isArray(report.items) ? report.items.filter((i) => (i.kind === "assistant" || i.kind === "tool") && typeof i.text === "string") : [];
|
|
2249
|
+
const live = items.map((i) => i.kind === "tool" ? `- \u{1F527} ${age(i.at)} \xB7 ${i.text}` : `**Assistant activity \xB7 ${age(i.at)}**
|
|
2250
|
+
${i.text}`).join("\n\n");
|
|
2251
|
+
const last = typeof report.lastVisible?.text === "string" ? report.lastVisible.text : "";
|
|
2252
|
+
const repeatedIdleLast = !report.active && !!last && items.some((i) => i.kind === "assistant" && i.text === last);
|
|
2253
|
+
return [
|
|
2254
|
+
`**Live response:** ${report.active ? "working" : "idle"} \xB7 snapshot ${age(report.generatedAt)}${typeof report.turn === "number" ? ` \xB7 turn #${report.turn}` : ""}${report.startedAt ? ` started ${age(report.startedAt)}` : ""}`,
|
|
2255
|
+
live || "_(No user-displayable progress in the current/recent turn.)_",
|
|
2256
|
+
...repeatedIdleLast ? [] : [`---
|
|
2257
|
+
**Last visible assistant output \xB7 ${age(report.lastVisible?.at)}:**
|
|
2258
|
+
${last || "_(none captured in memory for this session)_"}`],
|
|
2259
|
+
"_Live authenticated snapshot; memory-only. No reasoning, tool arguments/results, or disk logs._"
|
|
2260
|
+
].join("\n\n");
|
|
2261
|
+
} catch {
|
|
2262
|
+
return `\u26A0\uFE0F ${peer}
|
|
2263
|
+
|
|
2264
|
+
Malformed verified Peek response.`;
|
|
2265
|
+
}
|
|
2266
|
+
}
|
|
2267
|
+
function renderContextReceipt(peer, receipt) {
|
|
2268
|
+
if (!receipt.ok) return `\u26A0\uFE0F ${peer}
|
|
2269
|
+
|
|
2270
|
+
${receipt.detail}`;
|
|
2271
|
+
const fallback = `\u{1F4CA} ${peer}
|
|
2272
|
+
|
|
2273
|
+
${receipt.detail}`;
|
|
2274
|
+
const ackStart = receipt.detail.indexOf("{");
|
|
2275
|
+
if (ackStart < 0) return fallback;
|
|
2276
|
+
try {
|
|
2277
|
+
const ack = JSON.parse(receipt.detail.slice(ackStart));
|
|
2278
|
+
if (ack.ok !== true || typeof ack.message !== "string") return fallback;
|
|
2279
|
+
const r = JSON.parse(ack.message);
|
|
2280
|
+
return `\u{1F4CA} **Context estimate** \xB7 ${peer}
|
|
2281
|
+
|
|
2282
|
+
| | |
|
|
2283
|
+
|---|---|
|
|
2284
|
+
| Estimated tokens | ${typeof r.estimatedTokens === "number" ? r.estimatedTokens.toLocaleString() : "?"} |
|
|
2285
|
+
| Context window | ${r.contextWindow ? r.contextWindow.toLocaleString() : "unknown"} |
|
|
2286
|
+
| Usage | ${typeof r.percent === "number" ? `${r.percent}%` : "unknown"} |
|
|
2287
|
+
| Auto-compact | ${r.autoCompactEnabled ? `at ${(r.autoCompactLimitTokens ?? 0).toLocaleString()} tokens` : "off"} |
|
|
2288
|
+
| Queued inputs | ${r.pendingQueuedInputs ?? 0} |
|
|
2289
|
+
| State | ${r.compactionRunning ? "compacting" : r.isStreaming ? "working" : "idle"} |${r.lastCompactOutcome ? `
|
|
2290
|
+
| Last compact | ${r.lastCompactOutcome} |` : ""}
|
|
2291
|
+
|
|
2292
|
+
_Estimate (bytes/4 heuristic) \u2014 same basis as the TUI's /debugs/context report._`;
|
|
2293
|
+
} catch {
|
|
2294
|
+
return fallback;
|
|
2295
|
+
}
|
|
922
2296
|
}
|
|
923
2297
|
function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
|
|
924
2298
|
const IM_INPUT_PREFIX = connection.sourcePrefix;
|
|
925
2299
|
const key = (id) => JSON.stringify([cfg.provider, id]);
|
|
926
2300
|
const isManager = cfg.unattended === true && process.env.PIE_PROC_CURATED_NAME === "manager";
|
|
927
2301
|
const scopes = /* @__PURE__ */ new Set();
|
|
2302
|
+
const panelActionControllers = /* @__PURE__ */ new Set();
|
|
2303
|
+
const panelActionTasks = /* @__PURE__ */ new Set();
|
|
2304
|
+
let actionDeliveryOpen = true;
|
|
2305
|
+
const ACTION_RETIRE_DRAIN_MS = 7e3;
|
|
928
2306
|
let forwardingEnabled = cfg.enabled === true;
|
|
929
2307
|
let configurationFailed = false;
|
|
930
2308
|
function isForwardingEnabled() {
|
|
@@ -1440,8 +2818,8 @@ ${recoveryHint}`,
|
|
|
1440
2818
|
};
|
|
1441
2819
|
const claimStake = () => {
|
|
1442
2820
|
let release;
|
|
1443
|
-
const token = new Promise((
|
|
1444
|
-
release =
|
|
2821
|
+
const token = new Promise((resolve6) => {
|
|
2822
|
+
release = resolve6;
|
|
1445
2823
|
});
|
|
1446
2824
|
token.release = release;
|
|
1447
2825
|
anchorStakeFlights.set(sessionId, token);
|
|
@@ -1614,18 +2992,18 @@ ${recoveryHint}`,
|
|
|
1614
2992
|
const files = collectFileReferences(
|
|
1615
2993
|
text,
|
|
1616
2994
|
ctx.cwd,
|
|
1617
|
-
(
|
|
2995
|
+
(path13) => {
|
|
1618
2996
|
try {
|
|
1619
|
-
const stat =
|
|
2997
|
+
const stat = fs8.statSync(path13);
|
|
1620
2998
|
return { isFile: stat.isFile(), size: stat.size };
|
|
1621
2999
|
} catch {
|
|
1622
3000
|
return null;
|
|
1623
3001
|
}
|
|
1624
3002
|
},
|
|
1625
3003
|
{
|
|
1626
|
-
canonicalize: (
|
|
3004
|
+
canonicalize: (path13) => {
|
|
1627
3005
|
try {
|
|
1628
|
-
return
|
|
3006
|
+
return fs8.realpathSync(path13);
|
|
1629
3007
|
} catch {
|
|
1630
3008
|
return null;
|
|
1631
3009
|
}
|
|
@@ -1722,6 +3100,8 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1722
3100
|
ctx.on("session:changed", (event) => {
|
|
1723
3101
|
inputEpoch++;
|
|
1724
3102
|
currentSessionId = event.sessionId;
|
|
3103
|
+
issuedWorkerCards.clear();
|
|
3104
|
+
peekCards.clear();
|
|
1725
3105
|
if (event.sessionId) resolveSessionAnchor(event.sessionId);
|
|
1726
3106
|
if (event.sessionId && !consumer && !consumerRecovering && !restartTimer && !terminated && !suspended) {
|
|
1727
3107
|
ctx.log("im-forward: session bound, starting event consumer");
|
|
@@ -1777,9 +3157,16 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1777
3157
|
const t = threadOwner({ provider: cfg.provider, threadId: meta.threadId });
|
|
1778
3158
|
if (t.corrupt || t.unavailable) unknown = true;
|
|
1779
3159
|
ownerSession = t.sessionId;
|
|
3160
|
+
if (t.ownerOffline && ownerSession) {
|
|
3161
|
+
ctx.log(`im-forward: thread owner ${ownerSession} offline in registry (stale pid); dispatching by session id`);
|
|
3162
|
+
}
|
|
1780
3163
|
}
|
|
1781
3164
|
if (!ownerSession && !unknown && meta.replyTo) {
|
|
1782
|
-
|
|
3165
|
+
const root = sessionRootOwner(cfg.provider, meta.replyTo);
|
|
3166
|
+
ownerSession = root?.sessionId;
|
|
3167
|
+
if (root?.ownerOffline && ownerSession) {
|
|
3168
|
+
ctx.log(`im-forward: root owner ${ownerSession} offline in registry (stale pid); dispatching by session id`);
|
|
3169
|
+
}
|
|
1783
3170
|
}
|
|
1784
3171
|
if (unknown) return { kind: "unknown-owner" };
|
|
1785
3172
|
if (!ownerSession) return { kind: "no-owner" };
|
|
@@ -1793,6 +3180,8 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1793
3180
|
}
|
|
1794
3181
|
}
|
|
1795
3182
|
const panelCardOwners = /* @__PURE__ */ new Map();
|
|
3183
|
+
const peekCards = /* @__PURE__ */ new Map();
|
|
3184
|
+
const issuedWorkerCards = /* @__PURE__ */ new Map();
|
|
1796
3185
|
const rememberPanelCard = (messageId, sessionId, chatId) => {
|
|
1797
3186
|
if (!messageId) return;
|
|
1798
3187
|
panelCardOwners.set(messageId, { sessionId, epoch: inputEpoch, chatId });
|
|
@@ -1801,13 +3190,15 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1801
3190
|
for (const k of oldest) panelCardOwners.delete(k);
|
|
1802
3191
|
}
|
|
1803
3192
|
};
|
|
3193
|
+
const peekAudienceIsDirect = (event) => event.chatType === "p2p" && (cfg.targetKind === "user" ? event.sender_id === cfg.targetId : event.chat_id === cfg.targetId) && (!cfg.allowUsers || !!event.sender_id && cfg.allowUsers.includes(event.sender_id));
|
|
1804
3194
|
const runPanelCommand = async (panelCmd, event, sessionId, isCurrent) => {
|
|
1805
3195
|
if (!isCurrent()) return;
|
|
1806
3196
|
const started = Date.now();
|
|
3197
|
+
const freshRecipient = cfg.targetKind === "user" ? cfg.targetId : event.chat_id;
|
|
1807
3198
|
if (panelCmd.restricted && cfg.allowUsers && (!event.sender_id || !cfg.allowUsers.includes(event.sender_id))) {
|
|
1808
3199
|
ctx.log(`im-forward: restricted panel action ${panelCmd.cmd} refused for ${event.sender_id ?? "unknown"} (not in allowUsers)`);
|
|
1809
3200
|
try {
|
|
1810
|
-
await connection.send(
|
|
3201
|
+
await connection.send(freshRecipient, "\u26D4\uFE0F This action requires admin rights (allowUsers).", `panel-refused-${event.event_id}`);
|
|
1811
3202
|
} catch {
|
|
1812
3203
|
}
|
|
1813
3204
|
return;
|
|
@@ -1826,24 +3217,142 @@ ${receipt.detail}`,
|
|
|
1826
3217
|
};
|
|
1827
3218
|
try {
|
|
1828
3219
|
if (connection.sendCard) {
|
|
1829
|
-
const sent = await connection.sendCard(
|
|
3220
|
+
const sent = await connection.sendCard(freshRecipient, spec, `panel-model-${event.event_id}`);
|
|
1830
3221
|
if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
|
|
1831
|
-
} else await connection.send(
|
|
3222
|
+
} else await connection.send(freshRecipient, `**${spec.title}**
|
|
1832
3223
|
${spec.body}`, `panel-model-${event.event_id}`);
|
|
1833
3224
|
} catch {
|
|
1834
3225
|
}
|
|
1835
3226
|
return;
|
|
1836
3227
|
}
|
|
3228
|
+
const peekAction = /^panel\.peek(\.refresh)?\.([A-Za-z0-9-]+)$/.exec(panelCmd.cmd);
|
|
3229
|
+
if (peekAction) {
|
|
3230
|
+
const refresh = peekAction[1] === ".refresh";
|
|
3231
|
+
const ref = peekAction[2];
|
|
3232
|
+
const canReadSensitive = peekAudienceIsDirect(event);
|
|
3233
|
+
const peekRecipient = freshRecipient;
|
|
3234
|
+
const patchOnly = async (messageId, spec) => {
|
|
3235
|
+
if (!messageId || !connection.patch) {
|
|
3236
|
+
ctx.log("im-forward: Peek patch unavailable; no fallback send");
|
|
3237
|
+
return;
|
|
3238
|
+
}
|
|
3239
|
+
try {
|
|
3240
|
+
await connection.patch(messageId, spec);
|
|
3241
|
+
} catch {
|
|
3242
|
+
}
|
|
3243
|
+
};
|
|
3244
|
+
if (refresh) {
|
|
3245
|
+
const cardId = event.message_id;
|
|
3246
|
+
const binding2 = cardId ? peekCards.get(cardId) : void 0;
|
|
3247
|
+
const bindingMatches = () => !!cardId && !!binding2 && peekCards.get(cardId) === binding2 && binding2.ref === ref && binding2.chatId === event.chat_id && binding2.senderId === event.sender_id && binding2.ownerSession === currentSessionId && binding2.epoch === inputEpoch && isCurrent();
|
|
3248
|
+
if (!binding2 || !bindingMatches() || !canReadSensitive) return;
|
|
3249
|
+
const verifiedBinding = binding2;
|
|
3250
|
+
const run = verifiedBinding.chain.then(async () => {
|
|
3251
|
+
const receipt = await applyPeerControl(verifiedBinding.ref, "session.peek", {}, { instanceId: verifiedBinding.ref, sessionId: verifiedBinding.targetSession });
|
|
3252
|
+
if (!bindingMatches()) return;
|
|
3253
|
+
const spec = { title: "\u{1F440} Worker Peek", color: receipt.ok ? "green" : "red", body: renderPeekReceipt(verifiedBinding.ref, receipt), actions: [{ id: `panel.peek.refresh.${verifiedBinding.ref}`, label: "\u{1F504} Refresh", payload: { peek: { ref: verifiedBinding.ref, session: verifiedBinding.targetSession } } }, { id: "panel.summon", label: "\u21A9\uFE0F Back" }] };
|
|
3254
|
+
await patchOnly(cardId, spec);
|
|
3255
|
+
});
|
|
3256
|
+
verifiedBinding.chain = run.catch(() => void 0);
|
|
3257
|
+
await run;
|
|
3258
|
+
return;
|
|
3259
|
+
}
|
|
3260
|
+
if (!canReadSensitive) {
|
|
3261
|
+
const denied = { title: "Peek unavailable", color: "red", body: "\u26D4\uFE0F Peek is limited to the configured authorized direct-message audience. Group audience privacy cannot be proven.", actions: [{ id: "panel.summon", label: "\u21A9\uFE0F Back" }] };
|
|
3262
|
+
if (connection.sendCard) {
|
|
3263
|
+
const sent2 = await connection.sendCard(peekRecipient, denied, `panel-peek-denied-${event.event_id}`);
|
|
3264
|
+
if (isCurrent()) rememberPanelCard(sent2?.messageId, sessionId, event.chat_id);
|
|
3265
|
+
}
|
|
3266
|
+
return;
|
|
3267
|
+
}
|
|
3268
|
+
const wire = isRecord(panelCmd.payload) && isRecord(panelCmd.payload.peek) ? panelCmd.payload.peek : void 0;
|
|
3269
|
+
const issuedRef = wire && typeof wire.ref === "string" ? wire.ref : void 0;
|
|
3270
|
+
const issuedSession = wire && typeof wire.session === "string" ? wire.session : void 0;
|
|
3271
|
+
const issuedCard = event.message_id ? issuedWorkerCards.get(event.message_id) : void 0;
|
|
3272
|
+
if (!issuedCard || issuedCard.chatId !== event.chat_id || issuedCard.ref !== ref || issuedCard.targetSession !== issuedSession || issuedRef !== ref || !issuedSession) {
|
|
3273
|
+
if (connection.sendCard) await connection.sendCard(peekRecipient, { title: "Peek refused", color: "red", body: "Missing or forged worker/session binding. Reopen the worker from /panel.", actions: [{ id: "panel.summon", label: "\u21A9\uFE0F Back" }] }, `panel-peek-refused-${event.event_id}`);
|
|
3274
|
+
return;
|
|
3275
|
+
}
|
|
3276
|
+
if (!isCurrent() || !connection.sendCard) return;
|
|
3277
|
+
const sent = await connection.sendCard(peekRecipient, { title: "\u{1F440} Worker Peek", color: "blue", body: "Requesting a live authenticated snapshot\u2026", actions: [] }, `panel-peek-${event.event_id}`);
|
|
3278
|
+
if (!sent?.messageId || !isCurrent()) return;
|
|
3279
|
+
rememberPanelCard(sent.messageId, sessionId, event.chat_id);
|
|
3280
|
+
const binding = { ref, targetSession: issuedSession, chatId: event.chat_id, ...event.sender_id ? { senderId: event.sender_id } : {}, ownerSession: sessionId, epoch: inputEpoch, chain: Promise.resolve() };
|
|
3281
|
+
peekCards.set(sent.messageId, binding);
|
|
3282
|
+
if (peekCards.size > 100) for (const old of [...peekCards.keys()].slice(0, 25)) peekCards.delete(old);
|
|
3283
|
+
const initial = (async () => {
|
|
3284
|
+
const receipt = await applyPeerControl(ref, "session.peek", {}, { instanceId: ref, sessionId: issuedSession });
|
|
3285
|
+
if (!isCurrent() || inputEpoch !== binding.epoch || currentSessionId !== binding.ownerSession || peekCards.get(sent.messageId) !== binding) return;
|
|
3286
|
+
const spec = { title: "\u{1F440} Worker Peek", color: receipt.ok ? "green" : "red", body: renderPeekReceipt(ref, receipt), actions: [{ id: `panel.peek.refresh.${ref}`, label: "\u{1F504} Refresh", payload: { peek: { ref, session: issuedSession } } }, { id: "panel.summon", label: "\u21A9\uFE0F Back" }] };
|
|
3287
|
+
await patchOnly(sent.messageId, spec);
|
|
3288
|
+
})();
|
|
3289
|
+
binding.chain = initial.catch(() => void 0);
|
|
3290
|
+
await initial;
|
|
3291
|
+
return;
|
|
3292
|
+
}
|
|
3293
|
+
const contextAction = /^panel\.context\.([A-Za-z0-9-]+)$/.exec(panelCmd.cmd);
|
|
3294
|
+
if (contextAction) {
|
|
3295
|
+
const receipt = await applyPeerControl(contextAction[1], "session.context", {});
|
|
3296
|
+
if (!isCurrent()) return;
|
|
3297
|
+
const spec = {
|
|
3298
|
+
title: "Context Report",
|
|
3299
|
+
body: renderContextReceipt(contextAction[1], receipt),
|
|
3300
|
+
actions: [{ id: "panel.context", label: "\u21A9\uFE0F Back to context list" }]
|
|
3301
|
+
};
|
|
3302
|
+
try {
|
|
3303
|
+
if (connection.sendCard) {
|
|
3304
|
+
const sent = await connection.sendCard(freshRecipient, spec, `panel-context-${event.event_id}`);
|
|
3305
|
+
if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
|
|
3306
|
+
} else await connection.send(freshRecipient, `**${spec.title}**
|
|
3307
|
+
${spec.body}`, `panel-context-${event.event_id}`);
|
|
3308
|
+
} catch {
|
|
3309
|
+
}
|
|
3310
|
+
return;
|
|
3311
|
+
}
|
|
3312
|
+
const compactAction = /^panel\.compact\.([A-Za-z0-9-]+)$/.exec(panelCmd.cmd);
|
|
3313
|
+
if (compactAction) {
|
|
3314
|
+
if (!cfg.allowUsers || !event.sender_id || !cfg.allowUsers.includes(event.sender_id)) {
|
|
3315
|
+
ctx.log(`im-forward: panel.compact refused for ${event.sender_id ?? "unknown"} (execution-sink gate: allowUsers membership required)`);
|
|
3316
|
+
try {
|
|
3317
|
+
await connection.send(freshRecipient, "\u26D4\uFE0F Compacting a session requires admin rights (allowUsers).", `panel-refused-${event.event_id}`);
|
|
3318
|
+
} catch {
|
|
3319
|
+
}
|
|
3320
|
+
return;
|
|
3321
|
+
}
|
|
3322
|
+
const receipt = await applyPeerControl(compactAction[1], "session.compact", {});
|
|
3323
|
+
if (!isCurrent()) return;
|
|
3324
|
+
const spec = {
|
|
3325
|
+
title: receipt.ok ? "Compaction Submitted" : receipt.unknown ? "Compaction Status Unknown" : "Compaction Refused",
|
|
3326
|
+
body: `${receipt.ok ? "\u{1F9F9}" : "\u26A0\uFE0F"} ${compactAction[1]}
|
|
3327
|
+
|
|
3328
|
+
${receipt.detail}
|
|
3329
|
+
|
|
3330
|
+
${receipt.ok ? "Compaction runs on the target host (LLM summary \u2014 may take a minute). Tap \u{1F4CA} Check context afterwards: the Last compact row shows the committed/failed outcome." : receipt.unknown ? "Check context before submitting again." : "Check the refusal reason before trying again."}`,
|
|
3331
|
+
actions: [
|
|
3332
|
+
{ id: `panel.context.${compactAction[1]}`, label: "\u{1F4CA} Check context" },
|
|
3333
|
+
{ id: "panel.compact", label: "\u21A9\uFE0F Back to compact list" }
|
|
3334
|
+
]
|
|
3335
|
+
};
|
|
3336
|
+
try {
|
|
3337
|
+
if (connection.sendCard) {
|
|
3338
|
+
const sent = await connection.sendCard(freshRecipient, spec, `panel-compact-${event.event_id}`);
|
|
3339
|
+
if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
|
|
3340
|
+
} else await connection.send(freshRecipient, `**${spec.title}**
|
|
3341
|
+
${spec.body}`, `panel-compact-${event.event_id}`);
|
|
3342
|
+
} catch {
|
|
3343
|
+
}
|
|
3344
|
+
return;
|
|
3345
|
+
}
|
|
1837
3346
|
if (panelCmd.cmd === "panel.upgrade.confirm") {
|
|
1838
3347
|
if (!cfg.allowUsers || !event.sender_id || !cfg.allowUsers.includes(event.sender_id)) {
|
|
1839
3348
|
ctx.log(`im-forward: panel.upgrade.confirm refused for ${event.sender_id ?? "unknown"} (execution-sink gate: allowUsers membership required)`);
|
|
1840
3349
|
try {
|
|
1841
|
-
await connection.send(
|
|
3350
|
+
await connection.send(freshRecipient, "\u26D4\uFE0F Upgrading pie requires admin rights (allowUsers).", `panel-refused-${event.event_id}`);
|
|
1842
3351
|
} catch {
|
|
1843
3352
|
}
|
|
1844
3353
|
return;
|
|
1845
3354
|
}
|
|
1846
|
-
const
|
|
3355
|
+
const spawn6 = await import("node:child_process");
|
|
1847
3356
|
const started2 = Date.now();
|
|
1848
3357
|
let actorOk = false;
|
|
1849
3358
|
let actorDetail = "";
|
|
@@ -1851,27 +3360,27 @@ ${spec.body}`, `panel-model-${event.event_id}`);
|
|
|
1851
3360
|
const entry = process.argv[1] ? pathResolve(process.argv[1]) : "";
|
|
1852
3361
|
if (!entry) throw new Error("cannot resolve the pie entry point");
|
|
1853
3362
|
const configRoot = pathDirname(pathDirname(ipcDiscoveryRoot2()));
|
|
1854
|
-
const logFile =
|
|
3363
|
+
const logFile = join9(configRoot, "manager", "upgrade-actor.log");
|
|
1855
3364
|
let out;
|
|
1856
3365
|
try {
|
|
1857
|
-
|
|
1858
|
-
out =
|
|
3366
|
+
fs8.mkdirSync(pathDirname(logFile), { recursive: true });
|
|
3367
|
+
out = fs8.openSync(logFile, "a");
|
|
1859
3368
|
} catch {
|
|
1860
3369
|
out = void 0;
|
|
1861
3370
|
}
|
|
1862
|
-
const child =
|
|
3371
|
+
const child = spawn6.spawn(process.execPath, [entry, "manager", "upgrade"], {
|
|
1863
3372
|
cwd: process.cwd(),
|
|
1864
3373
|
detached: true,
|
|
1865
3374
|
stdio: out !== void 0 ? ["ignore", out, out] : "ignore",
|
|
1866
3375
|
windowsHide: true,
|
|
1867
3376
|
env: process.env
|
|
1868
3377
|
});
|
|
1869
|
-
const spawnOutcome = await new Promise((
|
|
3378
|
+
const spawnOutcome = await new Promise((resolve6) => {
|
|
1870
3379
|
let settled = false;
|
|
1871
3380
|
const settle = (v) => {
|
|
1872
3381
|
if (!settled) {
|
|
1873
3382
|
settled = true;
|
|
1874
|
-
|
|
3383
|
+
resolve6(v);
|
|
1875
3384
|
}
|
|
1876
3385
|
};
|
|
1877
3386
|
child.once("spawn", () => settle("spawned"));
|
|
@@ -1884,7 +3393,7 @@ ${spec.body}`, `panel-model-${event.event_id}`);
|
|
|
1884
3393
|
child.unref();
|
|
1885
3394
|
if (out !== void 0) {
|
|
1886
3395
|
try {
|
|
1887
|
-
|
|
3396
|
+
fs8.closeSync(out);
|
|
1888
3397
|
} catch {
|
|
1889
3398
|
}
|
|
1890
3399
|
}
|
|
@@ -1907,14 +3416,228 @@ ${actorDetail}
|
|
|
1907
3416
|
IM pauses briefly during the restart; tap \u{1F504} Refresh afterwards \u2014 the panel's footer line shows the outcome (old \u2192 new version).` : `Could not spawn the upgrade actor: ${actorDetail}`,
|
|
1908
3417
|
actions: actorOk ? [{ id: "panel.refresh", label: "\u{1F504} Refresh" }] : [{ id: "panel.upgrade", label: "\u21A9\uFE0F Back to upgrade card" }]
|
|
1909
3418
|
};
|
|
1910
|
-
try {
|
|
1911
|
-
if (connection.sendCard) {
|
|
1912
|
-
const sent = await connection.sendCard(
|
|
1913
|
-
if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
|
|
1914
|
-
} else await connection.send(
|
|
1915
|
-
${spec.body}`, `panel-upgrade-${event.event_id}`);
|
|
1916
|
-
} catch {
|
|
3419
|
+
try {
|
|
3420
|
+
if (connection.sendCard) {
|
|
3421
|
+
const sent = await connection.sendCard(freshRecipient, spec, `panel-upgrade-${event.event_id}`);
|
|
3422
|
+
if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
|
|
3423
|
+
} else await connection.send(freshRecipient, `**${spec.title}**
|
|
3424
|
+
${spec.body}`, `panel-upgrade-${event.event_id}`);
|
|
3425
|
+
} catch {
|
|
3426
|
+
}
|
|
3427
|
+
return;
|
|
3428
|
+
}
|
|
3429
|
+
const actionMatch = /^panel\.action\.([a-z0-9][a-z0-9-]{0,31})$/.exec(panelCmd.cmd);
|
|
3430
|
+
if (actionMatch) {
|
|
3431
|
+
const actionId = actionMatch[1];
|
|
3432
|
+
const runtimeAlive = () => !terminated;
|
|
3433
|
+
const actionCanDeliver = () => actionDeliveryOpen;
|
|
3434
|
+
const sendActionCard = async (spec, key2, guard) => {
|
|
3435
|
+
if (!guard()) return void 0;
|
|
3436
|
+
try {
|
|
3437
|
+
if (connection.sendCard) {
|
|
3438
|
+
const sent = await connection.sendCard(freshRecipient, spec, key2);
|
|
3439
|
+
if (guard()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
|
|
3440
|
+
return sent?.messageId;
|
|
3441
|
+
}
|
|
3442
|
+
return (await connection.send(freshRecipient, `**${spec.title ?? "Action"}**
|
|
3443
|
+
${spec.body}`, key2))?.messageId;
|
|
3444
|
+
} catch {
|
|
3445
|
+
}
|
|
3446
|
+
return void 0;
|
|
3447
|
+
};
|
|
3448
|
+
const action = findAction(actionId);
|
|
3449
|
+
if (!action) {
|
|
3450
|
+
await sendActionCard({
|
|
3451
|
+
title: "\u26A0\uFE0F \u52A8\u4F5C\u5DF2\u79FB\u9664",
|
|
3452
|
+
body: `\`${actionId}\` \u4E0D\u5728\u6CE8\u518C\u8868\u91CC\uFF08\u53EF\u80FD\u5DF2\u88AB\u5220\u9664\uFF09\u3002
|
|
3453
|
+
|
|
3454
|
+
\u70B9 /panel \u7684 \u26A1 \u5168\u90E8\u52A8\u4F5C \u67E5\u770B\u5F53\u524D\u53EF\u7528\u7684\u6309\u94AE\u3002`,
|
|
3455
|
+
actions: [{ id: "panel.actions", label: "\u26A1 \u5168\u90E8\u52A8\u4F5C" }, { id: "panel.summon", label: "\u21A9\uFE0F Back to panel" }]
|
|
3456
|
+
}, `panel-action-gone-${event.event_id}`, isCurrent);
|
|
3457
|
+
return;
|
|
3458
|
+
}
|
|
3459
|
+
let workerCtx;
|
|
3460
|
+
if (action.scope !== "manager") {
|
|
3461
|
+
const payloadWorker = (() => {
|
|
3462
|
+
const w = isRecord(panelCmd.payload) ? panelCmd.payload.worker : void 0;
|
|
3463
|
+
if (!isRecord(w)) return void 0;
|
|
3464
|
+
return {
|
|
3465
|
+
name: typeof w.name === "string" && w.name ? w.name : void 0,
|
|
3466
|
+
ref: typeof w.ref === "string" && w.ref ? w.ref : void 0
|
|
3467
|
+
};
|
|
3468
|
+
})();
|
|
3469
|
+
let peer;
|
|
3470
|
+
if (action.scope.startsWith("worker:")) {
|
|
3471
|
+
peer = findPeerByName(action.scope.slice("worker:".length));
|
|
3472
|
+
} else if (payloadWorker?.ref) {
|
|
3473
|
+
peer = findPeerByInstanceId(payloadWorker.ref);
|
|
3474
|
+
} else if (payloadWorker?.name) {
|
|
3475
|
+
peer = findPeerByName(payloadWorker.name);
|
|
3476
|
+
}
|
|
3477
|
+
if (peer === "ambiguous") {
|
|
3478
|
+
await sendActionCard({
|
|
3479
|
+
title: `\u26A0\uFE0F ${action.label}`,
|
|
3480
|
+
body: `\u540D\u5B57 \`${action.scope.startsWith("worker:") ? action.scope.slice("worker:".length) : payloadWorker?.name ?? ""}\` \u540C\u65F6\u547D\u4E2D\u591A\u4E2A\u5728\u7EBF session\u2014\u2014\u4ECE /panel \u2192 \u{1F4C2} \u70B9\u76EE\u6807 worker \u7684\u5361\u8FDB\u53BB\u518D\u70B9\uFF08\u6309\u94AE\u5E26\u7CBE\u786E\u5730\u5740\uFF09\u3002`,
|
|
3481
|
+
actions: [{ id: "panel.summon", label: "\u21A9\uFE0F Back to panel" }]
|
|
3482
|
+
}, `panel-action-ambiguous-${event.event_id}`, isCurrent);
|
|
3483
|
+
return;
|
|
3484
|
+
}
|
|
3485
|
+
if (!peer) {
|
|
3486
|
+
const wanted = action.scope.startsWith("worker:") ? action.scope.slice("worker:".length) : payloadWorker?.name ?? payloadWorker?.ref ?? "?";
|
|
3487
|
+
const generic = action.scope === "worker" && !payloadWorker?.name && !payloadWorker?.ref;
|
|
3488
|
+
await sendActionCard({
|
|
3489
|
+
title: `\u26A0\uFE0F ${action.label}`,
|
|
3490
|
+
body: generic ? "\u8FD9\u662F worker \u901A\u7528\u6309\u94AE\u2014\u2014\u8BF7\u5728\u67D0\u4E2A worker \u7684\u5361\u7247\u4E0A\u70B9\u51FB\uFF08/panel \u2192 \u{1F4C2} \u9009\u62E9 worker\uFF09\uFF0C\u811A\u672C\u9700\u8981\u77E5\u9053\u66FF\u54EA\u4E2A worker \u8DD1\u3002" : `worker \`${wanted}\` \u4E0D\u5728\u7EBF\uFF08worker \u6709 TTL \u56DE\u6536\uFF09\u3002\u7B49\u5B83\u5728\u7EBF\u65F6\u518D\u4ECE\u5B83\u7684\u5361\u7247\u89E6\u53D1\u3002`,
|
|
3491
|
+
actions: [{ id: "panel.summon", label: "\u21A9\uFE0F Back to panel" }]
|
|
3492
|
+
}, `panel-action-offline-${event.event_id}`, isCurrent);
|
|
3493
|
+
return;
|
|
3494
|
+
}
|
|
3495
|
+
workerCtx = { name: peer.name, ref: peer.instanceId, ...peer.cwd ? { dir: peer.cwd } : {} };
|
|
3496
|
+
}
|
|
3497
|
+
const triggerOpenId = event.sender_id;
|
|
3498
|
+
const triggerQuick = peekNameCache(triggerOpenId) ?? fallbackName(triggerOpenId);
|
|
3499
|
+
const lock = await acquireLock(actionId, triggerQuick, action.timeoutMs ?? DEFAULT_TIMEOUT_MS, pathResolve(action.script));
|
|
3500
|
+
if (!lock.ok) {
|
|
3501
|
+
const since = lock.holder.startedAt > 0 ? new Date(lock.holder.startedAt).toLocaleTimeString("en-GB", { hour12: false }) : "?";
|
|
3502
|
+
await sendActionCard({
|
|
3503
|
+
title: `\u23F3 ${action.label}`,
|
|
3504
|
+
body: lock.holder.note ? `\u26A0\uFE0F ${lock.holder.note}` : `\u6B63\u5728\u8FD0\u884C\u4E2D\uFF08\u7531 ${lock.holder.triggerName} \u89E6\u53D1\u4E8E ${since}\uFF09\u3002\u540C\u4E00\u52A8\u4F5C\u540C\u65F6\u53EA\u8DD1\u4E00\u4E2A\u2014\u2014\u7B49\u5B83\u5B8C\u6210\u6216\u8D85\u65F6\u540E\u518D\u70B9\u3002`,
|
|
3505
|
+
actions: [{ id: "panel.summon", label: "\u21A9\uFE0F Back to panel" }]
|
|
3506
|
+
}, `panel-action-busy-${event.event_id}`, isCurrent);
|
|
3507
|
+
return;
|
|
3508
|
+
}
|
|
3509
|
+
const timeoutS = Math.round((action.timeoutMs ?? DEFAULT_TIMEOUT_MS) / 1e3);
|
|
3510
|
+
let ackMessageId;
|
|
3511
|
+
const publishTerminal = async (spec, key2) => {
|
|
3512
|
+
if (!actionCanDeliver()) return;
|
|
3513
|
+
if (ackMessageId && connection.sendCard && connection.patch) {
|
|
3514
|
+
try {
|
|
3515
|
+
if (await connection.patch(ackMessageId, spec)) return;
|
|
3516
|
+
} catch {
|
|
3517
|
+
}
|
|
3518
|
+
}
|
|
3519
|
+
await sendActionCard(spec, key2, actionCanDeliver);
|
|
3520
|
+
};
|
|
3521
|
+
const publishCancellation = (body) => publishTerminal({
|
|
3522
|
+
title: `\u26A0\uFE0F ${action.label}`,
|
|
3523
|
+
color: "red",
|
|
3524
|
+
body,
|
|
3525
|
+
actions: [{ id: `panel.action.${actionId}`, label: "\u{1F501} \u91CD\u8BD5", ...workerCtx ? { payload: { worker: { name: workerCtx.name, ...workerCtx.ref ? { ref: workerCtx.ref } : {} } } } : {} }, { id: "panel.summon", label: "\u21A9\uFE0F \u9762\u677F" }]
|
|
3526
|
+
}, `panel-action-cancel-${event.event_id}`);
|
|
3527
|
+
if (!runtimeAlive() || !isCurrent()) {
|
|
3528
|
+
lock.release();
|
|
3529
|
+
return;
|
|
1917
3530
|
}
|
|
3531
|
+
const actionAbort = new AbortController();
|
|
3532
|
+
panelActionControllers.add(actionAbort);
|
|
3533
|
+
actionAbort.signal.addEventListener("abort", lock.release, { once: true });
|
|
3534
|
+
const initialAck = Promise.resolve().then(async () => {
|
|
3535
|
+
if (!runtimeAlive() || !isCurrent()) return false;
|
|
3536
|
+
ackMessageId = await sendActionCard({
|
|
3537
|
+
title: `\u{1F680} ${action.label}`,
|
|
3538
|
+
color: "blue",
|
|
3539
|
+
body: `\u7531 ${triggerQuick} \u89E6\u53D1 \xB7 \u8FD0\u884C\u4E2D\u2026\uFF08\u8D85\u65F6\u4E0A\u9650 ${timeoutS}s\uFF09
|
|
3540
|
+
|
|
3541
|
+
\u5B8C\u6210\u540E\u672C\u5361\u81EA\u52A8\u66F4\u65B0\u4E3A\u7ED3\u679C\u3002`,
|
|
3542
|
+
actions: []
|
|
3543
|
+
}, `panel-action-${event.event_id}`, isCurrent);
|
|
3544
|
+
return true;
|
|
3545
|
+
});
|
|
3546
|
+
const actionTask = (async () => {
|
|
3547
|
+
try {
|
|
3548
|
+
if (!await initialAck) return;
|
|
3549
|
+
if (actionAbort.signal.aborted) {
|
|
3550
|
+
if (ackMessageId) await publishCancellation("\u8FD0\u884C\u65F6\u5DF2\u9000\u51FA\uFF0C\u672C\u6B21\u64CD\u4F5C\u672A\u6267\u884C\u3002");
|
|
3551
|
+
else ctx.log(`im-forward: panel action ${actionId} retired with no initial card receipt; script not started`);
|
|
3552
|
+
return;
|
|
3553
|
+
}
|
|
3554
|
+
actionAbort.signal.removeEventListener("abort", lock.release);
|
|
3555
|
+
if (!lock.rearm(action.timeoutMs ?? DEFAULT_TIMEOUT_MS)) {
|
|
3556
|
+
await publishCancellation("\u6267\u884C\u69FD\u5728\u542F\u52A8\u524D\u6613\u4E3B\uFF0C\u672C\u6B21\u89E6\u53D1\u5DF2\u53D6\u6D88\uFF08\u672A\u6267\u884C\uFF09\u3002\u8BF7\u91CD\u8BD5\u3002");
|
|
3557
|
+
return;
|
|
3558
|
+
}
|
|
3559
|
+
ctx.log(`im-forward: panel action ${actionId} triggered by ${triggerQuick} (${triggerOpenId ?? "no-openid"})${workerCtx ? ` as worker ${workerCtx.name}` : ""}`);
|
|
3560
|
+
const result2 = await executeAction({
|
|
3561
|
+
action,
|
|
3562
|
+
trigger: { name: triggerQuick, ...triggerOpenId ? { openId: triggerOpenId } : {} },
|
|
3563
|
+
chatId: event.chat_id,
|
|
3564
|
+
...workerCtx ? { worker: workerCtx } : {},
|
|
3565
|
+
onChildSpawn: (pid) => lock.announceChild(pid),
|
|
3566
|
+
signal: actionAbort.signal
|
|
3567
|
+
});
|
|
3568
|
+
if (result2.cancelled) {
|
|
3569
|
+
appendAudit({
|
|
3570
|
+
at: Date.now(),
|
|
3571
|
+
actionId,
|
|
3572
|
+
label: action.label,
|
|
3573
|
+
trigger: { name: triggerQuick, ...triggerOpenId ? { openId: triggerOpenId } : {} },
|
|
3574
|
+
chatId: event.chat_id,
|
|
3575
|
+
...workerCtx ? { worker: workerCtx.name } : {},
|
|
3576
|
+
durationMs: result2.durationMs,
|
|
3577
|
+
exitCode: result2.exitCode,
|
|
3578
|
+
timedOut: false,
|
|
3579
|
+
ok: false,
|
|
3580
|
+
logFile: result2.logFile
|
|
3581
|
+
});
|
|
3582
|
+
await publishCancellation(terminated ? "\u8FD0\u884C\u65F6\u5DF2\u9000\u51FA\uFF0C\u672C\u6B21\u64CD\u4F5C\u5DF2\u53D6\u6D88\u3002\u82E5\u811A\u672C\u6B64\u524D\u4EA7\u751F\u4E86\u8F93\u51FA\uFF0C\u8BF7\u5148\u6838\u5BF9\u7ED3\u679C\u518D\u91CD\u8BD5\u3002" : "\u6267\u884C\u69FD\u5728\u811A\u672C\u542F\u52A8\u4E00\u523B\u6613\u4E3B\uFF0C\u672C\u6B21\u89E6\u53D1\u5DF2\u53D6\u6D88\uFF08\u811A\u672C\u5DF2\u5728\u542F\u52A8\u65F6\u7EC8\u6B62\uFF1B\u53EF\u80FD\u5DF2\u6709\u90E8\u5206\u8F93\u51FA\uFF09\u3002\u8BF7\u91CD\u8BD5\u3002");
|
|
3583
|
+
return;
|
|
3584
|
+
}
|
|
3585
|
+
const triggerName = terminated ? triggerQuick : await resolveUserName(triggerOpenId, { signal: actionAbort.signal, cwd: ctx.cwd, ...cfg.profile ? { profile: cfg.profile } : {}, ...cfg.larkCliPath ? { binary: cfg.larkCliPath } : {} });
|
|
3586
|
+
bumpRunStats(actionId, triggerName);
|
|
3587
|
+
appendAudit({
|
|
3588
|
+
at: Date.now(),
|
|
3589
|
+
actionId,
|
|
3590
|
+
label: action.label,
|
|
3591
|
+
trigger: { name: triggerName, ...triggerOpenId ? { openId: triggerOpenId } : {} },
|
|
3592
|
+
chatId: event.chat_id,
|
|
3593
|
+
...workerCtx ? { worker: workerCtx.name } : {},
|
|
3594
|
+
durationMs: result2.durationMs,
|
|
3595
|
+
exitCode: result2.exitCode,
|
|
3596
|
+
timedOut: result2.timedOut,
|
|
3597
|
+
ok: result2.ok,
|
|
3598
|
+
logFile: result2.logFile
|
|
3599
|
+
});
|
|
3600
|
+
if (!actionCanDeliver()) return;
|
|
3601
|
+
const icon = result2.timedOut ? "\u23F1\uFE0F" : result2.ok ? "\u2705" : "\u274C";
|
|
3602
|
+
const statusLine = result2.timedOut ? `\u8D85\u65F6\uFF08>${timeoutS}s\uFF09\uFF0C\u5DF2\u7EC8\u6B62` : result2.ok ? `\u8017\u65F6 ${(result2.durationMs / 1e3).toFixed(1)}s` : `exit ${result2.exitCode ?? "?"} \xB7 \u8017\u65F6 ${(result2.durationMs / 1e3).toFixed(1)}s`;
|
|
3603
|
+
const outBody = truncateMarkdown(result2.stdout.trim() || (result2.ok ? "_(no output)_" : ""));
|
|
3604
|
+
const logNote = result2.logDegraded ? `
|
|
3605
|
+
_(\u65E5\u5FD7\u4E0D\u5B8C\u6574\uFF1A\u8D85\u9650\u6216\u5199\u5165\u5931\u8D25\uFF1B\u5DF2\u6709\u90E8\u5206\u89C1 ${result2.logFile})_` : result2.stdoutTruncated || result2.stderrTruncated ? `
|
|
3606
|
+
_(\u8F93\u51FA\u8FC7\u957F\u5DF2\u622A\u65AD;\u5B8C\u6574\u89C1 ${result2.logFile})_` : "";
|
|
3607
|
+
const resultSpec = {
|
|
3608
|
+
title: `${icon} ${action.label}`,
|
|
3609
|
+
color: result2.ok ? "green" : "red",
|
|
3610
|
+
body: [
|
|
3611
|
+
`\u7531 ${triggerName} \u89E6\u53D1 \xB7 ${statusLine}${workerCtx ? ` \xB7 as ${workerCtx.name}` : ""}`,
|
|
3612
|
+
``,
|
|
3613
|
+
outBody,
|
|
3614
|
+
result2.stderrTail.trim() && !result2.ok ? `
|
|
3615
|
+
**stderr**
|
|
3616
|
+
\`\`\`
|
|
3617
|
+
${result2.stderrTail.trim().slice(0, 1500)}
|
|
3618
|
+
\`\`\`` : "",
|
|
3619
|
+
logNote
|
|
3620
|
+
].filter((line) => line !== "").join("\n"),
|
|
3621
|
+
actions: [{ id: `panel.action.${actionId}`, label: "\u{1F501} \u518D\u8DD1\u4E00\u6B21", ...workerCtx ? { payload: { worker: { name: workerCtx.name, ...workerCtx.ref ? { ref: workerCtx.ref } : {} } } } : {} }, { id: "panel.summon", label: "\u21A9\uFE0F \u9762\u677F" }]
|
|
3622
|
+
};
|
|
3623
|
+
await publishTerminal(resultSpec, `panel-action-result-${event.event_id}`);
|
|
3624
|
+
} catch (error) {
|
|
3625
|
+
ctx.log(`im-forward: panel action ${actionId} execution error: ${error instanceof Error ? error.message : String(error)}`);
|
|
3626
|
+
await publishTerminal({
|
|
3627
|
+
title: `\u274C ${action.label}`,
|
|
3628
|
+
color: "red",
|
|
3629
|
+
body: `\u6267\u884C\u5668\u81EA\u8EAB\u51FA\u9519\uFF1A${error instanceof Error ? error.message : String(error)}`,
|
|
3630
|
+
actions: [{ id: "panel.summon", label: "\u21A9\uFE0F \u9762\u677F" }]
|
|
3631
|
+
}, `panel-action-error-${event.event_id}`);
|
|
3632
|
+
} finally {
|
|
3633
|
+
actionAbort.signal.removeEventListener("abort", lock.release);
|
|
3634
|
+
lock.release();
|
|
3635
|
+
panelActionControllers.delete(actionAbort);
|
|
3636
|
+
}
|
|
3637
|
+
})();
|
|
3638
|
+
panelActionTasks.add(actionTask);
|
|
3639
|
+
void actionTask.then(() => panelActionTasks.delete(actionTask), () => panelActionTasks.delete(actionTask));
|
|
3640
|
+
await initialAck;
|
|
1918
3641
|
return;
|
|
1919
3642
|
}
|
|
1920
3643
|
const result = executePanelCommand({ ...panelCmd, senderId: event.sender_id, originCardId: event.message_id });
|
|
@@ -1930,11 +3653,19 @@ ${spec.body}`, `panel-upgrade-${event.event_id}`);
|
|
|
1930
3653
|
}
|
|
1931
3654
|
if (!isCurrent()) return;
|
|
1932
3655
|
if (connection.sendCard) {
|
|
1933
|
-
const sent = await connection.sendCard(
|
|
1934
|
-
if (isCurrent())
|
|
3656
|
+
const sent = await connection.sendCard(freshRecipient, result.spec, `panel-${event.event_id}`);
|
|
3657
|
+
if (isCurrent()) {
|
|
3658
|
+
rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
|
|
3659
|
+
const peek = result.spec.actions.find((a) => /^panel\.peek\.[A-Za-z0-9-]+$/.test(a.id));
|
|
3660
|
+
const bound = peek && isRecord(peek.payload) && isRecord(peek.payload.peek) ? peek.payload.peek : void 0;
|
|
3661
|
+
if (sent?.messageId && bound && typeof bound.ref === "string" && typeof bound.session === "string") {
|
|
3662
|
+
issuedWorkerCards.set(sent.messageId, { ref: bound.ref, targetSession: bound.session, chatId: event.chat_id });
|
|
3663
|
+
if (issuedWorkerCards.size > 100) for (const old of [...issuedWorkerCards.keys()].slice(0, 25)) issuedWorkerCards.delete(old);
|
|
3664
|
+
}
|
|
3665
|
+
}
|
|
1935
3666
|
ctx.log(`im-forward: panel card sent (${panelCmd.cmd})`);
|
|
1936
3667
|
} else {
|
|
1937
|
-
await connection.send(
|
|
3668
|
+
await connection.send(freshRecipient, `**${result.spec.title ?? "Panel"}**
|
|
1938
3669
|
${result.spec.body}`, `panel-${event.event_id}`);
|
|
1939
3670
|
}
|
|
1940
3671
|
} catch (error) {
|
|
@@ -1967,6 +3698,15 @@ ${result.spec.body}`, `panel-${event.event_id}`);
|
|
|
1967
3698
|
}
|
|
1968
3699
|
const messageId = event.message_id;
|
|
1969
3700
|
if (!messageId) return;
|
|
3701
|
+
const peekAtGate = event.text?.startsWith("/card ") ? parsePanelCommand(event.text) : void 0;
|
|
3702
|
+
if (peekAtGate && /^panel\.peek\.[A-Za-z0-9-]+$/.test(peekAtGate.cmd) && !peekAudienceIsDirect(event)) {
|
|
3703
|
+
const recipient = cfg.targetKind === "user" ? cfg.targetId : event.chat_id;
|
|
3704
|
+
if (connection.sendCard) {
|
|
3705
|
+
const sent = await connection.sendCard(recipient, { title: "Peek unavailable", color: "red", body: "\u26D4\uFE0F Peek is limited to the configured authorized direct-message audience. Group audience privacy cannot be proven.", actions: [{ id: "panel.summon", label: "\u21A9\uFE0F Back" }] }, `panel-peek-denied-${event.event_id}`);
|
|
3706
|
+
if (sent?.messageId && currentSessionId) rememberPanelCard(sent.messageId, currentSessionId, event.chat_id);
|
|
3707
|
+
}
|
|
3708
|
+
return;
|
|
3709
|
+
}
|
|
1970
3710
|
const owner = panelCardOwners.get(messageId);
|
|
1971
3711
|
const nonBoundPanel = cfg.targetKind === "chat" && !!cfg.targetId && event.chat_id !== cfg.targetId;
|
|
1972
3712
|
const fastEpoch = inputEpoch;
|
|
@@ -2085,7 +3825,7 @@ ${result.spec.body}`, `panel-${event.event_id}`);
|
|
|
2085
3825
|
return;
|
|
2086
3826
|
}
|
|
2087
3827
|
if (outcome.kind === "delivery-failed") {
|
|
2088
|
-
ctx.log(`im-forward: dispatch to ${outcome.owner} failed for ${messageId}; dropping`);
|
|
3828
|
+
ctx.log(`im-forward: dispatch to ${outcome.owner} failed for ${messageId} (owner may be offline); dropping \u2014 ownership retained, never taken over`);
|
|
2089
3829
|
return;
|
|
2090
3830
|
}
|
|
2091
3831
|
if (outcome.kind === "unknown-owner") {
|
|
@@ -2641,6 +4381,25 @@ ${imagelessCaption || (imageKeys.length ? IM_INPUT_FALLBACK_CAPTION : "") || cap
|
|
|
2641
4381
|
inFlightRetries.clear();
|
|
2642
4382
|
if (restartTimer) clearTimeout(restartTimer);
|
|
2643
4383
|
if (generation) generation.retired = true;
|
|
4384
|
+
for (const controller of panelActionControllers) controller.abort();
|
|
4385
|
+
if (panelActionTasks.size > 0) {
|
|
4386
|
+
let drainTimer;
|
|
4387
|
+
await Promise.race([
|
|
4388
|
+
Promise.allSettled([...panelActionTasks]).then(() => void 0),
|
|
4389
|
+
new Promise((resolve6) => {
|
|
4390
|
+
drainTimer = setTimeout(resolve6, ACTION_RETIRE_DRAIN_MS);
|
|
4391
|
+
drainTimer.unref?.();
|
|
4392
|
+
})
|
|
4393
|
+
]);
|
|
4394
|
+
if (drainTimer) clearTimeout(drainTimer);
|
|
4395
|
+
}
|
|
4396
|
+
actionDeliveryOpen = false;
|
|
4397
|
+
if (panelActionTasks.size) {
|
|
4398
|
+
try {
|
|
4399
|
+
ctx.log(`im-forward: retirement drain expired with ${panelActionTasks.size} panel action(s) pending; terminal card delivery unconfirmed`);
|
|
4400
|
+
} catch {
|
|
4401
|
+
}
|
|
4402
|
+
}
|
|
2644
4403
|
const results = await Promise.allSettled([
|
|
2645
4404
|
...resources.map(
|
|
2646
4405
|
(scope) => Promise.resolve().then(() => scope.dispose())
|
|
@@ -2690,411 +4449,122 @@ ${imagelessCaption || (imageKeys.length ? IM_INPUT_FALLBACK_CAPTION : "") || cap
|
|
|
2690
4449
|
cfg.unattended ? "- note: unanchored DM/@app messages bind to this resident session; reply/thread messages route to their referenced session." : "- note: interactive host \u2014 only reply/thread-attributed or explicitly addressed messages enter (unanchored messages belong to the resident manager, if running)."
|
|
2691
4450
|
);
|
|
2692
4451
|
if (lastSendError)
|
|
2693
|
-
lines.push(
|
|
2694
|
-
`- last send error: ${lastSendError} (at ${new Date(lastSendErrorAt).toISOString()})`
|
|
2695
|
-
);
|
|
2696
|
-
if (anchorFallbacks)
|
|
2697
|
-
lines.push(`- anchor fallbacks to chat root: ${anchorFallbacks}`);
|
|
2698
|
-
if (pendingInputs.length)
|
|
2699
|
-
lines.push(`- pending turn attributions: ${pendingInputs.length}`);
|
|
2700
|
-
if (retryAttempts.size)
|
|
2701
|
-
lines.push(
|
|
2702
|
-
`- inbound retries pending: ${retryTimers.size} (attempts so far: ${Math.max(...retryAttempts.values())})`
|
|
2703
|
-
);
|
|
2704
|
-
commandCtx.ui.notify(lines.join("\n"), "info");
|
|
2705
|
-
}
|
|
2706
|
-
});
|
|
2707
|
-
}
|
|
2708
|
-
|
|
2709
|
-
// builtin/extensions/im-forward/onboarding.ts
|
|
2710
|
-
async function runSetup(ctx, dir, providers, signal, isCurrent = () => !signal.aborted, intent = "first-run", suspendEventConsumer) {
|
|
2711
|
-
const initial = resolveConfig(ctx.cwd, dir);
|
|
2712
|
-
if (initial.problems.length) {
|
|
2713
|
-
ctx.ui.notify(initial.problems.join("\n"), "error");
|
|
2714
|
-
return;
|
|
2715
|
-
}
|
|
2716
|
-
const snapshot = configSnapshot(ctx.cwd, dir);
|
|
2717
|
-
const options = { signal, timeout: 12e4 };
|
|
2718
|
-
if (!providers.length || !isCurrent()) return;
|
|
2719
|
-
let selected;
|
|
2720
|
-
if (intent === "switch-app" && initial.config) {
|
|
2721
|
-
const bound = providers.find((item) => item.id === initial.config?.provider);
|
|
2722
|
-
if (providers.length === 1 && bound) selected = bound;
|
|
2723
|
-
}
|
|
2724
|
-
if (!selected) {
|
|
2725
|
-
const choice = await ctx.ui.select("IM forwarding setup \u2014 platform", [...providers.map((item) => item.label), "Cancel"], options);
|
|
2726
|
-
if (!isCurrent() || !choice || choice === "Cancel") return;
|
|
2727
|
-
selected = providers.find((item) => item.label === choice);
|
|
2728
|
-
}
|
|
2729
|
-
if (!selected || !isCurrent()) return;
|
|
2730
|
-
ctx.ui.notify(`IM forwarding setup \u2014 ${selected.label}`, "info");
|
|
2731
|
-
const settings = await selected.setup({ ui: ctx.ui, cwd: ctx.cwd, signal, suspendEventConsumer }, initial.config?.provider === selected.id ? initial.config.settings : void 0, void 0, intent);
|
|
2732
|
-
if (!isCurrent() || !settings) return;
|
|
2733
|
-
const resolved = selected.resolve(settings);
|
|
2734
|
-
if (!resolved) {
|
|
2735
|
-
ctx.ui.notify("IM forwarding setup: invalid provider settings; nothing was saved.", "error");
|
|
2736
|
-
return;
|
|
2737
|
-
}
|
|
2738
|
-
const profile = typeof settings.larkCliProfile === "string" ? String(settings.larkCliProfile) : void 0;
|
|
2739
|
-
const profileLine = profile ? `
|
|
2740
|
-
lark-cli profile: ${String(profile)}` : "";
|
|
2741
|
-
const appLine = resolved.appId ? `
|
|
2742
|
-
App: ${resolved.appId}` : "";
|
|
2743
|
-
const confirmed = await ctx.ui.confirm("IM forwarding setup", `Platform: ${selected.label}
|
|
2744
|
-
Target: ${resolved.targetId}${appLine}${profileLine}
|
|
2745
|
-
Allowed senders: ${resolved.allowUsers?.join(", ") || "anyone in target"}
|
|
2746
|
-
Save location: ${saveLocation(ctx.cwd, dir)}
|
|
2747
|
-
Enable forwarding and start the connection? No test message will be sent. Saving does not prove connection readiness.`, options);
|
|
2748
|
-
if (!isCurrent() || !confirmed) return;
|
|
2749
|
-
writeConfig(ctx.cwd, dir, { enabled: true, provider: selected.id, settings }, snapshot);
|
|
2750
|
-
if (selected.id === "feishu") {
|
|
2751
|
-
const binary = typeof settings.larkCli === "string" ? String(settings.larkCli) : void 0;
|
|
2752
|
-
void probeCardActionSubscription(ctx, ctx.cwd, binary, profile).catch(() => void 0);
|
|
2753
|
-
}
|
|
2754
|
-
return resolveConfig(ctx.cwd, dir).config ?? void 0;
|
|
2755
|
-
}
|
|
2756
|
-
async function probeCardActionSubscription(ctx, cwd, binaryOverride, profile) {
|
|
2757
|
-
const { spawn: spawn5 } = await import("node:child_process");
|
|
2758
|
-
const binary = binaryOverride ?? await settingsProbeBinary();
|
|
2759
|
-
if (!binary) return;
|
|
2760
|
-
await new Promise((resolve5) => {
|
|
2761
|
-
let settled = false;
|
|
2762
|
-
const done = () => {
|
|
2763
|
-
if (!settled) {
|
|
2764
|
-
settled = true;
|
|
2765
|
-
resolve5();
|
|
2766
|
-
}
|
|
2767
|
-
};
|
|
2768
|
-
const timer = setTimeout(() => {
|
|
2769
|
-
try {
|
|
2770
|
-
child.kill("SIGKILL");
|
|
2771
|
-
} catch {
|
|
2772
|
-
}
|
|
2773
|
-
done();
|
|
2774
|
-
}, 3500);
|
|
2775
|
-
timer.unref?.();
|
|
2776
|
-
const child = spawn5(binary, ["event", "consume", "card.action.trigger", "--as", "bot", ...profile ? ["--profile", profile] : []], { cwd, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
|
|
2777
|
-
child.on("error", () => done());
|
|
2778
|
-
child.on("close", () => done());
|
|
2779
|
-
let out = "";
|
|
2780
|
-
child.stdout.on("data", (chunk) => {
|
|
2781
|
-
out += chunk.toString("utf8").slice(0, 8e3);
|
|
2782
|
-
});
|
|
2783
|
-
child.on("close", () => {
|
|
2784
|
-
const unsubscribed = /requires callbacks not subscribed/i.test(out);
|
|
2785
|
-
if (unsubscribed) {
|
|
2786
|
-
const launcher = /https:\/\/open\.feishu\.cn\/page\/launcher\?[^\s"]+/.exec(out)?.[0];
|
|
2787
|
-
ctx.ui.notify(`Panel buttons require a one-time subscription to card.action.trigger. Without it, the panel still works through text commands.${launcher ? `
|
|
2788
|
-
Open this link and scan the QR code to subscribe: ${launcher}` : "\nIn the developer console, open Events & Callbacks and subscribe to card.action.trigger."}`, "info");
|
|
2789
|
-
}
|
|
2790
|
-
});
|
|
2791
|
-
});
|
|
2792
|
-
}
|
|
2793
|
-
async function settingsProbeBinary() {
|
|
2794
|
-
try {
|
|
2795
|
-
const { spawnSync } = await import("node:child_process");
|
|
2796
|
-
const which = spawnSync(process.platform === "win32" ? "where" : "which", ["lark-cli"], { encoding: "utf8", timeout: 3e3, windowsHide: true });
|
|
2797
|
-
const path12 = which.stdout?.split(/\r?\n/)[0]?.trim();
|
|
2798
|
-
return path12 || void 0;
|
|
2799
|
-
} catch {
|
|
2800
|
-
return void 0;
|
|
2801
|
-
}
|
|
2802
|
-
}
|
|
2803
|
-
|
|
2804
|
-
// builtin/extensions/im-forward/providers/feishu/index.ts
|
|
2805
|
-
import { spawn as spawn4 } from "node:child_process";
|
|
2806
|
-
import * as fs9 from "node:fs";
|
|
2807
|
-
import * as os4 from "node:os";
|
|
2808
|
-
import * as path11 from "node:path";
|
|
2809
|
-
|
|
2810
|
-
// builtin/extensions/im-forward/lark-cli.ts
|
|
2811
|
-
import { spawn as spawn2 } from "node:child_process";
|
|
2812
|
-
import { StringDecoder as StringDecoder2 } from "node:string_decoder";
|
|
2813
|
-
|
|
2814
|
-
// builtin/extensions/im-forward/launch.ts
|
|
2815
|
-
import { spawn } from "node:child_process";
|
|
2816
|
-
import * as fs7 from "node:fs";
|
|
2817
|
-
import * as path7 from "node:path";
|
|
2818
|
-
import { StringDecoder } from "node:string_decoder";
|
|
2819
|
-
function resolveLaunchSpec(explicit, cwd = process.cwd(), platform = process.platform, env = process.env) {
|
|
2820
|
-
const windows = platform === "win32";
|
|
2821
|
-
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)));
|
|
2822
|
-
for (const candidate of candidates) {
|
|
2823
|
-
try {
|
|
2824
|
-
if (!fs7.statSync(candidate).isFile()) continue;
|
|
2825
|
-
const ext = path7.extname(candidate).toLowerCase();
|
|
2826
|
-
if (ext === ".js" || ext === ".mjs") return { command: process.execPath, prefix: [candidate] };
|
|
2827
|
-
if (windows && ext === ".cmd") {
|
|
2828
|
-
const dir = path7.dirname(candidate);
|
|
2829
|
-
for (const root of [path7.join(dir, "node_modules", "@larksuite", "cli"), path7.resolve(dir, "..", "@larksuite", "cli")]) {
|
|
2830
|
-
try {
|
|
2831
|
-
const pkg = JSON.parse(fs7.readFileSync(path7.join(root, "package.json"), "utf8"));
|
|
2832
|
-
const bin = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.["lark-cli"];
|
|
2833
|
-
if (pkg.name !== "@larksuite/cli" || typeof bin !== "string" || bin.replace(/^\.\//, "") !== "scripts/run.js") continue;
|
|
2834
|
-
const entry = path7.join(root, "scripts", "run.js");
|
|
2835
|
-
if (fs7.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
|
|
2836
|
-
} catch {
|
|
2837
|
-
}
|
|
2838
|
-
}
|
|
2839
|
-
continue;
|
|
2840
|
-
}
|
|
2841
|
-
if (windows && ext !== ".exe") continue;
|
|
2842
|
-
fs7.accessSync(candidate, fs7.constants.X_OK);
|
|
2843
|
-
return { command: candidate, prefix: [] };
|
|
2844
|
-
} catch {
|
|
2845
|
-
}
|
|
2846
|
-
}
|
|
2847
|
-
return null;
|
|
2848
|
-
}
|
|
2849
|
-
var treeStops = /* @__PURE__ */ new WeakMap();
|
|
2850
|
-
var hasExited = (child) => child.exitCode != null || child.signalCode != null;
|
|
2851
|
-
function stopOwnedTree(child, signal) {
|
|
2852
|
-
const existing = treeStops.get(child);
|
|
2853
|
-
if (existing) return existing;
|
|
2854
|
-
if (process.platform === "win32" && hasExited(child)) return Promise.resolve(false);
|
|
2855
|
-
const pending = stopOwnedTreeInner(child, signal);
|
|
2856
|
-
treeStops.set(child, pending);
|
|
2857
|
-
void pending.finally(() => treeStops.delete(child));
|
|
2858
|
-
return pending;
|
|
2859
|
-
}
|
|
2860
|
-
function stopOwnedTreeInner(child, signal) {
|
|
2861
|
-
if (process.platform !== "win32" || !child.pid) {
|
|
2862
|
-
try {
|
|
2863
|
-
if (child.pid) process.kill(-child.pid, signal);
|
|
2864
|
-
else child.kill(signal);
|
|
2865
|
-
return Promise.resolve(true);
|
|
2866
|
-
} catch {
|
|
2867
|
-
try {
|
|
2868
|
-
return Promise.resolve(child.kill(signal));
|
|
2869
|
-
} catch {
|
|
2870
|
-
return Promise.resolve(false);
|
|
2871
|
-
}
|
|
2872
|
-
}
|
|
2873
|
-
}
|
|
2874
|
-
return new Promise((resolve5) => {
|
|
2875
|
-
let done = false;
|
|
2876
|
-
let killer;
|
|
2877
|
-
const finish = (ok) => {
|
|
2878
|
-
if (done) return;
|
|
2879
|
-
done = true;
|
|
2880
|
-
clearTimeout(timer);
|
|
2881
|
-
if (!ok && !hasExited(child)) {
|
|
2882
|
-
try {
|
|
2883
|
-
child.kill(signal);
|
|
2884
|
-
} catch {
|
|
2885
|
-
}
|
|
2886
|
-
}
|
|
2887
|
-
resolve5(ok);
|
|
2888
|
-
};
|
|
2889
|
-
const timer = setTimeout(() => {
|
|
2890
|
-
try {
|
|
2891
|
-
killer?.kill();
|
|
2892
|
-
} catch {
|
|
2893
|
-
}
|
|
2894
|
-
finish(false);
|
|
2895
|
-
}, 1500);
|
|
2896
|
-
try {
|
|
2897
|
-
const root = process.env.SystemRoot || process.env.windir || "C:\\Windows";
|
|
2898
|
-
killer = spawn(path7.join(root, "System32", "taskkill.exe"), ["/PID", String(child.pid), "/T", "/F"], { shell: false, windowsHide: true, stdio: "ignore" });
|
|
2899
|
-
killer.on("error", () => finish(false));
|
|
2900
|
-
killer.on("exit", (code) => finish(code === 0));
|
|
2901
|
-
} catch {
|
|
2902
|
-
finish(false);
|
|
2903
|
-
}
|
|
2904
|
-
});
|
|
2905
|
-
}
|
|
2906
|
-
function lineReader(onLine, max = 1024 * 1024) {
|
|
2907
|
-
const decoder = new StringDecoder("utf8");
|
|
2908
|
-
let pending = "";
|
|
2909
|
-
let dropping = false;
|
|
2910
|
-
const accept = (text) => {
|
|
2911
|
-
for (const [i, part] of text.split("\n").entries()) {
|
|
2912
|
-
if (i) {
|
|
2913
|
-
if (!dropping) onLine(pending);
|
|
2914
|
-
pending = "";
|
|
2915
|
-
dropping = false;
|
|
2916
|
-
}
|
|
2917
|
-
if (!dropping) {
|
|
2918
|
-
pending += part;
|
|
2919
|
-
if (pending.length > max) {
|
|
2920
|
-
pending = "";
|
|
2921
|
-
dropping = true;
|
|
2922
|
-
}
|
|
2923
|
-
}
|
|
4452
|
+
lines.push(
|
|
4453
|
+
`- last send error: ${lastSendError} (at ${new Date(lastSendErrorAt).toISOString()})`
|
|
4454
|
+
);
|
|
4455
|
+
if (anchorFallbacks)
|
|
4456
|
+
lines.push(`- anchor fallbacks to chat root: ${anchorFallbacks}`);
|
|
4457
|
+
if (pendingInputs.length)
|
|
4458
|
+
lines.push(`- pending turn attributions: ${pendingInputs.length}`);
|
|
4459
|
+
if (retryAttempts.size)
|
|
4460
|
+
lines.push(
|
|
4461
|
+
`- inbound retries pending: ${retryTimers.size} (attempts so far: ${Math.max(...retryAttempts.values())})`
|
|
4462
|
+
);
|
|
4463
|
+
commandCtx.ui.notify(lines.join("\n"), "info");
|
|
2924
4464
|
}
|
|
2925
|
-
};
|
|
2926
|
-
return { write: (chunk) => accept(decoder.write(chunk)), end() {
|
|
2927
|
-
accept(decoder.end());
|
|
2928
|
-
if (pending && !dropping) onLine(pending);
|
|
2929
|
-
pending = "";
|
|
2930
|
-
} };
|
|
2931
|
-
}
|
|
2932
|
-
var shutdowns = /* @__PURE__ */ new WeakMap();
|
|
2933
|
-
function shutdownConsumer(child) {
|
|
2934
|
-
const existing = shutdowns.get(child);
|
|
2935
|
-
if (existing) return existing;
|
|
2936
|
-
const pending = shutdownConsumerInner(child);
|
|
2937
|
-
shutdowns.set(child, pending);
|
|
2938
|
-
return pending;
|
|
4465
|
+
});
|
|
2939
4466
|
}
|
|
2940
|
-
|
|
2941
|
-
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
let timer;
|
|
2948
|
-
await Promise.race([close, new Promise((resolve5) => {
|
|
2949
|
-
timer = setTimeout(resolve5, ms);
|
|
2950
|
-
})]);
|
|
2951
|
-
clearTimeout(timer);
|
|
2952
|
-
};
|
|
2953
|
-
try {
|
|
2954
|
-
child.stdin?.end();
|
|
2955
|
-
} catch {
|
|
4467
|
+
|
|
4468
|
+
// builtin/extensions/im-forward/onboarding.ts
|
|
4469
|
+
async function runSetup(ctx, dir, providers, signal, isCurrent = () => !signal.aborted, intent = "first-run", suspendEventConsumer) {
|
|
4470
|
+
const initial = resolveConfig(ctx.cwd, dir);
|
|
4471
|
+
if (initial.problems.length) {
|
|
4472
|
+
ctx.ui.notify(initial.problems.join("\n"), "error");
|
|
4473
|
+
return;
|
|
2956
4474
|
}
|
|
2957
|
-
|
|
2958
|
-
|
|
2959
|
-
|
|
2960
|
-
|
|
4475
|
+
const snapshot = configSnapshot(ctx.cwd, dir);
|
|
4476
|
+
const options = { signal, timeout: 12e4 };
|
|
4477
|
+
if (!providers.length || !isCurrent()) return;
|
|
4478
|
+
let selected;
|
|
4479
|
+
if (intent === "switch-app" && initial.config) {
|
|
4480
|
+
const bound = providers.find((item) => item.id === initial.config?.provider);
|
|
4481
|
+
if (providers.length === 1 && bound) selected = bound;
|
|
2961
4482
|
}
|
|
2962
|
-
if (!
|
|
2963
|
-
await
|
|
2964
|
-
|
|
4483
|
+
if (!selected) {
|
|
4484
|
+
const choice = await ctx.ui.select("IM forwarding setup \u2014 platform", [...providers.map((item) => item.label), "Cancel"], options);
|
|
4485
|
+
if (!isCurrent() || !choice || choice === "Cancel") return;
|
|
4486
|
+
selected = providers.find((item) => item.label === choice);
|
|
2965
4487
|
}
|
|
2966
|
-
|
|
2967
|
-
|
|
2968
|
-
|
|
4488
|
+
if (!selected || !isCurrent()) return;
|
|
4489
|
+
ctx.ui.notify(`IM forwarding setup \u2014 ${selected.label}`, "info");
|
|
4490
|
+
const settings = await selected.setup({ ui: ctx.ui, cwd: ctx.cwd, signal, suspendEventConsumer }, initial.config?.provider === selected.id ? initial.config.settings : void 0, void 0, intent);
|
|
4491
|
+
if (!isCurrent() || !settings) return;
|
|
4492
|
+
const resolved = selected.resolve(settings);
|
|
4493
|
+
if (!resolved) {
|
|
4494
|
+
ctx.ui.notify("IM forwarding setup: invalid provider settings; nothing was saved.", "error");
|
|
4495
|
+
return;
|
|
4496
|
+
}
|
|
4497
|
+
const profile = typeof settings.larkCliProfile === "string" ? String(settings.larkCliProfile) : void 0;
|
|
4498
|
+
const profileLine = profile ? `
|
|
4499
|
+
lark-cli profile: ${String(profile)}` : "";
|
|
4500
|
+
const appLine = resolved.appId ? `
|
|
4501
|
+
App: ${resolved.appId}` : "";
|
|
4502
|
+
const confirmed = await ctx.ui.confirm("IM forwarding setup", `Platform: ${selected.label}
|
|
4503
|
+
Target: ${resolved.targetId}${appLine}${profileLine}
|
|
4504
|
+
Allowed senders: ${resolved.allowUsers?.join(", ") || "anyone in target"}
|
|
4505
|
+
Save location: ${saveLocation(ctx.cwd, dir)}
|
|
4506
|
+
Enable forwarding and start the connection? No test message will be sent. Saving does not prove connection readiness.`, options);
|
|
4507
|
+
if (!isCurrent() || !confirmed) return;
|
|
4508
|
+
writeConfig(ctx.cwd, dir, { enabled: true, provider: selected.id, settings }, snapshot);
|
|
4509
|
+
if (selected.id === "feishu") {
|
|
4510
|
+
const binary = typeof settings.larkCli === "string" ? String(settings.larkCli) : void 0;
|
|
4511
|
+
void probeCardActionSubscription(ctx, ctx.cwd, binary, profile).catch(() => void 0);
|
|
4512
|
+
}
|
|
4513
|
+
return resolveConfig(ctx.cwd, dir).config ?? void 0;
|
|
2969
4514
|
}
|
|
2970
|
-
|
|
2971
|
-
|
|
2972
|
-
|
|
2973
|
-
|
|
2974
|
-
|
|
2975
|
-
resolve5({ stdout: "", error: "cancelled" });
|
|
2976
|
-
return;
|
|
2977
|
-
}
|
|
2978
|
-
let child;
|
|
2979
|
-
try {
|
|
2980
|
-
const spec = typeof binary === "string" ? resolveLaunchSpec(binary) ?? (options.spawn ? { command: binary, prefix: [] } : null) : binary;
|
|
2981
|
-
if (!spec) throw new Error("unsupported executable");
|
|
2982
|
-
child = (options.spawn ?? spawn2)(spec.command, [...spec.prefix, ...args], {
|
|
2983
|
-
shell: false,
|
|
2984
|
-
windowsHide: true,
|
|
2985
|
-
stdio: [options.stdin ?? "ignore", "pipe", "pipe"],
|
|
2986
|
-
detached: process.platform !== "win32",
|
|
2987
|
-
...cwd ? { cwd } : {}
|
|
2988
|
-
});
|
|
2989
|
-
} catch {
|
|
2990
|
-
resolve5({ stdout: "", error: "spawn failed" });
|
|
2991
|
-
return;
|
|
2992
|
-
}
|
|
2993
|
-
let stdout = "";
|
|
2994
|
-
let stderr = "";
|
|
4515
|
+
async function probeCardActionSubscription(ctx, cwd, binaryOverride, profile) {
|
|
4516
|
+
const { spawn: spawn6 } = await import("node:child_process");
|
|
4517
|
+
const binary = binaryOverride ?? await settingsProbeBinary();
|
|
4518
|
+
if (!binary) return;
|
|
4519
|
+
await new Promise((resolve6) => {
|
|
2995
4520
|
let settled = false;
|
|
2996
|
-
|
|
2997
|
-
|
|
2998
|
-
|
|
2999
|
-
|
|
3000
|
-
let closeTimer;
|
|
3001
|
-
const finish = (result) => {
|
|
3002
|
-
if (settled) return;
|
|
3003
|
-
settled = true;
|
|
3004
|
-
clearTimeout(timer);
|
|
3005
|
-
clearTimeout(killTimer);
|
|
3006
|
-
clearTimeout(closeTimer);
|
|
3007
|
-
options.signal?.removeEventListener("abort", abort);
|
|
3008
|
-
resolve5(result);
|
|
3009
|
-
};
|
|
3010
|
-
const terminatedResult = () => ({ stdout: termination?.startsWith("timeout") ? stdout : "", error: termination });
|
|
3011
|
-
const stop = (signal) => {
|
|
3012
|
-
try {
|
|
3013
|
-
return stopOwnedTree(child, signal);
|
|
3014
|
-
} catch {
|
|
3015
|
-
return Promise.resolve();
|
|
4521
|
+
const done = () => {
|
|
4522
|
+
if (!settled) {
|
|
4523
|
+
settled = true;
|
|
4524
|
+
resolve6();
|
|
3016
4525
|
}
|
|
3017
4526
|
};
|
|
3018
|
-
const
|
|
3019
|
-
const stopped = () => {
|
|
3020
|
-
treeStopped = true;
|
|
3021
|
-
if (settled) return;
|
|
3022
|
-
if (closed) {
|
|
3023
|
-
finish(terminatedResult());
|
|
3024
|
-
return;
|
|
3025
|
-
}
|
|
3026
|
-
closeTimer = setTimeout(() => {
|
|
3027
|
-
child.stdout?.destroy();
|
|
3028
|
-
child.stderr?.destroy();
|
|
3029
|
-
finish(terminatedResult());
|
|
3030
|
-
}, options.closeGraceMs ?? 1e3);
|
|
3031
|
-
};
|
|
3032
|
-
void stop("SIGKILL").then(stopped, stopped);
|
|
3033
|
-
};
|
|
3034
|
-
const terminate = (reason, graceful = false) => {
|
|
3035
|
-
if (settled || termination) return;
|
|
3036
|
-
termination = reason;
|
|
3037
|
-
clearTimeout(timer);
|
|
3038
|
-
if (graceful) {
|
|
3039
|
-
const stopped = () => {
|
|
3040
|
-
if (closed) {
|
|
3041
|
-
treeStopped = true;
|
|
3042
|
-
finish(terminatedResult());
|
|
3043
|
-
}
|
|
3044
|
-
};
|
|
3045
|
-
void stop("SIGTERM").then(stopped, stopped);
|
|
3046
|
-
if (!settled) killTimer = setTimeout(kill, options.killGraceMs ?? 1e3);
|
|
3047
|
-
} else kill();
|
|
3048
|
-
};
|
|
3049
|
-
const timer = setTimeout(() => terminate(`timeout after ${timeoutMs}ms`, true), timeoutMs);
|
|
3050
|
-
const abort = () => terminate("cancelled");
|
|
3051
|
-
options.signal?.addEventListener("abort", abort, { once: true });
|
|
3052
|
-
if (options.signal?.aborted) abort();
|
|
3053
|
-
const deliverLine = (line) => {
|
|
3054
|
-
if (settled || termination) return;
|
|
4527
|
+
const timer = setTimeout(() => {
|
|
3055
4528
|
try {
|
|
3056
|
-
|
|
4529
|
+
child.kill("SIGKILL");
|
|
3057
4530
|
} catch {
|
|
3058
|
-
terminate("output callback failed");
|
|
3059
|
-
}
|
|
3060
|
-
};
|
|
3061
|
-
const lines = options.onLine ? lineReader(deliverLine, 16384) : void 0;
|
|
3062
|
-
const errorLines = options.onLine ? lineReader(deliverLine, 16384) : void 0;
|
|
3063
|
-
const outDecoder = new StringDecoder2("utf8");
|
|
3064
|
-
const errDecoder = new StringDecoder2("utf8");
|
|
3065
|
-
child.stdout?.on("data", (chunk) => {
|
|
3066
|
-
if (settled || termination) return;
|
|
3067
|
-
lines?.write(chunk);
|
|
3068
|
-
if (termination) return;
|
|
3069
|
-
stdout += outDecoder.write(chunk);
|
|
3070
|
-
if (stdout.length > 8 * 1024 * 1024) {
|
|
3071
|
-
stdout = "";
|
|
3072
|
-
terminate("stdout exceeds 8 MiB limit");
|
|
3073
4531
|
}
|
|
4532
|
+
done();
|
|
4533
|
+
}, 3500);
|
|
4534
|
+
timer.unref?.();
|
|
4535
|
+
const child = spawn6(binary, ["event", "consume", "card.action.trigger", "--as", "bot", ...profile ? ["--profile", profile] : []], { cwd, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
|
|
4536
|
+
child.on("error", () => done());
|
|
4537
|
+
child.on("close", () => done());
|
|
4538
|
+
let out = "";
|
|
4539
|
+
child.stdout.on("data", (chunk) => {
|
|
4540
|
+
out += chunk.toString("utf8").slice(0, 8e3);
|
|
3074
4541
|
});
|
|
3075
|
-
child.
|
|
3076
|
-
|
|
3077
|
-
|
|
3078
|
-
|
|
3079
|
-
|
|
3080
|
-
|
|
3081
|
-
child.on("close", (code) => {
|
|
3082
|
-
closed = true;
|
|
3083
|
-
if (settled) return;
|
|
3084
|
-
if (termination) {
|
|
3085
|
-
if (treeStopped) finish(terminatedResult());
|
|
3086
|
-
return;
|
|
4542
|
+
child.on("close", () => {
|
|
4543
|
+
const unsubscribed = /requires callbacks not subscribed/i.test(out);
|
|
4544
|
+
if (unsubscribed) {
|
|
4545
|
+
const launcher = /https:\/\/open\.feishu\.cn\/page\/launcher\?[^\s"]+/.exec(out)?.[0];
|
|
4546
|
+
ctx.ui.notify(`Panel buttons require a one-time subscription to card.action.trigger. Without it, the panel still works through text commands.${launcher ? `
|
|
4547
|
+
Open this link and scan the QR code to subscribe: ${launcher}` : "\nIn the developer console, open Events & Callbacks and subscribe to card.action.trigger."}`, "info");
|
|
3087
4548
|
}
|
|
3088
|
-
stdout += outDecoder.end();
|
|
3089
|
-
stderr += errDecoder.end();
|
|
3090
|
-
lines?.end();
|
|
3091
|
-
errorLines?.end();
|
|
3092
|
-
if (termination) return;
|
|
3093
|
-
if (code === 0 && (stdout.trim() || options.allowEmpty)) finish({ stdout });
|
|
3094
|
-
else finish({ stdout, error: `exit ${code}${stderr ? `: ${stderr.slice(-300).trim()}` : ""}` });
|
|
3095
4549
|
});
|
|
3096
4550
|
});
|
|
3097
4551
|
}
|
|
4552
|
+
async function settingsProbeBinary() {
|
|
4553
|
+
try {
|
|
4554
|
+
const { spawnSync } = await import("node:child_process");
|
|
4555
|
+
const which = spawnSync(process.platform === "win32" ? "where" : "which", ["lark-cli"], { encoding: "utf8", timeout: 3e3, windowsHide: true });
|
|
4556
|
+
const path13 = which.stdout?.split(/\r?\n/)[0]?.trim();
|
|
4557
|
+
return path13 || void 0;
|
|
4558
|
+
} catch {
|
|
4559
|
+
return void 0;
|
|
4560
|
+
}
|
|
4561
|
+
}
|
|
4562
|
+
|
|
4563
|
+
// builtin/extensions/im-forward/providers/feishu/index.ts
|
|
4564
|
+
import { spawn as spawn5 } from "node:child_process";
|
|
4565
|
+
import * as fs10 from "node:fs";
|
|
4566
|
+
import * as os4 from "node:os";
|
|
4567
|
+
import * as path12 from "node:path";
|
|
3098
4568
|
|
|
3099
4569
|
// builtin/extensions/im-forward/providers/feishu/card.ts
|
|
3100
4570
|
var COLOR_TEMPLATE = {
|
|
@@ -3199,17 +4669,17 @@ function extractImageKey(content) {
|
|
|
3199
4669
|
}
|
|
3200
4670
|
|
|
3201
4671
|
// builtin/extensions/im-forward/providers/feishu/setup.ts
|
|
3202
|
-
import * as
|
|
3203
|
-
import * as
|
|
4672
|
+
import * as fs9 from "node:fs";
|
|
4673
|
+
import * as path11 from "node:path";
|
|
3204
4674
|
|
|
3205
4675
|
// builtin/extensions/im-forward/browser.ts
|
|
3206
|
-
import { spawn as
|
|
3207
|
-
import
|
|
4676
|
+
import { spawn as spawn4 } from "node:child_process";
|
|
4677
|
+
import path9 from "node:path";
|
|
3208
4678
|
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 }";
|
|
3209
4679
|
function browserLaunch(platform = process.platform, root = process.env.SystemRoot || "C:\\Windows") {
|
|
3210
4680
|
if (platform === "win32") {
|
|
3211
4681
|
if (!/^[A-Za-z]:\\/.test(root) || /[\x00-\x1f]/.test(root)) return;
|
|
3212
|
-
return { command:
|
|
4682
|
+
return { command: path9.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(browserScript, "utf16le").toString("base64")], stdin: true };
|
|
3213
4683
|
}
|
|
3214
4684
|
if (platform === "darwin") return { command: "/usr/bin/open", args: ["--"], stdin: false };
|
|
3215
4685
|
if (platform === "linux") return { command: "/usr/bin/xdg-open", args: [], stdin: false };
|
|
@@ -3218,7 +4688,7 @@ async function openBrowser(url, signal, seam = {}) {
|
|
|
3218
4688
|
if (signal.aborted || !/^https:\/\/[^\s\x00-\x1f\x7f]+$/.test(url)) return "failed";
|
|
3219
4689
|
const spec = browserLaunch(seam.platform);
|
|
3220
4690
|
if (!spec) return "failed";
|
|
3221
|
-
return new Promise((
|
|
4691
|
+
return new Promise((resolve6) => {
|
|
3222
4692
|
let child;
|
|
3223
4693
|
let settled = false;
|
|
3224
4694
|
let stopping = false;
|
|
@@ -3233,7 +4703,7 @@ async function openBrowser(url, signal, seam = {}) {
|
|
|
3233
4703
|
child?.stdin?.destroy();
|
|
3234
4704
|
child?.stdout?.destroy();
|
|
3235
4705
|
child?.stderr?.destroy();
|
|
3236
|
-
|
|
4706
|
+
resolve6(result);
|
|
3237
4707
|
};
|
|
3238
4708
|
const stop = () => {
|
|
3239
4709
|
if (settled || stopping) return;
|
|
@@ -3251,7 +4721,7 @@ async function openBrowser(url, signal, seam = {}) {
|
|
|
3251
4721
|
const abort = () => stop();
|
|
3252
4722
|
const timer = setTimeout(stop, seam.timeoutMs ?? 1e4);
|
|
3253
4723
|
try {
|
|
3254
|
-
child = (seam.spawn ??
|
|
4724
|
+
child = (seam.spawn ?? spawn4)(spec.command, spec.stdin ? spec.args : [...spec.args, url], { shell: false, windowsHide: true, detached: process.platform !== "win32", stdio: [spec.stdin ? "pipe" : "ignore", "ignore", "ignore"] });
|
|
3255
4725
|
child.on("error", stop);
|
|
3256
4726
|
child.on("close", (code) => {
|
|
3257
4727
|
closed = true;
|
|
@@ -3268,24 +4738,24 @@ async function openBrowser(url, signal, seam = {}) {
|
|
|
3268
4738
|
}
|
|
3269
4739
|
|
|
3270
4740
|
// builtin/extensions/im-forward/existing-app-terminal.ts
|
|
3271
|
-
import
|
|
4741
|
+
import path10 from "node:path";
|
|
3272
4742
|
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 }";
|
|
3273
4743
|
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 }";
|
|
3274
4744
|
function existingAppTerminal(binary, cwd, platform = process.platform, root = process.env.SystemRoot || "C:\\Windows") {
|
|
3275
4745
|
if (platform !== "win32" || !/^[A-Za-z]:\\/.test(root) || /[\x00-\x1f]/.test(root)) return null;
|
|
3276
4746
|
const payload = Buffer.from(JSON.stringify({ command: binary.command, args: [...binary.prefix, "config", "init", "--brand", "feishu"], cwd }), "utf8").toString("base64");
|
|
3277
4747
|
const script = existingAppOuterTemplate.replace("__PAYLOAD__", payload);
|
|
3278
|
-
return { command:
|
|
4748
|
+
return { command: path10.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), prefix: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")] };
|
|
3279
4749
|
}
|
|
3280
4750
|
|
|
3281
4751
|
// builtin/extensions/im-forward/providers/feishu/setup.ts
|
|
3282
4752
|
function findNpmCli() {
|
|
3283
|
-
const dirs = [
|
|
3284
|
-
for (const dir of dirs) for (const root of [
|
|
4753
|
+
const dirs = [path11.dirname(process.execPath), ...(process.env.PATH ?? "").split(path11.delimiter)];
|
|
4754
|
+
for (const dir of dirs) for (const root of [path11.join(dir, "node_modules", "npm"), path11.resolve(dir, "..", "lib", "node_modules", "npm")]) {
|
|
3285
4755
|
try {
|
|
3286
|
-
const pkg = JSON.parse(
|
|
3287
|
-
const entry =
|
|
3288
|
-
if (pkg.name === "npm" && pkg.bin?.npm === "bin/npm-cli.js" &&
|
|
4756
|
+
const pkg = JSON.parse(fs9.readFileSync(path11.join(root, "package.json"), "utf8"));
|
|
4757
|
+
const entry = path11.join(root, "bin", "npm-cli.js");
|
|
4758
|
+
if (pkg.name === "npm" && pkg.bin?.npm === "bin/npm-cli.js" && fs9.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
|
|
3289
4759
|
} catch {
|
|
3290
4760
|
}
|
|
3291
4761
|
}
|
|
@@ -3961,19 +5431,19 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
|
|
|
3961
5431
|
return Array.isArray(data?.messages) ? data.messages.flatMap((message) => isRecord(message) && typeof message.message_id === "string" ? [message.message_id] : []) : null;
|
|
3962
5432
|
},
|
|
3963
5433
|
async downloadImage(messageId, image, index) {
|
|
3964
|
-
const directory =
|
|
3965
|
-
const cleanup = () =>
|
|
5434
|
+
const directory = fs10.mkdtempSync(path12.join(os4.tmpdir(), "pie-im-forward-"));
|
|
5435
|
+
const cleanup = () => fs10.rmSync(directory, { recursive: true, force: true });
|
|
3966
5436
|
try {
|
|
3967
5437
|
const name = `image-${index + 1}.png`;
|
|
3968
5438
|
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 });
|
|
3969
5439
|
if (result.error || !parseLarkCliEnvelope(result.stdout).ok) throw new Error("Image download failed");
|
|
3970
|
-
let target =
|
|
3971
|
-
if (
|
|
5440
|
+
let target = path12.join(directory, name);
|
|
5441
|
+
if (fs10.statSync(target).size > 10 * 1024 * 1024) throw new Error("Image exceeds 10 MiB");
|
|
3972
5442
|
const detected = readImageFormat(target);
|
|
3973
5443
|
if (detected.ext === ".bin") throw new Error("Unsupported image format");
|
|
3974
5444
|
if (detected.ext !== ".png") {
|
|
3975
|
-
const corrected =
|
|
3976
|
-
|
|
5445
|
+
const corrected = path12.join(directory, `image-${index + 1}${detected.ext}`);
|
|
5446
|
+
fs10.renameSync(target, corrected);
|
|
3977
5447
|
target = corrected;
|
|
3978
5448
|
}
|
|
3979
5449
|
return { file: { path: target, displayName: `feishu-image-${index + 1}${detected.ext}` }, cleanup };
|
|
@@ -4012,7 +5482,7 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
|
|
|
4012
5482
|
optionalRespawnTimers.set(eventKey, timer);
|
|
4013
5483
|
};
|
|
4014
5484
|
const spawnConsume = (eventKey, map, required) => {
|
|
4015
|
-
const child2 =
|
|
5485
|
+
const child2 = spawn5(binary.command, [...binary.prefix, "event", "consume", eventKey, "--as", "bot", ...profile ? ["--profile", profile] : []], { stdio: ["pipe", "pipe", "pipe"], shell: false, windowsHide: true, detached: process.platform !== "win32" });
|
|
4016
5486
|
child2.stdin?.on("error", () => void 0);
|
|
4017
5487
|
const output = lineReader((line) => {
|
|
4018
5488
|
if (!closed) {
|
|
@@ -4153,18 +5623,18 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
|
|
|
4153
5623
|
const appId = await canonicalAppIdNow();
|
|
4154
5624
|
if (!appId) return void 0;
|
|
4155
5625
|
const larkHome = process.env.PIE_LARK_CLI_HOME && process.env.PIE_LARK_CLI_HOME.trim() ? process.env.PIE_LARK_CLI_HOME : os4.homedir();
|
|
4156
|
-
const logPath =
|
|
5626
|
+
const logPath = path12.join(larkHome, ".lark-cli", "events", appId, "bus.log");
|
|
4157
5627
|
let tail;
|
|
4158
5628
|
try {
|
|
4159
|
-
const fd =
|
|
5629
|
+
const fd = fs10.openSync(logPath, "r");
|
|
4160
5630
|
try {
|
|
4161
|
-
const size =
|
|
5631
|
+
const size = fs10.fstatSync(fd).size;
|
|
4162
5632
|
const start = Math.max(0, size - 64 * 1024);
|
|
4163
5633
|
const buf = Buffer.alloc(size - start);
|
|
4164
|
-
|
|
5634
|
+
fs10.readSync(fd, buf, 0, buf.length, start);
|
|
4165
5635
|
tail = buf.toString("utf8");
|
|
4166
5636
|
} finally {
|
|
4167
|
-
|
|
5637
|
+
fs10.closeSync(fd);
|
|
4168
5638
|
}
|
|
4169
5639
|
} catch {
|
|
4170
5640
|
return void 0;
|
|
@@ -4215,6 +5685,78 @@ function imForward(ctx) {
|
|
|
4215
5685
|
function initializeImForward(ctx, providers = implementedProviders) {
|
|
4216
5686
|
const caps = ctx.capabilities ?? { editorInjection: ctx.hasUI === true, interactiveUI: ctx.hasUI === true };
|
|
4217
5687
|
if (!caps.editorInjection) return;
|
|
5688
|
+
if (process.env.PIE_PROC_CURATED_NAME === "manager" && typeof ctx.registerTool === "function") {
|
|
5689
|
+
ctx.registerTool({
|
|
5690
|
+
name: "panel_action",
|
|
5691
|
+
label: "Panel custom actions",
|
|
5692
|
+
description: "Manage script-backed custom buttons on the IM /panel card (panel-actions, 11-23). THE MODEL: a button triggers a PRE-WRITTEN script \u2014 capability sedimentation. When a group member asks for something repeatable, delegate the script development to a worker (pie_proc oneshot): the worker writes the script into " + panelActionsRoot() + "/ and tests it; THEN you register the button here. Script contract: interpreter by extension (.mjs/.js\u2192node, .sh\u2192bash, .py\u2192python3); context arrives as env (PIE_ACTION_ID, PIE_ACTION_TRIGGER_NAME/OPEN_ID, PIE_ACTION_CHAT_ID, PIE_ACTION_PAYLOAD as JSON, and on worker-scoped buttons PIE_ACTION_WORKER + PIE_ACTION_WORKER_DIR); stdout IS the result (markdown, posted to IM); exit 0 = success, non-zero = failure. Scope: 'manager' (on the main panel card), 'worker' (on EVERY worker's card \u2014 one generic definition, runs with the clicked worker's identity/project dir), 'worker:<name>' (pinned to one worker). Before add, REPEAT the button's label/script/scope back to the requester for confirmation (the confirmation is the audit trail). Governance is attribution (creator + per-trigger byline + audit log), not gates \u2014 record creatorName/creatorOpenId from the conversation. remove keeps the script file (only the button goes away).",
|
|
5693
|
+
parameters: Type.Object({
|
|
5694
|
+
action: Type.Union([Type.Literal("add"), Type.Literal("remove"), Type.Literal("list")], { description: "add | remove | list" }),
|
|
5695
|
+
label: Type.Optional(Type.String({ description: "add: button label (emoji welcome, \u226440 chars)" })),
|
|
5696
|
+
script: Type.Optional(Type.String({ description: "add: script path (must EXIST and be tested \u2014 develop it via a worker first)" })),
|
|
5697
|
+
scope: Type.Optional(Type.String({ description: "add: manager (default) | worker | worker:<name>" })),
|
|
5698
|
+
cwd: Type.Optional(Type.String({ description: "add: script working directory (default: the script's own dir)" })),
|
|
5699
|
+
payload: Type.Optional(Type.Unknown({ description: "add: static JSON payload baked into the button (one script, several buttons)" })),
|
|
5700
|
+
timeoutMs: Type.Optional(Type.Number({ description: "add: per-run timeout (5s..60min, default 5min)", minimum: 5e3, maximum: 36e5 })),
|
|
5701
|
+
id: Type.Optional(Type.String({ description: "add: explicit id ([a-z0-9-], max 32); default: slug from label. remove: the id to delete" })),
|
|
5702
|
+
creatorName: Type.Optional(Type.String({ description: "add: display name of the group member who asked (attribution)" })),
|
|
5703
|
+
creatorOpenId: Type.Optional(Type.String({ description: "add: open_id of the requester when known (attribution)" }))
|
|
5704
|
+
}),
|
|
5705
|
+
risk: { riskClass: "config_write", requiresPermission: false, externalSideEffect: false, readsNetwork: false, writesNetwork: false, concurrencySafe: false },
|
|
5706
|
+
renderHint: { summary: (args) => `panel_action ${String(args.action)}${args.label ? ` ${String(args.label)}` : ""}${args.id ? ` ${String(args.id)}` : ""}` },
|
|
5707
|
+
execute: async (args) => {
|
|
5708
|
+
const text = (body, isError = false) => ({ content: [{ type: "text", text: body }], details: {}, ...isError ? { isError: true } : {} });
|
|
5709
|
+
const act = args.action;
|
|
5710
|
+
if (act === "list") {
|
|
5711
|
+
const { actions, error } = readRegistry();
|
|
5712
|
+
if (error) return text(error, true);
|
|
5713
|
+
if (actions.length === 0) return text(`No custom panel actions registered (registry: ${panelActionsRoot()}/registry.json).`);
|
|
5714
|
+
const rows = actions.map((a) => ({
|
|
5715
|
+
id: a.id,
|
|
5716
|
+
label: a.label,
|
|
5717
|
+
scope: a.scope,
|
|
5718
|
+
script: a.script,
|
|
5719
|
+
...a.cwd ? { cwd: a.cwd } : {},
|
|
5720
|
+
runs: a.runs,
|
|
5721
|
+
...a.lastRunBy ? { lastRunBy: a.lastRunBy } : {},
|
|
5722
|
+
...a.creator?.name ? { creator: a.creator.name } : {}
|
|
5723
|
+
}));
|
|
5724
|
+
return text(JSON.stringify(rows, null, 2));
|
|
5725
|
+
}
|
|
5726
|
+
if (act === "add") {
|
|
5727
|
+
const label = typeof args.label === "string" ? args.label : "";
|
|
5728
|
+
const script = typeof args.script === "string" ? args.script : "";
|
|
5729
|
+
if (!label.trim() || !script.trim()) return text("add requires label and script (develop the script via a worker FIRST \u2014 the path must exist)", true);
|
|
5730
|
+
const scope = typeof args.scope === "string" && args.scope.trim() ? args.scope.trim() : "manager";
|
|
5731
|
+
if (!isValidScope(scope)) return text(`invalid scope "${scope}" (manager | worker | worker:<name>)`, true);
|
|
5732
|
+
try {
|
|
5733
|
+
const created = addAction({
|
|
5734
|
+
label,
|
|
5735
|
+
script,
|
|
5736
|
+
scope,
|
|
5737
|
+
...typeof args.cwd === "string" && args.cwd.trim() ? { cwd: args.cwd } : {},
|
|
5738
|
+
...args.payload !== void 0 ? { payload: args.payload } : {},
|
|
5739
|
+
...typeof args.timeoutMs === "number" ? { timeoutMs: args.timeoutMs } : {},
|
|
5740
|
+
...typeof args.id === "string" && args.id.trim() ? { id: args.id.trim() } : {},
|
|
5741
|
+
...args.creatorName || args.creatorOpenId ? { creator: { ...typeof args.creatorOpenId === "string" ? { openId: args.creatorOpenId } : {}, ...typeof args.creatorName === "string" ? { name: args.creatorName } : {} } } : {}
|
|
5742
|
+
});
|
|
5743
|
+
return text(`\u2705 \u6309\u94AE\u5DF2\u6CE8\u518C:\u3010${created.label}\u3011id=\`${created.id}\` scope=${created.scope}
|
|
5744
|
+
|
|
5745
|
+
\u4E0B\u6B21 /panel \u5373\u53EF\u89C1(\u4E3B\u5361\u6309\u4F7F\u7528\u9891\u6B21\u5185\u8054,\u6216 \u26A1 \u5168\u90E8\u52A8\u4F5C \u91CC)\u3002\u70B9\u51FB\u5373\u8DD1\u811A\u672C,\u96F6 LLM\u3002`);
|
|
5746
|
+
} catch (error) {
|
|
5747
|
+
return text(`add failed: ${error instanceof Error ? error.message : String(error)}`, true);
|
|
5748
|
+
}
|
|
5749
|
+
}
|
|
5750
|
+
if (act === "remove") {
|
|
5751
|
+
const id = typeof args.id === "string" ? args.id.trim() : "";
|
|
5752
|
+
if (!id) return text("remove requires id", true);
|
|
5753
|
+
const removed = removeAction(id);
|
|
5754
|
+
return removed ? text(`\u{1F5D1} \u6309\u94AE\u3010${removed.label}\u3011(${id}) \u5DF2\u4ECE\u6CE8\u518C\u8868\u79FB\u9664(\u811A\u672C\u6587\u4EF6\u4FDD\u7559\u5728\u78C1\u76D8,\u6309\u94AE\u4E0D\u518D\u51FA\u73B0)\u3002`) : text(`action id "${id}" not found`, true);
|
|
5755
|
+
}
|
|
5756
|
+
return text(`unknown action "${act}"`, true);
|
|
5757
|
+
}
|
|
5758
|
+
});
|
|
5759
|
+
}
|
|
4218
5760
|
const interactive = caps.interactiveUI;
|
|
4219
5761
|
const dir = resolveConfigDir();
|
|
4220
5762
|
let disposed = false;
|
|
@@ -4290,7 +5832,7 @@ function initializeImForward(ctx, providers = implementedProviders) {
|
|
|
4290
5832
|
return () => {
|
|
4291
5833
|
};
|
|
4292
5834
|
};
|
|
4293
|
-
createRuntime(bridge, { enabled: config.enabled, provider: config.provider, label: provider.label, targetId: settings.targetId, targetKind: settings.targetKind, allowUsers: settings.allowUsers, retryBackoffMs: config.retryBackoffMs, ...settings.appId ? { appId: settings.appId } : {}, ...typeof settings.larkCliProfile === "string" && settings.larkCliProfile.trim() ? { profile: settings.larkCliProfile.trim() } : {}, ...settings.groupAccess ? { groupAccess: settings.groupAccess } : {}, ...caps.unattended ? { unattended: true } : {} }, connection, () => liveEnabled(config), (next) => {
|
|
5835
|
+
createRuntime(bridge, { enabled: config.enabled, provider: config.provider, label: provider.label, targetId: settings.targetId, targetKind: settings.targetKind, allowUsers: settings.allowUsers, retryBackoffMs: config.retryBackoffMs, ...settings.appId ? { appId: settings.appId } : {}, ...typeof settings.larkCliProfile === "string" && settings.larkCliProfile.trim() ? { profile: settings.larkCliProfile.trim() } : {}, ...typeof settings.larkCli === "string" && settings.larkCli.trim() ? { larkCliPath: settings.larkCli.trim() } : {}, ...settings.groupAccess ? { groupAccess: settings.groupAccess } : {}, ...caps.unattended ? { unattended: true } : {} }, connection, () => liveEnabled(config), (next) => {
|
|
4294
5836
|
const latest = readLiveConfig(ctx.cwd, dir);
|
|
4295
5837
|
if (latest.problems.length || !latest.config || configurationIdentity(latest.config) !== configurationIdentity(config)) throw new Error("Configuration changed; setup required");
|
|
4296
5838
|
writeConfig(ctx.cwd, dir, { enabled: next });
|