dsh-cc-loader 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cc-loader",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "Shared parse layer for the dsh-cc ecosystem: parses Claude Code .claude/ (project + global) into a standalone .dsh intermediate representation (IR), classifying every component DIRECT/ADAPTED/UNSUPPORTED/BLOCKED and filtering unsupported ones out.",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
package/src/agents.js CHANGED
@@ -57,7 +57,7 @@ export async function discoverAgents(agentsDir, scope, rank, warnings = []) {
57
57
  }
58
58
  const raw = await readTextSafe(path)
59
59
  if (raw === undefined) continue
60
- const parsed = parseFrontmatter(raw)
60
+ const parsed = parseFrontmatter(raw, warnings, `agent "${path}"`)
61
61
  if (parsed === undefined) {
62
62
  warnings.push(`agent "${path}" skipped: no frontmatter`)
63
63
  continue
package/src/index.js CHANGED
@@ -42,3 +42,8 @@ export {
42
42
  // Session event-log readers. `Session.events` was removed in DSH 0.1.2-alpha.4
43
43
  // and is gone in 0.1.5; every plugin read of the log goes through these.
44
44
  export { sessionEvents, sessionEventAt, sessionLastEvent } from './session-compat.js'
45
+ // "A session has started" moved from `agent/session-start` (0.1.5) to
46
+ // `agent/created` + `source` (0.2.0). This boundary is the only place that knows.
47
+ export { onSessionStart } from './session-start-compat.js'
48
+ // What `source` an injected message must carry for the host's v4 admission gate.
49
+ export { injectedSource } from './message-source.js'
package/src/load.js CHANGED
@@ -66,8 +66,9 @@ export async function loadClaude(opts = {}) {
66
66
  }
67
67
 
68
68
  // Agents: merge project + global into one catalog (project wins on name clash).
69
+ // mergeAgentCatalog reports into the array it was handed, so there is nothing
70
+ // to merge back — repeating that push duplicated every agent warning.
69
71
  const catalog = await mergeAgentCatalog(agentRoots, warnings)
70
- warnings.push(...catalog.warnings)
71
72
 
72
73
  // Permissions: discover the three settings files and merge.
73
74
  const discovered = await discoverSettings(cwd, {
@@ -0,0 +1,46 @@
1
+ // message-source.js — the single place that knows what `source` a message this
2
+ // ecosystem injects must carry for the host to admit it.
3
+ //
4
+ // WHY THIS EXISTS
5
+ // ---------------
6
+ // DSH's session format v4 has an admission gate that validates the `source` of
7
+ // EVERY durable message slot before the event is adopted. Its whole rule
8
+ // (`lib/types/message-sources.js`) is:
9
+ //
10
+ // function source(message) {
11
+ // const value = message["source"]
12
+ // if (!isSessionFormatJsonObject(value)
13
+ // || typeof value["kind"] !== "string"
14
+ // || value["kind"].length === 0
15
+ // || value["kind"] === "plugin")
16
+ // throw new SessionFormatError("format v4 message requires a producer-owned source kind")
17
+ // }
18
+ //
19
+ // The line of policy above it settles what that means: "Native source admission
20
+ // PRESERVES UNKNOWN ATTRIBUTION and REFUSES RETIRED PLUGIN WRAPPERS." So any
21
+ // non-empty `kind` other than `plugin` is admitted and kept verbatim — you do
22
+ // not have to register your name with the host. The single refused form is the
23
+ // V3 plugin wrapper `{ kind: 'plugin', plugin: '<name>' }`, and refusing it
24
+ // fails the whole TURN, not just that message.
25
+ //
26
+ // `kind` doubles as the context-row label, so it should name the producer.
27
+ //
28
+ // WHAT WENT WRONG
29
+ // ---------------
30
+ // cc-hooks and cc-agents shipped the V3 wrapper, so the first time either one
31
+ // injected anything — SessionStart context, hook-injected context, the catalog
32
+ // reminder, a prompt/agent hook result — the turn died with
33
+ // "format v4 message requires a producer-owned source kind". The constant was
34
+ // duplicated across three files, which is why the shape can drift again; this
35
+ // module is the one place it is written down.
36
+
37
+ /**
38
+ * Build the `source` for a message this ecosystem injects.
39
+ *
40
+ * @param {string} kind - the producing plugin; also the context-row label.
41
+ * Must be non-empty and must not be `'plugin'`.
42
+ * @returns {{ kind: string }} an admitted source.
43
+ */
44
+ export function injectedSource(kind) {
45
+ return { kind }
46
+ }
package/src/patterns.js CHANGED
@@ -10,6 +10,9 @@
10
10
  // `./` or bare = relative to cwd.
11
11
  // - Domain (WebFetch): `*` matches text between dots (a leading `*.` spans
12
12
  // any subdomain depth; a bare `*` matches everything).
13
+ //
14
+ // `[...]` character classes belong to the PATH dialect alone: CC's command and
15
+ // domain patterns have no class syntax, so `[` is a literal character there.
13
16
 
14
17
  /** Escape a literal string for use inside a RegExp. */
15
18
  export function escapeRegExp(s) {
@@ -35,9 +38,10 @@ export function globToRegexBody(pattern, { segment = '/' } = {}) {
35
38
  } else if (ch === '?') {
36
39
  out += seg === null ? '.' : `[^${seg}]`
37
40
  i++
38
- } else if (ch === '[') {
41
+ } else if (ch === '[' && seg === '/') {
39
42
  const close = pattern.indexOf(']', i + 1)
40
- if (close > 0) { out += pattern.slice(i, close + 1); i = close + 1 }
43
+ const cls = close > 0 ? pattern.slice(i, close + 1) : ''
44
+ if (cls !== '' && isUsableCharClass(cls)) { out += cls; i = close + 1 }
41
45
  else { out += '\\['; i++ }
42
46
  } else {
43
47
  out += escapeRegExp(ch)
@@ -47,6 +51,20 @@ export function globToRegexBody(pattern, { segment = '/' } = {}) {
47
51
  return out
48
52
  }
49
53
 
54
+ /**
55
+ * Whether a glob `[...]` slice is simultaneously a VALID regex character class.
56
+ *
57
+ * Gitignore classes and JS regex classes mostly agree, but a reversed range
58
+ * such as `[11-04-54]` (read as `1-0`) is tolerated by gitignore and rejected
59
+ * by `new RegExp`. Class compilation happens on every tool call, so letting one
60
+ * such class throw would take down the whole permission gate; an unusable class
61
+ * degrades to a literal `[` instead.
62
+ * @param {string} cls - the slice from `[` through `]` inclusive.
63
+ */
64
+ function isUsableCharClass(cls) {
65
+ try { new RegExp(cls); return true } catch { return false }
66
+ }
67
+
50
68
  /**
51
69
  * Compile a Bash/PowerShell command pattern.
52
70
  *
package/src/plugin.js CHANGED
@@ -445,7 +445,7 @@ async function isFile(path) {
445
445
  async function discoverCommandFile(filePath, source, rank, warnings = []) {
446
446
  const raw = await readTextSafe(filePath)
447
447
  if (raw === undefined) return undefined
448
- const parsed = parseFrontmatter(raw)
448
+ const parsed = parseFrontmatter(raw, warnings, `command "${filePath}"`)
449
449
  const stem = filePath.split(/[\\/]/).pop().replace(/\.md$/, '')
450
450
  if (!isSkillName(stem)) {
451
451
  warnings.push(`command "${filePath}" skipped: name not kebab-case`)
@@ -478,7 +478,7 @@ async function discoverCommandFile(filePath, source, rank, warnings = []) {
478
478
  async function discoverAgentFile(filePath, scope, rank, warnings = []) {
479
479
  const raw = await readTextSafe(filePath)
480
480
  if (raw === undefined) return undefined
481
- const parsed = parseFrontmatter(raw)
481
+ const parsed = parseFrontmatter(raw, warnings, `agent "${filePath}"`)
482
482
  if (parsed === undefined) {
483
483
  warnings.push(`agent "${filePath}" skipped: no frontmatter`)
484
484
  return undefined
@@ -0,0 +1,72 @@
1
+ // session-start-compat.js — the single compatibility boundary for the
2
+ // "a session has started" extension point.
3
+ //
4
+ // WHY THIS EXISTS
5
+ // ---------------
6
+ // DSH 0.2.0 moved this extension point and enriched its payload:
7
+ //
8
+ // 0.1.5-rc.2 agent/session-start { agent, source }
9
+ // 0.2.0-rc.2 agent/created { agent, source, signal? }
10
+ //
11
+ // `agent/session-start` is simply GONE in 0.2.0 — a listener on that name is
12
+ // never called, with no error at any point, so a plugin loads, passes the
13
+ // install gate, and silently loses the feature. `agent/created` does exist on
14
+ // 0.1.5, but there the payload is `{ agent }` alone: no `source`. The two names
15
+ // are therefore NOT aliases, and a plain rename trades one silent break for
16
+ // another (the SessionStart hook payload would lose its `source`).
17
+ //
18
+ // The discriminator is `source`: 0.2.0's `agent/created` always carries one (the
19
+ // registry announces as `announce(agent, source, signal)`), 0.1.5's never does,
20
+ // and 0.1.5's `agent/session-start` always does. Listening on both and acting
21
+ // only on a payload that carries `source` fires the handler exactly once on
22
+ // either generation, with no bookkeeping: the host calls its publication entry
23
+ // once per agent (`publish(source)`), and 0.2.0's registry rejects a second
24
+ // announce for the same entry.
25
+ //
26
+ // The official `@deepseek-ai/dsh-hooks-claude-code@0.2.0-rc.2` bridge makes the
27
+ // same move, dropping its `agent/session-start` listener for `agent/created`.
28
+ //
29
+ // SECOND HAZARD: 0.2.0's `agent/created` is a SERIAL event — its listeners are
30
+ // awaited, and a listener rejection vetoes session publication. 0.1.5's was
31
+ // synchronous and fire-and-forget. Session-start work here is slow (filesystem
32
+ // discovery, spawned hook processes), so this boundary deliberately does NOT
33
+ // return the handler's promise and never lets a throw escape: a plugin must not
34
+ // be able to stall or veto the host's session publication.
35
+
36
+ /**
37
+ * Subscribe to "a session has started", on either host generation.
38
+ *
39
+ * The handler runs at most once per agent with `{ agent, source, signal }`.
40
+ * `source` is one of `'startup' | 'resume' | 'clear' | 'compact'` and is
41
+ * present on both generations this boundary supports.
42
+ *
43
+ * The handler runs detached and its result is ignored — neither a throw nor a
44
+ * rejection reaches the host (see the header). A failure is logged instead.
45
+ *
46
+ * @param {{ on: Function, logger?: any }} ctx - the plugin context.
47
+ * @param {(payload: { agent: any, source: string, signal?: AbortSignal }) => unknown} handler
48
+ */
49
+ export function onSessionStart(ctx, handler) {
50
+ const invoke = (payload) => {
51
+ try {
52
+ const result = handler(payload)
53
+ if (result !== null && typeof result === 'object' && typeof result.then === 'function') {
54
+ result.then(undefined, (error) => warn(ctx, error))
55
+ }
56
+ } catch (error) {
57
+ warn(ctx, error)
58
+ }
59
+ }
60
+ ctx.on('agent/session-start', invoke)
61
+ ctx.on('agent/created', (payload) => {
62
+ // 0.1.5's `agent/created` is registration-only and carries no `source`;
63
+ // the session-start event that does carry one follows it immediately.
64
+ // Acting here as well would run the handler twice.
65
+ if (payload === null || typeof payload !== 'object' || payload.source === undefined) return
66
+ invoke(payload)
67
+ })
68
+ }
69
+
70
+ function warn(ctx, error) {
71
+ ctx.logger?.warn?.(`dsh-cc-loader: session-start listener failed: ${String(error)}`)
72
+ }
package/src/skills.js CHANGED
@@ -81,10 +81,11 @@ export async function readTextSafe(path) {
81
81
  /**
82
82
  * Collect skills + commands from one `.claude` dir into `out` (project or
83
83
  * global). Each entry carries its IR status; unsupported entries are filtered.
84
+ * @param {string[]} [warnings] - collector, shared with the callers that have
85
+ * their own warnings to report (load.js). Omit to get a fresh array back.
84
86
  * @returns {Promise<{skills: object[], commands: object[], warnings: string[]}>}
85
87
  */
86
- export async function collectClaudeDir(claudeDir, source, rank) {
87
- const warnings = []
88
+ export async function collectClaudeDir(claudeDir, source, rank, warnings = []) {
88
89
  const skills = await discoverSkills(join(claudeDir, 'skills'), source, rank, warnings)
89
90
  const commands = await discoverCommands(join(claudeDir, 'commands'), source, rank, warnings)
90
91
  return { skills, commands, warnings }
@@ -156,7 +157,7 @@ export async function discoverCommands(rootDir, source, rank, warnings = []) {
156
157
  }
157
158
  const raw = await readTextSafe(path)
158
159
  if (raw === undefined) continue
159
- const parsed = parseFrontmatter(raw)
160
+ const parsed = parseFrontmatter(raw, warnings, `command "${entry.name}"`)
160
161
  const description = parsed === undefined ? stem : (stringField(parsed.data, 'description') ?? stem)
161
162
  // Command tool-scope fields (CC kebab-case, same shape as skills).
162
163
  const allowedTools = parsed === undefined ? [] : stringList(parsed.data, 'allowed-tools')
@@ -185,7 +186,7 @@ export async function discoverCommands(rootDir, source, rank, warnings = []) {
185
186
  async function parseSkillCandidateFile(path, source, rank, flatName, warnings = []) {
186
187
  const raw = await readTextSafe(path)
187
188
  if (raw === undefined) return undefined
188
- const parsed = parseFrontmatter(raw)
189
+ const parsed = parseFrontmatter(raw, warnings, `skill "${path}"`)
189
190
  if (parsed === undefined) {
190
191
  warnings.push(`skill "${path}" skipped: no frontmatter`)
191
192
  return undefined
@@ -235,20 +236,83 @@ async function parseSkillCandidateFile(path, source, rank, flatName, warnings =
235
236
 
236
237
  // ─── frontmatter helpers ─────────────────────────────────────────────────────
237
238
 
238
- export function parseFrontmatter(raw) {
239
+ /**
240
+ * Read the `---`-delimited block at the top of a `.claude` markdown file.
241
+ *
242
+ * Claude Code tolerates frontmatter that strict YAML rejects, so dropping a
243
+ * file on a parse error loses assets CC reads happily. The recurring shape is
244
+ * an unquoted `description` carrying a second `: ` — community agent files
245
+ * produce it by putting `Context: …` or `user: '…'` inside `<example>` blocks.
246
+ * A failed strict parse therefore falls back to flat `key: value` lines, and
247
+ * says so through `warnings` rather than degrading in silence.
248
+ *
249
+ * @param {string} raw - whole file.
250
+ * @param {string[]} [warnings] - collector for the lenient-parse notice.
251
+ * @param {string} [label] - what to call the file in that notice. Callers own
252
+ * the path, so they supply it (`agent "/…/x.md"`).
253
+ * @returns {{ data: object, body: string } | undefined}
254
+ */
255
+ export function parseFrontmatter(raw, warnings, label) {
239
256
  const firstLineEnd = raw.indexOf('\n')
240
257
  if (firstLineEnd < 0) return undefined
241
258
  if (raw.slice(0, firstLineEnd).replace(/\r$/, '') !== '---') return undefined
242
259
  const start = firstLineEnd + 1
243
260
  const closing = findClosingFrontmatter(raw, start)
244
261
  if (closing === undefined) return undefined
262
+ const block = raw.slice(start, closing.start)
245
263
  let parsed
246
- try { parsed = parse(raw.slice(start, closing.start)) }
247
- catch { return undefined }
264
+ let reason
265
+ try {
266
+ parsed = parse(block)
267
+ } catch (error) {
268
+ parsed = parseLenient(block)
269
+ if (parsed === undefined) return undefined
270
+ reason = firstLineOf(String(error?.message ?? error))
271
+ }
248
272
  if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return undefined
273
+ if (reason !== undefined && warnings !== undefined) {
274
+ warnings.push(`${label ?? 'frontmatter'} has frontmatter strict YAML rejects (${reason}) — read as flat key: value; only top-level fields survive`)
275
+ }
249
276
  return { data: parsed, body: raw.slice(closing.bodyStart) }
250
277
  }
251
278
 
279
+ // Fields Claude Code documents as comma-separated lists. Strict YAML turns them
280
+ // into real arrays on its own, so this set matters only on the lenient path —
281
+ // without it `tools: Read, Bash` arrives as one bogus entry named "Read, Bash".
282
+ const COMMA_LIST_FIELDS = new Set([
283
+ 'tools', 'disallowedTools', 'skills', 'allowed-tools', 'disallowed-tools',
284
+ ])
285
+
286
+ /**
287
+ * Flat `key: value` reader for a frontmatter block strict YAML rejected. Every
288
+ * value stays a string except the documented comma lists above — coercing
289
+ * numbers would turn `description: 2024` into a number and lose the field. Only
290
+ * top-level unindented lines are read, so anything needing nesting or
291
+ * multi-line syntax is lost; this is a last resort, not a general YAML parser.
292
+ */
293
+ function parseLenient(block) {
294
+ const data = {}
295
+ let found = false
296
+ for (const line of block.split('\n')) {
297
+ const m = /^([A-Za-z][\w-]*):[ \t]?(.*)$/.exec(line.replace(/\r$/, ''))
298
+ if (m === null) continue
299
+ const value = m[2].trim()
300
+ if (value.length === 0) continue
301
+ found = true
302
+ data[m[1]] = COMMA_LIST_FIELDS.has(m[1])
303
+ ? value.split(',').map((s) => s.trim()).filter((s) => s.length > 0)
304
+ : value
305
+ }
306
+ return found ? data : undefined
307
+ }
308
+
309
+ function firstLineOf(message) {
310
+ const end = message.indexOf('\n')
311
+ const line = (end < 0 ? message : message.slice(0, end)).trim()
312
+ // YAML's first line ends with the colon that introduces its code frame.
313
+ return line.endsWith(':') ? line.slice(0, -1).trim() : line
314
+ }
315
+
252
316
  function findClosingFrontmatter(raw, start) {
253
317
  let lineStart = start
254
318
  while (lineStart <= raw.length) {