@qwen-code/channel-github 0.26.7-nightly.20261104.b9e20830f7 → 0.26.8

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.
@@ -414,6 +414,17 @@ export function validateBoundSessionConfig(config, channelName) {
414
414
  return undefined;
415
415
  }
416
416
  const MAX_INBOUND_TASK_ATTEMPTS = 3;
417
+ /**
418
+ * Polls of one notification window that may fail with a 5xx while reading a
419
+ * thread (~30 minutes at the default 60s poll, plus the in-call retries). The
420
+ * window stays unread through the first 29; on the 30th, threads that still
421
+ * fail are skipped like a permanent failure and the window can be marked
422
+ * read. The budget belongs to the window, not to a thread, so threads that
423
+ * fail in turn cannot keep mark-as-read and the cursor frozen indefinitely.
424
+ */
425
+ const MAX_TRANSIENT_FAILURE_POLLS = 30;
426
+ /** Bounds the per-window key sets of a window held for very long. */
427
+ const MAX_WINDOW_KEYS = 8192;
417
428
  /**
418
429
  * The poll cursor does not advance while an inbound task is recoverable, so a
419
430
  * slow or stuck turn makes GitHub return the same notifications on every poll.
@@ -541,10 +552,40 @@ function isNoReplySentinel(text) {
541
552
  const fenced = trimmed.match(/^```[^\n]*\n([\s\S]*?)\n```$/);
542
553
  return NO_REPLY_SENTINEL_PATTERN.test((fenced?.[1] ?? trimmed).trim());
543
554
  }
544
- function isDefiniteNoWriteGithubError(err) {
555
+ /** GitHub's wording for a secondary (abuse) rate limit. */
556
+ const SECONDARY_RATE_LIMIT_MESSAGE = /secondary rate limit|abuse detection/i;
557
+ /** `x-ratelimit-remaining` as a count; absent or malformed is undefined. */
558
+ function rateLimitRemaining(err) {
559
+ const value = err.response?.headers?.['x-ratelimit-remaining'];
560
+ if (typeof value === 'number') {
561
+ return Number.isInteger(value) && value >= 0 ? value : undefined;
562
+ }
563
+ return typeof value === 'string' && /^\d+$/.test(value)
564
+ ? Number(value)
565
+ : undefined;
566
+ }
567
+ /**
568
+ * A 403 or 429 carrying one of GitHub's rate-limit signals: an exhausted
569
+ * budget, `retry-after`, or the secondary-limit wording. GitHub sends a
570
+ * secondary limit with quota left and not always with `retry-after`, and its
571
+ * wording has changed before, so no single signal is required.
572
+ */
573
+ function isRateLimitAnswer(err) {
545
574
  const e = err;
546
575
  return ((e.status === 403 || e.status === 429) &&
547
- Number(e.response?.headers?.['x-ratelimit-remaining']) === 0);
576
+ (rateLimitRemaining(err) === 0 ||
577
+ e.response?.headers?.['retry-after'] !== undefined ||
578
+ SECONDARY_RATE_LIMIT_MESSAGE.test(String(e.message))));
579
+ }
580
+ /**
581
+ * GitHub's rate limiter rejected the write before creating anything: a rate
582
+ * limit answer that also carries `x-ratelimit-remaining`, which shows GitHub's
583
+ * API answered rather than, say, a bare 429 from a proxy in front of it. A
584
+ * component that copied GitHub's headers onto its own 403/429 could still be
585
+ * misread.
586
+ */
587
+ function isDefiniteNoWriteGithubError(err) {
588
+ return isRateLimitAnswer(err) && rateLimitRemaining(err) !== undefined;
548
589
  }
549
590
  /**
550
591
  * Watch-pass fail-fast predicate. The watch is best-effort detection that runs
@@ -576,22 +617,34 @@ function isWatchFailFastError(err) {
576
617
  * must not stop the others from being watched. A 403 aborts the pass only
577
618
  * when it is provably a shared rate limit; a per-repo permission 403 (a
578
619
  * fine-grained token lacking access to one repo) is isolated to that PR,
579
- * since bindings come from sessions, not the token's grants (R1-11).
620
+ * since bindings come from sessions, not the token's grants (R1-11). The
621
+ * notification lane stops a poll on the same answers (classifyThreadFailure).
580
622
  */
581
623
  function isWatchPassAbortError(err) {
582
624
  const e = err;
583
625
  if (e.status === 401 || e.status === 429)
584
626
  return true;
585
- if (e.status === 403) {
586
- // GitHub does not always send x-ratelimit-remaining === 0 on a
587
- // secondary/abuse limit, but it does send retry-after; either marks a
588
- // shared rate limit. A bare permission 403 (remaining > 0, no
589
- // retry-after) stays per-PR so it cannot starve the other watched PRs.
590
- const headers = e.response?.headers;
591
- return (Number(headers?.['x-ratelimit-remaining']) === 0 ||
592
- headers?.['retry-after'] !== undefined);
593
- }
594
- return false;
627
+ // A 403 aborts only as a rate limit; a bare permission 403 (quota left, no
628
+ // retry-after, no limit wording) stays per-PR so it cannot starve the other
629
+ // watched PRs.
630
+ return e.status === 403 && isRateLimitAnswer(err);
631
+ }
632
+ /**
633
+ * How a failure reading one notification's thread is handled. A rate-limit or
634
+ * credential answer (`shared`, the answers that also abort the PR watch pass)
635
+ * applies to every thread, so the poll stops and holds the window until GitHub
636
+ * answers again. A 5xx (`transient`; Octokit also reports network failures as
637
+ * 500) belongs to this thread. Another 4xx (a deleted, transferred or
638
+ * inaccessible thread) or a local exception without a status comes back the
639
+ * same on every retry (`permanent`).
640
+ */
641
+ function classifyThreadFailure(err) {
642
+ const e = err;
643
+ if (typeof e.status !== 'number')
644
+ return 'permanent';
645
+ if (isWatchPassAbortError(err))
646
+ return 'shared';
647
+ return e.status >= 500 ? 'transient' : 'permanent';
595
648
  }
596
649
  function parseTriggerKind(metadata) {
597
650
  return metadata?.match(/^Trigger: ([\w-]+)\./m)?.[1];
@@ -744,10 +797,37 @@ export class GithubChannel extends PollingChannelBase {
744
797
  prWatchStateLoaded = false;
745
798
  inboundRecoveryPending = true;
746
799
  recoverableInboundTasks = 0;
800
+ /**
801
+ * The inbound task store as this process last read or wrote it, for a check
802
+ * in the poll's error path that must not read the disk again.
803
+ */
804
+ inboundTaskSnapshot = [];
747
805
  activeInboundTaskIdsByMessage = new Map();
748
806
  cancelledInboundTaskIds = new Set();
749
807
  pendingCursorUpdatedAt;
750
808
  inboundPersistenceBlocked = false;
809
+ /**
810
+ * Set when reading a notification failed this poll with a 5xx or a shared
811
+ * failure (rate limit, credentials): the cursor and mark-as-read must not
812
+ * move past it, or the thread would never be listed again and its comment
813
+ * would be lost silently.
814
+ */
815
+ notificationRetryPending = false;
816
+ /** Polls since the window was last marked read that a 5xx kept it unread. */
817
+ transientHoldPolls = 0;
818
+ /** Polls since the window was last marked read stopped by a shared failure. */
819
+ sharedHoldPolls = 0;
820
+ /**
821
+ * Failing polls per thread since the window was last marked read. Only the
822
+ * log throttle reads it; the retry decision is the window's budget.
823
+ */
824
+ transientNotificationFailures = new Map();
825
+ /**
826
+ * Journal rows already written for the current window. A held window
827
+ * re-reads the same threads and comments on every poll, and rows that say
828
+ * nothing new (a repeated skip) are written once per window.
829
+ */
830
+ windowJournalKeys = new Set();
751
831
  constructor(name, config, bridge, options) {
752
832
  config.instructions = [
753
833
  config.instructions?.trim(),
@@ -1062,9 +1142,13 @@ export class GithubChannel extends PollingChannelBase {
1062
1142
  }
1063
1143
  async retryPendingFinalDeliveries(signal) {
1064
1144
  const pending = this.readPendingFinalDeliveries();
1145
+ let rateLimited = false;
1065
1146
  for (const record of pending) {
1066
- if (signal?.aborted)
1147
+ // A stop defers the abort while another write is in flight; start no
1148
+ // new record meanwhile.
1149
+ if (signal?.aborted || this.pendingFinalDeliveryRetryStopRequested) {
1067
1150
  return;
1151
+ }
1068
1152
  const auditBase = this.buildPublicationAuditBase({
1069
1153
  chatId: record.chatId,
1070
1154
  threadId: record.threadId,
@@ -1083,6 +1167,11 @@ export class GithubChannel extends PollingChannelBase {
1083
1167
  }
1084
1168
  continue;
1085
1169
  }
1170
+ // A rate limit answers every later record the same way: keep them for
1171
+ // the next start instead of spending three more attempts on each. The
1172
+ // already-posted check above needs no request, so it still runs.
1173
+ if (rateLimited)
1174
+ continue;
1086
1175
  try {
1087
1176
  const comment = await this.createIssueComment(record.chatId, record.threadId, this.formatMarkdownAttributedText(record.fullText, record.sourceLabel), 3, isDefiniteNoWriteGithubError, signal);
1088
1177
  // ponytail: GitHub has no createComment idempotency key without adding
@@ -1103,17 +1192,26 @@ export class GithubChannel extends PollingChannelBase {
1103
1192
  this.removeReplyPendingInboundTask(record);
1104
1193
  }
1105
1194
  catch (err) {
1106
- if (signal?.aborted)
1195
+ // The abort waits for an in-flight write, so an answer that arrives
1196
+ // with the signal aborted still decides the record; only an attempt
1197
+ // that was never sent leaves it for the next start.
1198
+ if (err.notSent)
1107
1199
  return;
1108
1200
  if (isDefiniteNoWriteGithubError(err)) {
1201
+ rateLimited = true;
1109
1202
  continue;
1110
1203
  }
1204
+ // A rate limit without GitHub's header is no proof the write was
1205
+ // refused, so this record is dropped below, but it would answer the
1206
+ // later records the same way: keep those for the next start.
1207
+ if (isRateLimitAnswer(err))
1208
+ rateLimited = true;
1111
1209
  this.recordPublicationAudit({
1112
1210
  ...auditBase,
1113
1211
  at: new Date().toISOString(),
1114
1212
  type: 'github_publication',
1115
- // Ambiguous by construction: the definite-no-write branch above
1116
- // already continued. Keep the key consumed (at-most-once).
1213
+ // Ambiguous by construction: a definite no-write never reaches
1214
+ // here. Keep the key consumed (at-most-once).
1117
1215
  outcome: 'failed_ambiguous',
1118
1216
  failurePhase: 'delivery',
1119
1217
  failureError: sanitizeLogText(err instanceof Error ? err.message : String(err), 200),
@@ -1319,6 +1417,7 @@ export class GithubChannel extends PollingChannelBase {
1319
1417
  }
1320
1418
  async pollOnce() {
1321
1419
  this.inboundPersistenceBlocked = false;
1420
+ this.notificationRetryPending = false;
1322
1421
  this.publicationAuditBlocked = false;
1323
1422
  this.publicationAuditKeysCache = undefined;
1324
1423
  if (this.deliverToBoundSessions) {
@@ -1456,6 +1555,8 @@ export class GithubChannel extends PollingChannelBase {
1456
1555
  }
1457
1556
  let reasonFilterJournaled = 0;
1458
1557
  let reasonFilterCollapsed = 0;
1558
+ let transientHeld = false;
1559
+ let sharedHeld = false;
1459
1560
  for (const notification of notifications) {
1460
1561
  if (!notification.subject.url)
1461
1562
  continue;
@@ -1502,6 +1603,12 @@ export class GithubChannel extends PollingChannelBase {
1502
1603
  subjectTitle: notification.subject.title || '',
1503
1604
  reason,
1504
1605
  };
1606
+ const failureKey = `${chatId}|${threadId}`;
1607
+ // A notification at or before the cursor belongs to a window that
1608
+ // already committed; it is listed again only because its mark-as-read
1609
+ // did not apply. A 5xx reading it neither holds the new window nor
1610
+ // spends its budget; a rate limit still stops the poll.
1611
+ const stale = notification.updated_at <= this.cursor.lastProcessedAt;
1505
1612
  try {
1506
1613
  switch (reason) {
1507
1614
  case 'mention':
@@ -1529,10 +1636,98 @@ export class GithubChannel extends PollingChannelBase {
1529
1636
  }
1530
1637
  }
1531
1638
  catch (err) {
1532
- process.stderr.write(`[Channel:${this.name}] API error processing ${threadId}, skipping: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
1639
+ const failure = classifyThreadFailure(err);
1640
+ let failures = 0;
1641
+ // Past the bound a new thread's count is not kept, so it is not known
1642
+ // which of its polls are milestones.
1643
+ let counted = false;
1644
+ if (failure === 'transient' && !stale) {
1645
+ failures =
1646
+ (this.transientNotificationFailures.get(failureKey) ?? 0) + 1;
1647
+ counted =
1648
+ this.transientNotificationFailures.has(failureKey) ||
1649
+ this.transientNotificationFailures.size < MAX_WINDOW_KEYS;
1650
+ if (counted) {
1651
+ this.transientNotificationFailures.set(failureKey, failures);
1652
+ }
1653
+ }
1654
+ const transientPoll = this.transientHoldPolls + 1;
1655
+ const retry = failure === 'shared' ||
1656
+ (failure === 'transient' &&
1657
+ !stale &&
1658
+ transientPoll < MAX_TRANSIENT_FAILURE_POLLS);
1659
+ if (retry) {
1660
+ this.notificationRetryPending = true;
1661
+ if (failure === 'shared')
1662
+ sharedHeld = true;
1663
+ else
1664
+ transientHeld = true;
1665
+ }
1666
+ // A held window re-reads the thread every poll. Report a thread's
1667
+ // first and every tenth failing poll in the window (once, if its count
1668
+ // is not kept), a shared failure on the first and every tenth poll it
1669
+ // stops, and each other outcome once per window under a key of its
1670
+ // own.
1671
+ const heldPolls = failure === 'shared' ? this.sharedHoldPolls + 1 : transientPoll;
1672
+ // A local error (no HTTP status) raised while the task store or the
1673
+ // publication audit is failing is not this thread's fault, and that
1674
+ // failure already holds the window: report it as retried.
1675
+ const storeHeld = failure === 'permanent' &&
1676
+ typeof err.status !== 'number' &&
1677
+ (this.inboundPersistenceBlocked || this.publicationAuditBlocked);
1678
+ // A thread whose own task has not settled (an error inside its run
1679
+ // leaves it running) holds the window as well: the cursor waits for
1680
+ // that task, so the thread is read again.
1681
+ const taskHeld = !retry && !storeHeld && this.threadTaskHoldsCursor(chatId, threadId);
1682
+ const held = retry || storeHeld || taskHeld;
1683
+ const milestone = (n) => n === 1 || n % 10 === 0;
1684
+ const report = failure === 'shared'
1685
+ ? milestone(heldPolls)
1686
+ : retry
1687
+ ? counted
1688
+ ? milestone(failures)
1689
+ : this.journalOncePerWindow(`failing\0${failureKey}`)
1690
+ : this.journalOncePerWindow(`${storeHeld || taskHeld ? 'held' : stale ? 'stale' : 'skip'}\0${failureKey}`);
1691
+ if (report) {
1692
+ const error = sanitizeLogText(err instanceof Error ? err.message : String(err), 200);
1693
+ process.stderr.write(failure === 'shared'
1694
+ ? `[Channel:${this.name}] API error processing ${threadId} (rate limit or credentials), keeping notifications unread and stopping this poll: ${error}\n`
1695
+ : retry
1696
+ ? `[Channel:${this.name}] API error processing ${threadId} (${heldPolls}/${MAX_TRANSIENT_FAILURE_POLLS}), keeping it unread for the next poll: ${error}\n`
1697
+ : storeHeld
1698
+ ? `[Channel:${this.name}] error processing ${threadId} while channel state cannot be persisted, keeping it unread for the next poll: ${error}\n`
1699
+ : taskHeld
1700
+ ? `[Channel:${this.name}] error processing ${threadId} while its task is unfinished, keeping it unread for the next poll: ${error}\n`
1701
+ : `[Channel:${this.name}] API error processing ${threadId}, skipping: ${error}\n`);
1702
+ let detail;
1703
+ if (failure === 'transient' && !stale) {
1704
+ detail = retry ? { failures, heldPolls } : { failures };
1705
+ }
1706
+ else if (failure === 'shared') {
1707
+ detail = { heldPolls };
1708
+ }
1709
+ this.recordChannelEvent({
1710
+ type: 'inbound',
1711
+ outcome: held ? 'failed' : 'skipped',
1712
+ reason: 'github_api_error',
1713
+ triggerKind: reason,
1714
+ repository: chatId,
1715
+ thread: threadId,
1716
+ number: issueNumber,
1717
+ error,
1718
+ ...(detail ? { detail } : {}),
1719
+ });
1720
+ }
1721
+ // The same limit would answer every remaining thread.
1722
+ if (failure === 'shared')
1723
+ break;
1533
1724
  continue;
1534
1725
  }
1535
1726
  }
1727
+ if (transientHeld)
1728
+ this.transientHoldPolls += 1;
1729
+ if (sharedHeld)
1730
+ this.sharedHoldPolls += 1;
1536
1731
  if (reasonFilterCollapsed > 0) {
1537
1732
  // One counted row instead of a row per notification: the threads differ,
1538
1733
  // so this carries no single repository/thread, and the page renders the
@@ -1555,6 +1750,7 @@ export class GithubChannel extends PollingChannelBase {
1555
1750
  try {
1556
1751
  if (!this.inboundPersistenceBlocked &&
1557
1752
  !this.publicationAuditBlocked &&
1753
+ !this.notificationRetryPending &&
1558
1754
  !this.hasCursorBlockingTasks() &&
1559
1755
  this.pendingCursorUpdatedAt) {
1560
1756
  const committedAt = this.pendingCursorUpdatedAt;
@@ -1563,6 +1759,12 @@ export class GithubChannel extends PollingChannelBase {
1563
1759
  this.cursor.lastProcessedAt = committedAt;
1564
1760
  }
1565
1761
  this.pendingCursorUpdatedAt = undefined;
1762
+ // A new window starts: its hold budget, streaks and once-per-window
1763
+ // journal keys start again.
1764
+ this.transientHoldPolls = 0;
1765
+ this.sharedHoldPolls = 0;
1766
+ this.transientNotificationFailures.clear();
1767
+ this.windowJournalKeys.clear();
1566
1768
  }
1567
1769
  }
1568
1770
  finally {
@@ -1582,6 +1784,21 @@ export class GithubChannel extends PollingChannelBase {
1582
1784
  this.pruneCommentTimes();
1583
1785
  }
1584
1786
  }
1787
+ /**
1788
+ * True the first time `key` is seen in the current notification window (it
1789
+ * resets when the window is marked read), so a held window that re-reads the
1790
+ * same thread or comment every poll journals the repeat once.
1791
+ */
1792
+ journalOncePerWindow(key) {
1793
+ if (this.windowJournalKeys.has(key))
1794
+ return false;
1795
+ // Past the bound a new key is journaled without being remembered, so only
1796
+ // the overflow repeats instead of every key at once.
1797
+ if (this.windowJournalKeys.size < MAX_WINDOW_KEYS) {
1798
+ this.windowJournalKeys.add(key);
1799
+ }
1800
+ return true;
1801
+ }
1585
1802
  async processCommentLane(ctx, onlyMentioned, directed = false) {
1586
1803
  const comments = await this.fetchNewComments(ctx);
1587
1804
  let dispatched = false;
@@ -1589,6 +1806,8 @@ export class GithubChannel extends PollingChannelBase {
1589
1806
  const key = comment.node_id || String(comment.id);
1590
1807
  const senderId = (comment.user?.login || 'unknown').toLowerCase();
1591
1808
  if (this.cursor.dispatchedComments?.includes(key)) {
1809
+ if (!this.journalOncePerWindow(`duplicate\0${key}`))
1810
+ continue;
1592
1811
  this.recordChannelEvent({
1593
1812
  type: 'inbound',
1594
1813
  outcome: 'skipped',
@@ -1607,6 +1826,8 @@ export class GithubChannel extends PollingChannelBase {
1607
1826
  ? testBotMention(body, this.botUsername)
1608
1827
  : false;
1609
1828
  if (onlyMentioned && !hasMention) {
1829
+ if (!this.journalOncePerWindow(`mention_required\0${key}`))
1830
+ continue;
1610
1831
  this.recordChannelEvent({
1611
1832
  type: 'inbound',
1612
1833
  outcome: 'skipped',
@@ -1889,43 +2110,40 @@ export class GithubChannel extends PollingChannelBase {
1889
2110
  const bodyKey = `${chatId}|${threadId}`;
1890
2111
  if (this.cursor.dispatchedBodies?.includes(bodyKey))
1891
2112
  return;
1892
- try {
1893
- const issue = await this.fetchIssueMeta(ctx);
1894
- const body = issue.body || '';
1895
- if (issue.user?.login === this.botUsername)
1896
- return;
1897
- const isMentioned = this.botUsername
1898
- ? testBotMention(body, this.botUsername)
1899
- : false;
1900
- if (requireMention && !isMentioned)
1901
- return;
1902
- const text = this.botUsername
1903
- ? stripBotMention(body, this.botUsername)
1904
- : body;
1905
- const envelope = {
1906
- channelName: this.name,
1907
- senderId: (issue.user?.login || 'unknown').toLowerCase(),
1908
- senderName: issue.user?.login || 'unknown',
1909
- chatId,
1910
- threadId,
1911
- messageId: `issue-body-${issueNumber}`,
1912
- text,
1913
- isGroup: true,
1914
- isMentioned,
1915
- isReplyToBot: false,
1916
- metadata: this.buildRouteMetadata(ctx),
1917
- };
1918
- const dispatched = await this.dispatchEnvelope(envelope, issueNumber, {
1919
- dispatchedBodies: [bodyKey],
1920
- });
1921
- // Same contract as the direct lane: a refused dispatch (audit
1922
- // freeze) claimed no task, so the key must not be recorded.
1923
- if (dispatched) {
1924
- this.recordDispatchedBody(bodyKey);
1925
- }
1926
- }
1927
- catch (err) {
1928
- process.stderr.write(`[Channel:${this.name}] failed to fetch issue for first contact: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
2113
+ // Fetch and dispatch failures reach pollOnce, which keeps the
2114
+ // notification unread when GitHub may answer differently next poll.
2115
+ const issue = await this.fetchIssueMeta(ctx);
2116
+ const body = issue.body || '';
2117
+ if (issue.user?.login === this.botUsername)
2118
+ return;
2119
+ const isMentioned = this.botUsername
2120
+ ? testBotMention(body, this.botUsername)
2121
+ : false;
2122
+ if (requireMention && !isMentioned)
2123
+ return;
2124
+ const text = this.botUsername
2125
+ ? stripBotMention(body, this.botUsername)
2126
+ : body;
2127
+ const envelope = {
2128
+ channelName: this.name,
2129
+ senderId: (issue.user?.login || 'unknown').toLowerCase(),
2130
+ senderName: issue.user?.login || 'unknown',
2131
+ chatId,
2132
+ threadId,
2133
+ messageId: `issue-body-${issueNumber}`,
2134
+ text,
2135
+ isGroup: true,
2136
+ isMentioned,
2137
+ isReplyToBot: false,
2138
+ metadata: this.buildRouteMetadata(ctx),
2139
+ };
2140
+ const dispatched = await this.dispatchEnvelope(envelope, issueNumber, {
2141
+ dispatchedBodies: [bodyKey],
2142
+ });
2143
+ // Same contract as the direct lane: a refused dispatch (audit
2144
+ // freeze) claimed no task, so the key must not be recorded.
2145
+ if (dispatched) {
2146
+ this.recordDispatchedBody(bodyKey);
1929
2147
  }
1930
2148
  }
1931
2149
  recordDispatchedBody(key) {
@@ -2156,6 +2374,7 @@ export class GithubChannel extends PollingChannelBase {
2156
2374
  number: task.issueNumber,
2157
2375
  messageId: task.source.messageId,
2158
2376
  actor: envelope.senderId,
2377
+ ...this.boundJournalIdentity(task.delivery),
2159
2378
  });
2160
2379
  return task;
2161
2380
  }
@@ -2559,11 +2778,20 @@ export class GithubChannel extends PollingChannelBase {
2559
2778
  * they settle instead of freezing the cursor forever.
2560
2779
  */
2561
2780
  hasCursorBlockingTasks() {
2562
- return this.readInboundTasks().some((task) => this.isRecoverableInboundTask(task) &&
2781
+ return this.readInboundTasks().some((task) => this.isCursorBlockingTask(task));
2782
+ }
2783
+ isCursorBlockingTask(task) {
2784
+ return (this.isRecoverableInboundTask(task) &&
2563
2785
  task.backpressure !== true &&
2564
2786
  !(this.watchReconcileBlocked &&
2565
2787
  task.envelope?.messageId?.startsWith('watch:') === true));
2566
2788
  }
2789
+ /** Whether one of the thread's own tasks holds the cursor, as last seen. */
2790
+ threadTaskHoldsCursor(chatId, threadId) {
2791
+ return this.inboundTaskSnapshot.some((task) => task.source.chatId === chatId &&
2792
+ task.source.threadId === threadId &&
2793
+ this.isCursorBlockingTask(task));
2794
+ }
2567
2795
  /**
2568
2796
  * Terminal outcome for a bound event that can no longer be delivered:
2569
2797
  * append it to the private dead-letter log (the private path's exhaustion
@@ -2702,12 +2930,32 @@ export class GithubChannel extends PollingChannelBase {
2702
2930
  thread: task.source.threadId,
2703
2931
  number: task.issueNumber,
2704
2932
  messageId: task.source.messageId,
2933
+ // Read the delivery from the UPDATED record: a retarget or a gone
2934
+ // fallback clears it mid-run, and the journal row must name the
2935
+ // session the transition actually refers to.
2936
+ ...this.boundJournalIdentity(task.delivery),
2705
2937
  ...(updates.attempts !== undefined
2706
2938
  ? { detail: { attempts: updates.attempts } }
2707
2939
  : {}),
2708
2940
  ...(updates.error ? { error: updates.error } : {}),
2709
2941
  });
2710
2942
  }
2943
+ /**
2944
+ * Session identity for journal rows about a bound delivery, so the events
2945
+ * page can link the row to the session that received the event. The
2946
+ * binding snapshot is the only place the target's workspace is known; a
2947
+ * frozen delivery on a restored task can outlive its binding, in which
2948
+ * case the row keeps the sessionId without a workspace.
2949
+ */
2950
+ boundJournalIdentity(delivery) {
2951
+ if (delivery?.kind !== 'bound-session')
2952
+ return {};
2953
+ const workspaceCwd = this.lastBindings.find((binding) => binding.sessionId === delivery.sessionId)?.workspaceCwd;
2954
+ return {
2955
+ sessionId: delivery.sessionId,
2956
+ ...(workspaceCwd ? { sessionWorkspaceCwd: workspaceCwd } : {}),
2957
+ };
2958
+ }
2711
2959
  removeInboundTask(taskId) {
2712
2960
  this.updateInboundTasks((records) => records.filter((record) => record.id !== taskId));
2713
2961
  }
@@ -2715,6 +2963,7 @@ export class GithubChannel extends PollingChannelBase {
2715
2963
  try {
2716
2964
  const records = update(this.readInboundTasks());
2717
2965
  this.writeInboundTasks(records);
2966
+ this.inboundTaskSnapshot = records;
2718
2967
  this.recoverableInboundTasks = records.filter((record) => this.isRecoverableInboundTask(record)).length;
2719
2968
  return records;
2720
2969
  }
@@ -2732,11 +2981,14 @@ export class GithubChannel extends PollingChannelBase {
2732
2981
  if (!Array.isArray(parsed) || !parsed.every(isInboundTaskRecord)) {
2733
2982
  throw new Error('invalid GitHub inbound task state');
2734
2983
  }
2984
+ this.inboundTaskSnapshot = parsed;
2735
2985
  return parsed;
2736
2986
  }
2737
2987
  catch (err) {
2738
- if (err.code === 'ENOENT')
2988
+ if (err.code === 'ENOENT') {
2989
+ this.inboundTaskSnapshot = [];
2739
2990
  return [];
2991
+ }
2740
2992
  this.inboundPersistenceBlocked = true;
2741
2993
  process.stderr.write(`[Channel:${this.name}] failed to read GitHub inbound tasks: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 200)}\n`);
2742
2994
  throw err;
@@ -2801,6 +3053,8 @@ export class GithubChannel extends PollingChannelBase {
2801
3053
  ...(record.threadId ? { thread: record.threadId } : {}),
2802
3054
  ...(record.number !== undefined ? { number: record.number } : {}),
2803
3055
  sessionId: record.sessionId,
3056
+ // The reply session is the Channel's own, created in its workspace.
3057
+ sessionWorkspaceCwd: this.config.cwd,
2804
3058
  ...(record.sourceMessageId ? { messageId: record.sourceMessageId } : {}),
2805
3059
  ...(record.actor ? { actor: record.actor } : {}),
2806
3060
  ...(record.failureError ? { error: record.failureError } : {}),
@@ -2860,8 +3114,11 @@ export class GithubChannel extends PollingChannelBase {
2860
3114
  }
2861
3115
  async githubApi(fn, label, retries = 3, shouldRetry = () => true, signal) {
2862
3116
  for (let attempt = 1; attempt <= retries; attempt++) {
2863
- if (signal?.aborted)
2864
- throw new Error(`${label} aborted`);
3117
+ if (signal?.aborted) {
3118
+ // Thrown before this attempt was sent: callers can tell it from the
3119
+ // answer of a request that went out.
3120
+ throw Object.assign(new Error(`${label} aborted`), { notSent: true });
3121
+ }
2865
3122
  try {
2866
3123
  return await fn();
2867
3124
  }
@@ -2873,25 +3130,47 @@ export class GithubChannel extends PollingChannelBase {
2873
3130
  // Octokit RequestError: { status, response?: { headers } }
2874
3131
  const e = err;
2875
3132
  const headers = e.response?.headers ?? {};
3133
+ // A retry-after that is not a positive number of seconds (an HTTP
3134
+ // date, "0") is ignored, so the budget reset or the rate-limit
3135
+ // minimum below sets the wait instead.
3136
+ const retryAfter = Number(headers['retry-after'] ?? NaN);
3137
+ const usableRetryAfter = Number.isFinite(retryAfter) && retryAfter > 0;
3138
+ const rateLimited = isRateLimitAnswer(err);
3139
+ // GitHub answering with an exhausted budget means its window has not
3140
+ // reset yet, so a reset that looks past is clock skew: the minimum
3141
+ // below applies instead of a 1 s retry.
3142
+ const untilReset = Number(headers['x-ratelimit-reset']) * 1000 - Date.now();
2876
3143
  let cooldown;
2877
- if (headers['retry-after']) {
2878
- const retryAfter = Number(headers['retry-after']);
2879
- cooldown = Number.isFinite(retryAfter)
2880
- ? retryAfter * 1000
2881
- : 1000 * 2 ** (attempt - 1);
3144
+ if (usableRetryAfter) {
3145
+ cooldown = retryAfter * 1000;
3146
+ }
3147
+ else if (rateLimited &&
3148
+ rateLimitRemaining(err) === 0 &&
3149
+ untilReset > 0) {
3150
+ cooldown = untilReset + 1000;
2882
3151
  }
2883
- else if ((e.status === 403 || e.status === 429) &&
2884
- Number(headers['x-ratelimit-remaining']) === 0 &&
2885
- Number(headers['x-ratelimit-reset']) > 0) {
2886
- cooldown =
2887
- Math.max(0, Number(headers['x-ratelimit-reset']) * 1000 - Date.now()) + 1000;
3152
+ else if (rateLimited) {
3153
+ // GitHub's guidance for a rate limit without a usable retry-after
3154
+ // or reset: wait at least a minute, longer on each repeat.
3155
+ cooldown = 60_000 * 2 ** (attempt - 1);
2888
3156
  }
2889
3157
  else {
2890
3158
  cooldown = 1000 * 2 ** (attempt - 1);
2891
3159
  }
2892
3160
  cooldown = Math.min(cooldown, MAX_TIMER_DELAY_MS);
3161
+ // After disconnect() — which ends the wait early, skips it for a call
3162
+ // that started after the stop, or lets it run out while an in-flight
3163
+ // write defers the abort — give up with GitHub's last answer instead
3164
+ // of retrying into the same limit. A definite no-write stays
3165
+ // definite, so a final reply is kept as a pending delivery.
3166
+ const stopped = () => (usableRetryAfter || rateLimited) &&
3167
+ this.pendingFinalDeliveryRetryStopRequested;
3168
+ if (stopped())
3169
+ throw err;
2893
3170
  process.stderr.write(`[Channel:${this.name}] ${label} failed (attempt ${attempt}/${retries}, status=${e.status}), retrying in ${cooldown}ms: ${sanitizeLogText(e.message ?? String(err), 200)}\n`);
2894
3171
  await this.sleepForRetry(cooldown, signal);
3172
+ if (stopped())
3173
+ throw err;
2895
3174
  }
2896
3175
  }
2897
3176
  throw new Error('unreachable');