@mars.liu/dsh-cybernetics 0.6.0 → 0.8.4

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/src/controller.ts CHANGED
@@ -15,6 +15,31 @@ import type { WorkflowEngine } from '@deepseek-ai/dsh-workflow'
15
15
  /** Directory holding per-round audit logs, relative to the workspace root. */
16
16
  export const STATE_DIR = '.cybernetics'
17
17
 
18
+ /**
19
+ * One call-level model fallback within a round (v0.8): a role's configured
20
+ * model override failed to be called (availability failure) and the role's
21
+ * sub-agent was re-run on the session agent's model (no provider/model opts).
22
+ */
23
+ export interface RoleFallback {
24
+ /** Role whose override was bypassed ('default'/named task role, 'verify', 'triage'). */
25
+ role: string
26
+ /** The configured override that failed. */
27
+ from: { provider?: string; model?: string }
28
+ /**
29
+ * Signal layer (workflow runtime agent() hook, @deepseek-ai/dsh-workflow-ptc):
30
+ * 'availability-error' = the hook THREW a WorkflowError whose code/message
31
+ * matches an availability failure (AGENT_START always; AGENT_RESULT or
32
+ * uncoded errors on quota/rate-limit/auth/5xx/network/provider patterns);
33
+ * 'null-result' = the hook returned null (the runtime flattens a child run
34
+ * that ends stopReason ≠ 'completed' — e.g. a mid-run LLM call failure via
35
+ * dsh-subagent agent/error — into null without the cause), retried only
36
+ * because an override was in effect.
37
+ */
38
+ trigger: 'availability-error' | 'null-result'
39
+ /** Human-readable reason (first line of the runtime error, or the null semantics). */
40
+ reason: string
41
+ }
42
+
18
43
  /** One executed round, as returned by the workflow run. */
19
44
  export interface RoundResult {
20
45
  round: number
@@ -22,6 +47,8 @@ export interface RoundResult {
22
47
  verdict?: unknown
23
48
  triage?: unknown
24
49
  failed?: string
50
+ /** Call-level model fallbacks that occurred in this round (v0.8 audit). */
51
+ fallbacks?: RoleFallback[]
25
52
  /** Execution substrate used for this round (v0.6 audit). */
26
53
  executor?: 'ephemeral' | 'persistent'
27
54
  }
@@ -32,6 +59,24 @@ export interface RoleSpec {
32
59
  model?: string
33
60
  }
34
61
 
62
+ /**
63
+ * Parse a flat agent-model field ("provider/model" or a bare "model" name)
64
+ * into a workflow `agent()` override. Empty/whitespace/undefined → undefined,
65
+ * which the caller must treat as「与 session agent 一致」(no override handed
66
+ * to the round script — the workflow inherits the calling model).
67
+ */
68
+ export function parseAgentModelSpec(value?: string): RoleSpec | undefined {
69
+ const raw = (value ?? '').trim()
70
+ if (!raw) return undefined
71
+ const slash = raw.indexOf('/')
72
+ if (slash > 0 && slash < raw.length - 1) {
73
+ const provider = raw.slice(0, slash).trim()
74
+ const model = raw.slice(slash + 1).trim()
75
+ if (provider && model) return { provider, model }
76
+ }
77
+ return { model: raw }
78
+ }
79
+
35
80
  /** Per-role sub-agent configuration: 'default'/'verify'/'triage' plus named task roles. */
36
81
  export interface RolesConfig {
37
82
  default?: RoleSpec
@@ -112,6 +157,68 @@ export interface GoalRevisionRecord {
112
157
  reason: string
113
158
  /** Epoch milliseconds of the revision. */
114
159
  at: number
160
+ /**
161
+ * v0.7: how the old goal's in-flight round was handled, and why. Present on
162
+ * every revision so the audit trail records the decision basis, not just the
163
+ * outcome — see `decideAbort` for the decision tree.
164
+ */
165
+ abort?: { abort: boolean; mode: 'auto' | 'explicit'; basis: string }
166
+ }
167
+
168
+ /**
169
+ * Whether `revise` aborts the old goal's in-flight task agent round, and on
170
+ * what grounds. Pure — the caller supplies the "is a round in flight" fact
171
+ * from its own `running` map (no new orchestration mechanism; this reads the
172
+ * state the controller already maintains).
173
+ *
174
+ * Decision tree (v0.7 all-goals mode; `abortPrevious` explicitly passed keeps
175
+ * the v0.6 manual semantics):
176
+ * 1. `abortPrevious` given explicitly → honor it verbatim (mode 'explicit').
177
+ * 2. Old goal has NO round in flight → no abort, start the successor directly.
178
+ * 3. Old round in flight AND the revision rewrites the goal itself (a new
179
+ * `objective`, or a different `depth`) → the old round is working toward a
180
+ * target that no longer exists — contradictory goals / write-domain
181
+ * conflict → abort it (the cancel path) so it cannot interleave writes.
182
+ * 4. Old round in flight, correction only (new brief / title / role on the
183
+ * same objective) → the old work is still valuable and its result can be
184
+ * reused → let the round finish naturally, no abort.
185
+ */
186
+ export interface AbortDecision {
187
+ abort: boolean
188
+ mode: 'auto' | 'explicit'
189
+ basis: string
190
+ }
191
+
192
+ export function decideAbort(
193
+ previous: LoopState,
194
+ roundInFlight: boolean,
195
+ args: { abortPrevious?: boolean; objective?: string; depth?: 'quick' | 'full' },
196
+ ): AbortDecision {
197
+ if (args.abortPrevious !== undefined) {
198
+ return {
199
+ abort: args.abortPrevious,
200
+ mode: 'explicit',
201
+ basis: args.abortPrevious
202
+ ? '调用方显式要求中止旧轮(abortPrevious: true,复用 cancel 路径)'
203
+ : '调用方显式要求保留旧轮(abortPrevious: false,跑完自然结束)',
204
+ }
205
+ }
206
+ if (!roundInFlight) {
207
+ return { abort: false, mode: 'auto', basis: '旧 task agent 无在跑轮(查 goal 板 running 状态),直接启动新 goal,无需中止' }
208
+ }
209
+ const retargets = args.objective !== undefined || (args.depth !== undefined && args.depth !== (previous.depth ?? 'full'))
210
+ if (retargets) {
211
+ return {
212
+ abort: true,
213
+ mode: 'auto',
214
+ basis: '旧轮在跑且修订改写了目标本身(objective/depth 变化,目标矛盾/写域冲突)——自动中止旧轮,避免旧任务继续写入已被取代的方向',
215
+ }
216
+ }
217
+ return {
218
+ abort: false,
219
+ mode: 'auto',
220
+ basis: '旧轮在跑但任务目标未变(仅 brief/title/role 修正,旧工作仍可复用/可并行)——等待旧轮自然结束,结果由新 goal 继承',
221
+ }
115
222
  }
116
223
 
117
224
  /** Input for the append-only goal creation path. */
@@ -274,26 +381,42 @@ export async function runRound(
274
381
  }
275
382
  }
276
383
 
384
+ /**
385
+ * v0.8 visibility: render the round's call-level model fallbacks as a decision
386
+ * note suffix, so the tool result names every fallback (role, failed override,
387
+ * trigger) instead of only living in the audit log.
388
+ */
389
+ function fallbackSuffix(result: RoundResult): string {
390
+ const fallbacks = result.fallbacks ?? []
391
+ if (fallbacks.length === 0) return ''
392
+ const items = fallbacks.map((f) => {
393
+ const from = [f.from.provider, f.from.model].filter(Boolean).join('/') || '(inherit)'
394
+ return `${f.role}(${from}→session 模型,${f.trigger === 'null-result' ? '无产出' : '调用失败'})`
395
+ })
396
+ return `;⚠ 模型回退 ${fallbacks.length} 次:${items.join(',')}`
397
+ }
398
+
277
399
  /** Fold one round result into a continue/pause decision. Pure. */
278
400
  function decide(result: RoundResult, state: LoopState, config: ControllerConfig): ControllerDecision {
401
+ const fb = fallbackSuffix(result)
279
402
  if (result.failed) {
280
- return { action: 'pause', reason: 'failed', note: `第 ${result.round} 轮失败:${result.failed}` }
403
+ return { action: 'pause', reason: 'failed', note: `第 ${result.round} 轮失败:${result.failed}${fb}` }
281
404
  }
282
405
  const verdict = result.verdict as { met?: boolean; goalItselfQuestionable?: boolean; gaps?: string[] } | undefined
283
406
  if (verdict && verdict.goalItselfQuestionable) {
284
- return { action: 'pause', reason: 'goal-questionable', note: 'verify 判定目标本身可能有问题,需通过对话重新校准' }
407
+ return { action: 'pause', reason: 'goal-questionable', note: `verify 判定目标本身可能有问题,需通过对话重新校准${fb}` }
285
408
  }
286
409
  if (verdict?.met) {
287
- return { action: 'pause', reason: 'met', note: '验收全部通过;等待用户确认完成' }
410
+ return { action: 'pause', reason: 'met', note: `验收全部通过;等待用户确认完成${fb}` }
288
411
  }
289
412
  const triage = result.triage as { human?: { question?: string; step: string }[]; auto?: { step: string }[] } | undefined
290
413
  const human = triage?.human ?? []
291
414
  if (human.length > 0) {
292
- return { action: 'pause', reason: 'human-input', note: `待用户裁定:${human.map((h) => h.question ?? h.step).join(';')}` }
415
+ return { action: 'pause', reason: 'human-input', note: `待用户裁定:${human.map((h) => h.question ?? h.step).join(';')}${fb}` }
293
416
  }
294
417
  const cap = config.roundsPerSubgoal ?? 3
295
418
  if (state.round >= cap) {
296
- return { action: 'pause', reason: 'round-cap', note: `同一子目标已迭代 ${state.round} 轮仍未达成,升级用户` }
419
+ return { action: 'pause', reason: 'round-cap', note: `同一子目标已迭代 ${state.round} 轮仍未达成,升级用户${fb}` }
297
420
  }
298
421
  const gaps = verdict?.gaps ?? []
299
422
  const auto = triage?.auto ?? []
@@ -302,5 +425,5 @@ function decide(result: RoundResult, state: LoopState, config: ControllerConfig)
302
425
  : auto.length > 0
303
426
  ? auto.map((s) => s.step).join(';')
304
427
  : state.subgoal
305
- return { action: 'continue', subgoal: nextSubgoal, note: `进入第 ${state.round + 1} 轮` }
428
+ return { action: 'continue', subgoal: nextSubgoal, note: `进入第 ${state.round + 1} 轮${fb}` }
306
429
  }
package/src/index.ts CHANGED
@@ -25,8 +25,9 @@ import { randomUUID } from 'node:crypto'
25
25
  import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
26
26
  import { join } from 'node:path'
27
27
  import { fileURLToPath } from 'node:url'
28
+ import z from '@deepseek-ai/schemastery'
28
29
  import {
29
- STATE_DIR, createGoal, foldRound, runRound, startRound, supersedeGoal, writeRevisionLog,
30
+ STATE_DIR, createGoal, decideAbort, foldRound, parseAgentModelSpec, runRound, startRound, supersedeGoal, writeRevisionLog,
30
31
  } from './controller.ts'
31
32
  import type {
32
33
  ControllerConfig, ControllerDecision, LoopState, ResumableReason, RoundResult, RolesConfig,
@@ -68,6 +69,12 @@ export interface Config extends ControllerConfig {
68
69
  implicitTrigger?: boolean
69
70
  /** Per-role sub-agent model/provider overrides. */
70
71
  roles?: RolesConfig
72
+ /** Flat task-agent model override ("provider/model" or bare model); empty = inherit session agent. */
73
+ taskAgentModel?: string
74
+ /** Flat verify-agent model override (same format); empty = inherit session agent. */
75
+ verifyAgentModel?: string
76
+ /** Flat triage-agent model override (same format); empty = inherit session agent. */
77
+ triageAgentModel?: string
71
78
  /**
72
79
  * Hard orchestration gate (default false): hide execution tools from
73
80
  * TOP-LEVEL session agents at prompt-assembly time, so the session agent
@@ -89,12 +96,123 @@ export interface Config extends ControllerConfig {
89
96
  gateAllowlist?: string[]
90
97
  /** Extra tool names unioned onto the allowlist (default or gateAllowlist). */
91
98
  gateAllowlistExtra?: string[]
99
+ /**
100
+ * All-goals mode (v0.7, default false): EVERY user request — including
101
+ * trivial read-only questions and lightweight analysis — must go through a
102
+ * cybernetics goal first; in-place analysis by the session agent is banned.
103
+ * Off (default) keeps the v0.6 implicit-trigger behavior exactly unchanged.
104
+ */
105
+ allGoalsMode?: boolean
106
+ /**
107
+ * Max concurrent rounds across ALL sessions (default 0 = unlimited): a new
108
+ * round (blocking, 'start' or 'revise') is refused while this many rounds
109
+ * are in flight, protecting the host from parallel-agent storms.
110
+ */
111
+ maxConcurrentRounds?: number
92
112
  }
93
113
 
94
- // No `Config` export: this cordis requires a schemastery schema there// (Config.validate), which a zero-dependency plugin cannot import. The raw
95
- // patch config object passes through to apply() unvalidated; fields are
96
- // optional and read defensively (toolName, roundsPerSubgoal, roundScriptPath,
97
- // implicitTrigger, roles).
114
+ // Under the host's 0.1.7 settings model, an exported schemastery `Config`
115
+ // schema IS the plugin entry's settings page: the Web editor derives the
116
+ // plugin config form from it and serves it through the shared configuration
117
+ // forms (see @linxin666/dsh-ssh and @linxin666/dsh-usage for the same
118
+ // pattern). At least one field must be `.volatile()` for the page to be
119
+ // served at all; a volatile edit is committed into the running fiber's
120
+ // reference without a remount and announced via `loader/volatile-update`.
121
+ // The user-facing knobs (taskAgentModel / verifyAgentModel / triageAgentModel /
122
+ // roundsPerSubgoal / maxConcurrentRounds / allGoalsMode) are all
123
+ // volatile so they are visible AND writable in the settings panel and take
124
+ // effect on the next goal round. roles stays in the schema but is NOT
125
+ // volatile (v0.8.4): the panel serves only volatile fields, so it no longer
126
+ // shows in the GUI — advanced users (agent-guided) configure it directly in
127
+ // the profile config yaml; a host reload applies it. hardGate and the gate fields stay non-volatile: the panel
128
+ // cannot write them (they change structural wiring — tool stripping listener —
129
+ // so they belong in the profile config document instead).
130
+ export const Config = z.object({
131
+ /** Model-facing tool name. */
132
+ toolName: z.string().default('cybernetics').description('模型侧工具名(缺省 cybernetics)。'),
133
+ /** Inject the implicit goal-loop guidance section. */
134
+ implicitTrigger: z.boolean().default(true).description('注入隐式 goal-loop 系统提示段(缺省开启)。'),
135
+ /**
136
+ * Per-role sub-agent model/provider overrides: role -> {provider, model}.
137
+ * v0.8.4: NOT volatile — the settings card no longer exposes the roles JSON
138
+ * textarea (hand-editing JSON in the GUI is unfriendly), and the host panel
139
+ * serves only volatile fields, so a non-volatile roles simply disappears
140
+ * from the GUI while remaining configurable in the profile config yaml
141
+ * (save triggers a plugin-row remount / host reload, which is fine for an
142
+ * advanced setting an agent guides the user through). Runtime semantics are
143
+ * unchanged: readConfigField accepts a plain object (non-volatile) exactly
144
+ * like a live reference (volatile), and named task roles keep working.
145
+ */
146
+ roles: z.dict(z.object({
147
+ provider: z.string(),
148
+ model: z.string(),
149
+ })).description('按角色的子 agent provider/model 覆盖:role -> {provider, model}(如 default/verify/triage/frontend)。高级配置:直接编辑 profile 配置 yaml 后需宿主重载生效(GUI 不再提供此字段的编辑控件)。'),
150
+ /**
151
+ * Flat task-agent model override ("provider/model" or a bare model name).
152
+ * Empty = inherit the session agent. Merged over roles.default at wiring
153
+ * time (parseAgentModelSpec) — the flat fields are the settings-panel face;
154
+ * roles stays the canonical runtime shape the round script consumes.
155
+ * Volatile (v0.7.7): the host settings form (@deepseek-ai/dsh-settings
156
+ * volatileForm, lib/index.js:122-131) serves ONLY `.volatile()` fields, and
157
+ * its write() refuses any non-volatile path ("Config field ... is not
158
+ * volatile") — a plain field is invisible AND unwritable on the plugins
159
+ * page. Volatile commit keeps the running instance live; the value is read
160
+ * per round start (readConfigField unwrap below), so an edit takes effect
161
+ * on the next goal round without a remount.
162
+ */
163
+ taskAgentModel: z.string().default('').volatile().description('task agent 模型覆盖(「provider/model」或裸模型名);留空 = 与 session agent 一致。保存后下一轮 goal 即生效,无需重载。'),
164
+ /** Flat verify-agent model override; same format, fallback and volatile semantics as taskAgentModel. */
165
+ verifyAgentModel: z.string().default('').volatile().description('verify agent 模型覆盖(「provider/model」或裸模型名);留空 = 与 session agent 一致。保存后下一轮 goal 即生效,无需重载。'),
166
+ /**
167
+ * Flat triage-agent model override (v0.8.2); identical shape, fallback and
168
+ * volatile semantics as taskAgentModel/verifyAgentModel. The triage role
169
+ * reads the task/verify results and produces the round's convergence
170
+ * decision (met / continue / human-input / ...); quick-depth rounds skip
171
+ * verify+triage entirely, so this override only ever fires on full rounds.
172
+ */
173
+ triageAgentModel: z.string().default('').volatile().description('triage agent 模型覆盖(「provider/model」或裸模型名);留空 = 与 session agent 一致。triage 角色读 task/verify 结果输出本轮收敛决策(met/continue/human-input 等);quick 轮不启用。保存后下一轮 goal 即生效,无需重载。'),
174
+ /**
175
+ * Max consecutive rounds per subgoal before the loop pauses for the user
176
+ * (controller round-cap, default 3). Volatile: read per round start, so the
177
+ * panel edit governs the very next goal round without a remount.
178
+ */
179
+ roundsPerSubgoal: z.number().default(3).volatile().description('同一子目标的最大连续轮数(递归深度上限,缺省 3):超过即暂停并升级给用户。保存后下一轮 goal 即生效,无需重载。'),
180
+ /**
181
+ * Max concurrent rounds across all sessions (default 0 = unlimited).
182
+ * Volatile: enforced at every launch, live on the next tool call.
183
+ */
184
+ maxConcurrentRounds: z.number().default(0).volatile().description('全局并行轮数上限(缺省 0 = 不限):在跑轮数达到上限时拒绝启动新一轮,防止并行风暴。保存后即时生效,无需重载。'),
185
+ /** Hard orchestration gate (default false). */
186
+ hardGate: z.boolean().default(false).description('硬编排门:装配期从顶层 session agent 摘除执行工具,所有改动必须经 cybernetics goal + task agent。修改会触发插件重载。'),
187
+ /** Tool names hidden in denylist mode (default DEFAULT_GATED_TOOLS). */
188
+ gatedTools: z.array(z.string()).description('denylist 模式下隐藏的工具名(缺省内置 DEFAULT_GATED_TOOLS)。'),
189
+ /** Gate semantics. */
190
+ gateMode: z.union(['denylist', 'allowlist'] as const).default('denylist').description('门语义:denylist 隐藏 gatedTools;allowlist 只保留 gateAllowlist(+gateAllowlistExtra)与 cybernetics 工具本身。'),
191
+ /** Allowlist-mode survival set (default DEFAULT_GATE_ALLOWLIST). */
192
+ gateAllowlist: z.array(z.string()).description('allowlist 模式生存工具集(缺省内置 DEFAULT_GATE_ALLOWLIST)。'),
193
+ /** Extra tool names unioned onto the allowlist. */
194
+ gateAllowlistExtra: z.array(z.string()).description('并集追加进 allowlist 的额外工具名。'),
195
+ /**
196
+ * All-goals mode (v0.7, default false): every user request must go through
197
+ * a cybernetics goal first. Volatile: the settings-panel toggle commits
198
+ * into the running instance without a remount.
199
+ */
200
+ allGoalsMode: z.boolean().default(false).volatile()
201
+ .description('全目标模式(v0.7,缺省关):所有用户请求(含只读问题)都必须先经 cybernetics goal。开关在面板上保存后即时生效,无需重载。'),
202
+ })
203
+
204
+ /** One resolved config field: a live reference (volatile), or a plain value. */
205
+ type ConfigField<T> = { get(): T } | T
206
+
207
+ /** Read one resolved config field, following the live reference the schema produces for volatile fields. */
208
+ function readConfigField<T>(field: ConfigField<T> | undefined, fallback: T): T {
209
+ if (field === undefined) return fallback
210
+ if (typeof field === 'object' && field !== null && typeof (field as { get?: unknown }).get === 'function') {
211
+ const value = (field as { get(): T }).get()
212
+ return value === undefined ? fallback : value
213
+ }
214
+ return field as T
215
+ }
98
216
 
99
217
  /**
100
218
  * Multi-goal loop registry: session -> goalId -> loop. v0.3 lifts the
@@ -318,6 +436,42 @@ yourself — you manage goals and the task agents that execute them. Classify ea
318
436
  'round-cap'/'failed' = report status. Never mark a goal complete yourself; completion is the user's act.
319
437
  Use action 'list' to see every goal on this session's board with its status, round and subgoal.`
320
438
 
439
+ /**
440
+ * v0.7 all-goals mode addendum: turns the implicit trigger from "suggest a
441
+ * goal for substantial tasks" into "every request is a goal". Contains the
442
+ * four routing rules the protocol and tests pin down:
443
+ * (1) everything enters a goal; (2) simple read-only → 'quick' single round;
444
+ * (3) complex analysis / write tasks → progressive multi-round ('full');
445
+ * (4) the revise auto-abort decision tree.
446
+ */
447
+ const ALL_GOALS_GUIDANCE = `
448
+ ALL-GOALS MODE ACTIVE (routing protocol — no exceptions, no in-place analysis):
449
+ - RULE 1 — EVERYTHING ENTERS A GOAL: for ANY user request (question, lookup, analysis, change), first
450
+ create a goal via cybernetics (action 'start' with title + brief), then let the task agent produce the
451
+ answer. NEVER answer a request by doing the task work yourself with read tools — even a one-file lookup
452
+ or a quick calculation goes through the loop. If a change is requested while the hard gate is off, the
453
+ protocol still forbids in-place edits: delegate.
454
+ - RULE 2 — SIMPLE READ-ONLY REQUEST → depth 'quick': one task-agent round, no verify/triage, feed the
455
+ result straight back to the user (bounded lookups, single-file reads, small queries).
456
+ - RULE 3 — COMPLEX ANALYSIS or WRITE TASK → depth 'full', progressive multi-round: launch with action
457
+ 'start' (async), then 'collect' each settled round and advance the subgoal round by round (task →
458
+ verify → triage). Analysis: data fetching to disk, datasets, statistics, multi-step query planning.
459
+ Write tasks additionally rely on the hard gate: the session agent must NEVER execute a change itself —
460
+ delegation through the goal loop is the only path, however small the change.
461
+ - RULE 4 — REVISE DECISION TREE (updating an existing goal stays append-only: a new goal with
462
+ parentGoalId, old goal superseded; 'revise' is the only goal-change verb). Decide abortPrevious by the
463
+ old task agent's state (check with action 'list'):
464
+ (a) old round STILL RUNNING and the revision contradicts it (objective/depth rewritten — conflicting
465
+ goals / write-domain overlap) → let 'revise' auto-abort: do not pass abortPrevious; the plugin
466
+ cancels the old round automatically;
467
+ (b) old round STILL RUNNING but the correction keeps the objective (brief/title/role only) and the old
468
+ work stays valuable / parallelizable / reusable → do not pass abortPrevious; the plugin waits for
469
+ the old round to finish naturally;
470
+ (c) old task agent ALREADY FINISHED (goal not running on the board) → just call 'revise'; no abort is
471
+ needed and none is attempted.
472
+ The chosen branch and its reason are recorded in the .cybernetics/revisions-<newGoalId>.jsonl audit
473
+ line (abort.mode = auto|explicit + basis). Passing abortPrevious explicitly keeps manual control.`
474
+
321
475
  /** Tool names hidden from top-level session agents when the hard gate is on. */
322
476
  const DEFAULT_GATED_TOOLS = ['bash', 'edit', 'write']
323
477
 
@@ -373,6 +527,10 @@ not find it, that is the gate working as intended — delegate instead.`
373
527
  export function apply(ctx: any, config: Partial<Config> = {}) {
374
528
  const toolName = config.toolName ?? 'cybernetics'
375
529
  const hardGate = config.hardGate === true
530
+ // allGoalsMode is a volatile field: under the loader's schema resolution it
531
+ // arrives as a live reference whose value the settings panel commits in
532
+ // place (no remount), so read it at use time instead of capturing it once.
533
+ const allGoalsMode = () => readConfigField(config.allGoalsMode, false) === true
376
534
  const disposers: Array<() => void> = []
377
535
 
378
536
  // v0.6: register the multi-goal session projection, so every goal on the
@@ -389,13 +547,24 @@ export function apply(ctx: any, config: Partial<Config> = {}) {
389
547
  if (typeof projectionDisposer === 'function') disposers.push(projectionDisposer)
390
548
  }
391
549
 
392
- if (config.implicitTrigger !== false) {
393
- ctx.systemPrompt.section({
550
+ // The implicit guidance section embeds the volatile allGoalsMode wording,
551
+ // so it must be re-derived when a settings-panel toggle is committed into
552
+ // the running instance (the loader announces loader/volatile-update on this
553
+ // fiber instead of remounting; same re-derive pattern as dsh-ssh's sync()).
554
+ let disposeSection: (() => void) | undefined
555
+ function registerGuidanceSection() {
556
+ if (disposeSection !== undefined) disposeSection()
557
+ disposeSection = undefined
558
+ if (config.implicitTrigger === false) return
559
+ disposeSection = ctx.systemPrompt.section({
394
560
  name: `tool:${toolName}`,
395
561
  order: ctx.systemPrompt.getSectionOrder('TOOL_WORKFLOW'),
396
- text: IMPLICIT_GUIDANCE + (hardGate ? HARD_GATE_GUIDANCE : ''),
562
+ text: IMPLICIT_GUIDANCE + (allGoalsMode() ? ALL_GOALS_GUIDANCE : '') + (hardGate ? HARD_GATE_GUIDANCE : ''),
397
563
  })
398
564
  }
565
+ registerGuidanceSection()
566
+ disposers.push(() => { if (disposeSection !== undefined) disposeSection() })
567
+ ctx.on?.('loader/volatile-update', () => { registerGuidanceSection() })
399
568
 
400
569
  if (hardGate) {
401
570
  // The hard gate: a system-prompt/assemble waterfall listener that strips
@@ -403,12 +572,15 @@ export function apply(ctx: any, config: Partial<Config> = {}) {
403
572
  // (task/verify/triage) and team teammates are never in agents.roots(),
404
573
  // so their assemblies pass through untouched with full tool access.
405
574
  const allowlistMode = config.gateMode === 'allowlist'
575
+ // NOTE: schema-resolved config turns an unset z.array field into [] (not
576
+ // undefined), so fall back on length, not on ?? — otherwise the gate
577
+ // would silently keep/gate nothing.
406
578
  const keep = new Set([
407
- ...(config.gateAllowlist ?? DEFAULT_GATE_ALLOWLIST),
579
+ ...(config.gateAllowlist?.length ? config.gateAllowlist : DEFAULT_GATE_ALLOWLIST),
408
580
  ...(config.gateAllowlistExtra ?? []),
409
581
  toolName,
410
582
  ])
411
- const gated = new Set(config.gatedTools ?? DEFAULT_GATED_TOOLS)
583
+ const gated = new Set(config.gatedTools?.length ? config.gatedTools : DEFAULT_GATED_TOOLS)
412
584
  const listenerDisposer = ctx.on('system-prompt/assemble', (assembly: any, context: any, next: () => unknown) => {
413
585
  const scope = context?.scope
414
586
  if (!scope) return next()
@@ -524,7 +696,8 @@ export function apply(ctx: any, config: Partial<Config> = {}) {
524
696
  abortPrevious: {
525
697
  type: 'boolean',
526
698
  description:
527
- 'revise:是否中止旧 goal 正在运行的 task agent 轮(默认 false,让它跑完;true 时复用 cancel 路径)。',
699
+ 'revise:是否中止旧 goal 正在运行的 task agent 轮。缺省时按决策树自动判断(查 goal 板:旧轮在跑且目标被改写→自动中止;旧轮在跑但目标不变→等待自然结束;旧轮未跑→直启);' +
700
+ '显式传 true/false 保持人工控制(true 复用 cancel 路径)。',
528
701
  },
529
702
  executor: {
530
703
  type: 'string',
@@ -540,6 +713,7 @@ export function apply(ctx: any, config: Partial<Config> = {}) {
540
713
  goalId: { type: 'string' },
541
714
  previousGoalId: { type: 'string' },
542
715
  revised: { type: 'boolean' },
716
+ abort: { type: 'object' },
543
717
  revision: { type: 'object' },
544
718
  round: { type: 'number' },
545
719
  decision: { type: 'object' },
@@ -725,10 +899,40 @@ export function apply(ctx: any, config: Partial<Config> = {}) {
725
899
  // it visible in the tab even when this call changes nothing else.
726
900
  await publishBoard()
727
901
 
902
+ // Flat settings-panel model fields fold into the canonical roles shape:
903
+ // an unset field leaves its role untouched = inherit the session agent.
904
+ // All three fields are volatile (task/verify v0.7.7, triage v0.8.2), so
905
+ // the loader hands back live references — unwrap through readConfigField
906
+ // ('' = inherit) exactly like the allGoalsMode live ref above.
907
+ // roles may be volatile (a live reference, pre-0.8.3 configs) or a plain
908
+ // object (non-volatile since v0.8.4, configured via profile yaml) —
909
+ // readConfigField handles both shapes: a live ref is unwrapped, a plain
910
+ // object is returned as-is (hardGate and friends take the same path).
911
+ const roleOverrides: RolesConfig = { ...readConfigField(config.roles, {} as RolesConfig) }
912
+ const taskSpec = parseAgentModelSpec(readConfigField(config.taskAgentModel, ''))
913
+ if (taskSpec) roleOverrides.default = { ...roleOverrides.default, ...taskSpec }
914
+ const verifySpec = parseAgentModelSpec(readConfigField(config.verifyAgentModel, ''))
915
+ if (verifySpec) roleOverrides.verify = { ...roleOverrides.verify, ...verifySpec }
916
+ const triageSpec = parseAgentModelSpec(readConfigField(config.triageAgentModel, ''))
917
+ if (triageSpec) roleOverrides.triage = { ...roleOverrides.triage, ...triageSpec }
728
918
  const controllerConfig: ControllerConfig = {
729
919
  roundScriptPath: config.roundScriptPath ?? fileURLToPath(new URL('../workflows/round.js', import.meta.url)),
730
- roundsPerSubgoal: config.roundsPerSubgoal,
731
- roles: config.roles,
920
+ // Volatile schema fields surface as live references — unwrap per round
921
+ // start so a settings-panel edit governs the next round (0/undefined
922
+ // falls back to the controller's built-in default).
923
+ roundsPerSubgoal: Math.max(1, Math.floor(readConfigField(config.roundsPerSubgoal, 3))),
924
+ roles: roleOverrides,
925
+ }
926
+ // Concurrent-round cap (0 = unlimited), read live at every launch.
927
+ const maxConcurrentRounds = () => {
928
+ const raw = Math.floor(readConfigField(config.maxConcurrentRounds, 0))
929
+ return Number.isFinite(raw) && raw > 0 ? raw : 0
930
+ }
931
+ const concurrentCapError = () => {
932
+ const cap = maxConcurrentRounds()
933
+ return cap > 0 && running.size >= cap
934
+ ? `cybernetics: 已有 ${running.size} 个运行中的轮,达到全局并行上限 ${cap}(可在设置面板调高 maxConcurrentRounds 或等待完成)`
935
+ : undefined
732
936
  }
733
937
  const objective = loop.objective ?? goalView?.objective ?? loop.title ?? ''
734
938
 
@@ -762,6 +966,8 @@ export function apply(ctx: any, config: Partial<Config> = {}) {
762
966
  * goal's status is already 'running' when this is called.
763
967
  */
764
968
  const launchBackground = async (target: LoopState): Promise<{ round: number }> => {
969
+ const blocked = concurrentCapError()
970
+ if (blocked) throw new Error(blocked)
765
971
  const controller = new AbortController()
766
972
  if (exec.signal) {
767
973
  if (exec.signal.aborted) controller.abort()
@@ -805,7 +1011,20 @@ export function apply(ctx: any, config: Partial<Config> = {}) {
805
1011
  'revise the successor goal instead of forking the lineage',
806
1012
  )
807
1013
  }
808
- const abortPrevious = args.abortPrevious === true
1014
+ // v0.7 abort policy: explicit abortPrevious keeps the v0.6 manual
1015
+ // semantics; when the caller omits it, all-goals mode auto-decides via
1016
+ // the decision tree (see decideAbort). With allGoalsMode off, the
1017
+ // omitted flag means false exactly as before (backward compat) and the
1018
+ // audit records that legacy default instead of a fabricated decision.
1019
+ const roundInFlight = running.has(previous.goalId!)
1020
+ const abortDecision = decideAbort(previous, roundInFlight, args)
1021
+ const legacyDefault = args.abortPrevious === undefined && !allGoalsMode()
1022
+ const effectiveAbort = legacyDefault
1023
+ ? { abort: false, mode: 'explicit' as const, basis: 'all-goals 模式未开启:abortPrevious 缺省沿用 v0.6 默认 false(不中止旧轮)' }
1024
+ : abortDecision
1025
+ const abortPrevious = args.abortPrevious !== undefined
1026
+ ? args.abortPrevious === true
1027
+ : (allGoalsMode() ? abortDecision.abort : false)
809
1028
  const previousHandle = running.get(previous.goalId!)
810
1029
  let aborted: string | undefined
811
1030
  if (abortPrevious && previousHandle) {
@@ -833,7 +1052,10 @@ export function apply(ctx: any, config: Partial<Config> = {}) {
833
1052
  const at = Date.now()
834
1053
  let revisionLog: string | undefined
835
1054
  try {
836
- revisionLog = await writeRevisionLog(root, newGoalId, { from: previous.goalId!, to: newGoalId, reason, at })
1055
+ revisionLog = await writeRevisionLog(root, newGoalId, {
1056
+ from: previous.goalId!, to: newGoalId, reason, at,
1057
+ abort: effectiveAbort,
1058
+ })
837
1059
  } catch {
838
1060
  // Audit is observability: a read-only workspace must not break the
839
1061
  // revision (the lineage fields on the board still carry the change).
@@ -846,6 +1068,7 @@ export function apply(ctx: any, config: Partial<Config> = {}) {
846
1068
  round,
847
1069
  started: true,
848
1070
  ...(aborted ? { aborted } : {}),
1071
+ abort: effectiveAbort,
849
1072
  revision: { from: previous.goalId, to: newGoalId, reason, at },
850
1073
  ...(revisionLog ? { revisionLog } : {}),
851
1074
  }
@@ -887,6 +1110,8 @@ export function apply(ctx: any, config: Partial<Config> = {}) {
887
1110
  if (running.has(loop.goalId!)) {
888
1111
  throw new Error(`cybernetics: goal "${loop.goalId}" already has a round in flight — collect or cancel it first`)
889
1112
  }
1113
+ const blocked = concurrentCapError()
1114
+ if (blocked) throw new Error(blocked)
890
1115
  loop.status = 'running'
891
1116
  // In-flight visibility: the blocking 'round' path can run for minutes, so
892
1117
  // publish before awaiting it (the async path needs no second publish —