pantheon-opencode 2.1.5 → 2.1.6

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.
@@ -20,6 +20,7 @@ import { join } from 'node:path'
20
20
  // @ts-expect-error scripts/skill-search.mjs is a plain Node ESM script without bundled .d.ts
21
21
  import { searchSkillSources } from '../../scripts/skill-search.mjs'
22
22
  import { PANTHEON_SKILL_CATALOG } from './pantheon-decision-catalog.ts'
23
+ import { resolveToolCwd } from './tool-context.ts'
23
24
  import type { V2ToolDef } from './tools.ts'
24
25
 
25
26
  export interface SkillSearchResult {
@@ -172,6 +173,72 @@ const SKILL_SEARCH_INPUT_SCHEMA: Record<string, unknown> = {
172
173
  },
173
174
  }
174
175
 
176
+ export interface SkillScore {
177
+ readonly score: number
178
+ readonly matchedTokens: number
179
+ }
180
+
181
+ /**
182
+ * Score relevance of a skill against query tokens.
183
+ *
184
+ * Uses word-boundary and segment matching with tiered weighting:
185
+ * - Exact ID match: 20 pts
186
+ * - Exact segment match in hyphenated/slashed ID: 12 pts
187
+ * - Prefix match on ID segment (>=4 chars): 6 pts
188
+ * - Exact word match in description: 5 pts
189
+ * - Prefix match on description word (>=4 chars): 2 pts
190
+ * - Multi-token synergy bonus: + (matchedTokens * 5) pts
191
+ *
192
+ * Substrings inside words (e.g. "rate" inside "generates" or "migrate")
193
+ * receive ZERO points, completely eliminating false-positive lexical bleed.
194
+ */
195
+ export function scoreSkillMatch(
196
+ id: string,
197
+ description: string,
198
+ queryTokens: readonly string[],
199
+ ): SkillScore {
200
+ const idLower = id.toLowerCase()
201
+ const descLower = description.toLowerCase()
202
+ const idTokens = idLower.split(/[^a-z0-9]+/).filter(Boolean)
203
+ const descWords = descLower.split(/[^a-z0-9]+/).filter(Boolean)
204
+
205
+ let score = 0
206
+ let matchedTokens = 0
207
+
208
+ for (const t of queryTokens) {
209
+ let tokenScore = 0
210
+
211
+ if (idLower === t) {
212
+ tokenScore += 20
213
+ } else if (idTokens.includes(t)) {
214
+ tokenScore += 12
215
+ } else if (
216
+ idTokens.some((w) => w.length >= 4 && t.length >= 4 && (w.startsWith(t) || t.startsWith(w)))
217
+ ) {
218
+ tokenScore += 6
219
+ }
220
+
221
+ if (descWords.includes(t)) {
222
+ tokenScore += 5
223
+ } else if (
224
+ descWords.some((w) => w.length >= 4 && t.length >= 4 && (w.startsWith(t) || t.startsWith(w)))
225
+ ) {
226
+ tokenScore += 2
227
+ }
228
+
229
+ if (tokenScore > 0) {
230
+ score += tokenScore
231
+ matchedTokens += 1
232
+ }
233
+ }
234
+
235
+ if (matchedTokens > 1) {
236
+ score += matchedTokens * 5
237
+ }
238
+
239
+ return { score, matchedTokens }
240
+ }
241
+
175
242
  export function executeSkillSearch(
176
243
  input: Record<string, unknown>,
177
244
  options: { cwd?: string } = {},
@@ -195,48 +262,35 @@ export function executeSkillSearch(
195
262
  ],
196
263
  )
197
264
 
198
- const results: SkillSearchResult[] = []
199
265
  const failures: string[] = []
200
266
 
201
267
  const cwd = options.cwd ?? process.cwd()
202
268
  const installedMap = scanInstalledSkills(cwd)
203
269
 
270
+ const tokens = query
271
+ .toLowerCase()
272
+ .split(/[^a-z0-9]+/)
273
+ .filter((t) => t.length > 1)
274
+
275
+ const scoredResults: Array<SkillSearchResult & { score: number }> = []
276
+
204
277
  // 1. Tier 1: Installed skills (Pantheon catalog + local filesystem .opencode/skills and .agents/skills)
205
- if (sources.has('installed')) {
206
- const tokens = query
207
- .toLowerCase()
208
- .split(/[^a-z0-9]+/)
209
- .filter((t) => t.length > 2)
210
-
211
- if (tokens.length > 0) {
212
- for (const entry of installedMap.values()) {
213
- const idLower = entry.id.toLowerCase()
214
- const descLower = entry.description.toLowerCase()
215
- const matchScore = tokens.reduce((score, t) => {
216
- const stem = t.length > 4 ? t.slice(0, 4) : t
217
- return (
218
- score +
219
- (idLower.includes(t) ||
220
- descLower.includes(t) ||
221
- idLower.includes(stem) ||
222
- descLower.includes(stem)
223
- ? 1
224
- : 0)
225
- )
226
- }, 0)
227
-
228
- if (matchScore > 0) {
229
- results.push({
230
- skill: entry.id,
231
- description: entry.description,
232
- source: 'installed',
233
- installed: true,
234
- installs: null,
235
- installCommand: null,
236
- path: entry.path,
237
- scope: entry.scope,
238
- })
239
- }
278
+ if (sources.has('installed') && tokens.length > 0) {
279
+ const minThreshold = tokens.length > 1 ? 5 : 2
280
+ for (const entry of installedMap.values()) {
281
+ const { score } = scoreSkillMatch(entry.id, entry.description, tokens)
282
+ if (score >= minThreshold) {
283
+ scoredResults.push({
284
+ skill: entry.id,
285
+ description: entry.description,
286
+ source: 'installed',
287
+ installed: true,
288
+ installs: null,
289
+ installCommand: null,
290
+ path: entry.path,
291
+ scope: entry.scope,
292
+ score,
293
+ })
240
294
  }
241
295
  }
242
296
  }
@@ -244,9 +298,9 @@ export function executeSkillSearch(
244
298
  // 2. External tiers (Anthropic, skills.sh, GitHub)
245
299
  const externalSources = ['anthropic', 'skills-sh', 'github'].filter((s) => sources.has(s))
246
300
 
247
- if (externalSources.length > 0 && results.length < limit) {
301
+ if (externalSources.length > 0 && scoredResults.length < limit) {
248
302
  try {
249
- const extLimit = limit - results.length
303
+ const extLimit = limit - scoredResults.length
250
304
  const extRes = searchSkillSources(query, {
251
305
  limit: extLimit,
252
306
  sources: externalSources,
@@ -257,6 +311,7 @@ export function executeSkillSearch(
257
311
  }
258
312
 
259
313
  if (Array.isArray(extRes.entries)) {
314
+ const minThreshold = tokens.length > 1 ? 5 : 2
260
315
  for (const entry of extRes.entries) {
261
316
  const bareName = (
262
317
  entry.skill.includes('@') ? entry.skill.split('@')[1] : entry.skill
@@ -266,7 +321,22 @@ export function executeSkillSearch(
266
321
  const installedRecord =
267
322
  installedMap.get(entry.skill.toLowerCase()) || installedMap.get(bareName)
268
323
 
269
- const pushItem: SkillSearchResult = {
324
+ const { score } = scoreSkillMatch(entry.skill, entry.skill, tokens)
325
+ if (score < minThreshold && !isInstalled) {
326
+ continue
327
+ }
328
+
329
+ if (
330
+ scoredResults.some(
331
+ (r) =>
332
+ r.skill.toLowerCase() === entry.skill.toLowerCase() ||
333
+ (bareName && r.skill.toLowerCase() === bareName),
334
+ )
335
+ ) {
336
+ continue
337
+ }
338
+
339
+ scoredResults.push({
270
340
  skill: entry.skill,
271
341
  description: entry.skill,
272
342
  source: entry.source as 'anthropic' | 'skills-sh' | 'github',
@@ -276,8 +346,8 @@ export function executeSkillSearch(
276
346
  installCommand: isInstalled ? null : `npx skills add ${entry.skill} -a opencode -y`,
277
347
  path: isInstalled && installedRecord ? installedRecord.path : null,
278
348
  ...(isInstalled && installedRecord ? { scope: installedRecord.scope } : {}),
279
- }
280
- results.push(pushItem)
349
+ score: score || 1,
350
+ })
281
351
  }
282
352
  }
283
353
  } catch (err) {
@@ -287,7 +357,11 @@ export function executeSkillSearch(
287
357
  }
288
358
  }
289
359
 
290
- const bounded = results.slice(0, limit)
360
+ scoredResults.sort((a, b) => b.score - a.score)
361
+ const bounded: SkillSearchResult[] = scoredResults
362
+ .slice(0, limit)
363
+ .map(({ score: _, ...item }) => item)
364
+
291
365
  return {
292
366
  ok: true,
293
367
  query,
@@ -297,14 +371,14 @@ export function executeSkillSearch(
297
371
  }
298
372
  }
299
373
 
300
- export function createV2SkillSearchDefinition(): V2ToolDef {
374
+ export function createV2SkillSearchDefinition(defaultDir?: string): V2ToolDef {
301
375
  return {
302
376
  name: 'pantheon_skill_search',
303
377
  description: TOOL_DESCRIPTION,
304
378
  input: SKILL_SEARCH_INPUT_SCHEMA,
305
379
  output: {},
306
380
  execute: async (input: Record<string, unknown>, context?: unknown) => {
307
- const cwd = (context as { directory?: string } | undefined)?.directory || process.cwd()
381
+ const cwd = resolveToolCwd(context, defaultDir)
308
382
  return {
309
383
  output: JSON.stringify(executeSkillSearch(input, { cwd }), null, 2),
310
384
  }
@@ -21,3 +21,26 @@ export interface ToolContextLike {
21
21
  */
22
22
  agent?: string
23
23
  }
24
+
25
+ /**
26
+ * Resolves the effective working directory for tool operations.
27
+ *
28
+ * Checks in order of precedence:
29
+ * 1. ctx.directory (explicit workspace directory on tool context)
30
+ * 2. ctx.worktree (worktree directory if isolated)
31
+ * 3. fallbackDir (injected location directory from host at plugin setup)
32
+ * 4. process.cwd() (fallback process directory)
33
+ */
34
+ export function resolveToolCwd(context: unknown, fallbackDir?: string): string {
35
+ const ctx = (context ?? {}) as Partial<ToolContextLike>
36
+ if (typeof ctx.directory === 'string' && ctx.directory.trim().length > 0) {
37
+ return ctx.directory
38
+ }
39
+ if (typeof ctx.worktree === 'string' && ctx.worktree.trim().length > 0) {
40
+ return ctx.worktree
41
+ }
42
+ if (typeof fallbackDir === 'string' && fallbackDir.trim().length > 0) {
43
+ return fallbackDir
44
+ }
45
+ return process.cwd()
46
+ }
@@ -57,7 +57,7 @@ import { createV2LocalDecisionDefinition } from './local-decision-tool.ts'
57
57
  import { createModelCommand } from './model-command.ts'
58
58
  import { createV2VisionTool, type V2VisionRuntime } from './native-vision.ts'
59
59
  import { createV2SkillSearchDefinition } from './skill-search-tool.ts'
60
- import type { ToolContextLike } from './tool-context.ts'
60
+ import { resolveToolCwd, type ToolContextLike } from './tool-context.ts'
61
61
 
62
62
  // ─── Contract types ─────────────────────────────────────────────────────
63
63
 
@@ -400,7 +400,7 @@ const MODEL_INPUT: Record<string, unknown> = {
400
400
  scope: {
401
401
  type: 'string',
402
402
  enum: ['project'],
403
- description: 'Project scope only; global overrides are not supported in V2.',
403
+ description: 'Project scope only; global overrides are not supported.',
404
404
  },
405
405
  },
406
406
  }
@@ -412,12 +412,12 @@ async function executeModel(
412
412
  context: unknown,
413
413
  ): Promise<V2ToolResult> {
414
414
  if (input.scope !== undefined && input.scope !== 'project') {
415
- return { output: 'Error: V2 pantheon_model is project-only; global scope is not supported.' }
415
+ return { output: 'Error: pantheon_model is project-only; global scope is not supported.' }
416
416
  }
417
417
  if (Object.hasOwn(input, 'confirm') || Object.hasOwn(input, 'authorize_global')) {
418
418
  return {
419
419
  output:
420
- 'Error: V2 pantheon_model does not accept authorization flags; global authorization is not supported by this tool.',
420
+ 'Error: pantheon_model does not accept authorization flags; global authorization is not supported by this tool.',
421
421
  }
422
422
  }
423
423
  // The V1 tool validates its own args (zod) and reports failures as text.
@@ -557,45 +557,49 @@ const SHELL_INPUT = {
557
557
  } as const
558
558
 
559
559
  /**
560
- * A V2 fallback shell tool alias. OpenCode registers `bash`, but models frequently
560
+ * Shell tool execution. OpenCode registers `bash`, but models frequently
561
561
  * attempt to invoke `shell` because of agent permission YAML conventions.
562
- * This alias ensures terminal commands execute seamlessly without tool-not-found errors.
562
+ * This tool ensures terminal commands execute seamlessly in the workspace directory.
563
563
  */
564
- const shellTool: V2ToolDef = {
565
- name: 'shell',
566
- description: 'Execute a shell command in the workspace directory. Alias for bash execution.',
567
- input: SHELL_INPUT,
568
- output: {},
569
- execute: async (input, context) => {
570
- const raw = (input as Record<string, unknown>) ?? {}
571
- const command = String(raw.command ?? raw.cmd ?? '')
572
- if (!command.trim()) {
573
- return { output: '', ok: false, error: 'Command cannot be empty' }
574
- }
575
- const toolCtx = toolContext(context)
576
- const cwd = toolCtx.directory || process.cwd()
577
- try {
578
- const { stdout, stderr } = await execAsync(command, {
579
- cwd,
580
- maxBuffer: 10 * 1024 * 1024,
581
- shell: '/bin/bash',
582
- })
583
- const output = [stdout, stderr].filter(Boolean).join('\n')
584
- return { output, ok: true }
585
- } catch (err: unknown) {
586
- const execError = err as { stdout?: string; stderr?: string; message?: string }
587
- const output = [execError.stdout, execError.stderr, execError.message]
588
- .filter(Boolean)
589
- .join('\n')
590
- return { output, ok: false, error: output }
591
- }
592
- },
564
+ export function createShellTool(fallbackDir?: string): V2ToolDef {
565
+ return {
566
+ name: 'shell',
567
+ description: 'Execute a shell command in the workspace directory. Alias for bash execution.',
568
+ input: SHELL_INPUT,
569
+ output: {},
570
+ execute: async (input, context) => {
571
+ const raw = (input as Record<string, unknown>) ?? {}
572
+ const command = String(raw.command ?? raw.cmd ?? '')
573
+ if (!command.trim()) {
574
+ return { output: '', ok: false, error: 'Command cannot be empty' }
575
+ }
576
+ const cwd = resolveToolCwd(context, fallbackDir)
577
+ try {
578
+ const { stdout, stderr } = await execAsync(command, {
579
+ cwd,
580
+ maxBuffer: 10 * 1024 * 1024,
581
+ shell: '/bin/bash',
582
+ })
583
+ const output = [stdout, stderr].filter(Boolean).join('\n')
584
+ return { output, ok: true }
585
+ } catch (err: unknown) {
586
+ const execError = err as { stdout?: string; stderr?: string; message?: string }
587
+ const output = [execError.stdout, execError.stderr, execError.message]
588
+ .filter(Boolean)
589
+ .join('\n')
590
+ return { output, ok: false, error: output }
591
+ }
592
+ },
593
+ }
593
594
  }
594
595
 
596
+ export const shellTool = createShellTool()
597
+
595
598
  export function createV2ToolDefinitions(
596
599
  visionRuntime?: V2VisionRuntime,
597
600
  shadow: V2ToolShadowOptions = {},
598
601
  jevRuntime?: V2JevDecisionRuntime,
602
+ hostLocationDirectory?: string,
599
603
  ): V2ToolDef[] {
600
604
  const definitions: V2ToolDef[] = [
601
605
  {
@@ -618,8 +622,8 @@ export function createV2ToolDefinitions(
618
622
  'on disk: a call reads that cache and never waits on the network unless refreshPricing is ' +
619
623
  'set, a stale cache is refreshed in the background and the report says so, and an unpriced ' +
620
624
  'model reads — and is excluded from the totals, which then say partial. Pass session=<root ' +
621
- 'session id> to aggregate that session plus its descendant sessions. Phase may be unknown ' +
622
- 'on V2; costs are catalog list prices, not an invoice.',
625
+ 'session id> to aggregate that session plus its descendant sessions. Phase may be unknown; ' +
626
+ 'costs are catalog list prices, not an invoice.',
623
627
  input: COST_INPUT,
624
628
  output: {},
625
629
  execute: executeCost,
@@ -628,8 +632,8 @@ export function createV2ToolDefinitions(
628
632
  name: 'pantheon_model',
629
633
  description:
630
634
  'Show, set, or reset explicit per-agent project-scoped model overrides in active-preset.json. ' +
631
- 'V2 ignores static preset names and PANTHEON_MODEL_PRESET; no wizard or implicit model ' +
632
- 'selection. Global overrides are not read or written in V2; future global support requires ' +
635
+ 'Ignores static preset names and PANTHEON_MODEL_PRESET; no wizard or implicit model ' +
636
+ 'selection. Global overrides are not read or written; future global support requires ' +
633
637
  'separate explicit authorization. Pass action="status" to read project-scoped overrides. ' +
634
638
  'Never writes .env or top-level model/small_model.',
635
639
  input: MODEL_INPUT,
@@ -644,9 +648,9 @@ export function createV2ToolDefinitions(
644
648
  )
645
649
  definitions.push(todowriteTool)
646
650
  definitions.push(todoreadTool)
647
- definitions.push(shellTool)
648
- definitions.push(createV2SkillSearchDefinition())
649
- definitions.push(createDeepworkTool())
651
+ definitions.push(createShellTool(hostLocationDirectory))
652
+ definitions.push(createV2SkillSearchDefinition(hostLocationDirectory))
653
+ definitions.push(createDeepworkTool(hostLocationDirectory))
650
654
  if (visionRuntime) definitions.push(createV2VisionTool(visionRuntime))
651
655
  if (jevRuntime) definitions.push(createV2JevDecisionDefinition(jevRuntime))
652
656
  return definitions