@adhdev/daemon-core 0.9.82-rc.482 → 0.9.82-rc.484

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.
@@ -161,7 +161,12 @@ export declare function assertPendingMeshCoordinatorEventV2(raw: unknown, path?:
161
161
  * Decide whether a v2 pending event should be delivered to the given drainer.
162
162
  * Centralised so every drain implementation uses the same rule.
163
163
  *
164
- * - 'broadcast': always delivered.
164
+ * - 'broadcast': always delivered. NOTE: a terminal task event that reached the
165
+ * queue as broadcast is an ownership leak (it belongs to its dispatching
166
+ * coordinator). This pure helper does not have the drain-window
167
+ * daemon-form/session matching semantics, so the terminal+broadcast
168
+ * dispatchedBy filter is applied one layer up in the drainer (see
169
+ * mesh-events-pending routeV2EventsForDrainer) where those semantics live.
165
170
  * - 'system': never delivered to coordinators (system handler only).
166
171
  * - 'unicast': delivered iff intendedFor matches drainer identity.
167
172
  *
@@ -170,6 +175,15 @@ export declare function assertPendingMeshCoordinatorEventV2(raw: unknown, path?:
170
175
  * are quarantined to a dedicated drain endpoint instead.
171
176
  */
172
177
  export declare function shouldDeliverPendingEventToCoordinator(event: PendingMeshCoordinatorEventV2, drainer: CoordinatorIdentity): boolean;
178
+ /**
179
+ * True for a terminal task event (completion / stop / refine outcome). A terminal
180
+ * event belongs to exactly the coordinator that dispatched the task, so it must
181
+ * never fan out to sibling coordinators that did not dispatch it. Used by the
182
+ * emit-side stamp (to avoid downgrading an unaddressed terminal event to full
183
+ * broadcast) and by the drain-side filter (defense-in-depth for any terminal
184
+ * event that already reached the queue as broadcast).
185
+ */
186
+ export declare function isTerminalTaskEvent(eventName: string): boolean;
173
187
  /**
174
188
  * Default the v2 scope for an event by its producer event name (design decision
175
189
  * §3). Terminal task events and coordinator-addressed alerts → unicast (routed
@@ -219,9 +233,18 @@ export declare function coordinatorIdentityFromEmitFields(fields: {
219
233
  * returns undefined: the event stays a v1 (unstamped) event and is broadcast-
220
234
  * treated during rollout, exactly as before — no regression, no fabricated
221
235
  * identity. When the resolved scope is 'unicast' but no `intendedFor` is
222
- * available, the scope is downgraded to 'broadcast' so the stamp never violates
223
- * the "unicast requires intendedFor" contract (a terminal event that cannot be
224
- * addressed to its originator is safest delivered broadly, not dropped).
236
+ * available, the fallback depends on the event class:
237
+ *
238
+ * - Terminal task events (completion / stop / refine outcome) MUST NOT be
239
+ * broadcast to every coordinator — a completion belongs to the coordinator
240
+ * that dispatched the task, and broadcasting it makes non-owner coordinators
241
+ * (e.g. sibling MAGI coordinators that never dispatched this replica's task)
242
+ * act on a completion that is not theirs (MAGI-REPLICA-COMPLETION-EVENT-LEAK).
243
+ * For these we address the event to `dispatchedBy` (the dispatching
244
+ * coordinator) and KEEP it unicast, so the stamp stays contract-valid and the
245
+ * event reaches only its originating coordinator.
246
+ * - Any other unicast event with no addressable target falls back to broadcast
247
+ * (contract-valid, still delivered, never dropped) — unchanged.
225
248
  */
226
249
  export declare function buildPendingEventEmitStamp(opts: {
227
250
  eventName: string;
@@ -34,6 +34,18 @@ export interface PendingMeshCoordinatorEvent {
34
34
  dispatchedBy?: CoordinatorIdentity;
35
35
  /** Present only for unicast scope: the coordinator this event is addressed to. */
36
36
  intendedFor?: CoordinatorIdentity;
37
+ /**
38
+ * True when this event was stamped as a broadcast SOLELY because no owning
39
+ * coordinator identity was resolvable at emit time (self-fallback: dispatchedBy
40
+ * is THIS daemon's own machineId, not a real coordinator). Such a broadcast has
41
+ * no owner, so the MAGI-REPLICA-COMPLETION-EVENT-LEAK guard — which only exists
42
+ * to stop a NON-owner coordinator from consuming an OWNED terminal event — must
43
+ * not apply: an ownerless terminal broadcast is a genuine "deliver to any
44
+ * coordinator that drains on this machine" event and identity-matching its
45
+ * self-id dispatchedBy against the drainer would wrongly route it away.
46
+ * Absent (undefined/false) on a normally-owned event → the leak guard applies.
47
+ */
48
+ dispatchedBySelfFallback?: boolean;
37
49
  }
38
50
  /**
39
51
  * Optional emit-time hint passed to queuePendingMeshCoordinatorEvent so a call
@@ -239,6 +239,20 @@ export declare class MeshRuntimeStore {
239
239
  * watchdog's). Indexed by (mesh_id, task_id).
240
240
  */
241
241
  taskHasConfirmedDelivery(meshId: string, taskId: string): boolean;
242
+ /**
243
+ * DELIVERED-NOT-CONSUMED re-drive support: true when at least one delivery record for
244
+ * the task has reached a CONSUMED status ('acked' / 'completed'). Distinct from
245
+ * {@link taskHasConfirmedDelivery} ('delivered' | 'acked' | 'completed'): a delivery is
246
+ * flipped to 'delivered' the instant the transport hands the dispatch off, but only
247
+ * flipped to 'acked' when the worker's agent:generating_started event arrives (see the
248
+ * generating_started handler in mesh-event-forwarding) — i.e. when the session has
249
+ * actually begun the turn. That distinction is the cross-daemon consumption signal the
250
+ * short-grace re-drive uses: a row whose delivery is 'delivered' but never 'acked' was
251
+ * handed to a REMOTE worker that never started generating — the remote autoLaunch
252
+ * delivered≠consumed gap — even when the session's busy verdict is UNKNOWN (not locally
253
+ * observable). Indexed by (mesh_id, task_id).
254
+ */
255
+ taskDeliveryConsumed(meshId: string, taskId: string): boolean;
242
256
  expireStaleSessionDeliveries(meshId: string): void;
243
257
  deleteSessionDeliveries(meshId: string): void;
244
258
  /**
@@ -119,6 +119,13 @@ export interface MeshWorkQueueEntry {
119
119
  * that cannot honor the model still runs the task (never a fatal launch error).
120
120
  */
121
121
  model?: string;
122
+ /**
123
+ * BRAIN-ROUTING (thinking axis): standard reasoning level ('low'|'medium'|'high')
124
+ * for the session that executes this task. When the task auto-launches, this is
125
+ * passed to launch_cli as `initialThinkingLevel` (CLI → thinkingLaunchArgs; ACP →
126
+ * setConfigOption('thought_level')). Rides in payload JSON. Best-effort like model.
127
+ */
128
+ thinkingLevel?: string;
122
129
  /**
123
130
  * M1: why this task is held back (e.g. "dependency_failed:<taskId>").
124
131
  * Only set by the system on dependency failure under the 'block' policy;
@@ -241,6 +248,16 @@ export declare function enqueueTask(meshId: string, message: string, opts?: {
241
248
  consensusGroupId?: string;
242
249
  /** MAGI-KIND-PANEL: model override forwarded to the executing session's launch (initialModel). */
243
250
  model?: string;
251
+ /** BRAIN-ROUTING: standard thinking level forwarded to launch (initialThinkingLevel). */
252
+ thinkingLevel?: string;
253
+ /**
254
+ * BRAIN-ROUTING: task execution difficulty ('easy'|'medium'|'difficult'|
255
+ * 'freeform'). When set, the mesh's difficulty→brain preset fills in model /
256
+ * thinkingLevel that were not passed explicitly (an explicit model/thinkingLevel
257
+ * wins). Purely a convenience resolver — the stored task still carries the
258
+ * resolved model/thinkingLevel, so downstream launch is unchanged.
259
+ */
260
+ difficulty?: string;
244
261
  /** Explicit task id for batch/template flows (M5). Random UUID when omitted. */
245
262
  id?: string;
246
263
  /** (3) Originating coordinator session id (for session-anchored completion routing). */
@@ -155,12 +155,17 @@ export declare class CliProviderInstance implements ProviderInstance {
155
155
  private presentationMode;
156
156
  private providerSessionId?;
157
157
  private launchMode;
158
+ private initialThinkingLevel?;
158
159
  private readonly startedAt;
159
160
  private onProviderSessionResolved?;
160
161
  constructor(provider: ProviderModule, workingDir: string, cliArgs?: string[], instanceId?: string, transportFactory?: PtyTransportFactory, options?: {
161
162
  providerSessionId?: string;
162
163
  launchMode?: 'new' | 'resume' | 'manual';
163
164
  extraEnv?: Record<string, string>;
165
+ /** BRAIN-ROUTING: standard thinking level to apply post-launch via the
166
+ * provider's thinkingControlId (runtime-control providers like hermes).
167
+ * Providers using thinkingLaunchArgs get it at spawn instead and ignore this. */
168
+ initialThinkingLevel?: string;
164
169
  onProviderSessionResolved?: (info: {
165
170
  instanceId: string;
166
171
  providerType: string;
@@ -321,6 +326,15 @@ export declare class CliProviderInstance implements ProviderInstance {
321
326
  */
322
327
  private lastCompletionSummary;
323
328
  private enforceFreshSessionLaunchIfNeeded;
329
+ /**
330
+ * BRAIN-ROUTING (runtime-control thinking axis): for a provider that selects
331
+ * reasoning effort via a runtime control instead of a launch arg (e.g. hermes
332
+ * `reasoning`), apply the requested initialThinkingLevel after spawn by invoking
333
+ * that control's setScript. The provider names the control via thinkingControlId.
334
+ * The standard level is mapped through thinkingLevelMap first (same as the
335
+ * launch-arg path). Best-effort: any failure logs and never blocks launch.
336
+ */
337
+ private applyInitialThinkingLevelViaControl;
324
338
  private completionHasFinalAssistantMessage;
325
339
  private recordPendingTranscriptProbe;
326
340
  /**
@@ -499,6 +499,53 @@ export interface ProviderModule {
499
499
  * request never fails a launch). Absent → no launch-time model selection for CLI.
500
500
  */
501
501
  modelLaunchArgs?: string[];
502
+ /**
503
+ * BRAIN-ROUTING (model axis): suggested model values for this provider, surfaced
504
+ * as dropdown options in the new-session dialog (e.g. claude ['opus','sonnet',
505
+ * 'haiku']; codex ['gpt-5.5','gpt-5-codex']). Advisory only — the UI allows free
506
+ * text too, so the list going stale never blocks a model the provider accepts.
507
+ */
508
+ modelOptions?: string[];
509
+ /**
510
+ * BRAIN-ROUTING (thinking axis): template for expanding an `initialThinkingLevel`
511
+ * selection into launch args for a CLI provider, parallel to modelLaunchArgs.
512
+ * `{{level}}` is substituted with the provider-appropriate reasoning-effort value
513
+ * (already mapped from the standard low|medium|high level, see thinkingLevelMap).
514
+ * Examples: claude-cli `['--effort', '{{level}}']` → `--effort high`; codex-cli
515
+ * `['-c', 'model_reasoning_effort={{level}}']`. Applied at session launch when
516
+ * `initialThinkingLevel` is passed AND this provider is a plain CLI. A CLI provider
517
+ * with no template silently ignores the thinking level (best-effort; never fails a
518
+ * launch). ACP providers instead route thinking through setConfigOption('thought_level').
519
+ */
520
+ thinkingLaunchArgs?: string[];
521
+ /**
522
+ * BRAIN-ROUTING (thinking axis): optional per-provider mapping from the standard
523
+ * thinking levels (`low`|`medium`|`high`) to this provider's own reasoning-effort
524
+ * vocabulary, used to fill `{{level}}` in thinkingLaunchArgs. e.g. claude-cli might
525
+ * map `{ high: 'max' }`; codex-cli `{ high: 'xhigh' }`. A level absent from the map
526
+ * passes through unchanged (so `medium` → `medium` by default).
527
+ */
528
+ thinkingLevelMap?: Partial<Record<'low' | 'medium' | 'high', string>>;
529
+ /**
530
+ * BRAIN-ROUTING (thinking axis): the reasoning-effort values this provider actually
531
+ * accepts, surfaced as the thinking-level dropdown options in the new-session
532
+ * dialog (e.g. claude ['low','medium','high','max']; codex ['minimal','low',
533
+ * 'medium','high','xhigh']). Absent → the UI falls back to the standard
534
+ * low/medium/high. These are the provider's OWN vocabulary and are passed through
535
+ * verbatim as initialThinkingLevel (not remapped by thinkingLevelMap, which only
536
+ * translates the mesh's standard low/medium/high presets).
537
+ */
538
+ thinkingLevelOptions?: string[];
539
+ /**
540
+ * BRAIN-ROUTING (thinking axis, runtime-control providers): the `controls[].id`
541
+ * of a runtime reasoning-effort control to drive for the thinking level when the
542
+ * provider has no `thinkingLaunchArgs` (e.g. hermes-cli's `reasoning` select,
543
+ * which types `/reasoning <level>` into the PTY via its setScript). At launch,
544
+ * initialThinkingLevel (after thinkingLevelMap) is applied by invoking that
545
+ * control's setScript with `{ value: <level> }`. Ignored if the id doesn't match a
546
+ * control. Providers that use thinkingLaunchArgs don't need this.
547
+ */
548
+ thinkingControlId?: string;
502
549
  /** Delay before submitting typed CLI input (provider-specific TUI tuning) */
503
550
  sendDelayMs?: number;
504
551
  /** Submit key used after typing into CLI PTY (default: carriage return) */
@@ -13,7 +13,7 @@
13
13
  import type { GitRepoStatus, GitCompactSummary } from './git/git-types.js';
14
14
  import type { MeshMissionSummary, MeshMissionSlimSummary } from './mesh/mesh-missions.js';
15
15
  import type { MeshMagiActivitySummary } from './mesh/mesh-magi-status.js';
16
- import type { MagiKindPanelMap } from '@adhdev/mesh-shared';
16
+ import type { MagiKindPanelMap, DifficultyBrainMap } from '@adhdev/mesh-shared';
17
17
  export interface RepoMesh {
18
18
  id: string;
19
19
  name: string;
@@ -372,7 +372,7 @@ export declare function magiAutoLaunchedSessionCleanupDecision(args: {
372
372
  };
373
373
  /** Min/max bounds for the global write-task parallel cap. */
374
374
  export declare const MESH_MAX_PARALLEL_TASKS_MIN = 1;
375
- export declare const MESH_MAX_PARALLEL_TASKS_MAX = 8;
375
+ export declare const MESH_MAX_PARALLEL_TASKS_MAX = 64;
376
376
  /**
377
377
  * Default multiplier applied to the write cap to derive the read-only diagnosis
378
378
  * cap. Read-only (live_debug_readonly) tasks carry no isolation/merge cost so they
@@ -555,6 +555,15 @@ export interface LocalMeshConfig {
555
555
  * Optional; absent on pre-feature configs.
556
556
  */
557
557
  magiKindPanels?: MagiKindPanelMap;
558
+ /**
559
+ * BRAIN-ROUTING: per-task-difficulty brain presets (machine-local), sibling of
560
+ * magiKindPanels. Keyed by difficulty (easy / medium / difficult / freeform);
561
+ * each maps to a BrainSlot (provider? / model? / thinkingLevel?). The coordinator
562
+ * classifies a task's difficulty at enqueue; the matching preset fills in the
563
+ * task's model / thinking level (an explicit task value wins). Optional; a mesh
564
+ * with none seeded uses DEFAULT_DIFFICULTY_BRAINS on first read.
565
+ */
566
+ difficultyBrains?: DifficultyBrainMap;
558
567
  }
559
568
  export interface LocalMeshEntry {
560
569
  id: string;
@@ -420,6 +420,10 @@ export interface AvailableProviderInfo {
420
420
  lastVerification?: MachineProviderCheckResult;
421
421
  /** Provider-declared Repo Mesh coordinator/MCP behavior. */
422
422
  meshCoordinator?: ProviderMeshCoordinatorConfig;
423
+ /** BRAIN-ROUTING: suggested model values for the new-session model dropdown. */
424
+ modelOptions?: string[];
425
+ /** BRAIN-ROUTING: reasoning-effort values for the new-session thinking dropdown. */
426
+ thinkingLevelOptions?: string[];
423
427
  /**
424
428
  * Provider trust classification — derived from the on-disk layer the
425
429
  * manifest came from and the shape of the manifest. Dashboards use
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adhdev/daemon-core",
3
- "version": "0.9.82-rc.482",
3
+ "version": "0.9.82-rc.484",
4
4
  "description": "ADHDev daemon core — CDP, IDE detection, providers, command execution",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -47,8 +47,8 @@
47
47
  "author": "vilmire",
48
48
  "license": "AGPL-3.0-or-later",
49
49
  "dependencies": {
50
- "@adhdev/mesh-shared": "0.9.82-rc.482",
51
- "@adhdev/session-host-core": "0.9.82-rc.482",
50
+ "@adhdev/mesh-shared": "0.9.82-rc.484",
51
+ "@adhdev/session-host-core": "0.9.82-rc.484",
52
52
  "@agentclientprotocol/sdk": "^0.16.1",
53
53
  "ajv": "^8.20.0",
54
54
  "ajv-formats": "^3.0.1",
@@ -276,6 +276,10 @@ type CliStartOptions = {
276
276
  resumeSessionId?: string;
277
277
  settingsOverride?: Record<string, any>;
278
278
  extraEnv?: Record<string, string>;
279
+ /** BRAIN-ROUTING thinking axis: standard level ('low'|'medium'|'high') applied
280
+ * at launch via the provider's thinkingLaunchArgs (CLI) or setConfigOption
281
+ * ('thought_level', ACP). Best-effort — ignored by providers with no support. */
282
+ initialThinkingLevel?: string;
279
283
  };
280
284
 
281
285
  const DEFAULT_COORDINATOR_DELEGATED_ENV_UNSETS = [
@@ -420,10 +424,32 @@ function expandResumeArgs(template: string[] | undefined, sessionId: string): st
420
424
  * there is no template or no model (a model request without a template is a no-op —
421
425
  * see startSession, where the caller logs the skip). MAGI kind-panel model axis.
422
426
  */
423
- function expandModelLaunchArgs(template: string[] | undefined, model: string | undefined): string[] | undefined {
427
+ export function expandModelLaunchArgs(template: string[] | undefined, model: string | undefined): string[] | undefined {
424
428
  const m = typeof model === 'string' ? model.trim() : '';
425
429
  if (!m || !Array.isArray(template) || template.length === 0) return undefined;
426
- return template.map((part) => part === '{{model}}' ? m : part);
430
+ // Substitute {{model}} anywhere in a token, not only when it is the whole token,
431
+ // so templates like ['-c', 'model={{model}}'] (codex) expand as well as the
432
+ // standalone ['--model', '{{model}}'] (claude) form.
433
+ return template.map((part) => part.includes('{{model}}') ? part.split('{{model}}').join(m) : part);
434
+ }
435
+
436
+ /**
437
+ * Expand a provider's `thinkingLaunchArgs` template with the requested thinking
438
+ * level, parallel to expandModelLaunchArgs. The standard level ('low'|'medium'|
439
+ * 'high') is first mapped through the provider's `thinkingLevelMap` (a level absent
440
+ * from the map passes through unchanged), then substituted into every `{{level}}`
441
+ * token. Returns undefined when there is no template or no level (best-effort; a
442
+ * thinking request without a template is a no-op). BRAIN-ROUTING thinking axis.
443
+ */
444
+ export function expandThinkingLaunchArgs(
445
+ template: string[] | undefined,
446
+ level: string | undefined,
447
+ levelMap: Partial<Record<string, string>> | undefined,
448
+ ): string[] | undefined {
449
+ const raw = typeof level === 'string' ? level.trim() : '';
450
+ if (!raw || !Array.isArray(template) || template.length === 0) return undefined;
451
+ const mapped = (levelMap && typeof levelMap[raw] === 'string' && levelMap[raw]!.trim()) ? levelMap[raw]!.trim() : raw;
452
+ return template.map((part) => part.includes('{{level}}') ? part.replace('{{level}}', mapped) : part);
427
453
  }
428
454
 
429
455
  function readSubcommandSessionId(args: string[], subcommands: string[]): string | undefined {
@@ -708,6 +734,9 @@ export class DaemonCliManager {
708
734
  providerSessionId?: string;
709
735
  launchMode?: CliLaunchMode;
710
736
  extraEnv?: Record<string, string>;
737
+ /** BRAIN-ROUTING: post-launch thinking level for runtime-control providers
738
+ * (e.g. hermes reasoning). Passed through to the instance. */
739
+ initialThinkingLevel?: string;
711
740
  /**
712
741
  * On an attach (attachExisting=true), the real spawn time (ms epoch) of the
713
742
  * session-host runtime being restored — a PAST timestamp. Used to restore the
@@ -956,6 +985,19 @@ export class DaemonCliManager {
956
985
  }
957
986
  }
958
987
 
988
+ // Brain routing thinking axis for ACP: route the standard level through the
989
+ // agent's thought_level config option. Best-effort — throws if the agent declares
990
+ // no thought_level category (see setConfigOption), so we swallow and warn.
991
+ if (options?.initialThinkingLevel) {
992
+ const lvl = options.initialThinkingLevel;
993
+ try {
994
+ await acpInstance.setConfigOption('thought_level', lvl);
995
+ console.log(colorize('green', ` 🧠 Initial thinking level set: ${lvl}`));
996
+ } catch (e: any) {
997
+ LOG.warn('CLI', `[ACP] Initial thinking level set failed (provider may not support thought_level): ${e?.message}`);
998
+ }
999
+ }
1000
+
959
1001
  this.persistRecentActivity({
960
1002
  kind: 'acp',
961
1003
  providerType: normalizedType,
@@ -1003,8 +1045,22 @@ export class DaemonCliManager {
1003
1045
  LOG.warn('CLI', `[${normalizedType}] initialModel='${initialModel}' requested but provider declares no modelLaunchArgs template — launching without model selection.`);
1004
1046
  }
1005
1047
 
1048
+ // ─── Thinking axis (brain routing): expand initialThinkingLevel → launch args ───
1049
+ // Parallel to the model axis: a plain CLI provider selects reasoning effort at spawn
1050
+ // via the manifest's thinkingLaunchArgs template ('{{level}}' → the mapped level).
1051
+ // Best-effort; a provider with no template (or no requested level) is a no-op. ACP
1052
+ // providers route thinking through setConfigOption('thought_level') above.
1053
+ const initialThinkingLevel = options?.initialThinkingLevel;
1054
+ const thinkingLaunchArgs = expandThinkingLaunchArgs(provider?.thinkingLaunchArgs, initialThinkingLevel, provider?.thinkingLevelMap);
1055
+ const cliArgsWithBrain = thinkingLaunchArgs
1056
+ ? [...thinkingLaunchArgs, ...(cliArgsWithModel || [])]
1057
+ : cliArgsWithModel;
1058
+ if (initialThinkingLevel && !thinkingLaunchArgs) {
1059
+ LOG.warn('CLI', `[${normalizedType}] initialThinkingLevel='${initialThinkingLevel}' requested but provider declares no thinkingLaunchArgs template — launching without thinking-level selection.`);
1060
+ }
1061
+
1006
1062
  // ─── Resolve launch options → provider session binding ───
1007
- const sessionBinding = resolveCliSessionBinding(provider, normalizedType, cliArgsWithModel, options?.resumeSessionId);
1063
+ const sessionBinding = resolveCliSessionBinding(provider, normalizedType, cliArgsWithBrain, options?.resumeSessionId);
1008
1064
  const resolvedCliArgs = sessionBinding.cliArgs;
1009
1065
 
1010
1066
  // If InstanceManager exists, manage as CliProviderInstance unified
@@ -1024,6 +1080,10 @@ export class DaemonCliManager {
1024
1080
  providerSessionId: sessionBinding.providerSessionId,
1025
1081
  launchMode: sessionBinding.launchMode,
1026
1082
  extraEnv: options?.extraEnv,
1083
+ // BRAIN-ROUTING: for a provider with no thinkingLaunchArgs but a
1084
+ // runtime reasoning control (hermes), apply the level post-launch.
1085
+ // The launch-arg providers (claude/codex) already consumed it at spawn.
1086
+ ...(options?.initialThinkingLevel && !provider?.thinkingLaunchArgs ? { initialThinkingLevel: options.initialThinkingLevel } : {}),
1027
1087
  onProviderSessionResolved: ({ providerSessionId, providerName, providerType, workspace }) => {
1028
1088
  this.persistRecentActivity({
1029
1089
  kind: 'cli',
@@ -1486,6 +1546,7 @@ export class DaemonCliManager {
1486
1546
  resumeSessionId: args?.resumeSessionId,
1487
1547
  settingsOverride,
1488
1548
  extraEnv: delegatedLaunch ? delegatedLaunch.env : args?.env,
1549
+ ...(typeof args?.initialThinkingLevel === 'string' && args.initialThinkingLevel.trim() ? { initialThinkingLevel: args.initialThinkingLevel.trim() } : {}),
1489
1550
  },
1490
1551
  );
1491
1552
 
@@ -8,6 +8,59 @@
8
8
  import type { LowFamilyContext, LowFamilyHandler } from './types.js';
9
9
 
10
10
  export const coordinatorPromptHandlers: Record<string, LowFamilyHandler> = {
11
+ /**
12
+ * Render the coordinator system prompt for a mesh + CLI type, so the
13
+ * dashboard can show the operator exactly what a coordinator session
14
+ * receives by default. This resolves the mesh, applies its repo-mesh
15
+ * config, and runs the SAME buildCoordinatorSystemPrompt the launch path
16
+ * uses — minus the runtime-only best-effort sections (mission / recent
17
+ * activity / operating notes), which are launch-scope and not part of the
18
+ * static "default base" an operator is trying to preview here.
19
+ *
20
+ * It respects mesh-level and user-file override/append layering, so the
21
+ * preview reflects the effective prompt: with no overrides configured it
22
+ * shows the pure daemon default; with an override set it shows that.
23
+ */
24
+ coordinator_prompt_preview: async (ctx: LowFamilyContext, args: any) => {
25
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
26
+ const cliType = typeof args?.cliType === 'string' && args.cliType.trim() ? args.cliType.trim() : 'claude-cli';
27
+ if (!meshId) return { success: false, error: 'meshId required' };
28
+ try {
29
+ // Prefer the router-bound resolver (inline cache aware); fall back to
30
+ // local config when a bare context is used (e.g. unit tests).
31
+ let mesh: any = null;
32
+ if (ctx.getMeshForCommand) {
33
+ const resolved = await ctx.getMeshForCommand(meshId);
34
+ mesh = resolved?.mesh ?? null;
35
+ }
36
+ if (!mesh) {
37
+ const { getMesh } = await import('../../config/mesh-config.js');
38
+ mesh = getMesh(meshId);
39
+ }
40
+ if (!mesh) return { success: false, error: `mesh not found: ${meshId}` };
41
+
42
+ // Apply the on-disk repo-mesh config overlay exactly as launch does,
43
+ // so policy/nodes reflect the effective mesh.
44
+ let effectiveMesh = mesh;
45
+ try {
46
+ const { loadRepoMeshJsonConfig, applyRepoMeshConfig } = await import('../../config/mesh-json-config.js');
47
+ const workspace = typeof mesh?.workspace === 'string' ? mesh.workspace : undefined;
48
+ if (workspace) {
49
+ const loaded = loadRepoMeshJsonConfig(workspace);
50
+ if (loaded?.sourceType !== 'invalid') {
51
+ effectiveMesh = applyRepoMeshConfig(mesh, loaded?.config);
52
+ }
53
+ }
54
+ } catch { /* overlay is best-effort — fall back to the raw mesh */ }
55
+
56
+ const { buildCoordinatorSystemPrompt } = await import('../../mesh/coordinator-prompt.js');
57
+ const prompt = buildCoordinatorSystemPrompt({ mesh: effectiveMesh, coordinatorCliType: cliType });
58
+ return { success: true, prompt, cliType, meshId, bytes: Buffer.byteLength(prompt, 'utf8') };
59
+ } catch (error: any) {
60
+ return { success: false, error: error?.message || String(error) };
61
+ }
62
+ },
63
+
11
64
  list_coordinator_prompts: async (_ctx: LowFamilyContext, _args: any) => {
12
65
  const fs = await import('node:fs');
13
66
  const path = await import('node:path');
@@ -457,6 +457,30 @@ export const meshCrudHandlers: Record<string, MedFamilyHandler> = {
457
457
  }
458
458
  },
459
459
 
460
+ // ─── Brain routing: per-difficulty brain presets (machine-local) ───
461
+ // getDifficultyBrains returns the seeded defaults when nothing is configured,
462
+ // so the editor always shows a usable mapping. set replaces the whole map.
463
+ difficulty_brains_get: async (_ctx: MedFamilyContext, _args: any) => {
464
+ try {
465
+ const { getDifficultyBrains } = await import('../../config/mesh-config.js');
466
+ return { success: true, difficultyBrains: getDifficultyBrains() };
467
+ } catch (e: any) {
468
+ return { success: false, error: e.message };
469
+ }
470
+ },
471
+
472
+ difficulty_brains_set: async (_ctx: MedFamilyContext, args: any) => {
473
+ try {
474
+ const { setDifficultyBrains } = await import('../../config/mesh-config.js');
475
+ // normalizeDifficultyBrainMap (inside setDifficultyBrains) drops unknown
476
+ // keys and empty slots. An empty result clears the override → defaults.
477
+ const difficultyBrains = setDifficultyBrains(args?.difficultyBrains);
478
+ return { success: true, difficultyBrains };
479
+ } catch (e: any) {
480
+ return { success: false, error: e.message };
481
+ }
482
+ },
483
+
460
484
  add_mesh_node: async (ctx: MedFamilyContext, args: any) => {
461
485
  const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
462
486
  const workspace = typeof args?.workspace === 'string' ? args.workspace.trim() : '';
@@ -480,6 +504,9 @@ export const meshCrudHandlers: Record<string, MedFamilyHandler> = {
480
504
  const daemonId = typeof args?.daemonId === 'string' && args.daemonId.trim() ? args.daemonId.trim() : undefined;
481
505
  const machineId = typeof args?.machineId === 'string' && args.machineId.trim() ? args.machineId.trim() : undefined;
482
506
  const repoRoot = typeof args?.repoRoot === 'string' && args.repoRoot.trim() ? args.repoRoot.trim() : undefined;
507
+ const capabilities = Array.isArray(args?.capabilities)
508
+ ? args.capabilities.map((t: any) => typeof t === 'string' ? t.trim() : '').filter(Boolean)
509
+ : undefined;
483
510
  const node = addNode(meshId, {
484
511
  workspace,
485
512
  ...(repoRoot ? { repoRoot } : {}),
@@ -487,6 +514,7 @@ export const meshCrudHandlers: Record<string, MedFamilyHandler> = {
487
514
  ...(machineId ? { machineId } : {}),
488
515
  ...(policy ? { policy } : {}),
489
516
  ...(role ? { role } : {}),
517
+ ...(capabilities && capabilities.length ? { capabilities } : {}),
490
518
  });
491
519
  if (!node) return { success: false, error: 'Mesh not found' };
492
520
  // mesh_status hands back a coordinator-memory aggregate
@@ -543,6 +571,13 @@ export const meshCrudHandlers: Record<string, MedFamilyHandler> = {
543
571
  } else if (args?.systemPrompt === null) {
544
572
  patch.systemPrompt = undefined;
545
573
  }
574
+ // Operator custom capability tags. An explicit (possibly empty) array
575
+ // replaces them; omitting the arg leaves existing tags untouched.
576
+ if (Array.isArray(args?.capabilities)) {
577
+ patch.capabilities = args.capabilities
578
+ .map((t: any) => typeof t === 'string' ? t.trim() : '')
579
+ .filter(Boolean);
580
+ }
546
581
  const node = updateNode(meshId, nodeId, patch as any);
547
582
  if (!node) return { success: false, error: 'Mesh node not found' };
548
583
  // Provider priority / systemPrompt changes don't touch
@@ -22,7 +22,8 @@ import type {
22
22
  RepoMeshHostMetadata,
23
23
  RepoMeshDaemonRole,
24
24
  } from '../repo-mesh-types.js';
25
- import type { MagiKindPanelMap, MagiSlot, MagiTaskKind } from '@adhdev/mesh-shared';
25
+ import type { MagiKindPanelMap, MagiSlot, MagiTaskKind, DifficultyBrainMap } from '@adhdev/mesh-shared';
26
+ import { normalizeDifficultyBrainMap, DEFAULT_DIFFICULTY_BRAINS } from '@adhdev/mesh-shared';
26
27
  import { mergeAndNormalizePolicy } from '../repo-mesh-types.js';
27
28
  import { createDefaultMeshHostMetadata } from '../mesh/mesh-host-ownership.js';
28
29
 
@@ -570,6 +571,11 @@ export function updateNode(
570
571
  opts: {
571
572
  userOverrides?: Partial<RepoMeshNodeCapabilities>;
572
573
  policy?: RepoMeshNodePolicy;
574
+ /** Operator-defined custom capability tags used by mesh queue matching.
575
+ * Passing an array replaces the node's custom tags (empty/whitespace
576
+ * entries dropped, deduped); an empty result clears them. Omit to leave
577
+ * the existing tags untouched. */
578
+ capabilities?: string[];
573
579
  worktreeBootstrap?: LocalMeshNodeEntry['worktreeBootstrap'];
574
580
  /** Per-node instruction surfaced in the coordinator prompt. Pass an
575
581
  * empty string or undefined to clear it. */
@@ -610,6 +616,13 @@ export function updateNode(
610
616
  node.reportedDaemonBuildVersion = opts.reportedDaemonBuildVersion.trim();
611
617
  }
612
618
  if (opts.policy) node.policy = { ...node.policy, ...opts.policy };
619
+ if (Object.prototype.hasOwnProperty.call(opts, 'capabilities')) {
620
+ // Explicit replace: normalize (trim/dedup/drop-empties); an empty result
621
+ // clears the tags entirely so the field never persists as [].
622
+ const tags = normalizeCapabilityTags(opts.capabilities);
623
+ if (tags && tags.length) node.capabilities = tags;
624
+ else delete node.capabilities;
625
+ }
613
626
  if (opts.worktreeBootstrap) node.worktreeBootstrap = opts.worktreeBootstrap;
614
627
  if (Object.prototype.hasOwnProperty.call(opts, 'systemPrompt')) {
615
628
  // Honor explicit clears: { systemPrompt: undefined } drops the field.
@@ -731,3 +744,31 @@ export function removeMagiKindPanel(kind: string): boolean {
731
744
  saveMeshConfig(stored);
732
745
  return true;
733
746
  }
747
+
748
+ // ─── Brain routing: per-difficulty brain presets (machine-local) ───
749
+
750
+ /**
751
+ * The difficulty→brain presets, machine-local. When nothing is configured yet,
752
+ * returns the sensible DEFAULT_DIFFICULTY_BRAINS so the coordinator always has a
753
+ * usable mapping (the operator can override via setDifficultyBrains). Returns a
754
+ * normalized copy — never the stored reference.
755
+ */
756
+ export function getDifficultyBrains(): DifficultyBrainMap {
757
+ const stored = loadMeshConfig().difficultyBrains;
758
+ const normalized = normalizeDifficultyBrainMap(stored);
759
+ return Object.keys(normalized).length > 0 ? normalized : { ...DEFAULT_DIFFICULTY_BRAINS };
760
+ }
761
+
762
+ /**
763
+ * Replace the difficulty→brain presets wholesale (the editor pushes the full map).
764
+ * Passing an empty/normalized-empty map clears the override, so getDifficultyBrains
765
+ * falls back to the defaults again. Returns the normalized, persisted map.
766
+ */
767
+ export function setDifficultyBrains(map: unknown): DifficultyBrainMap {
768
+ const normalized = normalizeDifficultyBrainMap(map);
769
+ const stored = loadMeshConfig();
770
+ if (Object.keys(normalized).length > 0) stored.difficultyBrains = normalized;
771
+ else delete stored.difficultyBrains;
772
+ saveMeshConfig(stored);
773
+ return normalized;
774
+ }