opencode-azure-devops-pr-review 0.4.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +72 -0
- package/README.md +42 -24
- package/package.json +1 -1
- package/src/attribution.mjs +2 -0
- package/src/azure.mjs +19 -13
- package/src/diagnostics.mjs +1 -0
- package/src/host.mjs +13 -5
- package/src/review-tools.mjs +4 -3
- package/src/runtime.mjs +301 -45
- package/src/session.mjs +69 -16
- package/src/store.mjs +94 -25
package/src/runtime.mjs
CHANGED
|
@@ -27,7 +27,7 @@ import { API_VERSION, createAzureClient, fetchTransport, pemCertificates, proxyL
|
|
|
27
27
|
import { REVIEW_TOOL_NAMES, reviewToolDefinitions, runReviewTool } from './review-tools.mjs';
|
|
28
28
|
import { runReview } from './review-work.mjs';
|
|
29
29
|
import { createReviewStore, createReviewWrites, stateRoot, REVIEW_LIMIT } from './store.mjs';
|
|
30
|
-
import { PROGRESS_EVENT_TYPES, TESTED_HOST_VERSION, USED_UP_LIMITS, fetchTransportSupported, hostCapabilities, listOf, packageNamed, pluginEntries, pluginSourceLabel, recordOf, requireMethods, sessionProgress, tokenUsage, usageTotals, withoutCredentials } from './host.mjs';
|
|
30
|
+
import { PROGRESS_EVENT_TYPES, TESTED_HOST_VERSION, USED_UP_LIMITS, fetchTransportSupported, hostCapabilities, isSessionNotFound, listOf, packageNamed, pluginEntries, pluginSourceLabel, recordOf, requireMethods, sessionProgress, tokenUsage, usageTotals, withoutCredentials } from './host.mjs';
|
|
31
31
|
import {
|
|
32
32
|
reviewProvenance, provenanceReport, commentAttribution, renderFinalReport, renderCommentActions,
|
|
33
33
|
renderIncompleteDraft, renderReceipt, renderDiagnosticNotices, renderCheckReport, renderPublication, describeReview,
|
|
@@ -119,6 +119,27 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
|
|
|
119
119
|
const sourceRuns = new Map(); // origin session -> active run ID
|
|
120
120
|
const completed = new Map(); // review ID -> completed review (persisted)
|
|
121
121
|
const commentLocks = new Set(); // PR targets with an active comment command
|
|
122
|
+
const closing = new Set(); // private sessions about to be deleted, or whose deletion OpenCode never answered
|
|
123
|
+
const answering = new Map(); // sessions a command still owes a notice, until its last one is out (counted)
|
|
124
|
+
const settling = new Map(); // reviews and unfinished runs a command is still finishing with: not evicted meanwhile (counted)
|
|
125
|
+
const createdEarlier = new Set(); // private sessions an earlier process created: those of saved reviews and of the session records
|
|
126
|
+
let expiring = Promise.resolve(); // the passes over sessions that are due to go, one after another
|
|
127
|
+
let expiringNext = false; // a pass is waiting for its turn: it covers what later callers ask for
|
|
128
|
+
// Count one more holder of `key`; the returned function gives it up, once.
|
|
129
|
+
const hold = (holders, key) => {
|
|
130
|
+
holders.set(key, (holders.get(key) ?? 0) + 1);
|
|
131
|
+
let held = true;
|
|
132
|
+
return () => {
|
|
133
|
+
if (!held) return;
|
|
134
|
+
held = false;
|
|
135
|
+
const others = holders.get(key) - 1;
|
|
136
|
+
if (others > 0) holders.set(key, others); else holders.delete(key);
|
|
137
|
+
};
|
|
138
|
+
};
|
|
139
|
+
// Sessions a command still needs: the one it answers in, until its last notice is out, and while its run is
|
|
140
|
+
// active the run's conversation, the session its notices go to and its stages' sessions.
|
|
141
|
+
const sessionsInUse = () => new Set([...answering.keys(),
|
|
142
|
+
...[...runs.values()].flatMap(run => [run.origin, run.notifySession, ...run.stages.map(stage => stage.sessionID)])]);
|
|
122
143
|
const openStores = new Map(); // data directory -> store promise
|
|
123
144
|
const jobs = new Set();
|
|
124
145
|
const registrations = [];
|
|
@@ -159,12 +180,16 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
|
|
|
159
180
|
// An unwritable state directory must not disable the plugin: fall back to a
|
|
160
181
|
// per-user directory under the system temporary directory.
|
|
161
182
|
let storeFallback;
|
|
162
|
-
|
|
183
|
+
// An evicted review takes its sessions with it, before its record goes; what cannot be deleted then is recorded
|
|
184
|
+
// as still to be deleted.
|
|
185
|
+
const onRemove = review => discardSessions([...review.reportSessions, ...(review.closingSessions ?? [])], review.id);
|
|
163
186
|
const store = await createReviewStore({ root: options.stateDirectory ?? stateRoot(), onRemove }).catch(error => {
|
|
164
187
|
storeFallback = errorText(error);
|
|
165
188
|
return createReviewStore({ root: join(tmpdir(), `azpr-v2-state-${process.getuid?.() ?? 'user'}`), onRemove });
|
|
166
189
|
});
|
|
167
190
|
const capabilities = hostCapabilities(context);
|
|
191
|
+
// Whether AZPR deletes its private sessions at all: the setting, and a host that can.
|
|
192
|
+
const deletesSessions = Boolean(settings.deletePrivateSessions && capabilities.sessionRemove);
|
|
168
193
|
// When reviews were completed and last used decides which one a command without an ID acts on,
|
|
169
194
|
// so these times never repeat or run backwards, whatever the clock does: each is later than every
|
|
170
195
|
// one issued in this process or saved by an earlier one.
|
|
@@ -177,9 +202,20 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
|
|
|
177
202
|
for (const review of await store.load().catch(() => [])) {
|
|
178
203
|
completed.set(review.id, review);
|
|
179
204
|
savedUse.set(review.id, review.usedAt);
|
|
205
|
+
// A deletion an earlier process asked for and never saw answered may still be carried out.
|
|
206
|
+
for (const sessionID of review.closingSessions ?? []) closing.add(sessionID);
|
|
207
|
+
// The sessions an earlier process created stay private sessions, also once their review is evicted.
|
|
208
|
+
for (const sessionID of [...review.reportSessions, ...(review.closingSessions ?? [])]) createdEarlier.add(sessionID);
|
|
180
209
|
for (const time of [review.completedAt, review.usedAt]) if (Number.isFinite(Date.parse(time))) lastStamp = Math.max(lastStamp, Date.parse(time));
|
|
181
210
|
}
|
|
211
|
+
// So do the sessions the records name: kept from unfinished runs, or still to be deleted. The latter take no
|
|
212
|
+
// commands either: a deletion may have been asked for and never answered.
|
|
213
|
+
const recorded = await store.recordedSessions().catch(() => ({ kept: [], due: [] }));
|
|
214
|
+
for (const sessionID of [...recorded.kept, ...recorded.due]) createdEarlier.add(sessionID);
|
|
215
|
+
for (const sessionID of recorded.due) closing.add(sessionID);
|
|
182
216
|
void store.sweep().catch(() => {});
|
|
217
|
+
// What an earlier process could not delete is tried again now.
|
|
218
|
+
void releaseExpired();
|
|
183
219
|
|
|
184
220
|
// ---------------------------------------------------------------- helpers
|
|
185
221
|
// OpenCode lists these next to the command names on one line and cuts what does not fit (a user's
|
|
@@ -351,46 +387,203 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
|
|
|
351
387
|
owner.data = undefined;
|
|
352
388
|
}
|
|
353
389
|
/**
|
|
354
|
-
*
|
|
355
|
-
*
|
|
356
|
-
*
|
|
390
|
+
* Whether OpenCode may still have the session: false only when OpenCode says
|
|
391
|
+
* it does not exist. A read that fails otherwise settles nothing, so the
|
|
392
|
+
* session stays on record.
|
|
393
|
+
*/
|
|
394
|
+
async function sessionExists(sessionID) {
|
|
395
|
+
try { await deadline(() => context.session.get({ sessionID }), options.removeTimeoutMs ?? 5000); return true; }
|
|
396
|
+
catch (error) { return !isSessionNotFound(error); }
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* Delete AZPR's own reviewer sessions, a few at a time so a host that stalls
|
|
400
|
+
* on deletion delays the receipt by one timeout per batch, not per session.
|
|
401
|
+
* A session a command needs is left alone, checked when its turn comes.
|
|
402
|
+
* Returns the sessions that are not known to be gone, for a caller that can
|
|
403
|
+
* try again later: `left` are still there (needed by a command, or OpenCode
|
|
404
|
+
* refused the deletion of a session it still has), `unanswered` are those
|
|
405
|
+
* whose deletion OpenCode had not answered when this process stopped
|
|
406
|
+
* waiting, so it may still be carried out.
|
|
357
407
|
*/
|
|
358
408
|
async function removeSessions(sessionIDs) {
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
const pending = [...
|
|
409
|
+
const requested = [...new Set(sessionIDs ?? [])];
|
|
410
|
+
if (!deletesSessions) return { left: requested, unanswered: [] };
|
|
411
|
+
const pending = [...requested], left = [], unanswered = [];
|
|
362
412
|
const worker = async () => {
|
|
363
413
|
while (pending.length) {
|
|
364
414
|
const sessionID = pending.shift();
|
|
365
|
-
|
|
415
|
+
if (sessionsInUse().has(sessionID)) { left.push(sessionID); continue; }
|
|
416
|
+
let answered = false;
|
|
417
|
+
const removal = Promise.resolve().then(() => context.session.remove({ sessionID })).finally(() => { answered = true; });
|
|
418
|
+
try { await deadline(() => removal, options.removeTimeoutMs ?? 5000); }
|
|
419
|
+
catch (error) {
|
|
420
|
+
if (!answered) unanswered.push(sessionID);
|
|
421
|
+
// A session that is gone already needs no further attempt; OpenCode says so here, or when it is read.
|
|
422
|
+
else if (!isSessionNotFound(error) && await sessionExists(sessionID)) left.push(sessionID);
|
|
423
|
+
}
|
|
366
424
|
}
|
|
367
425
|
};
|
|
368
426
|
await Promise.all(Array.from({ length: Math.min(SESSION_REMOVALS, pending.length) }, worker));
|
|
427
|
+
return { left, unanswered };
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* Delete sessions that no review or run keeps any more. From here on they
|
|
431
|
+
* are private sessions that take no commands, until they are gone. A session
|
|
432
|
+
* leaves the records only when it is gone: what could not be deleted (a
|
|
433
|
+
* command needs it, OpenCode refused, or never answered) is recorded under
|
|
434
|
+
* `id` as still to be deleted, which every later pass tries again.
|
|
435
|
+
* `unrecorded` sessions are on no record yet, so they are recorded before
|
|
436
|
+
* the attempt. Returns false when sessions that are still there could not be
|
|
437
|
+
* recorded.
|
|
438
|
+
*/
|
|
439
|
+
async function discardSessions(sessionIDs, id = randomUUID().slice(0, 8), unrecorded = false) {
|
|
440
|
+
if (!deletesSessions) return true;
|
|
441
|
+
const due = [...new Set(sessionIDs ?? [])];
|
|
442
|
+
for (const sessionID of due) closing.add(sessionID);
|
|
443
|
+
if (unrecorded) await store.retrySessions(id, due).catch(() => {});
|
|
444
|
+
const { left, unanswered } = await removeSessions(due);
|
|
445
|
+
for (const sessionID of due) if (!left.includes(sessionID) && !unanswered.includes(sessionID)) closing.delete(sessionID);
|
|
446
|
+
return store.retrySessions(id, [...left, ...unanswered]).then(() => true, () => !left.length && !unanswered.length);
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* One pass over the sessions that are due to go: those that could not be
|
|
450
|
+
* deleted earlier, tried again every time, and those kept from unfinished
|
|
451
|
+
* runs beyond the limit, except runs whose command has not ended. Passes
|
|
452
|
+
* run one after another, after a review or an unfinished run and at load,
|
|
453
|
+
* and in the background: no receipt waits for an earlier failure to be
|
|
454
|
+
* tried again. A pass reads the records when its turn comes, so one that
|
|
455
|
+
* waits serves every caller until then, and a host that is slow to delete
|
|
456
|
+
* never has more than one pass waiting. A pass never fails; the next one
|
|
457
|
+
* tries what it left. Where sessions are not deleted at all, the records
|
|
458
|
+
* are left as they are.
|
|
459
|
+
*/
|
|
460
|
+
function releaseExpired() {
|
|
461
|
+
const pass = async () => {
|
|
462
|
+
expiringNext = false;
|
|
463
|
+
try {
|
|
464
|
+
for (const due of await store.expiredSessions(id => settling.has(id))) {
|
|
465
|
+
// A kept record goes once its sessions are deleted, or recorded as still to be deleted.
|
|
466
|
+
if (await discardSessions(due.sessionIDs, due.runId) && due.kept) await store.keepSessions(due.runId, []);
|
|
467
|
+
}
|
|
468
|
+
} catch { /* The next pass tries again. */ }
|
|
469
|
+
};
|
|
470
|
+
if (deletesSessions && !expiringNext) { expiringNext = true; expiring = expiring.then(pass); }
|
|
471
|
+
return expiring;
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* The sessions of a run that ended, and those to delete now. OpenCode lists
|
|
475
|
+
* every private session like a conversation of its own, so only `keep` (the
|
|
476
|
+
* session holding the run's report or draft) stays; all stay while debugging,
|
|
477
|
+
* after an unconfirmed abort, or where sessions are not deleted at all.
|
|
478
|
+
*/
|
|
479
|
+
function endedSessions(run, keep) {
|
|
480
|
+
const sessions = [...new Set(run.stages.map(stage => stage.sessionID).filter(Boolean))];
|
|
481
|
+
const prune = deletesSessions && !settings.debug.enabled && !run.abortUnconfirmed;
|
|
482
|
+
return { sessions, obsolete: prune ? sessions.filter(id => id !== keep) : [] };
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* Delete a run's obsolete sessions, which are closed to commands already
|
|
486
|
+
* (`closing`): a command typed in one is refused, since its answer would have
|
|
487
|
+
* nowhere to go. Counts the deleted ones for the receipt and returns the
|
|
488
|
+
* others: `left` are still there, `unanswered` are those whose deletion
|
|
489
|
+
* OpenCode never answered and may still carry out. The caller decides which
|
|
490
|
+
* of them stay closed.
|
|
491
|
+
*/
|
|
492
|
+
async function deleteClosing(run, obsolete) {
|
|
493
|
+
const outcome = await removeSessions(obsolete);
|
|
494
|
+
run.sessionsRemoved = obsolete.length - outcome.left.length - outcome.unanswered.length;
|
|
495
|
+
return outcome;
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* A review run that saved no review. Its sessions go on record before any is
|
|
499
|
+
* deleted: those the run keeps on purpose on its own record, which follows
|
|
500
|
+
* the review limit, and those to delete apart, as still to be deleted. A
|
|
501
|
+
* process that ends during the cleanup therefore forgets none of them, and
|
|
502
|
+
* the next one knows which are still to go. What should be gone and is not
|
|
503
|
+
* stays on that record, tried again at every pass and closed to commands
|
|
504
|
+
* meanwhile. Until the command has ended (`output.release`, given up by
|
|
505
|
+
* `launch`) later runs do not evict the run's own record, since its draft
|
|
506
|
+
* session would go with it, and no pass takes on the sessions this cleanup
|
|
507
|
+
* is deleting.
|
|
508
|
+
*/
|
|
509
|
+
async function releaseUnfinished(run, output) {
|
|
510
|
+
if (!deletesSessions) return;
|
|
511
|
+
const { sessions, obsolete } = endedSessions(run, run.reportStage?.sessionID);
|
|
512
|
+
if (sessions.length) {
|
|
513
|
+
const kept = sessions.filter(id => !obsolete.includes(id));
|
|
514
|
+
for (const id of obsolete) closing.add(id);
|
|
515
|
+
(output.release ??= []).push(hold(settling, run.id));
|
|
516
|
+
// Every session in one write first, so that no moment leaves one of them unrecorded; then those to delete
|
|
517
|
+
// apart, and the run's own record with what it keeps. Where they cannot be recorded apart, the run's own
|
|
518
|
+
// record goes on naming them.
|
|
519
|
+
await store.keepSessions(run.id, sessions).catch(() => {});
|
|
520
|
+
const apart = !obsolete.length || await store.retrySessions(run.id, obsolete).then(() => true, () => false);
|
|
521
|
+
if (apart && obsolete.length) await store.keepSessions(run.id, kept).catch(() => {});
|
|
522
|
+
if (obsolete.length) {
|
|
523
|
+
const { left, unanswered } = await deleteClosing(run, obsolete);
|
|
524
|
+
const survivors = [...left, ...unanswered];
|
|
525
|
+
for (const id of obsolete) if (!survivors.includes(id)) closing.delete(id);
|
|
526
|
+
if (apart) await store.retrySessions(run.id, survivors).catch(() => {});
|
|
527
|
+
else await store.keepSessions(run.id, [...kept, ...survivors]).catch(() => {});
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
// Also after a run that created no session: what an earlier cleanup could not delete is tried again.
|
|
531
|
+
void releaseExpired();
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* A run of a saved review ended: what to do with its sessions, decided before
|
|
535
|
+
* anything is awaited. The review's record takes them all; those to delete
|
|
536
|
+
* now go on it apart, as `closingSessions`, and are closed to commands from
|
|
537
|
+
* here on. Only `keep` stays a session of the review, the one holding its
|
|
538
|
+
* report; a comment run keeps none, since its receipt carries its result.
|
|
539
|
+
* The caller saves the record before `finishCleanup` deletes anything, so a
|
|
540
|
+
* process that ends during the cleanup forgets no session, and the next one
|
|
541
|
+
* knows which of them may be gone or may still go. Returns the sessions to
|
|
542
|
+
* delete.
|
|
543
|
+
*/
|
|
544
|
+
function scheduleCleanup(run, review, keep) {
|
|
545
|
+
const { sessions, obsolete } = endedSessions(run, keep);
|
|
546
|
+
for (const id of sessions) if (!obsolete.includes(id)) review.reportSessions.add(id);
|
|
547
|
+
for (const id of obsolete) {
|
|
548
|
+
review.reportSessions.delete(id);
|
|
549
|
+
(review.closingSessions ??= new Set()).add(id);
|
|
550
|
+
closing.add(id);
|
|
551
|
+
}
|
|
552
|
+
return obsolete;
|
|
369
553
|
}
|
|
370
554
|
/**
|
|
371
|
-
*
|
|
372
|
-
*
|
|
373
|
-
*
|
|
555
|
+
* Delete what `scheduleCleanup` chose, after the record was saved. A session
|
|
556
|
+
* OpenCode confirms as deleted leaves the record. One that is still there (a
|
|
557
|
+
* command needed it, or OpenCode refused) is one of the review's own again.
|
|
558
|
+
* One whose deletion was never answered stays among `closingSessions`, only
|
|
559
|
+
* to be deleted with the review. Returns whether the record changed.
|
|
374
560
|
*/
|
|
375
|
-
async function
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
const
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
561
|
+
async function finishCleanup(run, review, obsolete) {
|
|
562
|
+
if (!obsolete.length) return false;
|
|
563
|
+
const { left, unanswered } = await deleteClosing(run, obsolete);
|
|
564
|
+
for (const id of obsolete) {
|
|
565
|
+
if (unanswered.includes(id)) continue;
|
|
566
|
+
review.closingSessions?.delete(id);
|
|
567
|
+
closing.delete(id);
|
|
568
|
+
if (left.includes(id)) review.reportSessions.add(id);
|
|
569
|
+
}
|
|
570
|
+
if (!review.closingSessions?.size) delete review.closingSessions;
|
|
571
|
+
return obsolete.length > unanswered.length;
|
|
382
572
|
}
|
|
383
573
|
// One write of a review's record, queued behind the writes of that review before it. `value` is
|
|
384
574
|
// the review or a copy with changes not yet applied to it, and is read when the write starts.
|
|
385
575
|
function writeReview(review, value = () => review) {
|
|
386
576
|
return writes.write(review.id, async () => {
|
|
577
|
+
// An evicted review is gone: a save queued behind its removal must not bring its record back.
|
|
578
|
+
if (completed.get(review.id) !== review) throw new Error('The review is no longer kept.');
|
|
387
579
|
const record = value(), used = record.usedAt;
|
|
388
580
|
await store.save(record);
|
|
389
581
|
savedUse.set(review.id, used);
|
|
390
582
|
});
|
|
391
583
|
}
|
|
584
|
+
/** Save the review; false when it could not be saved. */
|
|
392
585
|
async function persistReview(review) {
|
|
393
|
-
try { await writeReview(review); } catch { review.persistFailed = true; }
|
|
586
|
+
try { await writeReview(review); return true; } catch { review.persistFailed = true; return false; }
|
|
394
587
|
}
|
|
395
588
|
// A review a person adjusted is posted only from a saved preview: one that cannot be saved is
|
|
396
589
|
// dropped, also in this process, so that a restart never finds another state than this one.
|
|
@@ -401,19 +594,31 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
|
|
|
401
594
|
throw new Error(`[AZPR] The new preview of review ${review.id} could not be saved (${errorText(error)}); it was dropped, so nothing can be posted from it.`);
|
|
402
595
|
}
|
|
403
596
|
}
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
597
|
+
// A review a command is working on is not evicted: its run, a comment run's last steps or the cleanup of its
|
|
598
|
+
// sessions. Nor is one whose session a running command needs, since evicting it would delete that session.
|
|
599
|
+
const reviewInUse = id => {
|
|
600
|
+
if (settling.has(id) || commenting.has(id) || [...runs.values()].some(active => active.review?.id === id)) return true;
|
|
601
|
+
const sessions = completed.get(id)?.reportSessions, needed = sessionsInUse();
|
|
602
|
+
return Boolean(sessions) && [...sessions].some(sessionID => needed.has(sessionID));
|
|
603
|
+
};
|
|
604
|
+
/** Evict the oldest reviews beyond the limit, in this process and on disk, except those in use. */
|
|
605
|
+
async function evictReviews() {
|
|
407
606
|
const ordered = [...completed.values()].sort((a, b) => String(a.completedAt).localeCompare(String(b.completedAt)));
|
|
408
607
|
for (const old of ordered.slice(0, Math.max(0, ordered.length - REVIEW_LIMIT))) {
|
|
409
|
-
if (
|
|
608
|
+
if (reviewInUse(old.id)) continue;
|
|
410
609
|
completed.delete(old.id);
|
|
411
610
|
if (old.dataDirectory) openStores.delete(old.dataDirectory);
|
|
412
611
|
// Behind any write of the record still under way, so none can bring the file back.
|
|
413
612
|
await writes.write(old.id, () => store.remove(old)).catch(() => {});
|
|
414
613
|
old.data = undefined;
|
|
415
614
|
}
|
|
416
|
-
await store.enforceLimit().catch(() => {});
|
|
615
|
+
await store.enforceLimit(reviewInUse).catch(() => {});
|
|
616
|
+
}
|
|
617
|
+
/** Keep a completed review, evicting the oldest ones beyond the limit. */
|
|
618
|
+
async function rememberReview(review) {
|
|
619
|
+
completed.set(review.id, review);
|
|
620
|
+
await persistReview(review);
|
|
621
|
+
await evictReviews();
|
|
417
622
|
}
|
|
418
623
|
|
|
419
624
|
// ----------------------------------------------------- cancellation
|
|
@@ -560,7 +765,11 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
|
|
|
560
765
|
if (spec.mode !== run.profile) throw new Error('[AZPR] Reviewer profile mismatch before invocation.');
|
|
561
766
|
const idModel = stageModel(settings, role);
|
|
562
767
|
const title = `[AZPR ${run.id}] ${spec.label}${label ? ` ${label}` : ''}${attempt > 1 ? ` (attempt ${attempt})` : ''}`;
|
|
563
|
-
|
|
768
|
+
// Marks the session as AZPR's: its run, role and conversation, and for a comment run the review it acts on.
|
|
769
|
+
const metadata = { azpr: { run: run.id, role, conversation: run.origin, ...(run.review ? { review: run.review.id } : {}) } };
|
|
770
|
+
const made = await bounded(() => createReviewSession(context, { origin: run.origin, title, role, model: modelRef(idModel), metadata, signal,
|
|
771
|
+
// Created after its stage was cancelled: no stage knows this session, so it is deleted here.
|
|
772
|
+
onLate: late => { seenSessions.add(late.id); void discardSessions([late.id], undefined, true); } }), signal);
|
|
564
773
|
if (!text(made.id) || made.id === run.origin || seenSessions.has(made.id)) throw new Error('SDK did not return a new independent session.');
|
|
565
774
|
seenSessions.add(made.id);
|
|
566
775
|
watch.waiting = false;
|
|
@@ -615,6 +824,7 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
|
|
|
615
824
|
record.hostContinuations = (record.hostContinuations ?? 0) + answer.continuation.count;
|
|
616
825
|
if (answer.continuation.restartedAt) record.continuationRestarts = (record.continuationRestarts ?? 0) + 1;
|
|
617
826
|
}
|
|
827
|
+
if (answer.retriedSteps) record.hostStepRetries = (record.hostStepRetries ?? 0) + answer.retriedSteps;
|
|
618
828
|
evaluation = await handler.evaluate(answerText, evaluation?.result, session);
|
|
619
829
|
const budget = turn < settings.workflow.repairAttempts;
|
|
620
830
|
if (evaluation.issues?.length && evaluation.repairPrompt && budget) {
|
|
@@ -740,7 +950,7 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
|
|
|
740
950
|
if (sourceRuns.has(details.origin) || (details.lockKey && commentLocks.has(details.lockKey))) {
|
|
741
951
|
throw Object.assign(new Error('[AZPR] A review/comment command is already running for this conversation or PR.'), { busy: true });
|
|
742
952
|
}
|
|
743
|
-
requireMethods(context, ['session.create', 'session.prompt', 'session.wait', 'session.context', 'session.interrupt', 'session.synthetic'], 'the review workflow');
|
|
953
|
+
requireMethods(context, ['session.create', 'session.get', 'session.prompt', 'session.wait', 'session.context', 'session.interrupt', 'session.synthetic'], 'the review workflow');
|
|
744
954
|
let id; do { id = randomUUID().slice(0, 8); } while (runs.has(id) || completed.has(id));
|
|
745
955
|
const run = { ...details, id, active: true, controller: new AbortController(), stages: [], toolText: new Map(),
|
|
746
956
|
deadlineAt: settings.runTimeoutSeconds === null ? null : Date.now() + settings.runTimeoutSeconds * 1000 };
|
|
@@ -876,7 +1086,11 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
|
|
|
876
1086
|
}
|
|
877
1087
|
|
|
878
1088
|
async function executeReview(mode, input, output, dispatch) {
|
|
879
|
-
|
|
1089
|
+
// Also after a restart, when this process no longer knows the sessions it created: the saved reviews and the
|
|
1090
|
+
// records of unfinished runs name them.
|
|
1091
|
+
if (seenSessions.has(input.sessionID) || createdEarlier.has(input.sessionID)) {
|
|
1092
|
+
throw new Error('[AZPR] Start a new review from your ordinary development session, not a reviewer session.');
|
|
1093
|
+
}
|
|
880
1094
|
if (!text(input.sessionID) || !text(input.arguments) || input.arguments.length > 16000) {
|
|
881
1095
|
throw new Error(`[AZPR] Usage: /${input.command} <Azure PR URL>${mode === 'check' ? '' : ' [--preview|--publish|--no-comment]'} [your context]`);
|
|
882
1096
|
}
|
|
@@ -920,8 +1134,23 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
|
|
|
920
1134
|
}
|
|
921
1135
|
return { status: final.status, report: rendered, review: completedReview };
|
|
922
1136
|
}, dispatch);
|
|
923
|
-
if (status === 'COMPLETE' && review)
|
|
924
|
-
|
|
1137
|
+
if (status === 'COMPLETE' && review) {
|
|
1138
|
+
// Not evicted until this command has ended, with its receipt delivered and the comment step it hands on
|
|
1139
|
+
// done: an eviction in between would bring the record back with the cleanup's save, or take the report
|
|
1140
|
+
// session and the review's data from under the receipt and that step. `launch` gives the hold up.
|
|
1141
|
+
(output.release ??= []).push(hold(settling, review.id));
|
|
1142
|
+
// The save that keeps the review names the sessions about to be deleted. A save that fails does not stop
|
|
1143
|
+
// the cleanup: sessions left without a record would be forgotten just the same.
|
|
1144
|
+
const obsolete = scheduleCleanup(run, review, run.reportStage?.sessionID);
|
|
1145
|
+
await rememberReview(review);
|
|
1146
|
+
await finishCleanup(run, review, obsolete);
|
|
1147
|
+
// The review whose receipt arrives last is the current one, as its report says. The cleanup may have waited
|
|
1148
|
+
// for OpenCode while a person used another review here, so the choice is made now, next to the receipt.
|
|
1149
|
+
review.usedAt = stamp();
|
|
1150
|
+
await persistReview(review);
|
|
1151
|
+
// What an eviction or an earlier cleanup could not delete is tried again.
|
|
1152
|
+
void releaseExpired();
|
|
1153
|
+
} else await releaseUnfinished(run, output);
|
|
925
1154
|
// A review stopped while its report was delivered stays COMPLETE, but its comment step is off,
|
|
926
1155
|
// also in the report the receipt encloses, which was rendered before the stop.
|
|
927
1156
|
let enclosed = report;
|
|
@@ -1161,12 +1390,21 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
|
|
|
1161
1390
|
if (everAdjusted(review)) earlier = describeEarlierText(review, result.otherComments);
|
|
1162
1391
|
return { status: result.status, report: `${preview}\n\n${renderPublication(review, result)}`, failure: result.reason ?? '' };
|
|
1163
1392
|
}, dispatch);
|
|
1164
|
-
|
|
1393
|
+
// What this run decides about the review's preview and its own sessions is settled here, before anything is
|
|
1394
|
+
// awaited: the command locks are released already, so a later command may be planning or saving while this
|
|
1395
|
+
// run's sessions are deleted.
|
|
1165
1396
|
if (planning) review.plan = null;
|
|
1166
|
-
//
|
|
1167
|
-
|
|
1397
|
+
// A comment run keeps none of its sessions; the record names them before they are deleted.
|
|
1398
|
+
const obsolete = scheduleCleanup(run, review);
|
|
1399
|
+
await persistReview(review);
|
|
1400
|
+
await finishCleanup(run, review, obsolete);
|
|
1401
|
+
// The review whose receipt arrives last is the current one, as a preview's next steps say; this holds for
|
|
1402
|
+
// the automatic step too, which no command selected. The cleanup may have waited for OpenCode while a
|
|
1403
|
+
// person used another review here, so the choice is made now, next to the receipt.
|
|
1168
1404
|
review.usedAt = stamp();
|
|
1169
1405
|
await persistReview(review);
|
|
1406
|
+
// What an earlier cleanup could not delete is tried again.
|
|
1407
|
+
void releaseExpired();
|
|
1170
1408
|
const safe = (report || '').replaceAll('</azpr_comment_data>', '</azpr_comment_data>');
|
|
1171
1409
|
// A held preview says itself what to do; an adjustment says whether it was saved.
|
|
1172
1410
|
const retry = failure && ['INCOMPLETE', 'FAILED', 'PARTIALLY_POSTED'].includes(status) && !hold
|
|
@@ -1198,6 +1436,10 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
|
|
|
1198
1436
|
async function execute(input, output, dispatch) {
|
|
1199
1437
|
const mode = COMMANDS[input.command];
|
|
1200
1438
|
if (!mode) return;
|
|
1439
|
+
// Its answer would have nowhere to go.
|
|
1440
|
+
if (closing.has(input.sessionID)) {
|
|
1441
|
+
throw new Error('[AZPR] This reviewer session is being deleted: its run has ended, or its review is no longer kept. Type the command in the conversation the review was started in, or in the session that holds its report.');
|
|
1442
|
+
}
|
|
1201
1443
|
if (HELP_ARGUMENT.test(String(input.arguments ?? '').trim())) {
|
|
1202
1444
|
output.text = `${COMMAND_HELP[input.command]()}\nNo model or Azure DevOps request was made for this help.`;
|
|
1203
1445
|
return;
|
|
@@ -1215,13 +1457,19 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
|
|
|
1215
1457
|
*/
|
|
1216
1458
|
async function launch(name, sessionID, body) {
|
|
1217
1459
|
const output = {};
|
|
1460
|
+
// Until this command's last notice is out, the session it answers in is needed, and so is what the body
|
|
1461
|
+
// holds (`output.release`), also after its run has ended.
|
|
1462
|
+
const answered = hold(answering, sessionID);
|
|
1463
|
+
const ended = () => { answered(); for (const giveUp of output.release ?? []) giveUp(); };
|
|
1218
1464
|
let release;
|
|
1219
1465
|
const dispatch = { ready: new Promise(resolve => { release = resolve; }) };
|
|
1220
1466
|
const task = body(output, dispatch);
|
|
1221
1467
|
// Validation and /pr-stop answer immediately; workflows run in the background.
|
|
1222
1468
|
if (!dispatch.run) {
|
|
1223
|
-
|
|
1224
|
-
|
|
1469
|
+
try {
|
|
1470
|
+
await task;
|
|
1471
|
+
await deliver(sessionID, output.text);
|
|
1472
|
+
} finally { ended(); }
|
|
1225
1473
|
return;
|
|
1226
1474
|
}
|
|
1227
1475
|
const run = dispatch.run;
|
|
@@ -1231,7 +1479,7 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
|
|
|
1231
1479
|
}).catch(async error => {
|
|
1232
1480
|
const delivered = await deliver(sessionID, `[AZPR ${run.id}] INCOMPLETE\nReason: ${errorText(error)}`, run.id);
|
|
1233
1481
|
await run.debug?.write('delivery.json', { ...delivered, sessionID, error: errorText(error) });
|
|
1234
|
-
}).then(() => output.next && commentAfterReview(sessionID, output.next)).catch(() => { /* The step reports its own outcome. */ });
|
|
1482
|
+
}).then(() => output.next && commentAfterReview(sessionID, output.next)).catch(() => { /* The step reports its own outcome. */ }).finally(ended);
|
|
1235
1483
|
jobs.add(completion);
|
|
1236
1484
|
void completion.finally(() => jobs.delete(completion));
|
|
1237
1485
|
try {
|
|
@@ -1278,13 +1526,17 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
|
|
|
1278
1526
|
if (!g?.run.active || g.role !== execution?.agent) throw new Error('[AZPR] AZPR tools are available only to an active AZPR reviewer session.');
|
|
1279
1527
|
const snapshot = g.referenceSnapshot;
|
|
1280
1528
|
if (!snapshot) throw new Error('[AZPR] No PR snapshot is available for this reviewer.');
|
|
1529
|
+
// OpenCode aborts this signal when it interrupts the call; from 2.3.0 on, reading it (once) also tells the host
|
|
1530
|
+
// that a call a person stops ends by itself. The call then ends at once and the request only it waits for is
|
|
1531
|
+
// aborted, while reads the run's other sessions share go on.
|
|
1532
|
+
const given = execution.signal, stop = given instanceof AbortSignal ? given : undefined;
|
|
1281
1533
|
let outcome;
|
|
1282
1534
|
// Bounded by the Azure DevOps call timeouts, so the inactivity watchdog waits for it.
|
|
1283
1535
|
g.watch.toolsRunning++;
|
|
1284
1536
|
try {
|
|
1285
|
-
outcome = await runReviewTool(name, clone(input ?? {}), { azure, run: g.run, snapshot });
|
|
1537
|
+
outcome = await scoped(() => runReviewTool(name, clone(input ?? {}), { azure, run: g.run, snapshot, signal: stop }), stop);
|
|
1286
1538
|
} catch (error) {
|
|
1287
|
-
if (!g.run.active || g.run.controller.signal.aborted) throw error;
|
|
1539
|
+
if (!g.run.active || g.run.controller.signal.aborted || stop?.aborted) throw error;
|
|
1288
1540
|
if (error?.kind === 'timeout') g.toolTimeouts++;
|
|
1289
1541
|
const message = `${name} failed: ${errorText(error)}`;
|
|
1290
1542
|
return { output: message, content: [{ type: 'text', text: message }], metadata: { isError: true } };
|
|
@@ -1292,17 +1544,21 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
|
|
|
1292
1544
|
g.watch.toolsRunning--;
|
|
1293
1545
|
touch(g, `tool ${name} ended`);
|
|
1294
1546
|
}
|
|
1295
|
-
|
|
1296
|
-
for (const read of outcome.reads ?? []) if (read.version === snapshot.head || read.version === snapshot.base) g.reads.add(`${read.version}\n${read.path}`);
|
|
1547
|
+
let observation;
|
|
1297
1548
|
if (outcome.observation && ['initial', 'final'].includes(ROLES[g.role].format)) {
|
|
1298
|
-
// Keep observed source text with its request for anchor checks in comment planning.
|
|
1549
|
+
// Keep observed source text with its request for anchor checks in comment planning. A stopped call does not
|
|
1550
|
+
// wait for that save, which finishes by itself.
|
|
1299
1551
|
try {
|
|
1300
|
-
|
|
1301
|
-
g.run.toolText.set(observation.key, observation);
|
|
1552
|
+
observation = await scoped(async () => captureObservation(await dataFor(g.run), name, { path: outcome.observation.path, version: outcome.observation.version }, outcome.observation.text), stop);
|
|
1302
1553
|
} catch {
|
|
1303
|
-
g.run.debug.warnings.push('A review tool observation could not be saved for comment planning.');
|
|
1554
|
+
if (!stop?.aborted) g.run.debug.warnings.push('A review tool observation could not be saved for comment planning.');
|
|
1304
1555
|
}
|
|
1305
1556
|
}
|
|
1557
|
+
// A call the host stopped ends here: it showed the session nothing, so nothing is credited to it.
|
|
1558
|
+
if (stop?.aborted) throw abortError(stop);
|
|
1559
|
+
if (observation) g.run.toolText.set(observation.key, observation);
|
|
1560
|
+
// Only contents this call showed at the reviewed commits count as this session's reads.
|
|
1561
|
+
for (const read of outcome.reads ?? []) if (read.version === snapshot.head || read.version === snapshot.base) g.reads.add(`${read.version}\n${read.path}`);
|
|
1306
1562
|
return { output: outcome.text, content: [{ type: 'text', text: outcome.text }] };
|
|
1307
1563
|
}
|
|
1308
1564
|
|
|
@@ -1404,7 +1660,7 @@ export async function setupAzurePrReview(context, baseDirectory = DEFAULT_DIR, o
|
|
|
1404
1660
|
// Enforce the shell setting and the project boundary, regardless of
|
|
1405
1661
|
// permission rules the host appends after this plugin. Outside the
|
|
1406
1662
|
// project only AZPR's own private data is readable; the host's default
|
|
1407
|
-
// for other paths is not trusted (OpenCode 2.0.22 asked; 2.0.31 through 2.
|
|
1663
|
+
// for other paths is not trusted (OpenCode 2.0.22 asked; 2.0.31 through 2.3.0 allow).
|
|
1408
1664
|
// Private reviewers run unattended: a request that would wait for
|
|
1409
1665
|
// approval is refused at once. Only shell keeps host approvals, and only
|
|
1410
1666
|
// when the user allowed it (shell: "ask" or "inherit").
|