@qwen-code/channel-github 0.27.4 → 0.28.1-preview.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.
@@ -0,0 +1,983 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Qwen Team
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import { setTimeout as delay } from 'node:timers/promises';
7
+ import { MANAGED_OUTBOUND_LIMIT, resolvePrivatePolicy, } from '@qwen-code/channel-base';
8
+ import { DISPATCHED_COMMENTS_LIMIT, MANAGED_GITHUB_PENDING_LIMIT, ManagedGithubStateStore, } from './managed-state.js';
9
+ import { isDefinitiveGithubReadFailure } from './managed-github-deps.js';
10
+ import { testBotMention } from './mention.js';
11
+ const CLAIM_BATCH = 16;
12
+ const DEFAULT_POLL_INTERVAL = 60_000;
13
+ const MIN_POLL_INTERVAL = 1_000;
14
+ const MAX_POLL_INTERVAL = 86_400_000;
15
+ const GITHUB_EVENT_PREFIX = 'github:';
16
+ const INSTANCE_SCOPED_REFUSALS = new Set([
17
+ 'workspace_not_found',
18
+ 'workspace_forbidden',
19
+ 'actor_scope_mismatch',
20
+ 'workspace_unavailable',
21
+ ]);
22
+ const INSTANCE_REFUSAL_DROP_LIMIT = 1;
23
+ const CHANNEL_NOT_FOUND = 'channel_not_found';
24
+ // The wire's text bound (the control plane's Jakarta @Size) and the Harness
25
+ // envelope's byte line, mirrored locally to keep this package free of core
26
+ // imports. Both match the DingTalk reference adapter's clamp.
27
+ const MAX_WIRE_TEXT_CHARS = 32_000;
28
+ const ENVELOPE_BYTE_LIMIT = 64 * 1024;
29
+ const TEXT_ENVELOPE_OVERHEAD_BYTES = 4096;
30
+ // The wire's subject bound (InboundEventRequest.subject @Size(max = 200)).
31
+ const MAX_SUBJECT_CHARS = 200;
32
+ export function githubSettings(config) {
33
+ if (config['useLocalGh'] === true) {
34
+ // The gh CLI login is a machine-level identity; a tenant-scoped managed
35
+ // deployment authenticates with its own token.
36
+ throw new Error('The managed GitHub path does not support useLocalGh; configure a token.');
37
+ }
38
+ const token = config['token'];
39
+ if (!validCredential(token))
40
+ throw new Error('GitHub channel requires a token.');
41
+ const rawBaseUrl = config['baseUrl'];
42
+ const baseUrlRaw = typeof rawBaseUrl === 'string' && rawBaseUrl.trim()
43
+ ? rawBaseUrl.trim()
44
+ : 'https://api.github.com';
45
+ let parsedBase;
46
+ try {
47
+ parsedBase = new URL(baseUrlRaw);
48
+ }
49
+ catch {
50
+ throw new Error('GitHub channel baseUrl is not a valid URL.');
51
+ }
52
+ // WHATWG parses a scheme-less "host:port/path" with an empty hostname and a
53
+ // bogus protocol; it would fail identity resolution as "unknown scheme"
54
+ // behind the token-pointing message. Require an absolute http(s) URL.
55
+ if (!/^https?:$/.test(parsedBase.protocol) || !parsedBase.hostname) {
56
+ throw new Error('GitHub channel baseUrl must be an absolute http(s) URL with a host.');
57
+ }
58
+ // Normalize before the state-directory hash: trailing slash and host case
59
+ // are the same endpoint and must key one state directory, not two owners.
60
+ const baseUrl = `${parsedBase.origin}${parsedBase.pathname.replace(/\/+$/, '')}`;
61
+ const rawInterval = config['pollInterval'];
62
+ const pollInterval = Number(rawInterval ?? DEFAULT_POLL_INTERVAL);
63
+ const intervalAccepted = Number.isSafeInteger(pollInterval) &&
64
+ pollInterval >= MIN_POLL_INTERVAL &&
65
+ pollInterval <= MAX_POLL_INTERVAL;
66
+ const rawRepoFilter = config['repoFilter'];
67
+ const repoFilterMode = config['repoFilterMode'];
68
+ let repoFilter;
69
+ // The plugin descriptor defaults repoFilterMode to 'off' and the Web Shell
70
+ // editor seeds 'off' on save, so 'off' — and a blocklist with no list — must
71
+ // start as "no repository filtering", not be refused. Only the invertible
72
+ // and fail-open shapes are refused.
73
+ if (repoFilterMode === 'blocklist' && rawRepoFilter !== undefined) {
74
+ // A blocklist excludes the listed repos; reading it as an allowlist would
75
+ // answer only in the repos the operator blocked. The managed path cannot
76
+ // carry a blocklist, so refuse the invertible shape rather than guess.
77
+ throw new Error("The managed GitHub path supports repoFilter only as an allowlist; a blocklist with a repoFilter list would invert the operator's intent.");
78
+ }
79
+ if (rawRepoFilter !== undefined && repoFilterMode === undefined) {
80
+ // Legacy reads a list with no mode as "filter off"; promoting it to an
81
+ // active allowlist would answer only inside the parked repos. Require the
82
+ // explicit managed spelling instead of guessing.
83
+ throw new Error('GitHub channel repoFilter requires repoFilterMode "allowlist" on the managed path.');
84
+ }
85
+ if (repoFilterMode === 'allowlist') {
86
+ if (rawRepoFilter === undefined) {
87
+ // Declaring an allowlist without a list must not fail open to every repo.
88
+ throw new Error('GitHub channel repoFilterMode "allowlist" requires a non-empty repoFilter array.');
89
+ }
90
+ if (!Array.isArray(rawRepoFilter) ||
91
+ rawRepoFilter.length === 0 ||
92
+ !rawRepoFilter.every((entry) => typeof entry === 'string' &&
93
+ REPOSITORY_FULL_NAME_RE.test(entry.trim()))) {
94
+ // An empty or malformed allowlist would silently drop every event
95
+ // while the adapter reports running (the Legacy validator refuses both
96
+ // for the same reason).
97
+ throw new Error('GitHub channel repoFilter must be a non-empty array of owner/repo strings.');
98
+ }
99
+ repoFilter = rawRepoFilter.map((entry) => entry.trim().toLowerCase());
100
+ }
101
+ // 'off' (the plugin/editor default) and a blocklist without a list leave
102
+ // repoFilter undefined — no repository filtering, nothing to invert.
103
+ return {
104
+ token: token.trim(),
105
+ baseUrl,
106
+ pollInterval: intervalAccepted ? pollInterval : DEFAULT_POLL_INTERVAL,
107
+ pollIntervalRewritten: rawInterval !== undefined && !intervalAccepted,
108
+ repoFilter,
109
+ };
110
+ }
111
+ // Mirror the email/DingTalk credential rule: a copy-paste trailing newline or
112
+ // an embedded CR/LF/NUL must be rejected, not passed through to the API where
113
+ // it surfaces as an auth error pointing at the credential.
114
+ function validCredential(value) {
115
+ return typeof value === 'string' && !!value.trim() && !/[\r\n\0]/.test(value);
116
+ }
117
+ // The Legacy repository full-name shape (GithubAdapter.ts
118
+ // REPOSITORY_FULL_NAME_RE): owner/repo, no whitespace or path separators.
119
+ const REPOSITORY_FULL_NAME_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
120
+ // The Legacy adapter's subject-URL mechanics: one repo + issue/PR number is
121
+ // one chat_thread route. chatId is lowercased like the Legacy group id.
122
+ function extractSubjectUrl(url) {
123
+ const match = url.match(/\/repos\/([^/]+)\/([^/]+)\/(issues|pulls)\/(\d+)/);
124
+ if (!match)
125
+ return null;
126
+ const owner = match[1];
127
+ const repo = match[2];
128
+ const kind = match[3] === 'pulls' ? 'pr' : 'issue';
129
+ const issueNumber = Number(match[4]);
130
+ return {
131
+ chatId: `${owner}/${repo}`.toLowerCase(),
132
+ threadId: `${kind}:${issueNumber}`,
133
+ owner,
134
+ repo,
135
+ issueNumber,
136
+ };
137
+ }
138
+ export class ManagedGithubAdapter {
139
+ settings;
140
+ policy;
141
+ store;
142
+ controlPlane;
143
+ deps;
144
+ log;
145
+ pollLoop;
146
+ state;
147
+ client;
148
+ accountId;
149
+ startedAt;
150
+ releaseLock;
151
+ running = false;
152
+ ownershipLost = false;
153
+ loop;
154
+ abort;
155
+ registeredGeneration;
156
+ instanceStalled = false;
157
+ loggedNoClaimSlot = false;
158
+ loggedSettleFailure = false;
159
+ constructor(options) {
160
+ this.settings = githubSettings(options.config);
161
+ const config = options.config;
162
+ // parseChannelConfig always injects privatePolicy/senderPolicy/groupPolicy
163
+ // defaults into `config`, so an operator's explicit policy choice must be
164
+ // judged on the raw pre-parse entry, not the fully-defaulted parse result.
165
+ const raw = options.rawConfig ?? config;
166
+ const groupPolicy = raw['groupPolicy'];
167
+ if (groupPolicy === 'pairing') {
168
+ // Same "skip every comment while reporting running" hazard as
169
+ // privatePolicy pairing: the managed policy shape has no pairing arm.
170
+ throw new Error('The managed GitHub path does not support groupPolicy "pairing"; use allowedUsers or groupPolicy "open"/"disabled".');
171
+ }
172
+ const groups = config['groups'];
173
+ if (groups &&
174
+ typeof groups === 'object' &&
175
+ Object.keys(groups).length > 0) {
176
+ // Per-repo sender lists cannot be represented by the flat managed
177
+ // policy; silently dropping them would admit senders the operator
178
+ // excluded (or drop ones they allowed).
179
+ throw new Error('The managed GitHub path does not support per-repo "groups"; configure allowedUsers instead.');
180
+ }
181
+ let senderPolicy = resolvePrivatePolicy(config);
182
+ if (senderPolicy === 'pairing') {
183
+ // The managed policy shape has no pairing arm; silently coercing it to
184
+ // an empty allowlist would skip every comment while reporting running.
185
+ throw new Error('The managed GitHub path does not support privatePolicy "pairing"; use allowedUsers, open, or disabled.');
186
+ }
187
+ // The plugin's own schema documents groupPolicy as the GitHub admission
188
+ // gate. Honor an active groupPolicy when the operator did not explicitly
189
+ // choose a managed policy in the RAW entry: a channel configured
190
+ // groupPolicy "open" must not resolve to an empty allowlist and silently
191
+ // consume every mention. Absence is judged on `raw`, not `config` —
192
+ // parseChannelConfig injects privatePolicy/senderPolicy into config for
193
+ // every channel, so a config-based guard would be dead on the production
194
+ // path. groupPolicy "disabled" (the parse default when absent) stays inert
195
+ // — keep the managed resolvePrivatePolicy result — rather than clobber an
196
+ // allowedUsers allowlist into admit-nothing.
197
+ if (raw['privatePolicy'] === undefined &&
198
+ raw['senderPolicy'] === undefined &&
199
+ groupPolicy !== undefined) {
200
+ if (groupPolicy === 'open' || groupPolicy === 'allowlist') {
201
+ senderPolicy = groupPolicy;
202
+ }
203
+ else if (groupPolicy !== 'disabled') {
204
+ throw new Error('GitHub channel groupPolicy must be one of: allowlist, open, disabled.');
205
+ }
206
+ }
207
+ const allowed = config['allowedUsers'];
208
+ this.policy = {
209
+ adapter: 'github',
210
+ senderPolicy: senderPolicy === 'disabled' || senderPolicy === 'open'
211
+ ? senderPolicy
212
+ : 'allowlist',
213
+ allowedSenders: Array.isArray(allowed)
214
+ ? allowed
215
+ .filter((entry) => typeof entry === 'string')
216
+ .map((entry) => entry.trim().toLowerCase())
217
+ : [],
218
+ dispatchMode: config['dispatchMode'] === 'steer' ? 'steer' : 'followup',
219
+ };
220
+ this.store = new ManagedGithubStateStore(options.name, options.cwd, this.settings.baseUrl);
221
+ this.controlPlane = options.controlPlane;
222
+ this.deps = options.deps;
223
+ this.log =
224
+ options.deps.log ?? ((line) => process.stderr.write(`${line}\n`));
225
+ if (this.settings.pollIntervalRewritten) {
226
+ this.log(`Managed GitHub pollInterval ${String(options.config['pollInterval'])} is not an integer in [${MIN_POLL_INTERVAL}, ${MAX_POLL_INTERVAL}]; using ${this.settings.pollInterval} ms.`);
227
+ }
228
+ this.pollLoop = options.pollLoop ?? true;
229
+ }
230
+ get stateFile() {
231
+ return this.store.file;
232
+ }
233
+ get generation() {
234
+ return this.state?.generation;
235
+ }
236
+ async connect() {
237
+ if (this.running || this.releaseLock)
238
+ throw new Error('Managed GitHub adapter is already connected.');
239
+ try {
240
+ this.releaseLock = await this.deps.lock(this.store.directory, () => {
241
+ // A reaped stale lock means a second owner won the state directory.
242
+ // Stop, and stop persisting: an in-flight tick or the shutdown drain
243
+ // must not rewrite the file the new owner now holds.
244
+ this.ownershipLost = true;
245
+ this.log('Managed GitHub state ownership was lost to another process; adapter stopped.');
246
+ this.stop();
247
+ });
248
+ }
249
+ catch {
250
+ throw new Error('GitHub state is owned by another process; managed adapter not started.');
251
+ }
252
+ try {
253
+ this.state = this.store.load() ?? {
254
+ version: 1,
255
+ generation: 1,
256
+ cursor: { lastProcessedAt: null, dispatchedComments: [] },
257
+ pending: [],
258
+ outbound: [],
259
+ };
260
+ if (this.state.pending.some((entry) => entry.held)) {
261
+ this.instanceStalled = true;
262
+ this.state.instanceRefusals = Math.max(this.state.instanceRefusals ?? 0, INSTANCE_REFUSAL_DROP_LIMIT + 1);
263
+ }
264
+ this.persist();
265
+ this.abort = new AbortController();
266
+ this.running = true;
267
+ this.loggedNoClaimSlot = false;
268
+ this.registeredGeneration = undefined;
269
+ this.client = await this.deps.createClient(this.settings);
270
+ // The first identity failure must surface: a bad token creates no
271
+ // usable client, and swallowing it would report a healthy start that
272
+ // is permanently deaf. The deps redact the credential from the error.
273
+ this.accountId = await this.client.resolveIdentity();
274
+ if (!this.running)
275
+ throw new Error('Managed GitHub adapter stopped during connection.');
276
+ await this.ensureRegistered(this.state);
277
+ await this.reportOrphanedOutbound();
278
+ // A lock compromise can land during the awaits above. Re-check so
279
+ // connect() rejects rather than resolving a healthy-looking start for
280
+ // a stopped, deaf adapter the CLI would then park on.
281
+ if (!this.running || this.ownershipLost)
282
+ throw new Error('Managed GitHub adapter stopped during connection.');
283
+ // The first window starts at connect time: no historical backlog.
284
+ this.startedAt = new Date((this.deps.now ?? Date.now)()).toISOString();
285
+ if (this.pollLoop)
286
+ this.loop = this.runLoop();
287
+ }
288
+ catch (error) {
289
+ this.stop();
290
+ await this.release();
291
+ throw error;
292
+ }
293
+ }
294
+ async disconnect() {
295
+ this.stop();
296
+ await this.loop;
297
+ await this.controlPlane.disconnect().catch(() => undefined);
298
+ await this.release();
299
+ }
300
+ /** One admission re-drive, one inbound poll and one outbound pull. */
301
+ async tick() {
302
+ await this.ensureRegistered(this.state);
303
+ await this.resubmitPending();
304
+ await this.pollInbound();
305
+ await this.reportOrphanedOutbound();
306
+ await this.pullOutbox();
307
+ }
308
+ async runLoop() {
309
+ try {
310
+ while (this.running) {
311
+ try {
312
+ await this.tick();
313
+ }
314
+ catch (error) {
315
+ this.log(`Managed GitHub tick failed: ${String(error)}`);
316
+ }
317
+ if (this.running) {
318
+ const floor = this.client?.pollIntervalFloorMs() ?? 0;
319
+ await delay(Math.max(this.settings.pollInterval, floor), undefined, {
320
+ signal: this.abort.signal,
321
+ }).catch(() => { });
322
+ }
323
+ }
324
+ }
325
+ finally {
326
+ this.stop();
327
+ }
328
+ }
329
+ senderAllowed(sender) {
330
+ switch (this.policy.senderPolicy) {
331
+ case 'disabled':
332
+ return false;
333
+ case 'open':
334
+ return true;
335
+ default:
336
+ return this.policy.allowedSenders.includes(sender);
337
+ }
338
+ }
339
+ repoAllowed(chatId) {
340
+ return (!this.settings.repoFilter || this.settings.repoFilter.includes(chatId));
341
+ }
342
+ async pollInbound() {
343
+ const state = this.state;
344
+ if (!this.running || this.instanceStalled || !this.client)
345
+ return;
346
+ if (state.pending.length >= MANAGED_GITHUB_PENDING_LIMIT) {
347
+ if (!this.loggedNoClaimSlot) {
348
+ this.loggedNoClaimSlot = true;
349
+ this.log('Managed GitHub has no durable claim slot; the inbound poll waits for pending admissions to settle.');
350
+ }
351
+ return;
352
+ }
353
+ this.loggedNoClaimSlot = false;
354
+ // The watermark steps back one second because GitHub timestamps are
355
+ // second-granular; the overlap is absorbed by the dispatched ring and,
356
+ // ultimately, by the control plane's platformEventId idempotency.
357
+ const since = state.cursor.lastProcessedAt
358
+ ? new Date(Date.parse(state.cursor.lastProcessedAt) - 1000).toISOString()
359
+ : this.startedAt;
360
+ let notifications;
361
+ try {
362
+ notifications = await this.client.listNotifications(since);
363
+ }
364
+ catch (error) {
365
+ // A failed read holds the window; the next poll re-lists it.
366
+ this.log(`Managed GitHub notification poll failed: ${String(error)}`);
367
+ return;
368
+ }
369
+ const kept = notifications.filter((notification) => {
370
+ if (notification.reason !== 'mention')
371
+ return false;
372
+ const type = notification.subject.type;
373
+ if (type !== 'Issue' && type !== 'PullRequest')
374
+ return false;
375
+ const target = extractSubjectUrl(notification.subject.url ?? '');
376
+ return !!target && this.repoAllowed(target.chatId);
377
+ });
378
+ // A thread whose comments cannot be read, whose collection was cut short
379
+ // by the claim cap, or whose mark-read fails freezes the whole window:
380
+ // the watermark advances only on a complete pass, and a thread is marked
381
+ // read only when every comment it produced was fully collected.
382
+ let windowComplete = true;
383
+ const processedThreads = new Set();
384
+ const droppedThreads = new Set();
385
+ for (const notification of kept) {
386
+ if (!this.running)
387
+ return;
388
+ if (state.pending.length >= MANAGED_GITHUB_PENDING_LIMIT)
389
+ break;
390
+ const target = extractSubjectUrl(notification.subject.url ?? '');
391
+ let comments;
392
+ try {
393
+ comments = await this.client.listComments(target.owner, target.repo, target.issueNumber, since);
394
+ }
395
+ catch (error) {
396
+ if (isDefinitiveGithubReadFailure(error)) {
397
+ // Poison escape: a deleted or inaccessible thread answers the same
398
+ // refusal forever; without this it freezes the watermark for the
399
+ // life of the channel. Drop it visibly — its mentions are
400
+ // unrecoverable — and skip its mark-read (which would also fail).
401
+ droppedThreads.add(notification.id);
402
+ this.log(`Managed GitHub drops unreadable thread ${target.chatId}#${target.issueNumber}: ${String(error)}`);
403
+ continue;
404
+ }
405
+ windowComplete = false;
406
+ this.log(`Managed GitHub could not read comments for ${target.chatId}#${target.issueNumber}: ${String(error)}`);
407
+ continue;
408
+ }
409
+ let capped = false;
410
+ for (const comment of comments) {
411
+ if (state.pending.length >= MANAGED_GITHUB_PENDING_LIMIT) {
412
+ capped = true;
413
+ break;
414
+ }
415
+ const login = comment.user?.login;
416
+ const body = comment.body;
417
+ if (!login || !body || !body.trim())
418
+ continue;
419
+ if (login.toLowerCase() === this.accountId.toLowerCase())
420
+ continue;
421
+ if (!testBotMention(body, this.accountId))
422
+ continue;
423
+ // node_id is globally unique; the numeric id fallback is only unique
424
+ // per repo, so scope it by thread — two repos' comment #555 must stay
425
+ // two platform events, not one replayed away.
426
+ const key = comment.node_id ??
427
+ `${target.chatId}/${target.threadId}/${comment.id}`;
428
+ const eventId = `${GITHUB_EVENT_PREFIX}${key}`;
429
+ if (state.cursor.dispatchedComments.includes(key) ||
430
+ state.pending.some((entry) => entry.eventId === eventId)) {
431
+ continue;
432
+ }
433
+ const senderId = login.toLowerCase();
434
+ if (!this.senderAllowed(senderId)) {
435
+ this.log(`Managed GitHub sender ${senderId} is not allowed; comment ${key} skipped.`);
436
+ this.recordDispatched(key);
437
+ try {
438
+ this.persist();
439
+ }
440
+ catch (error) {
441
+ // The skip is already applied in memory; disk keeps no claim, so a
442
+ // restart re-lists the comment and skips it again. Never abort the
443
+ // poll over the failed write.
444
+ this.log(`Managed GitHub could not persist the sender skip of ${key}: ${persistErrorText(error)}; a restart re-lists and skips it again.`);
445
+ }
446
+ continue;
447
+ }
448
+ const event = {
449
+ accountGeneration: state.generation,
450
+ platformEventId: eventId,
451
+ semanticRevision: 1,
452
+ scope: {
453
+ kind: 'chat_thread',
454
+ senderId: null,
455
+ chatId: target.chatId,
456
+ threadId: target.threadId,
457
+ },
458
+ senderId,
459
+ chatId: target.chatId,
460
+ threadId: target.threadId,
461
+ subject: fitSubject(notification.subject.title),
462
+ text: fitInboundText(body),
463
+ attachments: [],
464
+ replyContext: {
465
+ owner: target.owner,
466
+ repo: target.repo,
467
+ issueNumber: target.issueNumber,
468
+ senderId,
469
+ },
470
+ };
471
+ const previousPending = state.pending;
472
+ state.pending = [
473
+ ...state.pending,
474
+ { eventId, event, notificationThreadId: notification.id },
475
+ ].slice(-MANAGED_GITHUB_PENDING_LIMIT);
476
+ try {
477
+ this.persist();
478
+ }
479
+ catch (error) {
480
+ // A failed save must not leave the claim in memory: the dedupe arm
481
+ // would then skip a re-listed comment for a claim the store never
482
+ // accepted. Roll back so the next poll re-stages it.
483
+ state.pending = previousPending;
484
+ throw error;
485
+ }
486
+ }
487
+ // A capped collection leaves comments uncollected: marking this thread
488
+ // read would consume notifications whose mentions were never staged.
489
+ if (!capped)
490
+ processedThreads.add(notification.id);
491
+ }
492
+ await this.resubmitPending();
493
+ // Mark a thread read only after every event it produced has left pending
494
+ // (admitted, replayed or visibly dropped). A thread still holding a claim
495
+ // keeps the window frozen so the next poll re-drives it.
496
+ const heldThreads = new Set(state.pending.map((entry) => entry.notificationThreadId));
497
+ for (const notification of kept) {
498
+ if (!this.running)
499
+ return;
500
+ if (droppedThreads.has(notification.id))
501
+ continue;
502
+ if (!processedThreads.has(notification.id)) {
503
+ windowComplete = false;
504
+ continue;
505
+ }
506
+ if (heldThreads.has(notification.id)) {
507
+ windowComplete = false;
508
+ continue;
509
+ }
510
+ try {
511
+ await this.client.markThreadRead(notification.id);
512
+ }
513
+ catch (error) {
514
+ windowComplete = false;
515
+ this.log(`Managed GitHub could not mark notification ${notification.id} read: ${String(error)}; the window holds.`);
516
+ }
517
+ }
518
+ if (windowComplete && notifications.length > 0) {
519
+ let watermark = state.cursor.lastProcessedAt;
520
+ // The outer windowComplete was already evaluated to enter this block;
521
+ // a local flag is what actually gates the persist below.
522
+ let unparseable = false;
523
+ for (const notification of notifications) {
524
+ const updated = Date.parse(notification.updated_at);
525
+ if (Number.isNaN(updated)) {
526
+ // Persisting an unparseable watermark would throw RangeError on
527
+ // every later tick's since computation and fail load() on restart.
528
+ // Hold the window instead; outbound keeps moving.
529
+ unparseable = true;
530
+ this.log(`Managed GitHub notification ${notification.id} has an unparseable updated_at; the window holds.`);
531
+ continue;
532
+ }
533
+ if (!watermark || updated > Date.parse(watermark)) {
534
+ watermark = notification.updated_at;
535
+ }
536
+ }
537
+ if (!unparseable &&
538
+ watermark &&
539
+ watermark !== state.cursor.lastProcessedAt) {
540
+ state.cursor.lastProcessedAt = watermark;
541
+ this.persist();
542
+ }
543
+ }
544
+ }
545
+ recordDispatched(key) {
546
+ const state = this.state;
547
+ if (!state.cursor.dispatchedComments.includes(key)) {
548
+ state.cursor.dispatchedComments = [
549
+ ...state.cursor.dispatchedComments,
550
+ key,
551
+ ].slice(-DISPATCHED_COMMENTS_LIMIT);
552
+ }
553
+ }
554
+ async submit(eventId, event) {
555
+ const state = this.state;
556
+ try {
557
+ const admitted = await this.controlPlane.submitInbound(event);
558
+ const wasHeld = state.pending.some((entry) => entry.eventId === eventId && entry.held === true);
559
+ const previousPending = state.pending;
560
+ const previousDispatched = state.cursor.dispatchedComments;
561
+ const previousRefusals = state.instanceRefusals;
562
+ const previousStalled = this.instanceStalled;
563
+ state.pending = state.pending.filter((entry) => entry.eventId !== eventId);
564
+ this.recordDispatched(eventId.slice(GITHUB_EVENT_PREFIX.length));
565
+ if (!admitted.replayed && wasHeld) {
566
+ state.instanceRefusals = 0;
567
+ this.instanceStalled = false;
568
+ }
569
+ else {
570
+ this.liftStallWhenNothingHeld();
571
+ }
572
+ try {
573
+ this.persist();
574
+ this.loggedSettleFailure = false;
575
+ }
576
+ catch (error) {
577
+ // The admission answer arrived but the settle never reached disk.
578
+ // Roll back everything the settle touched so the next tick re-drives
579
+ // the identical event into the idempotent replayed answer; a
580
+ // half-settled memory state would drop the claim from this process's
581
+ // re-drive while disk still holds it (the DingTalk discipline).
582
+ state.pending = previousPending;
583
+ state.cursor.dispatchedComments = previousDispatched;
584
+ state.instanceRefusals = previousRefusals;
585
+ this.instanceStalled = previousStalled;
586
+ // Latched: the rollback keeps the claim pending, so every tick
587
+ // re-drives it and an unlatched line would re-log per claim per tick.
588
+ if (!this.loggedSettleFailure) {
589
+ this.loggedSettleFailure = true;
590
+ this.log(`Managed GitHub could not persist the admission of ${eventId}: ${persistErrorText(error)}; it re-drives on the next tick.`);
591
+ }
592
+ return;
593
+ }
594
+ }
595
+ catch (error) {
596
+ const status = error.status;
597
+ const code = error.code;
598
+ if (this.isRegistrationRefusal(error)) {
599
+ this.registeredGeneration = 0;
600
+ return;
601
+ }
602
+ if (typeof status === 'number' &&
603
+ (status === 400 ||
604
+ status === 403 ||
605
+ status === 409 ||
606
+ (status === 404 && INSTANCE_SCOPED_REFUSALS.has(String(code))))) {
607
+ if (INSTANCE_SCOPED_REFUSALS.has(String(code))) {
608
+ state.instanceRefusals = (state.instanceRefusals ?? 0) + 1;
609
+ const entry = state.pending.find((p) => p.eventId === eventId);
610
+ if (entry?.held ||
611
+ state.instanceRefusals > INSTANCE_REFUSAL_DROP_LIMIT) {
612
+ if (!entry?.held) {
613
+ state.pending = state.pending.map((p) => p.eventId === eventId ? { ...p, held: true } : p);
614
+ try {
615
+ this.persist();
616
+ }
617
+ catch (error) {
618
+ // The hold stays armed in memory for this process; a restart
619
+ // before the write lands re-arms it after one refusal, which
620
+ // is the bounded first-occurrence tradeoff, never a loss.
621
+ this.log(`Managed GitHub could not persist the held claim ${eventId}: ${persistErrorText(error)}; the stall stays armed in memory.`);
622
+ }
623
+ }
624
+ if (!this.instanceStalled) {
625
+ this.instanceStalled = true;
626
+ this.log(`Managed GitHub stopped admitting: every comment is refused with ${status} ${String(code)}; check the instance's --workspace and --actor flags.`);
627
+ }
628
+ return;
629
+ }
630
+ }
631
+ this.log(`Managed GitHub admission of ${eventId} was refused (${status}); the comment is skipped.`);
632
+ state.pending = state.pending.filter((p) => p.eventId !== eventId);
633
+ this.recordDispatched(eventId.slice(GITHUB_EVENT_PREFIX.length));
634
+ this.liftStallWhenNothingHeld();
635
+ try {
636
+ this.persist();
637
+ }
638
+ catch (error) {
639
+ // The drop is already applied in memory; disk keeps the claim, so a
640
+ // restart re-drives it into the same deterministic refusal and drops
641
+ // it again. Never abort the batch over the failed write.
642
+ this.log(`Managed GitHub could not persist the refused admission of ${eventId}: ${persistErrorText(error)}; a restart re-drives it into the same refusal.`);
643
+ }
644
+ return;
645
+ }
646
+ // A lost answer or a transient refusal: the claim, with its persisted
647
+ // event, stays in pending so the next tick re-drives the identical
648
+ // event, never a rebuilt one.
649
+ }
650
+ }
651
+ /**
652
+ * The stall exists to be lifted by the held claim's probe: when the last
653
+ * held claim leaves without proving the binding, no probe remains, and a
654
+ * flag kept armed would gate every later tick. The refusal streak is NOT
655
+ * reset here: only the held claim's fresh admission proves the binding.
656
+ */
657
+ liftStallWhenNothingHeld() {
658
+ if (this.instanceStalled &&
659
+ !this.state.pending.some((entry) => entry.held === true)) {
660
+ this.instanceStalled = false;
661
+ this.log('Managed GitHub admission resumed; no claim remains held, and the refusal streak still stands for the next instance-scoped refusal.');
662
+ }
663
+ }
664
+ async resubmitPending() {
665
+ const state = this.state;
666
+ if (!state)
667
+ return;
668
+ // Probe held claims first: the stall lifts only on a held claim's fresh
669
+ // admission, and push order lets an earlier claim whose answer never
670
+ // comes shadow the one probe per tick. The sort is stable.
671
+ const ordered = [...state.pending].sort((a, b) => Number(b.held === true) - Number(a.held === true));
672
+ for (const entry of ordered) {
673
+ if (!this.running)
674
+ return;
675
+ if (!this.senderAllowed(entry.event.senderId) ||
676
+ !this.repoAllowed(entry.event.chatId)) {
677
+ // The policy moved on since the claim: the persisted event drops
678
+ // visibly rather than drive a Session the current policy forbids.
679
+ // The repo allowlist gets the same re-check as the sender policy —
680
+ // a claim staged under a wider filter must not post into a repo the
681
+ // operator has since excluded.
682
+ this.log(`Managed GitHub event ${entry.eventId} is refused by the current sender policy or repo allowlist; its claim drops.`);
683
+ state.pending = state.pending.filter((p) => p.eventId !== entry.eventId);
684
+ this.recordDispatched(entry.eventId.slice(GITHUB_EVENT_PREFIX.length));
685
+ this.liftStallWhenNothingHeld();
686
+ try {
687
+ this.persist();
688
+ }
689
+ catch (error) {
690
+ // Same shape as the refusal drop: memory applied, disk keeps the
691
+ // claim, a restart re-drives it into the same policy refusal.
692
+ this.log(`Managed GitHub could not persist the policy drop of ${entry.eventId}: ${persistErrorText(error)}; a restart re-drives it into the same refusal.`);
693
+ }
694
+ continue;
695
+ }
696
+ await this.submit(entry.eventId, entry.event);
697
+ if (this.registeredGeneration === 0 || this.instanceStalled)
698
+ return;
699
+ }
700
+ }
701
+ isRegistrationRefusal(error) {
702
+ const status = error.status;
703
+ const code = error.code;
704
+ return ((status === 404 && String(code) === CHANNEL_NOT_FOUND) ||
705
+ (status === 409 &&
706
+ (code === 'channel_generation_unregistered' ||
707
+ code === 'channel_disconnected')));
708
+ }
709
+ async ensureRegistered(state) {
710
+ if (this.registeredGeneration === state.generation)
711
+ return;
712
+ try {
713
+ await this.controlPlane.register({
714
+ platform: 'github',
715
+ accountId: this.accountId,
716
+ accountGeneration: state.generation,
717
+ policy: this.policy,
718
+ });
719
+ this.registeredGeneration = state.generation;
720
+ }
721
+ catch (error) {
722
+ this.registeredGeneration = 0;
723
+ throw error;
724
+ }
725
+ }
726
+ async pullOutbox() {
727
+ // Guard before the claim, not in the per-delivery loop: the claim itself
728
+ // moves up to CLAIM_BATCH deliveries to sending server-side, so a stop
729
+ // that lands mid-tick must not claim a batch it would then abandon.
730
+ if (!this.running || !this.state)
731
+ return;
732
+ let claimed;
733
+ try {
734
+ claimed = await this.controlPlane.claimDeliveries(CLAIM_BATCH);
735
+ }
736
+ catch (error) {
737
+ if (this.isRegistrationRefusal(error)) {
738
+ this.registeredGeneration = 0;
739
+ return;
740
+ }
741
+ throw error;
742
+ }
743
+ for (const delivery of claimed) {
744
+ if (!this.running)
745
+ return;
746
+ await this.send(delivery);
747
+ }
748
+ }
749
+ async send(delivery) {
750
+ const state = this.state;
751
+ const context = delivery.replyContext;
752
+ const owner = context?.owner;
753
+ const repo = context?.repo;
754
+ const issueNumber = context?.issueNumber;
755
+ const chatId = typeof owner === 'string' && typeof repo === 'string'
756
+ ? `${owner}/${repo}`.toLowerCase()
757
+ : '';
758
+ if (typeof owner !== 'string' ||
759
+ !owner ||
760
+ typeof repo !== 'string' ||
761
+ !repo ||
762
+ !Number.isSafeInteger(issueNumber) ||
763
+ issueNumber < 1 ||
764
+ // Re-check the current policy before posting, mirroring the DingTalk /
765
+ // email send-time re-check: a sender or repo the operator has since
766
+ // excluded must not receive the reply even though it was admitted.
767
+ !this.senderAllowed(context?.senderId ?? '') ||
768
+ !this.repoAllowed(chatId)) {
769
+ // One delivery's unreportable rejection receipt must never abort the
770
+ // claimed batch: the deliveries behind it were already moved to sending
771
+ // server-side and would settle unknown (lost) if the tick escaped here.
772
+ try {
773
+ await this.controlPlane.receipt(delivery.deliveryId, {
774
+ outcome: 'rejected',
775
+ });
776
+ }
777
+ catch (error) {
778
+ if (this.isRegistrationRefusal(error)) {
779
+ this.registeredGeneration = 0;
780
+ return;
781
+ }
782
+ this.log(`Managed GitHub rejection receipt for ${delivery.deliveryId} could not be reported (${String(error)}); the rest of the batch still sends.`);
783
+ }
784
+ return;
785
+ }
786
+ for (const segment of delivery.segments) {
787
+ if (!this.running)
788
+ return;
789
+ const previousOutbound = state.outbound;
790
+ state.outbound = [
791
+ ...state.outbound,
792
+ { deliveryId: delivery.deliveryId, ordinal: segment.ordinal },
793
+ ].slice(-MANAGED_OUTBOUND_LIMIT);
794
+ try {
795
+ this.persist();
796
+ }
797
+ catch (error) {
798
+ // The ledger entry is the double-send guard: without it on disk, a
799
+ // crash after the comment post would re-send on restart. Roll back
800
+ // and abandon this delivery before the side effect; the lease
801
+ // reconciler settles it unknown (the DingTalk discipline).
802
+ state.outbound = previousOutbound;
803
+ this.log(`Managed GitHub could not persist the outbound ledger for ${delivery.deliveryId}: ${persistErrorText(error)}; the send is abandoned and the lease reconciler settles it.`);
804
+ return;
805
+ }
806
+ let outcome;
807
+ try {
808
+ // One ledger segment is one comment: the producer's 48 KiB UTF-8
809
+ // segment cap is below GitHub's 65,536-character body cap, so no
810
+ // provider-side chunking exists here.
811
+ const posted = await this.client.postComment(owner, repo, issueNumber, segment.text);
812
+ outcome = {
813
+ outcome: 'accepted',
814
+ ordinal: segment.ordinal,
815
+ providerMessageId: String(posted.id),
816
+ acceptedAt: (this.deps.now ?? Date.now)(),
817
+ };
818
+ }
819
+ catch (error) {
820
+ const definitive = error.definitive;
821
+ outcome = definitive ? { outcome: 'rejected' } : { outcome: 'unknown' };
822
+ }
823
+ const entry = state.outbound.find((candidate) => candidate.deliveryId === delivery.deliveryId &&
824
+ candidate.ordinal === segment.ordinal);
825
+ if (entry)
826
+ entry.receipt = outcome;
827
+ try {
828
+ this.persist();
829
+ }
830
+ catch (error) {
831
+ // The send already happened: report the outcome to the control plane
832
+ // even if the local write failed — the server-side settle is the
833
+ // durable record, and the orphan re-drive replays the in-memory
834
+ // receipt until the local write lands (the DingTalk discipline).
835
+ this.log(`Managed GitHub could not persist the receipt for ${delivery.deliveryId}: ${persistErrorText(error)}; it is still reported and re-driven locally.`);
836
+ }
837
+ try {
838
+ await this.controlPlane.receipt(delivery.deliveryId, outcome);
839
+ }
840
+ catch (error) {
841
+ // One delivery's unreportable receipt never aborts the claimed
842
+ // batch: the entry stays outbound with the outcome persisted, so
843
+ // every later tick re-drives exactly this receipt — never the send.
844
+ this.log(`Managed GitHub receipt for ${delivery.deliveryId} could not be reported (${String(error)}); it re-drives on the next tick.`);
845
+ return;
846
+ }
847
+ state.outbound = state.outbound.filter((candidate) => !(candidate.deliveryId === delivery.deliveryId &&
848
+ candidate.ordinal === segment.ordinal));
849
+ try {
850
+ this.persist();
851
+ }
852
+ catch (error) {
853
+ // The receipt is already reported; disk keeps the entry, so the next
854
+ // tick's orphan re-drive replays the receipt and removes it again.
855
+ this.log(`Managed GitHub could not persist the settled segment of ${delivery.deliveryId}: ${persistErrorText(error)}; the orphan re-drive removes it on the next tick.`);
856
+ }
857
+ if (outcome.outcome !== 'accepted')
858
+ return;
859
+ }
860
+ }
861
+ async reportOrphanedOutbound() {
862
+ const state = this.state;
863
+ if (!state)
864
+ return;
865
+ for (const entry of [...state.outbound]) {
866
+ if (!this.running)
867
+ return;
868
+ // A segment whose send produced a persisted receipt replays that
869
+ // receipt — the control plane may already hold it (its answer was
870
+ // lost) and settles idempotently. Only a segment whose send never
871
+ // produced an outcome settles unknown.
872
+ try {
873
+ await this.controlPlane.receipt(entry.deliveryId, entry.receipt ?? { outcome: 'unknown' });
874
+ }
875
+ catch (error) {
876
+ const status = error.status;
877
+ const code = error.code;
878
+ if (this.isRegistrationRefusal(error)) {
879
+ this.registeredGeneration = 0;
880
+ this.log(`Managed GitHub receipt for ${entry.deliveryId} was refused as not registered (${String(status)} ${String(code)}); it re-drives after the next tick re-registers.`);
881
+ return;
882
+ }
883
+ // A deterministic refusal never converges on re-drive, and a held
884
+ // entry runs before every outbox pull: it would stall every later
885
+ // delivery. Drop it visibly; the lease reconciler records the
886
+ // delivery unknown.
887
+ if (!(status === 400 ||
888
+ status === 403 ||
889
+ status === 409 ||
890
+ (status === 404 && code === 'delivery_not_found'))) {
891
+ throw error;
892
+ }
893
+ this.log(`Managed GitHub receipt for ${entry.deliveryId} was refused (${String(status)}); it is dropped.`);
894
+ }
895
+ state.outbound = state.outbound.filter((candidate) => candidate !== entry);
896
+ try {
897
+ this.persist();
898
+ }
899
+ catch (error) {
900
+ // Disk keeps the entry; the next tick replays the same idempotent
901
+ // receipt and retries the removal. Never abort the remaining orphans.
902
+ this.log(`Managed GitHub could not persist the orphan removal of ${entry.deliveryId}: ${persistErrorText(error)}; it re-drives on the next tick.`);
903
+ }
904
+ }
905
+ }
906
+ persist() {
907
+ // Once the lock is compromised the state file belongs to another process;
908
+ // never rewrite it, even from an in-flight tick's post-await persist.
909
+ if (this.ownershipLost)
910
+ return;
911
+ if (this.state)
912
+ this.store.save(this.state);
913
+ }
914
+ stop() {
915
+ this.running = false;
916
+ this.abort?.abort();
917
+ try {
918
+ this.client?.disconnect();
919
+ }
920
+ catch {
921
+ // The client may already be closed; stopping is best-effort.
922
+ }
923
+ }
924
+ async release() {
925
+ const releaseLock = this.releaseLock;
926
+ this.releaseLock = undefined;
927
+ if (releaseLock)
928
+ await releaseLock().catch(() => undefined);
929
+ }
930
+ }
931
+ // The store rethrows a fixed sentence (the state file may hold platform data)
932
+ // but preserves the fs error on `cause`. Log the cause so ENOSPC, EACCES and a
933
+ // read-only directory are diagnosable instead of hidden behind the sentence.
934
+ // Mirrors the DingTalk adapter's persistErrorText.
935
+ function persistErrorText(error) {
936
+ return String(error.cause ?? error);
937
+ }
938
+ function fitSubject(title) {
939
+ if (!title)
940
+ return null;
941
+ let bounded = title.slice(0, MAX_SUBJECT_CHARS);
942
+ if (/[\uD800-\uDBFF]$/.test(bounded))
943
+ bounded = bounded.slice(0, -1);
944
+ return bounded;
945
+ }
946
+ /**
947
+ * The wire admits at most MAX_WIRE_TEXT_CHARS characters and the Harness
948
+ * envelope at most ENVELOPE_BYTE_LIMIT bytes of event JSON. Clamp to both so
949
+ * an over-long comment is admitted truncated instead of meeting a
950
+ * deterministic 400 and being dropped whole. Copied from the DingTalk
951
+ * adapter's clamp (managed-dingtalk-adapter.ts), not email's raw-UTF-8
952
+ * budget: a CJK comment can sit under the character line yet overflow the
953
+ * byte envelope, and escape-heavy text inflates the JSON-serialized length.
954
+ */
955
+ function fitInboundText(text) {
956
+ // The cap counts UTF-16 units (the server's maxTextChars does too), so a
957
+ // code-point cap could overshoot it; but a UTF-16 slice can land inside a
958
+ // surrogate pair, so back off a trailing high surrogate to keep the text
959
+ // well-formed.
960
+ let bounded = text.slice(0, MAX_WIRE_TEXT_CHARS);
961
+ if (/[\uD800-\uDBFF]$/.test(bounded))
962
+ bounded = bounded.slice(0, -1);
963
+ const byteLimit = ENVELOPE_BYTE_LIMIT - TEXT_ENVELOPE_OVERHEAD_BYTES;
964
+ // The bound is enforced on the JSON-serialized envelope, where a control
965
+ // character costs six bytes and a quote/backslash two — not on the raw
966
+ // UTF-8 length. Budget the escaped length and cut by code points until it
967
+ // fits.
968
+ const encodedBytes = (s) => Buffer.byteLength(JSON.stringify(s), 'utf8') - 2;
969
+ if (encodedBytes(bounded) <= byteLimit)
970
+ return bounded;
971
+ const chars = Array.from(bounded);
972
+ let lo = 0;
973
+ let hi = chars.length;
974
+ while (lo < hi) {
975
+ const mid = Math.ceil((lo + hi) / 2);
976
+ if (encodedBytes(chars.slice(0, mid).join('')) <= byteLimit)
977
+ lo = mid;
978
+ else
979
+ hi = mid - 1;
980
+ }
981
+ return chars.slice(0, lo).join('');
982
+ }
983
+ //# sourceMappingURL=managed-github-adapter.js.map