@xi4z/dsh-utils-utils-agents 0.0.0-stage → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/lib/git.d.ts +87 -0
  3. package/lib/git.js +403 -0
  4. package/lib/git.js.map +1 -0
  5. package/lib/global-repo.d.ts +57 -0
  6. package/lib/global-repo.js +301 -0
  7. package/lib/global-repo.js.map +1 -0
  8. package/lib/index.d.ts +111 -0
  9. package/lib/index.js +470 -0
  10. package/lib/index.js.map +1 -0
  11. package/lib/legacy.d.ts +30 -0
  12. package/lib/legacy.js +141 -0
  13. package/lib/legacy.js.map +1 -0
  14. package/lib/native.d.ts +74 -0
  15. package/lib/native.js +232 -0
  16. package/lib/native.js.map +1 -0
  17. package/lib/presets.d.ts +34 -0
  18. package/lib/presets.js +312 -0
  19. package/lib/presets.js.map +1 -0
  20. package/lib/shared.d.ts +105 -0
  21. package/lib/shared.js +507 -0
  22. package/lib/shared.js.map +1 -0
  23. package/lib/skill-discovery.d.ts +52 -0
  24. package/lib/skill-discovery.js +850 -0
  25. package/lib/skill-discovery.js.map +1 -0
  26. package/lib/skill-panel.d.ts +36 -0
  27. package/lib/skill-panel.js +409 -0
  28. package/lib/skill-panel.js.map +1 -0
  29. package/lib/update.d.ts +129 -0
  30. package/lib/update.js +507 -0
  31. package/lib/update.js.map +1 -0
  32. package/lib/util.d.ts +215 -0
  33. package/lib/util.js +475 -0
  34. package/lib/util.js.map +1 -0
  35. package/locale/en.json +6 -0
  36. package/locale/zh.json +6 -0
  37. package/package.json +52 -3
  38. package/src/git.ts +444 -0
  39. package/src/global-repo.ts +343 -0
  40. package/src/index.ts +522 -0
  41. package/src/legacy.ts +170 -0
  42. package/src/native.ts +291 -0
  43. package/src/presets.ts +329 -0
  44. package/src/shared.ts +589 -0
  45. package/src/skill-discovery.ts +917 -0
  46. package/src/skill-panel.ts +488 -0
  47. package/src/update.ts +574 -0
  48. package/src/util.ts +570 -0
  49. package/README.md +0 -3
@@ -0,0 +1,488 @@
1
+ /**
2
+ * `utils-agents` skill-visibility half: a host-side switchboard for the skill
3
+ * catalog. The model-facing catalog is produced by filtering
4
+ * `ctx.skills.snapshot()` on `invocation.modelInvocable`, so this module pins
5
+ * `list` and `snapshot` on the registry instance and reports
6
+ * `modelInvocable: false` for the skill names the user disabled. `get` is
7
+ * deliberately untouched: a human can still load a disabled skill by name.
8
+ *
9
+ * The switchboard itself is a read-only route,
10
+ * `GET /api/dsh-utils/skill-panel/list` (path kept for the browser half),
11
+ * registered on the Connection API. It used to be the separate
12
+ * `@xi4z/dsh-utils-skill-panel` component; the bundle now mounts it as part of
13
+ * `@xi4z/dsh-utils-utils-agents`.
14
+ *
15
+ * @module @xi4z/dsh-utils-utils-agents/skill-panel
16
+ */
17
+
18
+ import type { Context } from '@deepseek-ai/cordis'
19
+ import type {
20
+ SkillCatalogSnapshot,
21
+ SkillSummary,
22
+ SkillViewOptions,
23
+ } from '@deepseek-ai/dsh-skill'
24
+ /** Exact Connection route that serves the panel's skill list. */
25
+ export const ROUTE_PATH = '/api/dsh-utils/skill-panel/list'
26
+
27
+ /** Reply headers shared by successful and failed route responses. */
28
+ const JSON_HEADERS = {
29
+ 'content-type': 'application/json; charset=utf-8',
30
+ 'cache-control': 'no-store',
31
+ } as const
32
+
33
+ /** Volatile Config fields arrive as live references; `.get()` snapshots. */
34
+ interface VolatileRef<T> {
35
+ get(): T
36
+ }
37
+
38
+ /** One setting as the Loader supplies it: a live reference, or a plain value in tests. */
39
+ type MaybeRef<T> = T | VolatileRef<T>
40
+
41
+ /** The runtime shape `apply` receives (the field is volatile and optional). */
42
+ export interface SkillPanelConfig {
43
+ readonly disabledSkills?: MaybeRef<readonly string[]>
44
+ }
45
+
46
+ /** The subset of the skill registry this component reads and pins. */
47
+ interface RegistryLike {
48
+ list(options?: SkillViewOptions): Promise<SkillSummary[]>
49
+ snapshot(options?: SkillViewOptions): Promise<SkillCatalogSnapshot>
50
+ get?(name: string, options?: SkillViewOptions): Promise<unknown>
51
+ }
52
+
53
+ /** Original discovery functions captured before the instance methods are pinned. */
54
+ interface Originals {
55
+ readonly list?: (options?: SkillViewOptions) => Promise<SkillSummary[]>
56
+ readonly snapshot?: (options?: SkillViewOptions) => Promise<SkillCatalogSnapshot>
57
+ }
58
+
59
+ /** One exact Connection Fetch route, structurally typed so no client dependency is needed. */
60
+ interface ConnectionLike {
61
+ readonly fetch: {
62
+ register(route: {
63
+ readonly path: string
64
+ readonly methods: readonly string[]
65
+ readonly requestBody: string
66
+ readonly fetch: (request: Request) => Promise<Response>
67
+ }): () => Promise<void>
68
+ }
69
+ }
70
+
71
+ /** One row of the route payload. */
72
+ interface SkillPanelRow {
73
+ name: string
74
+ description: string
75
+ whenToUse?: string
76
+ source: string
77
+ provider: string
78
+ path?: string
79
+ modelInvocable: boolean
80
+ userInvocable: boolean
81
+ enabled: boolean
82
+ }
83
+
84
+ /** The route payload; the browser panel parses this exact shape. */
85
+ interface SkillPanelPayload {
86
+ sessionId: string | null
87
+ cwd: string
88
+ complete: boolean
89
+ skills: SkillPanelRow[]
90
+ disabledSkills: string[]
91
+ }
92
+
93
+ /**
94
+ * Activate the component.
95
+ * @param ctx - host Cordis context; `skills` is guaranteed by {@link inject}.
96
+ * @param config - row config; volatile fields arrive as live references.
97
+ */
98
+ export function applySkillPanel(ctx: Context, config: SkillPanelConfig = {}): void {
99
+ const registry = (ctx as unknown as { skills?: RegistryLike }).skills
100
+ // Capture the raw service instance, not the traceable proxy: a bound proxy
101
+ // method still resolves `this.snapshot` dynamically and would run the pinned
102
+ // wrapper from the panel route.
103
+ const rawRegistry = underlying(registry) as RegistryLike | undefined
104
+ const originals: Originals = {
105
+ list: typeof rawRegistry?.list === 'function' ? rawRegistry.list.bind(rawRegistry) : undefined,
106
+ snapshot: typeof rawRegistry?.snapshot === 'function' ? rawRegistry.snapshot.bind(rawRegistry) : undefined,
107
+ }
108
+
109
+ const restores: Array<() => void> = []
110
+ if (registry && originals.list) {
111
+ const wrapped = (options?: SkillViewOptions): Promise<SkillSummary[]> =>
112
+ originals.list!(options).then((skills) => filterList(skills, config))
113
+ restores.push(pin(registry as unknown as Record<string, unknown>, 'list', wrapped))
114
+ }
115
+ if (registry && originals.snapshot) {
116
+ const wrapped = (options?: SkillViewOptions): Promise<SkillCatalogSnapshot> =>
117
+ originals.snapshot!(options).then((snapshot) => filterSnapshot(snapshot, config))
118
+ restores.push(pin(registry as unknown as Record<string, unknown>, 'snapshot', wrapped))
119
+ }
120
+ if (restores.length > 0) {
121
+ ctx.effect(() => () => {
122
+ for (const restore of restores.reverse()) {
123
+ try {
124
+ restore()
125
+ } catch (error) {
126
+ ctx.logger.warn(`utils-agents skill-panel: cannot restore the skill catalog methods: ${errorMessage(error)}`)
127
+ }
128
+ }
129
+ }, 'utils-agents skill-panel: catalog filter')
130
+ }
131
+
132
+ registerRoute(ctx, config, originals)
133
+ }
134
+
135
+ /**
136
+ * Replace one own or inherited method with a filtered wrapper and return the
137
+ * exact undo. An inherited method is shadowed with an own property and removed
138
+ * again so the prototype implementation comes back.
139
+ * @param holder - registry instance being pinned.
140
+ * @param key - method name.
141
+ * @param value - wrapper to install.
142
+ * @returns undo that restores the previous descriptor or deletes the shadow.
143
+ */
144
+ function pin(holder: Record<string, unknown>, key: string, value: unknown): () => void {
145
+ const own = Object.getOwnPropertyDescriptor(holder, key)
146
+ Object.defineProperty(holder, key, {
147
+ configurable: true,
148
+ enumerable: own?.enumerable ?? false,
149
+ writable: true,
150
+ value,
151
+ })
152
+ return () => {
153
+ const current = Object.getOwnPropertyDescriptor(holder, key)
154
+ if (own) {
155
+ if (current?.value === value) Object.defineProperty(holder, key, own)
156
+ return
157
+ }
158
+ if (current?.value === value) delete holder[key]
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Register the panel's list route on Connection.
164
+ * @param ctx - host context.
165
+ * @param config - row config; disabled names are re-read per request.
166
+ * @param originals - unwrapped discovery functions.
167
+ */
168
+ function registerRoute(ctx: Context, config: SkillPanelConfig, originals: Originals): void {
169
+ ctx.inject(['connection'], (scope) => {
170
+ const connection = (scope as unknown as { connection?: ConnectionLike }).connection
171
+ // A non-web host never provides Connection; the panel simply has no route.
172
+ if (!connection) return
173
+ scope.effect(() => {
174
+ try {
175
+ return connection.fetch.register({
176
+ path: ROUTE_PATH,
177
+ methods: ['GET'],
178
+ requestBody: 'buffered',
179
+ fetch: (request) => handleList(ctx, config, originals, request),
180
+ })
181
+ } catch (error) {
182
+ ctx.logger.warn(`utils-agents skill-panel: cannot register ${ROUTE_PATH}: ${errorMessage(error)}`)
183
+ return () => Promise.resolve()
184
+ }
185
+ }, `utils-agents skill-panel: ${ROUTE_PATH}`)
186
+ })
187
+ }
188
+
189
+ /**
190
+ * Serve one panel request.
191
+ * @param ctx - host context.
192
+ * @param config - row config.
193
+ * @param originals - unwrapped discovery functions.
194
+ * @param request - incoming GET request.
195
+ * @returns JSON response with the panel payload.
196
+ */
197
+ async function handleList(
198
+ ctx: Context,
199
+ config: SkillPanelConfig,
200
+ originals: Originals,
201
+ request: Request,
202
+ ): Promise<Response> {
203
+ try {
204
+ return json(await describe(ctx, config, originals, request), 200)
205
+ } catch (error) {
206
+ ctx.logger.warn(`utils-agents skill-panel: cannot list skills: ${errorMessage(error)}`)
207
+ return json({ error: errorMessage(error) }, 500)
208
+ }
209
+ }
210
+
211
+ /**
212
+ * Unwrap a Cordis traceable service proxy to the service instance it shadows.
213
+ * `agentPresets.serviceFor` may return another proxy for the same registry, and
214
+ * comparing proxies would miss the `list` this component pinned.
215
+ * @param value - a service or proxy.
216
+ * @returns the service instance when the value is a traceable proxy.
217
+ */
218
+ function underlying(value: unknown): unknown {
219
+ if (value === null || typeof value !== 'object') return value
220
+ const original = (value as Record<symbol, unknown>)[Symbol.for('cordis.original')]
221
+ return original ?? value
222
+ }
223
+
224
+ /**
225
+ * Build the panel payload for one request.
226
+ * @param ctx - host context.
227
+ * @param config - row config.
228
+ * @param originals - unwrapped discovery functions.
229
+ * @param request - incoming GET request.
230
+ * @returns the payload the browser panel parses.
231
+ */
232
+ async function describe(
233
+ ctx: Context,
234
+ config: SkillPanelConfig,
235
+ originals: Originals,
236
+ request: Request,
237
+ ): Promise<SkillPanelPayload> {
238
+ const sessionId = new URL(request.url).searchParams.get('sessionId')?.trim() || undefined
239
+ const agent = sessionId === undefined ? undefined : agentOf(ctx, sessionId)
240
+ const workingDirectory = serviceOf(ctx, 'workingDirectory')
241
+ const cwd = await resolveCwd(ctx, agent, workingDirectory, request.signal)
242
+ const registry = agent === undefined ? (ctx as unknown as { skills?: RegistryLike }).skills : scopedRegistry(ctx, agent)
243
+ const options: SkillViewOptions = {
244
+ cwd,
245
+ signal: request.signal,
246
+ ...(agent === undefined ? {} : { scope: agent as never }),
247
+ }
248
+ const skills = await listWithOriginals(ctx, registry, originals, options)
249
+ const disabled = disabledNames(config)
250
+ const disabledSet = new Set(disabled)
251
+ const rows = skills
252
+ .map((skill) => describeSkill(skill, disabledSet))
253
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
254
+ return {
255
+ sessionId: sessionId ?? null,
256
+ cwd,
257
+ complete: true,
258
+ skills: rows,
259
+ disabledSkills: disabled,
260
+ }
261
+ }
262
+
263
+ /**
264
+ * Read one host service defensively: this component ships without a dependency
265
+ * on the optional host packages that provide them.
266
+ * @param ctx - host context.
267
+ * @param name - service name.
268
+ * @returns the service, or undefined when the host does not provide it.
269
+ */
270
+ function serviceOf(ctx: Context, name: string): Record<string, unknown> | undefined {
271
+ const get = (ctx as unknown as { get?: (name: string) => unknown }).get
272
+ if (typeof get !== 'function') return undefined
273
+ try {
274
+ return get.call(ctx, name) as Record<string, unknown> | undefined
275
+ } catch {
276
+ return undefined
277
+ }
278
+ }
279
+
280
+ /**
281
+ * Resolve a live Agent for a session id.
282
+ * @param ctx - host context.
283
+ * @param sessionId - browser-supplied session id.
284
+ * @returns the live Agent, or undefined for an unknown session.
285
+ */
286
+ function agentOf(ctx: Context, sessionId: string): Record<string, any> | undefined {
287
+ const agents = serviceOf(ctx, 'agents')
288
+ if (agents === undefined || typeof agents.get !== 'function') return undefined
289
+ try {
290
+ return (agents.get as (id: string) => Record<string, any> | undefined)(sessionId)
291
+ } catch {
292
+ return undefined
293
+ }
294
+ }
295
+
296
+ /**
297
+ * Pick the skill registry a live Agent reads: a preset scoped layer when the
298
+ * Agent runs in one, otherwise the host registry.
299
+ * @param ctx - host context.
300
+ * @param agent - live Agent.
301
+ * @returns the skill registry to list.
302
+ */
303
+ function scopedRegistry(ctx: Context, agent: Record<string, any>): RegistryLike | undefined {
304
+ const presets = serviceOf(ctx, 'agentPresets')
305
+ if (presets !== undefined && typeof presets.serviceFor === 'function') {
306
+ try {
307
+ const scoped = (presets.serviceFor as (agent: unknown, name: string) => unknown)(agent, 'skills')
308
+ if (scoped !== undefined && scoped !== null) return scoped as RegistryLike
309
+ } catch (error) {
310
+ ctx.logger.debug(`utils-agents skill-panel: preset skill layer lookup failed: ${errorMessage(error)}`)
311
+ }
312
+ }
313
+ return (ctx as unknown as { skills?: RegistryLike }).skills
314
+ }
315
+
316
+ /**
317
+ * Resolve the workspace root used for discovery.
318
+ * @param ctx - host context.
319
+ * @param agent - live Agent, if any.
320
+ * @param workingDirectory - `ctx.workingDirectory`, if the host provides it.
321
+ * @param signal - request cancellation.
322
+ * @returns an absolute directory.
323
+ */
324
+ async function resolveCwd(
325
+ ctx: Context,
326
+ agent: Record<string, any> | undefined,
327
+ workingDirectory: Record<string, any> | undefined,
328
+ signal: AbortSignal,
329
+ ): Promise<string> {
330
+ if (agent !== undefined && workingDirectory !== undefined && typeof workingDirectory.ensure === 'function') {
331
+ try {
332
+ const cwd = await (workingDirectory.ensure as (agent: unknown, signal?: AbortSignal) => Promise<unknown>)(agent, signal)
333
+ if (typeof cwd === 'string' && cwd !== '') return cwd
334
+ } catch (error) {
335
+ ctx.logger.debug(`utils-agents skill-panel: working directory lookup failed: ${errorMessage(error)}`)
336
+ }
337
+ }
338
+ const sessionCwd = agent?.session?.header?.cwd
339
+ if (typeof sessionCwd === 'string' && sessionCwd !== '') return sessionCwd
340
+ const fallback = workingDirectory?.defaultDirectory
341
+ if (typeof fallback === 'string' && fallback !== '') return fallback
342
+ return process.cwd()
343
+ }
344
+
345
+ /**
346
+ * List skills through the captured (unwrapped) function, so the panel always
347
+ * sees disabled skills and can render their off switches.
348
+ * @param ctx - host context.
349
+ * @param registry - registry selected for this request.
350
+ * @param originals - captured discovery functions.
351
+ * @param options - lookup options.
352
+ * @returns winning skill summaries.
353
+ */
354
+ async function listWithOriginals(
355
+ ctx: Context,
356
+ registry: RegistryLike | undefined,
357
+ originals: Originals,
358
+ options: SkillViewOptions,
359
+ ): Promise<SkillSummary[]> {
360
+ if (registry === undefined) throw new Error('skill registry is unavailable')
361
+ const host = (ctx as unknown as { skills?: RegistryLike }).skills
362
+ const same = underlying(registry) === underlying(host)
363
+ if (same && originals.snapshot !== undefined) {
364
+ // `SkillRegistry.list()` delegates to `this.snapshot()`. Even the captured
365
+ // `list` would resolve that through the pinned proxy, so read the captured
366
+ // raw snapshot for the panel's unfiltered view.
367
+ const snapshot = await originals.snapshot(options)
368
+ return snapshot.skills
369
+ }
370
+ const target = underlying(registry) as RegistryLike
371
+ if (typeof target.snapshot === 'function') {
372
+ return (await target.snapshot(options)).skills
373
+ }
374
+ if (typeof target.list !== 'function') throw new Error('skill registry does not expose list()')
375
+ return target.list(options)
376
+ }
377
+
378
+ /**
379
+ * Read the configured disabled names, trimming and de-duplicating them.
380
+ * @param config - row config, possibly holding a volatile reference.
381
+ * @returns normalized names; never cached across calls.
382
+ */
383
+ function disabledNames(config: SkillPanelConfig | undefined): string[] {
384
+ const ref = config?.disabledSkills
385
+ let raw: unknown = ref
386
+ if (ref !== null && typeof ref === 'object' && typeof (ref as VolatileRef<unknown>).get === 'function') {
387
+ try {
388
+ raw = (ref as VolatileRef<unknown>).get()
389
+ } catch {
390
+ return []
391
+ }
392
+ }
393
+ if (!Array.isArray(raw)) return []
394
+ const names: string[] = []
395
+ const seen = new Set<string>()
396
+ for (const entry of raw) {
397
+ if (typeof entry !== 'string') continue
398
+ const value = entry.trim()
399
+ if (value === '' || seen.has(value)) continue
400
+ seen.add(value)
401
+ names.push(value)
402
+ }
403
+ return names
404
+ }
405
+
406
+ /**
407
+ * Hide disabled skills from one summary array without mutating it.
408
+ * @param skills - registry summaries.
409
+ * @param config - row config.
410
+ * @returns the same array when nothing is disabled, else a mapped copy.
411
+ */
412
+ function filterList(skills: SkillSummary[], config: SkillPanelConfig): SkillSummary[] {
413
+ if (!Array.isArray(skills)) return skills
414
+ const disabled = disabledNames(config)
415
+ if (disabled.length === 0) return skills
416
+ const set = new Set(disabled)
417
+ return skills.map((skill) => hideSkill(skill, set))
418
+ }
419
+
420
+ /**
421
+ * Report disabled skills as model-uninvocable in one catalog observation.
422
+ * @param snapshot - registry observation.
423
+ * @param config - row config.
424
+ * @returns the same observation when nothing is disabled, else a mapped copy.
425
+ */
426
+ function filterSnapshot(snapshot: SkillCatalogSnapshot, config: SkillPanelConfig): SkillCatalogSnapshot {
427
+ if (snapshot === null || typeof snapshot !== 'object' || !Array.isArray(snapshot.skills)) return snapshot
428
+ const skills = filterList(snapshot.skills, config)
429
+ if (skills === snapshot.skills) return snapshot
430
+ return { ...snapshot, skills }
431
+ }
432
+
433
+ /**
434
+ * Mark one disabled skill as model-uninvocable.
435
+ * @param skill - registry summary.
436
+ * @param disabled - normalized disabled name set.
437
+ * @returns a patched summary, or the input when it is not disabled.
438
+ */
439
+ function hideSkill(skill: SkillSummary, disabled: ReadonlySet<string>): SkillSummary {
440
+ if (skill === null || typeof skill !== 'object') return skill
441
+ if (typeof skill.name !== 'string' || !disabled.has(skill.name)) return skill
442
+ if (typeof skill.invocation?.modelInvocable === 'boolean' && skill.invocation.modelInvocable === false) return skill
443
+ return {
444
+ ...skill,
445
+ invocation: { ...(skill.invocation ?? {}), modelInvocable: false },
446
+ } as SkillSummary
447
+ }
448
+
449
+ /**
450
+ * Project one summary into the route row shape.
451
+ * @param skill - registry summary.
452
+ * @param disabled - normalized disabled name set.
453
+ * @returns the browser-facing row.
454
+ */
455
+ function describeSkill(skill: SkillSummary, disabled: ReadonlySet<string>): SkillPanelRow {
456
+ const modelInvocable = skill.invocation?.modelInvocable !== false
457
+ const userInvocable = skill.invocation?.userInvocable !== false
458
+ return {
459
+ name: skill.name,
460
+ description: skill.description,
461
+ ...(typeof skill.whenToUse === 'string' && skill.whenToUse !== '' ? { whenToUse: skill.whenToUse } : {}),
462
+ source: skill.source,
463
+ provider: skill.provider,
464
+ ...(typeof skill.path === 'string' && skill.path !== '' ? { path: skill.path } : {}),
465
+ modelInvocable,
466
+ userInvocable,
467
+ enabled: modelInvocable && !disabled.has(skill.name),
468
+ }
469
+ }
470
+
471
+ /**
472
+ * Build one JSON response.
473
+ * @param value - payload.
474
+ * @param status - HTTP status.
475
+ * @returns the response.
476
+ */
477
+ function json(value: unknown, status: number): Response {
478
+ return new Response(JSON.stringify(value), { status, headers: JSON_HEADERS })
479
+ }
480
+
481
+ /**
482
+ * Render an unknown error for a log line or route payload.
483
+ * @param error - thrown value.
484
+ * @returns its message.
485
+ */
486
+ function errorMessage(error: unknown): string {
487
+ return error instanceof Error ? error.message : String(error)
488
+ }