@aexol/opencode-wizard 0.3.2 → 0.3.4

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.
Files changed (97) hide show
  1. package/README.md +4 -0
  2. package/dist/graphql-operations.d.ts +4 -0
  3. package/dist/graphql-operations.js +225 -0
  4. package/dist/graphql-operations.js.map +1 -0
  5. package/dist/plugin-tools.d.ts +64 -0
  6. package/dist/plugin-tools.js +57 -0
  7. package/dist/plugin-tools.js.map +1 -0
  8. package/dist/published-skills-system-note.d.ts +9 -0
  9. package/dist/published-skills-system-note.js +34 -0
  10. package/dist/published-skills-system-note.js.map +1 -0
  11. package/dist/published-skills-transform.d.ts +161 -0
  12. package/dist/published-skills-transform.js +238 -0
  13. package/dist/published-skills-transform.js.map +1 -0
  14. package/dist/server/auth-flow.d.ts +10 -0
  15. package/dist/server/auth-flow.js +215 -0
  16. package/dist/server/auth-flow.js.map +1 -0
  17. package/dist/server/auth-store.d.ts +19 -0
  18. package/dist/server/auth-store.js +177 -0
  19. package/dist/server/auth-store.js.map +1 -0
  20. package/dist/server/client.d.ts +51 -0
  21. package/dist/server/client.js +244 -0
  22. package/dist/server/client.js.map +1 -0
  23. package/dist/server/config.d.ts +2 -0
  24. package/dist/server/config.js +82 -0
  25. package/dist/server/config.js.map +1 -0
  26. package/dist/server/constants.d.ts +26 -0
  27. package/dist/server/constants.js +32 -0
  28. package/dist/server/constants.js.map +1 -0
  29. package/dist/server/path-utils.d.ts +2 -0
  30. package/dist/server/path-utils.js +8 -0
  31. package/dist/server/path-utils.js.map +1 -0
  32. package/dist/server/presence.d.ts +14 -0
  33. package/dist/server/presence.js +68 -0
  34. package/dist/server/presence.js.map +1 -0
  35. package/dist/server/runtime.d.ts +32 -0
  36. package/dist/server/runtime.js +1110 -0
  37. package/dist/server/runtime.js.map +1 -0
  38. package/dist/server/status.d.ts +27 -0
  39. package/dist/server/status.js +224 -0
  40. package/dist/server/status.js.map +1 -0
  41. package/dist/server/types.d.ts +321 -0
  42. package/dist/server/types.js +2 -0
  43. package/dist/server/types.js.map +1 -0
  44. package/dist/server/workspace.d.ts +15 -0
  45. package/dist/server/workspace.js +126 -0
  46. package/dist/server/workspace.js.map +1 -0
  47. package/dist/server.d.ts +4 -304
  48. package/dist/server.js +4 -2489
  49. package/dist/server.js.map +1 -1
  50. package/dist/smoke-published-skills.js +11 -9
  51. package/dist/smoke-published-skills.js.map +1 -1
  52. package/dist/tui/components/common.d.ts +15 -0
  53. package/dist/tui/components/common.js +81 -0
  54. package/dist/tui/components/common.js.map +1 -0
  55. package/dist/tui/components/preference-action-notice-row.d.ts +5 -0
  56. package/dist/tui/components/preference-action-notice-row.js +17 -0
  57. package/dist/tui/components/preference-action-notice-row.js.map +1 -0
  58. package/dist/tui/components/skill-catalog-row.d.ts +8 -0
  59. package/dist/tui/components/skill-catalog-row.js +124 -0
  60. package/dist/tui/components/skill-catalog-row.js.map +1 -0
  61. package/dist/tui/components/status-content.d.ts +14 -0
  62. package/dist/tui/components/status-content.js +131 -0
  63. package/dist/tui/components/status-content.js.map +1 -0
  64. package/dist/tui/components/wizard-skills-dialog-content.d.ts +9 -0
  65. package/dist/tui/components/wizard-skills-dialog-content.js +219 -0
  66. package/dist/tui/components/wizard-skills-dialog-content.js.map +1 -0
  67. package/dist/tui/components/wizard-skills-dialog.d.ts +7 -0
  68. package/dist/tui/components/wizard-skills-dialog.js +156 -0
  69. package/dist/tui/components/wizard-skills-dialog.js.map +1 -0
  70. package/dist/tui/constants.d.ts +8 -0
  71. package/dist/tui/constants.js +9 -0
  72. package/dist/tui/constants.js.map +1 -0
  73. package/dist/tui/formatting.d.ts +8 -0
  74. package/dist/tui/formatting.js +45 -0
  75. package/dist/tui/formatting.js.map +1 -0
  76. package/dist/tui/plugin.d.ts +2 -0
  77. package/dist/tui/plugin.js +26 -0
  78. package/dist/tui/plugin.js.map +1 -0
  79. package/dist/tui/rendering.d.ts +2 -0
  80. package/dist/tui/rendering.js +8 -0
  81. package/dist/tui/rendering.js.map +1 -0
  82. package/dist/tui/skill-helpers.d.ts +13 -0
  83. package/dist/tui/skill-helpers.js +49 -0
  84. package/dist/tui/skill-helpers.js.map +1 -0
  85. package/dist/tui/slots.d.ts +2 -0
  86. package/dist/tui/slots.js +56 -0
  87. package/dist/tui/slots.js.map +1 -0
  88. package/dist/tui/status.d.ts +2 -0
  89. package/dist/tui/status.js +21 -0
  90. package/dist/tui/status.js.map +1 -0
  91. package/dist/tui/types.d.ts +75 -0
  92. package/dist/tui/types.js +2 -0
  93. package/dist/tui/types.js.map +1 -0
  94. package/dist/tui.d.ts +1 -44
  95. package/dist/tui.js +2 -870
  96. package/dist/tui.js.map +1 -1
  97. package/package.json +1 -1
package/dist/server.js CHANGED
@@ -1,2492 +1,7 @@
1
- import fs from 'node:fs/promises';
2
- import http from 'node:http';
3
- import os from 'node:os';
4
- import path from 'node:path';
5
- import crypto from 'node:crypto';
6
- import { execFile } from 'node:child_process';
7
- import { promisify } from 'node:util';
8
- import { URL, fileURLToPath } from 'node:url';
9
- import { resolveBackendOriginFromValues } from './config.js';
10
- import { sendOAuthCallbackHtmlResponse } from './oauth-callback-page.js';
11
- import { deleteFileIfExists, readJsonFile, writePrivateJsonFile } from './storage.js';
12
- const execFileAsync = promisify(execFile);
13
- const MODULE_FILE_PATH = fileURLToPath(import.meta.url);
14
- const PACKAGE_ROOT_PATH = path.resolve(path.dirname(MODULE_FILE_PATH), '..');
15
- export const PLUGIN_ID = 'opencode-wizard';
16
- const CACHE_TTL_MS = 30_000;
17
- const ROOT_SKILL_SEED_PATH = '.opencode/skills';
18
- const GLOBAL_CONFIG_PATH = path.join(os.homedir(), '.config', 'opencode', 'opencode-wizard.json');
19
- const LEGACY_AUTH_STATE_PATH = 'plugin/opencode-wizard/.generated/auth-state.json';
20
- const OIDC_ISSUER = 'https://login.microsoftonline.com/86f4caf4-0d6f-4682-9a06-ea57f3e4e76c/v2.0';
21
- const OIDC_CLIENT_ID = 'da963901-2375-442b-9e99-14e59f43eda2';
22
- const OIDC_CALLBACK_ORIGIN = 'http://localhost:24953';
23
- const OIDC_CALLBACK_PATH = '/oauth/callback';
24
- const OIDC_CALLBACK_URL = `${OIDC_CALLBACK_ORIGIN}${OIDC_CALLBACK_PATH}`;
25
- const OIDC_SCOPES = ['openid', 'profile', 'email'];
26
- const LOGIN_TIMEOUT_MS = 5 * 60_000;
27
- const SYSTEM_NOTE_SKILL_NAME_LIMIT = 10;
28
- const SYSTEM_NOTE_DETAIL_LIMIT = 3;
29
- const SYSTEM_NOTE_DETAIL_CHAR_LIMIT = 2_400;
30
- const SYSTEM_NOTE_SKILL_DESCRIPTION_LIMIT = 140;
31
- const PRESENCE_EVENT_TIMEOUT_MS = 3_000;
32
- const PRESENCE_EVENT_MAX_ATTEMPTS = 2;
33
- const PRESENCE_EVENT_RETRY_DELAY_MS = 250;
34
- const PRESENCE_SHUTDOWN_SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'];
35
- const PRESENCE_SIGNAL_EXIT_CODES = {
36
- SIGINT: 130,
37
- SIGTERM: 143,
38
- SIGHUP: 129
39
- };
40
- const createIdleLoginBootstrapSnapshot = () => ({
41
- status: 'idle',
42
- trigger: null,
43
- startedAt: null,
44
- expiresAt: null,
45
- browserUrl: null,
46
- browserOpenError: null,
47
- email: null,
48
- message: null
49
- });
50
- const STATUS_PATH_LOGIN_RETRY_COOLDOWN_MS = 60_000;
51
- const statusPathLoginBootstrap = {
52
- promise: null,
53
- status: 'idle',
54
- message: null,
55
- failedAt: null
56
- };
57
- const importOpencodePluginModule = new Function('specifier', 'return import(specifier)');
58
- export const AVAILABLE_PUBLISHED_SKILL_TOOLS = ['opencode_wizard_published_skills_fetch', 'opencode_wizard_published_skill_preference_set', 'opencode_wizard_status'];
59
- let publishedSkillPreferenceCacheVersion = 0;
60
- export const NATIVE_SKILLS_URL_COMPATIBILITY = {
61
- configKey: 'skills.urls',
62
- deliveryMode: 'public_static_registry',
63
- wizardPrivateDelivery: 'authenticated_scoped_fetch_tool',
64
- authSupport: 'none',
65
- guidance: 'OpenCode skills.urls is for public/static registries and complements opencode-wizard; private workspace-scoped skills stay available through the authenticated fetch tool only.'
66
- };
67
- const PUBLISHED_SKILLS_CATALOG_QUERY = `
68
- query PluginPublishedSkills($input: PublishedSkillsDeliveryInput!) {
69
- pluginPublishedSkills(input: $input) {
70
- workspace {
71
- id
72
- slug
73
- name
74
- repositoryUrl
75
- defaultBranch
76
- status
77
- }
78
- directoryPath
79
- skills {
80
- assignmentSource
81
- assignmentType
82
- scopePath
83
- includeChildren
84
- skill {
85
- id
86
- slug
87
- name
88
- summary
89
- whenToUse
90
- status
91
- installPolicy
92
- tags {
93
- id
94
- slug
95
- label
96
- description
97
- facet {
98
- id
99
- slug
100
- label
101
- description
102
- }
103
- }
104
- }
105
- skillVersion {
106
- id
107
- version
108
- title
109
- summary
110
- status
111
- }
112
- publishedArtifact {
113
- id
114
- frontmatterName
115
- frontmatterDescription
116
- checksum
117
- publishedAt
118
- fileCount
119
- }
120
- }
121
- catalogSkills {
122
- skill {
123
- id
124
- slug
125
- name
126
- summary
127
- whenToUse
128
- status
129
- installPolicy
130
- tags {
131
- id
132
- slug
133
- label
134
- description
135
- facet {
136
- id
137
- slug
138
- label
139
- description
140
- }
141
- }
142
- }
143
- skillVersion {
144
- id
145
- version
146
- title
147
- summary
148
- status
149
- }
150
- publishedArtifact {
151
- id
152
- frontmatterName
153
- frontmatterDescription
154
- checksum
155
- publishedAt
156
- fileCount
157
- }
158
- }
159
- userPreferences {
160
- scopeKey
161
- userKey
162
- ignoredSkills {
163
- assignmentSource
164
- assignmentType
165
- scopePath
166
- includeChildren
167
- skill {
168
- id
169
- slug
170
- name
171
- summary
172
- whenToUse
173
- status
174
- installPolicy
175
- tags {
176
- id
177
- slug
178
- label
179
- description
180
- facet {
181
- id
182
- slug
183
- label
184
- description
185
- }
186
- }
187
- }
188
- skillVersion {
189
- id
190
- version
191
- title
192
- summary
193
- status
194
- }
195
- publishedArtifact {
196
- id
197
- frontmatterName
198
- frontmatterDescription
199
- checksum
200
- publishedAt
201
- fileCount
202
- }
203
- }
204
- }
205
- }
206
- }
207
- `;
208
- const SET_PUBLISHED_SKILL_PREFERENCE_MUTATION = `
209
- mutation SetPublishedSkillPreference($input: SetPublishedSkillPreferenceInput!) {
210
- setPublishedSkillPreference(input: $input) {
211
- scopeKey
212
- userKey
213
- ignoredSkills {
214
- assignmentSource
215
- assignmentType
216
- scopePath
217
- includeChildren
218
- skill {
219
- id
220
- slug
221
- name
222
- summary
223
- whenToUse
224
- status
225
- installPolicy
226
- tags {
227
- id
228
- slug
229
- label
230
- description
231
- facet {
232
- id
233
- slug
234
- label
235
- description
236
- }
237
- }
238
- }
239
- skillVersion {
240
- id
241
- version
242
- title
243
- summary
244
- status
245
- }
246
- publishedArtifact {
247
- id
248
- frontmatterName
249
- frontmatterDescription
250
- checksum
251
- publishedAt
252
- fileCount
253
- }
254
- }
255
- }
256
- }
257
- `;
258
- const PUBLISHED_SKILL_DETAIL_QUERY = `
259
- query PluginPublishedSkillVersionArtifact($input: PublishedSkillArtifactDetailInput!) {
260
- pluginPublishedSkillVersionArtifact(input: $input) {
261
- id
262
- frontmatterName
263
- frontmatterDescription
264
- markdownBody
265
- renderedContent
266
- checksum
267
- publishedAt
268
- fileCount
269
- files {
270
- id
271
- relativePath
272
- contentType
273
- content
274
- checksum
275
- size
276
- sortOrder
277
- }
278
- }
279
- }
280
- `;
281
- const parseDotEnvValue = value => {
282
- const trimmedValue = value.trim();
283
- if (trimmedValue.startsWith('"') && trimmedValue.endsWith('"') || trimmedValue.startsWith("'") && trimmedValue.endsWith("'")) {
284
- return trimmedValue.slice(1, -1);
285
- }
286
- return trimmedValue;
287
- };
288
- const parseDotEnv = raw => {
289
- const values = new Map();
290
- for (const line of raw.split(/\r?\n/u)) {
291
- const trimmedLine = line.trim();
292
- if (!trimmedLine || trimmedLine.startsWith('#')) continue;
293
- const separatorIndex = trimmedLine.indexOf('=');
294
- if (separatorIndex <= 0) continue;
295
- const key = trimmedLine.slice(0, separatorIndex).trim();
296
- if (!key) continue;
297
- const rawValue = trimmedLine.slice(separatorIndex + 1);
298
- values.set(key, parseDotEnvValue(rawValue));
299
- }
300
- return values;
301
- };
302
- const findUpwardFile = async (startDirectory, fileName) => {
303
- let currentDirectory = normalizeAbsolutePath(startDirectory);
304
- while (true) {
305
- const candidatePath = path.join(currentDirectory, fileName);
306
- try {
307
- await fs.access(candidatePath);
308
- return candidatePath;
309
- } catch {
310
- const parentDirectory = path.dirname(currentDirectory);
311
- if (parentDirectory === currentDirectory) return null;
312
- currentDirectory = parentDirectory;
313
- }
314
- }
315
- };
316
- const readLocalEnvValues = async startDirectory => {
317
- const envPath = await findUpwardFile(startDirectory, '.env');
318
- if (!envPath) return new Map();
319
- try {
320
- const raw = await fs.readFile(envPath, 'utf8');
321
- return parseDotEnv(raw);
322
- } catch {
323
- return new Map();
324
- }
325
- };
326
- const resolveBackendOrigin = async worktree => {
327
- const envValues = await readLocalEnvValues(worktree);
328
- return resolveBackendOriginFromValues({
329
- environmentBackendOrigin: process.env.OPENCODE_WIZARD_BACKEND_ORIGIN,
330
- localBackendOrigin: envValues.get('OPENCODE_WIZARD_BACKEND_ORIGIN')
331
- });
332
- };
333
- const toWorkspaceSlug = value => {
334
- const normalized = value.trim().toLowerCase().replace(/[^a-z0-9-]+/gu, '-').replace(/^-+|-+$/gu, '');
335
- if (normalized) return normalized;
336
- return 'workspace';
337
- };
338
- const resolveFallbackWorkspaceSlug = worktree => {
339
- const configuredWorkspaceSlug = process.env.OPENCODE_WIZARD_SKILLS_WORKSPACE_SLUG?.trim();
340
- if (configuredWorkspaceSlug) return toWorkspaceSlug(configuredWorkspaceSlug);
341
- return toWorkspaceSlug(path.basename(path.resolve(worktree)));
342
- };
343
- export const resolveConfig = async worktree => {
344
- const backendOrigin = await resolveBackendOrigin(worktree);
345
- return {
346
- backendOrigin,
347
- graphqlUrl: `${backendOrigin}/graphql`,
348
- authSessionUrl: `${backendOrigin}/api/opencode-plugin/oauth/session`,
349
- presenceUrl: `${backendOrigin}/api/opencode-plugin/presence`,
350
- actionsUrl: `${backendOrigin}/api/opencode-plugin/actions`,
351
- fallbackWorkspaceSlug: resolveFallbackWorkspaceSlug(worktree),
352
- rootSkillSeedPath: ROOT_SKILL_SEED_PATH,
353
- authStatePath: GLOBAL_CONFIG_PATH
354
- };
355
- };
356
- const normalizeAbsolutePath = value => path.resolve(value);
357
- const normalizeRepositoryPath = (worktree, directory) => {
358
- const absoluteWorktree = normalizeAbsolutePath(worktree);
359
- const absoluteDirectory = normalizeAbsolutePath(directory);
360
- const relativePath = path.relative(absoluteWorktree, absoluteDirectory);
361
- if (!relativePath || relativePath === '') return '.';
362
- if (relativePath.startsWith('..') || path.isAbsolute(relativePath)) return '.';
363
- return relativePath.split(path.sep).join('/');
364
- };
365
- const tryExecGit = async args => {
366
- try {
367
- const {
368
- stdout
369
- } = await execFileAsync('git', args, {
370
- encoding: 'utf8'
371
- });
372
- const normalizedOutput = stdout.trim();
373
- if (normalizedOutput) return normalizedOutput;
374
- return null;
375
- } catch {
376
- return null;
377
- }
378
- };
379
- const resolveGitRoot = async directory => {
380
- const gitRoot = await tryExecGit(['-C', directory, 'rev-parse', '--show-toplevel']);
381
- if (!gitRoot) return null;
382
- return normalizeAbsolutePath(gitRoot);
383
- };
384
- const normalizeGitRemoteUrl = remoteUrl => {
385
- if (!remoteUrl) return null;
386
- const trimmedRemoteUrl = remoteUrl.trim();
387
- if (!trimmedRemoteUrl) return null;
388
- const scpLikeMatch = /^git@([^:]+):(.+)$/u.exec(trimmedRemoteUrl);
389
- if (scpLikeMatch) {
390
- return `ssh://git@${scpLikeMatch[1]}/${scpLikeMatch[2].replace(/^\/+/, '')}`;
391
- }
392
- try {
393
- const parsedUrl = new URL(trimmedRemoteUrl);
394
- return parsedUrl.toString().replace(/\/+$/u, '');
395
- } catch {
396
- return null;
397
- }
398
- };
399
- const resolveGitRemoteOriginUrl = async repositoryRoot => {
400
- const remoteUrl = await tryExecGit(['-C', repositoryRoot, 'remote', 'get-url', 'origin']);
401
- return normalizeGitRemoteUrl(remoteUrl);
402
- };
403
- const resolveWorkspace = async ({
404
- config,
405
- directory
406
- }) => {
407
- const requestedDirectory = normalizeAbsolutePath(directory);
408
- const gitRoot = await resolveGitRoot(requestedDirectory);
409
- const repositoryRoot = gitRoot ?? requestedDirectory;
410
- const repositoryUrl = gitRoot ? await resolveGitRemoteOriginUrl(gitRoot) : null;
411
- const fallbackWorkspaceSlug = config.fallbackWorkspaceSlug;
412
- const directoryPath = normalizeRepositoryPath(repositoryRoot, requestedDirectory);
413
- const workspaceIdentity = `workspaceSlug:${fallbackWorkspaceSlug}`;
414
- return {
415
- requestedDirectory,
416
- repositoryRoot,
417
- repositoryUrl,
418
- fallbackWorkspaceSlug,
419
- directoryPath,
420
- cacheKey: JSON.stringify([workspaceIdentity, directoryPath])
421
- };
422
- };
423
- const toDeliveryInput = resolution => {
424
- if (resolution.fallbackWorkspaceSlug) {
425
- return {
426
- workspaceSlug: resolution.fallbackWorkspaceSlug,
427
- directoryPath: resolution.directoryPath
428
- };
429
- }
430
- if (resolution.repositoryUrl) {
431
- return {
432
- repositoryUrl: resolution.repositoryUrl,
433
- directoryPath: resolution.directoryPath
434
- };
435
- }
436
- return {
437
- workspaceSlug: 'workspace',
438
- directoryPath: resolution.directoryPath
439
- };
440
- };
441
- const formatSkillLabel = item => {
442
- const artifactName = item.publishedArtifact.frontmatterName.trim();
443
- if (artifactName.length > 0) return artifactName;
444
- return item.skill.name;
445
- };
446
- const toFrontmatterString = value => JSON.stringify(value);
447
- const isRecord = value => {
448
- return typeof value === 'object' && value !== null && !Array.isArray(value);
449
- };
450
- const isValidIsoDateString = value => {
451
- return typeof value === 'string' && Number.isFinite(Date.parse(value));
452
- };
453
- const isAuthState = value => {
454
- if (!isRecord(value)) return false;
455
- return value.pluginId === PLUGIN_ID && typeof value.sessionToken === 'string' && isValidIsoDateString(value.expiresAt) && isValidIsoDateString(value.authenticatedAt) && typeof value.userId === 'string' && typeof value.email === 'string';
456
- };
457
- const readGlobalConfig = async configFile => {
458
- const storedConfig = await readJsonFile(configFile);
459
- if (isRecord(storedConfig)) return storedConfig;
460
- return {};
461
- };
462
- const writeGlobalConfig = async (configFile, config) => {
463
- await writePrivateJsonFile(configFile, config);
464
- };
465
- const withoutLegacyPublishedSkillPreferences = config => {
466
- const {
467
- publishedSkillPreferences,
468
- ignoredPublishedSkills,
469
- ...safeConfig
470
- } = config;
471
- void publishedSkillPreferences;
472
- void ignoredPublishedSkills;
473
- return safeConfig;
474
- };
475
- const hasLegacyPublishedSkillPreferences = config => {
476
- return Object.prototype.hasOwnProperty.call(config, 'publishedSkillPreferences') || Object.prototype.hasOwnProperty.call(config, 'ignoredPublishedSkills');
477
- };
478
- const readGlobalAuthState = async configFile => {
479
- const storedConfig = await readGlobalConfig(configFile);
480
- const storedAuthState = storedConfig.auth;
481
- if (storedAuthState === undefined || storedAuthState === null) return null;
482
- if (isAuthState(storedAuthState)) {
483
- if (hasLegacyPublishedSkillPreferences(storedConfig)) {
484
- await writeGlobalConfig(configFile, withoutLegacyPublishedSkillPreferences(storedConfig));
485
- }
486
- return storedAuthState;
487
- }
488
- await writeGlobalConfig(configFile, {
489
- ...withoutLegacyPublishedSkillPreferences(storedConfig),
490
- auth: null
491
- });
492
- return null;
493
- };
494
- const readLegacyAuthState = async authStateFile => {
495
- const storedAuthState = await readJsonFile(authStateFile);
496
- if (storedAuthState === null) return null;
497
- if (isAuthState(storedAuthState)) return storedAuthState;
498
- await deleteFileIfExists(authStateFile);
499
- return null;
500
- };
501
- const writeAuthState = async (configFile, authState) => {
502
- const storedConfig = await readGlobalConfig(configFile);
503
- await writeGlobalConfig(configFile, {
504
- ...withoutLegacyPublishedSkillPreferences(storedConfig),
505
- auth: authState
506
- });
507
- };
508
- const clearAuthState = async configFile => {
509
- const storedConfig = await readGlobalConfig(configFile);
510
- await writeGlobalConfig(configFile, {
511
- ...withoutLegacyPublishedSkillPreferences(storedConfig),
512
- auth: null
513
- });
514
- };
515
- const toIgnoredSkillSlug = value => {
516
- const normalized = value.trim().toLowerCase();
517
- if (!normalized) return null;
518
- return normalized;
519
- };
520
- const toPublishedSkillPreferenceAction = value => {
521
- const normalized = value.trim().toLowerCase();
522
- if (normalized === 'install' || normalized === 'uninstall' || normalized === 'ignore' || normalized === 'unignore') {
523
- return normalized;
524
- }
525
- throw new Error('Published skill preference action must be one of: install, uninstall, ignore, unignore.');
526
- };
527
- const toPublishedSkillPreferenceScope = (value, defaultScope) => {
528
- if (!value) return defaultScope;
529
- const normalized = value.trim().toLowerCase();
530
- if (normalized === 'global' || normalized === 'project') return normalized;
531
- throw new Error('Published skill preferenceScope must be either global or project.');
532
- };
533
- const getPublishedSkillIgnoreScopeKey = (resolution, payload) => {
534
- const workspaceSlug = payload?.workspace?.slug ?? resolution.fallbackWorkspaceSlug;
535
- if (workspaceSlug) return `workspace:${toWorkspaceSlug(workspaceSlug)}`;
536
- if (resolution.repositoryUrl) return `repository:${resolution.repositoryUrl}`;
537
- return `path:${toWorkspaceSlug(path.basename(resolution.repositoryRoot))}`;
538
- };
539
- const toStoredUserKey = authState => {
540
- if (authState?.userId) return authState.userId;
541
- if (authState?.email) return authState.email.toLowerCase();
542
- return 'anonymous';
543
- };
544
- const resolvePublishedSkillPreferenceCacheContext = async config => {
545
- const authState = await readGlobalAuthState(config.authStatePath);
546
- return {
547
- userKey: toStoredUserKey(authState),
548
- preferenceVersion: publishedSkillPreferenceCacheVersion
549
- };
550
- };
551
- const getCatalogCacheKey = (workspaceResolution, preferenceContext) => {
552
- return JSON.stringify([workspaceResolution.cacheKey, preferenceContext.userKey, preferenceContext.preferenceVersion]);
553
- };
554
- const toAuthState = session => ({
555
- pluginId: PLUGIN_ID,
556
- sessionToken: session.jwtToken,
557
- expiresAt: session.expiresAt,
558
- authenticatedAt: new Date().toISOString(),
559
- userId: session.user.id,
560
- email: session.user.email
561
- });
562
- const resolveStoredAuthState = async (worktree, config) => {
563
- const authState = await readGlobalAuthState(config.authStatePath);
564
- if (authState && Date.parse(authState.expiresAt) > Date.now()) {
565
- return authState;
566
- }
567
- if (authState) {
568
- await clearAuthState(config.authStatePath);
569
- return null;
570
- }
571
- const legacyAuthStateFile = path.resolve(worktree, LEGACY_AUTH_STATE_PATH);
572
- const legacyAuthState = await readLegacyAuthState(legacyAuthStateFile);
573
- if (!legacyAuthState) return null;
574
- if (Date.parse(legacyAuthState.expiresAt) <= Date.now()) {
575
- await deleteFileIfExists(legacyAuthStateFile);
576
- return null;
577
- }
578
- await writeAuthState(config.authStatePath, legacyAuthState);
579
- await deleteFileIfExists(legacyAuthStateFile);
580
- return legacyAuthState;
581
- };
582
- export const buildSkillMarkdown = item => {
583
- const artifactBody = item.publishedArtifact.markdownBody.trim();
584
- const fallbackBody = item.publishedArtifact.renderedContent.trim();
585
- const body = artifactBody || fallbackBody;
586
- if (body.startsWith('---')) {
587
- return body.endsWith('\n') ? body : `${body}\n`;
588
- }
589
- const name = formatSkillLabel(item);
590
- const description = item.publishedArtifact.frontmatterDescription.trim() || item.skill.summary?.trim() || '';
591
- const frontmatter = ['---', `name: ${toFrontmatterString(name)}`, `description: ${toFrontmatterString(description)}`, '---'].join('\n');
592
- if (!body) {
593
- return `${frontmatter}\n`;
594
- }
595
- return `${frontmatter}\n\n${body.endsWith('\n') ? body : `${body}\n`}`;
596
- };
597
- const getSkillIdentifiers = item => {
598
- const candidates = [item.skill.slug, item.publishedArtifact.frontmatterName, item.skill.name];
599
- const seen = new Set();
600
- return candidates.reduce((all, candidate) => {
601
- const normalized = candidate.trim();
602
- if (!normalized) return all;
603
- const cacheKey = normalized.toLowerCase();
604
- if (seen.has(cacheKey)) return all;
605
- seen.add(cacheKey);
606
- all.push(normalized);
607
- return all;
608
- }, []);
609
- };
610
- const toPublishedSkillFacetSummary = facet => ({
611
- slug: facet.slug,
612
- label: facet.label,
613
- description: facet.description ?? null
614
- });
615
- const toPublishedSkillTagSummary = tag => ({
616
- slug: tag.slug,
617
- label: tag.label,
618
- description: tag.description ?? null,
619
- facet: tag.facet ? toPublishedSkillFacetSummary(tag.facet) : null
620
- });
621
- const getPublishedSkillFacets = items => {
622
- const facetsBySlug = new Map();
623
- for (const item of items) {
624
- for (const tag of item.skill.tags) {
625
- if (!tag.facet) continue;
626
- if (facetsBySlug.has(tag.facet.slug)) continue;
627
- facetsBySlug.set(tag.facet.slug, toPublishedSkillFacetSummary(tag.facet));
628
- }
629
- }
630
- return [...facetsBySlug.values()].sort((left, right) => left.slug.localeCompare(right.slug));
631
- };
632
- const isUserPublishedSkillAssignment = assignmentSource => assignmentSource === 'USER' || assignmentSource === 'USER_GLOBAL' || assignmentSource === 'USER_WORKSPACE';
633
- const getPublishedSkillAssignmentLabel = assignmentSource => {
634
- if (assignmentSource === 'GLOBAL') return 'GLOBAL SCOPE assignment';
635
- if (assignmentSource === 'WORKSPACE') return 'PROJECT SCOPE assignment';
636
- if (assignmentSource === 'USER_GLOBAL') return 'USER SCOPE preference (global target)';
637
- if (assignmentSource === 'USER_WORKSPACE') return 'USER SCOPE preference (project target)';
638
- if (assignmentSource === 'USER') return 'USER SCOPE assignment';
639
- return `${assignmentSource.toUpperCase().replace(/_/gu, ' ')} assignment`;
640
- };
641
- const getPublishedSkillAssignmentCounts = items => items.reduce((counts, item) => {
642
- if (isUserPublishedSkillAssignment(item.assignmentSource)) {
643
- return {
644
- ...counts,
645
- user: counts.user + 1
646
- };
647
- }
648
- if (item.assignmentSource === 'GLOBAL') {
649
- return {
650
- ...counts,
651
- global: counts.global + 1
652
- };
653
- }
654
- if (item.assignmentSource === 'WORKSPACE') {
655
- return {
656
- ...counts,
657
- project: counts.project + 1
658
- };
659
- }
660
- return {
661
- ...counts,
662
- other: counts.other + 1
663
- };
664
- }, {
665
- global: 0,
666
- project: 0,
667
- user: 0,
668
- other: 0
669
- });
670
- const getSkillContextKind = item => {
671
- if (item.assignmentSource === 'GLOBAL' || item.assignmentSource === 'USER_GLOBAL') return 'global';
672
- return 'project';
673
- };
674
- const getSkillPolicyLabel = (policy, contextKind, assignmentSource) => {
675
- if (isUserPublishedSkillAssignment(assignmentSource) && policy === 'GLOBAL_CONTEXT') {
676
- return 'GLOBAL_CONTEXT · active USER SCOPE context';
677
- }
678
- if (isUserPublishedSkillAssignment(assignmentSource)) return 'PROJECT_INSTALLABLE · active USER SCOPE preference';
679
- if (policy === 'GLOBAL_CONTEXT') return 'GLOBAL_CONTEXT · active context only, not project-installable';
680
- if (contextKind === 'installable') return 'PROJECT_INSTALLABLE · available to install';
681
- if (contextKind === 'global') return 'PROJECT_INSTALLABLE · active GLOBAL SCOPE assignment';
682
- return 'PROJECT_INSTALLABLE · active PROJECT SCOPE assignment';
683
- };
684
- const toPublishedSkillSummary = item => {
685
- const contextKind = getSkillContextKind(item);
686
- return {
687
- skillSlug: item.skill.slug,
688
- skillName: item.skill.name,
689
- artifactName: item.publishedArtifact.frontmatterName,
690
- artifactDescription: item.publishedArtifact.frontmatterDescription,
691
- whenToUse: item.skill.whenToUse ?? null,
692
- version: item.skillVersion.version,
693
- assignmentSource: item.assignmentSource,
694
- assignmentType: item.assignmentType,
695
- scopePath: item.scopePath,
696
- includeChildren: item.includeChildren ?? null,
697
- checksum: item.publishedArtifact.checksum,
698
- publishedAt: item.publishedArtifact.publishedAt,
699
- fileCount: item.publishedArtifact.fileCount,
700
- identifiers: getSkillIdentifiers(item),
701
- tags: item.skill.tags.map(toPublishedSkillTagSummary),
702
- contextKind,
703
- installPolicy: item.skill.installPolicy,
704
- assignmentLabel: getPublishedSkillAssignmentLabel(item.assignmentSource),
705
- policyLabel: getSkillPolicyLabel(item.skill.installPolicy, contextKind, item.assignmentSource)
706
- };
707
- };
708
- export const toPublishedSkillDetail = item => ({
709
- ...toPublishedSkillSummary(item),
710
- skillId: item.skill.id,
711
- skillVersionId: item.skillVersion.id,
712
- artifactId: item.publishedArtifact.id,
713
- markdownDocument: buildSkillMarkdown(item),
714
- markdownBody: item.publishedArtifact.markdownBody,
715
- renderedContent: item.publishedArtifact.renderedContent,
716
- files: item.publishedArtifact.files,
717
- resources: item.publishedArtifact.files.filter(file => file.relativePath !== 'SKILL.md')
718
- });
719
- const toInstallableSkillSummary = item => ({
720
- skillSlug: item.skill.slug,
721
- skillName: item.skill.name,
722
- artifactName: item.publishedArtifact.frontmatterName,
723
- artifactDescription: item.publishedArtifact.frontmatterDescription,
724
- whenToUse: item.skill.whenToUse ?? null,
725
- version: item.skillVersion.version,
726
- assignmentSource: 'CATALOG',
727
- assignmentType: 'PATH',
728
- scopePath: '',
729
- includeChildren: true,
730
- checksum: item.publishedArtifact.checksum,
731
- publishedAt: item.publishedArtifact.publishedAt,
732
- fileCount: item.publishedArtifact.fileCount,
733
- identifiers: getSkillIdentifiers({
734
- ...item,
735
- assignmentSource: 'CATALOG',
736
- assignmentType: 'PATH',
737
- scopePath: '',
738
- includeChildren: true
739
- }),
740
- tags: item.skill.tags.map(toPublishedSkillTagSummary),
741
- contextKind: 'installable',
742
- installPolicy: item.skill.installPolicy,
743
- assignmentLabel: 'catalog skill',
744
- policyLabel: getSkillPolicyLabel(item.skill.installPolicy, 'installable', 'CATALOG')
745
- });
746
- export const toPublishedSkillCatalog = payload => ({
747
- pluginId: PLUGIN_ID,
748
- runtimeMode: 'tool_fetch_only',
749
- deliveryModel: 'backend_published_installed_effective_skills',
750
- workspace: payload.workspace,
751
- directoryPath: payload.directoryPath,
752
- rootSkillSeedPath: ROOT_SKILL_SEED_PATH,
753
- availableTools: AVAILABLE_PUBLISHED_SKILL_TOOLS,
754
- publishedSkillCount: payload.skills.length,
755
- assignmentCounts: getPublishedSkillAssignmentCounts(payload.skills),
756
- facets: getPublishedSkillFacets(payload.skills),
757
- skills: payload.skills.map(toPublishedSkillSummary)
758
- });
759
- const filterIgnoredPublishedSkills = async (config, result) => {
760
- const authState = await readGlobalAuthState(config.authStatePath);
761
- const userKey = toStoredUserKey(authState);
762
- if (!result.fetchResult.ok) {
763
- return {
764
- ...result,
765
- ignoreState: {
766
- scopeKey: getPublishedSkillIgnoreScopeKey(result.workspaceResolution),
767
- userKey,
768
- ignoredSkillSlugs: [],
769
- installedGlobalSkillSlugs: [],
770
- installedWorkspaceSkillSlugs: []
771
- },
772
- ignoredSkills: []
773
- };
774
- }
775
- const ignoredSkills = result.fetchResult.payload.userPreferences.ignoredSkills.map(toPublishedSkillSummary);
776
- const ignoredSkillSlugs = ignoredSkills.map(skill => skill.skillSlug);
777
- return {
778
- ...result,
779
- ignoreState: {
780
- scopeKey: result.fetchResult.payload.userPreferences.scopeKey,
781
- userKey: result.fetchResult.payload.userPreferences.userKey || userKey,
782
- ignoredSkillSlugs,
783
- installedGlobalSkillSlugs: [],
784
- installedWorkspaceSkillSlugs: []
785
- },
786
- ignoredSkills
787
- };
788
- };
789
- const getWorkspaceUnavailableMessage = payload => {
790
- if (payload.workspace) return null;
791
- return 'Workspace-specific skills are unavailable because the workspace was not found; global skills are still loaded.';
792
- };
793
- const normalizeSkillIdentifier = value => value.trim().toLowerCase();
794
- const parseSkillIdentifiers = value => {
795
- const seen = new Set();
796
- return value.split(/[\n,]/).map(item => item.trim()).filter(item => item.length > 0).filter(item => {
797
- const normalized = normalizeSkillIdentifier(item);
798
- if (seen.has(normalized)) return false;
799
- seen.add(normalized);
800
- return true;
801
- });
802
- };
803
- const mergeSkillIdentifiers = values => {
804
- const seen = new Set();
805
- return values.filter(value => {
806
- const normalized = normalizeSkillIdentifier(value);
807
- if (!normalized || seen.has(normalized)) return false;
808
- seen.add(normalized);
809
- return true;
810
- });
811
- };
812
- export const parseRequestedSkillArgs = args => {
813
- const requestedSkills = [];
814
- if (typeof args.skill === 'string') {
815
- requestedSkills.push(...parseSkillIdentifiers(args.skill));
816
- }
817
- if (typeof args.skills === 'string') {
818
- requestedSkills.push(...parseSkillIdentifiers(args.skills));
819
- }
820
- return mergeSkillIdentifiers(requestedSkills);
821
- };
822
- export const selectPublishedSkills = (payload, identifiers) => {
823
- const itemsByIdentifier = new Map();
824
- for (const item of payload.skills) {
825
- for (const identifier of getSkillIdentifiers(item)) {
826
- itemsByIdentifier.set(normalizeSkillIdentifier(identifier), item);
827
- }
828
- }
829
- const selectedItems = [];
830
- const selectedKeys = new Set();
831
- const missingIdentifiers = [];
832
- for (const identifier of identifiers) {
833
- const matched = itemsByIdentifier.get(normalizeSkillIdentifier(identifier));
834
- if (!matched) {
835
- missingIdentifiers.push(identifier);
836
- continue;
837
- }
838
- if (selectedKeys.has(matched.publishedArtifact.id)) {
839
- continue;
840
- }
841
- selectedKeys.add(matched.publishedArtifact.id);
842
- selectedItems.push(matched);
843
- }
844
- return {
845
- selectedItems,
846
- missingIdentifiers
847
- };
848
- };
849
- const truncateText = (value, maxLength) => {
850
- const normalized = value.replace(/\s+/gu, ' ').trim();
851
- if (normalized.length <= maxLength) return normalized;
852
- return `${normalized.slice(0, Math.max(maxLength - 1, 0)).trimEnd()}…`;
853
- };
854
- const buildSkillCatalogLine = skill => {
855
- const description = truncateText(skill.whenToUse || skill.artifactDescription || skill.skillName || skill.skillSlug, SYSTEM_NOTE_SKILL_DESCRIPTION_LIMIT);
856
- const scopeLabel = isUserPublishedSkillAssignment(skill.assignmentSource) ? 'USER SCOPE' : skill.contextKind === 'global' ? 'GLOBAL SCOPE' : 'PROJECT SCOPE';
857
- const assignmentLabel = skill.assignmentSource.toLowerCase().replace(/_/gu, ' ');
858
- return `- ${skill.artifactName || skill.skillName} (${skill.skillSlug}, ${assignmentLabel} assignment) [${scopeLabel}]: ${description}`;
859
- };
860
- const buildSkillDetailSnippetLine = detail => {
861
- const body = detail.markdownBody || detail.renderedContent || detail.markdownDocument;
862
- return `- ${detail.artifactName || detail.skillName}: ${truncateText(body, 700)}`;
863
- };
864
- export const buildSystemNote = (result, config, details) => {
865
- if (!result.fetchResult.ok) return null;
866
- const catalog = toPublishedSkillCatalog(result.fetchResult.payload);
867
- const skillNames = catalog.skills.map(skill => skill.artifactName || skill.skillName || skill.skillSlug);
868
- const renderedSkillNames = skillNames.length > 0 ? skillNames.slice(0, SYSTEM_NOTE_SKILL_NAME_LIMIT).join(', ') : 'none';
869
- const remainingCount = Math.max(skillNames.length - SYSTEM_NOTE_SKILL_NAME_LIMIT, 0);
870
- const renderedCountSuffix = remainingCount > 0 ? ` (+${remainingCount} more)` : '';
871
- const globalSkills = catalog.skills.filter(skill => skill.contextKind === 'global' && !isUserPublishedSkillAssignment(skill.assignmentSource)).slice(0, 8).map(buildSkillCatalogLine);
872
- const projectSkills = catalog.skills.filter(skill => skill.contextKind === 'project' && !isUserPublishedSkillAssignment(skill.assignmentSource)).slice(0, 5).map(buildSkillCatalogLine);
873
- const userSkills = catalog.skills.filter(skill => isUserPublishedSkillAssignment(skill.assignmentSource)).slice(0, 5).map(buildSkillCatalogLine);
874
- const detailLines = details.slice(0, SYSTEM_NOTE_DETAIL_LIMIT).map(buildSkillDetailSnippetLine);
875
- const detailBlock = detailLines.length > 0 ? `Loaded body snippets (capped):\n${truncateText(detailLines.join('\n'), SYSTEM_NOTE_DETAIL_CHAR_LIMIT)}` : '';
876
- return [result.fetchResult.payload.workspace ? `Workspace: ${result.fetchResult.payload.workspace.slug}.` : 'Workspace not found; workspace-scoped wizard skills are unavailable.', `Current directory: ${result.directoryPath}.`, `Active wizard skills: ${renderedSkillNames}${renderedCountSuffix}.`, `Counts: ${catalog.assignmentCounts.global} global, ${catalog.assignmentCounts.project} project, ${catalog.assignmentCounts.user} user, ${catalog.assignmentCounts.other} other.`, 'Wizard-listed skills are backend-published, not native OpenCode skills.', 'Use native skill tooling only for names in native available_skills.', 'When a wizard skill matches by whenToUse, fetch its current body with opencode_wizard_published_skills_fetch before using it.', 'Use `skills` for multiple wizard skill identifiers; use `skill` for one.', 'If native skill loading cannot find a wizard-listed skill, fetch it as a wizard skill instead.', 'Fetched wizard bodies are authoritative over local seed/native sources.', globalSkills.length > 0 ? `Global skills:\n${globalSkills.join('\n')}` : 'Global skills: none.', projectSkills.length > 0 ? `Project skills:\n${projectSkills.join('\n')}` : 'Project skills: none.', userSkills.length > 0 ? `User skills:\n${userSkills.join('\n')}` : 'User skills: none.', detailBlock].filter(Boolean).join(' ');
877
- };
878
- const toWorkspaceResolutionOutput = resolution => ({
879
- requestedDirectory: resolution.requestedDirectory,
880
- repositoryRoot: resolution.repositoryRoot,
881
- repositoryUrl: resolution.repositoryUrl,
882
- fallbackWorkspaceSlug: resolution.fallbackWorkspaceSlug,
883
- directoryPath: resolution.directoryPath
884
- });
885
- const toWorkspaceResolutionMetadata = resolution => ({
886
- directoryPath: resolution.directoryPath,
887
- repositoryRoot: resolution.repositoryRoot,
888
- repositoryUrl: resolution.repositoryUrl ?? '',
889
- fallbackWorkspaceSlug: resolution.fallbackWorkspaceSlug ?? ''
890
- });
891
- const formatStatusOutput = async (worktree, config, publishedSkillsResult, loginBootstrapSnapshot) => {
892
- const authState = await resolveStoredAuthState(worktree, config);
893
- const filteredResult = await filterIgnoredPublishedSkills(config, publishedSkillsResult);
894
- const base = {
895
- pluginId: PLUGIN_ID,
896
- runtimeMode: 'tool_fetch_only',
897
- nativeSkillsUrlCompatibility: NATIVE_SKILLS_URL_COMPATIBILITY,
898
- backendOrigin: config.backendOrigin,
899
- graphqlUrl: config.graphqlUrl,
900
- fallbackWorkspaceSlug: config.fallbackWorkspaceSlug,
901
- workspaceResolution: toWorkspaceResolutionOutput(publishedSkillsResult.workspaceResolution),
902
- rootSkillSeedPath: config.rootSkillSeedPath,
903
- authStatePath: config.authStatePath,
904
- requestedDirectoryPath: publishedSkillsResult.directoryPath,
905
- authMode: publishedSkillsResult.fetchResult.authMode,
906
- authState: authState === null ? null : {
907
- email: authState.email,
908
- userId: authState.userId,
909
- authenticatedAt: authState.authenticatedAt,
910
- expiresAt: authState.expiresAt
911
- },
912
- loginBootstrap: loginBootstrapSnapshot.status === 'idle' ? null : {
913
- status: loginBootstrapSnapshot.status,
914
- trigger: loginBootstrapSnapshot.trigger,
915
- startedAt: loginBootstrapSnapshot.startedAt,
916
- expiresAt: loginBootstrapSnapshot.expiresAt,
917
- browserUrl: loginBootstrapSnapshot.browserUrl,
918
- browserOpenError: loginBootstrapSnapshot.browserOpenError,
919
- email: loginBootstrapSnapshot.email,
920
- message: loginBootstrapSnapshot.message
921
- },
922
- status: filteredResult.fetchResult.status,
923
- fetchedAt: filteredResult.fetchResult.fetchedAt,
924
- source: filteredResult.fetchResult.source,
925
- availableTools: AVAILABLE_PUBLISHED_SKILL_TOOLS,
926
- ignoredPublishedSkills: {
927
- scopeKey: filteredResult.ignoreState.scopeKey,
928
- userKey: filteredResult.ignoreState.userKey,
929
- count: filteredResult.ignoreState.ignoredSkillSlugs.length
930
- }
931
- };
932
- if (!filteredResult.fetchResult.ok) {
933
- return JSON.stringify({
934
- ...base,
935
- message: filteredResult.fetchResult.message
936
- }, null, 2);
937
- }
938
- return JSON.stringify({
939
- ...base,
940
- ...toPublishedSkillCatalog(filteredResult.fetchResult.payload),
941
- message: getWorkspaceUnavailableMessage(filteredResult.fetchResult.payload)
942
- }, null, 2);
943
- };
944
- export const toPluginAuthStateSummary = authState => {
945
- if (!authState) {
946
- return {
947
- status: 'missing',
948
- email: null,
949
- userId: null,
950
- authenticatedAt: null,
951
- expiresAt: null
952
- };
953
- }
954
- return {
955
- status: 'authenticated',
956
- email: authState.email,
957
- userId: authState.userId,
958
- authenticatedAt: authState.authenticatedAt,
959
- expiresAt: authState.expiresAt
960
- };
961
- };
962
- export const resolvePluginStatusSnapshot = async ({
963
- worktree,
964
- directory,
965
- signal
966
- }) => {
967
- const config = await resolveConfig(worktree);
968
- const workspaceResolution = await resolveWorkspace({
969
- config,
970
- directory
971
- });
972
- const fetchResult = await fetchPublishedSkillsCatalog(worktree, config, workspaceResolution, signal);
973
- const filteredResult = await filterIgnoredPublishedSkills(config, {
974
- directoryPath: workspaceResolution.directoryPath,
975
- workspaceResolution,
976
- fetchResult
977
- });
978
- const authState = await resolveStoredAuthState(worktree, config);
979
- return {
980
- pluginId: PLUGIN_ID,
981
- runtimeMode: 'tool_fetch_only',
982
- nativeSkillsUrlCompatibility: NATIVE_SKILLS_URL_COMPATIBILITY,
983
- backendOrigin: config.backendOrigin,
984
- graphqlUrl: config.graphqlUrl,
985
- fallbackWorkspaceSlug: config.fallbackWorkspaceSlug,
986
- workspaceResolution: toWorkspaceResolutionOutput(workspaceResolution),
987
- rootSkillSeedPath: config.rootSkillSeedPath,
988
- authStatePath: config.authStatePath,
989
- authState: toPluginAuthStateSummary(authState),
990
- status: filteredResult.fetchResult.status,
991
- authMode: filteredResult.fetchResult.authMode,
992
- fetchedAt: filteredResult.fetchResult.fetchedAt,
993
- source: filteredResult.fetchResult.source,
994
- availableTools: AVAILABLE_PUBLISHED_SKILL_TOOLS,
995
- message: filteredResult.fetchResult.ok ? getWorkspaceUnavailableMessage(filteredResult.fetchResult.payload) : filteredResult.fetchResult.message,
996
- catalog: filteredResult.fetchResult.ok ? toPublishedSkillCatalog(filteredResult.fetchResult.payload) : null,
997
- installableCatalog: filteredResult.fetchResult.ok ? {
998
- count: filteredResult.fetchResult.payload.catalogSkills.length,
999
- skills: filteredResult.fetchResult.payload.catalogSkills.map(toInstallableSkillSummary)
1000
- } : null,
1001
- ignoredPublishedSkills: {
1002
- scopeKey: filteredResult.ignoreState.scopeKey,
1003
- userKey: filteredResult.ignoreState.userKey,
1004
- count: filteredResult.ignoreState.ignoredSkillSlugs.length,
1005
- skills: filteredResult.ignoredSkills
1006
- }
1007
- };
1008
- };
1009
- const withStatusMessage = (snapshot, message) => ({
1010
- ...snapshot,
1011
- message
1012
- });
1013
- const toAiFacingPluginStatusSnapshot = snapshot => {
1014
- const {
1015
- ignoredPublishedSkills,
1016
- installableCatalog: _installableCatalog,
1017
- ...safeSnapshot
1018
- } = snapshot;
1019
- return {
1020
- ...safeSnapshot,
1021
- ignoredPublishedSkills: {
1022
- scopeKey: ignoredPublishedSkills.scopeKey,
1023
- count: ignoredPublishedSkills.count
1024
- }
1025
- };
1026
- };
1027
- const startStatusPathLoginBootstrap = (worktree, config) => {
1028
- if (statusPathLoginBootstrap.promise) return;
1029
- if (statusPathLoginBootstrap.status === 'failed' && statusPathLoginBootstrap.failedAt && Date.now() - statusPathLoginBootstrap.failedAt < STATUS_PATH_LOGIN_RETRY_COOLDOWN_MS) {
1030
- return;
1031
- }
1032
- statusPathLoginBootstrap.status = 'pending';
1033
- statusPathLoginBootstrap.message = 'Browser login started automatically from the TUI/status path.';
1034
- statusPathLoginBootstrap.failedAt = null;
1035
- statusPathLoginBootstrap.promise = (async () => {
1036
- const loginSignal = AbortSignal.timeout(LOGIN_TIMEOUT_MS);
1037
- const loginStart = await startLoginFlow(loginSignal);
1038
- const browserOpenError = await openBrowser(loginStart.browserUrl);
1039
- if (browserOpenError) {
1040
- statusPathLoginBootstrap.message = `Automatic browser open failed. Open ${loginStart.browserUrl} manually.`;
1041
- }
1042
- try {
1043
- const callbackPayload = await loginStart.callbackPromise;
1044
- if (callbackPayload.status === 'error') {
1045
- throw new Error(callbackPayload.message);
1046
- }
1047
- if (callbackPayload.state !== loginStart.expectedState) {
1048
- throw new Error('OAuth callback state did not match the original login request.');
1049
- }
1050
- const pluginSession = await createPluginSession({
1051
- code: callbackPayload.code,
1052
- codeVerifier: loginStart.codeVerifier,
1053
- redirectUri: OIDC_CALLBACK_URL,
1054
- config,
1055
- signal: loginSignal
1056
- });
1057
- const authState = toAuthState(pluginSession);
1058
- await writeAuthState(config.authStatePath, authState);
1059
- statusPathLoginBootstrap.status = 'authenticated';
1060
- statusPathLoginBootstrap.message = `Browser login completed successfully for ${authState.email}.`;
1061
- return authState;
1062
- } finally {
1063
- await loginStart.closeCallbackServer().catch(() => undefined);
1064
- }
1065
- })().catch(error => {
1066
- statusPathLoginBootstrap.status = 'failed';
1067
- statusPathLoginBootstrap.failedAt = Date.now();
1068
- statusPathLoginBootstrap.message = error instanceof Error ? error.message : 'Browser login failed.';
1069
- throw error;
1070
- }).finally(() => {
1071
- statusPathLoginBootstrap.promise = null;
1072
- });
1073
- statusPathLoginBootstrap.promise.catch(() => undefined);
1074
- };
1075
- export const resolvePluginStatusSnapshotWithAuthBootstrap = async ({
1076
- worktree,
1077
- directory,
1078
- signal
1079
- }) => {
1080
- const snapshot = await resolvePluginStatusSnapshot({
1081
- worktree,
1082
- directory,
1083
- signal
1084
- });
1085
- if (snapshot.status !== 'missing_auth') return snapshot;
1086
- const config = await resolveConfig(worktree);
1087
- startStatusPathLoginBootstrap(worktree, config);
1088
- if (statusPathLoginBootstrap.message) {
1089
- return withStatusMessage(snapshot, statusPathLoginBootstrap.message);
1090
- }
1091
- return withStatusMessage(snapshot, 'Browser login is pending from the TUI/status path.');
1092
- };
1093
- const toBackendPreferenceScope = preferenceScope => {
1094
- if (preferenceScope === 'global') return 'GLOBAL';
1095
- return 'WORKSPACE';
1096
- };
1097
- const setPublishedSkillPreference = async ({
1098
- worktree,
1099
- directory,
1100
- config,
1101
- skillSlug,
1102
- preferenceScope,
1103
- installed,
1104
- ignored
1105
- }) => {
1106
- const workspaceResolution = await resolveWorkspace({
1107
- config,
1108
- directory
1109
- });
1110
- const response = await fetchPublishedSkillsGraphQl({
1111
- worktree,
1112
- config,
1113
- query: SET_PUBLISHED_SKILL_PREFERENCE_MUTATION,
1114
- variables: {
1115
- input: {
1116
- ...toDeliveryInput(workspaceResolution),
1117
- skillSlug,
1118
- preferenceScope: toBackendPreferenceScope(preferenceScope),
1119
- installed,
1120
- ignored
1121
- }
1122
- },
1123
- signal: AbortSignal.timeout(PRESENCE_EVENT_TIMEOUT_MS)
1124
- });
1125
- if (!response.ok) {
1126
- throw new Error(response.result.message);
1127
- }
1128
- const preferences = response.data.setPublishedSkillPreference;
1129
- publishedSkillPreferenceCacheVersion += 1;
1130
- return {
1131
- scopeKey: preferences.scopeKey,
1132
- userKey: preferences.userKey,
1133
- ignoredSkillSlugs: preferences.ignoredSkills.map(item => item.skill.slug),
1134
- installedGlobalSkillSlugs: [],
1135
- installedWorkspaceSkillSlugs: []
1136
- };
1137
- };
1138
- export const setPublishedSkillIgnored = async ({
1139
- worktree,
1140
- directory,
1141
- skillSlug,
1142
- ignored,
1143
- preferenceScope
1144
- }) => {
1145
- const config = await resolveConfig(worktree);
1146
- const normalizedSkillSlug = toIgnoredSkillSlug(skillSlug);
1147
- if (!normalizedSkillSlug) {
1148
- throw new Error('Cannot toggle an empty published skill slug.');
1149
- }
1150
- return setPublishedSkillPreference({
1151
- worktree,
1152
- directory,
1153
- config,
1154
- skillSlug: normalizedSkillSlug,
1155
- preferenceScope: preferenceScope ?? 'project',
1156
- ignored
1157
- });
1158
- };
1159
- export const setPublishedSkillInstalled = async ({
1160
- worktree,
1161
- directory,
1162
- skillSlug,
1163
- installed,
1164
- preferenceScope
1165
- }) => {
1166
- const config = await resolveConfig(worktree);
1167
- const normalizedSkillSlug = toIgnoredSkillSlug(skillSlug);
1168
- if (!normalizedSkillSlug) {
1169
- throw new Error('Cannot toggle an empty published skill slug.');
1170
- }
1171
- return setPublishedSkillPreference({
1172
- worktree,
1173
- directory,
1174
- config,
1175
- skillSlug: normalizedSkillSlug,
1176
- preferenceScope,
1177
- installed
1178
- });
1179
- };
1180
- const toPluginStatusMetadata = snapshot => ({
1181
- backendOrigin: snapshot.backendOrigin,
1182
- graphqlUrl: snapshot.graphqlUrl,
1183
- pluginStatus: snapshot.status,
1184
- authStatus: snapshot.authState.status,
1185
- authEmail: snapshot.authState.email ?? '',
1186
- authUserId: snapshot.authState.userId ?? ''
1187
- });
1188
- const isUnauthorizedGraphQlMessage = message => {
1189
- const normalizedMessage = message.toLowerCase();
1190
- return normalizedMessage.includes('not authorized') || normalizedMessage.includes('unauthorized');
1191
- };
1192
- const createRandomBase64Url = bytes => {
1193
- return crypto.randomBytes(bytes).toString('base64url');
1194
- };
1195
- const createCodeChallenge = codeVerifier => {
1196
- return crypto.createHash('sha256').update(codeVerifier).digest('base64url');
1197
- };
1198
- const getMessageFromUnknownPayload = value => {
1199
- if (!value || typeof value !== 'object') return null;
1200
- const candidate = 'message' in value ? value.message : null;
1201
- return typeof candidate === 'string' ? candidate : null;
1202
- };
1203
- const wait = async milliseconds => {
1204
- await new Promise(resolve => {
1205
- setTimeout(resolve, milliseconds);
1206
- });
1207
- };
1208
- const shouldRetryPresenceEvent = status => {
1209
- return status === 408 || status === 429 || status >= 500;
1210
- };
1211
- const fetchOidcDiscoveryDocument = async signal => {
1212
- const discoveryUrl = `${OIDC_ISSUER.replace(/\/+$/, '')}/.well-known/openid-configuration`;
1213
- const response = await fetch(discoveryUrl, {
1214
- method: 'GET',
1215
- signal
1216
- });
1217
- if (!response.ok) {
1218
- throw new Error(`OIDC discovery failed with HTTP ${response.status}.`);
1219
- }
1220
- return await response.json();
1221
- };
1222
- const isCallbackPortInUseError = error => {
1223
- if (!error || typeof error !== 'object') return false;
1224
- if (!('code' in error)) return false;
1225
- return error.code === 'EADDRINUSE';
1226
- };
1227
- const toCallbackServerStartError = error => {
1228
- if (!isCallbackPortInUseError(error)) {
1229
- return error instanceof Error ? error : new Error('Failed to start local OAuth callback server.');
1230
- }
1231
- return new Error('OAuth login cannot start because localhost:24953 is already in use. Another OpenCode login is likely in progress; finish it or close the other instance, then retry.');
1232
- };
1233
- const startLocalCallbackServer = async ({
1234
- expectedState,
1235
- signal
1236
- }) => {
1237
- let settled = false;
1238
- let resolvePayload = () => undefined;
1239
- let rejectPayload = () => undefined;
1240
- const callbackPromise = new Promise((resolve, reject) => {
1241
- resolvePayload = resolve;
1242
- rejectPayload = reject;
1243
- });
1244
- const finalize = payload => {
1245
- if (settled) return;
1246
- settled = true;
1247
- resolvePayload(payload);
1248
- };
1249
- const fail = reason => {
1250
- if (settled) return;
1251
- settled = true;
1252
- rejectPayload(reason);
1253
- };
1254
- const server = http.createServer((request, response) => {
1255
- const requestUrl = new URL(request.url ?? '/', OIDC_CALLBACK_ORIGIN);
1256
- if (requestUrl.pathname !== OIDC_CALLBACK_PATH) {
1257
- sendOAuthCallbackHtmlResponse(response, 404, 'opencode-wizard plugin login', 'Unknown callback path.');
1258
- return;
1259
- }
1260
- const error = requestUrl.searchParams.get('error');
1261
- const errorDescription = requestUrl.searchParams.get('error_description');
1262
- if (error) {
1263
- const message = errorDescription ?? error;
1264
- sendOAuthCallbackHtmlResponse(response, 400, 'opencode-wizard plugin login failed', message);
1265
- finalize({
1266
- status: 'error',
1267
- message
1268
- });
1269
- return;
1270
- }
1271
- const state = requestUrl.searchParams.get('state');
1272
- const code = requestUrl.searchParams.get('code');
1273
- if (!state || state !== expectedState) {
1274
- sendOAuthCallbackHtmlResponse(response, 400, 'opencode-wizard plugin login failed', 'OAuth state did not match the login request.');
1275
- finalize({
1276
- status: 'error',
1277
- message: 'OAuth state did not match the login request.'
1278
- });
1279
- return;
1280
- }
1281
- if (!code) {
1282
- sendOAuthCallbackHtmlResponse(response, 400, 'opencode-wizard plugin login failed', 'OAuth callback did not include an authorization code.');
1283
- finalize({
1284
- status: 'error',
1285
- message: 'OAuth callback did not include an authorization code.'
1286
- });
1287
- return;
1288
- }
1289
- sendOAuthCallbackHtmlResponse(response, 200, 'opencode-wizard plugin callback received', 'Callback received. OpenCode is finalizing the backend session now.');
1290
- finalize({
1291
- status: 'success',
1292
- code,
1293
- state
1294
- });
1295
- });
1296
- const close = async () => {
1297
- await new Promise((resolve, reject) => {
1298
- server.close(error => {
1299
- if (error) {
1300
- reject(error);
1301
- return;
1302
- }
1303
- resolve();
1304
- });
1305
- });
1306
- };
1307
- await new Promise((resolve, reject) => {
1308
- const rejectStart = error => {
1309
- reject(toCallbackServerStartError(error));
1310
- };
1311
- server.once('error', rejectStart);
1312
- server.listen(24953, 'localhost', () => {
1313
- server.off('error', rejectStart);
1314
- server.on('error', error => {
1315
- fail(error instanceof Error ? error : new Error('Local OAuth callback server failed.'));
1316
- });
1317
- resolve();
1318
- });
1319
- });
1320
- signal.addEventListener('abort', () => {
1321
- fail(signal.reason instanceof Error ? signal.reason : new Error('OAuth login aborted.'));
1322
- void close().catch(() => undefined);
1323
- }, {
1324
- once: true
1325
- });
1326
- return {
1327
- callbackPromise,
1328
- close
1329
- };
1330
- };
1331
- const fetchPublishedSkillsGraphQl = async ({
1332
- worktree,
1333
- config,
1334
- query,
1335
- variables,
1336
- signal,
1337
- onAuthStateChanged
1338
- }) => {
1339
- const authState = await resolveStoredAuthState(worktree, config);
1340
- const fetchedAt = new Date().toISOString();
1341
- if (!authState) {
1342
- return {
1343
- ok: false,
1344
- result: {
1345
- ok: false,
1346
- status: 'missing_auth',
1347
- authMode: 'missing',
1348
- message: 'No plugin session is stored. Interactive opencode_wizard_published_skills_fetch can bootstrap browser login automatically when needed. Configured backend and GraphQL URLs are shown for visibility, but no GraphQL request was made because auth is missing.',
1349
- fetchedAt,
1350
- source: 'network'
1351
- }
1352
- };
1353
- }
1354
- let response;
1355
- try {
1356
- response = await fetch(config.graphqlUrl, {
1357
- method: 'POST',
1358
- headers: {
1359
- 'content-type': 'application/json',
1360
- authorization: `Bearer ${authState.sessionToken}`
1361
- },
1362
- body: JSON.stringify({
1363
- query,
1364
- variables
1365
- }),
1366
- signal
1367
- });
1368
- } catch (error) {
1369
- return {
1370
- ok: false,
1371
- result: {
1372
- ok: false,
1373
- status: 'request_failed',
1374
- authMode: 'session',
1375
- message: error instanceof Error ? error.message : 'Unknown fetch error',
1376
- fetchedAt,
1377
- source: 'network'
1378
- }
1379
- };
1380
- }
1381
- if (response.status === 401 || response.status === 403) {
1382
- await clearAuthState(config.authStatePath);
1383
- onAuthStateChanged?.();
1384
- return {
1385
- ok: false,
1386
- result: {
1387
- ok: false,
1388
- status: 'missing_auth',
1389
- authMode: 'session',
1390
- message: 'Stored plugin session was rejected by the backend. Retry opencode_wizard_published_skills_fetch to bootstrap a fresh browser login automatically.',
1391
- fetchedAt,
1392
- source: 'network'
1393
- }
1394
- };
1395
- }
1396
- if (!response.ok) {
1397
- return {
1398
- ok: false,
1399
- result: {
1400
- ok: false,
1401
- status: 'request_failed',
1402
- authMode: 'session',
1403
- message: `GraphQL request failed with HTTP ${response.status}.`,
1404
- fetchedAt,
1405
- source: 'network'
1406
- }
1407
- };
1408
- }
1409
- let body;
1410
- try {
1411
- body = await response.json();
1412
- } catch (error) {
1413
- return {
1414
- ok: false,
1415
- result: {
1416
- ok: false,
1417
- status: 'request_failed',
1418
- authMode: 'session',
1419
- message: `GraphQL response was not valid JSON: ${error instanceof Error ? error.message : 'Unknown parse error'}`,
1420
- fetchedAt,
1421
- source: 'network'
1422
- }
1423
- };
1424
- }
1425
- if (body.errors?.length) {
1426
- const message = body.errors.map(error => error.message).join('; ');
1427
- if (body.errors.some(error => isUnauthorizedGraphQlMessage(error.message))) {
1428
- await clearAuthState(config.authStatePath);
1429
- onAuthStateChanged?.();
1430
- return {
1431
- ok: false,
1432
- result: {
1433
- ok: false,
1434
- status: 'missing_auth',
1435
- authMode: 'session',
1436
- message: 'Stored plugin session is no longer valid. Retry opencode_wizard_published_skills_fetch to bootstrap a fresh browser login automatically.',
1437
- fetchedAt,
1438
- source: 'network'
1439
- }
1440
- };
1441
- }
1442
- return {
1443
- ok: false,
1444
- result: {
1445
- ok: false,
1446
- status: 'request_failed',
1447
- authMode: 'session',
1448
- message,
1449
- fetchedAt,
1450
- source: 'network'
1451
- }
1452
- };
1453
- }
1454
- if (!body.data) {
1455
- return {
1456
- ok: false,
1457
- result: {
1458
- ok: false,
1459
- status: 'request_failed',
1460
- authMode: 'session',
1461
- message: 'GraphQL response did not include data.',
1462
- fetchedAt,
1463
- source: 'network'
1464
- }
1465
- };
1466
- }
1467
- return {
1468
- ok: true,
1469
- data: body.data,
1470
- fetchedAt
1471
- };
1472
- };
1473
- const fetchPublishedSkillsCatalog = async (worktree, config, resolution, signal, onAuthStateChanged) => {
1474
- const response = await fetchPublishedSkillsGraphQl({
1475
- worktree,
1476
- config,
1477
- query: PUBLISHED_SKILLS_CATALOG_QUERY,
1478
- variables: {
1479
- input: toDeliveryInput(resolution)
1480
- },
1481
- signal,
1482
- onAuthStateChanged
1483
- });
1484
- if (!response.ok) {
1485
- return response.result;
1486
- }
1487
- const payload = response.data.pluginPublishedSkills;
1488
- if (!payload) {
1489
- return {
1490
- ok: false,
1491
- status: 'request_failed',
1492
- authMode: 'session',
1493
- message: 'GraphQL response did not include pluginPublishedSkills.',
1494
- fetchedAt: response.fetchedAt,
1495
- source: 'network'
1496
- };
1497
- }
1498
- return {
1499
- ok: true,
1500
- status: 'ready',
1501
- authMode: 'session',
1502
- payload,
1503
- fetchedAt: response.fetchedAt,
1504
- source: 'network'
1505
- };
1506
- };
1507
- const fetchPublishedSkillDetail = async ({
1508
- worktree,
1509
- config,
1510
- resolution,
1511
- skillVersionId,
1512
- signal,
1513
- onAuthStateChanged,
1514
- purpose
1515
- }) => {
1516
- const response = await fetchPublishedSkillsGraphQl({
1517
- worktree,
1518
- config,
1519
- query: PUBLISHED_SKILL_DETAIL_QUERY,
1520
- variables: {
1521
- input: {
1522
- ...toDeliveryInput(resolution),
1523
- skillVersionId,
1524
- purpose
1525
- }
1526
- },
1527
- signal,
1528
- onAuthStateChanged
1529
- });
1530
- if (!response.ok) {
1531
- return response;
1532
- }
1533
- const artifact = response.data.pluginPublishedSkillVersionArtifact;
1534
- if (!artifact) {
1535
- return {
1536
- ok: false,
1537
- result: {
1538
- ok: false,
1539
- status: 'not_found',
1540
- authMode: 'session',
1541
- message: 'Published skill detail is not effective for the current scope.',
1542
- fetchedAt: response.fetchedAt,
1543
- source: 'network'
1544
- }
1545
- };
1546
- }
1547
- return {
1548
- ok: true,
1549
- artifact
1550
- };
1551
- };
1552
- const toFetchFailureOutput = async ({
1553
- worktree,
1554
- config,
1555
- publishedSkillsResult,
1556
- loginBootstrapSnapshot
1557
- }) => ({
1558
- output: await formatStatusOutput(worktree, config, publishedSkillsResult, loginBootstrapSnapshot),
1559
- metadata: {
1560
- status: publishedSkillsResult.fetchResult.status,
1561
- ...toWorkspaceResolutionMetadata(publishedSkillsResult.workspaceResolution),
1562
- source: publishedSkillsResult.fetchResult.source
1563
- }
1564
- });
1565
- const startLoginFlow = async signal => {
1566
- const discovery = await fetchOidcDiscoveryDocument(signal);
1567
- const codeVerifier = createRandomBase64Url(64);
1568
- const expectedState = createRandomBase64Url(32);
1569
- const codeChallenge = createCodeChallenge(codeVerifier);
1570
- const expiresAt = new Date(Date.now() + LOGIN_TIMEOUT_MS).toISOString();
1571
- const {
1572
- callbackPromise,
1573
- close
1574
- } = await startLocalCallbackServer({
1575
- expectedState,
1576
- signal
1577
- });
1578
- const browserUrl = new URL(discovery.authorization_endpoint);
1579
- browserUrl.searchParams.set('client_id', OIDC_CLIENT_ID);
1580
- browserUrl.searchParams.set('response_type', 'code');
1581
- browserUrl.searchParams.set('redirect_uri', OIDC_CALLBACK_URL);
1582
- browserUrl.searchParams.set('response_mode', 'query');
1583
- browserUrl.searchParams.set('scope', OIDC_SCOPES.join(' '));
1584
- browserUrl.searchParams.set('code_challenge', codeChallenge);
1585
- browserUrl.searchParams.set('code_challenge_method', 'S256');
1586
- browserUrl.searchParams.set('state', expectedState);
1587
- return {
1588
- browserUrl: browserUrl.toString(),
1589
- expiresAt,
1590
- codeVerifier,
1591
- expectedState,
1592
- callbackPromise,
1593
- closeCallbackServer: close
1594
- };
1595
- };
1596
- const createPluginSession = async ({
1597
- code,
1598
- codeVerifier,
1599
- redirectUri,
1600
- config,
1601
- signal
1602
- }) => {
1603
- const response = await fetch(config.authSessionUrl, {
1604
- method: 'POST',
1605
- headers: {
1606
- 'content-type': 'application/json'
1607
- },
1608
- body: JSON.stringify({
1609
- code,
1610
- codeVerifier,
1611
- redirectUri
1612
- }),
1613
- signal
1614
- });
1615
- const payload = await response.json().catch(() => null);
1616
- if (!response.ok) {
1617
- throw new Error(getMessageFromUnknownPayload(payload) ?? `Plugin session exchange failed with HTTP ${response.status}.`);
1618
- }
1619
- if (!payload || !('success' in payload) || payload.success !== true) {
1620
- throw new Error('Plugin session exchange returned an unexpected payload.');
1621
- }
1622
- return payload.session;
1623
- };
1624
- const emitPresenceEvent = async ({
1625
- config,
1626
- authState,
1627
- event,
1628
- workspacePath
1629
- }) => {
1630
- for (let attempt = 1; attempt <= PRESENCE_EVENT_MAX_ATTEMPTS; attempt += 1) {
1631
- try {
1632
- const response = await fetch(config.presenceUrl, {
1633
- method: 'POST',
1634
- headers: {
1635
- 'content-type': 'application/json',
1636
- authorization: `Bearer ${authState.sessionToken}`
1637
- },
1638
- body: JSON.stringify({
1639
- event,
1640
- occurredAt: new Date().toISOString(),
1641
- workspacePath
1642
- }),
1643
- keepalive: event === 'STOP',
1644
- signal: AbortSignal.timeout(PRESENCE_EVENT_TIMEOUT_MS)
1645
- });
1646
- if (response.ok) return;
1647
- if (!shouldRetryPresenceEvent(response.status) || attempt === PRESENCE_EVENT_MAX_ATTEMPTS) return;
1648
- } catch {
1649
- if (attempt === PRESENCE_EVENT_MAX_ATTEMPTS) return;
1650
- }
1651
- await wait(PRESENCE_EVENT_RETRY_DELAY_MS * attempt);
1652
- }
1653
- };
1654
- const emitPluginActionEvent = async ({
1655
- config,
1656
- authState,
1657
- event,
1658
- workspacePath,
1659
- directoryPath
1660
- }) => {
1661
- if (!authState) return;
1662
- try {
1663
- await fetch(config.actionsUrl, {
1664
- method: 'POST',
1665
- headers: {
1666
- 'content-type': 'application/json',
1667
- authorization: `Bearer ${authState.sessionToken}`
1668
- },
1669
- body: JSON.stringify({
1670
- event,
1671
- occurredAt: new Date().toISOString(),
1672
- workspacePath,
1673
- directoryPath
1674
- }),
1675
- keepalive: event === 'STOP',
1676
- signal: AbortSignal.timeout(PRESENCE_EVENT_TIMEOUT_MS)
1677
- });
1678
- } catch {
1679
- return;
1680
- }
1681
- };
1682
- const openBrowser = async url => {
1683
- try {
1684
- if (process.platform === 'darwin') {
1685
- await execFileAsync('open', [url]);
1686
- return null;
1687
- }
1688
- if (process.platform === 'win32') {
1689
- await execFileAsync('cmd', ['/c', 'start', '', url]);
1690
- return null;
1691
- }
1692
- await execFileAsync('xdg-open', [url]);
1693
- return null;
1694
- } catch (error) {
1695
- return error instanceof Error ? error.message : 'Failed to open browser automatically';
1696
- }
1697
- };
1698
- const normalizeDirectoryArg = (contextDirectory, directory) => {
1699
- return normalizeAbsolutePath(directory ? path.resolve(contextDirectory, directory) : contextDirectory);
1700
- };
1701
- const getDetailCacheKey = (catalogCacheKey, skillVersionId) => {
1702
- return JSON.stringify([catalogCacheKey, skillVersionId]);
1703
- };
1704
- const getDetailInflightKey = (catalogCacheKey, skillVersionId, purpose) => {
1705
- return JSON.stringify([catalogCacheKey, skillVersionId, purpose]);
1706
- };
1707
- const OpencodeWizardSkillsPlugin = async input => {
1708
- const {
1709
- tool
1710
- } = await importOpencodePluginModule('@opencode-ai/plugin');
1711
- const config = await resolveConfig(input.worktree);
1712
- const workspacePath = normalizeAbsolutePath(input.worktree);
1713
- const cache = new Map();
1714
- const catalogInflight = new Map();
1715
- const detailCache = new Map();
1716
- const detailInflight = new Map();
1717
- const initialAuthState = await resolveStoredAuthState(input.worktree, config);
1718
- const loginBootstrap = {
1719
- promise: null,
1720
- snapshot: createIdleLoginBootstrapSnapshot()
1721
- };
1722
- let lastAuthenticatedAuthState = initialAuthState;
1723
- let didEmitStart = false;
1724
- let didScheduleStop = false;
1725
- let presenceStartPromise = null;
1726
- let presenceStopPromise = null;
1727
- let lastInteractiveDirectoryPath = null;
1728
- const resolveActionAuthState = async () => {
1729
- const storedAuthState = await resolveStoredAuthState(input.worktree, config);
1730
- if (storedAuthState) return storedAuthState;
1731
- return lastAuthenticatedAuthState;
1732
- };
1733
- const emitActionEventForCurrentSession = async ({
1734
- event,
1735
- authState,
1736
- directoryPath
1737
- }) => {
1738
- await emitPluginActionEvent({
1739
- config,
1740
- authState: authState ?? (await resolveActionAuthState()),
1741
- event,
1742
- workspacePath,
1743
- directoryPath
1744
- });
1745
- };
1746
- const schedulePresenceStart = authState => {
1747
- lastAuthenticatedAuthState = authState;
1748
- if (didEmitStart) {
1749
- return presenceStartPromise ?? Promise.resolve();
1750
- }
1751
- didEmitStart = true;
1752
- presenceStartPromise = Promise.all([emitPresenceEvent({
1753
- config,
1754
- authState,
1755
- event: 'START',
1756
- workspacePath
1757
- }), emitActionEventForCurrentSession({
1758
- event: 'START',
1759
- authState,
1760
- directoryPath: lastInteractiveDirectoryPath ?? undefined
1761
- })]).then(() => undefined);
1762
- return presenceStartPromise;
1763
- };
1764
- const schedulePresenceStop = () => {
1765
- if (didScheduleStop) {
1766
- return presenceStopPromise ?? Promise.resolve();
1767
- }
1768
- didScheduleStop = true;
1769
- if (!didEmitStart || !lastAuthenticatedAuthState) {
1770
- presenceStopPromise = Promise.resolve();
1771
- return presenceStopPromise;
1772
- }
1773
- presenceStopPromise = (async () => {
1774
- await presenceStartPromise?.catch(() => undefined);
1775
- await Promise.all([emitPresenceEvent({
1776
- config,
1777
- authState: lastAuthenticatedAuthState,
1778
- event: 'STOP',
1779
- workspacePath
1780
- }), emitActionEventForCurrentSession({
1781
- event: 'STOP',
1782
- authState: lastAuthenticatedAuthState,
1783
- directoryPath: lastInteractiveDirectoryPath ?? undefined
1784
- })]);
1785
- })();
1786
- return presenceStopPromise;
1787
- };
1788
- const scheduleInteractivePresenceStart = async () => {
1789
- const authState = await resolveStoredAuthState(input.worktree, config);
1790
- if (!authState) return;
1791
- await schedulePresenceStart(authState);
1792
- };
1793
- process.once('beforeExit', () => {
1794
- void schedulePresenceStop();
1795
- });
1796
- for (const shutdownSignal of PRESENCE_SHUTDOWN_SIGNALS) {
1797
- try {
1798
- process.once(shutdownSignal, () => {
1799
- void schedulePresenceStop().finally(() => {
1800
- process.exit(PRESENCE_SIGNAL_EXIT_CODES[shutdownSignal]);
1801
- });
1802
- });
1803
- } catch {
1804
- continue;
1805
- }
1806
- }
1807
- const clearPublishedSkillState = () => {
1808
- cache.clear();
1809
- catalogInflight.clear();
1810
- detailCache.clear();
1811
- detailInflight.clear();
1812
- };
1813
- const persistAuthState = async session => {
1814
- const authState = toAuthState(session);
1815
- await writeAuthState(config.authStatePath, authState);
1816
- clearPublishedSkillState();
1817
- return authState;
1818
- };
1819
- const startLoginCompletion = trigger => {
1820
- if (loginBootstrap.promise) {
1821
- return loginBootstrap.promise;
1822
- }
1823
- const startedAt = new Date().toISOString();
1824
- loginBootstrap.snapshot = {
1825
- status: 'starting',
1826
- trigger,
1827
- startedAt,
1828
- expiresAt: null,
1829
- browserUrl: null,
1830
- browserOpenError: null,
1831
- email: null,
1832
- message: null
1833
- };
1834
- const loginPromise = (async () => {
1835
- const loginSignal = AbortSignal.timeout(LOGIN_TIMEOUT_MS);
1836
- let loginStart = null;
1837
- try {
1838
- loginStart = await startLoginFlow(loginSignal);
1839
- const browserOpenError = await openBrowser(loginStart.browserUrl);
1840
- loginBootstrap.snapshot = {
1841
- status: 'pending',
1842
- trigger,
1843
- startedAt,
1844
- expiresAt: loginStart.expiresAt,
1845
- browserUrl: loginStart.browserUrl,
1846
- browserOpenError,
1847
- email: null,
1848
- message: browserOpenError ? `Automatic browser open failed. Open ${loginStart.browserUrl} manually.` : `Browser login started for published skill ${trigger}.`
1849
- };
1850
- const callbackPayload = await loginStart.callbackPromise;
1851
- if (callbackPayload.status === 'error') {
1852
- throw new Error(callbackPayload.message);
1853
- }
1854
- if (callbackPayload.state !== loginStart.expectedState) {
1855
- throw new Error('OAuth callback state did not match the original login request.');
1856
- }
1857
- loginBootstrap.snapshot = {
1858
- status: 'pending',
1859
- trigger,
1860
- startedAt,
1861
- expiresAt: loginStart.expiresAt,
1862
- browserUrl: loginStart.browserUrl,
1863
- browserOpenError,
1864
- email: null,
1865
- message: 'OAuth callback received. Finalizing backend session exchange.'
1866
- };
1867
- const pluginSession = await createPluginSession({
1868
- code: callbackPayload.code,
1869
- codeVerifier: loginStart.codeVerifier,
1870
- redirectUri: OIDC_CALLBACK_URL,
1871
- config,
1872
- signal: loginSignal
1873
- });
1874
- const authState = await persistAuthState(pluginSession);
1875
- await emitActionEventForCurrentSession({
1876
- event: 'LOGIN_SUCCESS',
1877
- authState,
1878
- directoryPath: lastInteractiveDirectoryPath ?? undefined
1879
- });
1880
- loginBootstrap.snapshot = {
1881
- status: 'authenticated',
1882
- trigger,
1883
- startedAt,
1884
- expiresAt: authState.expiresAt,
1885
- browserUrl: loginStart.browserUrl,
1886
- browserOpenError,
1887
- email: authState.email,
1888
- message: `Browser login completed successfully for published skill ${trigger}.`
1889
- };
1890
- return authState;
1891
- } catch (error) {
1892
- await emitActionEventForCurrentSession({
1893
- event: 'LOGIN_FAILED',
1894
- directoryPath: lastInteractiveDirectoryPath ?? undefined
1895
- });
1896
- loginBootstrap.snapshot = {
1897
- status: 'failed',
1898
- trigger,
1899
- startedAt,
1900
- expiresAt: loginBootstrap.snapshot.expiresAt,
1901
- browserUrl: loginBootstrap.snapshot.browserUrl,
1902
- browserOpenError: loginBootstrap.snapshot.browserOpenError,
1903
- email: null,
1904
- message: error instanceof Error ? error.message : 'Browser login failed.'
1905
- };
1906
- throw error;
1907
- } finally {
1908
- await loginStart?.closeCallbackServer().catch(() => undefined);
1909
- loginBootstrap.promise = null;
1910
- }
1911
- })();
1912
- loginBootstrap.promise = loginPromise;
1913
- return loginPromise;
1914
- };
1915
- const loadPublishedSkillCatalog = async ({
1916
- directory,
1917
- useCache,
1918
- signal
1919
- }) => {
1920
- const workspaceResolution = await resolveWorkspace({
1921
- config,
1922
- directory
1923
- });
1924
- const directoryPath = workspaceResolution.directoryPath;
1925
- const preferenceContext = await resolvePublishedSkillPreferenceCacheContext(config);
1926
- const cacheKey = getCatalogCacheKey(workspaceResolution, preferenceContext);
1927
- const cached = cache.get(cacheKey);
1928
- if (useCache && cached && cached.expiresAt > Date.now()) {
1929
- return {
1930
- directoryPath,
1931
- workspaceResolution,
1932
- fetchResult: {
1933
- ...cached.result,
1934
- source: 'cache'
1935
- }
1936
- };
1937
- }
1938
- const inflight = catalogInflight.get(cacheKey);
1939
- if (inflight) {
1940
- return inflight;
1941
- }
1942
- const requestPromise = (async () => {
1943
- const fetchResult = await fetchPublishedSkillsCatalog(input.worktree, config, workspaceResolution, signal, clearPublishedSkillState);
1944
- cache.set(cacheKey, {
1945
- result: fetchResult,
1946
- expiresAt: Date.now() + CACHE_TTL_MS
1947
- });
1948
- return {
1949
- directoryPath,
1950
- workspaceResolution,
1951
- fetchResult
1952
- };
1953
- })();
1954
- catalogInflight.set(cacheKey, requestPromise);
1955
- try {
1956
- return await requestPromise;
1957
- } finally {
1958
- catalogInflight.delete(cacheKey);
1959
- }
1960
- };
1961
- const loadPublishedSkillDetail = async ({
1962
- workspaceResolution,
1963
- item,
1964
- signal,
1965
- useCache,
1966
- purpose
1967
- }) => {
1968
- const directoryPath = workspaceResolution.directoryPath;
1969
- const preferenceContext = await resolvePublishedSkillPreferenceCacheContext(config);
1970
- const catalogCacheKey = getCatalogCacheKey(workspaceResolution, preferenceContext);
1971
- const cacheKey = getDetailCacheKey(catalogCacheKey, item.skillVersion.id);
1972
- const inflightKey = getDetailInflightKey(catalogCacheKey, item.skillVersion.id, purpose);
1973
- const cached = detailCache.get(cacheKey);
1974
- if (purpose === 'SYSTEM_CONTEXT' && useCache && cached && cached.expiresAt > Date.now()) {
1975
- return {
1976
- ok: true,
1977
- detail: toPublishedSkillDetail({
1978
- ...item,
1979
- publishedArtifact: cached.artifact
1980
- })
1981
- };
1982
- }
1983
- const inflight = detailInflight.get(inflightKey);
1984
- if (inflight) {
1985
- return inflight;
1986
- }
1987
- const requestPromise = (async () => {
1988
- const detailResult = await fetchPublishedSkillDetail({
1989
- worktree: input.worktree,
1990
- config,
1991
- resolution: workspaceResolution,
1992
- skillVersionId: item.skillVersion.id,
1993
- signal,
1994
- onAuthStateChanged: clearPublishedSkillState,
1995
- purpose
1996
- });
1997
- if (!detailResult.ok) {
1998
- return {
1999
- ok: false,
2000
- status: detailResult.result.status,
2001
- output: JSON.stringify({
2002
- pluginId: PLUGIN_ID,
2003
- runtimeMode: 'tool_fetch_only',
2004
- status: detailResult.result.status,
2005
- requestedDirectoryPath: directoryPath,
2006
- workspaceResolution: toWorkspaceResolutionOutput(workspaceResolution),
2007
- requestedSkillVersionId: item.skillVersion.id,
2008
- message: detailResult.result.message,
2009
- fetchedAt: detailResult.result.fetchedAt,
2010
- source: detailResult.result.source
2011
- }, null, 2),
2012
- metadata: {
2013
- status: detailResult.result.status,
2014
- ...toWorkspaceResolutionMetadata(workspaceResolution),
2015
- source: detailResult.result.source
2016
- }
2017
- };
2018
- }
2019
- detailCache.set(cacheKey, {
2020
- artifact: detailResult.artifact,
2021
- expiresAt: Date.now() + CACHE_TTL_MS
2022
- });
2023
- return {
2024
- ok: true,
2025
- detail: toPublishedSkillDetail({
2026
- ...item,
2027
- publishedArtifact: detailResult.artifact
2028
- })
2029
- };
2030
- })();
2031
- detailInflight.set(inflightKey, requestPromise);
2032
- try {
2033
- return await requestPromise;
2034
- } finally {
2035
- detailInflight.delete(inflightKey);
2036
- }
2037
- };
2038
- const loadSystemNoteDetails = async ({
2039
- publishedSkillsResult,
2040
- signal
2041
- }) => {
2042
- if (!publishedSkillsResult.fetchResult.ok) return [];
2043
- const prioritizedItems = [...publishedSkillsResult.fetchResult.payload.skills].sort((left, right) => {
2044
- const leftSummary = toPublishedSkillSummary(left);
2045
- const rightSummary = toPublishedSkillSummary(right);
2046
- if (leftSummary.contextKind === rightSummary.contextKind) return formatSkillLabel(left).localeCompare(formatSkillLabel(right));
2047
- if (leftSummary.contextKind === 'global') return -1;
2048
- if (rightSummary.contextKind === 'global') return 1;
2049
- return 0;
2050
- });
2051
- const detailResults = await Promise.all(prioritizedItems.slice(0, SYSTEM_NOTE_DETAIL_LIMIT).map(item => loadPublishedSkillDetail({
2052
- workspaceResolution: publishedSkillsResult.workspaceResolution,
2053
- item,
2054
- signal,
2055
- useCache: true,
2056
- purpose: 'SYSTEM_CONTEXT'
2057
- })));
2058
- return detailResults.reduce((details, result) => {
2059
- if (!result.ok) return details;
2060
- details.push(result.detail);
2061
- return details;
2062
- }, []);
2063
- };
2064
- const executePublishedSkillsFetchTool = async ({
2065
- args,
2066
- context
2067
- }) => {
2068
- const requestedDirectory = normalizeDirectoryArg(context.directory, args.directory);
2069
- const requestedSkills = parseRequestedSkillArgs(args);
2070
- const fetchActionDirectoryPath = normalizeRepositoryPath(workspacePath, requestedDirectory);
2071
- lastInteractiveDirectoryPath = fetchActionDirectoryPath;
2072
- const emitFetchOutcome = async event => {
2073
- await emitActionEventForCurrentSession({
2074
- event,
2075
- directoryPath: fetchActionDirectoryPath
2076
- });
2077
- };
2078
- let publishedSkillsResult = await loadPublishedSkillCatalog({
2079
- directory: requestedDirectory,
2080
- useCache: !args.refresh,
2081
- signal: context.abort
2082
- });
2083
- if (publishedSkillsResult.fetchResult.ok) {
2084
- await scheduleInteractivePresenceStart();
2085
- }
2086
- if (!publishedSkillsResult.fetchResult.ok && publishedSkillsResult.fetchResult.status === 'missing_auth') {
2087
- try {
2088
- await startLoginCompletion('fetch').then(async authState => {
2089
- await schedulePresenceStart(authState);
2090
- });
2091
- publishedSkillsResult = await loadPublishedSkillCatalog({
2092
- directory: requestedDirectory,
2093
- useCache: false,
2094
- signal: context.abort
2095
- });
2096
- if (publishedSkillsResult.fetchResult.ok) {
2097
- await scheduleInteractivePresenceStart();
2098
- }
2099
- } catch {
2100
- // Return the original fetch failure with the latest login bootstrap snapshot attached.
2101
- }
2102
- }
2103
- if (!publishedSkillsResult.fetchResult.ok) {
2104
- await emitFetchOutcome('FETCH_FAILED');
2105
- return toFetchFailureOutput({
2106
- worktree: input.worktree,
2107
- config,
2108
- publishedSkillsResult,
2109
- loginBootstrapSnapshot: loginBootstrap.snapshot
2110
- });
2111
- }
2112
- const filteredPublishedSkillsResult = await filterIgnoredPublishedSkills(config, publishedSkillsResult);
2113
- if (!filteredPublishedSkillsResult.fetchResult.ok) {
2114
- await emitFetchOutcome('FETCH_FAILED');
2115
- return toFetchFailureOutput({
2116
- worktree: input.worktree,
2117
- config,
2118
- publishedSkillsResult: filteredPublishedSkillsResult,
2119
- loginBootstrapSnapshot: loginBootstrap.snapshot
2120
- });
2121
- }
2122
- const selection = selectPublishedSkills(filteredPublishedSkillsResult.fetchResult.payload, requestedSkills);
2123
- const isSingleRequest = requestedSkills.length === 1;
2124
- if (requestedSkills.length === 0) {
2125
- const catalog = toPublishedSkillCatalog(filteredPublishedSkillsResult.fetchResult.payload);
2126
- context.metadata({
2127
- title: `opencode-wizard published skills catalog: ${catalog.publishedSkillCount} active`,
2128
- metadata: {
2129
- ...toWorkspaceResolutionMetadata(filteredPublishedSkillsResult.workspaceResolution),
2130
- status: 'ready',
2131
- publishedSkillCount: catalog.publishedSkillCount.toString(),
2132
- globalAssignmentCount: catalog.assignmentCounts.global.toString(),
2133
- projectAssignmentCount: catalog.assignmentCounts.project.toString(),
2134
- userAssignmentCount: catalog.assignmentCounts.user.toString(),
2135
- ignoredSkillCount: filteredPublishedSkillsResult.ignoreState.ignoredSkillSlugs.length.toString()
2136
- }
2137
- });
2138
- await emitFetchOutcome('FETCH_SUCCESS');
2139
- return {
2140
- output: JSON.stringify({
2141
- ...catalog,
2142
- status: 'ready',
2143
- requestedDirectoryPath: filteredPublishedSkillsResult.directoryPath,
2144
- workspaceResolution: toWorkspaceResolutionOutput(filteredPublishedSkillsResult.workspaceResolution),
2145
- ignoredPublishedSkills: {
2146
- scopeKey: filteredPublishedSkillsResult.ignoreState.scopeKey,
2147
- count: filteredPublishedSkillsResult.ignoreState.ignoredSkillSlugs.length
2148
- },
2149
- fetchedAt: filteredPublishedSkillsResult.fetchResult.fetchedAt,
2150
- source: filteredPublishedSkillsResult.fetchResult.source,
2151
- message: 'Catalog discovery only. Provide `skill` for one identifier or prefer `skills` for comma/newline-separated multiple identifiers to fetch markdown bodies/details.'
2152
- }, null, 2),
2153
- metadata: {
2154
- status: 'ready',
2155
- ...toWorkspaceResolutionMetadata(filteredPublishedSkillsResult.workspaceResolution),
2156
- publishedSkillCount: catalog.publishedSkillCount.toString(),
2157
- globalAssignmentCount: catalog.assignmentCounts.global.toString(),
2158
- projectAssignmentCount: catalog.assignmentCounts.project.toString(),
2159
- userAssignmentCount: catalog.assignmentCounts.user.toString(),
2160
- ignoredSkillCount: filteredPublishedSkillsResult.ignoreState.ignoredSkillSlugs.length.toString()
2161
- }
2162
- };
2163
- }
2164
- if (selection.selectedItems.length === 0 && isSingleRequest) {
2165
- await emitFetchOutcome('FETCH_FAILED');
2166
- return {
2167
- output: JSON.stringify({
2168
- pluginId: PLUGIN_ID,
2169
- runtimeMode: 'tool_fetch_only',
2170
- status: 'not_found',
2171
- requestedDirectoryPath: filteredPublishedSkillsResult.directoryPath,
2172
- workspaceResolution: toWorkspaceResolutionOutput(filteredPublishedSkillsResult.workspaceResolution),
2173
- requestedSkill: requestedSkills[0],
2174
- availableSkills: filteredPublishedSkillsResult.fetchResult.payload.skills.map(toPublishedSkillSummary),
2175
- ignoredPublishedSkills: {
2176
- scopeKey: filteredPublishedSkillsResult.ignoreState.scopeKey,
2177
- count: filteredPublishedSkillsResult.ignoreState.ignoredSkillSlugs.length
2178
- }
2179
- }, null, 2),
2180
- metadata: {
2181
- status: 'not_found',
2182
- ...toWorkspaceResolutionMetadata(filteredPublishedSkillsResult.workspaceResolution)
2183
- }
2184
- };
2185
- }
2186
- let skillDetailResults = await Promise.all(selection.selectedItems.map(item => loadPublishedSkillDetail({
2187
- workspaceResolution: filteredPublishedSkillsResult.workspaceResolution,
2188
- item,
2189
- signal: context.abort,
2190
- useCache: !args.refresh,
2191
- purpose: 'TOOL_FETCH'
2192
- })));
2193
- if (skillDetailResults.some(result => !result.ok && result.status === 'missing_auth')) {
2194
- try {
2195
- await startLoginCompletion('fetch').then(async authState => {
2196
- await schedulePresenceStart(authState);
2197
- });
2198
- skillDetailResults = await Promise.all(selection.selectedItems.map(item => loadPublishedSkillDetail({
2199
- workspaceResolution: filteredPublishedSkillsResult.workspaceResolution,
2200
- item,
2201
- signal: context.abort,
2202
- useCache: false,
2203
- purpose: 'TOOL_FETCH'
2204
- })));
2205
- } catch {
2206
- // Return the original detail failure after the login bootstrap attempt updates snapshot state.
2207
- }
2208
- }
2209
- const failedSkillDetail = skillDetailResults.find(result => !result.ok);
2210
- if (failedSkillDetail && !failedSkillDetail.ok) {
2211
- await emitFetchOutcome('FETCH_FAILED');
2212
- return failedSkillDetail;
2213
- }
2214
- const skillDetails = skillDetailResults.map(result => {
2215
- if (!result.ok) {
2216
- throw new Error('Published skill detail result unexpectedly missing after success guard.');
2217
- }
2218
- return result.detail;
2219
- });
2220
- if (isSingleRequest && skillDetails[0]) {
2221
- const detail = skillDetails[0];
2222
- context.metadata({
2223
- title: `opencode-wizard published skill: ${detail.artifactName || detail.skillName}`,
2224
- metadata: {
2225
- ...toWorkspaceResolutionMetadata(filteredPublishedSkillsResult.workspaceResolution),
2226
- skillSlug: detail.skillSlug,
2227
- version: detail.version
2228
- }
2229
- });
2230
- await emitFetchOutcome('FETCH_SUCCESS');
2231
- return {
2232
- output: JSON.stringify({
2233
- pluginId: PLUGIN_ID,
2234
- runtimeMode: 'tool_fetch_only',
2235
- requestedDirectoryPath: filteredPublishedSkillsResult.directoryPath,
2236
- workspaceResolution: toWorkspaceResolutionOutput(filteredPublishedSkillsResult.workspaceResolution),
2237
- workspace: filteredPublishedSkillsResult.fetchResult.payload.workspace,
2238
- fetchedAt: filteredPublishedSkillsResult.fetchResult.fetchedAt,
2239
- source: filteredPublishedSkillsResult.fetchResult.source,
2240
- skill: detail
2241
- }, null, 2),
2242
- metadata: {
2243
- status: 'ready',
2244
- ...toWorkspaceResolutionMetadata(filteredPublishedSkillsResult.workspaceResolution),
2245
- skillSlug: detail.skillSlug
2246
- }
2247
- };
2248
- }
2249
- context.metadata({
2250
- title: `opencode-wizard published skills fetch: ${skillDetails.length}`,
2251
- metadata: {
2252
- ...toWorkspaceResolutionMetadata(filteredPublishedSkillsResult.workspaceResolution),
2253
- requestedCount: requestedSkills.length.toString(),
2254
- matchedCount: skillDetails.length.toString()
2255
- }
2256
- });
2257
- await emitFetchOutcome('FETCH_SUCCESS');
2258
- return {
2259
- output: JSON.stringify({
2260
- pluginId: PLUGIN_ID,
2261
- runtimeMode: 'tool_fetch_only',
2262
- requestedDirectoryPath: filteredPublishedSkillsResult.directoryPath,
2263
- workspaceResolution: toWorkspaceResolutionOutput(filteredPublishedSkillsResult.workspaceResolution),
2264
- workspace: filteredPublishedSkillsResult.fetchResult.payload.workspace,
2265
- fetchedAt: filteredPublishedSkillsResult.fetchResult.fetchedAt,
2266
- source: filteredPublishedSkillsResult.fetchResult.source,
2267
- requestedSkills,
2268
- missingSkills: selection.missingIdentifiers,
2269
- skills: skillDetails
2270
- }, null, 2),
2271
- metadata: {
2272
- status: selection.missingIdentifiers.length > 0 ? 'partial' : 'ready',
2273
- ...toWorkspaceResolutionMetadata(filteredPublishedSkillsResult.workspaceResolution),
2274
- matchedCount: skillDetails.length.toString()
2275
- }
2276
- };
2277
- };
2278
- const executeStatusTool = async ({
2279
- args,
2280
- context
2281
- }) => {
2282
- const requestedDirectory = normalizeDirectoryArg(context.directory, args.directory);
2283
- let snapshot = await resolvePluginStatusSnapshot({
2284
- worktree: input.worktree,
2285
- directory: requestedDirectory,
2286
- signal: context.abort
2287
- });
2288
- if (snapshot.status === 'missing_auth') {
2289
- try {
2290
- await startLoginCompletion('status').then(async authState => {
2291
- await schedulePresenceStart(authState);
2292
- });
2293
- snapshot = await resolvePluginStatusSnapshot({
2294
- worktree: input.worktree,
2295
- directory: requestedDirectory,
2296
- signal: context.abort
2297
- });
2298
- } catch {
2299
- // Keep returning the safe missing-auth snapshot when interactive login is cancelled or fails.
2300
- }
2301
- }
2302
- if (snapshot.status === 'ready') {
2303
- await scheduleInteractivePresenceStart();
2304
- }
2305
- const metadata = toPluginStatusMetadata(snapshot);
2306
- context.metadata({
2307
- title: `opencode-wizard status: ${snapshot.status} / auth ${snapshot.authState.status}`,
2308
- metadata
2309
- });
2310
- return {
2311
- output: JSON.stringify(toAiFacingPluginStatusSnapshot(snapshot), null, 2),
2312
- metadata
2313
- };
2314
- };
2315
- const executePublishedSkillPreferenceTool = async ({
2316
- args,
2317
- context
2318
- }) => {
2319
- const requestedDirectory = normalizeDirectoryArg(context.directory, args.directory);
2320
- const directoryPath = normalizeRepositoryPath(workspacePath, requestedDirectory);
2321
- lastInteractiveDirectoryPath = directoryPath;
2322
- const requestedSkill = typeof args.skill === 'string' ? args.skill.trim() : '';
2323
- const emitPreferenceOutcome = async event => {
2324
- await emitActionEventForCurrentSession({
2325
- event,
2326
- directoryPath
2327
- });
2328
- };
2329
- try {
2330
- if (!requestedSkill) {
2331
- throw new Error('Published skill preference tool requires a non-empty skill slug, artifact name, or skill name.');
2332
- }
2333
- if (typeof args.action !== 'string') {
2334
- throw new Error('Published skill preference tool requires an action: install, uninstall, ignore, or unignore.');
2335
- }
2336
- const action = toPublishedSkillPreferenceAction(args.action);
2337
- const catalogResult = await loadPublishedSkillCatalog({
2338
- directory: requestedDirectory,
2339
- useCache: true,
2340
- signal: context.abort
2341
- });
2342
- if (!catalogResult.fetchResult.ok) {
2343
- throw new Error(`Cannot resolve published skill preference target: ${catalogResult.fetchResult.message}`);
2344
- }
2345
- const selectableCatalogSkills = catalogResult.fetchResult.payload.catalogSkills.map(item => ({
2346
- ...item,
2347
- assignmentSource: 'CATALOG',
2348
- assignmentType: 'PATH',
2349
- scopePath: '',
2350
- includeChildren: true
2351
- }));
2352
- const preferenceSelection = selectPublishedSkills({
2353
- ...catalogResult.fetchResult.payload,
2354
- skills: [...catalogResult.fetchResult.payload.skills, ...selectableCatalogSkills, ...catalogResult.fetchResult.payload.userPreferences.ignoredSkills]
2355
- }, [requestedSkill]);
2356
- const matchedSkill = preferenceSelection.selectedItems[0];
2357
- if (!matchedSkill) {
2358
- throw new Error(`Published skill preference target was not found for identifier: ${requestedSkill}.`);
2359
- }
2360
- const skillSlug = matchedSkill.skill.slug;
2361
- const preferenceState = action === 'ignore' || action === 'unignore' ? await setPublishedSkillIgnored({
2362
- worktree: input.worktree,
2363
- directory: requestedDirectory,
2364
- skillSlug,
2365
- ignored: action === 'ignore',
2366
- preferenceScope: toPublishedSkillPreferenceScope(args.preferenceScope, 'project')
2367
- }) : await setPublishedSkillInstalled({
2368
- worktree: input.worktree,
2369
- directory: requestedDirectory,
2370
- skillSlug,
2371
- installed: action === 'install',
2372
- preferenceScope: toPublishedSkillPreferenceScope(args.preferenceScope, 'project')
2373
- });
2374
- await scheduleInteractivePresenceStart();
2375
- await emitPreferenceOutcome('PREFERENCE_SUCCESS');
2376
- const metadata = {
2377
- status: 'updated',
2378
- skillSlug,
2379
- action,
2380
- directoryPath,
2381
- ignoredSkillCount: preferenceState.ignoredSkillSlugs.length.toString()
2382
- };
2383
- context.metadata({
2384
- title: `opencode-wizard published skill preference: ${action} ${skillSlug}`,
2385
- metadata
2386
- });
2387
- return {
2388
- output: JSON.stringify({
2389
- pluginId: PLUGIN_ID,
2390
- status: 'updated',
2391
- requestedIdentifier: requestedSkill,
2392
- skillSlug,
2393
- action,
2394
- requestedDirectoryPath: directoryPath,
2395
- preferenceState,
2396
- message: 'Published skill preference updated through the shared server-backed API; TUI views will reflect this after refresh.'
2397
- }, null, 2),
2398
- metadata
2399
- };
2400
- } catch (error) {
2401
- await emitPreferenceOutcome('PREFERENCE_FAILED');
2402
- throw error;
2403
- }
2404
- };
2405
- return {
2406
- tool: {
2407
- opencode_wizard_published_skills_fetch: tool({
2408
- description: 'Fetch one or multiple wizard-published skill bodies/details for the current scope. Use this for wizard-listed/private/scoped/backend-published skill slugs instead of the native OpenCode skill tool, and after native errors like `Skill "..." not found`; prefer `skills` for multiple identifiers and call with no args to discover the catalog and bootstrap auth when needed',
2409
- args: {
2410
- skill: tool.schema.string().optional().describe('Single skill slug, artifact name, or skill name; backward-compatible with comma/newline-delimited lists'),
2411
- skills: tool.schema.string().optional().describe('One or more comma-separated or newline-separated skill slugs, artifact names, or skill names'),
2412
- directory: tool.schema.string().optional().describe('Optional absolute or relative directory override'),
2413
- refresh: tool.schema.boolean().optional().describe('Bypass the local plugin cache for this request')
2414
- },
2415
- async execute(args, context) {
2416
- return executePublishedSkillsFetchTool({
2417
- args,
2418
- context
2419
- });
2420
- }
2421
- }),
2422
- opencode_wizard_published_skill_preference_set: tool({
2423
- description: 'Install, uninstall, ignore, or unignore a backend-published wizard skill for non-TUI workflows using the same shared server-backed preference API as the TUI overlay',
2424
- args: {
2425
- skill: tool.schema.string().describe('Published skill slug, artifact name, or skill name to update'),
2426
- action: tool.schema.string().describe('Preference action: install, uninstall, ignore, or unignore'),
2427
- preferenceScope: tool.schema.string().optional().describe('Preference scope for the action: project or global; defaults to project'),
2428
- directory: tool.schema.string().optional().describe('Optional absolute or relative directory override')
2429
- },
2430
- async execute(args, context) {
2431
- return executePublishedSkillPreferenceTool({
2432
- args,
2433
- context
2434
- });
2435
- }
2436
- }),
2437
- opencode_wizard_status: tool({
2438
- description: 'Report opencode-wizard plugin status, bootstrap auth when missing, and return a safe auth summary without exposing tokens',
2439
- args: {
2440
- directory: tool.schema.string().optional().describe('Optional absolute or relative directory override')
2441
- },
2442
- async execute(args, context) {
2443
- return executeStatusTool({
2444
- args,
2445
- context
2446
- });
2447
- }
2448
- })
2449
- },
2450
- 'experimental.chat.system.transform': async (_hookInput, output) => {
2451
- let publishedSkillsResult = await loadPublishedSkillCatalog({
2452
- directory: input.directory,
2453
- useCache: true,
2454
- signal: AbortSignal.timeout(5_000)
2455
- });
2456
- if (!publishedSkillsResult.fetchResult.ok && publishedSkillsResult.fetchResult.status === 'missing_auth') {
2457
- try {
2458
- await startLoginCompletion('status').then(async authState => {
2459
- await schedulePresenceStart(authState);
2460
- });
2461
- publishedSkillsResult = await loadPublishedSkillCatalog({
2462
- directory: input.directory,
2463
- useCache: false,
2464
- signal: AbortSignal.timeout(5_000)
2465
- });
2466
- } catch {
2467
- const loginMessage = loginBootstrap.snapshot.message ? ` Last login status: ${loginBootstrap.snapshot.message}` : '';
2468
- output.system.push(`opencode-wizard plugin stored auth is missing, expired, or rejected. Startup browser login was started but did not complete successfully.${loginMessage} Use opencode_wizard_status or opencode_wizard_published_skills_fetch to retry authentication when published skills are needed. No tokens are exposed.`);
2469
- return;
2470
- }
2471
- if (!publishedSkillsResult.fetchResult.ok) {
2472
- output.system.push(`opencode-wizard plugin startup login completed, but published skills are still unavailable: ${publishedSkillsResult.fetchResult.message} No tokens are exposed.`);
2473
- return;
2474
- }
2475
- }
2476
- if (publishedSkillsResult.fetchResult.ok) {
2477
- await scheduleInteractivePresenceStart();
2478
- }
2479
- const filteredPublishedSkillsResult = await filterIgnoredPublishedSkills(config, publishedSkillsResult);
2480
- const details = await loadSystemNoteDetails({
2481
- publishedSkillsResult: filteredPublishedSkillsResult,
2482
- signal: AbortSignal.timeout(5_000)
2483
- });
2484
- const systemNote = buildSystemNote(filteredPublishedSkillsResult, config, details);
2485
- if (!systemNote) return;
2486
- output.system.push(systemNote);
2487
- }
2488
- };
2489
- };
1
+ export { AVAILABLE_PUBLISHED_SKILL_TOOLS, resolveAvailableTools } from './plugin-tools.js';
2
+ export { buildSkillMarkdown, parseRequestedSkillArgs, selectPublishedSkills, toPublishedSkillDetail } from './published-skills-transform.js';
3
+ export { PLUGIN_ID, NATIVE_SKILLS_URL_COMPATIBILITY, buildSystemNote, resolveConfig, resolvePluginStatusSnapshot, resolvePluginStatusSnapshotWithAuthBootstrap, setPublishedSkillIgnored, setPublishedSkillInstalled, toPluginAuthStateSummary, toPublishedSkillCatalog } from './server/runtime.js';
4
+ import { PLUGIN_ID, OpencodeWizardSkillsPlugin } from './server/runtime.js';
2490
5
  export default {
2491
6
  id: PLUGIN_ID,
2492
7
  server: OpencodeWizardSkillsPlugin