@linxin666/dsh-liangshen 0.1.13 → 0.1.15

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,10 +1,15 @@
1
- # The `liangshen` (梁神模式) agent preset: full Standard capabilities with a
2
- # two-phase input bootstrap — the first model request sees only the platform
3
- # shell plus `read`, only the one-line persona prompt section, no runtime
4
- # contexts, and no injected pre-step messages (Minimal-aligned trajectory
5
- # anchor); the full catalog, every prompt section, and the ordinary
6
- # runtime/workspace/skill injections return after the first durable tool call.
7
- # Adapted from the builtin `standard` preset.
1
+ # The `liangshen` (梁神模式) agent preset: phase 1 exposes the builtin Minimal
2
+ # preset's exact two tools (persistent `bash` plus `str_replace_editor`) and
3
+ # the same one-line persona, with no runtime contexts and no injected pre-step
4
+ # messages, anchoring the Minimal trajectory; after a stabilized anchor the
5
+ # wire switches to Code Mode (PTC) and the ordinary injections open. The
6
+ # phase-1 surface matches the official "exact RL prompt and schemas" snapshot
7
+ # byte-for-byte on the model-visible wire shape, at the cost of keeping the
8
+ # persistent shell for the whole session. Unlike the builtin Minimal preset,
9
+ # the phase-1 editor inherits the host file sandbox instead of mounting a bare
10
+ # local filesystem (see the filesystem section below).
11
+ #
12
+ # Adapted from the builtin `minimal` and `standard` presets.
8
13
  #
9
14
  # This file is an AGENT-PLANE composition. The roster mounts it ONCE under a
10
15
  # standing scope; every session naming it joins by scope parentage, so the
@@ -26,33 +31,33 @@
26
31
  # ── identity ────────────────────────────────────────────────────────────────
27
32
 
28
33
  # Phase 1 shows only this one-line persona: `tool-bootstrap` filters the
29
- # assembled sections down to `persona` during phase 1 and restores every
30
- # section after promotion, so plan-mode's `plan:policy` takes effect instead
31
- # of being permanently shadowed by a `complete` persona.
34
+ # assembled sections down to the persona section (`deployment:persona`, the
35
+ # name `dsh-persona` registers under, plus the legacy `persona` name) during
36
+ # phase 1 and restores every section after promotion, appending the session's
37
+ # working directory to the persona — so the agent knows its workspace and
38
+ # plan-mode's `plan:policy` takes effect instead of being permanently
39
+ # shadowed by a `complete` persona.
32
40
  - id: persona
33
41
  name: '@deepseek-ai/dsh-persona'
34
42
  config:
35
43
  text: You are a helpful software engineer assistant.
36
44
 
37
- # Two-phase input bootstrap. Before the session's first durable tool/call event
38
- # the first model request sees exactly one platform shell plus `read`, only the
39
- # `persona` prompt section, no runtime contexts, and only direct user messages;
40
- # after that event every Standard tool below, all assembled prompt sections
41
- # (including plan-mode's `plan:policy`), and the ordinary
42
- # runtime/workspace/skill injections become visible. `anchorGate` holds the
43
- # promotion open until the first reasoning block is minimal-like (with a
44
- # four-step fallback), so a `Let me` first block does not immediately earn the
45
- # full catalog. `promoteAfterFirstResponse` avoids a permanent two-tool
46
- # session when the first response calls no tool, and releases an anchor-gated
47
- # session once its first turn ends (`turn/end`). After promotion the catalog
48
- # is presented as Code Mode (PTC): a single `run_code` tool on the wire,
49
- # switched at the step boundary. Workspace instructions and the skill catalog
50
- # are additionally deferred for one step after promotion (`deferredSources`).
45
+ # Two-phase input bootstrap with the exact Minimal phase-1 tools. Before the
46
+ # first durable tool/call event the model sees only persistent `bash` plus
47
+ # `str_replace_editor`, only the `persona` prompt section, no runtime
48
+ # contexts, and only direct user messages. `anchorGate` holds the promotion
49
+ # open until the first reasoning block is minimal-like (four-step fallback);
50
+ # `promoteAfterFirstResponse` avoids a permanent two-tool session after a
51
+ # tool-less first response, and releases an anchor-gated session once its
52
+ # first turn ends (`turn/end`). After promotion the catalog is presented as
53
+ # Code Mode (PTC): a single `run_code` tool on the wire, switched at the step
54
+ # boundary; workspace instructions and the skill catalog are deferred one
55
+ # step after promotion.
51
56
  - id: tool-bootstrap
52
57
  name: ./tool-bootstrap.mjs
53
58
  config:
54
- shellTools: [bash, pwsh]
55
- commonTools: [read]
59
+ shellTools: [bash]
60
+ commonTools: [str_replace_editor]
56
61
  messageSources: [user]
57
62
  anchorGate: true
58
63
  maxBootstrapSteps: 4
@@ -68,24 +73,55 @@
68
73
  config:
69
74
  maxBytes: 65536
70
75
 
71
- # ── shell ───────────────────────────────────────────────────────────────────
76
+ # ── minimal phase-1 shell ───────────────────────────────────────────────────
72
77
 
73
- # `shell-env` stays in the HOST composition: `apps/cli/src/web.ts` injects it to
74
- # publish `DSH_WEB_URL`/`DSH_WEB_MODE`, and a host row that injects a service is
75
- # the criterion for host-plane ownership — injection resolves before any session
76
- # exists, so there is no agent to key by. Behind a preset realm those variables
77
- # never reached the model's shell at all. Both shell tools consume the host
78
- # registry from here; their executors (`bash-sandbox`/`pwsh-sandbox`) are
79
- # host-plane too.
80
- - id: tool-bash
81
- name: '@deepseek-ai/dsh-tool-bash'
82
- disabled: !!js process.platform === 'win32'
78
+ # The PTY registry is an agent-owned service, so it lives in an entry-local
79
+ # realm. The backend still consumes the host sandbox policy and subprocess
80
+ # implementation, while the tool registers into this agent's scoped catalog.
81
+ # This persistent `bash` replaces the Standard ephemeral shell for the WHOLE
82
+ # session (both tools register the name `bash`), which is the exact-Minimal
83
+ # tradeoff this experimental preset evaluates.
84
+ - id: persistent-shell
85
+ name: cordis:group
86
+ group: true
87
+ isolate:
88
+ terminals: true
89
+ config:
90
+ - id: pty
91
+ name: '@deepseek-ai/dsh-terminal'
83
92
 
84
- - id: tool-pwsh
85
- name: '@deepseek-ai/dsh-tool-pwsh'
86
- disabled: !!js process.platform !== 'win32'
93
+ - id: terminal-bash
94
+ name: '@deepseek-ai/dsh-terminal-bash'
95
+ config:
96
+ timeoutMs: 300000
97
+
98
+ - id: persistent-bash
99
+ name: '@deepseek-ai/dsh-tool-bash-persistent'
100
+ config:
101
+ timeoutMs: 300000
102
+ description: |-
103
+ Run commands in a bash shell
104
+ * When invoking this tool, the contents of the "command" parameter does NOT need to be XML-escaped.
105
+ * You don't have access to the internet via this tool.
106
+ * You do have access to a mirror of common linux and python packages via apt and pip.
107
+ * State is persistent across command calls and discussions with the user.
108
+ * To inspect a particular line range of a file, e.g. lines 10-25, try 'sed -n 10,25p /path/to/the/file'.
109
+ * Please avoid commands that may produce a very large amount of output.
110
+ * Please run long lived commands in the background, e.g. 'sleep 10 &' or start a server in the background.
111
+
112
+ # ── minimal phase-1 filesystem ──────────────────────────────────────────────
113
+
114
+ # Phase-1 editor as a direct top-level row: it reuses the host's sandboxed
115
+ # `ctx.fs`, not a bare local filesystem. No `dsh-fs-local` realm is mounted, so
116
+ # the phase-1 editor inherits the host file sandbox exactly like every
117
+ # Standard file tool, and the model-facing schema stays the builtin Minimal
118
+ # `str_replace_editor`.
119
+ - id: str-replace-editor
120
+ name: '@deepseek-ai/dsh-tool-str-replace-editor'
121
+ config:
122
+ maxOutputChars: 16000
87
123
 
88
- # ── filesystem ──────────────────────────────────────────────────────────────
124
+ # ── standard filesystem tools ───────────────────────────────────────────────
89
125
 
90
126
  # Both register into the host `tools` registry and provide nothing, so
91
127
  # they need no realm. The `fs` service and its policy stay in the host.
@@ -100,12 +136,10 @@
100
136
  # ── background jobs ────────────────────────────────────────────────────────
101
137
 
102
138
  # Only the model-facing controls. The task REGISTRY stays on the host plane:
103
- # its producers sit outside any realm this file could put it in — `tool-bash`
104
- # above resolves it with `ctx.get`, and an entry-local realm here is invisible
105
- # to every sibling row, so `run_in_background` would answer "background jobs
106
- # unavailable" while these controls sat in the catalog. The registry is keyed by
107
- # owning agent anyway, so one host instance serves every session. What a preset
108
- # chooses is whether its agent can collect and stop background work at all.
139
+ # its producers sit outside any realm this file could put it in, and the
140
+ # registry is keyed by owning agent anyway. With the persistent shell, long
141
+ # commands run through `&`; these controls still expose whatever the host
142
+ # registry tracks.
109
143
  - id: tool-jobs
110
144
  name: '@deepseek-ai/dsh-tool-jobs'
111
145
 
@@ -1,3 +1,3 @@
1
1
  name: 梁神模式
2
- description: 首轮极简锚定:仅平台 shell 与 read,无运行时上下文与指令注入;首次工具调用后恢复完整 Standard 能力。
2
+ description: V4 Pro 专属,小南梁进化,梁神,启动!
3
3
  order: 4
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * Phase 1 (no persisted `tool/call` yet):
6
6
  * - tool catalog: one platform shell plus `commonTools`
7
- * - prompt sections: only the `persona` section (all other sections,
7
+ * - prompt sections: only the persona section (all other sections,
8
8
  * including plan-mode's `plan:policy`, return after promotion)
9
9
  * - runtime contexts: emptied (no sandbox/approval snapshot)
10
10
  * - pre-step messages: only explicit user messages pass
@@ -32,6 +32,26 @@ export const name = 'anchored-tool-bootstrap'
32
32
  /** Prompt assembly and the tool registry must exist before this filter runs. */
33
33
  export const inject = ['systemPrompt', 'tools']
34
34
 
35
+ /**
36
+ * Prompt section names that carry the preset persona. The `dsh-persona` row
37
+ * registers the preset persona as `deployment:persona` (the PERSONA_SECTION
38
+ * name of `@deepseek-ai/dsh-system-prompt`), shadowing the deployment
39
+ * default for the preset scope; `persona` is the legacy name kept for older
40
+ * harnesses that registered the persona section without the prefix.
41
+ */
42
+ const PERSONA_SECTION_NAMES = new Set(['deployment:persona', 'persona'])
43
+
44
+ /**
45
+ * Workspace line a promoted persona gains. Phase 1 keeps the exact one-line
46
+ * persona (the Minimal anchor); after promotion the model must also know the
47
+ * session's selected workspace, which the Standard persona carries through
48
+ * the `{{cwd}}` prompt variable. The literal cwd is read from the session
49
+ * header at assembly time instead, so the line stays correct after a
50
+ * workspace switch and a session without a selected workspace keeps the bare
51
+ * one-liner rather than failing prompt interpolation.
52
+ */
53
+ const WORKSPACE_LINE_PREFIX = '\n\nYour working directory is '
54
+
35
55
  /** Message-source kinds the model may see during phase 1. */
36
56
  const DEFAULT_MESSAGE_SOURCES = ['user']
37
57
 
@@ -200,6 +220,29 @@ function refresh(agent, policy) {
200
220
  return state
201
221
  }
202
222
 
223
+ /**
224
+ * Append the session's working directory to the persona section of a promoted
225
+ * assembly. Returns the assembly unchanged when there is no persona section,
226
+ * no selected workspace, or the exact line is already present.
227
+ */
228
+ function withWorkspaceLine(assembly, agent) {
229
+ const cwd = agent?.session?.header?.cwd
230
+ if (typeof cwd !== 'string' || cwd.length === 0) return assembly
231
+ if (!Array.isArray(assembly.sections)) return assembly
232
+ const line = `${WORKSPACE_LINE_PREFIX}${cwd}.`
233
+ const persona = assembly.sections.find(section =>
234
+ PERSONA_SECTION_NAMES.has(section?.name)
235
+ && typeof section?.text === 'string'
236
+ && !section.text.includes(line))
237
+ if (persona === undefined) return assembly
238
+ return {
239
+ ...assembly,
240
+ sections: assembly.sections.map(section => section === persona
241
+ ? { ...section, text: `${persona.text}${line}` }
242
+ : section),
243
+ }
244
+ }
245
+
203
246
  /** Register the per-session bootstrap quarantine and promotion policy. */
204
247
  export function apply(ctx, config) {
205
248
  const commonTools = stringList(config.commonTools, 'commonTools')
@@ -245,7 +288,7 @@ export function apply(ctx, config) {
245
288
  const agent = context.agent
246
289
  if (agent === undefined) return assembled
247
290
  const state = refresh(agent, policy)
248
- if (state.promoted) return assembled
291
+ if (state.promoted) return withWorkspaceLine(assembled, agent)
249
292
 
250
293
  const available = new Set(assembled.tools.map(tool => tool.name))
251
294
  const selectedShells = shellTools.filter(toolName => available.has(toolName))
@@ -263,7 +306,7 @@ export function apply(ctx, config) {
263
306
  tools: assembled.tools.filter(tool => bootstrap.has(tool.name)),
264
307
  contexts: [],
265
308
  ...(Array.isArray(assembled.sections)
266
- ? { sections: assembled.sections.filter(section => section?.name === 'persona') }
309
+ ? { sections: assembled.sections.filter(section => PERSONA_SECTION_NAMES.has(section?.name)) }
267
310
  : {}),
268
311
  }
269
312
  }, { prepend: true })
@@ -0,0 +1,36 @@
1
+ // Generated by scripts/sync-shared.mjs from shared/host/dsh-home.ts. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs".
2
+ /**
3
+ * DSH_HOME resolution shared by the plugin family's Host halves: the
4
+ * environment override wins, the platform home fallback follows. Mirrors
5
+ * what dsh-pet and dsh-liangshen each used to implement locally.
6
+ */
7
+
8
+ import { homedir } from 'node:os'
9
+ import { isAbsolute, join } from 'node:path'
10
+
11
+ /** Expand a leading ~ (or ~user) in a path, platform-style. */
12
+ export function expandHome(path: string, home: string = homedir()): string {
13
+ if (path === '~') return home
14
+ if (path.startsWith('~/') || path.startsWith('~\\')) return join(home, path.slice(2))
15
+ return path
16
+ }
17
+
18
+ /**
19
+ * Resolve the DSH home directory.
20
+ * @param env - process environment to read DSH_HOME from.
21
+ * @param home - platform home directory fallback (test seam).
22
+ * @returns the absolute DSH home path.
23
+ */
24
+ export function resolveDshHome(env: NodeJS.ProcessEnv = process.env, home: string = homedir()): string {
25
+ const raw = env.DSH_HOME
26
+ if (raw !== undefined && raw.trim() !== '') {
27
+ const expanded = expandHome(raw.trim(), home)
28
+ return isAbsolute(expanded) ? expanded : join(process.cwd(), expanded)
29
+ }
30
+ return join(home, '.dsh')
31
+ }
32
+
33
+ /** Resolve the DSH home directory from the live environment. */
34
+ export function dshHome(): string {
35
+ return resolveDshHome()
36
+ }
package/src/index.test.ts CHANGED
@@ -58,4 +58,10 @@ describe('dshHome', () => {
58
58
  expect(dshHome()).toBe('/srv/dsh-home')
59
59
  })
60
60
  })
61
+
62
+ it('resolves a relative override against the process cwd (shared contract)', () => {
63
+ withEnv({ DSH_HOME: 'data/home' }, () => {
64
+ expect(dshHome()).toBe(join(process.cwd(), 'data', 'home'))
65
+ })
66
+ })
61
67
  })
package/src/index.ts CHANGED
@@ -8,19 +8,19 @@
8
8
  * half, no routes, no agent tools — the preset itself provides the tools.
9
9
  *
10
10
  * The preset is the "anchored-standard" idea shipped as a named mode: the
11
- * first model request sees only the platform shell plus `read` (Minimal
12
- * prompt condition), and the full Standard tool catalog opens after the
13
- * session's first durable tool call. Derived from
11
+ * first model request sees only the builtin Minimal preset's exact two tools
12
+ * (persistent `bash` plus `str_replace_editor`), and after the anchor the
13
+ * wire switches to Code Mode (PTC). Derived from
14
14
  * https://github.com/xiaobright/dsh-anchored-standard (MIT).
15
15
  */
16
16
 
17
17
  import { existsSync, mkdirSync } from 'node:fs'
18
- import { homedir } from 'node:os'
19
18
  import { join } from 'node:path'
20
19
  import { fileURLToPath } from 'node:url'
21
20
  import type { Context } from '@deepseek-ai/cordis'
22
21
  import type {} from '@deepseek-ai/dsh-system-prompt'
23
22
  import z from 'schemastery'
23
+ import { dshHome } from './dsh-home.ts'
24
24
  import { syncPresetTrees } from './sync.ts'
25
25
 
26
26
  /** Stable cordis plugin name. */
@@ -49,22 +49,13 @@ const DEFAULT_ANNOUNCE = true
49
49
  const SECTION_ORDER = 150
50
50
 
51
51
  /** Model-facing announcement: plugin presence, principle, and limits. */
52
- export const LIANGSHEN_GUIDANCE = '本机已安装 dsh-liangshen 插件(梁神模式 agent preset):新建会话的预设选择器中可选「梁神模式」与「梁神模式-精确实验」。原理:两阶段锚定——首轮模型请求仅暴露平台 shell 与 read(精确实验版为持久 bash 与 str_replace_editor),只保留一行 persona,清空运行时上下文并只放行用户的直接消息,锚定 Minimal 推理轨迹;晋升受首块锚定门控(首块包含 we 且无 let me,四步兜底),无工具首轮会在响应后自动晋升,晋升后 wire 切换为 Code Mode(PTC,单一 run_code),workspace 指令与 skill 目录在晋升后再延迟一步注入。preset 文件由插件维护于 ~/.dsh/.agent-presets,升级插件时自动更新;默认预设由用户自行选择。用户提到「梁神模式 / 锚定模式 / anchored standard」时即指本插件,请据此协作。'
53
-
54
- /** Expand a leading `~`, `~/` or `~\` to the current user's home directory. */
55
- function expandTilde(path: string): string {
56
- if (path === '~') return homedir()
57
- if (path.startsWith('~/') || path.startsWith('~\\')) return join(homedir(), path.slice(2))
58
- return path
59
- }
60
-
61
- /** Resolve the harness home (DSH_HOME overrides the conventional ~/.dsh). */
62
- export function dshHome(): string {
63
- const override = process.env.DSH_HOME
64
- if (override === undefined) return join(homedir(), '.dsh')
65
- const trimmed = override.trim()
66
- return trimmed === '' ? join(homedir(), '.dsh') : expandTilde(trimmed)
67
- }
52
+ export const LIANGSHEN_GUIDANCE = '本机已安装 dsh-liangshen 插件(梁神模式 agent preset):新建会话的预设选择器中可选「梁神模式」。原理:两阶段锚定——首轮模型请求仅暴露官方 Minimal 精确双工具(持久 bash 与 str_replace_editor,文件工具继承宿主沙箱),只保留一行 persona,清空运行时上下文并只放行用户的直接消息,锚定 Minimal 推理轨迹;晋升受首块锚定门控(首块包含 we 且无 let me,四步兜底),无工具首轮会在响应后自动晋升,晋升后 wire 切换为 Code Mode(PTC,单一 run_code)并在 persona 追加所选工作区路径,workspace 指令与 skill 目录在晋升后再延迟一步注入。preset 文件由插件维护于 ~/.dsh/.agent-presets,升级插件时自动更新;默认预设由用户自行选择。用户提到「梁神模式 / 锚定模式 / anchored standard」时即指本插件,请据此协作。'
53
+ // The harness-home resolution (DSH_HOME override with the platform-home
54
+ // fallback and ~ expansion) lives in the family-shared copy ./dsh-home.ts.
55
+ // Re-export it so the plugin surface stays stable while the implementation is
56
+ // shared across packages. A relative DSH_HOME resolves against the process CWD
57
+ // (absolute), which is the shared contract.
58
+ export { dshHome } from './dsh-home.ts'
68
59
 
69
60
  /** Absolute path of the bundled preset tree inside this package. */
70
61
  export function bundledPresetsRoot(): string {
@@ -87,13 +78,16 @@ export function apply(ctx: Context, config?: Config): void {
87
78
  const targetRoot = join(dshHome(), '.agent-presets')
88
79
  try {
89
80
  mkdirSync(targetRoot, { recursive: true })
90
- const result = syncPresetTrees(bundledPresetsRoot(), targetRoot)
81
+ const result = syncPresetTrees(bundledPresetsRoot(), targetRoot, ['liangshen-exact'])
91
82
  for (const { id, error } of result.failed) {
92
83
  ctx.logger?.warn?.(`dsh-liangshen: preset ${id} sync failed: ${error}`)
93
84
  }
94
85
  if (result.synced.length > 0) {
95
86
  ctx.logger?.info?.(`dsh-liangshen: presets synced into ${targetRoot}: ${result.synced.join(', ')}`)
96
87
  }
88
+ if (result.retired.length > 0) {
89
+ ctx.logger?.info?.(`dsh-liangshen: retired stale presets from ${targetRoot}: ${result.retired.join(', ')}`)
90
+ }
97
91
  } catch (error) {
98
92
  ctx.logger?.warn?.(`dsh-liangshen: preset sync failed: ${error instanceof Error ? error.message : String(error)}`)
99
93
  }
@@ -0,0 +1,64 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { validateAgentCordis } from './schema.ts'
3
+
4
+ const VALID = [
5
+ "- id: persona",
6
+ " name: '@deepseek-ai/dsh-persona'",
7
+ "- id: bootstrap",
8
+ " name: ./tool-bootstrap.mjs",
9
+ "- id: shell-group",
10
+ " name: cordis:group",
11
+ " group: true",
12
+ " isolate:",
13
+ " terminals: true",
14
+ " config:",
15
+ " - id: pty",
16
+ " name: '@deepseek-ai/dsh-terminal'",
17
+ ].join('\n')
18
+
19
+ describe('validateAgentCordis', () => {
20
+ it('accepts a well-formed preset document', () => {
21
+ expect(validateAgentCordis(VALID)).toEqual([])
22
+ })
23
+
24
+ it('rejects an empty document', () => {
25
+ expect(validateAgentCordis('')).not.toEqual([])
26
+ expect(validateAgentCordis('\n \n')).not.toEqual([])
27
+ })
28
+
29
+ it('rejects a document that is not a list of rows', () => {
30
+ expect(validateAgentCordis('rows: []\n')).not.toEqual([])
31
+ })
32
+
33
+ it('rejects a row without a name', () => {
34
+ const doc = "- id: persona\n group: true\n"
35
+ expect(validateAgentCordis(doc)).not.toEqual([])
36
+ })
37
+
38
+ it('rejects a row whose name starts with an unsupported prefix', () => {
39
+ const doc = "- id: bad\n name: 'plain-text'\n"
40
+ expect(validateAgentCordis(doc)).not.toEqual([])
41
+ })
42
+
43
+ it('rejects duplicate row ids', () => {
44
+ const doc = [
45
+ "- id: persona",
46
+ " name: '@deepseek-ai/dsh-persona'",
47
+ "- id: persona",
48
+ " name: '@deepseek-ai/dsh-tool-todo'",
49
+ ].join('\n')
50
+ const errors = validateAgentCordis(doc)
51
+ expect(errors.some(error => error.includes('duplicate row id'))).toBe(true)
52
+ })
53
+
54
+ it('rejects a group-true row that does not use cordis:group', () => {
55
+ const doc = "- id: shell-group\n name: '@deepseek-ai/dsh-persona'\n group: true\n"
56
+ expect(validateAgentCordis(doc)).not.toEqual([])
57
+ })
58
+
59
+ it('rejects a row with a blank id', () => {
60
+ const doc = "- id: \n"
61
+ const errors = validateAgentCordis(doc)
62
+ expect(errors.some(error => error.includes('empty row id'))).toBe(true)
63
+ })
64
+ })
package/src/schema.ts ADDED
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Structural validation for a bundled `agent.cordis.yml`.
3
+ *
4
+ * Deliberately dependency-free: it parses only the flat row metadata the sync
5
+ * and the dsh agent-presets loader rely on. Every top-level row is written as
6
+ * `- id: <id>` at column zero, with the `name`/`group`/`disabled` keys at two
7
+ * spaces of indentation. Nested `config:` and `isolate:` bodies are opaque to
8
+ * this validator — the dsh loader checks their semantics.
9
+ *
10
+ * Returns the list of problems found; an empty array means the document is
11
+ * structurally valid.
12
+ */
13
+
14
+ /** A top-level row opener: `- id: <id>` (id may be blank for diagnostics). */
15
+ const ROW_RE = /^-\s+id:\s*(.*)$/
16
+ /** Any top-level list item, for ids missing from a row opener. */
17
+ const ITEM_RE = /^-\s/
18
+ /** A two-space-indented flat metadata key: ` name: <value>`. */
19
+ const META_RE = /^ {2}([A-Za-z][A-Za-z0-9_-]*):\s*(.*)$/
20
+ /** The only `name` forms the dsh agent-presets loader mounts from a row. */
21
+ const NAME_PREFIX_RE = /^(\.\/|@|cordis:)/
22
+
23
+ /** Strip one pair of surrounding single or double quotes from a scalar. */
24
+ function unquote(value: string): string {
25
+ if (value.length >= 2) {
26
+ const first = value[0]
27
+ if ((first === "'" || first === '"') && value.endsWith(first)) {
28
+ return value.slice(1, -1)
29
+ }
30
+ }
31
+ return value
32
+ }
33
+
34
+ /**
35
+ * Validate the structural contract of an `agent.cordis.yml` document.
36
+ * @param text - the raw YAML document text.
37
+ * @returns a list of human-readable problems; empty means valid.
38
+ */
39
+ export function validateAgentCordis(text: string): string[] {
40
+ const errors: string[] = []
41
+ const normalized = text.replace(/\r\n/g, '\n')
42
+ if (normalized.trim() === '') {
43
+ return ['document is empty']
44
+ }
45
+
46
+ const seenIds = new Set<string>()
47
+ const current = { id: null as string | null, name: null as string | null, group: null as string | null }
48
+
49
+ const closeRow = (): void => {
50
+ if (current.id === null) return
51
+ if (current.name === null) {
52
+ errors.push(`row "${current.id}": missing "name" key`)
53
+ } else if (!NAME_PREFIX_RE.test(current.name)) {
54
+ errors.push(`row "${current.id}": name "${current.name}" must start with "./", "@" or "cordis:"`)
55
+ }
56
+ if (current.group === 'true' && current.name !== 'cordis:group') {
57
+ errors.push(`row "${current.id}": "group: true" requires name "cordis:group"`)
58
+ }
59
+ current.name = null
60
+ current.group = null
61
+ current.id = null
62
+ }
63
+
64
+ const lines = normalized.split('\n')
65
+ for (let index = 0; index < lines.length; index += 1) {
66
+ const lineNo = index + 1
67
+ const line = lines[index]
68
+ const trimmed = line.trim()
69
+ if (trimmed === '' || trimmed.startsWith('#')) continue
70
+
71
+ const row = ROW_RE.exec(line)
72
+ if (row !== null) {
73
+ closeRow()
74
+ const id = row[1].trim()
75
+ if (id === '') {
76
+ errors.push(`line ${lineNo}: empty row id`)
77
+ current.id = null
78
+ } else {
79
+ if (seenIds.has(id)) errors.push(`line ${lineNo}: duplicate row id "${id}"`)
80
+ seenIds.add(id)
81
+ current.id = id
82
+ }
83
+ current.name = null
84
+ current.group = null
85
+ continue
86
+ }
87
+
88
+ if (current.id === null) {
89
+ if (ITEM_RE.test(line)) {
90
+ errors.push(`line ${lineNo}: list item does not declare an "id:"`)
91
+ } else if (/^\S/.test(line)) {
92
+ errors.push(`line ${lineNo}: content outside a "- id:" row`)
93
+ }
94
+ continue
95
+ }
96
+
97
+ const meta = META_RE.exec(line)
98
+ if (meta !== null) {
99
+ const value = unquote(meta[2].trim())
100
+ if (meta[1] === 'name') current.name = value
101
+ else if (meta[1] === 'group') current.group = value
102
+ continue
103
+ }
104
+ // Anything indented at least two spaces is a nested body, opaque here.
105
+ if (/^ {2}/.test(line)) continue
106
+ errors.push(`line ${lineNo}: unexpected content in row "${current.id}"`)
107
+ }
108
+ closeRow()
109
+ return errors
110
+ }