@linxin666/dsh-liangshen 0.4.14 → 0.4.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.
package/lib/index.js CHANGED
@@ -400,11 +400,9 @@ function readPresetDefinition(id, dir) {
400
400
  /**
401
401
  * The overlay table: settings field to composition row and config key.
402
402
  *
403
- * `presentation` writes the `tool-catalog` row alone, because that row's
404
- * declaration IS the wire: the plugin hands the value to
405
- * `agent.ctx.tools.presentAs` and re-assembles, so the catalog text and the
406
- * declared presentation always travel together. The composition carries no
407
- * executor row to mount or unmount.
403
+ * `presentation` also selects the executor: the catalog declares the wire and
404
+ * the official PTC executor row carries it. Native mode disables that row so
405
+ * the assembled native roster remains the only surface.
408
406
  */
409
407
  function overrideTargets(overrides) {
410
408
  return [["tool-catalog", { ...overrides.presentation === void 0 ? {} : { presentation: overrides.presentation } }], ["minimal-prompt", { ...overrides.dispatcher === void 0 ? {} : { dispatcher: overrides.dispatcher } }]];
@@ -424,7 +422,12 @@ function overrideTargets(overrides) {
424
422
  function applyPresetOverrides(rows, overrides) {
425
423
  const table = overrideTargets(overrides);
426
424
  return rows.map((row) => {
427
- const target = table.find(([id]) => id === row.id);
425
+ const id = row.id;
426
+ if (id === "tool-executor-ptc" && overrides.presentation !== void 0) return {
427
+ ...row,
428
+ disabled: overrides.presentation !== "ptc"
429
+ };
430
+ const target = table.find(([targetId]) => targetId === id);
428
431
  if (target === void 0) return row;
429
432
  const [, patch] = target;
430
433
  if (Object.keys(patch).length === 0) return row;
@@ -56,7 +56,7 @@ export interface PluginCardContext {
56
56
  /** Service lookup; absent on a context double that only models the slots. */
57
57
  get?(name: string): unknown;
58
58
  /** Event subscription seat; absent on an event-less test double. */
59
- on?(event: string, listener: (...args: never[]) => void): unknown;
59
+ on?(event: never, listener: never): unknown;
60
60
  }
61
61
  /** Owner share of a family list-seat card (that seat supplies nothing). */
62
62
  export interface SettingsPluginItemOwnerProps {
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@linxin666/dsh-liangshen",
3
3
  "description": "LiangShen (梁神) agent preset plus its composer lever for the dsh web GUI. The host half declares the bundled preset to the harness's agent-preset registry at activation (declare = enabled), so the preset is selectable for new sessions without writing anything into the harness home; the preset keeps a minimal persona with standing working discipline while the harness's own user-role agent-instructions injection delivers the workspace instructions (the optional `instructionSource: system-prompt` mode lifts them into the prompt instead), and declares one tool presentation for the session's whole lifetime: `ptc` by default (the wire collapses to `run_code` and every other tool is reached through the generated SDK), with `native` as the explicit assembled-roster option. High-fan-out tool families (default `mcp__*`) stay paged out of the wire until the preset's own `tool_activate` tool loads their namespace (LRU cap three, state replayed from the durable session event stream), and the tool catalog — exactly the reachable tools plus paged-out namespace summaries — and a one-line working-context projection travel as durable user messages republished only on change. The browser half adds a slot-machine lever left of the model selector on the new-session screen to toggle the mode. Hot-pluggable via cordis.patch.yml + profile symlink, no dsh source changes.",
4
- "version": "0.4.14",
4
+ "version": "0.4.15",
5
5
  "icon": "icon.svg",
6
6
  "type": "module",
7
7
  "engines": {
8
- "node": "^22.19.0 || >=24.0.0"
8
+ "node": ">=24.9.0"
9
9
  },
10
10
  "main": "lib/index.js",
11
11
  "types": "lib/types/index.d.ts",
@@ -25,7 +25,7 @@
25
25
  },
26
26
  "dsh": {
27
27
  "engines": {
28
- "dsh": ">=0.2.1-rc.3"
28
+ "dsh": ">=0.2.2-rc.1"
29
29
  },
30
30
  "bundle": {
31
31
  "patch": "./cordis.patch.yml"
@@ -42,25 +42,25 @@
42
42
  }
43
43
  },
44
44
  "peerDependencies": {
45
- "@deepseek-ai/dsh": ">=0.2.1-rc.3"
45
+ "@deepseek-ai/dsh": ">=0.2.2-rc.1"
46
46
  },
47
47
  "dependencies": {
48
- "@deepseek-ai/schemastery": "^3.18.5"
48
+ "@deepseek-ai/schemastery": "^3.19.0"
49
49
  },
50
50
  "devDependencies": {
51
- "@deepseek-ai/cordis": "^4.0.5",
52
- "@deepseek-ai/dsh-agent-preset-registry": "^0.2.1-rc.3",
53
- "@deepseek-ai/dsh-api-remotes": "^0.2.1-rc.3",
54
- "@deepseek-ai/dsh-api-session-controller": "^0.2.1-rc.3",
55
- "@deepseek-ai/dsh-client-connection": "^0.2.1-rc.3",
56
- "@deepseek-ai/dsh-client-locale": "^0.2.1-rc.3",
57
- "@deepseek-ai/dsh-client-store": "^0.2.1-rc.3",
58
- "@deepseek-ai/dsh-client-ui-conversation": "^0.2.1-rc.3",
59
- "@deepseek-ai/dsh-client-ui-renderer": "^0.2.1-rc.3",
60
- "@deepseek-ai/dsh-client-ui-settings": "^0.2.1-rc.3",
61
- "@deepseek-ai/dsh-client-ui-slots": "^0.2.1-rc.3",
62
- "@deepseek-ai/dsh-settings": "^0.2.1-rc.3",
63
- "@deepseek-ai/dsh-system-prompt": "^0.2.1-rc.3",
51
+ "@deepseek-ai/cordis": "^4.1.0",
52
+ "@deepseek-ai/dsh-agent-preset-registry": "^0.2.2-rc.1",
53
+ "@deepseek-ai/dsh-api-remotes": "^0.2.2-rc.1",
54
+ "@deepseek-ai/dsh-api-session-controller": "^0.2.2-rc.1",
55
+ "@deepseek-ai/dsh-client-connection": "^0.2.2-rc.1",
56
+ "@deepseek-ai/dsh-client-locale": "^0.2.2-rc.1",
57
+ "@deepseek-ai/dsh-client-store": "^0.2.2-rc.1",
58
+ "@deepseek-ai/dsh-client-ui-conversation": "^0.2.2-rc.1",
59
+ "@deepseek-ai/dsh-client-ui-renderer": "^0.2.2-rc.1",
60
+ "@deepseek-ai/dsh-client-ui-settings": "^0.2.2-rc.1",
61
+ "@deepseek-ai/dsh-client-ui-slots": "^0.2.2-rc.1",
62
+ "@deepseek-ai/dsh-settings": "^0.2.2-rc.1",
63
+ "@deepseek-ai/dsh-system-prompt": "^0.2.2-rc.1",
64
64
  "@testing-library/react": "^16.1.0",
65
65
  "@types/node": "^22.20.0",
66
66
  "@types/react": "~18.3.1",
@@ -195,10 +195,9 @@
195
195
  # PTC runtime, a host that declines the declaration, or a wire that offers no
196
196
  # schema projection keeps the native surface and warns once.
197
197
  #
198
- # The composition carries NO executor row. The 0.2.1-rc.3 SDK ships the
199
- # presentation as a tool property selected through `presentAs`; it publishes no
200
- # `@deepseek-ai/dsh-tool-executor-ptc`, so a row naming it never starts and the
201
- # preset's load audit reports it alongside the rows that did mount (2026-10-26).
198
+ # This cohort splits execution into an agent-scoped executor row. The row below
199
+ # selects the same official PTC executor as the builtin ptc preset; the settings
200
+ # overlay disables it for native presentation so the two modes stay distinct.
202
201
  #
203
202
  # The row ships `presentation: 'ptc'` because that is the shipped default, and
204
203
  # the settings overlay rewrites the SAME key, so the settings switch and the
@@ -235,6 +234,25 @@
235
234
  - id: subagent-routes
236
235
  name: ./subagent-routes.mjs
237
236
 
237
+ # The dispatch execution guard. A preset row composes ONE tool registry, and an
238
+ # in-process child agent inherits that composition, so two things break quietly:
239
+ # a child calls a coordinator-only tool (ask_user_question, the plan-mode
240
+ # transitions, create_goal / update_goal, present) and splits one decision into
241
+ # two - the child asks, the user answers, and the dispatcher never learns what
242
+ # was asked; or a caller sleeps to wait for a child that the built-in completion
243
+ # notification will wake it for. This row refuses both at call execution time: a
244
+ # delegated caller is told to hand the open question back to the dispatcher, and
245
+ # a pure sleep statement (a wait beside nothing but no-ops) is refused while one
246
+ # of its children is still running. It uses ONLY `ctx.tools.guard()`, so the
247
+ # declared tool surface does not move by a byte and a prefix-caching provider
248
+ # never rebuilds because of this row. Every fact it cannot read fails open (no
249
+ # agents service, no roots, a throwing probe), so a host that cannot answer keeps
250
+ # the harness's own behaviour instead of failing the preset's load. It
251
+ # deliberately has no settings-card field: the row's own `enabled` key is the off
252
+ # switch, exactly as for `subagent-routes` above.
253
+ - id: dispatch-guard
254
+ name: ./dispatch-guard.mjs
255
+
238
256
  # The harness's workspace-instruction loader. Under the default
239
257
  # `instructionSource: host` this row owns the channel: its baseline and dynamic
240
258
  # user-role messages reach the model untouched. Under
@@ -425,18 +443,6 @@
425
443
  # selection fails with `child model selection is disabled for this tool
426
444
  # instance` and the settings page's subagent toggle reads as dead.
427
445
  #
428
- # `modelSelectionSettings: true` is the PRE-SPLIT spelling of the same
429
- # opt-in: one boolean that published the route fields AND registered
430
- # discovery. The SDK pinned in this package's devDependencies
431
- # (0.2.1-rc.3) still ships only that key, while the harness checkout this
432
- # repository runs against has replaced it with the pair above. That
433
- # loader's schema does not declare the retired name, so nothing reads it:
434
- # Schemastery keeps the undeclared field but fills `modelSelection` and
435
- # `modelDiscovery` with `false`, leaving the opt-in inert with no error
436
- # to notice. Both spellings therefore ship together: each generation
437
- # reads the key it knows and ignores the other, and neither host loses
438
- # the opt-in. Delete `modelSelectionSettings` once no supported cohort
439
- # predates the split.
440
446
  #
441
447
  # EXACTLY ONE delegation row per composition scope may enable
442
448
  # `modelDiscovery`: it registers the discovery tool under the FIXED name
@@ -455,7 +461,6 @@
455
461
  config:
456
462
  provider: spawn
457
463
  toolName: subagent
458
- modelSelectionSettings: true
459
464
  modelSelection: true
460
465
  modelDiscovery: true
461
466
  backgroundMode: continuable
@@ -524,3 +529,9 @@
524
529
  config:
525
530
  fetch: false
526
531
  searchTimeoutMs: 60000
532
+
533
+ # PTC execution is an agent-scoped plugin in this cohort. The declaration
534
+ # overlay disables this row for the native presentation; without it, `presentAs`
535
+ # can select the wire but no executor can carry a run_code program.
536
+ - id: tool-executor-ptc
537
+ name: '@deepseek-ai/dsh-tool-executor-ptc'
@@ -0,0 +1,471 @@
1
+ /**
2
+ * dispatch-guard — the LiangShen preset's execution-time guard against two
3
+ * dispatch-plane overreaches.
4
+ *
5
+ * A preset row composes ONE tool registry, and an in-process child agent
6
+ * inherits that composition. Two things therefore break quietly:
7
+ *
8
+ * 1. **A child calls a coordinator-only tool.** `ask_user_question`,
9
+ * `exit_plan_mode`, `create_goal` and their kin are the points where a
10
+ * decision is made. A child that asks the user itself, enters plan mode
11
+ * itself, or opens a goal itself splits one decision into two: the child asks,
12
+ * the user answers, and the dispatcher never learns what was asked. A child
13
+ * is supposed to hand the open question BACK, not to consume it.
14
+ * 2. **A caller sleeps while a child is still running.** The harness wakes the
15
+ * caller through the child's completion notification, so a `sleep` loop
16
+ * burns tokens to observe an event that arrives on its own.
17
+ *
18
+ * ## Why the tool surface does not move
19
+ *
20
+ * The guard uses exactly one seam, `ctx.tools.guard(exec => …)`:
21
+ *
22
+ * - it does not wrap `tools.register`, does not wrap `tools.definitions`, and
23
+ * does not listen on prompt assembly, so the declared tool schema stays
24
+ * byte-identical and a prefix-caching provider never rebuilds its cache
25
+ * because this row exists;
26
+ * - interception happens at CALL EXECUTION time, which keeps "the model can see
27
+ * the tool" and "the model can drive the tool" separate: the tool stays in
28
+ * the table and only the out-of-bounds call is refused.
29
+ *
30
+ * ## Where the facts come from
31
+ *
32
+ * Both decisions are structural probes over facts the host already holds, never
33
+ * an import of a cohort-specific type:
34
+ *
35
+ * - "is this caller a child": first the durable session lineage
36
+ * (`session.header.origin === 'subagent'`), then the live root set
37
+ * (`agents.roots()`);
38
+ * - "does this caller still have a child running": `subagents.list` and
39
+ * `agents.list`, whichever answers.
40
+ *
41
+ * Every fact the guard cannot read fails OPEN: a leg the host cannot resolve
42
+ * keeps the harness's own behaviour instead of failing the preset's load, which
43
+ * is why `agents` and `subagents` are read through `ctx.get()` at call time
44
+ * and never declared in `inject`.
45
+ */
46
+
47
+ /** Cordis plugin name used by loader diagnostics. */
48
+ export const name = 'liangshen-dispatch-guard'
49
+
50
+ /**
51
+ * Services this row declares.
52
+ *
53
+ * Only `tools` is declared, and only because this row mounts inside it: the
54
+ * guard seam lives on `ctx.tools.guard`. `agents` and `subagents` are NOT
55
+ * declared — a preset row runs in its own fiber, so a static declaration makes
56
+ * the row depend on a service the host may never provide, while an undeclared
57
+ * name read through `ctx.get()` degrades to `undefined` and lets the row mount
58
+ * anyway.
59
+ */
60
+ export const inject = ['tools']
61
+
62
+ /**
63
+ * Tools a delegated subagent must not call.
64
+ *
65
+ * All seven are decision or delivery points rather than work: the ask and the
66
+ * plan transitions belong to the coordinator, the goal domain is held by the
67
+ * coordinator, and `present` is the coordinator's delivery gate. A child that
68
+ * needs a decision reports the open question instead.
69
+ */
70
+ export const DEFAULT_COORDINATOR_TOOLS = Object.freeze([
71
+ 'ask_user_question',
72
+ 'enter_plan_mode',
73
+ 'leave_plan_mode',
74
+ 'exit_plan_mode',
75
+ 'create_goal',
76
+ 'update_goal',
77
+ 'present',
78
+ ])
79
+
80
+ /**
81
+ * Shell tools whose `command` argument can carry a wait.
82
+ *
83
+ * A wait is only a problem when a child is actually running; with no child,
84
+ * `sleep 1` is an ordinary command and must pass through untouched.
85
+ */
86
+ export const DEFAULT_SHELL_TOOLS = Object.freeze([
87
+ 'bash',
88
+ 'pwsh',
89
+ 'win_bash',
90
+ ])
91
+
92
+ /**
93
+ * One statement that only waits.
94
+ *
95
+ * Anchored at both ends so a statement that waits AND does work (`sleep 1 && npm
96
+ * test` is split before matching, but `sleep 1 | cat` is not) fails to match and
97
+ * therefore passes through: an unrecognised statement is never treated as a wait.
98
+ */
99
+ const WAIT_COMMAND_PATTERN = /^(?:sleep\s+\d+(?:\.\d+)?[smhd]?|Start-Sleep\s+(?:-(?:Seconds|Milliseconds|s|m)\s+)?\d+(?:\.\d+)?|timeout(?:\.exe)?\s+(?:\/t\s+)?\d+(?:\s+\/nobreak)?|ping(?:\.exe)?\s+-n\s+\d+\s+(?:127\.0\.0\.1|localhost))$/i
100
+
101
+ /** One statement that does nothing at all, so it changes no verdict. */
102
+ const NOOP_COMMAND_PATTERN = /^(?:echo\b.*|Write-Host\b.*|Write-Output\b.*|true|:)$/i
103
+
104
+ /** A comment line: the shell ignores it, so it may accompany a wait. */
105
+ const COMMENT_COMMAND_PATTERN = /^#/
106
+
107
+ /** Read a value as a plain record. */
108
+ function asRecord(value) {
109
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : undefined
110
+ }
111
+
112
+ /** Read a value as a plain array. */
113
+ function asArray(value) {
114
+ return Array.isArray(value) ? value : []
115
+ }
116
+
117
+ /** Read a record's string `id`. */
118
+ function idOf(value) {
119
+ const record = asRecord(value)
120
+ return typeof record?.['id'] === 'string' ? record['id'] : undefined
121
+ }
122
+
123
+ /**
124
+ * Read one OPTIONAL service off the host context.
125
+ *
126
+ * Always through `ctx.get()`: an undeclared property read on a real cordis
127
+ * context throws `cannot get property "…" without inject` on the spot, and a
128
+ * failed read must leave the guard without an opinion, never raise on a tool
129
+ * call.
130
+ */
131
+ function readService(ctx, serviceName) {
132
+ const reader = asRecord(ctx)?.['get']
133
+ if (typeof reader !== 'function') return undefined
134
+ try {
135
+ return reader.call(ctx, serviceName)
136
+ } catch {
137
+ return undefined
138
+ }
139
+ }
140
+
141
+ /** The live root set of an `agents` service, when it can be read at all. */
142
+ function rootsOf(agents) {
143
+ const roots = asRecord(agents)?.['roots']
144
+ if (typeof roots !== 'function') return undefined
145
+ try {
146
+ const listed = roots.call(agents)
147
+ return Array.isArray(listed) ? listed : undefined
148
+ } catch {
149
+ return undefined
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Whether this caller is a delegated child.
155
+ *
156
+ * Two levels, the independently valid fact first:
157
+ *
158
+ * 1. durable lineage — `session.header.origin === 'subagent'`, written when the
159
+ * child session was created, so it survives a host generation change;
160
+ * 2. the live root set — an agent that is NOT among `agents.roots()` is somebody
161
+ * else's child. Liveness is checked first (`agents.get(id) === agent`): an
162
+ * agent that is no longer the one registered under that id has been replaced
163
+ * or expired, and judging whether a stale object is a child is meaningless,
164
+ * so it passes through.
165
+ *
166
+ * A host without `agents`, without `roots`, or with a throwing read cannot be
167
+ * judged and answers `false`: treating an unreadable identity as a child would
168
+ * refuse the coordinator's own calls.
169
+ * @param agent - Calling agent.
170
+ * @param ctx - Host context carrying the optional `agents` service.
171
+ * @returns whether the caller is a delegated subagent.
172
+ */
173
+ export function isDelegatedCaller(agent, ctx) {
174
+ const caller = asRecord(agent)
175
+ if (caller === undefined) return false
176
+ const header = asRecord(asRecord(caller['session'])?.['header'])
177
+ if (header?.['origin'] === 'subagent') return true
178
+
179
+ const agents = readService(ctx, 'agents')
180
+ if (asRecord(agents) === undefined) return false
181
+ const roots = rootsOf(agents)
182
+ if (roots === undefined) return false
183
+ const id = idOf(caller)
184
+ const get = asRecord(agents)?.['get']
185
+ if (id !== undefined && typeof get === 'function') {
186
+ let live
187
+ try {
188
+ live = get.call(agents, id)
189
+ } catch {
190
+ live = undefined
191
+ }
192
+ if (live !== agent) return false
193
+ }
194
+ return !roots.includes(agent)
195
+ }
196
+
197
+ /**
198
+ * Whether one statement is harmless filler beside a wait.
199
+ * @param statement - Trimmed statement.
200
+ * @returns whether the statement makes no difference to the verdict.
201
+ */
202
+ function isNoopStatement(statement) {
203
+ return NOOP_COMMAND_PATTERN.test(statement) || COMMENT_COMMAND_PATTERN.test(statement)
204
+ }
205
+
206
+ /**
207
+ * Whether a command only waits.
208
+ *
209
+ * The command is split on `;`, `&&` and newlines, and it counts as a pure wait
210
+ * only when at least one statement waits and EVERY statement either waits or is
211
+ * harmless filler. One statement doing real work (`npm test`, `git status`,
212
+ * `node …`) makes the whole command real work, and such a command MUST pass
213
+ * through — otherwise the guard refuses legitimate background work.
214
+ * @param command - Candidate command.
215
+ * @returns whether the command only waits.
216
+ */
217
+ export function isPureSleepCommand(command) {
218
+ if (typeof command !== 'string') return false
219
+ const statements = command
220
+ .split(/;|&&|\n/u)
221
+ .map(statement => statement.trim())
222
+ .filter(statement => statement.length > 0)
223
+ if (statements.length === 0) return false
224
+ let sawWait = false
225
+ for (const statement of statements) {
226
+ if (WAIT_COMMAND_PATTERN.test(statement)) {
227
+ sawWait = true
228
+ continue
229
+ }
230
+ if (!isNoopStatement(statement)) return false
231
+ }
232
+ return sawWait
233
+ }
234
+
235
+ /**
236
+ * Call a host "list my entries" method defensively.
237
+ *
238
+ * Generations disagree about the shape: a scoped `list(agent, 'children')`, a
239
+ * scoped-but-single-argument `list(agent)`, and an argument-free `list()` all
240
+ * exist in the wild. Each form is tried in order and the first one that answers
241
+ * wins.
242
+ * @param fn - Host method.
243
+ * @param self - Receiver the method belongs to.
244
+ * @param agent - Calling agent.
245
+ * @param scoped - whether to try the scoped forms first.
246
+ * @returns whatever the host returned, or undefined when no form answered.
247
+ */
248
+ function callList(fn, self, agent, scoped = true) {
249
+ if (typeof fn !== 'function') return undefined
250
+ const attempts = scoped ? [[agent, 'children'], [agent], []] : [[], [agent]]
251
+ for (const args of attempts) {
252
+ try {
253
+ const listed = fn.apply(self, args)
254
+ // A host may ignore the extra argument and answer in full; only an
255
+ // undefined return means this form is not understood.
256
+ if (listed !== undefined) return listed
257
+ } catch {
258
+ // This generation does not know the form: fall back to the next one.
259
+ }
260
+ }
261
+ return undefined
262
+ }
263
+
264
+ /**
265
+ * Pull the entry records out of a host listing.
266
+ *
267
+ * A host may answer with a plain array, or with a record wrapping one of
268
+ * `children` / `agents` / `entries` / `list`.
269
+ * @param listed - Host return value.
270
+ * @returns the entry records, empty when none could be read.
271
+ */
272
+ function entriesOf(listed) {
273
+ if (Array.isArray(listed)) return listed.filter(entry => asRecord(entry) !== undefined)
274
+ const record = asRecord(listed)
275
+ if (record === undefined) return []
276
+ const entries = []
277
+ for (const key of ['children', 'agents', 'entries', 'list']) {
278
+ const candidate = record[key]
279
+ if (!Array.isArray(candidate)) continue
280
+ for (const entry of candidate) {
281
+ if (asRecord(entry) !== undefined) entries.push(entry)
282
+ }
283
+ }
284
+ return entries
285
+ }
286
+
287
+ /**
288
+ * Read the directly injected running-child callback off the context.
289
+ *
290
+ * This read is wrapped in try/catch on purpose: a real cordis context throws on
291
+ * any property read that `inject` does not cover, and one failed read must not
292
+ * make the guard raise on every tool call.
293
+ * @param ctx - Host context.
294
+ * @returns the injected callback, or undefined when the host carries none.
295
+ */
296
+ function injectedHasRunningChildren(ctx) {
297
+ if (asRecord(ctx) === undefined) return undefined
298
+ let injected
299
+ try {
300
+ injected = ctx['hasRunningChildren']
301
+ } catch {
302
+ return undefined
303
+ }
304
+ return typeof injected === 'function' ? injected : undefined
305
+ }
306
+
307
+ /**
308
+ * The session id of a caller, as its header records it.
309
+ * @param agent - Calling agent.
310
+ * @returns the session id, or undefined when the header carries none.
311
+ */
312
+ function sessionIdOf(agent) {
313
+ return idOf(asRecord(asRecord(agent)?.['session'])?.['header'])
314
+ }
315
+
316
+ /**
317
+ * Whether this caller still has a child running.
318
+ *
319
+ * Two host probes, either one answering counts:
320
+ *
321
+ * 1. `subagents.list` — any direct entry whose `status === 'running'`;
322
+ * 2. `agents.list()` — any running entry whose `parent` is the caller's agent id
323
+ * or the caller's session header id.
324
+ *
325
+ * A directly injected `ctx.hasRunningChildren(agent)` callback wins over both
326
+ * when the host provides one. Every read failure answers `false`: this test only
327
+ * ever adds a denial, so an unreadable host keeps the call.
328
+ * @param agent - Calling agent.
329
+ * @param ctx - Host context carrying the optional `subagents` / `agents` services.
330
+ * @returns whether a child of this caller is still running.
331
+ */
332
+ export function hasRunningChildSubagent(agent, ctx) {
333
+ const caller = asRecord(agent)
334
+ if (caller === undefined) return false
335
+
336
+ const injected = injectedHasRunningChildren(ctx)
337
+ if (injected !== undefined) {
338
+ try {
339
+ return injected(agent) === true
340
+ } catch {
341
+ return false
342
+ }
343
+ }
344
+
345
+ const subagents = readService(ctx, 'subagents')
346
+ if (asRecord(subagents) !== undefined) {
347
+ const listed = callList(asRecord(subagents)?.['list'], subagents, agent)
348
+ if (entriesOf(listed).some(entry => entry['status'] === 'running')) return true
349
+ }
350
+
351
+ const agents = readService(ctx, 'agents')
352
+ if (asRecord(agents) !== undefined) {
353
+ const listed = callList(asRecord(agents)?.['list'], agents, agent, false)
354
+ const parentIds = new Set()
355
+ const ownId = idOf(caller)
356
+ if (ownId !== undefined) parentIds.add(ownId)
357
+ const headerId = sessionIdOf(caller)
358
+ if (headerId !== undefined) parentIds.add(headerId)
359
+ const running = entriesOf(listed).some(entry =>
360
+ entry['status'] === 'running'
361
+ && typeof entry['parent'] === 'string'
362
+ && parentIds.has(entry['parent']))
363
+ if (running) return true
364
+ }
365
+
366
+ return false
367
+ }
368
+
369
+ /** The denial for a child that called a coordinator-only tool. */
370
+ function delegatedCallerDenial(toolName) {
371
+ return `DELEGATED_CALLER: "${toolName}" is a dispatch-level tool and a delegated subagent must not call it directly. `
372
+ + 'Report back to the dispatcher instead: include status: "hand_back" or status: "blocked" '
373
+ + 'and the unresolved question or decision in your report, and let the dispatcher act on it.'
374
+ }
375
+
376
+ /** The denial for sleeping while a child is still running. */
377
+ function activeChildSleepDenial() {
378
+ return 'ACTIVE_CHILD_SLEEP_FORBIDDEN: a child subagent is still running, so sleeping to wait for it is not allowed. '
379
+ + 'End your turn now and let the built-in subagent completion notification wake you.'
380
+ }
381
+
382
+ /**
383
+ * Decide one call.
384
+ *
385
+ * The two decisions are independent, so they are checked in a fixed order: the
386
+ * coordinator-only refusal is a fact about WHO called, and it precedes the
387
+ * shell check because a coordinator-only tool is refused whatever its arguments
388
+ * say.
389
+ * @param input - Caller, tool name, arguments, host context and configured lists.
390
+ * @returns a denial reason, or undefined to leave the call untouched.
391
+ */
392
+ export function dispatchDenialReason(input) {
393
+ const {
394
+ agent, toolName, args, ctx,
395
+ coordinatorTools = DEFAULT_COORDINATOR_TOOLS,
396
+ shellTools = DEFAULT_SHELL_TOOLS,
397
+ hasRunningChildren,
398
+ } = asRecord(input) ?? {}
399
+ if (typeof toolName !== 'string') return undefined
400
+
401
+ if (asArray(coordinatorTools).includes(toolName) && isDelegatedCaller(agent, ctx)) {
402
+ return delegatedCallerDenial(toolName)
403
+ }
404
+
405
+ if (asArray(shellTools).includes(toolName)) {
406
+ const command = asRecord(args)?.['command']
407
+ const background = asRecord(args)?.['run_in_background'] === true
408
+ // A backgrounded command is not a wait the caller sits in, so it is exempt.
409
+ if (!background && isPureSleepCommand(command)) {
410
+ let running = false
411
+ try {
412
+ running = typeof hasRunningChildren === 'function'
413
+ ? hasRunningChildren(agent) === true
414
+ : hasRunningChildSubagent(agent, ctx)
415
+ } catch {
416
+ running = false
417
+ }
418
+ if (running) return activeChildSleepDenial()
419
+ }
420
+ }
421
+
422
+ return undefined
423
+ }
424
+
425
+ /**
426
+ * Install the guard for the calling scope.
427
+ * @param ctx - Host context carrying the tool registry.
428
+ * @param config - Row configuration.
429
+ * @returns a disposer that removes the guard, or undefined when the scope has no
430
+ * guard seam at all.
431
+ */
432
+ export function installDispatchGuard(ctx, config = {}) {
433
+ let tools
434
+ try {
435
+ tools = asRecord(ctx)?.['tools']
436
+ } catch {
437
+ tools = undefined
438
+ }
439
+ const register = asRecord(tools)?.['guard']
440
+ if (typeof register !== 'function') return undefined
441
+ const coordinatorTools = Array.isArray(config?.coordinatorTools)
442
+ ? config.coordinatorTools
443
+ : DEFAULT_COORDINATOR_TOOLS
444
+ const shellTools = Array.isArray(config?.shellTools) ? config.shellTools : DEFAULT_SHELL_TOOLS
445
+ const dispose = register.call(tools, execution => dispatchDenialReason({
446
+ agent: execution?.agent,
447
+ toolName: execution?.name,
448
+ args: execution?.arguments,
449
+ ctx,
450
+ coordinatorTools,
451
+ shellTools,
452
+ }))
453
+ return typeof dispose === 'function' ? dispose : () => undefined
454
+ }
455
+
456
+ /**
457
+ * Mount the row: register the guard for this scope, with an off switch.
458
+ *
459
+ * The off switch is the row's own `enabled` key rather than a settings-card
460
+ * field: the row is a guard, not a feature, and the composition is the one place
461
+ * that says which guards a preset mounts.
462
+ * @param ctx - Cordis context of the composing scope.
463
+ * @param config - Row configuration; omitted fields select the shipped lists.
464
+ */
465
+ export function apply(ctx, config = {}) {
466
+ if (config?.enabled === false) return
467
+ ctx.effect(
468
+ () => installDispatchGuard(ctx, config) ?? (() => undefined),
469
+ 'liangshen: dispatch execution guard',
470
+ )
471
+ }