@cydm/pie 4.15.3 → 4.16.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.
@@ -3,7 +3,7 @@ import {
3
3
  isWindowsServiceManager,
4
4
  launchWindowsServiceUpgradeActor,
5
5
  resolveAbsoluteActorEnv
6
- } from "../../../chunks/chunk-Y6AVNVOD.js";
6
+ } from "../../../chunks/chunk-7UFRZTQI.js";
7
7
  import {
8
8
  DISPATCH_PREFIX,
9
9
  IPC_PROTOCOL_VERSION,
@@ -12,7 +12,7 @@ import {
12
12
  registerDispatchReceiver,
13
13
  registerImBinding,
14
14
  registerTurnImDriver
15
- } from "../../../chunks/chunk-TYCKSYUF.js";
15
+ } from "../../../chunks/chunk-XUXKF5ZK.js";
16
16
  import {
17
17
  currentWorkerLifecycleBridge,
18
18
  syncInheritedWorkerModels
@@ -29,10 +29,10 @@ import {
29
29
  readDistillWorkerLog,
30
30
  spawnDistillAutoWorker,
31
31
  spawnWikiGcWorker
32
- } from "../../../chunks/chunk-NCO26FXT.js";
32
+ } from "../../../chunks/chunk-MC5ZYWSP.js";
33
33
  import {
34
34
  readCuratedMemoryGitLog
35
- } from "../../../chunks/chunk-VWDCKHCC.js";
35
+ } from "../../../chunks/chunk-ZSFE6N5J.js";
36
36
  import {
37
37
  liveSessionHolder
38
38
  } from "../../../chunks/chunk-Q5PSWX3B.js";
@@ -1332,7 +1332,18 @@ function extractImageKey(content) {
1332
1332
  var SAFE_FEISHU_CHAT_ID = /^oc_[A-Za-z0-9_-]+$/;
1333
1333
  var SAFE_FEISHU_THREAD_ID = /^omt_[A-Za-z0-9_-]+$/;
1334
1334
  var SAFE_APPLINK_HOST = /^[a-z0-9.-]+$/i;
1335
- var FEISHU_THREAD_LATEST_POSITION = "9999999";
1335
+ function parseFeishuThreadPosition(value) {
1336
+ if (typeof value === "number") {
1337
+ return Number.isSafeInteger(value) && value >= 0 ? value : void 0;
1338
+ }
1339
+ if (typeof value === "string") {
1340
+ const trimmed = value.trim();
1341
+ if (!/^\d+$/.test(trimmed)) return void 0;
1342
+ const parsed = Number(trimmed);
1343
+ return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : void 0;
1344
+ }
1345
+ return void 0;
1346
+ }
1336
1347
  function formatFeishuThreadUrl(anchor) {
1337
1348
  const rawChat = typeof anchor.chatId === "string" && anchor.chatId ? anchor.chatId : typeof anchor.home === "string" && anchor.home ? anchor.home : "";
1338
1349
  const rawThread = typeof anchor.threadId === "string" ? anchor.threadId : "";
@@ -1341,7 +1352,264 @@ function formatFeishuThreadUrl(anchor) {
1341
1352
  const host = SAFE_APPLINK_HOST.test(rawHost) ? rawHost : "applink.feishu.cn";
1342
1353
  const encodedChat = encodeURIComponent(rawChat);
1343
1354
  const encodedThread = encodeURIComponent(rawThread);
1344
- return `https://${host}/client/thread/open?open_chat_id=${encodedChat}&open_thread_id=${encodedThread}&openchatid=${encodedChat}&openthreadid=${encodedThread}&thread_position=${FEISHU_THREAD_LATEST_POSITION}`;
1355
+ const base = `https://${host}/client/thread/open?open_chat_id=${encodedChat}&open_thread_id=${encodedThread}&openchatid=${encodedChat}&openthreadid=${encodedThread}`;
1356
+ const pos = parseFeishuThreadPosition(anchor.threadPosition);
1357
+ return pos !== void 0 ? `${base}&thread_position=${pos}` : base;
1358
+ }
1359
+ function extractHttpLinkDestination(rawDest) {
1360
+ const trimmed = rawDest.trim();
1361
+ if (!trimmed) return void 0;
1362
+ let candidate;
1363
+ let rest;
1364
+ if (trimmed.startsWith("<")) {
1365
+ const closeAngle = trimmed.indexOf(">");
1366
+ if (closeAngle <= 1) return void 0;
1367
+ candidate = trimmed.slice(1, closeAngle);
1368
+ rest = trimmed.slice(closeAngle + 1).trim();
1369
+ } else {
1370
+ const ws = /\s/.exec(trimmed);
1371
+ if (ws) {
1372
+ candidate = trimmed.slice(0, ws.index);
1373
+ rest = trimmed.slice(ws.index).trim();
1374
+ } else {
1375
+ candidate = trimmed;
1376
+ rest = "";
1377
+ }
1378
+ }
1379
+ if (rest && !(/^"(?:\\.|[^"\\])*"$/.test(rest) || /^'(?:\\.|[^'\\])*'$/.test(rest) || /^\((?:\\.|[^)\\])*\)$/.test(rest))) {
1380
+ return void 0;
1381
+ }
1382
+ const unescaped = candidate.replace(/\\([()\\])/g, "$1");
1383
+ if (!/^https?:\/\/[^\s<>]+$/i.test(unescaped)) return void 0;
1384
+ return unescaped;
1385
+ }
1386
+ var MAX_LINK_DEST_SCAN = 2048;
1387
+ function indexParagraphDelimiters(text) {
1388
+ const codeSpanEnds = /* @__PURE__ */ new Map();
1389
+ const bracketEnds = /* @__PURE__ */ new Map();
1390
+ const runsByLen = /* @__PURE__ */ new Map();
1391
+ for (let i = 0; i < text.length; ) {
1392
+ const ch = text[i];
1393
+ if (ch === "\\" && i + 1 < text.length) {
1394
+ i += 2;
1395
+ continue;
1396
+ }
1397
+ if (ch === "`") {
1398
+ let run = 1;
1399
+ while (i + run < text.length && text[i + run] === "`") run++;
1400
+ let list = runsByLen.get(run);
1401
+ if (!list) {
1402
+ list = [];
1403
+ runsByLen.set(run, list);
1404
+ }
1405
+ list.push(i);
1406
+ i += run;
1407
+ continue;
1408
+ }
1409
+ i++;
1410
+ }
1411
+ const runCursor = /* @__PURE__ */ new Map();
1412
+ const bracketStack = [];
1413
+ for (let i = 0; i < text.length; ) {
1414
+ const ch = text[i];
1415
+ if (ch === "\\" && i + 1 < text.length) {
1416
+ i += 2;
1417
+ continue;
1418
+ }
1419
+ if (ch === "`") {
1420
+ let run = 1;
1421
+ while (i + run < text.length && text[i + run] === "`") run++;
1422
+ const list = runsByLen.get(run);
1423
+ let cursor = runCursor.get(run) ?? 0;
1424
+ while (list && cursor < list.length && list[cursor] <= i) cursor++;
1425
+ if (list && cursor < list.length) {
1426
+ const closePos = list[cursor];
1427
+ runCursor.set(run, cursor + 1);
1428
+ codeSpanEnds.set(i, closePos + run);
1429
+ i = closePos + run;
1430
+ continue;
1431
+ }
1432
+ runCursor.set(run, list?.length ?? 0);
1433
+ i += run;
1434
+ continue;
1435
+ }
1436
+ if (ch === "[") {
1437
+ bracketStack.push(i);
1438
+ } else if (ch === "]" && bracketStack.length > 0) {
1439
+ const openIdx = bracketStack.pop();
1440
+ bracketEnds.set(openIdx, i);
1441
+ }
1442
+ i++;
1443
+ }
1444
+ return { codeSpanEnds, bracketEnds };
1445
+ }
1446
+ function findLinkDestEnd(text, start, lastCloseParen) {
1447
+ if (start > lastCloseParen) return -1;
1448
+ const limit = Math.min(lastCloseParen + 1, start + MAX_LINK_DEST_SCAN);
1449
+ let depth = 0;
1450
+ let inQuote = null;
1451
+ let inAngle = false;
1452
+ let i = start;
1453
+ while (i < limit) {
1454
+ const ch = text[i];
1455
+ if (ch === "\n" || ch === "\r") return -1;
1456
+ if (ch === "\\" && i + 1 < limit) {
1457
+ i += 2;
1458
+ continue;
1459
+ }
1460
+ if (inQuote) {
1461
+ if (ch === inQuote) inQuote = null;
1462
+ i++;
1463
+ continue;
1464
+ }
1465
+ if (inAngle) {
1466
+ if (ch === ">") inAngle = false;
1467
+ i++;
1468
+ continue;
1469
+ }
1470
+ if (ch === "<" && depth === 0 && text.slice(start, i).trim() === "") {
1471
+ inAngle = true;
1472
+ i++;
1473
+ continue;
1474
+ }
1475
+ if ((ch === '"' || ch === "'") && depth === 0 && i > start && /\s/.test(text[i - 1])) {
1476
+ inQuote = ch;
1477
+ i++;
1478
+ continue;
1479
+ }
1480
+ if (ch === "(") {
1481
+ depth++;
1482
+ } else if (ch === ")") {
1483
+ if (depth === 0) return i;
1484
+ depth--;
1485
+ }
1486
+ i++;
1487
+ }
1488
+ return -1;
1489
+ }
1490
+ function rewriteParagraphPostLinks(para) {
1491
+ if (!para.includes("](") && !/<https?:\/\//i.test(para)) return para;
1492
+ const { codeSpanEnds, bracketEnds } = indexParagraphDelimiters(para);
1493
+ const lastCloseParen = para.lastIndexOf(")");
1494
+ let out = "";
1495
+ let i = 0;
1496
+ while (i < para.length) {
1497
+ const ch = para[i];
1498
+ if (ch === "\\" && i + 1 < para.length) {
1499
+ out += para.slice(i, i + 2);
1500
+ i += 2;
1501
+ continue;
1502
+ }
1503
+ if (ch === "`") {
1504
+ const spanEnd = codeSpanEnds.get(i);
1505
+ if (spanEnd !== void 0) {
1506
+ out += para.slice(i, spanEnd);
1507
+ i = spanEnd;
1508
+ } else {
1509
+ let run = 1;
1510
+ while (i + run < para.length && para[i + run] === "`") run++;
1511
+ out += para.slice(i, i + run);
1512
+ i += run;
1513
+ }
1514
+ continue;
1515
+ }
1516
+ if (ch === "!" && para[i + 1] === "[") {
1517
+ const altEnd = bracketEnds.get(i + 1);
1518
+ if (altEnd !== void 0 && para[altEnd + 1] === "(") {
1519
+ const destEnd = findLinkDestEnd(para, altEnd + 2, lastCloseParen);
1520
+ if (destEnd >= 0) {
1521
+ out += para.slice(i, destEnd + 1);
1522
+ i = destEnd + 1;
1523
+ continue;
1524
+ }
1525
+ }
1526
+ out += "![";
1527
+ i += 2;
1528
+ continue;
1529
+ }
1530
+ if (ch === "<") {
1531
+ const auto = /^<(https?:\/\/[^\s<>]+)>/i.exec(para.slice(i));
1532
+ if (auto) {
1533
+ out += auto[1];
1534
+ i += auto[0].length;
1535
+ continue;
1536
+ }
1537
+ }
1538
+ if (ch === "[") {
1539
+ const labelEnd = bracketEnds.get(i);
1540
+ if (labelEnd !== void 0 && para[labelEnd + 1] === "(") {
1541
+ const destEnd = findLinkDestEnd(para, labelEnd + 2, lastCloseParen);
1542
+ if (destEnd >= 0) {
1543
+ const rawDest = para.slice(labelEnd + 2, destEnd);
1544
+ const url = extractHttpLinkDestination(rawDest);
1545
+ if (url) {
1546
+ const rawLabel = para.slice(i + 1, labelEnd).trim();
1547
+ const plainLabel = rawLabel.replace(/^[`*_\s]+|[`*_\s]+$/g, "");
1548
+ if (!plainLabel || plainLabel === url) {
1549
+ out += url;
1550
+ } else {
1551
+ out += `${rawLabel} ( ${url} )`;
1552
+ }
1553
+ i = destEnd + 1;
1554
+ continue;
1555
+ }
1556
+ out += para.slice(i, destEnd + 1);
1557
+ i = destEnd + 1;
1558
+ continue;
1559
+ }
1560
+ }
1561
+ }
1562
+ out += ch;
1563
+ i++;
1564
+ }
1565
+ return out;
1566
+ }
1567
+ function leadingIndentColumns(line) {
1568
+ let cols = 0;
1569
+ for (const ch of line) {
1570
+ if (ch === " ") cols += 1;
1571
+ else if (ch === " ") cols = 4 * Math.ceil((cols + 1) / 4);
1572
+ else break;
1573
+ }
1574
+ return cols;
1575
+ }
1576
+ function preserveFeishuPostMarkdownLinks(markdown) {
1577
+ if (!markdown || !markdown.includes("](") && !/<https?:\/\//i.test(markdown)) {
1578
+ return markdown;
1579
+ }
1580
+ const rawLines = markdown.split("\n");
1581
+ const scan = scanFenceLines(markdown.includes("\r") ? markdown.replace(/\r\n/g, "\n") : markdown);
1582
+ const outLines = [];
1583
+ let changed = false;
1584
+ let i = 0;
1585
+ while (i < rawLines.length) {
1586
+ const inFence = scan.stateAtLineStart[i] !== null || scan.openedBy[i] !== null || scan.closedBy[i] !== null;
1587
+ const trimmed = rawLines[i].trim();
1588
+ if (inFence || trimmed === "") {
1589
+ outLines.push(rawLines[i]);
1590
+ i++;
1591
+ continue;
1592
+ }
1593
+ const start = i;
1594
+ while (i < rawLines.length) {
1595
+ const f = scan.stateAtLineStart[i] !== null || scan.openedBy[i] !== null || scan.closedBy[i] !== null;
1596
+ if (f || rawLines[i].trim() === "") break;
1597
+ i++;
1598
+ }
1599
+ const blockLines = rawLines.slice(start, i);
1600
+ const precededByBlankOrStart = start === 0 || rawLines[start - 1].trim() === "";
1601
+ const startsWithListMarker = /^\s*(?:[-*+]|\d{1,9}[.)])(?:\s|$)/.test(blockLines[0]);
1602
+ const isIndentedCodeBlock = precededByBlankOrStart && !startsWithListMarker && blockLines.every((l) => leadingIndentColumns(l) >= 4);
1603
+ if (isIndentedCodeBlock) {
1604
+ outLines.push(...blockLines);
1605
+ continue;
1606
+ }
1607
+ const joined = blockLines.join("\n");
1608
+ const rewritten = rewriteParagraphPostLinks(joined);
1609
+ if (rewritten !== joined) changed = true;
1610
+ outLines.push(...rewritten.split("\n"));
1611
+ }
1612
+ return changed ? outLines.join("\n") : markdown;
1345
1613
  }
1346
1614
 
1347
1615
  // builtin/extensions/im-forward/providers/feishu/setup.ts
@@ -2136,8 +2404,10 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
2136
2404
  const recipient = targetKind === "user" ? ["--user-id", target] : ["--chat-id", target];
2137
2405
  const boundedKey = boundIdempotencyKey(key);
2138
2406
  const threadFlag = options?.replyInThread ? ["--reply-in-thread"] : [];
2139
- const data = await call(replyTo ? ["im", "+messages-reply", "--as", "bot", "--message-id", replyTo, "--markdown", text, ...threadFlag, "--idempotency-key", boundedKey] : ["im", "+messages-send", "--as", "bot", ...recipient, "--markdown", text, "--idempotency-key", boundedKey]);
2140
- return typeof data?.message_id === "string" ? { messageId: data.message_id, threadId: typeof data.thread_id === "string" ? data.thread_id : null, ...typeof data.chat_id === "string" && data.chat_id ? { chatId: data.chat_id } : {} } : null;
2407
+ const markdown = preserveFeishuPostMarkdownLinks(text);
2408
+ const data = await call(replyTo ? ["im", "+messages-reply", "--as", "bot", "--message-id", replyTo, "--markdown", markdown, ...threadFlag, "--idempotency-key", boundedKey] : ["im", "+messages-send", "--as", "bot", ...recipient, "--markdown", markdown, "--idempotency-key", boundedKey]);
2409
+ const threadPosition = parseFeishuThreadPosition(data?.thread_message_position);
2410
+ return typeof data?.message_id === "string" ? { messageId: data.message_id, threadId: typeof data.thread_id === "string" ? data.thread_id : null, ...typeof data.chat_id === "string" && data.chat_id ? { chatId: data.chat_id } : {}, ...threadPosition !== void 0 ? { threadPosition } : {} } : null;
2141
2411
  },
2142
2412
  async sendFile(target, file, key, replyTo, options) {
2143
2413
  const recipient = targetKind === "user" ? ["--user-id", target] : ["--chat-id", target];
@@ -2155,7 +2425,8 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
2155
2425
  replyTo ? ["im", "+messages-reply", "--as", "bot", "--message-id", replyTo, ...threadFlag, "--file", fileArg, "--idempotency-key", boundedKey] : ["im", "+messages-send", "--as", "bot", ...recipient, "--file", fileArg, "--idempotency-key", boundedKey],
2156
2426
  fileCwd
2157
2427
  );
2158
- return typeof data?.message_id === "string" ? { messageId: data.message_id, threadId: typeof data.thread_id === "string" ? data.thread_id : null, ...typeof data.chat_id === "string" && data.chat_id ? { chatId: data.chat_id } : {} } : null;
2428
+ const threadPosition = parseFeishuThreadPosition(data?.thread_message_position);
2429
+ return typeof data?.message_id === "string" ? { messageId: data.message_id, threadId: typeof data.thread_id === "string" ? data.thread_id : null, ...typeof data.chat_id === "string" && data.chat_id ? { chatId: data.chat_id } : {}, ...threadPosition !== void 0 ? { threadPosition } : {} } : null;
2159
2430
  },
2160
2431
  // 4.3.10 panel cards: compile the neutral CardSpec and send it as an
2161
2432
  // interactive message. The card JSON is provider-private output of
@@ -2166,7 +2437,8 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
2166
2437
  const content = JSON.stringify(compileCard(spec));
2167
2438
  const threadFlag = options?.replyInThread ? ["--reply-in-thread"] : [];
2168
2439
  const data = await call(replyTo ? ["im", "+messages-reply", "--as", "bot", "--message-id", replyTo, "--msg-type", "interactive", "--content", content, ...threadFlag, "--idempotency-key", boundedKey] : ["im", "+messages-send", "--as", "bot", ...recipient, "--msg-type", "interactive", "--content", content, "--idempotency-key", boundedKey]);
2169
- return typeof data?.message_id === "string" ? { messageId: data.message_id, threadId: typeof data.thread_id === "string" ? data.thread_id : null, ...typeof data.chat_id === "string" && data.chat_id ? { chatId: data.chat_id } : {} } : null;
2440
+ const threadPosition = parseFeishuThreadPosition(data?.thread_message_position);
2441
+ return typeof data?.message_id === "string" ? { messageId: data.message_id, threadId: typeof data.thread_id === "string" ? data.thread_id : null, ...typeof data.chat_id === "string" && data.chat_id ? { chatId: data.chat_id } : {}, ...threadPosition !== void 0 ? { threadPosition } : {} } : null;
2170
2442
  },
2171
2443
  // 4.3.10: patch an existing card in place (admin panels refresh without
2172
2444
  // re-sending). Feishu bound: the message must be <14 days old. Transient
@@ -2204,7 +2476,8 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
2204
2476
  async openTopic(_target, rootMessageId, key) {
2205
2477
  const boundedKey = boundIdempotencyKey(key);
2206
2478
  const data = await call(["im", "+messages-reply", "--as", "bot", "--message-id", rootMessageId, "--markdown", "\xB7", "--reply-in-thread", "--idempotency-key", boundedKey]);
2207
- return typeof data?.message_id === "string" ? { messageId: data.message_id, threadId: typeof data.thread_id === "string" ? data.thread_id : null, ...typeof data.chat_id === "string" && data.chat_id ? { chatId: data.chat_id } : {} } : null;
2479
+ const threadPosition = parseFeishuThreadPosition(data?.thread_message_position);
2480
+ return typeof data?.message_id === "string" ? { messageId: data.message_id, threadId: typeof data.thread_id === "string" ? data.thread_id : null, ...typeof data.chat_id === "string" && data.chat_id ? { chatId: data.chat_id } : {}, ...threadPosition !== void 0 ? { threadPosition } : {} } : null;
2208
2481
  },
2209
2482
  async acknowledge(id) {
2210
2483
  await call(["im", "reactions", "create", "--as", "bot", "--params", JSON.stringify({ message_id: id }), "--data", JSON.stringify({ reaction_type: { emoji_type: "THUMBSUP" } })]);
@@ -2238,12 +2511,40 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
2238
2511
  async metadata(id) {
2239
2512
  const data = await call(["im", "+messages-mget", "--as", "bot", "--message-ids", id]);
2240
2513
  const message = Array.isArray(data?.messages) ? data.messages[0] : void 0;
2514
+ const threadPosition = isRecord(message) ? parseFeishuThreadPosition(message.thread_message_position) : void 0;
2241
2515
  return isRecord(message) ? {
2242
2516
  threadId: typeof message.thread_id === "string" && message.thread_id || null,
2243
2517
  replyTo: typeof message.reply_to === "string" && message.reply_to || typeof message.root_id === "string" && message.root_id || null,
2244
- ...typeof message.chat_id === "string" && message.chat_id ? { chatId: message.chat_id } : {}
2518
+ ...typeof message.chat_id === "string" && message.chat_id ? { chatId: message.chat_id } : {},
2519
+ ...threadPosition !== void 0 ? { threadPosition } : {}
2245
2520
  } : null;
2246
2521
  },
2522
+ async latestThreadPosition(threadId, anchorMessageId, signal) {
2523
+ if (lifetime.signal.aborted || signal?.aborted) return null;
2524
+ const combined = signal ? AbortSignal.any([lifetime.signal, signal]) : lifetime.signal;
2525
+ const listArgs = ["im", "+threads-messages-list", "--as", "bot", "--thread", threadId, "--order", "desc", "--page-size", "1", "--no-reactions"];
2526
+ const result = await native(binary, profile ? [...listArgs, "--profile", profile] : listArgs, 3e3, void 0, { signal: combined });
2527
+ if (!result.error) {
2528
+ const data = parseLarkCliEnvelope(result.stdout).data;
2529
+ const latest = Array.isArray(data?.messages) ? data.messages[0] : void 0;
2530
+ const pos = isRecord(latest) ? parseFeishuThreadPosition(latest.thread_message_position) : void 0;
2531
+ if (pos !== void 0) return pos;
2532
+ return null;
2533
+ }
2534
+ if (anchorMessageId && !combined.aborted && /230027|user_unauthorized|authorization|permission/i.test(result.error)) {
2535
+ const mgetArgs = ["im", "+messages-mget", "--as", "bot", "--message-ids", anchorMessageId];
2536
+ const mgetRes = await native(binary, profile ? [...mgetArgs, "--profile", profile] : mgetArgs, 2500, void 0, { signal: combined });
2537
+ if (!mgetRes.error) {
2538
+ const meta = parseLarkCliEnvelope(mgetRes.stdout).data;
2539
+ const msg = Array.isArray(meta?.messages) ? meta.messages[0] : void 0;
2540
+ if (isRecord(msg) && (typeof msg.thread_id !== "string" || !msg.thread_id || msg.thread_id === threadId)) {
2541
+ const pos = parseFeishuThreadPosition(msg.thread_message_position);
2542
+ if (pos !== void 0) return pos;
2543
+ }
2544
+ }
2545
+ }
2546
+ return null;
2547
+ },
2247
2548
  async threadMessages(id) {
2248
2549
  const args = ["im", "+threads-messages-list", "--as", "bot", "--thread", id];
2249
2550
  const result = await native(binary, profile ? [...args, "--profile", profile] : args, 3e4, void 0, { signal: lifetime.signal });
@@ -2620,6 +2921,18 @@ function findImplementedProvider(id) {
2620
2921
  }
2621
2922
 
2622
2923
  // builtin/extensions/im-forward/session-anchors.ts
2924
+ function normalizeThreadPosition(value) {
2925
+ if (typeof value === "number") {
2926
+ return Number.isSafeInteger(value) && value >= 0 ? value : void 0;
2927
+ }
2928
+ if (typeof value === "string") {
2929
+ const trimmed = value.trim();
2930
+ if (!/^\d+$/.test(trimmed)) return void 0;
2931
+ const parsed = Number(trimmed);
2932
+ return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : void 0;
2933
+ }
2934
+ return void 0;
2935
+ }
2623
2936
  function anchorsDir() {
2624
2937
  return path8.join(addressBookRoot(), "im-forward", "anchors");
2625
2938
  }
@@ -2627,6 +2940,45 @@ function anchorPath(sessionId) {
2627
2940
  const safe = sessionId.replace(/[^a-zA-Z0-9._-]/g, "_");
2628
2941
  return path8.join(anchorsDir(), `${safe}.json`);
2629
2942
  }
2943
+ function positionHintPath(sessionId) {
2944
+ const safe = sessionId.replace(/[^A-Za-z0-9_.-]/g, "_");
2945
+ return path8.join(anchorsDir(), "positions", `${safe}.json`);
2946
+ }
2947
+ function readPositionHint(sessionId, provider, threadId) {
2948
+ if (!threadId) return void 0;
2949
+ try {
2950
+ const raw = fs6.readFileSync(positionHintPath(sessionId), "utf8");
2951
+ const parsed = JSON.parse(raw);
2952
+ if (parsed.provider !== provider || parsed.threadId !== threadId) return void 0;
2953
+ return normalizeThreadPosition(parsed.threadPosition);
2954
+ } catch {
2955
+ return void 0;
2956
+ }
2957
+ }
2958
+ function resolveMergedThreadPosition(sessionId, provider, anchor) {
2959
+ const inlinePos = normalizeThreadPosition(anchor.threadPosition);
2960
+ const sidecarPos = readPositionHint(sessionId, provider, anchor.threadId);
2961
+ if (inlinePos === void 0) return sidecarPos;
2962
+ if (sidecarPos === void 0) return inlinePos;
2963
+ return Math.max(inlinePos, sidecarPos);
2964
+ }
2965
+ function writeJsonFileAtomically(target, data) {
2966
+ fs6.mkdirSync(path8.dirname(target), { recursive: true });
2967
+ const payload = `${JSON.stringify(data)}
2968
+ `;
2969
+ const tmp = `${target}.${process.pid}.${Math.random().toString(36).slice(2, 8)}.tmp`;
2970
+ try {
2971
+ fs6.writeFileSync(tmp, payload, "utf8");
2972
+ fs6.renameSync(tmp, target);
2973
+ return true;
2974
+ } catch {
2975
+ try {
2976
+ fs6.rmSync(tmp, { force: true });
2977
+ } catch {
2978
+ }
2979
+ return false;
2980
+ }
2981
+ }
2630
2982
  function loadPersistedAnchor(sessionId, identity) {
2631
2983
  try {
2632
2984
  const raw = fs6.readFileSync(anchorPath(sessionId), "utf8");
@@ -2638,11 +2990,13 @@ function loadPersistedAnchor(sessionId, identity) {
2638
2990
  // DM root on restart). The provider check stays: a re-bound app is a
2639
2991
  // different home entirely.
2640
2992
  (parsed.targetId === identity.targetId || typeof parsed.anchor.home === "string")) {
2993
+ const threadPosition = resolveMergedThreadPosition(sessionId, parsed.provider, parsed.anchor);
2641
2994
  return {
2642
2995
  messageId: parsed.anchor.messageId,
2643
2996
  ...typeof parsed.anchor.threadId === "string" && parsed.anchor.threadId ? { threadId: parsed.anchor.threadId } : {},
2644
2997
  ...typeof parsed.anchor.home === "string" && parsed.anchor.home ? { home: parsed.anchor.home } : {},
2645
2998
  ...typeof parsed.anchor.chatId === "string" && parsed.anchor.chatId ? { chatId: parsed.anchor.chatId } : {},
2999
+ ...threadPosition !== void 0 ? { threadPosition } : {},
2646
3000
  at: parsed.anchor.at
2647
3001
  };
2648
3002
  }
@@ -2653,16 +3007,128 @@ function loadPersistedAnchor(sessionId, identity) {
2653
3007
  }
2654
3008
  function savePersistedAnchor(sessionId, identity, anchor) {
2655
3009
  try {
3010
+ const target = anchorPath(sessionId);
3011
+ const incomingPos = normalizeThreadPosition(anchor.threadPosition);
3012
+ let mergedPos = incomingPos;
3013
+ let threadChanged = false;
3014
+ try {
3015
+ const prevRaw = fs6.readFileSync(target, "utf8");
3016
+ const prev = JSON.parse(prevRaw);
3017
+ if (prev.provider === identity.provider && anchor.threadId && prev.anchor?.threadId === anchor.threadId) {
3018
+ const prevPos = resolveMergedThreadPosition(sessionId, identity.provider, prev.anchor);
3019
+ if (prevPos !== void 0) {
3020
+ mergedPos = incomingPos !== void 0 ? Math.max(prevPos, incomingPos) : prevPos;
3021
+ }
3022
+ } else if (prev.anchor?.threadId && prev.anchor.threadId !== anchor.threadId) {
3023
+ threadChanged = true;
3024
+ }
3025
+ } catch {
3026
+ }
3027
+ const cleanAnchor = {
3028
+ messageId: anchor.messageId,
3029
+ ...anchor.threadId ? { threadId: anchor.threadId } : {},
3030
+ ...anchor.home ? { home: anchor.home } : {},
3031
+ ...anchor.chatId ? { chatId: anchor.chatId } : {},
3032
+ ...mergedPos !== void 0 ? { threadPosition: mergedPos } : {},
3033
+ at: anchor.at
3034
+ };
2656
3035
  const file = {
2657
3036
  provider: identity.provider,
2658
3037
  targetId: identity.targetId,
2659
- anchor
3038
+ anchor: cleanAnchor
2660
3039
  };
2661
- const target = anchorPath(sessionId);
2662
- fs6.mkdirSync(path8.dirname(target), { recursive: true });
2663
- fs6.writeFileSync(target, `${JSON.stringify(file)}
2664
- `, "utf8");
3040
+ writeJsonFileAtomically(target, file);
3041
+ if (anchor.threadId && mergedPos !== void 0) {
3042
+ const hint = { provider: identity.provider, threadId: anchor.threadId, threadPosition: mergedPos };
3043
+ writeJsonFileAtomically(positionHintPath(sessionId), hint);
3044
+ } else if (threadChanged || !anchor.threadId) {
3045
+ try {
3046
+ fs6.rmSync(positionHintPath(sessionId), { force: true });
3047
+ } catch {
3048
+ }
3049
+ }
3050
+ } catch {
3051
+ }
3052
+ }
3053
+ function updatePersistedAnchorThreadPosition(sessionId, provider, threadId, threadPosition) {
3054
+ const pos = normalizeThreadPosition(threadPosition);
3055
+ if (!sessionId || !provider || !threadId || pos === void 0) return false;
3056
+ try {
3057
+ const raw = fs6.readFileSync(anchorPath(sessionId), "utf8");
3058
+ const parsed = JSON.parse(raw);
3059
+ if (parsed.provider !== provider || typeof parsed.targetId !== "string" || !parsed.anchor || parsed.anchor.threadId !== threadId || typeof parsed.anchor.messageId !== "string" || !parsed.anchor.messageId || typeof parsed.anchor.at !== "number") {
3060
+ return false;
3061
+ }
3062
+ const prevPos = resolveMergedThreadPosition(sessionId, provider, parsed.anchor);
3063
+ if (prevPos !== void 0 && pos <= prevPos) return false;
3064
+ const hint = { provider, threadId, threadPosition: pos };
3065
+ return writeJsonFileAtomically(positionHintPath(sessionId), hint);
2665
3066
  } catch {
3067
+ return false;
3068
+ }
3069
+ }
3070
+ var inFlightPositionLookups = /* @__PURE__ */ new Map();
3071
+ async function refreshAnchorThreadPositions(sessionIds, provider, lookup, opts = {}) {
3072
+ const unique = [...new Set(sessionIds.filter((s) => typeof s === "string" && s.length > 0))];
3073
+ if (unique.length === 0) return;
3074
+ const maxTargets = typeof opts.maxTargets === "number" && opts.maxTargets > 0 ? Math.min(opts.maxTargets, 24) : 12;
3075
+ const targets = [];
3076
+ for (const sessionId of unique) {
3077
+ if (targets.length >= maxTargets) break;
3078
+ try {
3079
+ const raw = fs6.readFileSync(anchorPath(sessionId), "utf8");
3080
+ const parsed = JSON.parse(raw);
3081
+ if (parsed.provider !== provider || !parsed.anchor?.threadId) continue;
3082
+ const existingPos = resolveMergedThreadPosition(sessionId, provider, parsed.anchor);
3083
+ if (!opts.force && existingPos !== void 0) continue;
3084
+ targets.push({
3085
+ sessionId,
3086
+ threadId: parsed.anchor.threadId,
3087
+ ...typeof parsed.anchor.messageId === "string" && parsed.anchor.messageId ? { messageId: parsed.anchor.messageId } : {}
3088
+ });
3089
+ } catch {
3090
+ }
3091
+ }
3092
+ if (targets.length === 0) return;
3093
+ const timeoutMs = typeof opts.timeoutMs === "number" && opts.timeoutMs > 0 ? opts.timeoutMs : 1500;
3094
+ const concurrency = typeof opts.concurrency === "number" && opts.concurrency > 0 ? Math.min(opts.concurrency, 8) : 4;
3095
+ const controller = new AbortController();
3096
+ let timer;
3097
+ const deadline = new Promise((resolve9) => {
3098
+ timer = setTimeout(() => {
3099
+ controller.abort();
3100
+ resolve9();
3101
+ }, timeoutMs);
3102
+ timer.unref?.();
3103
+ });
3104
+ let cursor = 0;
3105
+ const worker = async () => {
3106
+ while (!controller.signal.aborted) {
3107
+ const idx = cursor++;
3108
+ if (idx >= targets.length) return;
3109
+ const item = targets[idx];
3110
+ const dedupKey = `${provider}:${item.threadId}`;
3111
+ let pending = inFlightPositionLookups.get(dedupKey);
3112
+ if (!pending) {
3113
+ pending = Promise.resolve().then(() => lookup(item.threadId, item.messageId, controller.signal)).catch(() => null).finally(() => {
3114
+ if (inFlightPositionLookups.get(dedupKey) === pending) {
3115
+ inFlightPositionLookups.delete(dedupKey);
3116
+ }
3117
+ });
3118
+ inFlightPositionLookups.set(dedupKey, pending);
3119
+ }
3120
+ const pos = await pending;
3121
+ if (pos !== null && pos !== void 0) {
3122
+ updatePersistedAnchorThreadPosition(item.sessionId, provider, item.threadId, pos);
3123
+ }
3124
+ }
3125
+ };
3126
+ const workers = Array.from({ length: Math.min(concurrency, targets.length) }, () => worker());
3127
+ try {
3128
+ await Promise.race([Promise.allSettled(workers), deadline]);
3129
+ } finally {
3130
+ if (timer) clearTimeout(timer);
3131
+ controller.abort();
2666
3132
  }
2667
3133
  }
2668
3134
  function resolveSessionThreadUrl(sessionId) {
@@ -2671,7 +3137,9 @@ function resolveSessionThreadUrl(sessionId) {
2671
3137
  const raw = fs6.readFileSync(anchorPath(sessionId), "utf8");
2672
3138
  const parsed = JSON.parse(raw);
2673
3139
  if (typeof parsed.provider !== "string" || !parsed.anchor) return void 0;
2674
- return findImplementedProvider(parsed.provider)?.formatThreadUrl?.(parsed.anchor);
3140
+ const threadPosition = resolveMergedThreadPosition(sessionId, parsed.provider, parsed.anchor);
3141
+ const anchorWithPos = threadPosition !== void 0 ? { ...parsed.anchor, threadPosition } : { ...parsed.anchor, threadPosition: void 0 };
3142
+ return findImplementedProvider(parsed.provider)?.formatThreadUrl?.(anchorWithPos);
2675
3143
  } catch {
2676
3144
  return void 0;
2677
3145
  }
@@ -2748,7 +3216,7 @@ function createRuntimeRoutes(ctx) {
2748
3216
  if (live) return { messageId: live.messageId, threadId: live.threadId };
2749
3217
  return { threadId: null };
2750
3218
  }
2751
- function persistSessionAnchor(sessionId, messageId, threadId, home, chatId) {
3219
+ function persistSessionAnchor(sessionId, messageId, threadId, home, chatId, threadPosition) {
2752
3220
  if (threadId) persistedAnchorsLoaded.add(sessionId);
2753
3221
  replyAnchor.set(sessionId, { messageId, threadId, at: Date.now() });
2754
3222
  const resolvedChatId = chatId || (ctx.targetKind !== "user" && home ? home : void 0);
@@ -2758,6 +3226,7 @@ function createRuntimeRoutes(ctx) {
2758
3226
  ...threadId ? { threadId } : {},
2759
3227
  ...home ? { home } : {},
2760
3228
  ...resolvedChatId ? { chatId: resolvedChatId } : {},
3229
+ ...threadPosition !== void 0 ? { threadPosition } : {},
2761
3230
  at: Date.now()
2762
3231
  });
2763
3232
  } catch (error) {
@@ -4511,7 +4980,7 @@ function createOutboundRuntime(deps) {
4511
4980
  const { ctx, cfg, connection, isManager, routeState, isForwardingEnabled, isTerminated, getCurrentSessionId, getInputEpoch, handleInboundEvent } = deps;
4512
4981
  const IM_INPUT_PREFIX = connection.sourcePrefix;
4513
4982
  const resolveSessionAnchor = (sessionId) => routeState.resolveSessionAnchor(sessionId);
4514
- const persistSessionAnchor = (sessionId, messageId, threadId, home, chatId) => routeState.persistSessionAnchor(sessionId, messageId, threadId, home, chatId);
4983
+ const persistSessionAnchor = (sessionId, messageId, threadId, home, chatId, threadPosition) => routeState.persistSessionAnchor(sessionId, messageId, threadId, home, chatId, threadPosition);
4515
4984
  let forwardCounter = 0;
4516
4985
  const incarnation = crypto.randomUUID();
4517
4986
  let anchorFallbacks = 0;
@@ -4829,11 +5298,13 @@ ${recoveryHint}`,
4829
5298
  settleDelivery(deliverRequests, true);
4830
5299
  markSettled?.();
4831
5300
  registerRoute(sent, sessionId);
5301
+ let lastThreadSent = sent;
4832
5302
  const legacyUpgrade = !isManager && anchor !== void 0 && !sessionAnchor.threadId && sent.messageId !== anchor;
4833
5303
  const stakeNeeded = stakeFlightToken !== void 0;
4834
5304
  if (stakeNeeded) {
4835
5305
  try {
4836
5306
  let threadId = sent.threadId, anchorChatId = sent.chatId ?? null;
5307
+ let threadPos = sent.threadPosition;
4837
5308
  if (!threadId && connection.openTopic) {
4838
5309
  const opener = await providerCall(
4839
5310
  "thread opener",
@@ -4841,14 +5312,19 @@ ${recoveryHint}`,
4841
5312
  );
4842
5313
  threadId = opener?.threadId ?? null;
4843
5314
  anchorChatId ??= opener?.chatId ?? null;
4844
- if (opener) registerRoute(opener, sessionId);
5315
+ threadPos = opener?.threadPosition ?? threadPos;
5316
+ if (opener) {
5317
+ registerRoute(opener, sessionId);
5318
+ lastThreadSent = opener;
5319
+ }
4845
5320
  }
4846
5321
  if (!threadId || !anchorChatId) {
4847
5322
  const meta = await providerCall("metadata", () => connection.metadata(sent.messageId));
4848
5323
  threadId ??= meta?.threadId ?? null;
4849
5324
  anchorChatId ??= meta?.chatId ?? null;
5325
+ threadPos ??= meta?.threadPosition;
4850
5326
  }
4851
- persistSessionAnchor(sessionId, sent.messageId, threadId, cfg.targetId, anchorChatId);
5327
+ persistSessionAnchor(sessionId, sent.messageId, threadId, cfg.targetId, anchorChatId, threadPos);
4852
5328
  if (threadId) {
4853
5329
  claimThreadOwnership({ provider: cfg.provider, threadId }, sessionId);
4854
5330
  }
@@ -4895,6 +5371,20 @@ ${recoveryHint}`,
4895
5371
  return;
4896
5372
  }
4897
5373
  registerRoute(next, sessionId);
5374
+ lastThreadSent = next;
5375
+ }
5376
+ const effectiveThreadId = lastThreadSent.threadId ?? threadPlacement.topicId ?? sessionAnchorThreadId ?? null;
5377
+ if (effectiveThreadId && lastThreadSent.messageId) {
5378
+ if (lastThreadSent.threadPosition !== void 0) {
5379
+ updatePersistedAnchorThreadPosition(sessionId, cfg.provider, effectiveThreadId, lastThreadSent.threadPosition);
5380
+ } else if (!isTerminated() && isForwardingEnabled()) {
5381
+ const targetMsgId = lastThreadSent.messageId;
5382
+ void providerCall("thread position", () => connection.metadata(targetMsgId)).then((meta) => {
5383
+ if (meta?.threadPosition !== void 0 && (!meta.threadId || meta.threadId === effectiveThreadId) && !isTerminated()) {
5384
+ updatePersistedAnchorThreadPosition(sessionId, cfg.provider, effectiveThreadId, meta.threadPosition);
5385
+ }
5386
+ }).catch(() => void 0);
5387
+ }
4898
5388
  }
4899
5389
  if (connection.sendFile && !isTerminated() && isForwardingEnabled() && !systemNotice) {
4900
5390
  const files = collectFileReferences(
@@ -6686,9 +7176,14 @@ function composeWorkerCard(peer, opts = {}) {
6686
7176
  const managed = currentWorkerLifecycleBridge()?.lookupBySession(peer.sessionId);
6687
7177
  const canQuit = canRemotelyQuitPeer(peer);
6688
7178
  const workerCron = cronActiveCount(peer.sessionId);
7179
+ const yoloAction = typeof peer.yoloMode === "boolean" ? [{
7180
+ id: `panel.yolo.${peer.instanceId}.${peer.yoloMode ? "off" : "on"}`,
7181
+ label: peer.yoloMode ? "\u26A1 YOLO: ON" : "\u{1F6E1} YOLO: OFF"
7182
+ }] : [];
6689
7183
  const fixedActions = [
6690
7184
  { id: `panel.worker.${peer.instanceId}`, label: "\u{1F504} Refresh" },
6691
7185
  { id: `panel.worker.models.${peer.instanceId}`, label: "\u{1F39A} Model" },
7186
+ ...yoloAction,
6692
7187
  ...peer.sessionControls ? [
6693
7188
  { id: `panel.context.${peer.instanceId}`, label: "\u{1F4CA} Context", payload: fromWorker },
6694
7189
  { id: `panel.tree.${peer.instanceId}`, label: "\u{1F333} Tree", payload: fromWorker }
@@ -6716,9 +7211,10 @@ ${a.runs} run(s) \xB7 last ${cleanInline(a.lastRunBy ?? "\u2014", 24)}`,
6716
7211
  const footer = wActions.length > maxCustom ? `More actions (copy to run): ${wActions.slice(maxCustom).map((a) => `\`/card panel.action.${cleanCodeSpan(a.id, 32)} ${cleanCodeSpan(JSON.stringify({ worker: { ref: peer.instanceId } }), 80)}\``).join(" \xB7 ")}` : wActions.length === 0 ? "No custom worker actions yet (actions with scope=worker appear here)." : "Inline buttons run in this worker's context (zero LLM).";
6717
7212
  const threadUrl = resolveSessionThreadUrl(peer.sessionId);
6718
7213
  const infoLines = [
7214
+ ...opts.banner ? [opts.banner, ""] : [],
6719
7215
  `- **name**: ${cleanInline(peer.name, 48)} \xB7 **state**: ${cleanInline(state, 48)}`,
6720
7216
  `- **model**: \`${cleanCodeSpan(modelDisplay, 56)}\``,
6721
- `- **host**: ${cleanInline(managedLabel, 48)} \xB7 **version**: ${cleanInline(peer.version ?? "\u2014", 24)}`,
7217
+ `- **host**: ${cleanInline(managedLabel, 48)} \xB7 **version**: ${cleanInline(peer.version ?? "\u2014", 24)}${typeof peer.yoloMode === "boolean" ? ` \xB7 **yolo**: ${peer.yoloMode ? "on" : "off"}` : ""}`,
6722
7218
  ...peer.cwd ? [`- **cwd**: \`${cleanCodeSpan(peer.cwd, 96)}\``] : [],
6723
7219
  ...threadUrl ? [`- **thread**: [\u{1F4AC} Open Thread \u2197](${threadUrl})`] : []
6724
7220
  ];
@@ -6975,7 +7471,7 @@ function parsePanelCommand(text) {
6975
7471
  rest = next?.[2] ?? "";
6976
7472
  }
6977
7473
  if (cmd !== "panel" && cmd !== "panel.refresh" && cmd !== "panel.summon" && cmd !== "panel.home" && cmd !== "panel.archive" && cmd !== "panel.models" && cmd !== "panel.context" && cmd !== "panel.compact" && cmd !== "panel.tree" && cmd !== "panel.cron" && cmd !== "panel.memory" && cmd !== "panel.memory.view" && cmd !== "panel.memory.logs" && cmd !== "panel.memory.dream" && cmd !== "panel.memory.gc" && cmd !== "panel.upgrade" && cmd !== "panel.upgrade.confirm" && cmd !== "panel.help" && cmd !== "panel.actions" && cmd !== "panel.worker.offline" && cmd !== "\u9762\u677F") {
6978
- if (!/^panel\.model\.[A-Za-z0-9-]+\..+$/.test(cmd) && !/^panel\.thinking\.[A-Za-z0-9-]+\.(?:off|minimal|low|medium|high|xhigh|max)$/.test(cmd) && !/^panel\.(context|compact)\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.tree(?:\.branch(?:\.confirm)?)?\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.peek(?:\.refresh)?\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.archive\.view\.[A-Za-z0-9][A-Za-z0-9-_]{5,63}$/.test(cmd) && !/^panel\.worker(?:\.(?:models|cron))?\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.cron\.(?:pause|resume|stop(?:\.confirm)?)\.[A-Za-z0-9-]{8,64}$/.test(cmd) && !/^panel\.stop\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.quit(?:\.(?:confirm|force))?\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.resume\.[A-Za-z0-9][A-Za-z0-9-_]{5,63}$/.test(cmd) && !/^panel\.action\.[a-z0-9][a-z0-9-]{0,31}$/.test(cmd)) return void 0;
7474
+ if (!/^panel\.model\.[A-Za-z0-9-]+\..+$/.test(cmd) && !/^panel\.thinking\.[A-Za-z0-9-]+\.(?:off|minimal|low|medium|high|xhigh|max)$/.test(cmd) && !/^panel\.yolo\.[A-Za-z0-9-]+\.(?:on|off)$/.test(cmd) && !/^panel\.(context|compact)\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.tree(?:\.branch(?:\.confirm)?)?\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.peek(?:\.refresh)?\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.archive\.view\.[A-Za-z0-9][A-Za-z0-9-_]{5,63}$/.test(cmd) && !/^panel\.worker(?:\.(?:models|cron))?\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.cron\.(?:pause|resume|stop(?:\.confirm)?)\.[A-Za-z0-9-]{8,64}$/.test(cmd) && !/^panel\.stop\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.quit(?:\.(?:confirm|force))?\.[A-Za-z0-9-]+$/.test(cmd) && !/^panel\.resume\.[A-Za-z0-9][A-Za-z0-9-_]{5,63}$/.test(cmd) && !/^panel\.action\.[a-z0-9][a-z0-9-]{0,31}$/.test(cmd)) return void 0;
6979
7475
  }
6980
7476
  const leadingFlag = /^--restricted(?:\s+|$)/.exec(rest);
6981
7477
  const restricted = leadingFlag !== null;
@@ -7040,7 +7536,8 @@ function scanPeers() {
7040
7536
  thinkingLevel: typeof parsed.thinkingLevel === "string" && thinkingRe.test(parsed.thinkingLevel) ? parsed.thinkingLevel : void 0,
7041
7537
  effectiveThinkingLevel: typeof parsed.effectiveThinkingLevel === "string" && thinkingRe.test(parsed.effectiveThinkingLevel) ? parsed.effectiveThinkingLevel : void 0,
7042
7538
  supportedThinkingLevels: Array.isArray(parsed.supportedThinkingLevels) && parsed.supportedThinkingLevels.length <= 8 && parsed.supportedThinkingLevels.every((l) => typeof l === "string" && thinkingRe.test(l)) ? parsed.supportedThinkingLevels : void 0,
7043
- version: typeof parsed.version === "string" && parsed.version ? parsed.version : void 0
7539
+ version: typeof parsed.version === "string" && parsed.version ? parsed.version : void 0,
7540
+ ...typeof parsed.yoloMode === "boolean" ? { yoloMode: parsed.yoloMode } : {}
7044
7541
  });
7045
7542
  } catch {
7046
7543
  }
@@ -7640,6 +8137,14 @@ async function ensureResumedSessionTopic(opts) {
7640
8137
  const identity = { provider: opts.provider, targetId: opts.targetId };
7641
8138
  const existing = loadPersistedAnchor(opts.sessionId, identity);
7642
8139
  if (existing?.threadId) {
8140
+ if (opts.connection.latestThreadPosition) {
8141
+ await refreshAnchorThreadPositions(
8142
+ [opts.sessionId],
8143
+ opts.provider,
8144
+ (tid, mid, sig) => opts.connection.latestThreadPosition(tid, mid, sig),
8145
+ { force: true, timeoutMs: 1500 }
8146
+ );
8147
+ }
7643
8148
  return {
7644
8149
  opened: false,
7645
8150
  threadId: existing.threadId,
@@ -7653,13 +8158,17 @@ Reply in this thread to continue.`;
7653
8158
  const baseKey = `panel-resume-topic-${opts.eventId}-${opts.sessionId}`;
7654
8159
  try {
7655
8160
  let anchorMessageId;
8161
+ let positionQueryMessageId;
7656
8162
  let threadId = null;
7657
8163
  let anchorChatId = existing?.chatId ?? null;
8164
+ let threadPosition;
7658
8165
  if (existing?.messageId) {
7659
8166
  anchorMessageId = existing.messageId;
7660
8167
  const reply = await opts.connection.send(opts.recipient, readyText, baseKey, existing.messageId, { replyInThread: true });
8168
+ positionQueryMessageId = reply?.messageId;
7661
8169
  threadId = reply?.threadId ?? null;
7662
8170
  anchorChatId ??= reply?.chatId ?? null;
8171
+ threadPosition = reply?.threadPosition;
7663
8172
  } else {
7664
8173
  const sent = await opts.connection.send(opts.recipient, readyText, baseKey);
7665
8174
  if (!sent?.messageId) {
@@ -7668,17 +8177,23 @@ Reply in this thread to continue.`;
7668
8177
  anchorMessageId = sent.messageId;
7669
8178
  threadId = sent.threadId ?? null;
7670
8179
  anchorChatId ??= sent.chatId ?? null;
8180
+ threadPosition = sent.threadPosition;
7671
8181
  if (!threadId && opts.connection.openTopic) {
7672
8182
  const opener = await opts.connection.openTopic(opts.recipient, sent.messageId, `${baseKey}-opener`);
8183
+ positionQueryMessageId = opener?.messageId;
7673
8184
  threadId = opener?.threadId ?? null;
7674
8185
  anchorChatId ??= opener?.chatId ?? null;
8186
+ threadPosition = opener?.threadPosition ?? threadPosition;
7675
8187
  }
7676
8188
  }
7677
- if (!threadId || !anchorChatId) {
8189
+ if (!threadId || !anchorChatId || threadPosition === void 0 && positionQueryMessageId) {
7678
8190
  try {
7679
- const meta = await opts.connection.metadata(anchorMessageId);
8191
+ const meta = await opts.connection.metadata(positionQueryMessageId ?? anchorMessageId);
7680
8192
  threadId ??= meta?.threadId ?? null;
7681
8193
  anchorChatId ??= meta?.chatId ?? null;
8194
+ if (!meta?.threadId || !threadId || meta.threadId === threadId) {
8195
+ threadPosition ??= meta?.threadPosition;
8196
+ }
7682
8197
  } catch {
7683
8198
  }
7684
8199
  }
@@ -7694,6 +8209,7 @@ Reply in this thread to continue.`;
7694
8209
  ...threadId ? { threadId } : {},
7695
8210
  home: opts.recipient,
7696
8211
  ...anchorChatId ? { chatId: anchorChatId } : {},
8212
+ ...threadPosition !== void 0 ? { threadPosition } : {},
7697
8213
  at: Date.now()
7698
8214
  });
7699
8215
  claimSessionRoot(opts.provider, anchorMessageId, opts.sessionId);
@@ -8067,7 +8583,7 @@ function guardThreadWorkerScope(panelCmd, workerScoped, inThread, pinnedWorkerSe
8067
8583
  }
8068
8584
  return { blocked: true, spec: composeOfflineWorkerCard(pinnedWorkerSessionId, { inThread, hideHome: true }) };
8069
8585
  }
8070
- const ctrlPeerMatch = /^panel\.(?:model|thinking|context|compact|stop|peek(?:\.refresh)?)\.([A-Za-z0-9-]+)/.exec(panelCmd.cmd);
8586
+ const ctrlPeerMatch = /^panel\.(?:model|thinking|yolo|context|compact|stop|peek(?:\.refresh)?)\.([A-Za-z0-9-]+)/.exec(panelCmd.cmd);
8071
8587
  if (ctrlPeerMatch) {
8072
8588
  const peer = scanPeers().find((p) => p.instanceId === ctrlPeerMatch[1]);
8073
8589
  if (peer) {
@@ -8081,7 +8597,7 @@ function guardThreadWorkerScope(panelCmd, workerScoped, inThread, pinnedWorkerSe
8081
8597
  return { blocked: false };
8082
8598
  }
8083
8599
  function isMutatingWorkerLifecycleCommand(cmd) {
8084
- return /^panel\.thinking\./.test(cmd) || /^panel\.stop\./.test(cmd) || /^panel\.quit\.(?:confirm|force)\./.test(cmd) || /^panel\.resume\./.test(cmd);
8600
+ return /^panel\.thinking\./.test(cmd) || /^panel\.yolo\./.test(cmd) || /^panel\.stop\./.test(cmd) || /^panel\.quit\.(?:confirm|force)\./.test(cmd) || /^panel\.resume\./.test(cmd);
8085
8601
  }
8086
8602
  async function runWorkerLifecycleCommand(panelCmd, inThread, verifiedQuit, threadWorkerSessionId, hideHome = inThread, onResumed) {
8087
8603
  const cols = inThread ? 2 : 3;
@@ -8113,6 +8629,35 @@ async function runWorkerLifecycleCommand(panelCmd, inThread, verifiedQuit, threa
8113
8629
  })
8114
8630
  };
8115
8631
  }
8632
+ const yoloAction = /^panel\.yolo\.([A-Za-z0-9-]+)\.(on|off)$/.exec(panelCmd.cmd);
8633
+ if (yoloAction) {
8634
+ const [, peerRef, mode] = yoloAction;
8635
+ const enabled = mode === "on";
8636
+ const receipt = await applyPeerControl(peerRef, "yolo.set", { enabled });
8637
+ const livePeer = scanPeers().find((p) => p.instanceId === peerRef);
8638
+ const banner = receipt.ok ? `\u2705 YOLO mode set to \`${mode}\` (applies immediately)` : `\u26A0\uFE0F Failed to set YOLO \`${mode}\`: ${sanitizeLiteralMarkdown(receipt.detail)}`;
8639
+ if (livePeer) {
8640
+ const updatedPeer = receipt.ok ? { ...livePeer, yoloMode: enabled } : livePeer;
8641
+ return {
8642
+ handled: true,
8643
+ keyPrefix: "panel-yolo",
8644
+ spec: composeWorkerCard(updatedPeer, { inThread, hideHome, banner })
8645
+ };
8646
+ }
8647
+ return {
8648
+ handled: true,
8649
+ keyPrefix: "panel-yolo",
8650
+ spec: {
8651
+ title: receipt.ok ? `\u26A1 YOLO: ${mode.toUpperCase()}` : "\u26A0\uFE0F YOLO Toggle Failed",
8652
+ color: receipt.ok ? "green" : "red",
8653
+ columnsPerRow: cols,
8654
+ body: `${banner}
8655
+
8656
+ Target: \`${cleanCodeSpan(peerRef, 48)}\``,
8657
+ actions: homeOrWorker(peerRef)
8658
+ }
8659
+ };
8660
+ }
8116
8661
  const stopAction = /^panel\.stop\.([A-Za-z0-9-]+)$/.exec(panelCmd.cmd);
8117
8662
  if (stopAction) {
8118
8663
  const peerRef = stopAction[1];
@@ -10297,6 +10842,10 @@ function createPanelExecutor(ctx) {
10297
10842
  return;
10298
10843
  }
10299
10844
  }
10845
+ const archiveViewSession = /^panel\.archive\.view\.([A-Za-z0-9._-]+)$/.exec(effectiveCmd.cmd)?.[1];
10846
+ if (archiveViewSession && peekAudienceAllowed(event) && ctx.connection.latestThreadPosition) {
10847
+ await refreshAnchorThreadPositions([archiveViewSession], ctx.provider, (tid, mid, sig) => ctx.connection.latestThreadPosition(tid, mid, sig), { force: true, timeoutMs: 1500 });
10848
+ }
10300
10849
  const archiveResult = runArchivePanelCommand(effectiveCmd, {
10301
10850
  inThread,
10302
10851
  provider: ctx.provider,
@@ -10793,6 +11342,14 @@ ${result2.stderrTail.trim().slice(0, 1500).replace(/`/g, "'").replace(/</g, "\u2
10793
11342
  await initialAck;
10794
11343
  return;
10795
11344
  }
11345
+ if (ctx.connection.latestThreadPosition) {
11346
+ const isHomeOrRefresh = effectiveCmd.cmd === "panel.home" || effectiveCmd.cmd === "panel" || effectiveCmd.cmd === "\u9762\u677F" || effectiveCmd.cmd === "panel.refresh" || effectiveCmd.cmd === "panel.summon";
11347
+ const isWorkerView = effectiveCmd.cmd.startsWith("panel.worker.");
11348
+ const targetIds = isWorkerView ? threadWorkerSessionId ? [threadWorkerSessionId] : [] : isHomeOrRefresh ? scanPeers().map((p) => p.sessionId) : [];
11349
+ if (targetIds.length > 0) {
11350
+ await refreshAnchorThreadPositions(targetIds, ctx.provider, (tid, mid, sig) => ctx.connection.latestThreadPosition(tid, mid, sig), { force: effectiveCmd.cmd === "panel.refresh" || isWorkerView, timeoutMs: 1500 });
11351
+ }
11352
+ }
10796
11353
  const result = executePanelCommand({ ...effectiveCmd, senderId: event.sender_id, originCardId: canPatchOrigin ? event.message_id : void 0, inThread, ...workerScoped ? { workerScoped: true } : {}, ...threadWorkerSessionId ? { fallbackSessionId: threadWorkerSessionId } : {} });
10797
11354
  await deliverPanelSpec(result.spec, `panel-${event.event_id}`, result.patchOrigin);
10798
11355
  };
@@ -11350,12 +11907,15 @@ ${imagelessCaption || (imageKeys.length ? IM_INPUT_FALLBACK_CAPTION2 : "") || ca
11350
11907
  }
11351
11908
  return;
11352
11909
  }
11910
+ const chosenThreadId = route.threadId ?? meta.threadId ?? null;
11911
+ const inboundThreadPos = chosenThreadId && (!meta.threadId || meta.threadId === chosenThreadId) ? meta.threadPosition : void 0;
11353
11912
  persistSessionAnchor(
11354
11913
  route.sessionId,
11355
11914
  messageId,
11356
- route.threadId ?? meta.threadId ?? null,
11915
+ chosenThreadId,
11916
+ event.chat_id,
11357
11917
  event.chat_id,
11358
- event.chat_id
11918
+ inboundThreadPos
11359
11919
  );
11360
11920
  claimSessionRoot(cfg.provider, messageId, route.sessionId);
11361
11921
  if (route.threadId ?? meta.threadId) {