@sparkelf/dsh-plus 0.2.9-alpha.92 → 0.2.9-alpha.93

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.
@@ -1,646 +0,0 @@
1
- diff --git a/packages/core/session/src/index.ts b/packages/core/session/src/index.ts
2
- index 82d57f11..e3d8a856 100644
3
- --- a/packages/core/session/src/index.ts
4
- +++ b/packages/core/session/src/index.ts
5
- @@ -582,6 +582,15 @@ export class Session {
6
- */
7
- readonly header: SessionHeader
8
-
9
- + /**
10
- + * Opaque connector identity for this Session, or undefined when nobody attached one.
11
- + *
12
- + * The base never interprets it: it only hands it to the disclosure filters a plugin registered,
13
- + * which decide what the value means. Writable on purpose -- the owner replaces the whole object
14
- + * when its identity snapshot changes, rather than mutating a value other readers may hold.
15
- + */
16
- + actor?: unknown
17
- +
18
- /** Number of leading events inherited from this Session's fork parent. */
19
- readonly inheritedEventCount: SessionLogOffset
20
-
21
- @@ -1266,6 +1275,7 @@ export class SessionStore extends Service {
22
- eventState,
23
- this.projections,
24
- )
25
- + if (options.actor !== undefined) session.actor = options.actor
26
- attachments.set(session, null)
27
- return session
28
- }
29
- @@ -1290,6 +1300,7 @@ export class SessionStore extends Service {
30
- ...meta?.agentPreset === undefined ? {} : { agentPreset: meta.agentPreset },
31
- }
32
- const session = Session.create(sessionId, seed, header, options?.inheritedEventCount, this.projections)
33
- + if (options?.actor !== undefined) session.actor = options.actor
34
- attachments.set(session, null)
35
- return session
36
- }
37
- diff --git a/packages/core/session/src/types.ts b/packages/core/session/src/types.ts
38
- index 0f350a41..023601e9 100644
39
- --- a/packages/core/session/src/types.ts
40
- +++ b/packages/core/session/src/types.ts
41
- @@ -141,6 +141,15 @@ export interface SessionHeader {
42
- * store folds into a {@link SessionHeader}.
43
- */
44
- export interface CreateSessionOptions {
45
- + /**
46
- + * Opaque identity the owning connector attaches to this Session.
47
- + *
48
- + * The base neither reads nor copies it: a disclosure filter handed to
49
- + * `ctx.tools.addVisibilityFilter` / `ctx.skills.addVisibilityFilter` is the only consumer, and
50
- + * it interprets the value on its own. The connector replaces the whole object to refresh what
51
- + * it stands for, so a stale snapshot can never be mistaken for a live one.
52
- + */
53
- + readonly actor?: unknown
54
- /** Initial replay or fork history supplied at construction. */
55
- readonly seed?: readonly SessionEvent[]
56
- /**
57
- @@ -183,6 +192,8 @@ export interface RestoredSessionOptions {
58
- readonly inheritedEventCount: SessionLogOffset
59
- /** Aliasing state carried from the operation that produced the seed. */
60
- readonly eventState: SessionSeedEventState
61
- + /** Opaque connector identity, attached after the restored Session is constructed. */
62
- + readonly actor?: unknown
63
- }
64
-
65
- /** Inputs accepted while constructing an unpublished Session. */
66
- diff --git a/packages/core/tools/src/contracts.ts b/packages/core/tools/src/contracts.ts
67
- index 51597b41..9694b613 100644
68
- --- a/packages/core/tools/src/contracts.ts
69
- +++ b/packages/core/tools/src/contracts.ts
70
- @@ -4,7 +4,7 @@ import { TOOL_CONTEXT_UNAVAILABLE } from './error-codes.ts'
71
- import type { ToolCallId, ContentBlock, ToolSchema } from '@deepseek-ai/dsh-llm'
72
- import type { Agent, ModelSelection } from '@deepseek-ai/dsh-agent'
73
- import type { ScopeKey } from '@deepseek-ai/dsh-scope'
74
- -import type { UserMessage } from '@deepseek-ai/dsh-session'
75
- +import type { Session, UserMessage } from '@deepseek-ai/dsh-session'
76
- import type { JsonValue } from '@deepseek-ai/dsh-util-values'
77
- import type { JsonSchemaNode } from './json-schema.ts'
78
- import type { ToolCallView, ToolResultView } from './presentation.ts'
79
- @@ -112,6 +112,32 @@ export interface ToolActivationContext {
80
- readonly signal: AbortSignal
81
- }
82
-
83
- +/**
84
- + * One disclosure rule over the model-facing tool list.
85
- + *
86
- + * The base owns no permission model. A plugin that knows which tools are sensitive registers a
87
- + * filter; the rule itself decides what "sensitive" means, and the base only applies the result
88
- + * while it assembles the step's tool set.
89
- + */
90
- +export interface ToolVisibilityFilter {
91
- + /**
92
- + * Whether this rule speaks about one tool.
93
- + * @param tool - registered definition, including its name.
94
- + * @returns true when {@link hidden} must be consulted for this tool; false leaves it untouched.
95
- + */
96
- + readonly appliesTo: (tool: ToolDefinition) => boolean
97
- + /**
98
- + * Whether the tool must be withheld from the model in this Session.
99
- + *
100
- + * Called only for tools {@link appliesTo} accepted. Return true to hide. An exception is logged
101
- + * and treated as "not hidden", so one broken rule cannot empty the tool list.
102
- + * @param session - the Session being assembled, or undefined outside a Session.
103
- + * @param tool - the same definition {@link appliesTo} received.
104
- + * @returns true to hide the tool for this Session.
105
- + */
106
- + readonly hidden: (session: Session | undefined, tool: ToolDefinition) => boolean
107
- +}
108
- +
109
- /** Lifecycle-owned conditions for a registered tool. */
110
- export interface ToolRegistrationOptions {
111
- /**
112
- diff --git a/packages/core/tools/src/index.ts b/packages/core/tools/src/index.ts
113
- index 0cb307d1..bc1f3611 100644
114
- --- a/packages/core/tools/src/index.ts
115
- +++ b/packages/core/tools/src/index.ts
116
- @@ -3,6 +3,7 @@ import { Context, Service } from '@deepseek-ai/cordis'
117
- import z from '@deepseek-ai/schemastery'
118
- import { AnonymousEntries, NamedEntries, ScopedLayers, scopeOf, scopeChainOf } from '@deepseek-ai/dsh-scope'
119
- import type { ScopeKey, ScopeLayer } from '@deepseek-ai/dsh-scope'
120
- +import type { Agent } from '@deepseek-ai/dsh-agent'
121
- import { ToolExecutorUnavailableError } from './executor.ts'
122
- import type { ToolExecutor, ToolBatchInput, ToolBatchResult } from './executor.ts'
123
- import './events.ts'
124
- @@ -12,7 +13,7 @@ import { assertSupportedJsonSchema } from './json-schema.ts'
125
- import { RUN_CODE_NAME, ToolActivationError } from './contracts.ts'
126
- import type {
127
- ToolDefinition, ToolRestriction, ToolExecution, ToolGuard, ToolGuardDenial,
128
- - ResolvedToolSet, ToolActivationContext, ToolRegistrationOptions,
129
- + ResolvedToolSet, ToolActivationContext, ToolRegistrationOptions, ToolVisibilityFilter,
130
- } from './contracts.ts'
131
-
132
- declare module '@deepseek-ai/dsh-system-prompt' {
133
- @@ -97,6 +98,12 @@ class GuardLayer {
134
-
135
- /** Concrete tool registry and scoped executor dispatcher. */
136
- export class ToolsService extends Service {
137
- + /**
138
- + * Disclosure rules contributed by plugins. The base never inspects a rule: it asks each one
139
- + * whether it applies and whether the tool must be hidden, and treats a throw as "not hidden".
140
- + * Registration order does not matter -- the result is the union of every hiding rule.
141
- + */
142
- + private readonly visibilityFilters = new Set<ToolVisibilityFilter>()
143
- static inject = ['systemPrompt']
144
- static Config = z.object({
145
- mode: z.never().description('Removed. Mount a native or PTC tool executor instead.'),
146
- @@ -276,7 +283,7 @@ export class ToolsService extends Service {
147
- throw new ToolActivationError(name, cause)
148
- }
149
- signal.throwIfAborted()
150
- - if (enabled) admitted.set(name, definition)
151
- + if (enabled && !this.hiddenHere(context.agent, definition)) admitted.set(name, definition)
152
- }
153
- let closed = false
154
- return Object.freeze({
155
- @@ -296,6 +303,50 @@ export class ToolsService extends Service {
156
- })
157
- }
158
-
159
- + /**
160
- + * Register one disclosure rule over the model-facing tool list.
161
- + *
162
- + * Only {@link ToolsService.resolve} consults the rules; programmatic reads
163
- + * ({@link ToolsService.definitions}, {@link ToolsService.get}, {@link ToolsService.executable}) stay
164
- + * complete, so plugins keep seeing each other's tools. A rule applies only to the tools its
165
- + * `appliesTo` accepts, and any matching rule that hides a tool wins -- several plugins therefore
166
- + * hide the union of their rules without knowing about each other.
167
- + * @param filter - the rule; it must be pure and fast, because assembly runs it once per tool.
168
- + * @returns the disposer; owning it through `ctx.effect` unregisters with the plugin.
169
- + */
170
- + addVisibilityFilter(filter: ToolVisibilityFilter): () => void {
171
- + return this.ctx.effect(() => {
172
- + this.visibilityFilters.add(filter)
173
- + return () => { this.visibilityFilters.delete(filter) }
174
- + }, 'tools.addVisibilityFilter()')
175
- + }
176
- +
177
- + /**
178
- + * Whether any registered disclosure rule hides one tool for this step's Session.
179
- + *
180
- + * Fail-open by design: a rule that throws is logged and ignored, because a broken plugin must not
181
- + * empty the model's tool list. `appliesTo` is consulted first, so a rule never sees a tool it
182
- + * disclaimed, and a tool no rule claims is returned unchanged.
183
- + * @param agent - the Agent preparing the step; its Session carries the opaque actor a rule reads.
184
- + * @param definition - one admitted definition.
185
- + * @returns true when the definition must stay out of the step's tool set.
186
- + */
187
- + private hiddenHere(agent: Agent, definition: ToolDefinition): boolean {
188
- + if (this.visibilityFilters.size === 0) return false
189
- + const session = agent.session
190
- + for (const filter of this.visibilityFilters) {
191
- + try {
192
- + if (!filter.appliesTo(definition)) continue
193
- + if (filter.hidden(session, definition)) return true
194
- + } catch (error: unknown) {
195
- + this.ctx.logger.warn(
196
- + `tool "${definition.name}": a visibility filter failed and was ignored: ${String(error)}`,
197
- + )
198
- + }
199
- + }
200
- + return false
201
- + }
202
- +
203
- /**
204
- * Read the visible capability definitions for descriptions and program bindings.
205
- * @param scope - viewing Agent or preset; omitted selects the global view.
206
- diff --git a/packages/core/tools/tests/visibility.spec.ts b/packages/core/tools/tests/visibility.spec.ts
207
- new file mode 100644
208
- index 00000000..d6006337
209
- --- /dev/null
210
- +++ b/packages/core/tools/tests/visibility.spec.ts
211
- @@ -0,0 +1,136 @@
212
- +/** Disclosure filters narrow the step's model-facing tool set without touching programmatic reads. */
213
- +import { afterEach, expect, it } from 'vitest'
214
- +import { Context } from '@deepseek-ai/cordis'
215
- +import type { Agent } from '@deepseek-ai/dsh-agent'
216
- +import { SessionId } from '@deepseek-ai/dsh-session'
217
- +import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native'
218
- +import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
219
- +import ToolRuntime, { defineTool } from '@deepseek-ai/dsh-tools'
220
- +
221
- +const TEST_MODEL_SELECTION = { provider: 'test', model: 'test' }
222
- +const contexts: Context[] = []
223
- +afterEach(async () => {
224
- + for (const ctx of contexts.splice(0)) await ctx.fiber.dispose()
225
- +})
226
- +
227
- +/** An agent whose Session carries an opaque actor, or no Session at all. */
228
- +function agentWith(id: string, actor?: unknown): Agent {
229
- + return {
230
- + id: SessionId(id),
231
- + ...actor === undefined ? {} : { session: { actor } },
232
- + } as unknown as Agent
233
- +}
234
- +
235
- +const tool = (name: string) => defineTool({
236
- + name,
237
- + description: `The ${name} operation.`,
238
- + parameters: {},
239
- + output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
240
- + async execute() { return name },
241
- +})
242
- +
243
- +async function setup() {
244
- + const ctx = new Context()
245
- + contexts.push(ctx)
246
- + await ctx.plugin(SystemPrompt)
247
- + await ctx.plugin(ToolRuntime)
248
- + await ctx.plugin(NativeToolExecutor)
249
- + ctx.tools.register(tool('toolA'))
250
- + ctx.tools.register(tool('toolB'))
251
- + const controller = new AbortController()
252
- + const names = async (agent: Agent): Promise<string[]> => {
253
- + const toolSet = await ctx.tools.resolve({ agent, modelSelection: TEST_MODEL_SELECTION, signal: controller.signal })
254
- + try {
255
- + return ctx.tools.schemas(agent, toolSet).map(schema => schema.name)
256
- + } finally {
257
- + toolSet.dispose()
258
- + }
259
- + }
260
- + return { ctx, names, signal: controller.signal }
261
- +}
262
- +
263
- +it('keeps the whole set when nothing registers a filter', async () => {
264
- + const h = await setup()
265
- + // The registry is opt-in: with no rule the step sees exactly what it saw before.
266
- + expect(await h.names(agentWith('a', { permissions: ['toolA'] }))).toEqual(['toolA', 'toolB'])
267
- + expect(await h.names(agentWith('b'))).toEqual(['toolA', 'toolB'])
268
- +})
269
- +
270
- +it('hides only the tools a matching rule withholds, per Session', async () => {
271
- + const h = await setup()
272
- + // A connector that knows which tools need an identity hides everything but its own tool when the
273
- + // Session carries no actor. The rule never sees toolA, so that tool is unaffected.
274
- + h.ctx.tools.addVisibilityFilter({
275
- + appliesTo: definition => definition.name !== 'toolA',
276
- + hidden: session => session?.actor === undefined,
277
- + })
278
- +
279
- + expect(await h.names(agentWith('with-actor', { permissions: ['toolA'] }))).toEqual(['toolA', 'toolB'])
280
- + expect(await h.names(agentWith('without-actor'))).toEqual(['toolA'])
281
- +})
282
- +
283
- +it('leaves unclaimed and explicitly unhidden tools alone', async () => {
284
- + const h = await setup()
285
- + h.ctx.tools.addVisibilityFilter({ appliesTo: () => false, hidden: () => true })
286
- + h.ctx.tools.addVisibilityFilter({ appliesTo: definition => definition.name === 'toolB', hidden: () => false })
287
- +
288
- + // Neither rule claims toolA, and the one that claims toolB declines to hide it.
289
- + expect(await h.names(agentWith('plain'))).toEqual(['toolA', 'toolB'])
290
- +})
291
- +
292
- +it('restores the full set when the registration is disposed', async () => {
293
- + const h = await setup()
294
- + const dispose = h.ctx.tools.addVisibilityFilter({
295
- + appliesTo: definition => definition.name === 'toolB',
296
- + hidden: () => true,
297
- + })
298
- + expect(await h.names(agentWith('plain'))).toEqual(['toolA'])
299
- +
300
- + dispose()
301
- + expect(await h.names(agentWith('plain'))).toEqual(['toolA', 'toolB'])
302
- +})
303
- +
304
- +it('hides the union of several plugins rules', async () => {
305
- + const h = await setup()
306
- + h.ctx.tools.addVisibilityFilter({
307
- + appliesTo: definition => definition.name === 'toolA',
308
- + hidden: () => true,
309
- + })
310
- + h.ctx.tools.addVisibilityFilter({
311
- + appliesTo: definition => definition.name === 'toolB',
312
- + hidden: () => true,
313
- + })
314
- +
315
- + // Each plugin hides its own tool without knowing the other exists; both disappear.
316
- + expect(await h.names(agentWith('plain'))).toEqual([])
317
- +})
318
- +
319
- +it('treats a throwing rule as not hiding', async () => {
320
- + const h = await setup()
321
- + h.ctx.tools.addVisibilityFilter({
322
- + appliesTo: definition => definition.name === 'toolA',
323
- + hidden: () => { throw new Error('broken connector') },
324
- + })
325
- + h.ctx.tools.addVisibilityFilter({
326
- + appliesTo: () => { throw new Error('broken matcher') },
327
- + hidden: () => true,
328
- + })
329
- +
330
- + // A broken plugin must not empty the model's tool list.
331
- + expect(await h.names(agentWith('plain'))).toEqual(['toolA', 'toolB'])
332
- +})
333
- +
334
- +it('leaves programmatic reads complete', async () => {
335
- + const h = await setup()
336
- + h.ctx.tools.addVisibilityFilter({
337
- + appliesTo: definition => definition.name === 'toolB',
338
- + hidden: () => true,
339
- + })
340
- + const agent = agentWith('plain')
341
- +
342
- + // Inspection and dispatch stay whole: plugins keep seeing each other's tools, and the filter only
343
- + // governs what the step offers the model.
344
- + expect(h.ctx.tools.definitions(agent).map(definition => definition.name)).toEqual(['toolA', 'toolB'])
345
- + expect(h.ctx.tools.get('toolB', agent)?.name).toBe('toolB')
346
- + expect(h.ctx.tools.executable('toolB', agent)?.name).toBe('toolB')
347
- +})
348
-
349
- diff --git a/packages/skill/skill/src/index.ts b/packages/skill/skill/src/index.ts
350
- index 9c6bbf0c..c5901a08 100644
351
- --- a/packages/skill/skill/src/index.ts
352
- +++ b/packages/skill/skill/src/index.ts
353
- @@ -105,6 +105,49 @@ export interface SkillLookupOptions {
354
- readonly cwd?: string | undefined
355
- /** Abort discovery or loading work for the current caller. */
356
- readonly signal?: AbortSignal | undefined
357
- + /**
358
- + * Session the lookup belongs to, handed to every registered disclosure filter.
359
- + *
360
- + * Optional: a caller outside a Session (a cold listing, a test) reads the unfiltered catalog, so
361
- + * a plugin's rule only ever narrows a real Session's view.
362
- + */
363
- + readonly session?: SkillFilterSession | undefined
364
- +}
365
- +
366
- +/**
367
- + * The part of a Session a disclosure rule may read.
368
- + *
369
- + * Structural on purpose: the skill registry does not own Session identity and must not depend on
370
- + * the session package. A real `Session` satisfies this, so a caller passes `session` unchanged.
371
- + */
372
- +export interface SkillFilterSession {
373
- + /** Opaque connector identity; the base never interprets it. */
374
- + readonly actor?: unknown
375
- +}
376
- +
377
- +/**
378
- + * One disclosure rule over the skills a Session may see.
379
- + *
380
- + * Same shape and the same fail-open behaviour as the tool rule: the base owns no permission model,
381
- + * the plugin decides what `hidden` means, and several plugins hide the union of their rules.
382
- + */
383
- +export interface SkillVisibilityFilter {
384
- + /**
385
- + * Whether this rule speaks about one candidate.
386
- + * @param candidate - discovery candidate, including its name and metadata.
387
- + * @returns true when {@link hidden} must be consulted; false leaves the skill untouched.
388
- + */
389
- + readonly appliesTo: (candidate: SkillCandidate) => boolean
390
- + /**
391
- + * Whether the skill must stay out of this Session's list and load results.
392
- + *
393
- + * Called only for candidates {@link appliesTo} accepted. An exception is logged and treated as
394
- + * "not hidden", so one broken rule cannot empty the catalog.
395
- + * @param session - the Session the lookup belongs to, or undefined outside one.
396
- + * @param candidate - the same candidate {@link appliesTo} received.
397
- + * @returns true to hide the skill for this Session.
398
- + */
399
- + readonly hidden: (session: SkillFilterSession | undefined, candidate: SkillCandidate) => boolean
400
- }
401
-
402
- /**
403
- @@ -363,6 +406,12 @@ export class SkillRegistry extends Service {
404
- scope => new SkillLayer(scope),
405
- () => { this.invalidateCache() },
406
- )
407
- + /**
408
- + * Disclosure rules contributed by plugins. Applied at read time rather than inside the collect
409
- + * cache, because the answer depends on the Session (`actor`) and the cache is keyed by workspace
410
- + * and scope alone.
411
- + */
412
- + private readonly visibilityFilters = new Set<SkillVisibilityFilter>()
413
- private readonly collectCache = new Map<string, Map<string, IndexedCandidate>>()
414
- private revision = 0
415
- private nextProviderOrder = 0
416
- @@ -459,6 +508,23 @@ export class SkillRegistry extends Service {
417
- )
418
- }
419
-
420
- + /**
421
- + * Register one disclosure rule over the skills a Session may see.
422
- + *
423
- + * The rule narrows {@link SkillRegistry.list}, {@link SkillRegistry.snapshot} and
424
- + * {@link SkillRegistry.get} for the Session a lookup names; lookups without one read the full
425
- + * catalog. A rule decides only about the candidates its `appliesTo` accepts, and any matching
426
- + * rule that hides a skill wins.
427
- + * @param filter - the rule; it must be pure and fast.
428
- + * @returns the disposer; owning it through `ctx.effect` unregisters with the plugin.
429
- + */
430
- + addVisibilityFilter(filter: SkillVisibilityFilter): () => void {
431
- + return this.ctx.effect(() => {
432
- + this.visibilityFilters.add(filter)
433
- + return () => { this.visibilityFilters.delete(filter) }
434
- + }, 'skills.addVisibilityFilter()')
435
- + }
436
- +
437
- /**
438
- * List invocation-neutral skill summaries for a workspace. Consumers apply
439
- * model or user invocation policy at their operational boundary. Lookup
440
- @@ -482,6 +548,7 @@ export class SkillRegistry extends Service {
441
- const collected = await this.collect(options)
442
- return {
443
- skills: [...collected.entries.values()]
444
- + .filter(entry => !this.hiddenHere(options.session, entry.candidate))
445
- .map(entry => toSummary(entry.candidate))
446
- .sort(compareSkillSummary),
447
- complete: collected.cacheable,
448
- @@ -503,6 +570,7 @@ export class SkillRegistry extends Service {
449
- throwIfAborted(options.signal)
450
- const match = collected.entries.get(name)
451
- if (match === undefined) return undefined
452
- + if (this.hiddenHere(options.session, match.candidate)) return undefined
453
- const definition = await waitWithAbort(
454
- match.provider.get(match.candidate, options),
455
- options.signal,
456
- @@ -516,6 +584,30 @@ export class SkillRegistry extends Service {
457
- return definition
458
- }
459
-
460
- + /**
461
- + * Whether a registered disclosure rule hides one candidate for this lookup's Session.
462
- + *
463
- + * Fail-open like the tool rules: a throwing rule is logged and ignored rather than taking the
464
- + * catalog down with it, and a candidate no rule claims is unaffected.
465
- + * @param session - the Session the lookup belongs to, or undefined.
466
- + * @param candidate - one collected candidate.
467
- + * @returns true when the candidate must not appear in this Session's list or load.
468
- + */
469
- + private hiddenHere(session: SkillFilterSession | undefined, candidate: SkillCandidate): boolean {
470
- + if (this.visibilityFilters.size === 0) return false
471
- + for (const filter of this.visibilityFilters) {
472
- + try {
473
- + if (!filter.appliesTo(candidate)) continue
474
- + if (filter.hidden(session, candidate)) return true
475
- + } catch (error: unknown) {
476
- + this.ctx.logger.warn(
477
- + `skill "${candidate.name}": a visibility filter failed and was ignored: ${String(error)}`,
478
- + )
479
- + }
480
- + }
481
- + return false
482
- + }
483
- +
484
- private async collect(options: SkillViewOptions): Promise<CollectResult> {
485
- throwIfAborted(options.signal)
486
- let attempt = 1
487
- diff --git a/packages/skill/skill/tests/visibility.spec.ts b/packages/skill/skill/tests/visibility.spec.ts
488
- new file mode 100644
489
- index 00000000..32f60727
490
- --- /dev/null
491
- +++ b/packages/skill/skill/tests/visibility.spec.ts
492
- @@ -0,0 +1,131 @@
493
- +/** Disclosure filters narrow the skills a Session may list and load. */
494
- +import { describe, expect, it } from 'vitest'
495
- +import { Context } from '@deepseek-ai/cordis'
496
- +import SkillRegistry, {
497
- + type SkillCandidate,
498
- + type SkillDefinition,
499
- + type SkillLookupOptions,
500
- + type SkillProvider,
501
- +} from '@deepseek-ai/dsh-skill'
502
- +
503
- +function skill(name: string): SkillCandidate {
504
- + return {
505
- + name,
506
- + description: `${name} description.`,
507
- + invocation: { modelInvocable: true, userInvocable: true },
508
- + provider: 'memory',
509
- + source: 'memory',
510
- + rank: 10,
511
- + locator: { content: `${name} body.` },
512
- + }
513
- +}
514
- +
515
- +class MemoryProvider implements SkillProvider {
516
- + readonly name = 'memory'
517
- + constructor(private readonly candidates: SkillCandidate[]) {}
518
- + async list(): Promise<SkillCandidate[]> {
519
- + return this.candidates
520
- + }
521
- + async get(candidate: SkillCandidate): Promise<SkillDefinition | undefined> {
522
- + return { ...candidate, content: (candidate.locator as { content: string }).content }
523
- + }
524
- +}
525
- +
526
- +/** An agent Session stand-in carrying an opaque actor, or nothing. */
527
- +const sessionWith = (actor?: unknown): { actor?: unknown } => actor === undefined ? {} : { actor }
528
- +
529
- +async function setup() {
530
- + const ctx = new Context()
531
- + await ctx.plugin(SkillRegistry)
532
- + ctx.skills.registerProvider(() => new MemoryProvider([skill('alpha'), skill('beta')]))
533
- + const names = async (options: SkillLookupOptions = {}): Promise<string[]> =>
534
- + (await ctx.skills.list(options)).map(entry => entry.name)
535
- + return { ctx, names }
536
- +}
537
- +
538
- +describe('SkillRegistry visibility filters', () => {
539
- + it('keeps the catalog unchanged when nothing registers a filter', async () => {
540
- + const h = await setup()
541
- + expect(await h.names()).toEqual(['alpha', 'beta'])
542
- + expect(await h.names({ session: sessionWith({ permissions: ['alpha'] }) })).toEqual(['alpha', 'beta'])
543
- + })
544
- +
545
- + it('hides only what a matching rule withholds, per Session', async () => {
546
- + const h = await setup()
547
- + h.ctx.skills.addVisibilityFilter({
548
- + appliesTo: candidate => candidate.name !== 'alpha',
549
- + // A rule sees `undefined` when the lookup names no Session and decides for itself; this one
550
- + // only narrows a real Session, so an administrative listing still reads the whole catalog.
551
- + hidden: session => session !== undefined && session.actor === undefined,
552
- + })
553
- +
554
- + // A Session carrying an actor keeps the full catalog; one without it loses only what the rule
555
- + // claims, and `alpha` was never claimed.
556
- + expect(await h.names({ session: sessionWith({ permissions: ['alpha'] }) })).toEqual(['alpha', 'beta'])
557
- + expect(await h.names({ session: sessionWith() })).toEqual(['alpha'])
558
- + expect(await h.names()).toEqual(['alpha', 'beta'])
559
- + })
560
- +
561
- + it('withholds load results too, so a hidden skill cannot be fetched by name', async () => {
562
- + const h = await setup()
563
- + h.ctx.skills.addVisibilityFilter({
564
- + appliesTo: candidate => candidate.name === 'beta',
565
- + hidden: session => session !== undefined && session.actor === undefined,
566
- + })
567
- +
568
- + expect(await h.ctx.skills.get('beta', { session: sessionWith({}) })).toBeDefined()
569
- + expect(await h.ctx.skills.get('beta', { session: sessionWith() })).toBeUndefined()
570
- + // The same candidate is still loadable outside a Session, because this rule declines to narrow
571
- + // that case: hiding is about a Session's view, not the catalog.
572
- + expect(await h.ctx.skills.get('beta')).toBeDefined()
573
- + })
574
- +
575
- + it('lets a rule treat a Session-less lookup as hidden when it chooses to', async () => {
576
- + const h = await setup()
577
- + h.ctx.skills.addVisibilityFilter({
578
- + appliesTo: () => true,
579
- + hidden: session => session?.actor === undefined,
580
- + })
581
- + // `undefined` reaches the rule like any other value; the base does not add a policy of its own.
582
- + expect(await h.names()).toEqual([])
583
- + })
584
- +
585
- + it('leaves unclaimed and explicitly unhidden candidates alone', async () => {
586
- + const h = await setup()
587
- + h.ctx.skills.addVisibilityFilter({ appliesTo: () => false, hidden: () => true })
588
- + h.ctx.skills.addVisibilityFilter({ appliesTo: candidate => candidate.name === 'beta', hidden: () => false })
589
- + expect(await h.names({ session: sessionWith() })).toEqual(['alpha', 'beta'])
590
- + })
591
- +
592
- + it('restores the catalog when the registration is disposed', async () => {
593
- + const h = await setup()
594
- + const dispose = h.ctx.skills.addVisibilityFilter({
595
- + appliesTo: candidate => candidate.name === 'beta',
596
- + hidden: () => true,
597
- + })
598
- + expect(await h.names({ session: sessionWith() })).toEqual(['alpha'])
599
- +
600
- + dispose()
601
- + expect(await h.names({ session: sessionWith() })).toEqual(['alpha', 'beta'])
602
- + })
603
- +
604
- + it('hides the union of several plugins rules', async () => {
605
- + const h = await setup()
606
- + h.ctx.skills.addVisibilityFilter({ appliesTo: candidate => candidate.name === 'alpha', hidden: () => true })
607
- + h.ctx.skills.addVisibilityFilter({ appliesTo: candidate => candidate.name === 'beta', hidden: () => true })
608
- + expect(await h.names({ session: sessionWith() })).toEqual([])
609
- + })
610
- +
611
- + it('treats a throwing rule as not hiding', async () => {
612
- + const h = await setup()
613
- + h.ctx.skills.addVisibilityFilter({
614
- + appliesTo: candidate => candidate.name === 'alpha',
615
- + hidden: () => { throw new Error('broken connector') },
616
- + })
617
- + h.ctx.skills.addVisibilityFilter({
618
- + appliesTo: () => { throw new Error('broken matcher') },
619
- + hidden: () => true,
620
- + })
621
- + expect(await h.names({ session: sessionWith() })).toEqual(['alpha', 'beta'])
622
- + })
623
- +})
624
-
625
- diff --git a/packages/skill/tool-skill/src/index.ts b/packages/skill/tool-skill/src/index.ts
626
- index f08fb820..8dbbafe9 100644
627
- --- a/packages/skill/tool-skill/src/index.ts
628
- +++ b/packages/skill/tool-skill/src/index.ts
629
- @@ -134,7 +134,7 @@ export function apply(ctx: Context, config: Config = {}): void {
630
- // The agent is its own scope key, so the lookup resolves the layered
631
- // registry exactly as this agent's composition sees it.
632
- const cwd = exec.agent === undefined ? undefined : await ctx.workingDirectory.ensure(exec.agent, exec.signal)
633
- - const lookup = { cwd, signal: exec.signal, scope: exec.agent }
634
- + const lookup = { cwd, signal: exec.signal, scope: exec.agent, session: exec.agent?.session }
635
- const summary = (await ctx.skills.list(lookup)).find(skill => skill.name === args.name)
636
- if (!summary) {
637
- throw new Error(`skill "${args.name}" is unknown or no longer available`)
638
- @@ -223,7 +223,7 @@ export function apply(ctx: Context, config: Config = {}): void {
639
- signal.throwIfAborted()
640
- const toolVisible = ctx.tools.get(skillTool.name, agent) === skillTool
641
- const snapshot = toolVisible
642
- - ? await ctx.skills.snapshot({ cwd: await ctx.workingDirectory.ensure(agent, signal), signal, scope: agent })
643
- + ? await ctx.skills.snapshot({ cwd: await ctx.workingDirectory.ensure(agent, signal), signal, scope: agent, session: agent.session })
644
- : { skills: [], complete: true }
645
- signal.throwIfAborted()
646
- const skills = snapshot.skills.filter(isModelInvocable)