opencode-azure-devops-pr-review 0.3.0 → 0.3.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/setup.mjs CHANGED
@@ -9,14 +9,26 @@ import { COMMANDS, modelRef, privateAgent, validateSettings } from './config.mjs
9
9
  import { parseUniqueJSON } from './output.mjs';
10
10
  import { appendReport } from './session.mjs';
11
11
  import { listOf, recordOf, requireMethods } from './host.mjs';
12
+ import { organizationName } from './azure.mjs';
12
13
  import { readPatFile, setupAzurePrReview } from './runtime.mjs';
13
14
 
14
15
  const SOURCE_DIRECTORY = dirname(fileURLToPath(import.meta.url));
15
16
  const SETUP_DESCRIPTION = 'Configure AZPR with one model and an existing PAT file; no model or Azure calls';
16
- const USAGE = '/pr-setup --organization ORG --model PROVIDER/MODEL --pat-file "/absolute/path/to/pat"';
17
+ const USAGE = '/pr-setup --organization ORG --model PROVIDER/MODEL [--pat-file "/absolute/path/to/pat"]';
18
+ const RESTART = 'restart the OpenCode service (in a terminal: opencode service restart; if you run opencode serve yourself, restart that process)';
17
19
  const MAX_SETTINGS_BYTES = 1024 * 1024;
18
20
  const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
19
21
 
22
+ /** AZPR's directory for user files: $XDG_CONFIG_HOME/azpr, otherwise ~/.config/azpr. */
23
+ function userDirectory(environment) {
24
+ const root = environment.XDG_CONFIG_HOME || join(environment.HOME || homedir(), '.config');
25
+ if (!isAbsolute(root)) throw new Error('[AZPR] XDG_CONFIG_HOME must be an absolute path.');
26
+ return join(root, 'azpr');
27
+ }
28
+
29
+ /** The PAT file setup uses without --pat-file, where the quickstart creates it. */
30
+ export const defaultPatFile = (environment = process.env) => join(userDirectory(environment), 'pat');
31
+
20
32
  /** Explicit path wins; source installations retain their adjacent settings. */
21
33
  export async function settingsFileFor(options = {}, sourceDirectory = SOURCE_DIRECTORY, environment = process.env) {
22
34
  if (!object(options) || Object.keys(options).some(key => key !== 'settingsFile')) {
@@ -30,9 +42,7 @@ export async function settingsFileFor(options = {}, sourceDirectory = SOURCE_DIR
30
42
  }
31
43
  const legacy = join(sourceDirectory, 'settings.json');
32
44
  try { await lstat(legacy); return legacy; } catch (error) { if (error.code !== 'ENOENT') throw error; }
33
- const root = environment.XDG_CONFIG_HOME || join(environment.HOME || homedir(), '.config');
34
- if (!isAbsolute(root)) throw new Error('[AZPR] XDG_CONFIG_HOME must be an absolute path.');
35
- return join(root, 'azpr', 'settings.json');
45
+ return join(userDirectory(environment), 'settings.json');
36
46
  }
37
47
 
38
48
  /** Do not expose JSON parser excerpts: an existing profile can contain a PAT. */
@@ -72,8 +82,8 @@ export function parseSetupArguments(text) {
72
82
  result[flag] = tokens[++index];
73
83
  }
74
84
  }
75
- if (['--organization', '--model', '--pat-file'].some(flag => !result[flag])) {
76
- throw new Error('[AZPR] Supply --organization, --model and --pat-file together. Use /pr-setup --help.');
85
+ if (['--organization', '--model'].some(flag => !result[flag])) {
86
+ throw new Error('[AZPR] Supply --organization and --model (--pat-file is optional). Use /pr-setup --help.');
77
87
  }
78
88
  return result;
79
89
  }
@@ -108,8 +118,12 @@ async function readExisting(path) {
108
118
  } finally { await handle?.close(); }
109
119
  }
110
120
 
111
- /** Atomic, owner-only save; serialize setup calls and preserve unrelated values. */
112
- export async function saveSetup(context, path, arguments_) {
121
+ /**
122
+ * Atomic, owner-only save; serialize setup calls and preserve unrelated values.
123
+ * Without --pat-file, a replacement keeps the PAT file already set and a first
124
+ * setup uses the default PAT file. Returns the saved organization and PAT file.
125
+ */
126
+ export async function saveSetup(context, path, arguments_, environment = process.env) {
113
127
  const previous = await readExisting(path);
114
128
  if (previous !== null && !arguments_['--replace']) {
115
129
  throw new Error('[AZPR] Settings already exist. Add --replace to change organization, PAT file and all review/quick model slots while keeping other settings.');
@@ -120,16 +134,24 @@ export async function saveSetup(context, path, arguments_) {
120
134
  throw new Error('[AZPR] Repair models and azure objects in settings.json before setup; existing data was preserved.');
121
135
  }
122
136
  const model = arguments_['--model'];
123
- const patFile = arguments_['--pat-file'];
137
+ const organization = organizationName(arguments_['--organization']);
138
+ const kept = typeof raw.azure?.patFile === 'string' && raw.azure.patFile ? raw.azure.patFile : '';
139
+ const patFile = arguments_['--pat-file'] ?? (kept || defaultPatFile(environment));
124
140
  if (typeof patFile !== 'string' || !isAbsolute(patFile) || resolve(patFile) === resolve(path)) {
125
141
  throw new Error('[AZPR] --pat-file must name an absolute path separate from settings.json.');
126
142
  }
127
143
  const next = { ...raw, models: { ...raw.models,
128
144
  review: { functional: model, risk: model, verifier: model }, quick: { reviewer: model } },
129
- azure: { ...raw.azure, organization: arguments_['--organization'], pat: '', patFile } };
145
+ azure: { ...raw.azure, organization, pat: '', patFile } };
130
146
  validateSettings(next);
131
147
  await checkModel(context, model);
132
- await readPatFile(patFile);
148
+ try { await readPatFile(patFile); }
149
+ catch (error) {
150
+ if (arguments_['--pat-file'] !== undefined) throw error;
151
+ // Name the file setup chose, so the reader knows where to put the PAT.
152
+ const problem = error.message.replace(/^\[AZPR\] azure\.patFile /, '');
153
+ 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.`);
154
+ }
133
155
  const parent = dirname(path);
134
156
  await mkdir(parent, { recursive: true, mode: 0o700 });
135
157
  const parentInfo = await lstat(parent);
@@ -150,6 +172,7 @@ export async function saveSetup(context, path, arguments_) {
150
172
  await handle?.close();
151
173
  if (acquired) await unlink(lock);
152
174
  }
175
+ return { organization, patFile };
153
176
  }
154
177
 
155
178
  async function writeTemporary(path, text) {
@@ -157,16 +180,18 @@ async function writeTemporary(path, text) {
157
180
  try { await handle.writeFile(text); await handle.sync(); } finally { await handle.close(); }
158
181
  }
159
182
 
160
- async function guide(context, path, problem) {
161
- let catalog = [];
183
+ async function guide(context, path, problem, environment) {
184
+ let catalog = [], patFile;
162
185
  try { catalog = (listOf(await context.model.list()) ?? []).filter(item => item.enabled !== false && item.capabilities?.tools === true); } catch { /* Help remains usable before provider setup. */ }
186
+ try { patFile = defaultPatFile(environment); } catch { patFile = '$XDG_CONFIG_HOME/azpr/pat'; }
163
187
  const models = catalog.slice(0, 12).map(item => `${item.providerID}/${item.id}`);
164
188
  return `[AZPR] SETUP${problem ? ' REQUIRED' : ''}\nSettings: ${path}\n${problem ? `Problem when OpenCode loaded AZPR: ${problem}\n` : ''}\n` +
165
189
  `1. Connect your provider in OpenCode and choose one tool-capable model ID (${models.length ? models.join(', ') : 'run opencode models'}).\n` +
166
- '2. Create an Azure DevOps PAT for one organization with Code (Read) and Pull Request Threads (Read & write). Keep it alone in an existing regular file owned by you, with mode 600; never paste it into this conversation.\n' +
190
+ `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` +
167
191
  `3. Run ${USAGE}\n\n` +
192
+ '--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. ' +
168
193
  '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' +
169
- 'After saving, restart OpenCode and run /pr-check <PR URL>. Settings changes do not affect reviews already running.';
194
+ `After saving, ${RESTART}, then run /pr-check <PR URL>. Settings changes do not affect reviews already running.`;
170
195
  }
171
196
 
172
197
  /**
@@ -192,7 +217,8 @@ async function settingsProblem(path) {
192
217
 
193
218
  /** Missing/invalid settings expose only setup and blocked command explanations, with the reason. */
194
219
  export async function setupPlugin(context, sourceDirectory = SOURCE_DIRECTORY, testOptions = {}) {
195
- const path = await settingsFileFor(context.options ?? {}, sourceDirectory);
220
+ const { environment = process.env, ...runtimeOptions } = testOptions;
221
+ const path = await settingsFileFor(context.options ?? {}, sourceDirectory, environment);
196
222
  const { problem, disabled } = await settingsProblem(path);
197
223
  const blocked = Boolean(problem);
198
224
  if (disabled) return async () => {};
@@ -210,12 +236,14 @@ export async function setupPlugin(context, sourceDirectory = SOURCE_DIRECTORY, t
210
236
  let text;
211
237
  try {
212
238
  const arguments_ = parseSetupArguments(event.prompt.text ?? '');
213
- if (arguments_ === null) text = await guide(context, path, problem);
239
+ if (arguments_ === null) text = await guide(context, path, problem, environment);
214
240
  else {
215
241
  if (pending) throw new Error('[AZPR] Another setup is active.');
216
242
  pending = true;
217
- try { await saveSetup(context, path, arguments_); } finally { pending = false; }
218
- text = `[AZPR] SETTINGS SAVED\nSettings: ${path}\nRestart OpenCode, then run /pr-check <PR URL>. No model or Azure request was made. Existing reviews keep their original settings.`;
243
+ let saved;
244
+ try { saved = await saveSetup(context, path, arguments_, environment); } finally { pending = false; }
245
+ text = `[AZPR] SETTINGS SAVED\nSettings: ${path}\nOrganization: ${saved.organization}; PAT file: ${saved.patFile}\n` +
246
+ `To load them, ${RESTART}, then run /pr-check <PR URL>. No model or Azure request was made. Existing reviews keep their original settings.`;
219
247
  }
220
248
  } catch (error) {
221
249
  // OS errors may include file contents only through custom providers; report codes, not arbitrary text.
@@ -225,11 +253,11 @@ export async function setupPlugin(context, sourceDirectory = SOURCE_DIRECTORY, t
225
253
  } });
226
254
  if (blocked) for (const name of Object.keys(COMMANDS)) editor.add({ name, description: 'AZPR setup required; run /pr-setup', async execute(event) {
227
255
  await appendReport(context, { sessionID: event.sessionID,
228
- 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 OpenCode.` });
256
+ 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}.` });
229
257
  } });
230
258
  });
231
259
  let cleanup;
232
- try { if (!blocked) cleanup = await setupAzurePrReview(context, sourceDirectory, { ...testOptions, settingsPath: path }); }
260
+ try { if (!blocked) cleanup = await setupAzurePrReview(context, sourceDirectory, { ...runtimeOptions, settingsPath: path }); }
233
261
  catch (error) { await registration.dispose(); throw error; }
234
262
  return async () => { await cleanup?.(); await registration.dispose(); };
235
263
  }