@cydm/pie 4.6.0 → 4.7.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.
@@ -32,18 +32,24 @@ import {
32
32
  truncateMarkdown,
33
33
  tryClaimConsumer,
34
34
  writeConfig
35
- } from "../../../chunks/chunk-2CJIENLY.js";
35
+ } from "../../../chunks/chunk-7UAUDXZW.js";
36
+ import {
37
+ readProcessCommandLine
38
+ } from "../../../chunks/chunk-7RJXKN7N.js";
36
39
  import {
37
40
  detectImageMime,
38
41
  readImageFormat
39
42
  } from "../../../chunks/chunk-F7EBZTZO.js";
40
43
  import "../../../chunks/chunk-ZPJ3BNQB.js";
44
+ import {
45
+ Type
46
+ } from "../../../chunks/chunk-XXGYUYXI.js";
41
47
  import "../../../chunks/chunk-LZQXQOPJ.js";
42
48
 
43
49
  // builtin/extensions/im-forward/runtime.ts
44
50
  import * as crypto from "node:crypto";
45
- import * as fs6 from "node:fs";
46
- import { basename, join as pathJoin, resolve as pathResolve, join as join7, dirname as pathDirname } from "node:path";
51
+ import * as fs8 from "node:fs";
52
+ import { basename, join as pathJoin, resolve as pathResolve, join as join9, dirname as pathDirname } from "node:path";
47
53
  import * as os3 from "node:os";
48
54
 
49
55
  // builtin/extensions/im-forward/thread-registry.ts
@@ -101,18 +107,46 @@ function recordFor(threadKey, sessionId) {
101
107
  }
102
108
  function takeOver(threadKey, _dead, sessionId) {
103
109
  const file = ownerPath(threadKey);
110
+ const tmp = path.join(threadsDir(), `.new-${randomUUID()}.json`);
111
+ const record = recordFor(threadKey, sessionId);
112
+ try {
113
+ const fd = fs.openSync(tmp, "wx", 384);
114
+ try {
115
+ fs.writeFileSync(fd, JSON.stringify(record));
116
+ fs.fsyncSync(fd);
117
+ } finally {
118
+ fs.closeSync(fd);
119
+ }
120
+ } catch {
121
+ try {
122
+ fs.rmSync(tmp, { force: true });
123
+ } catch {
124
+ }
125
+ return { claimed: false, reason: "thread registry unavailable", transient: true };
126
+ }
104
127
  try {
105
- fs.rmSync(file, { force: true });
128
+ fs.renameSync(tmp, file);
129
+ return { claimed: true, ownerSessionId: sessionId };
106
130
  } catch {
131
+ try {
132
+ fs.rmSync(tmp, { force: true });
133
+ } catch {
134
+ }
107
135
  return { claimed: false, reason: "thread registry unavailable", transient: true };
108
136
  }
109
- return writeNew(threadKey, sessionId);
110
137
  }
111
138
  function decide(owner, threadKey, sessionId) {
112
139
  if (owner.sessionId === sessionId && owner.runtimeId === RUNTIME_ID) {
113
140
  return { claimed: true, ownerSessionId: sessionId };
114
141
  }
115
142
  if (owner.pid > 0 && !pidAlive(owner.pid)) {
143
+ if (owner.sessionId !== sessionId) {
144
+ return {
145
+ claimed: false,
146
+ reason: `thread owned by session ${owner.sessionId} (owner offline)`,
147
+ ownerSessionId: owner.sessionId
148
+ };
149
+ }
116
150
  return takeOver(threadKey, owner, sessionId);
117
151
  }
118
152
  return {
@@ -261,90 +295,1094 @@ function acquireThreadLock(threadKey) {
261
295
  try {
262
296
  fs.mkdirSync(candidate, { mode: 448 });
263
297
  } catch {
264
- return { acquired: false, reason: "thread registry unavailable", transient: true };
298
+ return { acquired: false, reason: "thread registry unavailable", transient: true };
299
+ }
300
+ try {
301
+ writeHolderEntry(candidate, token);
302
+ } catch {
303
+ try {
304
+ fs.rmSync(candidate, { recursive: true, force: true });
305
+ } catch {
306
+ }
307
+ return { acquired: false, reason: "thread registry unavailable", transient: true };
308
+ }
309
+ const deadline = Date.now() + 5e3;
310
+ for (; ; ) {
311
+ try {
312
+ fs.renameSync(candidate, lock);
313
+ acquiredLocks.set(threadKey, token);
314
+ return { acquired: true };
315
+ } catch (error) {
316
+ const code = error?.code;
317
+ if (code !== "EEXIST" && code !== "ENOTEMPTY" && code !== "EPERM" && code !== "ENOTDIR") {
318
+ return { acquired: false, reason: "thread registry unavailable", transient: true };
319
+ }
320
+ if (Date.now() > deadline) return { acquired: false, reason: "thread lock busy", transient: true };
321
+ try {
322
+ retireStaleLock(lock);
323
+ } catch {
324
+ }
325
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1 + Math.floor(Math.random() * 3));
326
+ }
327
+ }
328
+ } finally {
329
+ try {
330
+ fs.rmSync(candidate, { recursive: true, force: true });
331
+ } catch {
332
+ }
333
+ }
334
+ }
335
+ function releaseThreadLock(threadKey) {
336
+ const token = acquiredLocks.get(threadKey);
337
+ if (token === void 0) return;
338
+ acquiredLocks.delete(threadKey);
339
+ const lock = lockDirPath(threadKey);
340
+ try {
341
+ fs.unlinkSync(path.join(lock, `held.${token}`));
342
+ } catch {
343
+ }
344
+ try {
345
+ const remaining = fs.readdirSync(lock);
346
+ if (remaining.length === 0) fs.rmdirSync(lock);
347
+ } catch {
348
+ }
349
+ }
350
+ function threadOwner(input) {
351
+ const threadKey = encodeThreadKey(input);
352
+ let read;
353
+ try {
354
+ read = readOwner(threadKey);
355
+ } catch {
356
+ return { unavailable: true };
357
+ }
358
+ if (read.corrupt) return { corrupt: true };
359
+ if (!read.owner) return {};
360
+ if (read.owner.pid > 0 && !pidAlive(read.owner.pid)) {
361
+ return { sessionId: read.owner.sessionId, ownerOffline: true };
362
+ }
363
+ return { sessionId: read.owner.sessionId };
364
+ }
365
+
366
+ // builtin/extensions/im-forward/panel.ts
367
+ import * as fs4 from "node:fs";
368
+ import * as os2 from "node:os";
369
+ import * as path5 from "node:path";
370
+ import { fileURLToPath } from "node:url";
371
+
372
+ // builtin/extensions/im-forward/discovery.ts
373
+ import * as os from "node:os";
374
+ import * as path2 from "node:path";
375
+ function ipcDiscoveryRoot() {
376
+ const home = os.homedir() || process.env.HOME || process.env.USERPROFILE || "/tmp";
377
+ const override = process.env.PIE_IPC_CONFIG_DIR;
378
+ const agentDir = process.env.PIE_CODING_AGENT_DIR?.trim();
379
+ const raw = override !== void 0 ? override : agentDir || path2.join(home, ".pie");
380
+ const configDir = process.platform === "win32" ? raw : path2.resolve(raw === "~" ? home : raw.startsWith("~/") ? path2.join(home, raw.slice(2)) : raw);
381
+ return path2.join(configDir, "run", "ipc");
382
+ }
383
+
384
+ // builtin/extensions/im-forward/panel-actions.ts
385
+ import { spawn as spawn3 } from "node:child_process";
386
+ import { StringDecoder as StringDecoder3 } from "node:string_decoder";
387
+ import * as fs3 from "node:fs";
388
+ import * as path4 from "node:path";
389
+
390
+ // builtin/extensions/im-forward/lark-cli.ts
391
+ import { spawn as spawn2 } from "node:child_process";
392
+ import { StringDecoder as StringDecoder2 } from "node:string_decoder";
393
+
394
+ // builtin/extensions/im-forward/launch.ts
395
+ import { spawn } from "node:child_process";
396
+ import * as fs2 from "node:fs";
397
+ import * as path3 from "node:path";
398
+ import { StringDecoder } from "node:string_decoder";
399
+ function resolveLaunchSpec(explicit, cwd = process.cwd(), platform = process.platform, env = process.env) {
400
+ const windows = platform === "win32";
401
+ 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)));
402
+ for (const candidate of candidates) {
403
+ try {
404
+ if (!fs2.statSync(candidate).isFile()) continue;
405
+ const ext = path3.extname(candidate).toLowerCase();
406
+ if (ext === ".js" || ext === ".mjs") return { command: process.execPath, prefix: [candidate] };
407
+ if (windows && ext === ".cmd") {
408
+ const dir = path3.dirname(candidate);
409
+ for (const root of [path3.join(dir, "node_modules", "@larksuite", "cli"), path3.resolve(dir, "..", "@larksuite", "cli")]) {
410
+ try {
411
+ const pkg = JSON.parse(fs2.readFileSync(path3.join(root, "package.json"), "utf8"));
412
+ const bin = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.["lark-cli"];
413
+ if (pkg.name !== "@larksuite/cli" || typeof bin !== "string" || bin.replace(/^\.\//, "") !== "scripts/run.js") continue;
414
+ const entry = path3.join(root, "scripts", "run.js");
415
+ if (fs2.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
416
+ } catch {
417
+ }
418
+ }
419
+ continue;
420
+ }
421
+ if (windows && ext !== ".exe") continue;
422
+ fs2.accessSync(candidate, fs2.constants.X_OK);
423
+ return { command: candidate, prefix: [] };
424
+ } catch {
425
+ }
426
+ }
427
+ return null;
428
+ }
429
+ var treeStops = /* @__PURE__ */ new WeakMap();
430
+ var hasExited = (child) => child.exitCode != null || child.signalCode != null;
431
+ function stopOwnedTree(child, signal) {
432
+ const existing = treeStops.get(child);
433
+ if (existing) return existing;
434
+ if (process.platform === "win32" && hasExited(child)) return Promise.resolve(false);
435
+ const pending = stopOwnedTreeInner(child, signal);
436
+ treeStops.set(child, pending);
437
+ void pending.finally(() => treeStops.delete(child));
438
+ return pending;
439
+ }
440
+ function stopOwnedTreeInner(child, signal) {
441
+ if (process.platform !== "win32" || !child.pid) {
442
+ try {
443
+ if (child.pid) process.kill(-child.pid, signal);
444
+ else child.kill(signal);
445
+ return Promise.resolve(true);
446
+ } catch {
447
+ try {
448
+ return Promise.resolve(child.kill(signal));
449
+ } catch {
450
+ return Promise.resolve(false);
451
+ }
452
+ }
453
+ }
454
+ return new Promise((resolve6) => {
455
+ let done = false;
456
+ let killer;
457
+ const finish = (ok) => {
458
+ if (done) return;
459
+ done = true;
460
+ clearTimeout(timer);
461
+ if (!ok && !hasExited(child)) {
462
+ try {
463
+ child.kill(signal);
464
+ } catch {
465
+ }
466
+ }
467
+ resolve6(ok);
468
+ };
469
+ const timer = setTimeout(() => {
470
+ try {
471
+ killer?.kill();
472
+ } catch {
473
+ }
474
+ finish(false);
475
+ }, 1500);
476
+ try {
477
+ const root = process.env.SystemRoot || process.env.windir || "C:\\Windows";
478
+ killer = spawn(path3.join(root, "System32", "taskkill.exe"), ["/PID", String(child.pid), "/T", "/F"], { shell: false, windowsHide: true, stdio: "ignore" });
479
+ killer.on("error", () => finish(false));
480
+ killer.on("exit", (code) => finish(code === 0));
481
+ } catch {
482
+ finish(false);
483
+ }
484
+ });
485
+ }
486
+ function lineReader(onLine, max = 1024 * 1024) {
487
+ const decoder = new StringDecoder("utf8");
488
+ let pending = "";
489
+ let dropping = false;
490
+ const accept = (text) => {
491
+ for (const [i, part] of text.split("\n").entries()) {
492
+ if (i) {
493
+ if (!dropping) onLine(pending);
494
+ pending = "";
495
+ dropping = false;
496
+ }
497
+ if (!dropping) {
498
+ pending += part;
499
+ if (pending.length > max) {
500
+ pending = "";
501
+ dropping = true;
502
+ }
503
+ }
504
+ }
505
+ };
506
+ return { write: (chunk) => accept(decoder.write(chunk)), end() {
507
+ accept(decoder.end());
508
+ if (pending && !dropping) onLine(pending);
509
+ pending = "";
510
+ } };
511
+ }
512
+ var shutdowns = /* @__PURE__ */ new WeakMap();
513
+ function shutdownConsumer(child) {
514
+ const existing = shutdowns.get(child);
515
+ if (existing) return existing;
516
+ const pending = shutdownConsumerInner(child);
517
+ shutdowns.set(child, pending);
518
+ return pending;
519
+ }
520
+ async function shutdownConsumerInner(child) {
521
+ let closed = false;
522
+ const close = new Promise((resolve6) => child.once("close", () => {
523
+ closed = true;
524
+ resolve6();
525
+ }));
526
+ const wait = async (ms) => {
527
+ let timer;
528
+ await Promise.race([close, new Promise((resolve6) => {
529
+ timer = setTimeout(resolve6, ms);
530
+ })]);
531
+ clearTimeout(timer);
532
+ };
533
+ try {
534
+ child.stdin?.end();
535
+ } catch {
536
+ }
537
+ await wait(500);
538
+ if (!closed) {
539
+ await stopOwnedTree(child, "SIGTERM");
540
+ await wait(500);
541
+ }
542
+ if (!closed) {
543
+ await stopOwnedTree(child, "SIGKILL");
544
+ await wait(500);
545
+ }
546
+ child.stdin?.destroy();
547
+ child.stdout?.destroy();
548
+ child.stderr?.destroy();
549
+ }
550
+
551
+ // builtin/extensions/im-forward/lark-cli.ts
552
+ async function runLarkCli(binary, args, timeoutMs = 3e4, cwd, options = {}) {
553
+ return new Promise((resolve6) => {
554
+ if (options.signal?.aborted) {
555
+ resolve6({ stdout: "", error: "cancelled" });
556
+ return;
557
+ }
558
+ let child;
559
+ try {
560
+ const spec = typeof binary === "string" ? resolveLaunchSpec(binary) ?? (options.spawn ? { command: binary, prefix: [] } : null) : binary;
561
+ if (!spec) throw new Error("unsupported executable");
562
+ child = (options.spawn ?? spawn2)(spec.command, [...spec.prefix, ...args], {
563
+ shell: false,
564
+ windowsHide: true,
565
+ stdio: [options.stdin ?? "ignore", "pipe", "pipe"],
566
+ detached: process.platform !== "win32",
567
+ ...cwd ? { cwd } : {}
568
+ });
569
+ } catch {
570
+ resolve6({ stdout: "", error: "spawn failed" });
571
+ return;
572
+ }
573
+ let stdout = "";
574
+ let stderr = "";
575
+ let settled = false;
576
+ let closed = false;
577
+ let termination;
578
+ let treeStopped = false;
579
+ let killTimer;
580
+ let closeTimer;
581
+ const finish = (result) => {
582
+ if (settled) return;
583
+ settled = true;
584
+ clearTimeout(timer);
585
+ clearTimeout(killTimer);
586
+ clearTimeout(closeTimer);
587
+ options.signal?.removeEventListener("abort", abort);
588
+ resolve6(result);
589
+ };
590
+ const terminatedResult = () => ({ stdout: termination?.startsWith("timeout") ? stdout : "", error: termination });
591
+ const stop = (signal) => {
592
+ try {
593
+ return stopOwnedTree(child, signal);
594
+ } catch {
595
+ return Promise.resolve();
596
+ }
597
+ };
598
+ const kill = () => {
599
+ const stopped = () => {
600
+ treeStopped = true;
601
+ if (settled) return;
602
+ if (closed) {
603
+ finish(terminatedResult());
604
+ return;
605
+ }
606
+ closeTimer = setTimeout(() => {
607
+ child.stdout?.destroy();
608
+ child.stderr?.destroy();
609
+ finish(terminatedResult());
610
+ }, options.closeGraceMs ?? 1e3);
611
+ };
612
+ void stop("SIGKILL").then(stopped, stopped);
613
+ };
614
+ const terminate = (reason, graceful = false) => {
615
+ if (settled || termination) return;
616
+ termination = reason;
617
+ clearTimeout(timer);
618
+ if (graceful) {
619
+ const stopped = () => {
620
+ if (closed) {
621
+ treeStopped = true;
622
+ finish(terminatedResult());
623
+ }
624
+ };
625
+ void stop("SIGTERM").then(stopped, stopped);
626
+ if (!settled) killTimer = setTimeout(kill, options.killGraceMs ?? 1e3);
627
+ } else kill();
628
+ };
629
+ const timer = setTimeout(() => terminate(`timeout after ${timeoutMs}ms`, true), timeoutMs);
630
+ const abort = () => terminate("cancelled");
631
+ options.signal?.addEventListener("abort", abort, { once: true });
632
+ if (options.signal?.aborted) abort();
633
+ const deliverLine = (line) => {
634
+ if (settled || termination) return;
635
+ try {
636
+ options.onLine?.(line);
637
+ } catch {
638
+ terminate("output callback failed");
639
+ }
640
+ };
641
+ const lines = options.onLine ? lineReader(deliverLine, 16384) : void 0;
642
+ const errorLines = options.onLine ? lineReader(deliverLine, 16384) : void 0;
643
+ const outDecoder = new StringDecoder2("utf8");
644
+ const errDecoder = new StringDecoder2("utf8");
645
+ child.stdout?.on("data", (chunk) => {
646
+ if (settled || termination) return;
647
+ lines?.write(chunk);
648
+ if (termination) return;
649
+ stdout += outDecoder.write(chunk);
650
+ if (stdout.length > 8 * 1024 * 1024) {
651
+ stdout = "";
652
+ terminate("stdout exceeds 8 MiB limit");
653
+ }
654
+ });
655
+ child.stderr?.on("data", (chunk) => {
656
+ if (settled || termination) return;
657
+ errorLines?.write(chunk);
658
+ stderr = (stderr + errDecoder.write(chunk)).slice(-4096);
659
+ });
660
+ child.on("error", () => terminate("spawn error"));
661
+ child.on("close", (code) => {
662
+ closed = true;
663
+ if (settled) return;
664
+ if (termination) {
665
+ if (treeStopped) finish(terminatedResult());
666
+ return;
667
+ }
668
+ stdout += outDecoder.end();
669
+ stderr += errDecoder.end();
670
+ lines?.end();
671
+ errorLines?.end();
672
+ if (termination) return;
673
+ if (code === 0 && (stdout.trim() || options.allowEmpty)) finish({ stdout });
674
+ else finish({ stdout, error: `exit ${code}${stderr ? `: ${stderr.slice(-300).trim()}` : ""}` });
675
+ });
676
+ });
677
+ }
678
+
679
+ // builtin/extensions/im-forward/panel-actions.ts
680
+ function panelActionsRoot() {
681
+ return path4.join(path4.dirname(path4.dirname(ipcDiscoveryRoot())), "panel-actions");
682
+ }
683
+ function registryFile() {
684
+ return path4.join(panelActionsRoot(), "registry.json");
685
+ }
686
+ function auditFile() {
687
+ return path4.join(panelActionsRoot(), "audit.jsonl");
688
+ }
689
+ function logsDir() {
690
+ return path4.join(panelActionsRoot(), "logs");
691
+ }
692
+ function locksDir() {
693
+ return path4.join(panelActionsRoot(), "locks");
694
+ }
695
+ function nameCacheFile() {
696
+ return path4.join(panelActionsRoot(), "name-cache.json");
697
+ }
698
+ function expandTilde(p) {
699
+ const home = process.env.HOME ?? process.env.USERPROFILE ?? "/tmp";
700
+ return p === "~" ? home : p.startsWith("~/") ? path4.join(home, p.slice(2)) : p;
701
+ }
702
+ function readRegistry() {
703
+ let raw;
704
+ try {
705
+ raw = fs3.readFileSync(registryFile(), "utf8");
706
+ } catch {
707
+ return { actions: [] };
708
+ }
709
+ try {
710
+ const parsed = JSON.parse(raw);
711
+ if (!Array.isArray(parsed.actions)) throw new Error("actions must be an array");
712
+ const actions = parsed.actions.filter((a) => {
713
+ const r = a;
714
+ 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";
715
+ });
716
+ return { actions };
717
+ } catch (error) {
718
+ return { actions: [], error: `panel-actions registry unreadable: ${error instanceof Error ? error.message : String(error)}` };
719
+ }
720
+ }
721
+ function writeRegistry(reg) {
722
+ fs3.mkdirSync(panelActionsRoot(), { recursive: true });
723
+ const target = registryFile();
724
+ const tmp = `${target}.${process.pid}.${Date.now().toString(36)}.tmp`;
725
+ fs3.writeFileSync(tmp, JSON.stringify(reg, null, " "));
726
+ fs3.renameSync(tmp, target);
727
+ }
728
+ var ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/;
729
+ function slugifyActionId(label, existing) {
730
+ const base = label.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 28).replace(/^-+|-+$/g, "") || "action";
731
+ const ascii = base.replace(/[\u4e00-\u9fff]+/g, "x").replace(/[^a-z0-9-]/g, "").replace(/^-+|-+$/g, "") || "action";
732
+ let id = ascii;
733
+ for (let n = 2; existing.some((a) => a.id === id); n += 1) id = `${ascii}-${n}`;
734
+ return id.slice(0, 32);
735
+ }
736
+ function isValidScope(scope) {
737
+ return scope === "manager" || scope === "worker" || /^worker:[a-z0-9][a-z0-9-_]{0,47}$/i.test(scope);
738
+ }
739
+ function addAction(input) {
740
+ const label = input.label.trim();
741
+ if (!label) throw new Error("panel action label must not be empty");
742
+ if (label.length > 40) throw new Error(`panel action label too long (${label.length} chars, max 40)`);
743
+ if (!isValidScope(input.scope)) throw new Error(`invalid scope "${input.scope}" (manager | worker | worker:<name>)`);
744
+ const script = path4.resolve(expandTilde(input.script.trim()));
745
+ if (!fs3.existsSync(script) || !fs3.statSync(script).isFile()) {
746
+ throw new Error(`script not found: ${script} (the worker must deliver a tested script BEFORE the button is registered)`);
747
+ }
748
+ const cwd = input.cwd !== void 0 ? path4.resolve(expandTilde(input.cwd.trim())) : void 0;
749
+ if (cwd !== void 0 && (!fs3.existsSync(cwd) || !fs3.statSync(cwd).isDirectory())) {
750
+ throw new Error(`cwd not found: ${cwd}`);
751
+ }
752
+ const timeoutMs = input.timeoutMs !== void 0 ? Math.min(Math.max(Math.floor(input.timeoutMs), 5e3), 36e5) : void 0;
753
+ if (input.payload !== void 0) {
754
+ try {
755
+ JSON.stringify(input.payload);
756
+ } catch {
757
+ throw new Error("payload must be JSON-serializable");
758
+ }
759
+ }
760
+ const { actions, error } = readRegistry();
761
+ if (error) throw new Error(error);
762
+ const id = input.id !== void 0 ? input.id.trim() : slugifyActionId(label, actions);
763
+ if (!ID_PATTERN.test(id)) throw new Error(`invalid action id "${id}" ([a-z0-9-], max 32)`);
764
+ if (actions.some((a) => a.id === id)) throw new Error(`action id "${id}" already exists`);
765
+ const action = {
766
+ id,
767
+ label,
768
+ script,
769
+ ...cwd !== void 0 ? { cwd } : {},
770
+ ...input.payload !== void 0 ? { payload: input.payload } : {},
771
+ ...timeoutMs !== void 0 ? { timeoutMs } : {},
772
+ scope: input.scope,
773
+ ...input.creator ? { creator: input.creator } : {},
774
+ createdAt: Date.now(),
775
+ runs: 0
776
+ };
777
+ writeRegistry({ version: 1, actions: [...actions, action] });
778
+ return action;
779
+ }
780
+ function removeAction(id) {
781
+ const { actions, error } = readRegistry();
782
+ if (error) throw new Error(error);
783
+ const found = actions.find((a) => a.id === id);
784
+ if (!found) return void 0;
785
+ writeRegistry({ version: 1, actions: actions.filter((a) => a.id !== id) });
786
+ return found;
787
+ }
788
+ function managerActions() {
789
+ return readRegistry().actions.filter((a) => a.scope === "manager").sort((a, b) => b.runs - a.runs || a.createdAt - b.createdAt);
790
+ }
791
+ function workerActions(workerName) {
792
+ const pinned = `worker:${workerName}`;
793
+ return readRegistry().actions.filter((a) => a.scope === "worker" || a.scope.toLowerCase() === pinned.toLowerCase()).sort((a, b) => b.runs - a.runs || a.createdAt - b.createdAt);
794
+ }
795
+ function findAction(id) {
796
+ return readRegistry().actions.find((a) => a.id === id);
797
+ }
798
+ function bumpRunStats(id, byName) {
799
+ try {
800
+ const { actions, error } = readRegistry();
801
+ if (error) return;
802
+ const found = actions.find((a) => a.id === id);
803
+ if (!found) return;
804
+ found.runs += 1;
805
+ found.lastRunAt = Date.now();
806
+ found.lastRunBy = byName;
807
+ writeRegistry({ version: 1, actions });
808
+ } catch {
809
+ }
810
+ }
811
+ function appendAudit(entry) {
812
+ try {
813
+ fs3.mkdirSync(panelActionsRoot(), { recursive: true });
814
+ fs3.appendFileSync(auditFile(), `${JSON.stringify(entry)}
815
+ `);
816
+ } catch {
817
+ }
818
+ }
819
+ function readNameCache() {
820
+ try {
821
+ const parsed = JSON.parse(fs3.readFileSync(nameCacheFile(), "utf8"));
822
+ const out = {};
823
+ for (const [k, v] of Object.entries(parsed)) if (typeof v === "string" && v) out[k] = v;
824
+ return out;
825
+ } catch {
826
+ return {};
827
+ }
828
+ }
829
+ function fallbackName(openId) {
830
+ if (!openId) return "unknown";
831
+ return openId.length > 10 ? `ou\u2026${openId.slice(-6)}` : openId;
832
+ }
833
+ function peekNameCache(openId) {
834
+ if (!openId) return void 0;
835
+ return readNameCache()[openId];
836
+ }
837
+ async function resolveUserName(openId, opts = {}) {
838
+ if (!openId) return "unknown";
839
+ const cache = readNameCache();
840
+ const hit = cache[openId];
841
+ if (hit) return hit;
842
+ try {
843
+ const args = ["contact", "+get-user", "--user-id", openId, "--as", "bot"];
844
+ if (opts.profile) args.push("--profile", opts.profile);
845
+ const { stdout, error } = await runLarkCli(opts.binary ?? "lark-cli", args, 1e4);
846
+ if (!error && stdout.trim()) {
847
+ const parsed = JSON.parse(stdout);
848
+ const name = typeof parsed?.data?.user?.name === "string" ? parsed.data.user.name : typeof parsed.name === "string" ? parsed.name : void 0;
849
+ if (name) {
850
+ cache[openId] = name;
851
+ try {
852
+ fs3.mkdirSync(panelActionsRoot(), { recursive: true });
853
+ fs3.writeFileSync(nameCacheFile(), JSON.stringify(cache, null, " "));
854
+ } catch {
855
+ }
856
+ return name;
857
+ }
858
+ }
859
+ } catch {
860
+ }
861
+ return fallbackName(openId);
862
+ }
863
+ function lockDirFor(actionId) {
864
+ return path4.join(locksDir(), `${actionId}.lck`);
865
+ }
866
+ function lockInfoPath(dir) {
867
+ return path4.join(dir, "info.json");
868
+ }
869
+ function renewPath(dir) {
870
+ return path4.join(dir, "renew.json");
871
+ }
872
+ var birthtimeProbe;
873
+ function birthtimeUsable() {
874
+ if (birthtimeProbe !== void 0) return birthtimeProbe;
875
+ try {
876
+ fs3.mkdirSync(locksDir(), { recursive: true });
877
+ const probe = fs3.mkdtempSync(path4.join(locksDir(), ".probe-"));
878
+ try {
879
+ const b1 = fs3.statSync(probe).birthtimeMs;
880
+ fs3.writeFileSync(path4.join(probe, "x"), "x");
881
+ const b2 = fs3.statSync(probe).birthtimeMs;
882
+ birthtimeProbe = b1 > 0 && b1 === b2;
883
+ } finally {
884
+ fs3.rmSync(probe, { recursive: true, force: true });
885
+ }
886
+ } catch {
887
+ birthtimeProbe = false;
888
+ }
889
+ return birthtimeProbe;
890
+ }
891
+ function dirGeneration(dir) {
892
+ try {
893
+ const st = fs3.statSync(dir);
894
+ return birthtimeUsable() ? `${st.ino}:${st.birthtimeMs}` : `ino:${st.ino}`;
895
+ } catch {
896
+ return void 0;
897
+ }
898
+ }
899
+ function readLockInfo(dir) {
900
+ try {
901
+ const parsed = JSON.parse(fs3.readFileSync(lockInfoPath(dir), "utf8"));
902
+ if (typeof parsed?.token !== "string" || typeof parsed?.startedAt !== "number" || typeof parsed?.deadlineAt !== "number" || typeof parsed?.pid !== "number") {
903
+ return { malformed: true };
904
+ }
905
+ return { info: parsed, malformed: false };
906
+ } catch {
907
+ return { malformed: true };
908
+ }
909
+ }
910
+ function effectiveLock(dir) {
911
+ const { info, malformed } = readLockInfo(dir);
912
+ if (!info) return { malformed };
913
+ let deadlineAt = info.deadlineAt;
914
+ let childPid;
915
+ try {
916
+ const renew = JSON.parse(fs3.readFileSync(renewPath(dir), "utf8"));
917
+ if (renew?.token === info.token && typeof renew.deadlineAt === "number") {
918
+ deadlineAt = renew.deadlineAt;
919
+ if (typeof renew.childPid === "number") childPid = renew.childPid;
920
+ }
921
+ } catch {
922
+ }
923
+ return { info, deadlineAt, childPid, malformed: false };
924
+ }
925
+ function publishLockInfoCas(dir, info) {
926
+ const tmp = path4.join(locksDir(), `.info-${info.token}.tmp`);
927
+ try {
928
+ fs3.writeFileSync(tmp, JSON.stringify(info));
929
+ try {
930
+ fs3.linkSync(tmp, lockInfoPath(dir));
931
+ } catch {
932
+ return false;
933
+ }
934
+ return true;
935
+ } catch {
936
+ return false;
937
+ } finally {
938
+ try {
939
+ fs3.rmSync(tmp, { force: true });
940
+ } catch {
941
+ }
942
+ }
943
+ }
944
+ function publishRenew(dir, renew) {
945
+ const tmp = path4.join(locksDir(), `.renew-${renew.token}-${Date.now().toString(36)}.tmp`);
946
+ fs3.writeFileSync(tmp, JSON.stringify(renew));
947
+ fs3.renameSync(tmp, renewPath(dir));
948
+ }
949
+ function pidAlive2(pid) {
950
+ try {
951
+ process.kill(pid, 0);
952
+ return true;
953
+ } catch {
954
+ return false;
955
+ }
956
+ }
957
+ async function fenceChild(childPid, marker) {
958
+ if (childPid === void 0 || !Number.isInteger(childPid) || childPid <= 1) return "not-running";
959
+ if (!marker) return "unknown";
960
+ if (!pidAlive2(childPid)) {
961
+ if (process.platform === "win32") return "unknown";
962
+ try {
963
+ process.kill(-childPid, 0);
964
+ return "unknown";
965
+ } catch (error) {
966
+ return error.code === "ESRCH" ? "not-running" : "unknown";
967
+ }
968
+ }
969
+ const cmd = readProcessCommandLine(childPid);
970
+ if (cmd === void 0 || !cmd.includes(marker)) return "unknown";
971
+ if (process.platform === "win32") {
972
+ return await new Promise((resolve6) => {
973
+ let killer;
974
+ try {
975
+ killer = spawn3("taskkill", ["/T", "/F", "/PID", String(childPid)], { stdio: "ignore", windowsHide: true });
976
+ } catch {
977
+ resolve6("unknown");
978
+ return;
979
+ }
980
+ killer.on("error", () => resolve6("unknown"));
981
+ const deadline = Date.now() + 5e3;
982
+ const poll = () => {
983
+ if (!pidAlive2(childPid)) {
984
+ resolve6("fenced");
985
+ return;
986
+ }
987
+ if (Date.now() >= deadline) {
988
+ resolve6("unknown");
989
+ return;
990
+ }
991
+ setTimeout(poll, 100).unref?.();
992
+ };
993
+ setTimeout(poll, 100).unref?.();
994
+ });
995
+ }
996
+ let signaled = false;
997
+ try {
998
+ process.kill(-childPid, "SIGKILL");
999
+ signaled = true;
1000
+ } catch {
1001
+ }
1002
+ if (!signaled) {
1003
+ try {
1004
+ process.kill(childPid, "SIGKILL");
1005
+ signaled = true;
1006
+ } catch {
1007
+ }
1008
+ }
1009
+ return signaled ? "fenced" : "unknown";
1010
+ }
1011
+ async function claimReap(dir, token, expectedStaleToken, reapMarginMs, childMarker) {
1012
+ const cur = effectiveLock(dir);
1013
+ if (cur.info?.token !== expectedStaleToken) return "busy";
1014
+ if (pidAlive2(cur.info.pid) && Date.now() <= (cur.deadlineAt ?? 0) + reapMarginMs) return "busy";
1015
+ const fenced = await fenceChild(cur.childPid, childMarker);
1016
+ if (fenced === "unknown") return "unfenceable";
1017
+ const recheck = effectiveLock(dir);
1018
+ if (recheck.info?.token !== expectedStaleToken) return "busy";
1019
+ if (recheck.malformed) return "busy";
1020
+ if (pidAlive2(recheck.info.pid) && Date.now() <= (recheck.deadlineAt ?? 0) + reapMarginMs) return "busy";
1021
+ const aside = `${dir}.reap-${token}`;
1022
+ try {
1023
+ fs3.renameSync(dir, aside);
1024
+ } catch {
1025
+ return "busy";
1026
+ }
1027
+ try {
1028
+ fs3.rmSync(aside, { recursive: true, force: true });
1029
+ } catch {
1030
+ }
1031
+ return "reaped";
1032
+ }
1033
+ async function acquireLock(actionId, triggerName, timeoutMs = DEFAULT_TIMEOUT_MS, childMarker) {
1034
+ fs3.mkdirSync(locksDir(), { recursive: true });
1035
+ try {
1036
+ for (const entry of fs3.readdirSync(locksDir())) {
1037
+ if (!entry.includes(".reap-") && !(entry.startsWith(".info-") && entry.endsWith(".tmp"))) continue;
1038
+ try {
1039
+ const stale = path4.join(locksDir(), entry);
1040
+ if (Date.now() - fs3.statSync(stale).mtimeMs > 36e5) fs3.rmSync(stale, { recursive: true, force: true });
1041
+ } catch {
1042
+ }
1043
+ }
1044
+ } catch {
1045
+ }
1046
+ const dir = lockDirFor(actionId);
1047
+ const token = `${process.pid}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
1048
+ const startedAt = Date.now();
1049
+ const info = { pid: process.pid, token, triggerName, startedAt, deadlineAt: startedAt + timeoutMs };
1050
+ const reapMarginMs = 6e4;
1051
+ const malformedFreshMs = 12e4;
1052
+ for (let attempt = 0; attempt < 4; attempt += 1) {
1053
+ try {
1054
+ fs3.mkdirSync(dir);
1055
+ if (!publishLockInfoCas(dir, info)) continue;
1056
+ const myGeneration = dirGeneration(dir);
1057
+ if (myGeneration === void 0 || readLockInfo(dir).info?.token !== token) {
1058
+ continue;
1059
+ }
1060
+ let released = false;
1061
+ return {
1062
+ ok: true,
1063
+ token,
1064
+ stillOwned: () => readLockInfo(dir).info?.token === token,
1065
+ rearm: (ms) => {
1066
+ if (dirGeneration(dir) !== myGeneration) return false;
1067
+ const cur = readLockInfo(dir);
1068
+ if (cur.info?.token !== token) return false;
1069
+ try {
1070
+ publishRenew(dir, { token, deadlineAt: Date.now() + ms, at: Date.now() });
1071
+ } catch {
1072
+ return false;
1073
+ }
1074
+ return dirGeneration(dir) === myGeneration;
1075
+ },
1076
+ announceChild: (pid) => {
1077
+ if (dirGeneration(dir) !== myGeneration) return false;
1078
+ const cur = effectiveLock(dir);
1079
+ if (cur.info?.token !== token) return false;
1080
+ try {
1081
+ publishRenew(dir, { token, deadlineAt: cur.deadlineAt ?? Date.now(), childPid: pid, at: Date.now() });
1082
+ } catch {
1083
+ return false;
1084
+ }
1085
+ return dirGeneration(dir) === myGeneration;
1086
+ },
1087
+ // Ownership-checked release (r2) + generation check (r5): a
1088
+ // reaped-then-reacquired lock belongs to the NEW holder — a late
1089
+ // release() from the old owner must not delete it.
1090
+ release: () => {
1091
+ if (released) return;
1092
+ released = true;
1093
+ if (readLockInfo(dir).info?.token !== token) return;
1094
+ if (dirGeneration(dir) !== myGeneration) return;
1095
+ try {
1096
+ fs3.rmSync(dir, { recursive: true, force: true });
1097
+ } catch {
1098
+ }
1099
+ }
1100
+ };
1101
+ } catch (error) {
1102
+ if (error.code !== "EEXIST") throw error;
1103
+ const observedGeneration = dirGeneration(dir);
1104
+ const { info: existing, malformed } = readLockInfo(dir);
1105
+ if (malformed || !existing) {
1106
+ let mtime = 0;
1107
+ try {
1108
+ mtime = fs3.statSync(dir).mtimeMs;
1109
+ } catch {
1110
+ continue;
1111
+ }
1112
+ if (Date.now() - mtime < malformedFreshMs) {
1113
+ return { ok: false, holder: { triggerName: "unknown", startedAt: 0 } };
1114
+ }
1115
+ const recheck = readLockInfo(dir);
1116
+ if (!recheck.malformed && recheck.info) continue;
1117
+ if (dirGeneration(dir) !== observedGeneration) continue;
1118
+ const aside = `${dir}.reap-${token}`;
1119
+ try {
1120
+ fs3.renameSync(dir, aside);
1121
+ } catch {
1122
+ continue;
1123
+ }
1124
+ try {
1125
+ fs3.rmSync(aside, { recursive: true, force: true });
1126
+ } catch {
1127
+ }
1128
+ continue;
1129
+ }
1130
+ const effective = effectiveLock(dir);
1131
+ const wedged = pidAlive2(existing.pid) && Date.now() > (effective.deadlineAt ?? existing.deadlineAt) + reapMarginMs;
1132
+ if (pidAlive2(existing.pid) && !wedged) {
1133
+ return {
1134
+ ok: false,
1135
+ holder: { triggerName: existing.triggerName, startedAt: existing.startedAt }
1136
+ };
1137
+ }
1138
+ const reapOutcome = await claimReap(dir, token, existing.token, reapMarginMs, childMarker);
1139
+ if (reapOutcome === "unfenceable") {
1140
+ return {
1141
+ ok: false,
1142
+ holder: {
1143
+ triggerName: existing.triggerName,
1144
+ startedAt: existing.startedAt,
1145
+ 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`
1146
+ }
1147
+ };
1148
+ }
1149
+ if (reapOutcome === "busy") continue;
1150
+ continue;
1151
+ }
1152
+ }
1153
+ return { ok: false, holder: { triggerName: "unknown", startedAt: 0 } };
1154
+ }
1155
+ var DEFAULT_TIMEOUT_MS = 3e5;
1156
+ var CAPTURE_CAP_BYTES = 1e6;
1157
+ var KILL_GRACE_MS = 3e3;
1158
+ function interpreterFor(script) {
1159
+ const ext = path4.extname(script).toLowerCase();
1160
+ if (ext === ".mjs" || ext === ".js" || ext === ".cjs") return { command: process.execPath, prefix: [script] };
1161
+ if (ext === ".sh") return { command: "bash", prefix: [script] };
1162
+ if (ext === ".py") return { command: "python3", prefix: [script] };
1163
+ return { command: script, prefix: [] };
1164
+ }
1165
+ function scriptEnv(req) {
1166
+ const env = {};
1167
+ for (const key of ["PATH", "HOME", "LANG", "LC_ALL", "TERM", "TMPDIR", "USER", "LOGNAME", "SHELL"]) {
1168
+ const value = process.env[key];
1169
+ if (value !== void 0) env[key] = value;
1170
+ }
1171
+ env.PIE_ACTION_ID = req.action.id;
1172
+ env.PIE_ACTION_TRIGGER_NAME = req.trigger.name;
1173
+ if (req.trigger.openId) env.PIE_ACTION_TRIGGER_OPEN_ID = req.trigger.openId;
1174
+ env.PIE_ACTION_CHAT_ID = req.chatId;
1175
+ if (req.action.payload !== void 0) {
1176
+ try {
1177
+ env.PIE_ACTION_PAYLOAD = JSON.stringify(req.action.payload);
1178
+ } catch {
1179
+ }
1180
+ }
1181
+ if (req.worker) {
1182
+ env.PIE_ACTION_WORKER = req.worker.name;
1183
+ if (req.worker.dir) env.PIE_ACTION_WORKER_DIR = req.worker.dir;
1184
+ }
1185
+ return env;
1186
+ }
1187
+ async function executeAction(req) {
1188
+ const started = Date.now();
1189
+ const { action } = req;
1190
+ const timeoutMs = action.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1191
+ const script = path4.resolve(expandTilde(action.script));
1192
+ const cwd = action.cwd !== void 0 ? path4.resolve(expandTilde(action.cwd)) : path4.dirname(script);
1193
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
1194
+ const logFile = path4.join(logsDir(), `${action.id}-${stamp}-${Math.random().toString(36).slice(2, 6)}.log`);
1195
+ let stdout = "";
1196
+ let stderrTail = "";
1197
+ let stdoutTruncated = false;
1198
+ let stderrTruncated = false;
1199
+ let timedOut = false;
1200
+ let cancelled = false;
1201
+ const LOG_CAP_BYTES = 50 * 1024 * 1024;
1202
+ let logFd;
1203
+ let logBytes = 0;
1204
+ let logDegraded = false;
1205
+ const logWrite = (chunk) => {
1206
+ if (logFd === void 0 || logDegraded) return;
1207
+ const buf = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk;
1208
+ try {
1209
+ let offset = 0;
1210
+ while (offset < buf.length) {
1211
+ const remaining = LOG_CAP_BYTES - logBytes;
1212
+ if (remaining <= 0) {
1213
+ logDegraded = true;
1214
+ const marker = Buffer.from(`
1215
+ [panel-actions] log budget ${LOG_CAP_BYTES} bytes exceeded; further output dropped
1216
+ `, "utf8");
1217
+ try {
1218
+ fs3.writeSync(logFd, marker, 0, marker.length, null);
1219
+ } catch {
1220
+ }
1221
+ return;
1222
+ }
1223
+ const want = Math.min(buf.length - offset, remaining);
1224
+ const written = fs3.writeSync(logFd, buf, offset, want, null);
1225
+ if (written <= 0) throw new Error("zero-progress write");
1226
+ offset += written;
1227
+ logBytes += written;
1228
+ }
1229
+ } catch {
1230
+ logDegraded = true;
265
1231
  }
1232
+ };
1233
+ try {
1234
+ fs3.mkdirSync(logsDir(), { recursive: true });
1235
+ logFd = fs3.openSync(logFile, "w");
1236
+ } catch {
1237
+ logFd = void 0;
1238
+ logDegraded = true;
1239
+ }
1240
+ logWrite([
1241
+ `action: ${action.id} (${action.label})`,
1242
+ `script: ${script}`,
1243
+ `cwd: ${cwd}`,
1244
+ `trigger: ${req.trigger.name}${req.trigger.openId ? ` <${req.trigger.openId}>` : ""}`,
1245
+ `chat: ${req.chatId}`,
1246
+ req.worker ? `worker: ${req.worker.name}${req.worker.dir ? ` (${req.worker.dir})` : ""}` : void 0,
1247
+ `started: ${new Date(started).toISOString()}`,
1248
+ "=".repeat(60)
1249
+ ].filter((line) => line !== void 0).join("\n") + "\n");
1250
+ const exitCode = await new Promise((resolve6) => {
1251
+ const { command, prefix } = interpreterFor(script);
1252
+ let child;
266
1253
  try {
267
- writeHolderEntry(candidate, token);
268
- } catch {
1254
+ child = spawn3(command, prefix, {
1255
+ cwd,
1256
+ env: scriptEnv(req),
1257
+ detached: process.platform !== "win32",
1258
+ // own process group: timeout kills the TREE
1259
+ stdio: ["ignore", "pipe", "pipe"],
1260
+ windowsHide: true
1261
+ });
1262
+ } catch (error) {
1263
+ logWrite(`[spawn error] ${error instanceof Error ? error.message : String(error)}
1264
+ `);
1265
+ resolve6(null);
1266
+ return;
1267
+ }
1268
+ if (typeof child.pid === "number") {
1269
+ let announced = true;
269
1270
  try {
270
- fs.rmSync(candidate, { recursive: true, force: true });
1271
+ announced = req.onChildSpawn?.(child.pid) ?? true;
271
1272
  } catch {
1273
+ announced = false;
1274
+ }
1275
+ if (!announced) {
1276
+ cancelled = true;
1277
+ logWrite("[panel-actions] ownership lost before child registration; killing the child at birth\n");
1278
+ void stopOwnedTree(child, "SIGKILL");
272
1279
  }
273
- return { acquired: false, reason: "thread registry unavailable", transient: true };
274
1280
  }
275
- const deadline = Date.now() + 5e3;
276
- for (; ; ) {
277
- try {
278
- fs.renameSync(candidate, lock);
279
- acquiredLocks.set(threadKey, token);
280
- return { acquired: true };
281
- } catch (error) {
282
- const code = error?.code;
283
- if (code !== "EEXIST" && code !== "ENOTEMPTY" && code !== "EPERM" && code !== "ENOTDIR") {
284
- return { acquired: false, reason: "thread registry unavailable", transient: true };
285
- }
286
- if (Date.now() > deadline) return { acquired: false, reason: "thread lock busy", transient: true };
1281
+ const outDecoder = new StringDecoder3("utf8");
1282
+ const errDecoder = new StringDecoder3("utf8");
1283
+ child.stdout?.on("data", (chunk) => {
1284
+ logWrite(chunk);
1285
+ if (stdoutTruncated) return;
1286
+ stdout += outDecoder.write(chunk);
1287
+ if (stdout.length > CAPTURE_CAP_BYTES) {
1288
+ stdout = stdout.slice(0, CAPTURE_CAP_BYTES);
1289
+ stdoutTruncated = true;
1290
+ }
1291
+ });
1292
+ child.stderr?.on("data", (chunk) => {
1293
+ logWrite(chunk);
1294
+ const next = stderrTail + errDecoder.write(chunk);
1295
+ if (next.length > 8e3) stderrTruncated = true;
1296
+ stderrTail = next.slice(-8e3);
1297
+ });
1298
+ let settled = false;
1299
+ let killGrace;
1300
+ let finalDeadline;
1301
+ const settle = (code) => {
1302
+ if (settled) return;
1303
+ settled = true;
1304
+ clearTimeout(timeoutTimer);
1305
+ if (killGrace) clearTimeout(killGrace);
1306
+ if (finalDeadline) clearTimeout(finalDeadline);
1307
+ for (const stream of [child.stdout, child.stderr]) {
1308
+ stream?.removeAllListeners("data");
287
1309
  try {
288
- retireStaleLock(lock);
1310
+ stream?.destroy();
289
1311
  } catch {
290
1312
  }
291
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1 + Math.floor(Math.random() * 3));
292
1313
  }
1314
+ try {
1315
+ const rest = outDecoder.end();
1316
+ if (rest && !stdoutTruncated) {
1317
+ stdout += rest;
1318
+ if (stdout.length > CAPTURE_CAP_BYTES) {
1319
+ stdout = stdout.slice(0, CAPTURE_CAP_BYTES);
1320
+ stdoutTruncated = true;
1321
+ }
1322
+ }
1323
+ const errRest = errDecoder.end();
1324
+ if (errRest) {
1325
+ const next = stderrTail + errRest;
1326
+ if (next.length > 8e3) stderrTruncated = true;
1327
+ stderrTail = next.slice(-8e3);
1328
+ }
1329
+ } catch {
1330
+ }
1331
+ resolve6(code);
1332
+ };
1333
+ child.on("error", (error) => {
1334
+ logWrite(`[spawn error] ${error.message}
1335
+ `);
1336
+ settle(null);
1337
+ });
1338
+ child.on("close", (code) => settle(code));
1339
+ const timeoutTimer = setTimeout(() => {
1340
+ timedOut = true;
1341
+ logWrite(`[panel-actions] timeout ${timeoutMs}ms exceeded; SIGTERM to the tree
1342
+ `);
1343
+ void stopOwnedTree(child, "SIGTERM").then(() => {
1344
+ if (settled) return;
1345
+ killGrace = setTimeout(() => {
1346
+ if (settled) return;
1347
+ logWrite("[panel-actions] SIGKILL\n");
1348
+ void stopOwnedTree(child, "SIGKILL");
1349
+ finalDeadline = setTimeout(() => settle(null), 2e3);
1350
+ finalDeadline.unref?.();
1351
+ }, KILL_GRACE_MS);
1352
+ killGrace.unref?.();
1353
+ });
1354
+ }, timeoutMs);
1355
+ timeoutTimer.unref?.();
1356
+ if (cancelled) {
1357
+ const cancelDeadline = setTimeout(() => settle(null), 3e3);
1358
+ cancelDeadline.unref?.();
293
1359
  }
294
- } finally {
1360
+ });
1361
+ const durationMs = Date.now() - started;
1362
+ logWrite(`
1363
+ ${"=".repeat(60)}
1364
+ [exit] code=${exitCode === null ? "(none)" : exitCode}${timedOut ? " TIMED OUT" : ""} durationMs=${durationMs}
1365
+ `);
1366
+ if (logFd !== void 0) {
295
1367
  try {
296
- fs.rmSync(candidate, { recursive: true, force: true });
1368
+ fs3.closeSync(logFd);
297
1369
  } catch {
298
1370
  }
1371
+ logFd = void 0;
299
1372
  }
300
- }
301
- function releaseThreadLock(threadKey) {
302
- const token = acquiredLocks.get(threadKey);
303
- if (token === void 0) return;
304
- acquiredLocks.delete(threadKey);
305
- const lock = lockDirPath(threadKey);
306
- try {
307
- fs.unlinkSync(path.join(lock, `held.${token}`));
308
- } catch {
309
- }
310
- try {
311
- const remaining = fs.readdirSync(lock);
312
- if (remaining.length === 0) fs.rmdirSync(lock);
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");
1373
+ return {
1374
+ ok: !timedOut && !cancelled && exitCode === 0,
1375
+ timedOut,
1376
+ cancelled,
1377
+ exitCode,
1378
+ stdout,
1379
+ stderrTail,
1380
+ stdoutTruncated,
1381
+ stderrTruncated,
1382
+ logDegraded,
1383
+ durationMs,
1384
+ logFile
1385
+ };
348
1386
  }
349
1387
 
350
1388
  // builtin/extensions/im-forward/panel.ts
@@ -362,8 +1400,8 @@ function parsePanelCommand(text) {
362
1400
  cmd = next?.[1] ?? "";
363
1401
  rest = next?.[2] ?? "";
364
1402
  }
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;
1403
+ 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") {
1404
+ if (!/^panel\.model\.[A-Za-z0-9-]+\..+$/.test(cmd) && !/^panel\.(context|compact)\.[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
1405
  }
368
1406
  const leadingFlag = /^--restricted(?:\s+|$)/.exec(rest);
369
1407
  const restricted = leadingFlag !== null;
@@ -377,14 +1415,27 @@ function parsePanelCommand(text) {
377
1415
  }
378
1416
  return { cmd, restricted, payload };
379
1417
  }
1418
+ function findPeerByName(name) {
1419
+ const needle = name.trim().toLowerCase();
1420
+ if (!needle) return void 0;
1421
+ const matches = scanPeers().filter((p) => !p.isManager && p.name.toLowerCase() === needle);
1422
+ if (matches.length > 1) return "ambiguous";
1423
+ return matches[0];
1424
+ }
1425
+ function findPeerByInstanceId(instanceId) {
1426
+ if (!instanceId) return void 0;
1427
+ const peer = scanPeers().find((p) => p.instanceId === instanceId);
1428
+ if (!peer || peer.isManager) return void 0;
1429
+ return peer;
1430
+ }
380
1431
  function scanPeers() {
381
1432
  const out = [];
382
1433
  try {
383
1434
  const dir = ipcDiscoveryRoot();
384
- for (const file of fs2.readdirSync(dir).slice(0, 64)) {
1435
+ for (const file of fs4.readdirSync(dir).slice(0, 64)) {
385
1436
  if (!file.endsWith(".json")) continue;
386
1437
  try {
387
- const parsed = JSON.parse(fs2.readFileSync(path3.join(dir, file), "utf8"));
1438
+ const parsed = JSON.parse(fs4.readFileSync(path5.join(dir, file), "utf8"));
388
1439
  if (typeof parsed.sessionId !== "string" || typeof parsed.pid !== "number") continue;
389
1440
  if (typeof parsed.instanceId !== "string" || !parsed.instanceId) continue;
390
1441
  try {
@@ -400,6 +1451,8 @@ function scanPeers() {
400
1451
  unattended: parsed.unattended === true,
401
1452
  sessionTitle: typeof parsed.displaySessionName === "string" && parsed.displaySessionName.trim() ? parsed.displaySessionName.trim() : void 0,
402
1453
  project: typeof parsed.cwd === "string" && parsed.cwd ? parsed.cwd.split("/").filter(Boolean).at(-1) : void 0,
1454
+ cwd: typeof parsed.cwd === "string" && parsed.cwd ? parsed.cwd : void 0,
1455
+ isManager: parsed.isManager === true,
403
1456
  currentTool: typeof parsed.currentTool === "string" && parsed.currentTool ? parsed.currentTool : void 0,
404
1457
  model: typeof parsed.model === "string" && parsed.model ? parsed.model : void 0,
405
1458
  version: typeof parsed.version === "string" && parsed.version ? parsed.version : void 0
@@ -429,6 +1482,22 @@ ${rows.join("\n")}` : "_No live pie sessions_",
429
1482
  upgradeLine,
430
1483
  `${peers.length} session(s) \xB7 ${(/* @__PURE__ */ new Date()).toLocaleTimeString("en-GB", { hour12: false })}`
431
1484
  ].filter((line) => line !== void 0).join("\n");
1485
+ const fixed = [
1486
+ { id: "panel.refresh", label: "\u{1F504} Refresh" },
1487
+ { id: "panel.summon", label: "\u{1F4CB} Resummon" },
1488
+ { id: "panel.models", label: "\u{1F39A} Model" },
1489
+ { id: "panel.context", label: "\u{1F4CA} Context" },
1490
+ { id: "panel.compact", label: "\u{1F9F9} Compact" },
1491
+ { id: "panel.upgrade", label: "\u2B06\uFE0F Upgrade" },
1492
+ { id: "panel.help", label: "\u2753 Help" }
1493
+ ];
1494
+ const CARD_ACTION_BUDGET = 18;
1495
+ 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)}` }));
1496
+ const custom = managerActions();
1497
+ const slots = Math.max(0, CARD_ACTION_BUDGET - fixed.length - workerEntries.length);
1498
+ const inline = custom.length <= slots ? custom : custom.slice(0, Math.max(0, slots - 1));
1499
+ const customButtons = inline.map((a) => ({ id: `panel.action.${a.id}`, label: a.label.slice(0, 20) }));
1500
+ if (custom.length > inline.length) customButtons.push({ id: "panel.actions", label: `\u26A1 \u5168\u90E8\u52A8\u4F5C (${custom.length})` });
432
1501
  return {
433
1502
  title: "Pie Panel",
434
1503
  subtitle: `${os2.hostname()} \xB7 ${peers.length} session(s) \xB7 pie ${pieVersion()}`,
@@ -436,22 +1505,16 @@ ${rows.join("\n")}` : "_No live pie sessions_",
436
1505
  body,
437
1506
  // r1-P2: only REGISTERED commands get buttons — unmapped ids would fall
438
1507
  // 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
- ]
1508
+ actions: [...fixed, ...workerEntries, ...customButtons]
446
1509
  };
447
1510
  }
448
1511
  function pieVersion() {
449
1512
  try {
450
- const here = path3.dirname(fileURLToPath(import.meta.url));
1513
+ const here = path5.dirname(fileURLToPath(import.meta.url));
451
1514
  for (const up of [3, 4, 5, 6]) {
452
- const pkgPath = path3.resolve(here, ...Array(up).fill(".."), "package.json");
453
- if (!fs2.existsSync(pkgPath)) continue;
454
- const parsed = JSON.parse(fs2.readFileSync(pkgPath, "utf8"));
1515
+ const pkgPath = path5.resolve(here, ...Array(up).fill(".."), "package.json");
1516
+ if (!fs4.existsSync(pkgPath)) continue;
1517
+ const parsed = JSON.parse(fs4.readFileSync(pkgPath, "utf8"));
455
1518
  if (parsed.name === "@cydm/pie" && typeof parsed.version === "string") return parsed.version;
456
1519
  }
457
1520
  } catch {
@@ -460,8 +1523,8 @@ function pieVersion() {
460
1523
  }
461
1524
  function readUpgradeSnapshot() {
462
1525
  try {
463
- const configRoot = path3.dirname(path3.dirname(ipcDiscoveryRoot()));
464
- return JSON.parse(fs2.readFileSync(path3.join(configRoot, "manager", "upgrade.json"), "utf8"));
1526
+ const configRoot = path5.dirname(path5.dirname(ipcDiscoveryRoot()));
1527
+ return JSON.parse(fs4.readFileSync(path5.join(configRoot, "manager", "upgrade.json"), "utf8"));
465
1528
  } catch {
466
1529
  return void 0;
467
1530
  }
@@ -480,8 +1543,8 @@ function upgradeSummaryLine() {
480
1543
  function candidateModels() {
481
1544
  const out = /* @__PURE__ */ new Set();
482
1545
  try {
483
- const configRoot = path3.dirname(path3.dirname(ipcDiscoveryRoot()));
484
- const config = JSON.parse(fs2.readFileSync(path3.join(configRoot, "models.json"), "utf8"));
1546
+ const configRoot = path5.dirname(path5.dirname(ipcDiscoveryRoot()));
1547
+ const config = JSON.parse(fs4.readFileSync(path5.join(configRoot, "models.json"), "utf8"));
485
1548
  const d = config.defaults ?? {};
486
1549
  if (d.provider && d.modelId) out.add(`${d.provider}/${d.modelId}`);
487
1550
  for (const cls of Object.values(d.modelClasses ?? {})) {
@@ -515,6 +1578,116 @@ ${rows.join("\n")}` : "_No live pie sessions_",
515
1578
  actions: actions.length > 0 ? actions : [{ id: "panel.summon", label: "\u21A9\uFE0F Back to panel" }]
516
1579
  }, patchOrigin: false };
517
1580
  }
1581
+ if (input.cmd === "panel.context") {
1582
+ const peers = scanPeers();
1583
+ const rows = peers.map((p) => `| ${p.sessionTitle ?? p.name} | ${p.model ?? "\u2014"} | ${p.state} |`);
1584
+ const actions = peers.map((p) => ({ id: `panel.context.${p.instanceId}`, label: `\u{1F4CA} ${p.name.slice(0, 12)}` })).slice(0, 18);
1585
+ return { spec: {
1586
+ title: "Context Report",
1587
+ subtitle: `${peers.length} session(s) \xB7 pick a session to read its context estimate`,
1588
+ color: "violet",
1589
+ body: [
1590
+ peers.length > 0 ? `| Session | Model | State |
1591
+ |---|---|---|
1592
+ ${rows.join("\n")}` : "_No live pie sessions_",
1593
+ ``,
1594
+ "Each button asks the target host for its context ESTIMATE (same figures the TUI /debugs/context report shows). TUI sessions may not support this control yet."
1595
+ ].join("\n"),
1596
+ actions: actions.length > 0 ? actions : [{ id: "panel.summon", label: "\u21A9\uFE0F Back to panel" }]
1597
+ }, patchOrigin: false };
1598
+ }
1599
+ if (input.cmd === "panel.compact") {
1600
+ const peers = scanPeers();
1601
+ const rows = peers.map((p) => `| ${p.sessionTitle ?? p.name} | ${p.model ?? "\u2014"} | ${p.state} |`);
1602
+ const actions = peers.map((p) => ({ id: `panel.compact.${p.instanceId}`, label: `\u{1F9F9} ${p.name.slice(0, 12)}`, requireAllowUsers: true })).slice(0, 18);
1603
+ return { spec: {
1604
+ title: "Compact Context",
1605
+ subtitle: `${peers.length} session(s) \xB7 manual compaction replaces history with a checkpoint summary`,
1606
+ color: "violet",
1607
+ body: [
1608
+ peers.length > 0 ? `| Session | Model | State |
1609
+ |---|---|---|
1610
+ ${rows.join("\n")}` : "_No live pie sessions_",
1611
+ ``,
1612
+ "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."
1613
+ ].join("\n"),
1614
+ actions: actions.length > 0 ? actions : [{ id: "panel.summon", label: "\u21A9\uFE0F Back to panel" }]
1615
+ }, patchOrigin: false };
1616
+ }
1617
+ if (input.cmd === "panel.actions") {
1618
+ const all = managerActions();
1619
+ const PAGE_SIZE = 15;
1620
+ const totalPages = Math.max(1, Math.ceil(all.length / PAGE_SIZE));
1621
+ const rawPage = input.payload?.page;
1622
+ const requested = typeof rawPage === "number" && Number.isFinite(rawPage) ? Math.floor(rawPage) : 1;
1623
+ const page = Math.min(Math.max(1, requested), totalPages);
1624
+ const slice = all.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);
1625
+ const rows = slice.map((a) => `| ${a.label} | ${a.runs} | ${a.lastRunBy ?? "\u2014"} | ${a.creator?.name ?? "\u2014"} |`);
1626
+ const nav = [];
1627
+ if (page > 1) nav.push({ id: "panel.actions", label: `\u2190 \u7B2C ${page - 1} \u9875`, payload: { page: page - 1 } });
1628
+ if (page < totalPages) nav.push({ id: "panel.actions", label: `\u7B2C ${page + 1} \u9875 \u2192`, payload: { page: page + 1 } });
1629
+ return { spec: {
1630
+ title: "\u5168\u90E8\u52A8\u4F5C",
1631
+ subtitle: `${all.length} registered \xB7 page ${page}/${totalPages} \xB7 click to run (zero LLM \u2014 the script executes directly)`,
1632
+ color: "violet",
1633
+ body: [
1634
+ all.length > 0 ? `| Action | Runs | Last by | Created by |
1635
+ |---|---|---|---|
1636
+ ${rows.join("\n")}` : '_No custom actions yet \u2014 ask the manager to build one ("\u5E2E\u6211\u505A\u4E2A\u6309\u94AE,\u80FD\u2026")_',
1637
+ ``,
1638
+ "Every run is bylined with its triggerer and appended to the audit log."
1639
+ ].join("\n"),
1640
+ actions: [
1641
+ ...slice.map((a) => ({ id: `panel.action.${a.id}`, label: a.label.slice(0, 20) })),
1642
+ ...nav,
1643
+ { id: "panel.summon", label: "\u21A9\uFE0F Back to panel" }
1644
+ ].slice(0, 18)
1645
+ }, patchOrigin: false };
1646
+ }
1647
+ const workerView = /^panel\.worker\.([A-Za-z0-9-]+)$/.exec(input.cmd);
1648
+ if (workerView) {
1649
+ const peerId = workerView[1];
1650
+ const peer = scanPeers().find((p) => p.instanceId === peerId);
1651
+ if (!peer) {
1652
+ return { spec: {
1653
+ title: "Worker \u4E0D\u5728\u7EBF",
1654
+ 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",
1655
+ actions: [{ id: "panel.summon", label: "\u21A9\uFE0F Back to panel" }]
1656
+ }, patchOrigin: false };
1657
+ }
1658
+ const wActions = workerActions(peer.name);
1659
+ const workerCtx = { worker: { name: peer.name, ref: peer.instanceId } };
1660
+ const title = peer.sessionTitle ?? peer.name;
1661
+ const state = peer.state === "working" && peer.currentTool ? `working\xB7${peer.currentTool}` : peer.state;
1662
+ return { spec: {
1663
+ title: `\u{1F527} ${title}`,
1664
+ subtitle: `${peer.project ?? "\u2014"} \xB7 ${peer.model ?? "\u2014"} \xB7 ${state}`,
1665
+ color: "green",
1666
+ body: [
1667
+ `| Field | Value |
1668
+ |---|---|
1669
+ | name | ${peer.name} |
1670
+ | state | ${state} |
1671
+ | model | ${peer.model ?? "\u2014"} |
1672
+ | version | ${peer.version ?? "\u2014"} |${peer.cwd ? `
1673
+ | cwd | ${peer.cwd} |` : ""}`,
1674
+ ``,
1675
+ 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
1676
+ | Action | Runs | Last by |
1677
+ |---|---|---|
1678
+ ${wActions.map((a) => `| ${a.label} | ${a.runs} | ${a.lastRunBy ?? "\u2014"} |`).join("\n")}${wActions.length > 15 ? `
1679
+
1680
+ _\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_
1681
+ ${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_"
1682
+ ].join("\n"),
1683
+ actions: [
1684
+ { id: `panel.context.${peer.instanceId}`, label: "\u{1F4CA} Context" },
1685
+ { id: `panel.compact.${peer.instanceId}`, label: "\u{1F9F9} Compact", requireAllowUsers: true },
1686
+ ...wActions.slice(0, 15).map((a) => ({ id: `panel.action.${a.id}`, label: a.label.slice(0, 20), payload: workerCtx })),
1687
+ { id: "panel.summon", label: "\u21A9\uFE0F Back" }
1688
+ ].slice(0, 18)
1689
+ }, patchOrigin: false };
1690
+ }
518
1691
  if (input.cmd === "panel.upgrade") {
519
1692
  const snap = readUpgradeSnapshot();
520
1693
  const current = pieVersion();
@@ -543,7 +1716,7 @@ ${rows.join("\n")}` : "_No live pie sessions_",
543
1716
  if (input.cmd === "panel.help") {
544
1717
  return { spec: {
545
1718
  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.",
1719
+ 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
1720
  actions: [{ id: "panel.summon", label: "Back to panel" }]
548
1721
  }, patchOrigin: false };
549
1722
  }
@@ -552,13 +1725,13 @@ ${rows.join("\n")}` : "_No live pie sessions_",
552
1725
 
553
1726
  // builtin/extensions/im-forward/event-dispatch.ts
554
1727
  import * as net from "node:net";
555
- import * as fs3 from "node:fs";
556
- import * as path4 from "node:path";
1728
+ import * as fs5 from "node:fs";
1729
+ import * as path6 from "node:path";
557
1730
  import { createHmac, randomUUID as randomUUID2 } from "node:crypto";
558
1731
  function discoveryDir() {
559
- return path4.join(addressBookRoot(), "run", "ipc");
1732
+ return path6.join(addressBookRoot(), "run", "ipc");
560
1733
  }
561
- function pidAlive2(pid) {
1734
+ function pidAlive3(pid) {
562
1735
  if (!Number.isInteger(pid) || pid <= 0) return false;
563
1736
  try {
564
1737
  process.kill(pid, 0);
@@ -570,7 +1743,7 @@ function pidAlive2(pid) {
570
1743
  function findOwnerInstance(sessionId) {
571
1744
  let entries;
572
1745
  try {
573
- entries = fs3.readdirSync(discoveryDir());
1746
+ entries = fs5.readdirSync(discoveryDir());
574
1747
  } catch {
575
1748
  return void 0;
576
1749
  }
@@ -578,8 +1751,8 @@ function findOwnerInstance(sessionId) {
578
1751
  for (const name of entries.slice(0, 256)) {
579
1752
  if (!name.endsWith(".json")) continue;
580
1753
  try {
581
- const parsed = JSON.parse(fs3.readFileSync(path4.join(discoveryDir(), name), "utf8"));
582
- if (parsed.instanceId === name.slice(0, -".json".length) && parsed.sessionId === sessionId && parsed.port && typeof parsed.secret === "string" && parsed.protocol === IPC_PROTOCOL_VERSION && pidAlive2(parsed.pid ?? 0)) {
1754
+ const parsed = JSON.parse(fs5.readFileSync(path6.join(discoveryDir(), name), "utf8"));
1755
+ 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
1756
  candidates.push({ file: parsed, startedAt: typeof parsed.startedAt === "number" ? parsed.startedAt : 0 });
584
1757
  }
585
1758
  } catch {
@@ -592,7 +1765,7 @@ function findOwnerInstance(sessionId) {
592
1765
  function findNamedOwnerInstance(name, binding) {
593
1766
  let entries;
594
1767
  try {
595
- entries = fs3.readdirSync(discoveryDir()).filter((entry) => entry.endsWith(".json"));
1768
+ entries = fs5.readdirSync(discoveryDir()).filter((entry) => entry.endsWith(".json"));
596
1769
  } catch {
597
1770
  return void 0;
598
1771
  }
@@ -600,8 +1773,8 @@ function findNamedOwnerInstance(name, binding) {
600
1773
  const matches = [];
601
1774
  for (const entry of entries) {
602
1775
  try {
603
- const peer = JSON.parse(fs3.readFileSync(path4.join(discoveryDir(), entry), "utf8"));
604
- if (peer.sessionName?.trim() !== name || !pidAlive2(peer.pid)) continue;
1776
+ const peer = JSON.parse(fs5.readFileSync(path6.join(discoveryDir(), entry), "utf8"));
1777
+ if (peer.sessionName?.trim() !== name || !pidAlive3(peer.pid)) continue;
605
1778
  matches.push(peer);
606
1779
  } catch {
607
1780
  return void 0;
@@ -622,7 +1795,7 @@ var SYNTHETIC_SENDER = (() => {
622
1795
  return `pie-${hex.slice(0, 12)}`;
623
1796
  })();
624
1797
  function deliverOnce(port, secret, text, targetSessionId, targetInstanceId) {
625
- return new Promise((resolve5) => {
1798
+ return new Promise((resolve6) => {
626
1799
  const id = randomUUID2();
627
1800
  const envelope = {
628
1801
  v: IPC_PROTOCOL_VERSION,
@@ -650,7 +1823,7 @@ function deliverOnce(port, secret, text, targetSessionId, targetInstanceId) {
650
1823
  settled = true;
651
1824
  clearTimeout(timer);
652
1825
  socket.destroy();
653
- resolve5(ok);
1826
+ resolve6(ok);
654
1827
  };
655
1828
  const timer = setTimeout(() => finish(false), 5e3);
656
1829
  socket.once("error", () => finish(false));
@@ -698,16 +1871,16 @@ async function dispatchEventToSession(sessionId, eventText) {
698
1871
  }
699
1872
 
700
1873
  // builtin/extensions/im-forward/session-roots.ts
701
- import * as fs4 from "node:fs";
702
- import * as path5 from "node:path";
1874
+ import * as fs6 from "node:fs";
1875
+ import * as path7 from "node:path";
703
1876
  function rootsDir() {
704
- return path5.join(addressBookRoot(), "im-forward", "roots");
1877
+ return path7.join(addressBookRoot(), "im-forward", "roots");
705
1878
  }
706
1879
  function rootPath(provider, messageId) {
707
1880
  const safe = `${provider}:${messageId}`.replace(/[^a-zA-Z0-9._:-]/g, "_");
708
- return path5.join(rootsDir(), `${safe}.json`);
1881
+ return path7.join(rootsDir(), `${safe}.json`);
709
1882
  }
710
- function pidAlive3(pid) {
1883
+ function pidAlive4(pid) {
711
1884
  if (!Number.isInteger(pid) || pid <= 0) return false;
712
1885
  try {
713
1886
  process.kill(pid, 0);
@@ -721,17 +1894,17 @@ function claimSessionRoot(provider, messageId, sessionId) {
721
1894
  try {
722
1895
  const record = { sessionId, pid: process.pid, claimedAt: Date.now() };
723
1896
  const target = rootPath(provider, messageId);
724
- fs4.mkdirSync(rootsDir(), { recursive: true, mode: 448 });
725
- fs4.writeFileSync(target, `${JSON.stringify(record)}
1897
+ fs6.mkdirSync(rootsDir(), { recursive: true, mode: 448 });
1898
+ fs6.writeFileSync(target, `${JSON.stringify(record)}
726
1899
  `);
727
1900
  } catch {
728
1901
  }
729
1902
  }
730
1903
  function sessionRootOwner(provider, messageId) {
731
1904
  try {
732
- const parsed = JSON.parse(fs4.readFileSync(rootPath(provider, messageId), "utf8"));
1905
+ const parsed = JSON.parse(fs6.readFileSync(rootPath(provider, messageId), "utf8"));
733
1906
  if (typeof parsed.sessionId === "string" && parsed.sessionId && typeof parsed.pid === "number") {
734
- if (!pidAlive3(parsed.pid)) return void 0;
1907
+ if (!pidAlive4(parsed.pid)) return { sessionId: parsed.sessionId, pid: parsed.pid, claimedAt: parsed.claimedAt ?? 0, ownerOffline: true };
735
1908
  return { sessionId: parsed.sessionId, pid: parsed.pid, claimedAt: parsed.claimedAt ?? 0 };
736
1909
  }
737
1910
  return void 0;
@@ -741,18 +1914,18 @@ function sessionRootOwner(provider, messageId) {
741
1914
  }
742
1915
 
743
1916
  // builtin/extensions/im-forward/session-anchors.ts
744
- import * as fs5 from "node:fs";
745
- import * as path6 from "node:path";
1917
+ import * as fs7 from "node:fs";
1918
+ import * as path8 from "node:path";
746
1919
  function anchorsDir() {
747
- return path6.join(addressBookRoot(), "im-forward", "anchors");
1920
+ return path8.join(addressBookRoot(), "im-forward", "anchors");
748
1921
  }
749
1922
  function anchorPath(sessionId) {
750
1923
  const safe = sessionId.replace(/[^a-zA-Z0-9._-]/g, "_");
751
- return path6.join(anchorsDir(), `${safe}.json`);
1924
+ return path8.join(anchorsDir(), `${safe}.json`);
752
1925
  }
753
1926
  function loadPersistedAnchor(sessionId, identity) {
754
1927
  try {
755
- const raw = fs5.readFileSync(anchorPath(sessionId), "utf8");
1928
+ const raw = fs7.readFileSync(anchorPath(sessionId), "utf8");
756
1929
  const parsed = JSON.parse(raw);
757
1930
  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
1931
  // anchor may live in ANY room — a group chat id differs from the
@@ -781,8 +1954,8 @@ function savePersistedAnchor(sessionId, identity, anchor) {
781
1954
  anchor
782
1955
  };
783
1956
  const target = anchorPath(sessionId);
784
- fs5.mkdirSync(path6.dirname(target), { recursive: true });
785
- fs5.writeFileSync(target, `${JSON.stringify(file)}
1957
+ fs7.mkdirSync(path8.dirname(target), { recursive: true });
1958
+ fs7.writeFileSync(target, `${JSON.stringify(file)}
786
1959
  `, "utf8");
787
1960
  } catch {
788
1961
  }
@@ -796,7 +1969,7 @@ var RESTART_BACKOFF_MIN_MS = 5e3;
796
1969
  var RESTART_BACKOFF_MAX_MS = 6e4;
797
1970
  var SEND_FAILURE_NOTIFY_THROTTLE_MS = 5 * 60 * 1e3;
798
1971
  var CHUNK_RETRY_DELAY_MS = 2e3;
799
- var delay = (ms) => new Promise((resolve5) => setTimeout(resolve5, ms));
1972
+ var delay = (ms) => new Promise((resolve6) => setTimeout(resolve6, ms));
800
1973
  var MAX_INBOUND_RETRIES = 3;
801
1974
  var DEFAULT_INBOUND_RETRY_BACKOFF_MS = 5e3;
802
1975
  var MAX_PENDING_IM_INPUTS = 50;
@@ -836,10 +2009,10 @@ function ipcDiscoveryRoot2() {
836
2009
  }
837
2010
  function liveManagerForBinding(binding) {
838
2011
  try {
839
- for (const file of fs6.readdirSync(ipcDiscoveryRoot2())) {
2012
+ for (const file of fs8.readdirSync(ipcDiscoveryRoot2())) {
840
2013
  if (!file.endsWith(".json")) continue;
841
2014
  try {
842
- const peer = JSON.parse(fs6.readFileSync(pathJoin(ipcDiscoveryRoot2(), file), "utf8"));
2015
+ const peer = JSON.parse(fs8.readFileSync(pathJoin(ipcDiscoveryRoot2(), file), "utf8"));
843
2016
  if (peer.pid === process.pid || peer.isManager !== true || peer.imBinding !== binding || !Number.isInteger(peer.pid) || !peer.pid || peer.pid <= 0) continue;
844
2017
  try {
845
2018
  process.kill(peer.pid, 0);
@@ -854,13 +2027,13 @@ function liveManagerForBinding(binding) {
854
2027
  }
855
2028
  return false;
856
2029
  }
857
- async function applyModelControl(peerRef, model) {
2030
+ async function applyPeerControl(peerRef, control, payload) {
858
2031
  const net2 = await import("node:net");
859
2032
  let target;
860
2033
  try {
861
2034
  const dir = ipcDiscoveryRoot2();
862
- for (const file of fs6.readdirSync(dir).filter((f) => f.endsWith(".json"))) {
863
- const parsed = JSON.parse(fs6.readFileSync(join7(dir, file), "utf8"));
2035
+ for (const file of fs8.readdirSync(dir).filter((f) => f.endsWith(".json"))) {
2036
+ const parsed = JSON.parse(fs8.readFileSync(join9(dir, file), "utf8"));
864
2037
  if (!parsed.port || !parsed.secret || typeof parsed.pid !== "number" || !parsed.instanceId || typeof parsed.sessionId !== "string" || !parsed.sessionId) continue;
865
2038
  const match = parsed.instanceId === peerRef || parsed.instanceId.startsWith(peerRef) || parsed.displayName === peerRef;
866
2039
  if (!match) continue;
@@ -877,15 +2050,15 @@ async function applyModelControl(peerRef, model) {
877
2050
  if (!target) return { ok: false, detail: `Session not found: ${peerRef}` };
878
2051
  const envelope = signEnvelope({
879
2052
  v: IPC_PROTOCOL_VERSION,
880
- id: `panel-model-${Date.now()}`,
2053
+ id: `panel-${control.replace(/\./g, "")}-${crypto.randomUUID()}`,
881
2054
  from: "pie-panel0000000",
882
2055
  to: target.instanceId,
883
2056
  kind: "control",
884
2057
  sessionId: target.sessionId,
885
2058
  createdAt: Date.now(),
886
- text: JSON.stringify({ control: "model.set", payload: { model } })
2059
+ text: JSON.stringify({ control, payload })
887
2060
  }, target.secret);
888
- return await new Promise((resolve5) => {
2061
+ return await new Promise((resolve6) => {
889
2062
  let settled = false;
890
2063
  const finish = (ok, detail) => {
891
2064
  if (settled) return;
@@ -894,7 +2067,7 @@ async function applyModelControl(peerRef, model) {
894
2067
  sock.destroy();
895
2068
  } catch {
896
2069
  }
897
- resolve5({ ok, detail });
2070
+ resolve6({ ok, detail });
898
2071
  };
899
2072
  const sock = net2.connect({ host: "127.0.0.1", port: target.port }, () => {
900
2073
  sock.write(JSON.stringify(envelope) + "\n");
@@ -920,6 +2093,39 @@ async function applyModelControl(peerRef, model) {
920
2093
  });
921
2094
  });
922
2095
  }
2096
+ async function applyModelControl(peerRef, model) {
2097
+ return applyPeerControl(peerRef, "model.set", { model });
2098
+ }
2099
+ function renderContextReceipt(peer, receipt) {
2100
+ if (!receipt.ok) return `\u26A0\uFE0F ${peer}
2101
+
2102
+ ${receipt.detail}`;
2103
+ const fallback = `\u{1F4CA} ${peer}
2104
+
2105
+ ${receipt.detail}`;
2106
+ const ackStart = receipt.detail.indexOf("{");
2107
+ if (ackStart < 0) return fallback;
2108
+ try {
2109
+ const ack = JSON.parse(receipt.detail.slice(ackStart));
2110
+ if (ack.ok !== true || typeof ack.message !== "string") return fallback;
2111
+ const r = JSON.parse(ack.message);
2112
+ return `\u{1F4CA} **Context estimate** \xB7 ${peer}
2113
+
2114
+ | | |
2115
+ |---|---|
2116
+ | Estimated tokens | ${typeof r.estimatedTokens === "number" ? r.estimatedTokens.toLocaleString() : "?"} |
2117
+ | Context window | ${r.contextWindow ? r.contextWindow.toLocaleString() : "unknown"} |
2118
+ | Usage | ${typeof r.percent === "number" ? `${r.percent}%` : "unknown"} |
2119
+ | Auto-compact | ${r.autoCompactEnabled ? `at ${(r.autoCompactLimitTokens ?? 0).toLocaleString()} tokens` : "off"} |
2120
+ | Queued inputs | ${r.pendingQueuedInputs ?? 0} |
2121
+ | State | ${r.compactionRunning ? "compacting" : r.isStreaming ? "working" : "idle"} |${r.lastCompactOutcome ? `
2122
+ | Last compact | ${r.lastCompactOutcome} |` : ""}
2123
+
2124
+ _Estimate (bytes/4 heuristic) \u2014 same basis as the TUI's /debugs/context report._`;
2125
+ } catch {
2126
+ return fallback;
2127
+ }
2128
+ }
923
2129
  function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
924
2130
  const IM_INPUT_PREFIX = connection.sourcePrefix;
925
2131
  const key = (id) => JSON.stringify([cfg.provider, id]);
@@ -1440,8 +2646,8 @@ ${recoveryHint}`,
1440
2646
  };
1441
2647
  const claimStake = () => {
1442
2648
  let release;
1443
- const token = new Promise((resolve5) => {
1444
- release = resolve5;
2649
+ const token = new Promise((resolve6) => {
2650
+ release = resolve6;
1445
2651
  });
1446
2652
  token.release = release;
1447
2653
  anchorStakeFlights.set(sessionId, token);
@@ -1614,18 +2820,18 @@ ${recoveryHint}`,
1614
2820
  const files = collectFileReferences(
1615
2821
  text,
1616
2822
  ctx.cwd,
1617
- (path12) => {
2823
+ (path13) => {
1618
2824
  try {
1619
- const stat = fs6.statSync(path12);
2825
+ const stat = fs8.statSync(path13);
1620
2826
  return { isFile: stat.isFile(), size: stat.size };
1621
2827
  } catch {
1622
2828
  return null;
1623
2829
  }
1624
2830
  },
1625
2831
  {
1626
- canonicalize: (path12) => {
2832
+ canonicalize: (path13) => {
1627
2833
  try {
1628
- return fs6.realpathSync(path12);
2834
+ return fs8.realpathSync(path13);
1629
2835
  } catch {
1630
2836
  return null;
1631
2837
  }
@@ -1777,9 +2983,16 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1777
2983
  const t = threadOwner({ provider: cfg.provider, threadId: meta.threadId });
1778
2984
  if (t.corrupt || t.unavailable) unknown = true;
1779
2985
  ownerSession = t.sessionId;
2986
+ if (t.ownerOffline && ownerSession) {
2987
+ ctx.log(`im-forward: thread owner ${ownerSession} offline in registry (stale pid); dispatching by session id`);
2988
+ }
1780
2989
  }
1781
2990
  if (!ownerSession && !unknown && meta.replyTo) {
1782
- ownerSession = sessionRootOwner(cfg.provider, meta.replyTo)?.sessionId;
2991
+ const root = sessionRootOwner(cfg.provider, meta.replyTo);
2992
+ ownerSession = root?.sessionId;
2993
+ if (root?.ownerOffline && ownerSession) {
2994
+ ctx.log(`im-forward: root owner ${ownerSession} offline in registry (stale pid); dispatching by session id`);
2995
+ }
1783
2996
  }
1784
2997
  if (unknown) return { kind: "unknown-owner" };
1785
2998
  if (!ownerSession) return { kind: "no-owner" };
@@ -1834,6 +3047,59 @@ ${spec.body}`, `panel-model-${event.event_id}`);
1834
3047
  }
1835
3048
  return;
1836
3049
  }
3050
+ const contextAction = /^panel\.context\.([A-Za-z0-9-]+)$/.exec(panelCmd.cmd);
3051
+ if (contextAction) {
3052
+ const receipt = await applyPeerControl(contextAction[1], "session.context", {});
3053
+ if (!isCurrent()) return;
3054
+ const spec = {
3055
+ title: "Context Report",
3056
+ body: renderContextReceipt(contextAction[1], receipt),
3057
+ actions: [{ id: "panel.context", label: "\u21A9\uFE0F Back to context list" }]
3058
+ };
3059
+ try {
3060
+ if (connection.sendCard) {
3061
+ const sent = await connection.sendCard(event.chat_id, spec, `panel-context-${event.event_id}`);
3062
+ if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
3063
+ } else await connection.send(event.chat_id, `**${spec.title}**
3064
+ ${spec.body}`, `panel-context-${event.event_id}`);
3065
+ } catch {
3066
+ }
3067
+ return;
3068
+ }
3069
+ const compactAction = /^panel\.compact\.([A-Za-z0-9-]+)$/.exec(panelCmd.cmd);
3070
+ if (compactAction) {
3071
+ if (!cfg.allowUsers || !event.sender_id || !cfg.allowUsers.includes(event.sender_id)) {
3072
+ ctx.log(`im-forward: panel.compact refused for ${event.sender_id ?? "unknown"} (execution-sink gate: allowUsers membership required)`);
3073
+ try {
3074
+ await connection.send(event.chat_id, "\u26D4\uFE0F Compacting a session requires admin rights (allowUsers).", `panel-refused-${event.event_id}`);
3075
+ } catch {
3076
+ }
3077
+ return;
3078
+ }
3079
+ const receipt = await applyPeerControl(compactAction[1], "session.compact", {});
3080
+ if (!isCurrent()) return;
3081
+ const spec = {
3082
+ title: receipt.ok ? "Compaction Submitted" : "Compaction Refused",
3083
+ body: `${receipt.ok ? "\u{1F9F9}" : "\u26A0\uFE0F"} ${compactAction[1]}
3084
+
3085
+ ${receipt.detail}
3086
+
3087
+ ${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." : "Retry when the session is idle, or pick a different session."}`,
3088
+ actions: [
3089
+ { id: `panel.context.${compactAction[1]}`, label: "\u{1F4CA} Check context" },
3090
+ { id: "panel.compact", label: "\u21A9\uFE0F Back to compact list" }
3091
+ ]
3092
+ };
3093
+ try {
3094
+ if (connection.sendCard) {
3095
+ const sent = await connection.sendCard(event.chat_id, spec, `panel-compact-${event.event_id}`);
3096
+ if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
3097
+ } else await connection.send(event.chat_id, `**${spec.title}**
3098
+ ${spec.body}`, `panel-compact-${event.event_id}`);
3099
+ } catch {
3100
+ }
3101
+ return;
3102
+ }
1837
3103
  if (panelCmd.cmd === "panel.upgrade.confirm") {
1838
3104
  if (!cfg.allowUsers || !event.sender_id || !cfg.allowUsers.includes(event.sender_id)) {
1839
3105
  ctx.log(`im-forward: panel.upgrade.confirm refused for ${event.sender_id ?? "unknown"} (execution-sink gate: allowUsers membership required)`);
@@ -1843,7 +3109,7 @@ ${spec.body}`, `panel-model-${event.event_id}`);
1843
3109
  }
1844
3110
  return;
1845
3111
  }
1846
- const spawn5 = await import("node:child_process");
3112
+ const spawn6 = await import("node:child_process");
1847
3113
  const started2 = Date.now();
1848
3114
  let actorOk = false;
1849
3115
  let actorDetail = "";
@@ -1851,27 +3117,27 @@ ${spec.body}`, `panel-model-${event.event_id}`);
1851
3117
  const entry = process.argv[1] ? pathResolve(process.argv[1]) : "";
1852
3118
  if (!entry) throw new Error("cannot resolve the pie entry point");
1853
3119
  const configRoot = pathDirname(pathDirname(ipcDiscoveryRoot2()));
1854
- const logFile = join7(configRoot, "manager", "upgrade-actor.log");
3120
+ const logFile = join9(configRoot, "manager", "upgrade-actor.log");
1855
3121
  let out;
1856
3122
  try {
1857
- fs6.mkdirSync(pathDirname(logFile), { recursive: true });
1858
- out = fs6.openSync(logFile, "a");
3123
+ fs8.mkdirSync(pathDirname(logFile), { recursive: true });
3124
+ out = fs8.openSync(logFile, "a");
1859
3125
  } catch {
1860
3126
  out = void 0;
1861
3127
  }
1862
- const child = spawn5.spawn(process.execPath, [entry, "manager", "upgrade"], {
3128
+ const child = spawn6.spawn(process.execPath, [entry, "manager", "upgrade"], {
1863
3129
  cwd: process.cwd(),
1864
3130
  detached: true,
1865
3131
  stdio: out !== void 0 ? ["ignore", out, out] : "ignore",
1866
3132
  windowsHide: true,
1867
3133
  env: process.env
1868
3134
  });
1869
- const spawnOutcome = await new Promise((resolve5) => {
3135
+ const spawnOutcome = await new Promise((resolve6) => {
1870
3136
  let settled = false;
1871
3137
  const settle = (v) => {
1872
3138
  if (!settled) {
1873
3139
  settled = true;
1874
- resolve5(v);
3140
+ resolve6(v);
1875
3141
  }
1876
3142
  };
1877
3143
  child.once("spawn", () => settle("spawned"));
@@ -1884,7 +3150,7 @@ ${spec.body}`, `panel-model-${event.event_id}`);
1884
3150
  child.unref();
1885
3151
  if (out !== void 0) {
1886
3152
  try {
1887
- fs6.closeSync(out);
3153
+ fs8.closeSync(out);
1888
3154
  } catch {
1889
3155
  }
1890
3156
  }
@@ -1895,26 +3161,250 @@ ${spec.body}`, `panel-model-${event.event_id}`);
1895
3161
  actorDetail = `actor pid ${child.pid}${spawnOutcome === "timeout" ? " (spawn unconfirmed \u2014 will report via /panel)" : ""} \xB7 log ${logFile}`;
1896
3162
  }
1897
3163
  } catch (error) {
1898
- actorDetail = error instanceof Error ? error.message : String(error);
3164
+ actorDetail = error instanceof Error ? error.message : String(error);
3165
+ }
3166
+ ctx.log(`im-forward: panel.upgrade.confirm actor spawn ${actorOk ? "ok" : "failed"} (${actorDetail}, runtimeMs=${Date.now() - started2})`);
3167
+ const spec = {
3168
+ title: actorOk ? "Upgrade Started" : "Upgrade Failed to Start",
3169
+ body: actorOk ? `\u2B06\uFE0F npm install + manager restart running in the background.
3170
+
3171
+ ${actorDetail}
3172
+
3173
+ 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}`,
3174
+ actions: actorOk ? [{ id: "panel.refresh", label: "\u{1F504} Refresh" }] : [{ id: "panel.upgrade", label: "\u21A9\uFE0F Back to upgrade card" }]
3175
+ };
3176
+ try {
3177
+ if (connection.sendCard) {
3178
+ const sent = await connection.sendCard(event.chat_id, spec, `panel-upgrade-${event.event_id}`);
3179
+ if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
3180
+ } else await connection.send(event.chat_id, `**${spec.title}**
3181
+ ${spec.body}`, `panel-upgrade-${event.event_id}`);
3182
+ } catch {
3183
+ }
3184
+ return;
3185
+ }
3186
+ const actionMatch = /^panel\.action\.([a-z0-9][a-z0-9-]{0,31})$/.exec(panelCmd.cmd);
3187
+ if (actionMatch) {
3188
+ const actionId = actionMatch[1];
3189
+ const runtimeAlive = () => !terminated;
3190
+ const sendActionCard = async (spec, key2, guard) => {
3191
+ if (!guard()) return void 0;
3192
+ try {
3193
+ if (connection.sendCard) {
3194
+ const sent = await connection.sendCard(event.chat_id, spec, key2);
3195
+ if (guard()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
3196
+ return sent?.messageId;
3197
+ }
3198
+ await connection.send(event.chat_id, `**${spec.title ?? "Action"}**
3199
+ ${spec.body}`, key2);
3200
+ } catch {
3201
+ }
3202
+ return void 0;
3203
+ };
3204
+ const action = findAction(actionId);
3205
+ if (!action) {
3206
+ await sendActionCard({
3207
+ title: "\u26A0\uFE0F \u52A8\u4F5C\u5DF2\u79FB\u9664",
3208
+ body: `\`${actionId}\` \u4E0D\u5728\u6CE8\u518C\u8868\u91CC\uFF08\u53EF\u80FD\u5DF2\u88AB\u5220\u9664\uFF09\u3002
3209
+
3210
+ \u70B9 /panel \u7684 \u26A1 \u5168\u90E8\u52A8\u4F5C \u67E5\u770B\u5F53\u524D\u53EF\u7528\u7684\u6309\u94AE\u3002`,
3211
+ actions: [{ id: "panel.actions", label: "\u26A1 \u5168\u90E8\u52A8\u4F5C" }, { id: "panel.summon", label: "\u21A9\uFE0F Back to panel" }]
3212
+ }, `panel-action-gone-${event.event_id}`, isCurrent);
3213
+ return;
3214
+ }
3215
+ let workerCtx;
3216
+ if (action.scope !== "manager") {
3217
+ const payloadWorker = (() => {
3218
+ const w = isRecord(panelCmd.payload) ? panelCmd.payload.worker : void 0;
3219
+ if (!isRecord(w)) return void 0;
3220
+ return {
3221
+ name: typeof w.name === "string" && w.name ? w.name : void 0,
3222
+ ref: typeof w.ref === "string" && w.ref ? w.ref : void 0
3223
+ };
3224
+ })();
3225
+ let peer;
3226
+ if (action.scope.startsWith("worker:")) {
3227
+ peer = findPeerByName(action.scope.slice("worker:".length));
3228
+ } else if (payloadWorker?.ref) {
3229
+ peer = findPeerByInstanceId(payloadWorker.ref);
3230
+ } else if (payloadWorker?.name) {
3231
+ peer = findPeerByName(payloadWorker.name);
3232
+ }
3233
+ if (peer === "ambiguous") {
3234
+ await sendActionCard({
3235
+ title: `\u26A0\uFE0F ${action.label}`,
3236
+ 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`,
3237
+ actions: [{ id: "panel.summon", label: "\u21A9\uFE0F Back to panel" }]
3238
+ }, `panel-action-ambiguous-${event.event_id}`, isCurrent);
3239
+ return;
3240
+ }
3241
+ if (!peer) {
3242
+ const wanted = action.scope.startsWith("worker:") ? action.scope.slice("worker:".length) : payloadWorker?.name ?? payloadWorker?.ref ?? "?";
3243
+ const generic = action.scope === "worker" && !payloadWorker?.name && !payloadWorker?.ref;
3244
+ await sendActionCard({
3245
+ title: `\u26A0\uFE0F ${action.label}`,
3246
+ 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`,
3247
+ actions: [{ id: "panel.summon", label: "\u21A9\uFE0F Back to panel" }]
3248
+ }, `panel-action-offline-${event.event_id}`, isCurrent);
3249
+ return;
3250
+ }
3251
+ workerCtx = { name: peer.name, ref: peer.instanceId, ...peer.cwd ? { dir: peer.cwd } : {} };
3252
+ }
3253
+ const triggerOpenId = event.sender_id;
3254
+ const triggerQuick = peekNameCache(triggerOpenId) ?? fallbackName(triggerOpenId);
3255
+ const lock = await acquireLock(actionId, triggerQuick, action.timeoutMs ?? DEFAULT_TIMEOUT_MS, pathResolve(action.script));
3256
+ if (!lock.ok) {
3257
+ const since = lock.holder.startedAt > 0 ? new Date(lock.holder.startedAt).toLocaleTimeString("en-GB", { hour12: false }) : "?";
3258
+ await sendActionCard({
3259
+ title: `\u23F3 ${action.label}`,
3260
+ 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`,
3261
+ actions: [{ id: "panel.summon", label: "\u21A9\uFE0F Back to panel" }]
3262
+ }, `panel-action-busy-${event.event_id}`, isCurrent);
3263
+ return;
3264
+ }
3265
+ const timeoutS = Math.round((action.timeoutMs ?? DEFAULT_TIMEOUT_MS) / 1e3);
3266
+ let ackMessageId;
3267
+ const publishCancellation = async (body) => {
3268
+ if (!runtimeAlive()) return;
3269
+ const cancelSpec = {
3270
+ title: `\u26A0\uFE0F ${action.label}`,
3271
+ color: "red",
3272
+ body,
3273
+ 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" }]
3274
+ };
3275
+ let patched = false;
3276
+ if (ackMessageId && connection.patch) {
3277
+ try {
3278
+ patched = await connection.patch(ackMessageId, cancelSpec);
3279
+ } catch {
3280
+ patched = false;
3281
+ }
3282
+ }
3283
+ if (!patched) await sendActionCard(cancelSpec, `panel-action-cancel-${event.event_id}`, runtimeAlive);
3284
+ };
3285
+ try {
3286
+ ackMessageId = await sendActionCard({
3287
+ title: `\u{1F680} ${action.label}`,
3288
+ color: "blue",
3289
+ body: `\u7531 ${triggerQuick} \u89E6\u53D1 \xB7 \u8FD0\u884C\u4E2D\u2026\uFF08\u8D85\u65F6\u4E0A\u9650 ${timeoutS}s\uFF09
3290
+
3291
+ \u5B8C\u6210\u540E\u672C\u5361\u81EA\u52A8\u66F4\u65B0\u4E3A\u7ED3\u679C\u3002`,
3292
+ actions: []
3293
+ }, `panel-action-${event.event_id}`, isCurrent);
3294
+ if (!runtimeAlive()) {
3295
+ lock.release();
3296
+ return;
3297
+ }
3298
+ if (!lock.stillOwned()) {
3299
+ await publishCancellation("\u786E\u8BA4\u5361\u53D1\u9001\u8017\u65F6\u8D85\u8FC7\u4E86\u6267\u884C\u69FD\u7684\u5B58\u6D3B\u671F\u9650\uFF0C\u672C\u6B21\u89E6\u53D1\u5DF2\u53D6\u6D88\uFF08\u672A\u6267\u884C\uFF09\u3002\u8BF7\u91CD\u8BD5\u3002");
3300
+ lock.release();
3301
+ return;
3302
+ }
3303
+ } catch (error) {
3304
+ lock.release();
3305
+ ctx.log(`im-forward: panel action ${actionId} ack failed: ${error instanceof Error ? error.message : String(error)}`);
3306
+ return;
1899
3307
  }
1900
- ctx.log(`im-forward: panel.upgrade.confirm actor spawn ${actorOk ? "ok" : "failed"} (${actorDetail}, runtimeMs=${Date.now() - started2})`);
1901
- const spec = {
1902
- title: actorOk ? "Upgrade Started" : "Upgrade Failed to Start",
1903
- body: actorOk ? `\u2B06\uFE0F npm install + manager restart running in the background.
1904
-
1905
- ${actorDetail}
1906
-
1907
- 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
- actions: actorOk ? [{ id: "panel.refresh", label: "\u{1F504} Refresh" }] : [{ id: "panel.upgrade", label: "\u21A9\uFE0F Back to upgrade card" }]
1909
- };
1910
- try {
1911
- if (connection.sendCard) {
1912
- const sent = await connection.sendCard(event.chat_id, spec, `panel-upgrade-${event.event_id}`);
1913
- if (isCurrent()) rememberPanelCard(sent?.messageId, sessionId, event.chat_id);
1914
- } else await connection.send(event.chat_id, `**${spec.title}**
1915
- ${spec.body}`, `panel-upgrade-${event.event_id}`);
1916
- } catch {
3308
+ if (!lock.stillOwned()) {
3309
+ 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");
3310
+ lock.release();
3311
+ return;
1917
3312
  }
3313
+ void (async () => {
3314
+ try {
3315
+ if (!lock.rearm(action.timeoutMs ?? DEFAULT_TIMEOUT_MS)) {
3316
+ 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");
3317
+ return;
3318
+ }
3319
+ ctx.log(`im-forward: panel action ${actionId} triggered by ${triggerQuick} (${triggerOpenId ?? "no-openid"})${workerCtx ? ` as worker ${workerCtx.name}` : ""}`);
3320
+ const result2 = await executeAction({
3321
+ action,
3322
+ trigger: { name: triggerQuick, ...triggerOpenId ? { openId: triggerOpenId } : {} },
3323
+ chatId: event.chat_id,
3324
+ ...workerCtx ? { worker: workerCtx } : {},
3325
+ onChildSpawn: (pid) => lock.announceChild(pid)
3326
+ });
3327
+ if (result2.cancelled) {
3328
+ appendAudit({
3329
+ at: Date.now(),
3330
+ actionId,
3331
+ label: action.label,
3332
+ trigger: { name: triggerQuick, ...triggerOpenId ? { openId: triggerOpenId } : {} },
3333
+ chatId: event.chat_id,
3334
+ ...workerCtx ? { worker: workerCtx.name } : {},
3335
+ durationMs: result2.durationMs,
3336
+ exitCode: result2.exitCode,
3337
+ timedOut: false,
3338
+ ok: false,
3339
+ logFile: result2.logFile
3340
+ });
3341
+ await publishCancellation("\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");
3342
+ return;
3343
+ }
3344
+ const triggerName = await resolveUserName(triggerOpenId, { ...cfg.profile ? { profile: cfg.profile } : {}, ...cfg.larkCliPath ? { binary: cfg.larkCliPath } : {} });
3345
+ bumpRunStats(actionId, triggerName);
3346
+ appendAudit({
3347
+ at: Date.now(),
3348
+ actionId,
3349
+ label: action.label,
3350
+ trigger: { name: triggerName, ...triggerOpenId ? { openId: triggerOpenId } : {} },
3351
+ chatId: event.chat_id,
3352
+ ...workerCtx ? { worker: workerCtx.name } : {},
3353
+ durationMs: result2.durationMs,
3354
+ exitCode: result2.exitCode,
3355
+ timedOut: result2.timedOut,
3356
+ ok: result2.ok,
3357
+ logFile: result2.logFile
3358
+ });
3359
+ if (!runtimeAlive()) return;
3360
+ const icon = result2.timedOut ? "\u23F1\uFE0F" : result2.ok ? "\u2705" : "\u274C";
3361
+ 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`;
3362
+ const outBody = truncateMarkdown(result2.stdout.trim() || (result2.ok ? "_(no output)_" : ""));
3363
+ const logNote = result2.logDegraded ? `
3364
+ _(\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 ? `
3365
+ _(\u8F93\u51FA\u8FC7\u957F\u5DF2\u622A\u65AD;\u5B8C\u6574\u89C1 ${result2.logFile})_` : "";
3366
+ const resultSpec = {
3367
+ title: `${icon} ${action.label}`,
3368
+ color: result2.ok ? "green" : "red",
3369
+ body: [
3370
+ `\u7531 ${triggerName} \u89E6\u53D1 \xB7 ${statusLine}${workerCtx ? ` \xB7 as ${workerCtx.name}` : ""}`,
3371
+ ``,
3372
+ outBody,
3373
+ result2.stderrTail.trim() && !result2.ok ? `
3374
+ **stderr**
3375
+ \`\`\`
3376
+ ${result2.stderrTail.trim().slice(0, 1500)}
3377
+ \`\`\`` : "",
3378
+ logNote
3379
+ ].filter((line) => line !== "").join("\n"),
3380
+ 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" }]
3381
+ };
3382
+ let patched = false;
3383
+ if (ackMessageId && connection.patch) {
3384
+ try {
3385
+ patched = await connection.patch(ackMessageId, resultSpec);
3386
+ } catch {
3387
+ patched = false;
3388
+ }
3389
+ }
3390
+ if (!patched && runtimeAlive()) await sendActionCard(resultSpec, `panel-action-result-${event.event_id}`, runtimeAlive);
3391
+ } catch (error) {
3392
+ ctx.log(`im-forward: panel action ${actionId} execution error: ${error instanceof Error ? error.message : String(error)}`);
3393
+ if (runtimeAlive()) {
3394
+ try {
3395
+ await sendActionCard({
3396
+ title: `\u274C ${action.label}`,
3397
+ color: "red",
3398
+ body: `\u6267\u884C\u5668\u81EA\u8EAB\u51FA\u9519\uFF1A${error instanceof Error ? error.message : String(error)}`,
3399
+ actions: [{ id: "panel.summon", label: "\u21A9\uFE0F \u9762\u677F" }]
3400
+ }, `panel-action-error-${event.event_id}`, runtimeAlive);
3401
+ } catch {
3402
+ }
3403
+ }
3404
+ } finally {
3405
+ lock.release();
3406
+ }
3407
+ })();
1918
3408
  return;
1919
3409
  }
1920
3410
  const result = executePanelCommand({ ...panelCmd, senderId: event.sender_id, originCardId: event.message_id });
@@ -2085,7 +3575,7 @@ ${result.spec.body}`, `panel-${event.event_id}`);
2085
3575
  return;
2086
3576
  }
2087
3577
  if (outcome.kind === "delivery-failed") {
2088
- ctx.log(`im-forward: dispatch to ${outcome.owner} failed for ${messageId}; dropping`);
3578
+ ctx.log(`im-forward: dispatch to ${outcome.owner} failed for ${messageId} (owner may be offline); dropping \u2014 ownership retained, never taken over`);
2089
3579
  return;
2090
3580
  }
2091
3581
  if (outcome.kind === "unknown-owner") {
@@ -2691,410 +4181,121 @@ ${imagelessCaption || (imageKeys.length ? IM_INPUT_FALLBACK_CAPTION : "") || cap
2691
4181
  );
2692
4182
  if (lastSendError)
2693
4183
  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
- }
4184
+ `- last send error: ${lastSendError} (at ${new Date(lastSendErrorAt).toISOString()})`
4185
+ );
4186
+ if (anchorFallbacks)
4187
+ lines.push(`- anchor fallbacks to chat root: ${anchorFallbacks}`);
4188
+ if (pendingInputs.length)
4189
+ lines.push(`- pending turn attributions: ${pendingInputs.length}`);
4190
+ if (retryAttempts.size)
4191
+ lines.push(
4192
+ `- inbound retries pending: ${retryTimers.size} (attempts so far: ${Math.max(...retryAttempts.values())})`
4193
+ );
4194
+ commandCtx.ui.notify(lines.join("\n"), "info");
2924
4195
  }
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;
4196
+ });
2939
4197
  }
2940
- async function shutdownConsumerInner(child) {
2941
- let closed = false;
2942
- const close = new Promise((resolve5) => child.once("close", () => {
2943
- closed = true;
2944
- resolve5();
2945
- }));
2946
- const wait = async (ms) => {
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 {
4198
+
4199
+ // builtin/extensions/im-forward/onboarding.ts
4200
+ async function runSetup(ctx, dir, providers, signal, isCurrent = () => !signal.aborted, intent = "first-run", suspendEventConsumer) {
4201
+ const initial = resolveConfig(ctx.cwd, dir);
4202
+ if (initial.problems.length) {
4203
+ ctx.ui.notify(initial.problems.join("\n"), "error");
4204
+ return;
2956
4205
  }
2957
- await wait(500);
2958
- if (!closed) {
2959
- await stopOwnedTree(child, "SIGTERM");
2960
- await wait(500);
4206
+ const snapshot = configSnapshot(ctx.cwd, dir);
4207
+ const options = { signal, timeout: 12e4 };
4208
+ if (!providers.length || !isCurrent()) return;
4209
+ let selected;
4210
+ if (intent === "switch-app" && initial.config) {
4211
+ const bound = providers.find((item) => item.id === initial.config?.provider);
4212
+ if (providers.length === 1 && bound) selected = bound;
2961
4213
  }
2962
- if (!closed) {
2963
- await stopOwnedTree(child, "SIGKILL");
2964
- await wait(500);
4214
+ if (!selected) {
4215
+ const choice = await ctx.ui.select("IM forwarding setup \u2014 platform", [...providers.map((item) => item.label), "Cancel"], options);
4216
+ if (!isCurrent() || !choice || choice === "Cancel") return;
4217
+ selected = providers.find((item) => item.label === choice);
2965
4218
  }
2966
- child.stdin?.destroy();
2967
- child.stdout?.destroy();
2968
- child.stderr?.destroy();
4219
+ if (!selected || !isCurrent()) return;
4220
+ ctx.ui.notify(`IM forwarding setup \u2014 ${selected.label}`, "info");
4221
+ 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);
4222
+ if (!isCurrent() || !settings) return;
4223
+ const resolved = selected.resolve(settings);
4224
+ if (!resolved) {
4225
+ ctx.ui.notify("IM forwarding setup: invalid provider settings; nothing was saved.", "error");
4226
+ return;
4227
+ }
4228
+ const profile = typeof settings.larkCliProfile === "string" ? String(settings.larkCliProfile) : void 0;
4229
+ const profileLine = profile ? `
4230
+ lark-cli profile: ${String(profile)}` : "";
4231
+ const appLine = resolved.appId ? `
4232
+ App: ${resolved.appId}` : "";
4233
+ const confirmed = await ctx.ui.confirm("IM forwarding setup", `Platform: ${selected.label}
4234
+ Target: ${resolved.targetId}${appLine}${profileLine}
4235
+ Allowed senders: ${resolved.allowUsers?.join(", ") || "anyone in target"}
4236
+ Save location: ${saveLocation(ctx.cwd, dir)}
4237
+ Enable forwarding and start the connection? No test message will be sent. Saving does not prove connection readiness.`, options);
4238
+ if (!isCurrent() || !confirmed) return;
4239
+ writeConfig(ctx.cwd, dir, { enabled: true, provider: selected.id, settings }, snapshot);
4240
+ if (selected.id === "feishu") {
4241
+ const binary = typeof settings.larkCli === "string" ? String(settings.larkCli) : void 0;
4242
+ void probeCardActionSubscription(ctx, ctx.cwd, binary, profile).catch(() => void 0);
4243
+ }
4244
+ return resolveConfig(ctx.cwd, dir).config ?? void 0;
2969
4245
  }
2970
-
2971
- // builtin/extensions/im-forward/lark-cli.ts
2972
- async function runLarkCli(binary, args, timeoutMs = 3e4, cwd, options = {}) {
2973
- return new Promise((resolve5) => {
2974
- if (options.signal?.aborted) {
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 = "";
4246
+ async function probeCardActionSubscription(ctx, cwd, binaryOverride, profile) {
4247
+ const { spawn: spawn6 } = await import("node:child_process");
4248
+ const binary = binaryOverride ?? await settingsProbeBinary();
4249
+ if (!binary) return;
4250
+ await new Promise((resolve6) => {
2995
4251
  let settled = false;
2996
- let closed = false;
2997
- let termination;
2998
- let treeStopped = false;
2999
- let killTimer;
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();
4252
+ const done = () => {
4253
+ if (!settled) {
4254
+ settled = true;
4255
+ resolve6();
3016
4256
  }
3017
4257
  };
3018
- const kill = () => {
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;
4258
+ const timer = setTimeout(() => {
3055
4259
  try {
3056
- options.onLine?.(line);
4260
+ child.kill("SIGKILL");
3057
4261
  } 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
4262
  }
4263
+ done();
4264
+ }, 3500);
4265
+ timer.unref?.();
4266
+ const child = spawn6(binary, ["event", "consume", "card.action.trigger", "--as", "bot", ...profile ? ["--profile", profile] : []], { cwd, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
4267
+ child.on("error", () => done());
4268
+ child.on("close", () => done());
4269
+ let out = "";
4270
+ child.stdout.on("data", (chunk) => {
4271
+ out += chunk.toString("utf8").slice(0, 8e3);
3074
4272
  });
3075
- child.stderr?.on("data", (chunk) => {
3076
- if (settled || termination) return;
3077
- errorLines?.write(chunk);
3078
- stderr = (stderr + errDecoder.write(chunk)).slice(-4096);
3079
- });
3080
- child.on("error", () => terminate("spawn error"));
3081
- child.on("close", (code) => {
3082
- closed = true;
3083
- if (settled) return;
3084
- if (termination) {
3085
- if (treeStopped) finish(terminatedResult());
3086
- return;
4273
+ child.on("close", () => {
4274
+ const unsubscribed = /requires callbacks not subscribed/i.test(out);
4275
+ if (unsubscribed) {
4276
+ const launcher = /https:\/\/open\.feishu\.cn\/page\/launcher\?[^\s"]+/.exec(out)?.[0];
4277
+ ctx.ui.notify(`Panel buttons require a one-time subscription to card.action.trigger. Without it, the panel still works through text commands.${launcher ? `
4278
+ 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
4279
  }
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
4280
  });
3096
4281
  });
3097
4282
  }
4283
+ async function settingsProbeBinary() {
4284
+ try {
4285
+ const { spawnSync } = await import("node:child_process");
4286
+ const which = spawnSync(process.platform === "win32" ? "where" : "which", ["lark-cli"], { encoding: "utf8", timeout: 3e3, windowsHide: true });
4287
+ const path13 = which.stdout?.split(/\r?\n/)[0]?.trim();
4288
+ return path13 || void 0;
4289
+ } catch {
4290
+ return void 0;
4291
+ }
4292
+ }
4293
+
4294
+ // builtin/extensions/im-forward/providers/feishu/index.ts
4295
+ import { spawn as spawn5 } from "node:child_process";
4296
+ import * as fs10 from "node:fs";
4297
+ import * as os4 from "node:os";
4298
+ import * as path12 from "node:path";
3098
4299
 
3099
4300
  // builtin/extensions/im-forward/providers/feishu/card.ts
3100
4301
  var COLOR_TEMPLATE = {
@@ -3199,17 +4400,17 @@ function extractImageKey(content) {
3199
4400
  }
3200
4401
 
3201
4402
  // builtin/extensions/im-forward/providers/feishu/setup.ts
3202
- import * as fs8 from "node:fs";
3203
- import * as path10 from "node:path";
4403
+ import * as fs9 from "node:fs";
4404
+ import * as path11 from "node:path";
3204
4405
 
3205
4406
  // builtin/extensions/im-forward/browser.ts
3206
- import { spawn as spawn3 } from "node:child_process";
3207
- import path8 from "node:path";
4407
+ import { spawn as spawn4 } from "node:child_process";
4408
+ import path9 from "node:path";
3208
4409
  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
4410
  function browserLaunch(platform = process.platform, root = process.env.SystemRoot || "C:\\Windows") {
3210
4411
  if (platform === "win32") {
3211
4412
  if (!/^[A-Za-z]:\\/.test(root) || /[\x00-\x1f]/.test(root)) return;
3212
- return { command: path8.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(browserScript, "utf16le").toString("base64")], stdin: true };
4413
+ 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
4414
  }
3214
4415
  if (platform === "darwin") return { command: "/usr/bin/open", args: ["--"], stdin: false };
3215
4416
  if (platform === "linux") return { command: "/usr/bin/xdg-open", args: [], stdin: false };
@@ -3218,7 +4419,7 @@ async function openBrowser(url, signal, seam = {}) {
3218
4419
  if (signal.aborted || !/^https:\/\/[^\s\x00-\x1f\x7f]+$/.test(url)) return "failed";
3219
4420
  const spec = browserLaunch(seam.platform);
3220
4421
  if (!spec) return "failed";
3221
- return new Promise((resolve5) => {
4422
+ return new Promise((resolve6) => {
3222
4423
  let child;
3223
4424
  let settled = false;
3224
4425
  let stopping = false;
@@ -3233,7 +4434,7 @@ async function openBrowser(url, signal, seam = {}) {
3233
4434
  child?.stdin?.destroy();
3234
4435
  child?.stdout?.destroy();
3235
4436
  child?.stderr?.destroy();
3236
- resolve5(result);
4437
+ resolve6(result);
3237
4438
  };
3238
4439
  const stop = () => {
3239
4440
  if (settled || stopping) return;
@@ -3251,7 +4452,7 @@ async function openBrowser(url, signal, seam = {}) {
3251
4452
  const abort = () => stop();
3252
4453
  const timer = setTimeout(stop, seam.timeoutMs ?? 1e4);
3253
4454
  try {
3254
- child = (seam.spawn ?? spawn3)(spec.command, spec.stdin ? spec.args : [...spec.args, url], { shell: false, windowsHide: true, detached: process.platform !== "win32", stdio: [spec.stdin ? "pipe" : "ignore", "ignore", "ignore"] });
4455
+ 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
4456
  child.on("error", stop);
3256
4457
  child.on("close", (code) => {
3257
4458
  closed = true;
@@ -3268,24 +4469,24 @@ async function openBrowser(url, signal, seam = {}) {
3268
4469
  }
3269
4470
 
3270
4471
  // builtin/extensions/im-forward/existing-app-terminal.ts
3271
- import path9 from "node:path";
4472
+ import path10 from "node:path";
3272
4473
  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
4474
  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
4475
  function existingAppTerminal(binary, cwd, platform = process.platform, root = process.env.SystemRoot || "C:\\Windows") {
3275
4476
  if (platform !== "win32" || !/^[A-Za-z]:\\/.test(root) || /[\x00-\x1f]/.test(root)) return null;
3276
4477
  const payload = Buffer.from(JSON.stringify({ command: binary.command, args: [...binary.prefix, "config", "init", "--brand", "feishu"], cwd }), "utf8").toString("base64");
3277
4478
  const script = existingAppOuterTemplate.replace("__PAYLOAD__", payload);
3278
- return { command: path9.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), prefix: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")] };
4479
+ return { command: path10.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), prefix: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")] };
3279
4480
  }
3280
4481
 
3281
4482
  // builtin/extensions/im-forward/providers/feishu/setup.ts
3282
4483
  function findNpmCli() {
3283
- const dirs = [path10.dirname(process.execPath), ...(process.env.PATH ?? "").split(path10.delimiter)];
3284
- for (const dir of dirs) for (const root of [path10.join(dir, "node_modules", "npm"), path10.resolve(dir, "..", "lib", "node_modules", "npm")]) {
4484
+ const dirs = [path11.dirname(process.execPath), ...(process.env.PATH ?? "").split(path11.delimiter)];
4485
+ for (const dir of dirs) for (const root of [path11.join(dir, "node_modules", "npm"), path11.resolve(dir, "..", "lib", "node_modules", "npm")]) {
3285
4486
  try {
3286
- const pkg = JSON.parse(fs8.readFileSync(path10.join(root, "package.json"), "utf8"));
3287
- const entry = path10.join(root, "bin", "npm-cli.js");
3288
- if (pkg.name === "npm" && pkg.bin?.npm === "bin/npm-cli.js" && fs8.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
4487
+ const pkg = JSON.parse(fs9.readFileSync(path11.join(root, "package.json"), "utf8"));
4488
+ const entry = path11.join(root, "bin", "npm-cli.js");
4489
+ if (pkg.name === "npm" && pkg.bin?.npm === "bin/npm-cli.js" && fs9.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
3289
4490
  } catch {
3290
4491
  }
3291
4492
  }
@@ -3961,19 +5162,19 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
3961
5162
  return Array.isArray(data?.messages) ? data.messages.flatMap((message) => isRecord(message) && typeof message.message_id === "string" ? [message.message_id] : []) : null;
3962
5163
  },
3963
5164
  async downloadImage(messageId, image, index) {
3964
- const directory = fs9.mkdtempSync(path11.join(os4.tmpdir(), "pie-im-forward-"));
3965
- const cleanup = () => fs9.rmSync(directory, { recursive: true, force: true });
5165
+ const directory = fs10.mkdtempSync(path12.join(os4.tmpdir(), "pie-im-forward-"));
5166
+ const cleanup = () => fs10.rmSync(directory, { recursive: true, force: true });
3966
5167
  try {
3967
5168
  const name = `image-${index + 1}.png`;
3968
5169
  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
5170
  if (result.error || !parseLarkCliEnvelope(result.stdout).ok) throw new Error("Image download failed");
3970
- let target = path11.join(directory, name);
3971
- if (fs9.statSync(target).size > 10 * 1024 * 1024) throw new Error("Image exceeds 10 MiB");
5171
+ let target = path12.join(directory, name);
5172
+ if (fs10.statSync(target).size > 10 * 1024 * 1024) throw new Error("Image exceeds 10 MiB");
3972
5173
  const detected = readImageFormat(target);
3973
5174
  if (detected.ext === ".bin") throw new Error("Unsupported image format");
3974
5175
  if (detected.ext !== ".png") {
3975
- const corrected = path11.join(directory, `image-${index + 1}${detected.ext}`);
3976
- fs9.renameSync(target, corrected);
5176
+ const corrected = path12.join(directory, `image-${index + 1}${detected.ext}`);
5177
+ fs10.renameSync(target, corrected);
3977
5178
  target = corrected;
3978
5179
  }
3979
5180
  return { file: { path: target, displayName: `feishu-image-${index + 1}${detected.ext}` }, cleanup };
@@ -4012,7 +5213,7 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
4012
5213
  optionalRespawnTimers.set(eventKey, timer);
4013
5214
  };
4014
5215
  const spawnConsume = (eventKey, map, required) => {
4015
- const child2 = spawn4(binary.command, [...binary.prefix, "event", "consume", eventKey, "--as", "bot", ...profile ? ["--profile", profile] : []], { stdio: ["pipe", "pipe", "pipe"], shell: false, windowsHide: true, detached: process.platform !== "win32" });
5216
+ 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
5217
  child2.stdin?.on("error", () => void 0);
4017
5218
  const output = lineReader((line) => {
4018
5219
  if (!closed) {
@@ -4153,18 +5354,18 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
4153
5354
  const appId = await canonicalAppIdNow();
4154
5355
  if (!appId) return void 0;
4155
5356
  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 = path11.join(larkHome, ".lark-cli", "events", appId, "bus.log");
5357
+ const logPath = path12.join(larkHome, ".lark-cli", "events", appId, "bus.log");
4157
5358
  let tail;
4158
5359
  try {
4159
- const fd = fs9.openSync(logPath, "r");
5360
+ const fd = fs10.openSync(logPath, "r");
4160
5361
  try {
4161
- const size = fs9.fstatSync(fd).size;
5362
+ const size = fs10.fstatSync(fd).size;
4162
5363
  const start = Math.max(0, size - 64 * 1024);
4163
5364
  const buf = Buffer.alloc(size - start);
4164
- fs9.readSync(fd, buf, 0, buf.length, start);
5365
+ fs10.readSync(fd, buf, 0, buf.length, start);
4165
5366
  tail = buf.toString("utf8");
4166
5367
  } finally {
4167
- fs9.closeSync(fd);
5368
+ fs10.closeSync(fd);
4168
5369
  }
4169
5370
  } catch {
4170
5371
  return void 0;
@@ -4215,6 +5416,78 @@ function imForward(ctx) {
4215
5416
  function initializeImForward(ctx, providers = implementedProviders) {
4216
5417
  const caps = ctx.capabilities ?? { editorInjection: ctx.hasUI === true, interactiveUI: ctx.hasUI === true };
4217
5418
  if (!caps.editorInjection) return;
5419
+ if (process.env.PIE_PROC_CURATED_NAME === "manager" && typeof ctx.registerTool === "function") {
5420
+ ctx.registerTool({
5421
+ name: "panel_action",
5422
+ label: "Panel custom actions",
5423
+ 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).",
5424
+ parameters: Type.Object({
5425
+ action: Type.Union([Type.Literal("add"), Type.Literal("remove"), Type.Literal("list")], { description: "add | remove | list" }),
5426
+ label: Type.Optional(Type.String({ description: "add: button label (emoji welcome, \u226440 chars)" })),
5427
+ script: Type.Optional(Type.String({ description: "add: script path (must EXIST and be tested \u2014 develop it via a worker first)" })),
5428
+ scope: Type.Optional(Type.String({ description: "add: manager (default) | worker | worker:<name>" })),
5429
+ cwd: Type.Optional(Type.String({ description: "add: script working directory (default: the script's own dir)" })),
5430
+ payload: Type.Optional(Type.Unknown({ description: "add: static JSON payload baked into the button (one script, several buttons)" })),
5431
+ timeoutMs: Type.Optional(Type.Number({ description: "add: per-run timeout (5s..60min, default 5min)", minimum: 5e3, maximum: 36e5 })),
5432
+ id: Type.Optional(Type.String({ description: "add: explicit id ([a-z0-9-], max 32); default: slug from label. remove: the id to delete" })),
5433
+ creatorName: Type.Optional(Type.String({ description: "add: display name of the group member who asked (attribution)" })),
5434
+ creatorOpenId: Type.Optional(Type.String({ description: "add: open_id of the requester when known (attribution)" }))
5435
+ }),
5436
+ risk: { riskClass: "config_write", requiresPermission: false, externalSideEffect: false, readsNetwork: false, writesNetwork: false, concurrencySafe: false },
5437
+ renderHint: { summary: (args) => `panel_action ${String(args.action)}${args.label ? ` ${String(args.label)}` : ""}${args.id ? ` ${String(args.id)}` : ""}` },
5438
+ execute: async (args) => {
5439
+ const text = (body, isError = false) => ({ content: [{ type: "text", text: body }], details: {}, ...isError ? { isError: true } : {} });
5440
+ const act = args.action;
5441
+ if (act === "list") {
5442
+ const { actions, error } = readRegistry();
5443
+ if (error) return text(error, true);
5444
+ if (actions.length === 0) return text(`No custom panel actions registered (registry: ${panelActionsRoot()}/registry.json).`);
5445
+ const rows = actions.map((a) => ({
5446
+ id: a.id,
5447
+ label: a.label,
5448
+ scope: a.scope,
5449
+ script: a.script,
5450
+ ...a.cwd ? { cwd: a.cwd } : {},
5451
+ runs: a.runs,
5452
+ ...a.lastRunBy ? { lastRunBy: a.lastRunBy } : {},
5453
+ ...a.creator?.name ? { creator: a.creator.name } : {}
5454
+ }));
5455
+ return text(JSON.stringify(rows, null, 2));
5456
+ }
5457
+ if (act === "add") {
5458
+ const label = typeof args.label === "string" ? args.label : "";
5459
+ const script = typeof args.script === "string" ? args.script : "";
5460
+ 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);
5461
+ const scope = typeof args.scope === "string" && args.scope.trim() ? args.scope.trim() : "manager";
5462
+ if (!isValidScope(scope)) return text(`invalid scope "${scope}" (manager | worker | worker:<name>)`, true);
5463
+ try {
5464
+ const created = addAction({
5465
+ label,
5466
+ script,
5467
+ scope,
5468
+ ...typeof args.cwd === "string" && args.cwd.trim() ? { cwd: args.cwd } : {},
5469
+ ...args.payload !== void 0 ? { payload: args.payload } : {},
5470
+ ...typeof args.timeoutMs === "number" ? { timeoutMs: args.timeoutMs } : {},
5471
+ ...typeof args.id === "string" && args.id.trim() ? { id: args.id.trim() } : {},
5472
+ ...args.creatorName || args.creatorOpenId ? { creator: { ...typeof args.creatorOpenId === "string" ? { openId: args.creatorOpenId } : {}, ...typeof args.creatorName === "string" ? { name: args.creatorName } : {} } } : {}
5473
+ });
5474
+ return text(`\u2705 \u6309\u94AE\u5DF2\u6CE8\u518C:\u3010${created.label}\u3011id=\`${created.id}\` scope=${created.scope}
5475
+
5476
+ \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`);
5477
+ } catch (error) {
5478
+ return text(`add failed: ${error instanceof Error ? error.message : String(error)}`, true);
5479
+ }
5480
+ }
5481
+ if (act === "remove") {
5482
+ const id = typeof args.id === "string" ? args.id.trim() : "";
5483
+ if (!id) return text("remove requires id", true);
5484
+ const removed = removeAction(id);
5485
+ 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);
5486
+ }
5487
+ return text(`unknown action "${act}"`, true);
5488
+ }
5489
+ });
5490
+ }
4218
5491
  const interactive = caps.interactiveUI;
4219
5492
  const dir = resolveConfigDir();
4220
5493
  let disposed = false;
@@ -4290,7 +5563,7 @@ function initializeImForward(ctx, providers = implementedProviders) {
4290
5563
  return () => {
4291
5564
  };
4292
5565
  };
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) => {
5566
+ 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
5567
  const latest = readLiveConfig(ctx.cwd, dir);
4295
5568
  if (latest.problems.length || !latest.config || configurationIdentity(latest.config) !== configurationIdentity(config)) throw new Error("Configuration changed; setup required");
4296
5569
  writeConfig(ctx.cwd, dir, { enabled: next });