opencode-azure-devops-pr-review 0.4.2 → 0.4.3

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/setup.mjs CHANGED
@@ -1,21 +1,36 @@
1
- /** Native package bootstrap. Configuration lives outside the package cache. */
1
+ /**
2
+ * Native package bootstrap and setup. Configuration lives outside the package cache.
3
+ *
4
+ * Setup has two ways in, and one writer. `/pr-setup` with options saves what they name, and in OpenCode's
5
+ * terminal UI `/pr-setup` alone opens dialogs (src/tui-setup.mjs) that send their answers over the plugin's
6
+ * RPC. Both end in the functions here, which check every value, are the only ones to write the settings
7
+ * file and the token file, and are the only ones to ask Azure DevOps whether a token works.
8
+ */
2
9
  import { constants } from 'node:fs';
3
10
  import { open, readFile, lstat, mkdir, link, rename, stat, unlink } from 'node:fs/promises';
4
11
  import { homedir } from 'node:os';
5
12
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
6
13
  import { fileURLToPath } from 'node:url';
7
- import { randomUUID } from 'node:crypto';
8
- import { COMMANDS, modelRef, privateAgent, settingsText, validateSettings, withMissingSettings } from './config.mjs';
14
+ import { createHash, randomUUID } from 'node:crypto';
15
+ import { COMMANDS, MODES, SETTING_CHECKS, modelRef, modelSlots, patProblem, privateAgent, settingsText, validateSettings, withMissingSettings } from './config.mjs';
9
16
  import { parseUniqueJSON } from './output.mjs';
10
17
  import { appendReport } from './session.mjs';
11
- import { listOf, recordOf, requireMethods } from './host.mjs';
12
- import { organizationName } from './azure.mjs';
13
- import { readPatFile, setupAzurePrReview } from './runtime.mjs';
18
+ import { fetchTransportSupported, listOf, recordOf, requireMethods } from './host.mjs';
19
+ import { AzureError, createAzureClient, fetchTransport, organizationName, proxyLabel, restBaseUrl } from './azure.mjs';
20
+ import { createToolQueue } from './tool-queue.mjs';
21
+ import { readCaCertificates, readPatFile, setupAzurePrReview } from './runtime.mjs';
22
+ import { SETUP_RPC } from './tui-setup.mjs';
14
23
 
15
24
  const SOURCE_DIRECTORY = dirname(fileURLToPath(import.meta.url));
16
25
  // 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';
26
+ const SETUP_DESCRIPTION = 'Set up AZPR: organization, token, model; --help. In the terminal UI it asks in dialogs; elsewhere options name the values. No model call';
18
27
  const USAGE = '/pr-setup --organization ORG --model PROVIDER/MODEL [--pat-file "/absolute/path/to/pat"]';
28
+ // How long setup waits for Azure DevOps when it checks a token: a person is waiting for the answer.
29
+ const CHECK_TIMEOUT_MS = 20000;
30
+ // How long a first setup waits for OpenCode to drop the commands that only said "setup required".
31
+ const RELEASE_WAIT_MS = 3000;
32
+ // The commands of a process without usable settings: each only says what is missing.
33
+ const PLACEHOLDER_DESCRIPTION = 'AZPR setup required; run /pr-setup';
19
34
  const RESTART = 'restart the OpenCode service (in a terminal: opencode service restart; if you run opencode serve yourself, restart that process)';
20
35
  const MAX_SETTINGS_BYTES = 1024 * 1024;
21
36
  // A writer holds the setup lock for a few milliseconds. One this old was left behind by a process that
@@ -78,21 +93,152 @@ export function parseSetupArguments(text) {
78
93
  const result = {};
79
94
  for (let index = 0; index < tokens.length; index++) {
80
95
  const flag = tokens[index];
81
- if (!['--organization', '--model', '--pat-file', '--replace'].includes(flag) || Object.hasOwn(result, flag)) {
96
+ if (!SETUP_FLAGS.includes(flag) || Object.hasOwn(result, flag)) {
82
97
  throw new Error('[AZPR] Unknown or repeated setup option. Use /pr-setup --help. Never put the PAT itself in a command.');
83
98
  }
84
99
  if (flag === '--replace') result[flag] = true;
85
100
  else {
86
- if (!tokens[index + 1] || tokens[index + 1].startsWith('--')) throw new Error('[AZPR] A setup option needs a value. Use /pr-setup --help.');
101
+ if (tokens[index + 1] === undefined || tokens[index + 1].startsWith('--')) throw new Error('[AZPR] A setup option needs a value. Use /pr-setup --help.');
87
102
  result[flag] = tokens[++index];
88
103
  }
89
104
  }
90
- if (['--organization', '--model'].some(flag => !result[flag])) {
105
+ // The options of a first setup come together; an option that changes one setting stands alone.
106
+ if (FIRST_SETUP_FLAGS.some(flag => result[flag] !== undefined) && ['--organization', '--model'].some(flag => !result[flag])) {
91
107
  throw new Error('[AZPR] Supply --organization and --model (--pat-file is optional). Use /pr-setup --help.');
92
108
  }
93
109
  return result;
94
110
  }
95
111
 
112
+ // ------------------------------------------------------------------------------------------------ rows
113
+ const text = value => typeof value === 'string' ? value : '';
114
+ const OFF_WORD = /^(?:none|off)$/i;
115
+ const azureOf = raw => object(raw.azure) ? raw.azure : {};
116
+ const withAzure = (raw, values) => ({ ...raw, azure: { ...azureOf(raw), ...values } });
117
+ const modelsOf = (raw, mode) => modelSlots(mode).map(slot => text(raw.models?.[mode]?.[slot]));
118
+ const withModels = (raw, mode, value) => ({ ...raw, models: { ...(object(raw.models) ? raw.models : {}),
119
+ [mode]: { ...(object(raw.models?.[mode]) ? raw.models[mode] : {}), ...Object.fromEntries(modelSlots(mode).map(slot => [slot, value])) } } });
120
+ /** The one value that all of them have, or null when they differ. */
121
+ const shared = values => values.every(value => value === values[0]) ? values[0] : null;
122
+ /**
123
+ * Several values as one row of the list shows them: the value they share (`empty` where that is none), else
124
+ * only that they differ, since the list has room for a few words; the settings file has each of them.
125
+ */
126
+ const together = (values, empty, differ) => shared(values) === null ? differ : shared(values) || empty;
127
+ /** A path as a row of the list shows it: its last two parts where it is long. The dialog of the row has all of it. */
128
+ const shortPath = value => value.length <= 30 ? value : `…/${value.split('/').filter(Boolean).slice(-2).join('/')}`.slice(0, 34);
129
+ /** A proxy as it may be shown: scheme, host and port, and whether it carries a user name and password. */
130
+ function shownProxy(value) {
131
+ if (!value) return 'none';
132
+ try { const url = new URL(value); return `${proxyLabel(value)}${url.username || url.password ? ' (with credentials)' : ''}`; }
133
+ catch { return 'not a proxy URL'; }
134
+ }
135
+ /** HTTPS_PROXY of the process that runs AZPR, as it may be shown; Bun's fetch uses it when azure.proxy is empty. */
136
+ function serviceProxy(environment) {
137
+ const value = environment.HTTPS_PROXY || environment.https_proxy || '';
138
+ try { return value ? proxyLabel(value) : ''; } catch { return ''; }
139
+ }
140
+ const valid = (check, ...args) => { try { return check(...args); } catch (error) { throw new Error(`[AZPR] ${error.message}`); } };
141
+
142
+ function organizationOf(answer) {
143
+ const name = organizationName(text(answer).trim());
144
+ if (typeof name !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9-]{0,49}$/.test(name)) {
145
+ throw new Error('[AZPR] Use your Azure DevOps organization name (the <org> in https://dev.azure.com/<org>), or the URL of one of its pull requests.');
146
+ }
147
+ return name;
148
+ }
149
+ function proxyOf(answer, saved) {
150
+ const value = text(answer).trim();
151
+ if (value === '' || OFF_WORD.test(value)) return '';
152
+ // A dialog starts with the saved proxy without its user name and password: left as it is, it keeps them.
153
+ if (saved) { try { if (value === proxyLabel(saved)) return saved; } catch { /* A saved value that is no URL is replaced. */ } }
154
+ return valid(SETTING_CHECKS.proxy, value);
155
+ }
156
+ async function caFileOf(answer) {
157
+ const value = text(answer).trim();
158
+ if (value === '' || OFF_WORD.test(value)) return '';
159
+ if (!isAbsolute(value) || /[\0\r\n]/.test(value)) throw new Error('[AZPR] The CA certificate file must be an absolute path.');
160
+ await readCaCertificates(value);
161
+ return value;
162
+ }
163
+ async function modelOf(context, answer, optional) {
164
+ const value = text(answer).trim();
165
+ if (optional && (value === '' || OFF_WORD.test(value))) return '';
166
+ valid(SETTING_CHECKS.model, value, 'The model');
167
+ await checkModel(context, value);
168
+ return value;
169
+ }
170
+ const choiceOf = (row, answer) => {
171
+ const value = text(answer).trim();
172
+ if (!row.choices.some(choice => choice.value === value)) throw new Error(`[AZPR] ${row.label} must be one of: ${row.choices.map(choice => choice.value).join(', ')}.`);
173
+ return value;
174
+ };
175
+ const onOff = { choices: [{ value: 'on', label: 'On' }, { value: 'off', label: 'Off' }], show: value => value ? 'on' : 'off', current: value => value ? 'on' : 'off' };
176
+ const LANGUAGES = [['en', 'English'], ['zh-TW', '繁體中文'], ['zh-CN', '简体中文'], ['ja', '日本語'], ['ko', '한국어'], ['de', 'Deutsch'], ['fr', 'Français'], ['es', 'Español']];
177
+ const PUBLISH_CONFIRMATION = { title: 'Post comments without a preview?', keep: 'No, keep the current setting', accept: 'Yes, post them after every review',
178
+ message: 'Each completed review then posts its comments on the pull request under your name' };
179
+
180
+ /**
181
+ * What setup can set, in the order the terminal UI lists it; everything else stays in the settings file.
182
+ * A row reads its value from settings that have every default (`get`), shows it (`show`, and `current`:
183
+ * what a dialog starts with), takes an answer as a person gives it (`accept`: the value to save, or an
184
+ * Error that says what is wrong without quoting the answer) and writes it (`set`). `flag` is its
185
+ * /pr-setup option. The token has no option and is never part of `changes`: it travels alone.
186
+ */
187
+ const ROWS = Object.freeze([
188
+ { id: 'organization', flag: '--organization', group: 'Azure DevOps', label: 'Organization', kind: 'text', title: 'Azure DevOps organization', placeholder: 'my-organization',
189
+ description: () => 'The name in https://dev.azure.com/<organization>. You can also paste the URL of a pull request.',
190
+ get: raw => text(azureOf(raw).organization), show: value => value || 'not set', current: value => value,
191
+ accept: async (_context, answer) => organizationOf(answer), set: (raw, value) => withAzure(raw, { organization: value }) },
192
+ { id: 'token', group: 'Azure DevOps', label: 'Access token', kind: 'secret', title: 'Personal access token',
193
+ description: () => 'Create one at https://dev.azure.com/{organization}/_usersSettings/tokens with the scopes Code (Read) and Pull Request Threads (Read & write). Azure DevOps is asked once whether it works. It is then saved in a file only you can read (mode 600) and not shown again.' },
194
+ { id: 'proxy', flag: '--proxy', group: 'Azure DevOps', label: 'Proxy', kind: 'text', title: 'Proxy for Azure DevOps (optional)', placeholder: 'http://proxy.example.com:8080',
195
+ description: (raw, environment) => 'Only if this network reaches dev.azure.com through a proxy. Leave it empty and press Enter to skip. A user name and password go into the URL (http://user:password@host:port) and are visible while you type.' +
196
+ (serviceProxy(environment) ? ` When it is empty, AZPR uses the HTTPS_PROXY of the OpenCode service: ${serviceProxy(environment)}.` : '') +
197
+ (shownProxy(text(azureOf(raw).proxy)).endsWith(')') ? ' The saved proxy has a user name and password, which are not shown: leave the URL as it is to keep them.' : ''),
198
+ get: raw => text(azureOf(raw).proxy), show: shownProxy, current: value => { try { return value ? proxyLabel(value) : ''; } catch { return ''; } },
199
+ accept: async (_context, answer, raw) => proxyOf(answer, text(azureOf(raw).proxy)), set: (raw, value) => withAzure(raw, { proxy: value }) },
200
+ { id: 'caFile', flag: '--ca-file', group: 'Azure DevOps', label: 'CA certificate file', kind: 'text', title: 'CA certificate file (optional)', placeholder: '/absolute/path/to/company-root-ca.pem',
201
+ description: () => 'Only where a company proxy inspects HTTPS: the absolute path of its root CA certificate, a PEM file. Leave it empty and press Enter to skip.',
202
+ get: raw => text(azureOf(raw).caFile), show: value => value ? shortPath(value) : 'none', current: value => value,
203
+ accept: async (_context, answer) => caFileOf(answer), set: (raw, value) => withAzure(raw, { caFile: value }) },
204
+ { id: 'reviewModel', flag: '--review-model', group: 'Models', label: 'Review model', kind: 'model', title: 'Model for /pr-review',
205
+ get: raw => modelsOf(raw, 'review'), show: values => together(values, 'not set', 'differs by role'), current: values => shared(values) ?? '',
206
+ accept: (context, answer) => modelOf(context, answer, false), set: (raw, value) => withModels(raw, 'review', value) },
207
+ { id: 'quickModel', flag: '--quick-model', group: 'Models', label: 'Quick model', kind: 'model', title: 'Model for /pr-quick', optional: { label: 'Off', description: '/pr-quick stays off' },
208
+ get: raw => modelsOf(raw, 'quick'), show: values => values[0] || 'off', current: values => values[0],
209
+ accept: (context, answer) => modelOf(context, answer, true), set: (raw, value) => withModels(raw, 'quick', value) },
210
+ { id: 'deepModel', flag: '--deep-model', group: 'Models', label: 'Deep model', kind: 'model', title: 'Stronger model for /pr-deep', optional: { label: 'Off', description: '/pr-deep stays off' },
211
+ get: raw => modelsOf(raw, 'deep'), show: values => together(values, 'off', 'differs by role'), current: values => shared(values) ?? '',
212
+ accept: (context, answer) => modelOf(context, answer, true), set: (raw, value) => withModels(raw, 'deep', value) },
213
+ { id: 'language', flag: '--language', group: 'Reviews', label: 'Output language', kind: 'choice', title: 'Language of reports and comments',
214
+ choices: LANGUAGES.map(([value, label]) => ({ value, label, description: value })),
215
+ other: { label: 'Another language', title: 'Language of reports and comments', description: 'A language tag such as en, zh-TW, pt-BR or it.', placeholder: 'pt-BR' },
216
+ get: raw => text(raw.outputLanguage), show: value => value, current: value => value,
217
+ accept: async (_context, answer) => valid(SETTING_CHECKS.language, text(answer).trim()), set: (raw, value) => ({ ...raw, outputLanguage: value }) },
218
+ { id: 'afterReview', flag: '--after-review', group: 'Reviews', label: 'After a review', kind: 'choice', title: 'After a completed review',
219
+ choices: [{ value: 'preview', label: 'Show a comment preview', description: 'Nothing is posted' }, { value: 'none', label: 'Only the review', description: 'No preview' },
220
+ { value: 'publish', label: 'Post the comments', description: 'Without a preview', confirm: PUBLISH_CONFIRMATION }],
221
+ get: raw => MODES.map(mode => text(raw.afterReview?.[mode])), show: values => together(values, 'not set', 'differs by mode'), current: values => shared(values) ?? '',
222
+ accept: async (_context, answer, _raw, row) => choiceOf(row, answer), set: (raw, value) => ({ ...raw, afterReview: { ...(object(raw.afterReview) ? raw.afterReview : {}), ...Object.fromEntries(MODES.map(mode => [mode, value])) } }) },
223
+ { id: 'report', flag: '--report', group: 'Reviews', label: 'Report in the conversation', kind: 'choice', title: 'What a review returns to the conversation',
224
+ choices: [{ value: 'receipt', label: 'A receipt', description: 'The report waits in the review session' }, { value: 'full', label: 'The receipt with the report', description: 'Also in the conversation' }],
225
+ get: raw => text(raw.returnReport), show: value => value, current: value => value,
226
+ accept: async (_context, answer, _raw, row) => choiceOf(row, answer), set: (raw, value) => ({ ...raw, returnReport: value }) },
227
+ { id: 'progress', flag: '--progress', group: 'Reviews', label: 'Progress notices', kind: 'choice', title: 'Progress notices during long runs', ...onOff,
228
+ get: raw => raw.progressNotices === true, accept: async (_context, answer, _raw, row) => choiceOf(row, answer) === 'on', set: (raw, value) => ({ ...raw, progressNotices: value }) },
229
+ { id: 'panel', flag: '--panel', group: 'Terminal UI', label: 'Review panel', kind: 'choice', title: 'The review panel in the terminal UI',
230
+ choices: [{ value: 'auto', label: 'Opens by itself', description: 'When a run starts or a report arrives' }, { value: 'manual', label: 'Only with /pr-panel' }],
231
+ get: raw => text(raw.terminalPanel), show: value => value, current: value => value,
232
+ accept: async (_context, answer, _raw, row) => choiceOf(row, answer), set: (raw, value) => ({ ...raw, terminalPanel: value }) },
233
+ { id: 'debug', flag: '--debug', group: 'Diagnostics', label: 'Debug records', kind: 'choice', title: 'Debug records of every run', ...onOff,
234
+ get: raw => raw.debug?.enabled === true, accept: async (_context, answer, _raw, row) => choiceOf(row, answer) === 'on',
235
+ set: (raw, value) => ({ ...raw, debug: { ...(object(raw.debug) ? raw.debug : {}), enabled: value } }) },
236
+ ]);
237
+ const rowOf = id => ROWS.find(row => row.id === id);
238
+ /** --model, --pat-file and --replace belong to a first setup, as does --organization; the other options change one setting each. */
239
+ const FIRST_SETUP_FLAGS = Object.freeze(['--organization', '--model', '--pat-file', '--replace']);
240
+ const SETUP_FLAGS = Object.freeze([...new Set([...FIRST_SETUP_FLAGS, ...ROWS.flatMap(row => row.flag ? [row.flag] : [])])]);
241
+
96
242
  async function checkModel(context, value) {
97
243
  if (typeof context.model?.list !== 'function') throw new Error('[AZPR] The model catalog is unavailable. Connect a model provider in OpenCode, then retry setup.');
98
244
  const catalog = listOf(await context.model.list());
@@ -129,13 +275,21 @@ async function readExisting(path) {
129
275
 
130
276
  /**
131
277
  * Atomic, owner-only save; serialize setup calls and preserve unrelated values.
132
- * Without --pat-file, a replacement keeps the PAT file already set and a first
133
- * setup uses the default PAT file. The file names every setting, those setup
134
- * does not ask for at their defaults. Returns the saved organization and PAT file.
278
+ * The options of a first setup (--organization, --model, --pat-file) create the file, or with --replace
279
+ * set those values again: without --pat-file, a replacement keeps the PAT file already set and a first
280
+ * setup uses the default PAT file. Every other option changes the one setting it names in an existing
281
+ * file. The file names every setting, those setup does not ask for at their defaults. Returns the saved
282
+ * organization and PAT file, the labels of the single settings that were changed, whether the settings it
283
+ * replaced could not be used (`unusable`), and what the settings and the token file they name held when it
284
+ * read them (`before`) and what it leaves (`after`: the text it wrote with the token it read; see `pairWith`).
135
285
  */
136
286
  export async function saveSetup(context, path, arguments_, environment = process.env) {
137
287
  const previous = await readExisting(path);
138
- if (previous !== null && !arguments_['--replace']) {
288
+ const first = FIRST_SETUP_FLAGS.some(flag => arguments_[flag] !== undefined);
289
+ if (previous === null && !first) {
290
+ throw new Error('[AZPR] There are no settings yet. Supply --organization and --model, or run /pr-setup alone in OpenCode\'s terminal UI. Use /pr-setup --help.');
291
+ }
292
+ if (previous !== null && first && !arguments_['--replace']) {
139
293
  throw new Error('[AZPR] Settings already exist. Add --replace to change organization, PAT file and all review/quick model slots while keeping other settings.');
140
294
  }
141
295
  const raw = previous === null ? { version: 2 } : settingsJSON(previous);
@@ -143,47 +297,146 @@ export async function saveSetup(context, path, arguments_, environment = process
143
297
  if (raw.models !== undefined && !object(raw.models) || raw.azure !== undefined && !object(raw.azure)) {
144
298
  throw new Error('[AZPR] Repair models and azure objects in settings.json before setup; existing data was preserved.');
145
299
  }
146
- const model = arguments_['--model'];
147
- const organization = organizationName(arguments_['--organization']);
148
- const kept = typeof raw.azure?.patFile === 'string' && raw.azure.patFile ? raw.azure.patFile : '';
149
- const patFile = arguments_['--pat-file'] ?? (kept || defaultPatFile(environment));
150
- if (typeof patFile !== 'string' || !isAbsolute(patFile) || resolve(patFile) === resolve(path)) {
151
- throw new Error('[AZPR] --pat-file must name an absolute path separate from settings.json.');
152
- }
153
- const { settings: next } = withMissingSettings({ ...raw, models: { ...raw.models,
154
- review: { functional: model, risk: model, verifier: model }, quick: { reviewer: model } },
155
- azure: { ...raw.azure, organization, pat: '', patFile } });
156
- validateSettings(next);
157
- await checkModel(context, model);
158
- try { await readPatFile(patFile); }
159
- catch (error) {
160
- if (arguments_['--pat-file'] !== undefined) throw error;
161
- // Name the file setup chose, so the reader knows where to put the PAT.
162
- const problem = error.message.replace(/^\[AZPR\] azure\.patFile /, '');
163
- throw new Error(`[AZPR] No --pat-file was given, and the ${kept ? 'PAT file in the current settings' : 'default PAT file'} ${patFile} ${problem} Create it as the quickstart shows, or name another file with --pat-file.`);
164
- }
165
- await writeSettings(path, previous, next);
166
- return { organization, patFile };
300
+ // Whether the settings this save replaces could be used, and the token that goes with them, from one look at
301
+ // them when they are read: what this save leaves is said from what it read and wrote, never from a later
302
+ // look, which could be at another writer's work.
303
+ const held = await settingsTextProblem(previous);
304
+ const heldDigest = held.digest;
305
+ let next = raw, patFile = text(raw.azure?.patFile), leftDigest = heldDigest;
306
+ if (first) {
307
+ const model = arguments_['--model'];
308
+ const organization = organizationName(arguments_['--organization']);
309
+ const kept = typeof raw.azure?.patFile === 'string' && raw.azure.patFile ? raw.azure.patFile : '';
310
+ patFile = arguments_['--pat-file'] ?? (kept || defaultPatFile(environment));
311
+ if (typeof patFile !== 'string' || !isAbsolute(patFile) || resolve(patFile) === resolve(path)) {
312
+ throw new Error('[AZPR] --pat-file must name an absolute path separate from settings.json.');
313
+ }
314
+ next = { ...raw, models: { ...raw.models, review: { functional: model, risk: model, verifier: model }, quick: { reviewer: model } },
315
+ azure: { ...raw.azure, organization, pat: '', patFile } };
316
+ validateSettings(withMissingSettings(next).settings);
317
+ await checkModel(context, model);
318
+ // The PAT file must be usable. Its token goes with what this save leaves when the settings name the file
319
+ // anew; for a file they named already, the token is the one of the look above, whatever is there by now.
320
+ try {
321
+ const digest = digestOf(await readPatFile(patFile));
322
+ if (resolve(patFile) !== resolve(text(raw.azure?.patFile) || '/')) leftDigest = digest;
323
+ }
324
+ catch (error) {
325
+ if (arguments_['--pat-file'] !== undefined) throw error;
326
+ // Name the file setup chose, so the reader knows where to put the PAT.
327
+ const problem = error.message.replace(/^\[AZPR\] azure\.patFile /, '');
328
+ throw new Error(`[AZPR] No --pat-file was given, and the ${kept ? 'PAT file in the current settings' : 'default PAT file'} ${patFile} ${problem} Create it as the quickstart shows, or name another file with --pat-file.`);
329
+ }
330
+ }
331
+ // Each of the other options changes one setting; an answer is checked as the terminal UI's is.
332
+ const changed = [];
333
+ for (const row of ROWS) {
334
+ if (!row.flag || row.flag === '--organization' || arguments_[row.flag] === undefined) continue;
335
+ next = row.set(next, await row.accept(context, arguments_[row.flag], next, row));
336
+ changed.push(row.label);
337
+ }
338
+ const { settings } = withMissingSettings(next);
339
+ validateSettings(settings);
340
+ // Judged on the text this save replaces, not on a second read: whether it is this save that makes the settings usable.
341
+ const unusable = Boolean(held.problem);
342
+ await writeSettings(path, previous, settings);
343
+ return { organization: text(settings.azure?.organization), patFile, changed, first, unusable,
344
+ before: previous === null ? undefined : pairWith(previous, heldDigest), after: pairWith(settingsText(settings), leftDigest) };
167
345
  }
168
346
 
347
+ const mine = info => typeof process.getuid !== 'function' || info.uid === process.getuid();
169
348
  /**
170
- * Replace the settings file (or create it, when `previous` is null) atomically and owner-only, under
171
- * the setup lock, and only while the file still is what `previous` was. The errors of a held lock and
172
- * of a file changed meanwhile are marked `busy`: someone else is writing the file.
173
- *
174
- * The lock keeps other AZPR writers out, not a person's editor. The file is therefore compared with
175
- * `previous` once more after the new text is ready, right before it takes the file's place: what
176
- * someone saved while that text was written is not overwritten.
349
+ * One token as setup writes it and as it finds it in a file it may replace: one word of letters, digits, "-"
350
+ * and "_" that is as long as a token (an Azure DevOps PAT, also an expired one, or a placeholder). The two
351
+ * are the same test, so that what setup wrote it can replace: a line of JSON, a KEY=VALUE pair, a path, an
352
+ * address, a short word or a token with quotes around it is something else.
177
353
  */
178
- async function writeSettings(path, previous, settings, prepared) {
354
+ const TOKEN_WORD = /^[A-Za-z0-9_-]{20,1024}$/;
355
+ /** Why setup does not take a value as the token ('' when it does); it never contains the value. */
356
+ const tokenProblem = value => patProblem(value) || (TOKEN_WORD.test(value) ? ''
357
+ : 'not an Azure DevOps token: it has characters other than letters, digits, "-" and "_" (quotes around it, perhaps)');
358
+ /** The directory of a token file, made where it is missing: the user's own, and no one else may write to it. */
359
+ async function tokenDirectory(parent) {
360
+ await mkdir(parent, { recursive: true, mode: 0o700 });
361
+ const parentInfo = await lstat(parent);
362
+ if (!parentInfo.isDirectory() || (parentInfo.mode & 0o022) || !mine(parentInfo)) {
363
+ throw new Error('[AZPR] The directory of the token file must be a directory owned by you, not a symbolic link or writable by other users.');
364
+ }
365
+ }
366
+
367
+ /**
368
+ * Replace the token file the settings name for this organization: one file that holds only the token,
369
+ * readable by its owner alone (mode 600), in a directory no one else can write to. The new content takes
370
+ * the file's place in one step, so a reader sees the old token or the new one. A path that is anything but
371
+ * a regular file of the user's own is refused and left as it is.
372
+ */
373
+ async function writeTokenFile(path, token) {
374
+ await tokenDirectory(dirname(path));
375
+ const existing = await lstat(path).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
376
+ if (existing && (!existing.isFile() || existing.nlink !== 1 || !mine(existing))) {
377
+ throw new Error('[AZPR] The token file must be a regular file owned by you, without hard links; it was left as it is.');
378
+ }
379
+ // Settings name this path, and settings can be wrong: a file that holds something other than one token
380
+ // (TOKEN_WORD) is not a token file, whatever the settings say, and is never replaced.
381
+ if (existing && existing.size > 0) {
382
+ let content = null;
383
+ if (existing.size <= 4096) {
384
+ const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
385
+ try { content = (await handle.readFile('utf8')).trim(); } finally { await handle.close(); }
386
+ }
387
+ if (content === null || (content !== '' && !TOKEN_WORD.test(content))) {
388
+ throw new Error('[AZPR] The file that azure.patFile names holds something other than one token; it was left as it is. Name another file there, or remove this one.');
389
+ }
390
+ }
391
+ const temporary = `${path}.${randomUUID()}.tmp`;
392
+ let replaced = false;
393
+ try {
394
+ await writeTemporary(temporary, token);
395
+ await rename(temporary, path);
396
+ replaced = true;
397
+ } finally {
398
+ // The token is in place: what cannot be cleaned up after that is no reason to report it as not replaced.
399
+ await unlink(temporary).catch(error => { if (error.code !== 'ENOENT' && !replaced) throw error; });
400
+ }
401
+ }
402
+
403
+ /**
404
+ * Make a token file that did not exist, and return its path: `pat-<organization>` in `directory`, or that
405
+ * name with the first number that is free (`pat-<organization>-2`). The name is taken in one step that
406
+ * refuses a name which exists, so no file is ever overwritten, and no two saves get the same file, whichever
407
+ * settings file each is for: several settings files of one person share AZPR's directory, and their setup
408
+ * locks are not the same lock. Owner-only (mode 600), in a directory no one else can write to.
409
+ */
410
+ async function createTokenFile(directory, organization, token) {
411
+ await tokenDirectory(directory);
412
+ const temporary = join(directory, `pat.${randomUUID()}.tmp`);
413
+ let made = '';
414
+ try {
415
+ await writeTemporary(temporary, token);
416
+ for (let number = 1; number <= 999; number++) {
417
+ const file = join(directory, `pat-${organization.toLowerCase()}${number === 1 ? '' : `-${number}`}`);
418
+ try { await link(temporary, file); made = file; return file; }
419
+ catch (error) { if (error.code !== 'EEXIST') throw error; }
420
+ }
421
+ throw new Error('[AZPR] The directory of the token file has no free name for a token file of this organization; remove the ones that are no longer needed.');
422
+ } finally {
423
+ // The file was made: a temporary name that cannot be removed then is no reason to lose track of it.
424
+ await unlink(temporary).catch(error => { if (error.code !== 'ENOENT' && !made) throw error; });
425
+ }
426
+ }
427
+
428
+ /**
429
+ * Run `work` while holding the setup lock of the settings file `path`. The lock keeps AZPR's writers apart,
430
+ * in this process and in others: whoever finds it held gets an error marked `busy`.
431
+ */
432
+ async function withSetupLock(path, work) {
179
433
  const parent = dirname(path);
180
434
  await mkdir(parent, { recursive: true, mode: 0o700 });
181
435
  const parentInfo = await lstat(parent);
182
436
  if (!parentInfo.isDirectory() || (parentInfo.mode & 0o022) || (typeof process.getuid === 'function' && parentInfo.uid !== process.getuid())) {
183
437
  throw new Error('[AZPR] The settings directory must be a directory owned by you, not a symbolic link or writable by other users.');
184
438
  }
185
- const lock = lockOf(path), temporary = `${path}.${randomUUID()}.tmp`;
186
- const changed = () => Object.assign(new Error('[AZPR] Settings changed during setup; retry after reviewing the file.'), { busy: true });
439
+ const lock = lockOf(path);
187
440
  let handle, acquired = false;
188
441
  try {
189
442
  try { handle = await open(lock, 'wx', 0o600); acquired = true; }
@@ -191,19 +444,45 @@ async function writeSettings(path, previous, settings, prepared) {
191
444
  if (error.code !== 'EEXIST') throw error;
192
445
  throw Object.assign(new Error(`[AZPR] Another setup is active, or its lock was left behind (if none is running, delete ${basename(lock)} beside the settings file). No settings changed.`), { busy: true });
193
446
  }
194
- if (await readExisting(path) !== previous) throw changed();
447
+ return await work();
448
+ } finally {
449
+ // What the work wrote is written: a lock that cannot be removed is reported by the next writer that finds it.
450
+ await handle?.close().catch(() => {});
451
+ if (acquired) await unlink(lock).catch(() => {});
452
+ }
453
+ }
454
+ const settingsChanged = () => Object.assign(new Error('[AZPR] Settings changed during setup; retry after reviewing the file.'), { busy: true });
455
+
456
+ /**
457
+ * Under the setup lock: replace the settings file (or create it, when `previous` is null) atomically and
458
+ * owner-only, and only while the file still is what `previous` was. A file changed meanwhile is the
459
+ * `busy` error: someone else wrote it.
460
+ *
461
+ * The lock keeps other AZPR writers out, not a person's editor. The file is therefore compared with
462
+ * `previous` once more after the new text is ready, right before it takes the file's place: what
463
+ * someone saved while that text was written is not overwritten.
464
+ */
465
+ async function replaceSettings(path, previous, settings, prepared) {
466
+ const temporary = `${path}.${randomUUID()}.tmp`;
467
+ let committed = false;
468
+ try {
469
+ if (await readExisting(path) !== previous) throw settingsChanged();
195
470
  await writeTemporary(temporary, settingsText(settings));
196
471
  await prepared?.();
197
- if (await readExisting(path) !== previous) throw changed();
472
+ if (await readExisting(path) !== previous) throw settingsChanged();
198
473
  if (previous === null) await link(temporary, path); // Refuse a concurrent creator rather than overwriting it.
199
474
  else await rename(temporary, path);
475
+ committed = true;
200
476
  } finally {
201
- await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; });
202
- await handle?.close();
203
- if (acquired) await unlink(lock);
477
+ // Once the new text is in place the write has happened: a temporary file that cannot be removed then is
478
+ // left behind, and is no reason to report the write as failed (a caller would undo what belongs to it).
479
+ await unlink(temporary).catch(error => { if (error.code !== 'ENOENT' && !committed) throw error; });
204
480
  }
205
481
  }
206
482
 
483
+ /** Replace the settings file under the setup lock; see `replaceSettings`. */
484
+ const writeSettings = (path, previous, settings, prepared) => withSetupLock(path, () => replaceSettings(path, previous, settings, prepared));
485
+
207
486
  async function writeTemporary(path, text) {
208
487
  const handle = await open(path, 'wx', 0o600);
209
488
  try { await handle.writeFile(text); await handle.sync(); } finally { await handle.close(); }
@@ -273,13 +552,17 @@ async function guide(context, path, problem, environment) {
273
552
  try { catalog = (listOf(await context.model.list()) ?? []).filter(item => item.enabled !== false && item.capabilities?.tools === true); } catch { /* Help remains usable before provider setup. */ }
274
553
  try { patFile = defaultPatFile(environment); } catch { patFile = '$XDG_CONFIG_HOME/azpr/pat'; }
275
554
  const models = catalog.slice(0, 12).map(item => `${item.providerID}/${item.id}`);
555
+ const options = ROWS.filter(row => row.flag && row.flag !== '--organization').map(row => `${row.flag} ${row.other ? 'TAG' : row.kind === 'choice' ? row.choices.map(choice => choice.value).join('|')
556
+ : row.kind === 'model' ? `PROVIDER/MODEL${row.optional ? '|off' : ''}` : row.id === 'proxy' ? 'URL|none' : 'PATH|none'}`);
276
557
  return `[AZPR] SETUP${problem ? ' REQUIRED' : ''}\nSettings: ${path}\n${problem ? `Problem when OpenCode loaded AZPR: ${problem}\n` : ''}\n` +
558
+ 'In OpenCode\'s terminal UI, /pr-setup alone asks for the organization, an optional proxy, the token and a model in dialogs, checks the token with Azure DevOps and saves it for you; afterwards it lists the settings to change. In other clients, or to script it:\n\n' +
277
559
  `1. Connect your provider in OpenCode and choose one tool-capable model ID (${models.length ? models.join(', ') : 'run opencode models'}).\n` +
278
560
  `2. Create an Azure DevOps PAT for one organization with Code (Read) and Pull Request Threads (Read & write). Keep it alone in a regular file owned by you, with mode 600 (by default ${patFile}); never paste it into this conversation.\n` +
279
561
  `3. Run ${USAGE}\n\n` +
280
562
  '--organization also takes a PR or organization URL. Without --pat-file, setup uses the default PAT file, or with --replace the PAT file already set. ' +
281
- 'The selected model fills the three review roles and the quick reviewer. Deep remains unchanged (off for a new profile). Existing settings require --replace; other settings are kept. No model request or Azure request is made.\n' +
282
- `After saving, ${RESTART}, then run /pr-check <PR URL>. Settings changes do not affect reviews already running.`;
563
+ 'The selected model fills the three review roles and the quick reviewer. Deep remains unchanged (off for a new profile). Existing settings require --replace for these three options; other settings are kept. No model request or Azure request is made.\n\n' +
564
+ `One setting of existing settings is changed without --replace: ${options.join(', ')}.\n\n` +
565
+ `A first setup is loaded at once. After a later change, ${RESTART}. Then run /pr-check <PR URL>. Settings changes do not affect reviews already running.`;
283
566
  }
284
567
 
285
568
  /**
@@ -292,66 +575,602 @@ async function settingsProblem(path) {
292
575
  let text;
293
576
  try { text = await readFile(path, 'utf8'); }
294
577
  catch (error) { return { problem: error.code === 'ENOENT' ? 'there is no settings file yet.' : `the settings file could not be read (${error.code ?? 'unknown error'}).` }; }
578
+ return settingsTextProblem(text);
579
+ }
580
+ /**
581
+ * The same for a settings text that was read already (null: there is no file), so that a save judges the text
582
+ * it replaces; with `digest`, the digest of the token in the file the text names ('' where it names none or
583
+ * the file cannot be read). Both come from one read of that file: whether the settings can be used and which
584
+ * token goes with them are then said of the same moment.
585
+ */
586
+ async function settingsTextProblem(text) {
587
+ if (text === null) return { problem: 'there is no settings file yet.', digest: '' };
588
+ let settings;
295
589
  try {
296
590
  const raw = settingsJSON(text);
297
- if (raw.enabled === false) return { disabled: true, problem: '' };
298
- const settings = validateSettings(raw);
299
- if (settings.azure.patFile) await readPatFile(settings.azure.patFile);
300
- return { problem: '' };
591
+ if (raw.enabled === false) return { disabled: true, problem: '', digest: await tokenDigest(text) };
592
+ settings = validateSettings(raw);
301
593
  } catch (error) {
302
- return { problem: error instanceof Error && error.message ? error.message.replace(/^\[AZPR\] /, '') : 'the settings could not be loaded.' };
594
+ return { problem: error instanceof Error && error.message ? error.message.replace(/^\[AZPR\] /, '') : 'the settings could not be loaded.', digest: await tokenDigest(text) };
595
+ }
596
+ if (!settings.azure.patFile) return { problem: '', digest: '' };
597
+ try { return { problem: '', digest: digestOf(await readPatFile(settings.azure.patFile)) }; }
598
+ catch (error) { return { problem: error instanceof Error && error.message ? error.message.replace(/^\[AZPR\] /, '') : 'the settings could not be loaded.', digest: '' }; }
599
+ }
600
+
601
+ /** A token as it may be compared and remembered: a digest, never the token. */
602
+ const digestOf = token => createHash('sha256').update(token).digest('hex');
603
+ /** The digest of the token in the file a settings text names; '' where it names none or the file cannot be read. */
604
+ async function tokenDigest(text) {
605
+ try {
606
+ const file = settingsJSON(text).azure?.patFile;
607
+ if (typeof file === 'string' && file) return digestOf(await readPatFile(file));
608
+ } catch { /* A text that is no settings, or a token file that cannot be read: no token to tell apart. */ }
609
+ return '';
610
+ }
611
+ /** A settings text and the token that goes with it (as its digest), as one value to compare. */
612
+ const pairWith = (text, digest) => `${digest}\n${text}`;
613
+ /** What a settings text and the token file it names hold at this moment; undefined for no settings file. */
614
+ const pairOf = async text => typeof text === 'string' ? pairWith(text, await tokenDigest(text)) : undefined;
615
+
616
+ /** What an error may say to the person who is setting AZPR up: AZPR's own words, and never an OS or parser message. */
617
+ const said = (error, fallback) => typeof error?.message === 'string' && error.message.startsWith('[AZPR] ') ? error.message.slice(7) : fallback;
618
+
619
+ /** What Azure DevOps or the way to it refused, in setup's words, and which answer to ask for again (`fix`). */
620
+ function accessProblem(error, organization, proxy) {
621
+ if (!(error instanceof AzureError)) return { fix: '', problem: 'The check could not be run.' };
622
+ const status = error.status ? ` (HTTP ${error.status})` : '';
623
+ const code = [error.code, error.cause?.cause?.code, error.cause?.code].find(value => typeof value === 'string' && /^[A-Za-z][A-Za-z0-9_]{2,40}$/.test(value));
624
+ switch (error.kind) {
625
+ case 'auth': return { fix: 'token', problem: `Azure DevOps did not accept this token for the organization "${organization}"${status}. It may be mistyped or expired, or belong to another organization.` };
626
+ case 'permission': return { fix: 'token', problem: `Azure DevOps accepted the token but did not let it list pull requests${status}. It needs the scopes Code (Read) and Pull Request Threads (Read & write).` };
627
+ case 'not-found': return { fix: 'organization', problem: `Azure DevOps knows no organization named "${organization}"${status}.` };
628
+ case 'tls': return { fix: 'caFile', problem: `The TLS certificate of the connection was not accepted${code ? ` (${code})` : ''}. A proxy that inspects HTTPS needs its root CA certificate.` };
629
+ case 'proxy': return { fix: 'proxy', problem: error.status === 407 ? 'The proxy asks for a user name and password (HTTP 407).' : `A proxy or gateway answered instead of Azure DevOps${status}.` };
630
+ case 'timeout': return { fix: 'proxy', problem: `Azure DevOps did not answer within ${Math.round(CHECK_TIMEOUT_MS / 1000)} seconds.${proxy ? '' : ' This network may need a proxy.'}` };
631
+ case 'network': return { fix: 'proxy', problem: `Azure DevOps could not be reached${code ? ` (${code})` : ''}.${proxy ? ` Check the proxy ${shownProxy(proxy)}.` : ' This network may need a proxy.'}` };
632
+ case 'throttled': case 'server': return { fix: '', problem: `Azure DevOps answered with an error${status}. Try again in a moment.` };
633
+ default: return { fix: '', problem: `Azure DevOps answered in a way setup does not know${status}.` };
634
+ }
635
+ }
636
+
637
+ /**
638
+ * Setup for one settings file: what the RPC of the terminal UI's dialogs calls. `loaded()` says what this
639
+ * process has in use: `blocked` (no usable settings were found), `problem` (why) and `drift()` (the loaded
640
+ * runtime's own answer to whether the settings file and the PAT file are still what it read).
641
+ * `saved({ made, before, after })` is told after every save that succeeded: whether it made unusable
642
+ * settings usable (the settings it replaced could not be used, and it wrote something), and what the
643
+ * settings and the token file they name held when it read them and what it leaves (`pairWith`: the text
644
+ * in the file after it with the token it wrote, or else the one it found).
645
+ * `options` are the runtime's test options (fetch, azureBaseUrl), `checkTimeoutMs` and, for offline tests,
646
+ * `settingsPrepared` (runs when a save's new settings text is ready, before it replaces the file).
647
+ * `turn.busy` is the one turn of this server part's setup: a save takes it from its first read to the end
648
+ * of what follows it (the load of a first setup), and so does /pr-setup with options.
649
+ */
650
+ function createSetupService({ context, path, environment, options, loaded, saved, turn }) {
651
+ // One request at a time, and none of them waits long: this queue is setup's own, since it must work before
652
+ // there are settings, and so before the runtime and its queue exist.
653
+ const queue = createToolQueue({ concurrency: 1, timeoutMs: options.checkTimeoutMs ?? CHECK_TIMEOUT_MS });
654
+ const home = environment.HOME || homedir();
655
+ const shownPath = value => home && value.startsWith(`${home}/`) ? `~/${value.slice(home.length + 1)}` : value;
656
+
657
+ /** The settings file as setup may change it: its text (null: none yet), its content, and why it cannot be changed. */
658
+ async function current() {
659
+ let previous;
660
+ try { previous = await readExisting(path); }
661
+ catch (error) { return { previous: undefined, raw: null, fileProblem: said(error, `The settings file could not be read (${error?.code ?? 'unknown error'}).`) }; }
662
+ if (previous === null) return { previous, raw: { version: 2 }, fileProblem: '' };
663
+ try {
664
+ const raw = settingsJSON(previous);
665
+ if (raw.version !== 2) throw new Error('[AZPR] Setup supports only version-2 settings.');
666
+ for (const name of ['models', 'azure', 'debug', 'afterReview']) if (raw[name] !== undefined && !object(raw[name])) throw new Error(`[AZPR] "${name}" in the settings file is not a JSON object.`);
667
+ if (object(raw.models)) for (const mode of MODES) if (raw.models[mode] !== undefined && !object(raw.models[mode])) throw new Error(`[AZPR] "models.${mode}" in the settings file is not a JSON object.`);
668
+ return { previous, raw, fileProblem: '' };
669
+ } catch (error) { return { previous, raw: null, fileProblem: said(error, 'The settings file could not be read as settings.') }; }
670
+ }
671
+ /**
672
+ * Whether a token is saved and can be used, how the list shows that, and what its dialog adds; never the
673
+ * token. A saved token is what the settings name, as the runtime reads it: `azure.patFile`, else
674
+ * `azure.pat`. The default PAT file is none unless they name it: every settings file a person has may use it.
675
+ */
676
+ async function tokenState(raw) {
677
+ // A token is saved for an organization. Where the settings name none, a token that is there belongs to none
678
+ // yet: it is not offered, since a check would not send it.
679
+ const owned = Boolean(text(azureOf(raw).organization));
680
+ const file = text(azureOf(raw).patFile);
681
+ if (!file) {
682
+ return text(azureOf(raw).pat)
683
+ ? { saved: owned && !patProblem(azureOf(raw).pat), shown: 'in the settings file', note: 'A new token is saved in a file of its own instead of in the settings file.' }
684
+ : { saved: false, shown: 'not set', note: '' };
685
+ }
686
+ try {
687
+ await readPatFile(file);
688
+ return owned ? { saved: true, shown: 'saved', note: `The saved token is in ${shownPath(file)}.` }
689
+ : { saved: false, shown: 'saved without an organization', note: `The token in ${shownPath(file)} was saved without an organization and is not used; the token you enter gets a file of its own.` };
690
+ }
691
+ catch (error) {
692
+ if (/\(not found\)/.test(error.message)) return { saved: false, shown: 'not set', note: '' };
693
+ return { saved: false, shown: 'cannot be used', note: `The token file ${shownPath(file)} ${said(error, 'could not be read.').replace(/^azure\.patFile /, '')}` };
694
+ }
695
+ }
696
+
697
+ /** Whether the loaded runtime refuses new runs because the settings file or the PAT file changed since it read them. */
698
+ const drifted = async use => {
699
+ // No answer is no "nothing changed": a runtime that loaded nothing (settings switched off) has read none.
700
+ if (typeof use.drift !== 'function') return true;
701
+ try { return Boolean(await use.drift()); } catch { return true; }
702
+ };
703
+
704
+ async function status() {
705
+ const { previous, raw, fileProblem } = await current();
706
+ const view = withMissingSettings(raw ?? { version: 2 }).settings;
707
+ const token = await tokenState(view);
708
+ const use = loaded();
709
+ // A process that found no usable settings: setup is required while there are none, and once there are some
710
+ // that it has not loaded (another process's setup or an editor made them usable, or loading them failed),
711
+ // they wait for the restart. Without a settings file there is nothing to list, also while a runtime still
712
+ // works with the file that was there: setup starts again, and what it saves then waits for the restart.
713
+ // For settings in use the runtime itself says whether it would refuse new runs, by the rule of its
714
+ // preflight: any difference of the settings text but the defaults a load wrote into it, and any other
715
+ // content of the PAT file, whoever wrote them.
716
+ const state = use.blocked ? ((await settingsProblem(path)).problem ? 'required' : 'restart')
717
+ : previous === null ? 'required'
718
+ : (await drifted(use)) ? 'restart' : 'ready';
719
+ return { version: 1, state, problem: use.blocked ? use.problem : '', editable: raw !== null, fileProblem,
720
+ settingsFile: path, settingsFileShown: shortPath(shownPath(path)), organization: text(azureOf(view).organization),
721
+ rows: ROWS.map(row => row.kind === 'secret'
722
+ ? { id: row.id, group: row.group, label: row.label, kind: row.kind, title: row.title, description: `${row.description(view, environment)}${token.note ? ` ${token.note}` : ''}`, value: token.shown, saved: token.saved,
723
+ // Whether the settings name a token at all, usable or not: another organization then needs one of its own.
724
+ bound: Boolean(text(azureOf(view).patFile) || text(azureOf(view).pat)) }
725
+ : { id: row.id, group: row.group, label: row.label, kind: row.kind, title: row.title, value: row.show(row.get(view)), current: row.current(row.get(view)),
726
+ ...(row.description ? { description: row.description(view, environment) } : {}), ...(row.placeholder ? { placeholder: row.placeholder } : {}),
727
+ ...(row.optional ? { optional: row.optional } : {}), ...(row.choices ? { choices: row.choices } : {}), ...(row.other ? { other: row.other } : {}) }) };
728
+ }
729
+
730
+ /** An answer that is given is text, as a dialog gives it: anything else is no answer, not an empty one. */
731
+ const textual = (input, names) => {
732
+ for (const name of names) if (input[name] !== undefined && typeof input[name] !== 'string') throw new Error('[AZPR] Setup takes each answer as text.');
733
+ };
734
+
735
+ /** The answers of `changes` in their saved form, applied to `raw`; `model` stands for the review and the quick model. */
736
+ async function apply(raw, changes) {
737
+ if (!object(changes)) throw new Error('[AZPR] Setup was given no settings to change.');
738
+ let next = raw;
739
+ const values = {}, shown = {};
740
+ for (const [id, answer] of Object.entries(changes)) {
741
+ const rows = id === 'model' ? [rowOf('reviewModel'), rowOf('quickModel')] : [rowOf(id)];
742
+ if (rows.some(row => !row?.set)) throw new Error('[AZPR] Setup does not know one of the settings it was given.');
743
+ // Every answer is text, as a dialog or an option gives it: anything else is no answer, not an empty one.
744
+ if (typeof answer !== 'string') throw new Error('[AZPR] Setup takes each setting as text.');
745
+ for (const row of rows) {
746
+ const value = await row.accept(context, answer, next, row);
747
+ next = row.set(next, value);
748
+ // What goes back to the dialog is the answer in its saved form, but never a proxy's user name and
749
+ // password: not the saved one's (a proxy left as the dialog showed it stands for the saved one), and
750
+ // not those of a proxy that was just typed either. For such a proxy nothing goes back, and the dialog
751
+ // keeps what was typed.
752
+ if (row.id === 'proxy' && value && shownProxy(value).endsWith(')')) { if (text(answer).trim() !== value) values[id] = text(answer).trim(); }
753
+ else values[id] = row.kind === 'choice' && typeof value === 'boolean' ? (value ? 'on' : 'off') : value;
754
+ shown[id] = row.show(row.get(withMissingSettings(next).settings));
755
+ }
756
+ }
757
+ return { next, values, shown };
758
+ }
759
+
760
+ /** Whether answers can be used, without saving them: their saved form and how they may be shown. */
761
+ async function validate(input) {
762
+ const { raw, fileProblem } = await current();
763
+ if (raw === null) return { ok: false, problem: fileProblem };
764
+ const { values, shown } = await apply(raw, input?.changes);
765
+ return { ok: true, values, shown };
303
766
  }
767
+
768
+ /**
769
+ * Ask Azure DevOps once whether a token works for an organization. A token that is given is checked
770
+ * through the proxy and with the CA file given, else the saved ones. Without a token the saved one is
771
+ * checked, and it goes only where the saved settings send it: to the organization it was saved for,
772
+ * through the saved proxy and with the saved CA file. (A proxy and a CA file that the caller chooses
773
+ * could otherwise read a token the caller does not have.)
774
+ */
775
+ async function check(input) {
776
+ textual(input, ['organization', 'token', 'proxy', 'caFile']);
777
+ const { raw, fileProblem } = await current();
778
+ if (raw === null) return { ok: false, fix: '', problem: fileProblem };
779
+ const view = withMissingSettings(raw).settings;
780
+ const organization = organizationOf(input.organization ?? azureOf(view).organization);
781
+ const savedProxy = text(azureOf(view).proxy), savedCaFile = text(azureOf(view).caFile);
782
+ const proxy = input.proxy !== undefined ? proxyOf(input.proxy, savedProxy) : savedProxy;
783
+ const caFile = input.caFile !== undefined ? await caFileOf(input.caFile) : savedCaFile;
784
+ let token;
785
+ if (input.token !== undefined) {
786
+ token = text(input.token).trim();
787
+ const problem = tokenProblem(token);
788
+ if (problem) return { ok: false, fix: 'token', problem: `That is ${problem}.` };
789
+ } else {
790
+ const saved = text(azureOf(view).organization);
791
+ if (organization.toLowerCase() !== saved.toLowerCase()) {
792
+ return { ok: false, fix: 'token', problem: saved ? `The saved token was saved for the organization "${saved}". Enter a token of "${organization}".` : 'No token is saved for an organization yet.' };
793
+ }
794
+ if (proxy !== savedProxy || caFile !== savedCaFile) {
795
+ return { ok: false, fix: 'token', problem: 'The saved token is checked only through the saved proxy and with the saved CA certificate file. Enter the token to check it with the ones given here.' };
796
+ }
797
+ const file = text(azureOf(view).patFile);
798
+ if (!file && !text(azureOf(view).pat)) return { ok: false, fix: 'token', problem: 'No token is saved yet.' };
799
+ try { token = file ? await readPatFile(file) : azureOf(view).pat; }
800
+ catch (error) { return { ok: false, fix: 'token', problem: `The saved token cannot be used: ${said(error, 'its file is unreadable').replace(/^azure\.patFile /, 'its file ')}` }; }
801
+ }
802
+ const transport = fetchTransport({ proxy, caCertificates: await readCaCertificates(caFile), verifyTls: azureOf(view).verifyTls !== false });
803
+ if (Object.keys(transport).length && !options.fetch && !fetchTransportSupported()) {
804
+ return { ok: false, fix: '', problem: 'A proxy and a CA file need OpenCode\'s own runtime; this one would ignore them.' };
805
+ }
806
+ const client = createAzureClient({ organization, pat: token, baseUrl: restBaseUrl(options.azureBaseUrl ?? environment.AZPR_TEST_AZURE_BASE_URL),
807
+ transport, queue, retryDelayMs: 0, fetch: options.fetch });
808
+ try {
809
+ await client.access({ controller: new AbortController() });
810
+ return { ok: true, organization };
811
+ } catch (error) { return { ok: false, ...accessProblem(error, organization, proxy) }; }
812
+ }
813
+
814
+ /**
815
+ * Save answers and, when one was given, the token.
816
+ *
817
+ * A token is saved for an organization: the one this save sets, or the one it was checked for, which must
818
+ * still be the one in the settings. Organization and token change in one step, the write of the settings
819
+ * file. A token of the organization the settings named already replaces the token file they name. Every
820
+ * other token gets a file that did not exist (`createTokenFile`), which the settings name in the same
821
+ * write: a first setup's, another organization's, and one for settings that name the default PAT file,
822
+ * which every settings file a person has may use. So setup overwrites no file but the one these settings
823
+ * name for this organization, and whoever reads the settings and then the file they name has a token of
824
+ * that organization, also while a save is under way and after one that failed or was cut short.
825
+ *
826
+ * Both files are written under the setup lock, the token first, and only while the settings file still
827
+ * is what the answers were checked against. A token file this save made is removed again when the
828
+ * settings are not written: nothing names it.
829
+ */
830
+ async function save(input) {
831
+ if (turn.busy) return { ok: false, problem: 'Another setup is being saved.' };
832
+ turn.busy = true;
833
+ try {
834
+ textual(input, ['token', 'organization']);
835
+ const { previous, raw, fileProblem } = await current();
836
+ if (raw === null) return { ok: false, problem: fileProblem };
837
+ // Whether it is this save that makes the settings usable, judged on the text it replaces: only then are
838
+ // they this setup's to load. And the token that goes with them, from the same look, to tell later
839
+ // whether anything else wrote the settings or the token in between.
840
+ const held = await settingsTextProblem(previous);
841
+ const unusable = loaded().blocked && Boolean(held.problem), heldDigest = held.digest;
842
+ let { next } = await apply(raw, input.changes ?? {});
843
+ const before = withMissingSettings(raw).settings;
844
+ const was = text(azureOf(before).organization), named = text(azureOf(next).organization);
845
+ // The organization these settings name changes: from one to another, or from none to one.
846
+ const changed = named.toLowerCase() !== was.toLowerCase(), another = changed && Boolean(was);
847
+ // The file the token of these settings was in until now, where they named an organization and a token file.
848
+ const source = was ? text(azureOf(before).patFile) : '';
849
+ let token, directory = '';
850
+ if (input.token !== undefined) {
851
+ token = text(input.token).trim();
852
+ const problem = tokenProblem(token);
853
+ if (problem) return { ok: false, problem: `The token is ${problem}.` };
854
+ const expected = input.organization !== undefined ? organizationOf(input.organization) : Object.hasOwn(input.changes ?? {}, 'organization') ? named : '';
855
+ if (!expected) return { ok: false, problem: 'A token is saved for an organization: name the one it was checked for.' };
856
+ if (expected.toLowerCase() !== named.toLowerCase()) {
857
+ return { ok: false, problem: `The token was checked for the organization "${expected}", but the settings name ${named ? `"${named}"` : 'none'} now. Nothing was saved; run /pr-setup again.` };
858
+ }
859
+ const kept = text(azureOf(next).patFile);
860
+ if (kept && (!isAbsolute(kept) || resolve(kept) === resolve(path))) return { ok: false, problem: 'The token file must be an absolute path other than the settings file.' };
861
+ // Replaced where it is only when these settings name the file for this very organization, and it is not
862
+ // the default PAT file. Otherwise a file is made beside it, or in AZPR's directory; until it is made,
863
+ // the settings are checked with the name it will have if that name is free.
864
+ if (!(kept && was && !another && resolve(kept) !== resolve(defaultPatFile(environment)))) directory = dirname(kept || defaultPatFile(environment));
865
+ next = withAzure(next, { pat: '', patFile: directory ? join(directory, `pat-${named.toLowerCase()}`) : kept });
866
+ } else if (changed && (text(azureOf(before).patFile) || text(azureOf(before).pat))) {
867
+ // Without a new token, the one these settings name would pass to an organization it was not saved for:
868
+ // also a token that cannot be read at the moment (its file may be readable again later), and also one
869
+ // that was saved for no organization.
870
+ return { ok: false, problem: `${was ? `The saved token was saved for the organization "${was}". Another organization` : 'The token these settings name was saved without an organization. An organization'} needs a token of its own: enter it together with the organization.` };
871
+ }
872
+ let { settings } = withMissingSettings(next);
873
+ valid(validateSettings, settings);
874
+ let written = settingsText(settings), wrote = false, made = '', onDisk = previous;
875
+ if (token !== undefined || written !== previous) {
876
+ await withSetupLock(path, async () => {
877
+ // Once more, under the lock and before anything is written: the file still is what the answers were
878
+ // checked against.
879
+ if (await readExisting(path) !== previous) throw settingsChanged();
880
+ let replaced = false;
881
+ try {
882
+ if (directory) {
883
+ made = await createTokenFile(directory, named, token);
884
+ ({ settings } = withMissingSettings(withAzure(next, { patFile: made })));
885
+ valid(validateSettings, settings);
886
+ written = settingsText(settings);
887
+ } else if (token !== undefined) {
888
+ // The token that is already there is left as it is: nothing changed, so nothing waits for a restart.
889
+ const differs = !(await readPatFile(settings.azure.patFile).then(kept => kept === token, () => false));
890
+ if (differs) { await writeTokenFile(settings.azure.patFile, token); replaced = true; }
891
+ }
892
+ if (written !== previous) { await replaceSettings(path, previous, settings, options.settingsPrepared); onDisk = written; }
893
+ wrote = Boolean(made) || replaced || written !== previous;
894
+ } catch (error) {
895
+ // The file this save made is named by nothing: it is taken away again, and the organization and its
896
+ // token are as they were.
897
+ if (made) { await unlink(made).catch(() => {}); made = ''; throw error; }
898
+ if (!replaced) throw error;
899
+ // The token file the settings name has the new token by now: say so, since the answer otherwise
900
+ // reads as if nothing had changed.
901
+ throw new Error(`[AZPR] The token was saved, but the settings were not: ${said(error, 'the settings file could not be written.')}`);
902
+ }
903
+ });
904
+ }
905
+ // What this save leaves is said from what it wrote: the text that is in the file after it, and the token
906
+ // it was given, or else the one that was there when it read the settings. Never from another look at the
907
+ // files, which could be at what another writer put there since.
908
+ await saved({ made: unusable && wrote, before: typeof previous === 'string' ? pairWith(previous, heldDigest) : undefined,
909
+ after: pairWith(onDisk, token !== undefined ? digestOf(token) : heldDigest) });
910
+ // The token these settings had before is still in its file: a person decides what becomes of it.
911
+ const stays = made && source && resolve(source) !== resolve(made) && await readPatFile(source).then(() => true, () => false);
912
+ return { ok: true, status: await status(),
913
+ ...(stays ? { note: `The ${another ? `token of "${was}"` : 'earlier token'} is still in ${shownPath(source)}. Delete that file if you no longer need it.` } : {}) };
914
+ } finally { turn.busy = false; }
915
+ }
916
+
917
+ /** An RPC handler never throws: what went wrong is an answer, in AZPR's own words, and holds no value it was given. */
918
+ const answer = (handler, fallback) => async input => {
919
+ try { return await handler(object(input) ? input : {}); }
920
+ catch (error) { return { ok: false, fix: '', problem: said(error, fallback) }; }
921
+ };
922
+ return {
923
+ status: answer(status, 'AZPR\'s settings could not be read.'),
924
+ validate: answer(validate, 'That value could not be checked.'),
925
+ check: answer(check, 'The token could not be checked.'),
926
+ save: answer(save, 'The settings could not be saved; nothing was changed. Check the file permissions of the settings directory.'),
927
+ };
304
928
  }
305
929
 
306
930
  /** Missing/invalid settings expose only setup and blocked command explanations, with the reason. */
307
931
  export async function setupPlugin(context, sourceDirectory = SOURCE_DIRECTORY, testOptions = {}) {
308
- const { environment = process.env, settingsWaitMs, ...runtimeOptions } = testOptions;
932
+ const { environment = process.env, settingsWaitMs, checkTimeoutMs, releaseWaitMs = RELEASE_WAIT_MS, settingsPrepared, ...runtimeOptions } = testOptions;
309
933
  const path = await settingsFileFor(context.options ?? {}, sourceDirectory, environment);
310
- const { problem, disabled } = await settingsProblem(path);
311
- const blocked = Boolean(problem);
312
- if (disabled) return async () => {};
934
+ const first = await settingsProblem(path);
935
+ if (first.disabled) return async () => {};
313
936
  requireMethods(context, ['command.list', 'command.transform'], 'AZPR setup');
314
937
  const catalog = listOf(await context.command.list());
315
938
  if (!catalog) throw new Error('[AZPR] Invalid OpenCode command catalog.');
316
- const reserved = ['pr-setup', ...(blocked ? Object.keys(COMMANDS) : [])];
939
+ // What this process has in use: nothing while `blocked`, else a runtime, whose `drift()` says whether the
940
+ // settings file and the PAT file still are what it read. `own`: what the settings and the token file they
941
+ // name hold (`pairOf`) while they are this process's to load, because a save of its own setup made the
942
+ // settings usable and everything since was written by a save of that setup; undefined once anything else
943
+ // wrote either file.
944
+ const use = { blocked: Boolean(first.problem), problem: first.problem, loadProblem: '', drift: undefined, own: undefined };
945
+ /** What the settings file and the token file it names hold at this moment. */
946
+ const pairNow = async () => pairOf(await readFile(path, 'utf8').catch(() => null));
947
+ const reserved = ['pr-setup', ...(use.blocked ? Object.keys(COMMANDS) : [])];
317
948
  if (catalog.some(command => reserved.includes(command.name))) throw new Error('[AZPR] Reserved command name conflict; resolve it before loading AZPR.');
318
- let pending = false;
949
+ let cleanup, placeholders, activating, rpc, closed = false;
950
+ // What changes this plugin's review commands runs one after another: the load of a first setup, which
951
+ // takes the commands that say "setup required" away and registers the runtime's, and putting those commands
952
+ // back. Neither sees the other half done, and what one read of the host is not older than the other's work.
953
+ let lane = Promise.resolve();
954
+ const inLane = job => {
955
+ const run = lane.then(job, job);
956
+ lane = run.catch(() => {});
957
+ return run;
958
+ };
959
+ // One save at a time, whichever way it comes in (the dialogs' RPC or /pr-setup with options), until what
960
+ // follows it has ended: a second save during the load of a first setup would change what is being loaded.
961
+ const turn = { busy: false };
962
+ /**
963
+ * The review command names that another plugin has by now: what is listed under one of them and is not a
964
+ * command that only says "setup required". Asked right before those commands are registered, since a
965
+ * plugin can take a name at any moment. Null where the host does not answer: nothing is known then, and
966
+ * what was known earlier is not.
967
+ */
968
+ const taken = async () => {
969
+ try {
970
+ const listed = listOf(await context.command.list());
971
+ return listed && new Set(listed.filter(command => Object.hasOwn(COMMANDS, command?.name) && command.description !== PLACEHOLDER_DESCRIPTION).map(command => command.name));
972
+ } catch { return null; }
973
+ };
974
+
975
+ /** Load the runtime with the settings as they are now. */
976
+ const load = async () => {
977
+ // Before the runtime reads the settings for good: it compares later reads with this one.
978
+ const completion = await addMissingSettings(path, settingsWaitMs === undefined ? {} : { waitMs: settingsWaitMs, pauseMs: 10 });
979
+ const loaded = await setupAzurePrReview(context, sourceDirectory, { ...runtimeOptions, settingsPath: path, settingsCompletion: completion });
980
+ use.drift = typeof loaded?.settingsDrift === 'function' ? loaded.settingsDrift : undefined;
981
+ return loaded;
982
+ };
983
+ /**
984
+ * The commands of a process that found no usable settings: each says so. They load nothing, also when the
985
+ * settings can be used by now: settings that this process's own setup did not save (another process's, or an
986
+ * edit) are read after a restart, as always.
987
+ */
988
+ const registerPlaceholders = (taken = new Set()) => context.command.transform(editor => {
989
+ // Adding a command replaces the one that has its name: a name another plugin took meanwhile stays its own.
990
+ for (const name of Object.keys(COMMANDS)) if (!taken.has(name)) editor.add({ name, description: PLACEHOLDER_DESCRIPTION, async execute(event) {
991
+ const now = await settingsProblem(path);
992
+ const usable = !now.problem && !now.disabled;
993
+ await appendReport(context, { sessionID: event.sessionID, text: !usable
994
+ ? `[AZPR] SETUP REQUIRED\nNo review or Azure request was started. Settings at ${path} could not be used when OpenCode loaded AZPR: ${now.problem || use.problem} Run /pr-setup (in the terminal UI it asks in dialogs; --help shows the options); repair an existing settings file if necessary, then ${RESTART}.`
995
+ : use.loadProblem
996
+ ? `[AZPR] RESTART REQUIRED\nNo review or Azure request was started. The settings at ${path} are saved, but AZPR could not load them: ${use.loadProblem} Repair that, then ${RESTART}.`
997
+ : `[AZPR] RESTART REQUIRED\nNo review or Azure request was started. The settings at ${path} can be used now, but AZPR found no usable settings when OpenCode loaded it for this project directory, and these were saved elsewhere: by a setup in another project directory or another OpenCode process, or by hand. To load them, ${RESTART}.` });
998
+ } });
999
+ });
1000
+ /**
1001
+ * A first setup takes effect without a restart: nothing was loaded before, so loading the settings now
1002
+ * is the one time they are read. Only `afterSave` calls it. Returns whether the runtime is loaded afterwards.
1003
+ */
1004
+ function activate() {
1005
+ if (!use.blocked) return Promise.resolve(true);
1006
+ if (closed) return Promise.resolve(false);
1007
+ activating ??= inLane(async () => {
1008
+ try {
1009
+ const now = await settingsProblem(path);
1010
+ if (now.problem || now.disabled) { use.problem = now.problem || 'AZPR is switched off in its settings (enabled: false).'; return false; }
1011
+ // Only what this setup saved is this process's to load. What took its place since (another process's
1012
+ // setup, an editor; the settings or the token) waits for the restart, like every change from elsewhere.
1013
+ if (use.own === undefined || await pairNow() !== use.own) {
1014
+ use.own = undefined;
1015
+ use.loadProblem = '';
1016
+ return false;
1017
+ }
1018
+ // The runtime refuses command names that exist: the commands that only said "setup required" go first.
1019
+ await placeholders?.dispose();
1020
+ placeholders = undefined;
1021
+ // The host may list them a moment longer. What is listed under a review command's name and is not one
1022
+ // of them is another plugin's command: the runtime will refuse to load beside it.
1023
+ for (const until = Date.now() + releaseWaitMs; ; ) {
1024
+ const listed = (listOf(await context.command.list()) ?? []).filter(command => Object.hasOwn(COMMANDS, command?.name));
1025
+ if (listed.every(command => command.description !== PLACEHOLDER_DESCRIPTION) || Date.now() >= until) break;
1026
+ await new Promise(done => setTimeout(done, 50));
1027
+ }
1028
+ let outcome; // 'loaded', 'failed' (use.loadProblem says why), 'replaced' or 'closed'
1029
+ try {
1030
+ cleanup = await load();
1031
+ // The runtime read the files a moment after they were compared above. What it read is what they hold
1032
+ // now (its own answer), and what they hold now must be what this setup saved.
1033
+ // A load that answers neither (settings switched off meanwhile load nothing) is no load of them.
1034
+ const same = typeof use.drift === 'function' && await use.drift().then(drift => !drift, () => false) && await pairNow() === use.own;
1035
+ outcome = !same ? 'replaced' : closed ? 'closed' : 'loaded';
1036
+ } catch (error) {
1037
+ use.problem = use.loadProblem = said(error, 'the settings could not be loaded.');
1038
+ outcome = 'failed';
1039
+ }
1040
+ // Someone else's settings by now, or unloaded meanwhile: what was just loaded goes again.
1041
+ if (outcome === 'replaced' || outcome === 'closed') {
1042
+ const loaded = cleanup;
1043
+ cleanup = undefined;
1044
+ use.drift = undefined;
1045
+ if (outcome === 'replaced') { use.own = undefined; use.loadProblem = ''; }
1046
+ await Promise.resolve(loaded?.()).catch(() => {});
1047
+ }
1048
+ if (outcome !== 'loaded') {
1049
+ // The commands that say so come back, except under a name that is another plugin's by now; without
1050
+ // them only /pr-setup is left until the restart.
1051
+ await restoreNow();
1052
+ return false;
1053
+ }
1054
+ use.blocked = false;
1055
+ use.problem = use.loadProblem = '';
1056
+ // OpenCode 2.3.0 announces commands that change after a plugin was loaded without their location, and
1057
+ // its clients then keep the list they have: the terminal part reads the commands again on this event.
1058
+ try { await rpc?.events?.emit?.('loaded', {}); } catch { /* The commands work either way. */ }
1059
+ return true;
1060
+ } catch (error) {
1061
+ // A host call failed on the way (removing the commands, listing them, unloading). What was saved stays
1062
+ // saved, and the commands that say what is missing stay too, or come back.
1063
+ use.problem = use.loadProblem = said(error, 'OpenCode did not answer while AZPR replaced its commands.');
1064
+ await restoreNow();
1065
+ return false;
1066
+ } finally { activating = undefined; }
1067
+ });
1068
+ return activating;
1069
+ }
1070
+
1071
+ /**
1072
+ * Put the commands that say what is missing back where none are registered, except under a name another
1073
+ * plugin has by now. Only with a list of the commands read at this moment: where the host does not answer
1074
+ * they stay away (adding one would replace a command that may be someone's), and the next /pr-setup or save
1075
+ * tries again. `restoreNow` is the step itself, for what already runs in the lane (a load that failed);
1076
+ * everything else asks through `restorePlaceholders`, which waits for its turn there, so that the list it
1077
+ * reads is never older than a load, and a load never finds this half done.
1078
+ */
1079
+ const restoreNow = async () => {
1080
+ if (!use.blocked || placeholders || closed) return;
1081
+ const names = await taken();
1082
+ if (names && !closed) placeholders = await registerPlaceholders(names).catch(() => undefined);
1083
+ };
1084
+ const restorePlaceholders = () => inLane(restoreNow);
1085
+
1086
+ /**
1087
+ * After a save of this process's own setup: `made` (the settings it replaced could not be used, and it wrote
1088
+ * something), and what the settings and their token file held when it read them (`before`) and hold after
1089
+ * it (`after`). A process that found no usable settings loads them when its own save is what made them
1090
+ * usable, and tries again with a later save when loading them failed, as long as the two files held
1091
+ * nothing but what this setup wrote in between. Settings that could be used before the save, or that
1092
+ * took the place of what this setup saved, were made by something else (another process's setup, an
1093
+ * editor, a tool): those wait for the restart, as every change does, whatever this save added. Returns
1094
+ * whether the runtime is loaded afterwards (`ready`), and otherwise what stands in the way now
1095
+ * (`problem`; '' when it is only the restart).
1096
+ */
1097
+ const afterSave = async ({ made, before, after }) => {
1098
+ if (!use.blocked) return { ready: true, problem: '' };
1099
+ const now = await settingsProblem(path);
1100
+ // Still not usable: nothing is this setup's to load yet (what makes them usable later may be someone
1101
+ // else's doing), and the problem of now takes the place of the one found at load.
1102
+ if (now.problem) {
1103
+ use.own = undefined;
1104
+ use.problem = now.problem;
1105
+ use.loadProblem = '';
1106
+ await restorePlaceholders();
1107
+ return { ready: false, problem: now.problem };
1108
+ }
1109
+ if (made) use.own = after;
1110
+ else if (use.own !== undefined && before === use.own) use.own = after;
1111
+ // Not this setup's any more, or never: what a load of its own settings failed on says nothing about these.
1112
+ else { use.own = undefined; use.loadProblem = ''; }
1113
+ if (use.own === undefined) { await restorePlaceholders(); return { ready: false, problem: '' }; }
1114
+ const ready = await activate();
1115
+ return { ready, problem: ready ? '' : use.loadProblem };
1116
+ };
1117
+
1118
+ const service = createSetupService({ context, path, environment, options: { ...runtimeOptions, checkTimeoutMs, settingsPrepared }, loaded: () => use, turn,
1119
+ saved: async result => { await afterSave(result); } });
1120
+ const registrations = [];
319
1121
  const registration = await context.command.transform(editor => {
320
1122
  editor.add({ name: 'pr-setup', description: SETUP_DESCRIPTION, async execute(event) {
321
1123
  if (event.prompt.files?.length || event.prompt.agents?.length || event.prompt.skills?.length) throw new Error('[AZPR] Setup accepts literal options only.');
322
1124
  const session = typeof context.session?.get === 'function' ? recordOf(await context.session.get({ sessionID: event.sessionID })) : null;
323
1125
  if (privateAgent(session?.agent)) throw new Error('[AZPR] Private reviewers cannot configure AZPR.');
324
- let text;
1126
+ // Where the commands that say what is missing could not be registered earlier, they are now. Not while a
1127
+ // load is under way: it sees to them itself when it ends, and this command does not wait for it.
1128
+ if (!activating) await restorePlaceholders();
1129
+ let text, metadata;
325
1130
  try {
326
1131
  const arguments_ = parseSetupArguments(event.prompt.text ?? '');
327
- if (arguments_ === null) text = await guide(context, path, problem, environment);
328
- else {
329
- if (pending) throw new Error('[AZPR] Another setup is active.');
330
- pending = true;
331
- let saved;
332
- try { saved = await saveSetup(context, path, arguments_, environment); } finally { pending = false; }
333
- text = `[AZPR] SETTINGS SAVED\nSettings: ${path}\nOrganization: ${saved.organization}; PAT file: ${saved.patFile}\n` +
334
- `To load them, ${RESTART}, then run /pr-check <PR URL>. No model or Azure request was made. Existing reviews keep their original settings.`;
1132
+ if (arguments_ === null) {
1133
+ text = await guide(context, path, use.blocked ? use.problem : '', environment);
1134
+ // /pr-setup alone: the terminal UI opens its dialogs when it sees this notice. --help only explains.
1135
+ if (!(event.prompt.text ?? '').trim()) metadata = { azpr: { setup: true } };
1136
+ } else {
1137
+ if (turn.busy) throw new Error('[AZPR] Another setup is active.');
1138
+ turn.busy = true;
1139
+ let saved, after = { ready: false, problem: '' };
1140
+ const wasBlocked = use.blocked;
1141
+ try {
1142
+ saved = await saveSetup(context, path, arguments_, environment);
1143
+ if (wasBlocked) after = await afterSave({ made: saved.unusable, before: saved.before, after: saved.after });
1144
+ } finally { turn.busy = false; }
1145
+ text = `[AZPR] SETTINGS SAVED\nSettings: ${path}\n` +
1146
+ (saved.first ? `Organization: ${saved.organization}; PAT file: ${saved.patFile}\n` : '') +
1147
+ (saved.changed.length ? `Changed: ${saved.changed.join(', ')}\n` : '') +
1148
+ (after.ready ? 'AZPR has loaded them: run /pr-check <PR URL>. No model or Azure request was made.'
1149
+ : after.problem ? `AZPR could not load them: ${after.problem} Repair that, then ${RESTART}. No model or Azure request was made.`
1150
+ : `To load them, ${RESTART}, then run /pr-check <PR URL>. No model or Azure request was made.${wasBlocked ? '' : ' Existing reviews keep their original settings.'}`);
335
1151
  }
336
1152
  } catch (error) {
337
1153
  // OS errors may include file contents only through custom providers; report codes, not arbitrary text.
338
1154
  text = typeof error.message === 'string' && error.message.startsWith('[AZPR]') ? error.message : '[AZPR] Setup could not save settings. Check the model ID, organization, PAT file and local file permissions; existing settings were preserved.';
339
1155
  }
340
- await appendReport(context, { sessionID: event.sessionID, text });
341
- } });
342
- if (blocked) for (const name of Object.keys(COMMANDS)) editor.add({ name, description: 'AZPR setup required; run /pr-setup', async execute(event) {
343
- await appendReport(context, { sessionID: event.sessionID,
344
- text: `[AZPR] SETUP REQUIRED\nNo review or Azure request was started. Settings at ${path} could not be used when OpenCode loaded AZPR: ${problem} Run /pr-setup --help; repair an existing settings file if necessary, then ${RESTART}.` });
1156
+ await appendReport(context, { sessionID: event.sessionID, text, ...(metadata ? { metadata } : {}) });
345
1157
  } });
346
1158
  });
347
- let cleanup;
1159
+ registrations.push(registration);
348
1160
  try {
349
- if (!blocked) {
350
- // Before the runtime reads the settings for good: it compares later reads with this one.
351
- const completion = await addMissingSettings(path, settingsWaitMs === undefined ? {} : { waitMs: settingsWaitMs, pauseMs: 10 });
352
- cleanup = await setupAzurePrReview(context, sourceDirectory, { ...runtimeOptions, settingsPath: path, settingsCompletion: completion });
353
- }
1161
+ // The terminal UI's dialogs reach setup through the plugin's RPC; a host without it keeps the options.
1162
+ if (typeof context.rpc?.register === 'function') registrations.push(rpc = await context.rpc.register(SETUP_RPC, service));
1163
+ // A plugin may have taken a review command's name since the catalog was read above: that name stays its own.
1164
+ if (use.blocked) await restorePlaceholders();
1165
+ else cleanup = await load();
354
1166
  }
355
- catch (error) { await registration.dispose(); throw error; }
356
- return async () => { await cleanup?.(); await registration.dispose(); };
1167
+ catch (error) { await Promise.allSettled(registrations.map(item => item.dispose())); throw error; }
1168
+ return async () => {
1169
+ closed = true;
1170
+ await activating?.catch(() => {});
1171
+ await lane;
1172
+ await cleanup?.();
1173
+ await placeholders?.dispose();
1174
+ await Promise.allSettled(registrations.reverse().map(item => item.dispose()));
1175
+ };
357
1176
  }