opencode-azure-devops-pr-review 0.3.7 → 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/src/search.mjs CHANGED
@@ -66,14 +66,15 @@ export function readZip(bytes, limits = SEARCH_LIMITS) {
66
66
 
67
67
  /**
68
68
  * The searchable repository at one commit, read once per run. A repository
69
- * that cannot be searched (too large, ZIP64) is cached as unavailable.
69
+ * that cannot be searched (too large, ZIP64) is cached as unavailable;
70
+ * `tooLarge` marks the case a larger azure.archiveMegabytes would lift.
70
71
  */
71
72
  export function repositoryArchive(run, azure, snapshot, version) {
72
73
  const cache = run.archives ??= new Map();
73
74
  if (!cache.has(version)) {
74
75
  const pending = (async () => {
75
76
  const result = await azure.archive(run, snapshot, version);
76
- if (result.tooLarge) return { unavailable: `the repository archive is larger than the azure.archiveMegabytes setting allows (${result.size} bytes)` };
77
+ if (result.tooLarge) return { tooLarge: true, unavailable: `the repository archive is larger than the azure.archiveMegabytes setting allows (${result.size} bytes)` };
77
78
  try { return readZip(result.bytes); }
78
79
  catch (error) { if (error instanceof ArchiveError) return { unavailable: error.message }; throw error; }
79
80
  })();
package/src/session.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  /** OpenCode V2 session transport. No provider, Azure or HTTP client. */
2
2
  import { isDeepStrictEqual } from 'node:util';
3
- import { FOREIGN_MESSAGE_TYPES, USED_UP_LIMITS, isHostContinuation, requireMethods } from './host.mjs';
3
+ import { FOREIGN_MESSAGE_TYPES, USED_UP_LIMITS, isHostContinuation, recordOf, requireMethods } from './host.mjs';
4
4
 
5
5
  const pendingAdmissions = new WeakMap();
6
6
  const textValue = value => typeof value === 'string' && value.length > 0;
@@ -66,19 +66,50 @@ function sameModel(actual, expected) {
66
66
  (actual?.variant ?? 'default') === (expected.variant ?? 'default');
67
67
  }
68
68
 
69
- /** Create a linked, independent session with its agent and model already bound. */
70
- export async function createReviewSession(context, { origin, title, role, model, permissions, signal }) {
71
- const api = sessionApi(context, ['create']);
69
+ /**
70
+ * The conversation's location, which a child session would inherit. Undefined
71
+ * when the host reports none; the host then uses the location this plugin
72
+ * instance serves.
73
+ */
74
+ async function conversationLocation(api, origin, signal) {
75
+ const conversation = recordOf(await cancellable(() => api.get({ sessionID: origin }), signal).catch(() => null));
76
+ const directory = conversation?.location?.directory;
77
+ if (!textValue(directory)) return undefined;
78
+ const workspaceID = conversation.location.workspaceID;
79
+ return { directory, ...(workspaceID === undefined || workspaceID === null ? {} : { workspaceID }) };
80
+ }
81
+
82
+ /**
83
+ * Create a session of its own with its agent and model already bound, at the
84
+ * conversation's location. It is deliberately not a child of the conversation:
85
+ * OpenCode 2.3.0 and later hand every answer of a child session to its parent
86
+ * and wake the parent's own model with it. `metadata` marks the session as
87
+ * AZPR's for tools that list sessions. A cancellation can overtake the host:
88
+ * the session may still be created after this call gave up, and nothing else
89
+ * would know it. `onLate` then receives it, when it is the session this call
90
+ * asked for, so that the caller can delete it.
91
+ */
92
+ export async function createReviewSession(context, { origin, title, role, model, permissions, metadata, signal, onLate }) {
93
+ const api = sessionApi(context, ['create', 'get']);
72
94
  if (!textValue(origin) || !textValue(role) || !textValue(title)) throw new Error('[AZPR] Incomplete review session identity.');
73
95
  const selectedModel = modelRef(model);
74
- const made = await cancellable(() => api.create({
75
- parentID: origin, title, agent: role, model: selectedModel,
76
- ...(permissions === undefined ? {} : { permissions }),
77
- }), signal);
78
- if (!record(made) || !textValue(made.id) || made.id === origin || made.parentID !== origin ||
79
- made.agent !== role || !sameModel(made.model, selectedModel)) {
80
- throw new Error('[AZPR] OpenCode V2 did not create the requested independent reviewer session.');
96
+ const location = await conversationLocation(api, origin, signal);
97
+ const requested = made => record(made) && textValue(made.id) && made.id !== origin && (made.parentID ?? null) === null &&
98
+ made.agent === role && sameModel(made.model, selectedModel) &&
99
+ (location === undefined || !record(made.location) || made.location.directory === location.directory);
100
+ let creating, made;
101
+ try {
102
+ made = await cancellable(() => (creating = Promise.resolve(api.create({
103
+ title, agent: role, model: selectedModel,
104
+ ...(location === undefined ? {} : { location }),
105
+ ...(metadata === undefined ? {} : { metadata }),
106
+ ...(permissions === undefined ? {} : { permissions }),
107
+ }))), signal);
108
+ } catch (error) {
109
+ if (onLate) creating?.then(late => { if (requested(late)) onLate(late); }).catch(() => {});
110
+ throw error;
81
111
  }
112
+ if (!requested(made)) throw new Error('[AZPR] OpenCode V2 did not create the requested independent reviewer session.');
82
113
  return made;
83
114
  }
84
115
 
@@ -116,9 +147,28 @@ function providerFailure(final, assistants) {
116
147
  }
117
148
 
118
149
  /**
119
- * Text fragments of a stream the host interrupted and resumed. Accept only
120
- * errored text-only assistant messages that the host marked for retry, each
121
- * followed by the host continuation, and finally a successful text answer.
150
+ * Errored assistant messages of steps the host retried by itself after an
151
+ * interrupted stream (OpenCode 2.3.0 and later): each is marked for retry and
152
+ * directly followed by the assistant message of the retried step. The retry is
153
+ * sent with what the step had finished (its tool calls that ran and what came
154
+ * before them) and without the output the interruption cut off, so the answer
155
+ * is the final message alone and nothing of these messages is joined to it.
156
+ */
157
+ function retriedSteps(turn, enabled) {
158
+ const retried = new Set();
159
+ if (!enabled) return retried;
160
+ turn.forEach((message, index) => {
161
+ if (message?.type === 'assistant' && message.error && message.finish === 'error' && Number.isInteger(message.retry?.attempt) &&
162
+ message.retry.attempt >= 1 && Number.isFinite(message.time?.completed) && turn[index + 1]?.type === 'assistant') retried.add(message);
163
+ });
164
+ return retried;
165
+ }
166
+
167
+ /**
168
+ * Text fragments of a stream the host interrupted and resumed with a
169
+ * continuation message (OpenCode through 2.2.x). Accept only errored text-only
170
+ * assistant messages that the host marked for retry, each followed by the host
171
+ * continuation, and finally a successful text answer.
122
172
  */
123
173
  function continuedText(turn, enabled) {
124
174
  const none = { recovered: new Set(), synthetic: new Set() };
@@ -211,7 +261,9 @@ export async function requestReview(context, { sessionID, text, role, model, met
211
261
  throw new Error('[AZPR] The projected prompt differs from the admitted literal input.');
212
262
  }
213
263
  const turn = messages.slice(indexes[0] + 1);
214
- const continuation = continuedText(turn, allowHostContinuations);
264
+ // Either way the host recovers an interrupted stream; both need the caller's consent.
265
+ const retried = retriedSteps(turn, allowHostContinuations);
266
+ const continuation = continuedText(turn.filter(message => !retried.has(message)), allowHostContinuations);
215
267
  if (turn.some(message => FOREIGN_MESSAGE_TYPES.includes(message?.type) && !continuation.synthetic.has(message))) {
216
268
  const error = new Error('[AZPR] The session received another message during this turn; its output cannot be assigned to the authorized request.');
217
269
  error.contextChanged = true;
@@ -247,7 +299,7 @@ export async function requestReview(context, { sessionID, text, role, model, met
247
299
  throw responseError('[AZPR] Reviewer agent or model binding changed; no output was accepted.', answer);
248
300
  }
249
301
  if (!final || turn.at(-2) !== final || !Array.isArray(final.content) || !Number.isFinite(final.time?.completed) ||
250
- assistants.some(message => !continuation.recovered.has(message) && (message.error || !Number.isFinite(message.time?.completed) ||
302
+ assistants.some(message => !continuation.recovered.has(message) && !retried.has(message) && (message.error || !Number.isFinite(message.time?.completed) ||
251
303
  !['stop', 'tool-calls'].includes(message.finish)))) {
252
304
  const error = responseError('[AZPR] The session has no complete, successful final assistant response.', answer);
253
305
  error.transient = true;
@@ -266,6 +318,7 @@ export async function requestReview(context, { sessionID, text, role, model, met
266
318
  answer.parts = [{ type: 'text', text: texts.slice(restartedAt).join('') }];
267
319
  answer.continuation = { count: continuation.recovered.size, fragments, ...(restartedAt ? { restartedAt } : {}) };
268
320
  }
321
+ if (retried.size) answer.retriedSteps = retried.size;
269
322
  aborted(signal);
270
323
  return answer;
271
324
  }
package/src/setup.mjs CHANGED
@@ -13,7 +13,8 @@ import { organizationName } from './azure.mjs';
13
13
  import { readPatFile, setupAzurePrReview } from './runtime.mjs';
14
14
 
15
15
  const SOURCE_DIRECTORY = dirname(fileURLToPath(import.meta.url));
16
- const SETUP_DESCRIPTION = 'Configure AZPR with one model and an existing PAT file; no model or Azure calls';
16
+ // OpenCode's command list shows one line and cuts it: the first 50 characters say what this is for.
17
+ const SETUP_DESCRIPTION = 'Set up AZPR: organization, model, PAT file; --help. Uses one model and an existing PAT file; no model or Azure calls';
17
18
  const USAGE = '/pr-setup --organization ORG --model PROVIDER/MODEL [--pat-file "/absolute/path/to/pat"]';
18
19
  const RESTART = 'restart the OpenCode service (in a terminal: opencode service restart; if you run opencode serve yourself, restart that process)';
19
20
  const MAX_SETTINGS_BYTES = 1024 * 1024;
package/src/store.mjs CHANGED
@@ -18,6 +18,8 @@ const RECEIPT_LIMIT = 50;
18
18
  const STALE_DATA_MS = 24 * 60 * 60 * 1000;
19
19
  const FORMAT = 1;
20
20
  const ATTEMPT_RETENTION_MS = 90 * 24 * 60 * 60 * 1000;
21
+ // Marks a record of sessions that should be gone and could not be deleted. Run and review IDs are hexadecimal.
22
+ const RETRY = 'retry';
21
23
 
22
24
  export function stateRoot(env = process.env) {
23
25
  const base = isAbsolute(env.XDG_STATE_HOME ?? '') ? env.XDG_STATE_HOME : join(homedir(), '.local', 'state');
@@ -27,15 +29,47 @@ export function stateRoot(env = process.env) {
27
29
  const checksum = value => createHash('sha256').update(value).digest('hex');
28
30
  const inside = (root, path) => { const rel = relative(root, path); return rel && !rel.startsWith('..') && !isAbsolute(rel); };
29
31
 
30
- /** Plain JSON form of a review; Sets and Maps become arrays. */
32
+ /**
33
+ * Plain JSON form of a review; Sets and Maps become arrays. `closingSessions`
34
+ * (sessions whose deletion was asked for and never answered) is written only
35
+ * when there are any.
36
+ */
31
37
  export function serializeReview(review) {
32
- const { data, reportSessions, publication, ...rest } = review;
33
- return { ...rest, reportSessions: [...(reportSessions ?? [])], publication: [...(publication ?? new Map())],
34
- dataDirectory: review.dataDirectory ?? null };
38
+ const { data, reportSessions, closingSessions, publication, ...rest } = review;
39
+ return { ...rest, reportSessions: [...(reportSessions ?? [])], ...(closingSessions?.size ? { closingSessions: [...closingSessions] } : {}),
40
+ publication: [...(publication ?? new Map())], dataDirectory: review.dataDirectory ?? null };
35
41
  }
36
42
 
37
43
  export function deserializeReview(value) {
38
- return { ...value, reportSessions: new Set(value.reportSessions ?? []), publication: new Map(value.publication ?? []) };
44
+ return { ...value, reportSessions: new Set(value.reportSessions ?? []), ...(value.closingSessions ? { closingSessions: new Set(value.closingSessions) } : {}),
45
+ publication: new Map(value.publication ?? []) };
46
+ }
47
+
48
+ /**
49
+ * Writes of saved reviews, one at a time per review and in the order asked,
50
+ * so two writes of one record never overlap and an earlier write never lands
51
+ * after a later one. `write(id, action)` queues an action (a save or a
52
+ * removal) and returns its result; a failed action does not stop the next.
53
+ * `latest(id, save)` asks for a save that reads the review only when it
54
+ * starts: a request joins such a save while it waits in the queue, and once it
55
+ * has started, so has already read the review, the next request gets a save of
56
+ * its own after it. Either way a request is carried by a save that starts
57
+ * after it, and the record ends with the latest state asked for.
58
+ */
59
+ export function createReviewWrites() {
60
+ const tails = new Map(), waiting = new Map();
61
+ function write(id, action) {
62
+ const result = (tails.get(id) ?? Promise.resolve()).then(action);
63
+ const settled = result.then(() => {}, () => {});
64
+ tails.set(id, settled);
65
+ void settled.then(() => { if (tails.get(id) === settled) tails.delete(id); });
66
+ return result;
67
+ }
68
+ function latest(id, save) {
69
+ if (!waiting.has(id)) waiting.set(id, write(id, () => { waiting.delete(id); return save(); }));
70
+ return waiting.get(id);
71
+ }
72
+ return { write, latest };
39
73
  }
40
74
 
41
75
  async function writeAtomic(path, content) {
@@ -45,8 +79,12 @@ async function writeAtomic(path, content) {
45
79
  }
46
80
 
47
81
  /**
48
- * `onRemove(review)` runs after an evicted or removed review's files are
49
- * deleted (for example to delete its reviewer sessions); its errors are ignored.
82
+ * `onRemove(review)` runs before an evicted or removed review's files are
83
+ * deleted, to delete its reviewer sessions: the review's record is what names
84
+ * them, so it stays until they are dealt with, and a process that ends
85
+ * meanwhile finds the review again. When it returns false (sessions that are
86
+ * still there could not be put on record elsewhere) the review stays for a
87
+ * later attempt; its errors are ignored.
50
88
  */
51
89
  export async function createReviewStore({ root = stateRoot(), limit = REVIEW_LIMIT, now = () => Date.now(), onRemove } = {}) {
52
90
  const dirs = { reviews: join(root, 'reviews'), data: join(root, 'data'), receipts: join(root, 'receipts'), sessions: join(root, 'sessions'), attempts: join(root, 'attempts') };
@@ -67,10 +105,27 @@ export async function createReviewStore({ root = stateRoot(), limit = REVIEW_LIM
67
105
  return reviews.sort((a, b) => String(a.completedAt ?? '').localeCompare(String(b.completedAt ?? '')));
68
106
  }
69
107
 
108
+ // One record of sessions per key: written, replaced in its place, or removed by an empty list.
109
+ async function recordSessions(key, sessionIDs) {
110
+ const own = (await readdir(dirs.sessions)).filter(name => name.endsWith(`-${key}.json`)).sort();
111
+ const record = own.at(-1) ?? `${new Date(now()).toISOString().replace(/[:.]/g, '-')}-${key}.json`;
112
+ for (const other of own.slice(0, -1)) await rm(join(dirs.sessions, other), { force: true });
113
+ if (sessionIDs.length) await writeAtomic(join(dirs.sessions, record), JSON.stringify(sessionIDs));
114
+ else await rm(join(dirs.sessions, record), { force: true });
115
+ }
116
+
117
+ // A record's name ends with its ID; the ID of a record of sessions still to be deleted starts with RETRY.
118
+ const idOf = name => name.slice(name.lastIndexOf('-') + 1, -'.json'.length);
119
+ const isRetry = name => idOf(name).startsWith(RETRY);
120
+
121
+ /** Remove a review and its data, after `onRemove`; false when `onRemove` kept it. */
70
122
  async function removeReview(review) {
123
+ let settled = true;
124
+ try { settled = (await onRemove?.(review)) !== false; } catch { /* Cleanup never fails an eviction. */ }
125
+ if (!settled) return false;
71
126
  await rm(join(dirs.reviews, `${review.id}.json`), { force: true });
72
127
  if (review.dataDirectory && inside(dirs.data, review.dataDirectory)) await rm(review.dataDirectory, { recursive: true, force: true });
73
- try { await onRemove?.(review); } catch { /* Cleanup never fails an eviction. */ }
128
+ return true;
74
129
  }
75
130
 
76
131
  return {
@@ -86,12 +141,17 @@ export async function createReviewStore({ root = stateRoot(), limit = REVIEW_LIM
86
141
  const body = JSON.stringify(serializeReview(review));
87
142
  await writeAtomic(join(dirs.reviews, `${review.id}.json`), JSON.stringify({ format: FORMAT, sha256: checksum(body), body }));
88
143
  },
89
- /** Remove the oldest reviews on disk beyond the limit; returns evicted IDs. */
90
- async enforceLimit() {
144
+ /**
145
+ * Remove the oldest reviews on disk beyond the limit; returns evicted IDs.
146
+ * `inUse(id)` names reviews a command is working on, which stay.
147
+ */
148
+ async enforceLimit(inUse = () => false) {
91
149
  const reviews = await listReviews();
92
- const evicted = reviews.slice(0, Math.max(0, reviews.length - limit));
93
- for (const review of evicted) await removeReview(review);
94
- return evicted.map(review => review.id);
150
+ const evicted = [];
151
+ for (const review of reviews.slice(0, Math.max(0, reviews.length - limit))) {
152
+ if (!inUse(review.id) && await removeReview(review)) evicted.push(review.id);
153
+ }
154
+ return evicted;
95
155
  },
96
156
  remove: removeReview,
97
157
  /** Delete stale unreferenced data and legacy temporary directories. */
@@ -120,22 +180,58 @@ export async function createReviewStore({ root = stateRoot(), limit = REVIEW_LIM
120
180
  return removed;
121
181
  },
122
182
  /**
123
- * Remember reviewer sessions kept from a run that left no saved review.
124
- * The newest `limit` runs keep theirs; returns the session IDs of older
125
- * runs, whose records are removed, for the caller to delete.
183
+ * Remember the reviewer sessions a run that left no saved review keeps
184
+ * on purpose, such as the one holding its draft; the newest `limit` runs
185
+ * keep theirs. A run has one record: a later call replaces its earlier
186
+ * one and keeps its place in the order, and an empty list removes it.
126
187
  */
127
- async keepSessions(runId, sessionIDs) {
128
- await writeAtomic(join(dirs.sessions, `${new Date(now()).toISOString().replace(/[:.]/g, '-')}-${runId}.json`), JSON.stringify(sessionIDs));
188
+ keepSessions: (runId, sessionIDs) => recordSessions(runId, sessionIDs),
189
+ /**
190
+ * Remember sessions that are still to be deleted, under the ID of the
191
+ * run or review they belonged to: those a cleanup is about to delete,
192
+ * then those it could not delete. They are due at every pass
193
+ * (`expiredSessions`) and do not count against the limit. One record per
194
+ * ID, replaced by a later call and removed by an empty list.
195
+ */
196
+ retrySessions: (id, sessionIDs) => recordSessions(`${RETRY}${id}`, sessionIDs),
197
+ /**
198
+ * The sessions that are due to go, one entry per run or review, as
199
+ * { runId, sessionIDs, kept }: those still to be deleted, due at every
200
+ * pass, and the kept sessions of runs beyond the newest `limit` (`kept`),
201
+ * oldest first. A run with both has one entry, so that what is left of it
202
+ * is recorded once. `inUse(runId)` names runs whose command has not
203
+ * ended: their own cleanup deals with their sessions, so both of their
204
+ * records are left out, whatever their age. The records stay: the caller
205
+ * deletes the sessions, records what is left (`retrySessions`) and only
206
+ * then removes a kept record (`keepSessions`). An unreadable record
207
+ * names nothing and is removed.
208
+ */
209
+ async expiredSessions(inUse = () => false) {
129
210
  const files = (await readdir(dirs.sessions)).filter(name => name.endsWith('.json')).sort();
130
- const released = [];
131
- for (const old of files.slice(0, Math.max(0, files.length - limit))) {
211
+ const kept = files.filter(name => !isRetry(name)), due = new Map();
212
+ for (const name of [...files.filter(isRetry), ...kept.slice(0, Math.max(0, kept.length - limit))]) {
213
+ const retry = isRetry(name), runId = retry ? idOf(name).slice(RETRY.length) : idOf(name);
214
+ if (inUse(runId)) continue;
215
+ let ids;
216
+ try { ids = JSON.parse(await readFile(join(dirs.sessions, name), 'utf8')); } catch { ids = null; }
217
+ if (!Array.isArray(ids)) { await rm(join(dirs.sessions, name), { force: true }); continue; }
218
+ const entry = due.get(runId) ?? { runId, sessionIDs: [], kept: false };
219
+ for (const id of ids) if (typeof id === 'string' && !entry.sessionIDs.includes(id)) entry.sessionIDs.push(id);
220
+ if (!retry) entry.kept = true;
221
+ due.set(runId, entry);
222
+ }
223
+ return [...due.values()];
224
+ },
225
+ /** Every session the records name, as { kept, due }: kept on purpose by an unfinished run, and still to be deleted. */
226
+ async recordedSessions() {
227
+ const kept = [], due = [];
228
+ for (const name of (await readdir(dirs.sessions).catch(() => [])).filter(file => file.endsWith('.json'))) {
132
229
  try {
133
- const ids = JSON.parse(await readFile(join(dirs.sessions, old), 'utf8'));
134
- if (Array.isArray(ids)) released.push(...ids.filter(id => typeof id === 'string'));
135
- } catch { /* An unreadable record releases nothing. */ }
136
- await rm(join(dirs.sessions, old), { force: true });
230
+ const ids = JSON.parse(await readFile(join(dirs.sessions, name), 'utf8'));
231
+ if (Array.isArray(ids)) (isRetry(name) ? due : kept).push(...ids.filter(id => typeof id === 'string'));
232
+ } catch { /* An unreadable record names nothing. */ }
137
233
  }
138
- return released;
234
+ return { kept, due };
139
235
  },
140
236
  /**
141
237
  * Thread-creation attempts of one PR, keyed by comment marker and shared by