@cortex-agent/server 2026.9.21 → 2026.9.25

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.
Files changed (139) hide show
  1. package/defaults/config/thread-templates/agents/creative.json +17 -0
  2. package/defaults/prompts/systemPrompts/creative.md +13 -0
  3. package/defaults/prompts/systemPrompts/direct.md +1 -1
  4. package/dist/agent-adapter/claude/adapter.d.ts +12 -0
  5. package/dist/agent-adapter/claude/adapter.js +19 -1
  6. package/dist/agent-adapter/claude/spawn-args.d.ts +7 -0
  7. package/dist/agent-adapter/claude/spawn-args.js +10 -0
  8. package/dist/agent-adapter/pi/child-runner.d.ts +4 -2
  9. package/dist/agent-adapter/pi/child-runner.js +5 -1
  10. package/dist/agent-adapter/pi/event-parser.d.ts +3 -2
  11. package/dist/agent-adapter/pi/event-parser.js +46 -2
  12. package/dist/agent-adapter/pi/extensions.d.ts +7 -1
  13. package/dist/agent-adapter/pi/extensions.js +10 -3
  14. package/dist/agent-adapter/pi/mcp-bridge.js +8 -8
  15. package/dist/agent-adapter/pi/pi-session.js +5 -0
  16. package/dist/agent-adapter/pi/runtime.js +3 -0
  17. package/dist/agent-adapter/pi/session-options.js +5 -1
  18. package/dist/agent-adapter/pi/subagent.d.ts +15 -3
  19. package/dist/agent-adapter/pi/subagent.js +18 -0
  20. package/dist/agent-adapter/pi/tool-shims.d.ts +6 -1
  21. package/dist/agent-adapter/pi/tool-shims.js +34 -1
  22. package/dist/agent-adapter/types.d.ts +5 -0
  23. package/dist/core/agents/subagent/types.d.ts +3 -0
  24. package/dist/core/config-generator.js +17 -2
  25. package/dist/core/debug-mode.d.ts +11 -10
  26. package/dist/core/debug-mode.js +12 -18
  27. package/dist/core/exec-async.d.ts +26 -0
  28. package/dist/core/exec-async.js +47 -0
  29. package/dist/core/locales/en.d.ts +14 -1
  30. package/dist/core/locales/slices/commands.d.ts +12 -1
  31. package/dist/core/locales/slices/commands.js +24 -2
  32. package/dist/core/locales/slices/startup.d.ts +2 -0
  33. package/dist/core/locales/slices/startup.js +4 -0
  34. package/dist/core/rebuild-progress.d.ts +58 -0
  35. package/dist/core/rebuild-progress.js +103 -0
  36. package/dist/core/resilient-watch.js +5 -3
  37. package/dist/core/run-registry.d.ts +7 -0
  38. package/dist/core/run-registry.js +6 -0
  39. package/dist/core/types/thread-types.d.ts +23 -4
  40. package/dist/domain/agents/agent-state.d.ts +7 -0
  41. package/dist/domain/agents/agent-state.js +9 -1
  42. package/dist/domain/agents/agent-switch.d.ts +38 -0
  43. package/dist/domain/agents/agent-switch.js +106 -0
  44. package/dist/domain/agents/config.d.ts +20 -2
  45. package/dist/domain/agents/config.js +58 -4
  46. package/dist/domain/agents/index.d.ts +1 -0
  47. package/dist/domain/agents/index.js +1 -0
  48. package/dist/domain/agents/profile-manager.d.ts +6 -0
  49. package/dist/domain/agents/profile-manager.js +14 -1
  50. package/dist/domain/executions/registry.d.ts +2 -0
  51. package/dist/domain/executions/registry.js +84 -7
  52. package/dist/domain/plugins/runtime.js +1 -1
  53. package/dist/domain/plugins/skill-projection.d.ts +8 -2
  54. package/dist/domain/plugins/skill-projection.js +76 -19
  55. package/dist/domain/remote/client-bootstrap.js +1 -1
  56. package/dist/domain/remote/client-hot-reload.d.ts +1 -1
  57. package/dist/domain/remote/client-hot-reload.js +27 -23
  58. package/dist/domain/runs/engine-spec.js +4 -0
  59. package/dist/domain/runs/request.d.ts +6 -0
  60. package/dist/domain/runs/run.js +1 -0
  61. package/dist/domain/runs/spec-loader.d.ts +4 -3
  62. package/dist/domain/runs/spec-loader.js +4 -3
  63. package/dist/domain/scheduling/jobs/sync-public.js +6 -6
  64. package/dist/domain/scheduling/scheduler.js +14 -12
  65. package/dist/domain/sessions/session-lifecycle.d.ts +5 -0
  66. package/dist/domain/sessions/session-lifecycle.js +13 -1
  67. package/dist/domain/system/rebuild-hold.d.ts +44 -0
  68. package/dist/domain/system/rebuild-hold.js +91 -0
  69. package/dist/domain/system/server-update-check.d.ts +2 -1
  70. package/dist/domain/system/server-update-check.js +15 -13
  71. package/dist/domain/tasks/archiver.js +21 -13
  72. package/dist/domain/tasks/mutator.js +60 -59
  73. package/dist/domain/tasks/system/task-completion.d.ts +7 -2
  74. package/dist/domain/tasks/system/task-completion.js +69 -6
  75. package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +6 -1
  76. package/dist/domain/tasks/system/task-lifecycle-edit.js +21 -2
  77. package/dist/domain/tasks/system/task-lock.d.ts +23 -0
  78. package/dist/domain/tasks/system/task-lock.js +29 -1
  79. package/dist/domain/tasks/system/task-mutations.d.ts +14 -1
  80. package/dist/domain/tasks/system/task-mutations.js +25 -2
  81. package/dist/domain/tasks/system/task-state.d.ts +12 -1
  82. package/dist/domain/tasks/system/task-state.js +19 -2
  83. package/dist/domain/threads/prompt-builder.d.ts +9 -6
  84. package/dist/domain/threads/prompt-builder.js +28 -10
  85. package/dist/domain/threads/runner.js +7 -3
  86. package/dist/domain/threads/state-machine.js +15 -11
  87. package/dist/domain/threads/template-loader.js +6 -4
  88. package/dist/domain/threads/template-validate.d.ts +43 -6
  89. package/dist/domain/threads/template-validate.js +12 -0
  90. package/dist/domain/ui-service/app-router.d.ts +10 -0
  91. package/dist/domain/ui-service/app-router.js +2 -1
  92. package/dist/domain/ui-service/input-schemas.d.ts +11 -0
  93. package/dist/domain/ui-service/input-schemas.js +11 -0
  94. package/dist/domain/ui-service/mutate/sessions.d.ts +2 -1
  95. package/dist/domain/ui-service/mutate/sessions.js +40 -0
  96. package/dist/domain/ui-service/mutate/tasks.js +4 -3
  97. package/dist/domain/ui-service/query/config.js +19 -1
  98. package/dist/domain/ui-service/query/memory.js +28 -34
  99. package/dist/domain/ui-service/query/sessions.js +89 -12
  100. package/dist/domain/ui-service/query/system.js +19 -0
  101. package/dist/domain/ui-service/query-input-schemas.d.ts +1 -0
  102. package/dist/domain/ui-service/query-input-schemas.js +2 -0
  103. package/dist/domain/ui-service/types.d.ts +97 -3
  104. package/dist/domain/ui-service/ui-service.js +2 -1
  105. package/dist/entry/app.js +23 -4
  106. package/dist/entry/daemon-notice.d.ts +10 -1
  107. package/dist/entry/daemon-notice.js +16 -1
  108. package/dist/entry/daemon.d.ts +43 -2
  109. package/dist/entry/daemon.js +163 -9
  110. package/dist/orchestration/agent-runner.js +16 -0
  111. package/dist/orchestration/conversation-request.d.ts +33 -0
  112. package/dist/orchestration/conversation-request.js +78 -16
  113. package/dist/orchestration/mid-turn-inject.d.ts +3 -0
  114. package/dist/orchestration/mid-turn-inject.js +9 -4
  115. package/dist/orchestration/resume-dispatcher.js +4 -2
  116. package/dist/orchestration/routing/commands/mode.js +114 -63
  117. package/dist/orchestration/thread-executor.js +13 -0
  118. package/dist/orchestration/turn/turn.js +1 -0
  119. package/dist/store/conversation-display-projection.d.ts +9 -1
  120. package/dist/store/conversation-display-projection.js +13 -6
  121. package/dist/store/conversation-history-reader.d.ts +19 -0
  122. package/dist/store/conversation-history-reader.js +163 -44
  123. package/dist/store/conversation-history-repo.d.ts +37 -10
  124. package/dist/store/conversation-history-repo.js +161 -139
  125. package/dist/store/session-registry-journal.d.ts +4 -0
  126. package/dist/store/session-registry-journal.js +4 -0
  127. package/dist/store/session-registry-repo.d.ts +2 -1
  128. package/dist/store/session-registry-repo.js +2 -0
  129. package/dist/store/task-repo.d.ts +6 -3
  130. package/dist/store/task-repo.js +26 -10
  131. package/package.json +2 -1
  132. package/web/dist/AGENTS.md +10 -0
  133. package/web/dist/assets/index-B1dBi8Za.css +1 -0
  134. package/web/dist/assets/{index-DZTuqUO4.js → index-BAeLybF0.js} +1 -1
  135. package/web/dist/assets/index-BcQI8Fh5.js +445 -0
  136. package/web/dist/index.html +12 -4
  137. package/web/dist/theme.css +211 -40
  138. package/web/dist/assets/index-CwwQNMpP.css +0 -1
  139. package/web/dist/assets/index-DLSfgq3o.js +0 -444
@@ -6,7 +6,9 @@ const log = createLogger('agent-state');
6
6
  const STATE_FILE = path.join(STORE_DIR, 'agent-state.json');
7
7
  const LEGACY_FILE = path.join(STORE_DIR, 'mode.json');
8
8
  function emptyState() {
9
- return { activeProfile: null, channelProfiles: {}, defaultAgent: null, channelOverrides: {} };
9
+ return {
10
+ activeProfile: null, channelProfiles: {}, defaultAgent: null, channelAgents: {}, channelOverrides: {},
11
+ };
10
12
  }
11
13
  function record(value) {
12
14
  return value && typeof value === 'object' && !Array.isArray(value)
@@ -50,6 +52,9 @@ function parseSelectionDefault(value) {
50
52
  const profileName = record(value).profileName;
51
53
  if (typeof profileName === 'string' && profileName)
52
54
  seed.profileName = profileName;
55
+ const agentName = record(value).agentName;
56
+ if (typeof agentName === 'string' && agentName)
57
+ seed.agentName = agentName;
53
58
  return Object.keys(seed).length > 0 ? seed : undefined;
54
59
  }
55
60
  /** Parse either file shape into one state. Unknown and malformed fields collapse to the empty
@@ -63,6 +68,7 @@ function parseState(raw) {
63
68
  state.channelProfiles = stringMap(data.channelProfiles);
64
69
  if (typeof data.defaultAgent === 'string' && data.defaultAgent)
65
70
  state.defaultAgent = data.defaultAgent;
71
+ state.channelAgents = stringMap(data.channelAgents);
66
72
  state.channelOverrides = overrideMap(data.channelOverrides);
67
73
  // Assigned only when there is one: an explicit `selectionDefault: undefined` key is still a key,
68
74
  // and every caller here compares whole states.
@@ -123,6 +129,8 @@ export function saveAgentState(state) {
123
129
  data.channelProfiles = state.channelProfiles;
124
130
  if (state.defaultAgent)
125
131
  data.defaultAgent = state.defaultAgent;
132
+ if (Object.keys(state.channelAgents).length > 0)
133
+ data.channelAgents = state.channelAgents;
126
134
  if (Object.keys(state.channelOverrides).length > 0)
127
135
  data.channelOverrides = state.channelOverrides;
128
136
  if (state.selectionDefault && Object.keys(state.selectionDefault).length > 0) {
@@ -0,0 +1,38 @@
1
+ export type SwitchAgentFailure = 'unknown-agent' | 'cross-backend-live-session';
2
+ export interface SwitchAgentSuccess {
3
+ ok: true;
4
+ /** The agent the channel now runs. */
5
+ agentName: string;
6
+ /** The profile that agent will actually run under — its own when it pins one, otherwise the
7
+ * channel's. FOR DISPLAY ONLY: the run path re-resolves it every turn, and this rule never
8
+ * writes `channelProfiles` (a pinned profile is already an override there). */
9
+ effectiveProfile: string;
10
+ /** True when the switch moved to a different backend (only possible on a fresh session). */
11
+ backendChanged: boolean;
12
+ }
13
+ export interface SwitchAgentRefusal {
14
+ ok: false;
15
+ reason: SwitchAgentFailure;
16
+ /** The channel's effective backend before the switch; absent when the agent was unknown. */
17
+ currentBackend?: string;
18
+ /** The backend the agent would have run on; absent when the agent was unknown. */
19
+ targetBackend?: string;
20
+ }
21
+ export type SwitchAgentResult = SwitchAgentSuccess | SwitchAgentRefusal;
22
+ /**
23
+ * Switch the agent for a channel/session under the shared switch rule.
24
+ *
25
+ * Takes effect on the NEXT turn, like `!model`: the EngineSpec changes identity, so `SessionEngines`
26
+ * restarts the process with `--resume` and the conversation keeps its history under the new prompt
27
+ * and tool surface. Nothing is reset.
28
+ *
29
+ * The cross-backend refusal is {@link decideProfileSwitch}, unchanged — an agent that pins a
30
+ * profile on the other backend is a backend move wearing a different hat, and a live conversation
31
+ * cannot be resumed there.
32
+ */
33
+ export declare function switchChannelAgent(opts: {
34
+ channel: string;
35
+ name: string;
36
+ }): Promise<SwitchAgentResult>;
37
+ /** Drop the channel's agent selection: it follows the global default again, from the next turn. */
38
+ export declare function clearChannelAgentSelection(channel: string): Promise<void>;
@@ -0,0 +1,106 @@
1
+ // input: template-loader (getAgent) + config (getDefaultAgent/setDefaultAgent/clearChannelAgent/
2
+ // resolveBackendForChannel) + profile-manager (resolveProfileConfig) + profile-switch
3
+ // (decideProfileSwitch/channelHasHistory) + session-registry-repo (record sync)
4
+ // output: switchChannelAgent / clearChannelAgentSelection — the composed "switch the agent for a
5
+ // channel/session" rule used by the `!agent` command AND the Web UI, so the rule has ONE
6
+ // source of truth.
7
+ // pos: domain/agents — the environment twin of profile-switch.ts. An agent decides the
8
+ // conversation's prompt, tools, skills and rules; a profile decides its model. The two are
9
+ // independent axes, so switching an agent writes the agent map and nothing else — but they
10
+ // meet at the backend, because an agent that pins a profile pins that profile's backend,
11
+ // and a live conversation can no more move across backends this way than through `!profile`.
12
+ import { sessionStore } from '../../store/session-registry-repo.js';
13
+ import { clearChannelAgent, getActiveProfile, resolveBackendForChannel, setDefaultAgent, setSelectionDefaultAgent, } from './config.js';
14
+ import { resolveProfileConfig } from './profile-manager.js';
15
+ import { channelHasHistory, decideProfileSwitch } from './profile-switch.js';
16
+ // The template loader, not the `@domain/threads` barrel: the barrel re-exports prompt-builder,
17
+ // which imports this domain back, and the cycle would be real at module-init time.
18
+ import { getAgent } from '../threads/template-loader.js';
19
+ /**
20
+ * The backend an agent runs on for a given channel: its own profile's when it pins one, else the
21
+ * channel's — an `__active__` agent follows whatever the channel already resolves to, so it can
22
+ * never move the backend by itself.
23
+ */
24
+ function targetBackendOf(agentProfile, currentBackend) {
25
+ if (agentProfile === '__active__')
26
+ return currentBackend;
27
+ try {
28
+ return resolveProfileConfig(agentProfile).backend;
29
+ }
30
+ catch {
31
+ // A pinned profile that no longer exists cannot state a backend; the channel's own answer is
32
+ // the honest one, and the run path reports the bad name when the turn opens.
33
+ return currentBackend;
34
+ }
35
+ }
36
+ /**
37
+ * Switch the agent for a channel/session under the shared switch rule.
38
+ *
39
+ * Takes effect on the NEXT turn, like `!model`: the EngineSpec changes identity, so `SessionEngines`
40
+ * restarts the process with `--resume` and the conversation keeps its history under the new prompt
41
+ * and tool surface. Nothing is reset.
42
+ *
43
+ * The cross-backend refusal is {@link decideProfileSwitch}, unchanged — an agent that pins a
44
+ * profile on the other backend is a backend move wearing a different hat, and a live conversation
45
+ * cannot be resumed there.
46
+ */
47
+ export async function switchChannelAgent(opts) {
48
+ const { channel, name } = opts;
49
+ const agent = getAgent(name);
50
+ if (!agent)
51
+ return { ok: false, reason: 'unknown-agent' };
52
+ const currentBackend = resolveBackendForChannel(channel);
53
+ const targetBackend = targetBackendOf(agent.profile, currentBackend);
54
+ const decision = decideProfileSwitch({
55
+ currentBackend, targetBackend, hasHistory: await channelHasHistory(channel),
56
+ });
57
+ if (!decision.allowed) {
58
+ return { ok: false, reason: 'cross-backend-live-session', currentBackend, targetBackend };
59
+ }
60
+ setDefaultAgent(name, channel);
61
+ seedNextConversation(channel, name);
62
+ await syncSessionAgent(channel, name);
63
+ return {
64
+ ok: true,
65
+ agentName: name,
66
+ effectiveProfile: agent.profile === '__active__' ? resolveChannelProfileName(channel) : agent.profile,
67
+ backendChanged: decision.backendChanged,
68
+ };
69
+ }
70
+ /** Drop the channel's agent selection: it follows the global default again, from the next turn. */
71
+ export async function clearChannelAgentSelection(channel) {
72
+ clearChannelAgent(channel);
73
+ seedNextConversation(channel, null);
74
+ await syncSessionAgent(channel, null);
75
+ }
76
+ /** A pick made in the app says how the user wants to work, so the NEXT new conversation opens in
77
+ * the same environment. Direct (`web:`) channels only, for the reason `applyChannelSelection`
78
+ * gives: an `!agent` in some Slack thread is a tool for that thread. */
79
+ function seedNextConversation(channel, agentName) {
80
+ if (channel.startsWith('web:'))
81
+ setSelectionDefaultAgent(agentName);
82
+ }
83
+ /** Keep the session-registry record in lock-step (best-effort), so the Web session list and
84
+ * `!resume` report the agent the channel is on. The channel map is the runtime source of truth;
85
+ * a failure here costs a label, not the switch. */
86
+ async function syncSessionAgent(channel, agentName) {
87
+ try {
88
+ const sessionName = await sessionStore.getActiveSessionName(channel);
89
+ if (sessionName)
90
+ await sessionStore.updateSession(sessionName, { agentName });
91
+ }
92
+ catch {
93
+ // non-fatal — see above
94
+ }
95
+ }
96
+ /** The profile name an `__active__` agent displays: whatever the channel itself resolves to. */
97
+ function resolveChannelProfileName(channel) {
98
+ try {
99
+ return resolveProfileConfig(getActiveProfile(channel)).name;
100
+ }
101
+ catch {
102
+ // No profile resolvable at all (profiles.json unreadable) — say what the agent declares rather
103
+ // than inventing a name the run would not use.
104
+ return '__active__';
105
+ }
106
+ }
@@ -62,6 +62,9 @@ export declare function setChannelOverride(channel: string, patch: Partial<Recor
62
62
  * seed then carries a profile and no overrides.
63
63
  */
64
64
  export declare function setSelectionDefault(seed: SelectionDefault | null): void;
65
+ /** Remember the composer's AGENT pick in the same seed, leaving the engine half alone. A null name
66
+ * records "the next conversation opens on the global default", which is a choice like any other. */
67
+ export declare function setSelectionDefaultAgent(agentName: string | null): void;
65
68
  /** The seed for the next conversation, or null when nothing has been picked on this host yet. */
66
69
  export declare function getSelectionDefault(): SelectionDefault | null;
67
70
  /** Drop every override the channel carries — what an explicit "run this profile as declared"
@@ -73,8 +76,23 @@ export declare function setChannelModelOverride(channel: string, model: string |
73
76
  /** The channel-scoped thinking level `!thinking` writes — the chat twin of the composer's picker.
74
77
  * Clearing drops ONLY the level: a model chosen separately was a separate decision. */
75
78
  export declare function setChannelThinkingOverride(channel: string, thinking: string | null): void;
76
- export declare function getDefaultAgent(): string | null;
77
- export declare function setDefaultAgent(name: string | null): void;
79
+ /**
80
+ * The agent a channel runs: its own selection, else the global default. Null when neither is set
81
+ * and the caller's own fallback applies.
82
+ *
83
+ * The channel layer is what makes an agent a per-conversation choice rather than a daemon-wide
84
+ * one — the same shape `getActiveProfile` has, and deliberately so: profile and agent are two
85
+ * independent axes (which model vs which environment) and each has its own channel map.
86
+ */
87
+ export declare function getDefaultAgent(channel?: string): string | null;
88
+ /** Set the agent for one channel (`channel` given) or the global default (omitted). A null name
89
+ * clears: for a channel that means "follow the global default again", globally it means "no
90
+ * default agent at all". */
91
+ export declare function setDefaultAgent(name: string | null, channel?: string): void;
92
+ /** Drop the channel's agent selection — it follows the global default again. */
93
+ export declare function clearChannelAgent(channel: string): void;
94
+ /** Every channel that has selected an agent of its own. */
95
+ export declare function getChannelAgents(): Record<string, string>;
78
96
  export declare function isApiRateLimitError(errorMessage: string | null | undefined): boolean;
79
97
  export declare function isRetryableResult(result: {
80
98
  rateLimited?: boolean;
@@ -207,6 +207,7 @@ let agentState = loadAgentState();
207
207
  let activeProfile = agentState.activeProfile;
208
208
  let channelProfiles = agentState.channelProfiles;
209
209
  let defaultAgent = agentState.defaultAgent;
210
+ let channelAgents = agentState.channelAgents;
210
211
  // Seeded from the migrated state so a CLI process that never reaches the daemon's composition root
211
212
  // still has a value; `entry/app.ts` overwrites it at boot with the default profile's model, which
212
213
  // is the D5-correct answer. Read by PI's subagent catalog and the MCP tool context.
@@ -219,7 +220,7 @@ process.env.CORTEX_CLAUDE_MODEL = agentState.claudeModel || DEFAULT_CLAUDE_MODEL
219
220
  * which is exactly what a rollback to an older build should find, since this build never
220
221
  * acted on them either. */
221
222
  function persist() {
222
- agentState = { ...agentState, activeProfile, channelProfiles, defaultAgent };
223
+ agentState = { ...agentState, activeProfile, channelProfiles, defaultAgent, channelAgents };
223
224
  saveAgentState(agentState);
224
225
  }
225
226
  function saveModeFile(profile = activeProfile, agent = defaultAgent) {
@@ -347,7 +348,26 @@ export function setChannelOverride(channel, patch) {
347
348
  * seed then carries a profile and no overrides.
348
349
  */
349
350
  export function setSelectionDefault(seed) {
350
- agentState = { ...agentState, selectionDefault: seed ?? undefined };
351
+ // The agent is carried forward: the engine seed and the environment seed are two different picks,
352
+ // and choosing a model is not a statement about which environment the next conversation opens in.
353
+ // `setSelectionDefaultAgent` is the only writer of that half.
354
+ const agentName = agentState.selectionDefault?.agentName;
355
+ const next = seed && agentName && !seed.agentName ? { ...seed, agentName } : seed;
356
+ agentState = { ...agentState, selectionDefault: next ?? undefined };
357
+ persist();
358
+ }
359
+ /** Remember the composer's AGENT pick in the same seed, leaving the engine half alone. A null name
360
+ * records "the next conversation opens on the global default", which is a choice like any other. */
361
+ export function setSelectionDefaultAgent(agentName) {
362
+ const seed = { ...(agentState.selectionDefault ?? {}) };
363
+ if (agentName)
364
+ seed.agentName = agentName;
365
+ else
366
+ delete seed.agentName;
367
+ agentState = {
368
+ ...agentState,
369
+ selectionDefault: Object.keys(seed).length > 0 ? seed : undefined,
370
+ };
351
371
  persist();
352
372
  }
353
373
  /** The seed for the next conversation, or null when nothing has been picked on this host yet. */
@@ -374,11 +394,45 @@ export function setChannelModelOverride(channel, model) {
374
394
  export function setChannelThinkingOverride(channel, thinking) {
375
395
  setChannelOverride(channel, { thinking });
376
396
  }
377
- export function getDefaultAgent() { return defaultAgent; }
378
- export function setDefaultAgent(name) {
397
+ /**
398
+ * The agent a channel runs: its own selection, else the global default. Null when neither is set
399
+ * and the caller's own fallback applies.
400
+ *
401
+ * The channel layer is what makes an agent a per-conversation choice rather than a daemon-wide
402
+ * one — the same shape `getActiveProfile` has, and deliberately so: profile and agent are two
403
+ * independent axes (which model vs which environment) and each has its own channel map.
404
+ */
405
+ export function getDefaultAgent(channel) {
406
+ if (channel && channelAgents[channel])
407
+ return channelAgents[channel];
408
+ return defaultAgent;
409
+ }
410
+ /** Set the agent for one channel (`channel` given) or the global default (omitted). A null name
411
+ * clears: for a channel that means "follow the global default again", globally it means "no
412
+ * default agent at all". */
413
+ export function setDefaultAgent(name, channel) {
414
+ if (channel) {
415
+ if (name)
416
+ channelAgents[channel] = name;
417
+ else
418
+ delete channelAgents[channel];
419
+ persist();
420
+ return;
421
+ }
379
422
  defaultAgent = name;
380
423
  saveModeFile(activeProfile, defaultAgent);
381
424
  }
425
+ /** Drop the channel's agent selection — it follows the global default again. */
426
+ export function clearChannelAgent(channel) {
427
+ if (!channelAgents[channel])
428
+ return;
429
+ delete channelAgents[channel];
430
+ persist();
431
+ }
432
+ /** Every channel that has selected an agent of its own. */
433
+ export function getChannelAgents() {
434
+ return { ...channelAgents };
435
+ }
382
436
  export function isApiRateLimitError(errorMessage) {
383
437
  if (!errorMessage)
384
438
  return false;
@@ -1,5 +1,6 @@
1
1
  export * from './config.js';
2
2
  export * from './profile-switch.js';
3
+ export * from './agent-switch.js';
3
4
  export * from './model-selection.js';
4
5
  export { resolveRateLimitProvider } from './provider-run-lifecycle.js';
5
6
  export { buildPiGatewaySubPath, CHANNEL_SCOPED_PLUGINS, COMMISSION_SCOPED_PLUGINS, filterChannelScopedPlugins, filterScopedPlugins, } from '../runs/engine-spec.js';
@@ -9,6 +9,7 @@
9
9
  // `@domain/runs/engine-spec.js`.
10
10
  export * from './config.js';
11
11
  export * from './profile-switch.js';
12
+ export * from './agent-switch.js';
12
13
  export * from './model-selection.js';
13
14
  export { resolveRateLimitProvider } from './provider-run-lifecycle.js';
14
15
  export { buildPiGatewaySubPath, CHANNEL_SCOPED_PLUGINS, COMMISSION_SCOPED_PLUGINS, filterChannelScopedPlugins, filterScopedPlugins, } from '../runs/engine-spec.js';
@@ -68,6 +68,12 @@ export declare const THINKING_LEVELS_BY_BACKEND: Record<Backend, readonly string
68
68
  /** Is `level` a value this backend accepts? The selection path's gate, the profile validator's
69
69
  * rule — one predicate. */
70
70
  export declare function isValidThinkingLevel(backend: Backend, level: string): boolean;
71
+ /**
72
+ * Identity, not a revision counter, is what makes this safe: every path that can change the
73
+ * profiles — `save`, `mutate`, and the hot-reload watcher's `invalidate` + `readSync` — installs a
74
+ * NEW object, so a stale verdict cannot outlive a change. A file that fails validation is never
75
+ * recorded, so it keeps throwing until it is fixed.
76
+ */
71
77
  declare function loadProfilesFile(): ProfilesFile;
72
78
  /**
73
79
  * Pure resolver: maps a ProfileEntry's claudeBackend field to one of the two accepted values.
@@ -22,10 +22,23 @@ const THINKING_LEVEL_SETS = {
22
22
  export function isValidThinkingLevel(backend, level) {
23
23
  return THINKING_LEVEL_SETS[backend]?.has(level) ?? false;
24
24
  }
25
+ /** The profiles object whose validation already passed. `profileRepo` caches the PARSE; the
26
+ * validation was left to run again on every call, and every caller of this module goes through
27
+ * here — a 300-session `sessions.list` revalidated the whole file 300 times per request. */
28
+ let validatedProfiles = null;
29
+ /**
30
+ * Identity, not a revision counter, is what makes this safe: every path that can change the
31
+ * profiles — `save`, `mutate`, and the hot-reload watcher's `invalidate` + `readSync` — installs a
32
+ * NEW object, so a stale verdict cannot outlive a change. A file that fails validation is never
33
+ * recorded, so it keeps throwing until it is fixed.
34
+ */
25
35
  function loadProfilesFile() {
26
36
  try {
27
37
  const data = profileRepo.readSync();
28
- validateProfilesFile(data);
38
+ if (data !== validatedProfiles) {
39
+ validateProfilesFile(data);
40
+ validatedProfiles = data;
41
+ }
29
42
  return data;
30
43
  }
31
44
  catch (error) {
@@ -10,6 +10,8 @@ export { TERMINAL_STATUSES };
10
10
  * cannot recover it because re-entry completes under a NEW executionId that no longer matches
11
11
  * the original lock owner — leaking the lock until its 20-min TTL expires. Idempotent. */
12
12
  export declare function releaseExecutionLocks(executionId: string | null | undefined): void;
13
+ /** Async twin of `releaseExecutionLocks` for event-loop-sensitive callers (thread suspend path). */
14
+ export declare function releaseExecutionLocksAsync(executionId: string | null | undefined): Promise<void>;
13
15
  export declare function getExecution(id: string): import("../../store/execution-repo.js").ExecutionRecord;
14
16
  export declare function getExecutionByTaskId(taskId: string | null | undefined): import("../../store/execution-repo.js").ExecutionRecord;
15
17
  export declare function getAll(): import("../../store/execution-repo.js").ExecutionRecord[];
@@ -4,30 +4,103 @@
4
4
  // Lock-release: every terminal transition (complete/fail/cancel/stale) auto-releases any task lock held by the executionId.
5
5
  // releaseExecutionLocks(id) exposes the same release for the thread SUSPEND path (thread_wait) WITHOUT ending the execution (DR-0014 lock hygiene).
6
6
  import * as fs from 'node:fs';
7
+ import * as fsp from 'node:fs/promises';
8
+ import path from 'node:path';
7
9
  import { executionRepo, TERMINAL_STATUSES } from '../../store/execution-repo.js';
8
10
  import { PROJECTS_DIR } from '../../core/utils.js';
9
- import { readLock, releaseLock } from '../tasks/system/task-lock.js';
11
+ import { releaseLock, releaseLockAsync } from '../tasks/system/task-lock.js';
12
+ import { parseTasksFileWithLock } from '../../core/task-parser.js';
10
13
  import { createLogger } from '../../core/log.js';
11
14
  import { runRegistry } from '../../core/run-registry.js';
12
15
  export { TERMINAL_STATUSES };
13
16
  const lockLog = createLogger('execution-lock-release');
17
+ /** Project directories that currently have a TASKS.yaml. One readdir, no per-project stat. */
18
+ function projectsWithTasksFile() {
19
+ let names;
20
+ try {
21
+ names = fs.readdirSync(PROJECTS_DIR, { withFileTypes: true })
22
+ .filter(d => d.isDirectory()).map(d => d.name);
23
+ }
24
+ catch {
25
+ return [];
26
+ }
27
+ const out = [];
28
+ for (const project of names) {
29
+ const tasksPath = path.join(PROJECTS_DIR, project, 'TASKS.yaml');
30
+ if (fs.existsSync(tasksPath))
31
+ out.push({ project, tasksPath });
32
+ }
33
+ return out;
34
+ }
14
35
  /** Release any task locks still owned by `executionId` after its agent finished.
15
- * Idempotent — `releaseLock` returns success on absent or non-matching locks. */
36
+ * Idempotent — `releaseLock` returns success on absent or non-matching locks.
37
+ *
38
+ * The lock lives inside TASKS.yaml, so a project whose file does not even mention the execution
39
+ * id cannot hold a matching lock. Reading + substring-scanning the ~22 task files costs ~0.4ms;
40
+ * YAML-parsing all of them costs ~20ms (measured), so the parse is deferred to the rare match.
41
+ * This function stays sync because terminal transitions (and their tests) are sync; event-loop-
42
+ * sensitive callers use `releaseLocksOwnedByAsync` instead. */
16
43
  function releaseLocksOwnedBy(executionId) {
44
+ if (!executionId)
45
+ return;
46
+ for (const { project, tasksPath } of projectsWithTasksFile()) {
47
+ let content;
48
+ try {
49
+ content = fs.readFileSync(tasksPath, 'utf8');
50
+ }
51
+ catch {
52
+ continue;
53
+ }
54
+ if (!content.includes(executionId))
55
+ continue;
56
+ let lock;
57
+ try {
58
+ lock = parseTasksFileWithLock(content, project).lock;
59
+ }
60
+ catch {
61
+ continue;
62
+ }
63
+ if (!lock || lock.owner !== executionId)
64
+ continue;
65
+ try {
66
+ const r = releaseLock(project, executionId);
67
+ if (r.released) {
68
+ lockLog.warn(`auto-released stale lock on '${project}' held by execution ${executionId} ` +
69
+ `(agent finished without calling cortex-task lock-release)`);
70
+ }
71
+ }
72
+ catch (err) {
73
+ lockLog.warn(`release attempt failed for ${project} / ${executionId}: ${err?.message || err}`);
74
+ }
75
+ }
76
+ }
77
+ /** Async twin of `releaseLocksOwnedBy`: no sync fs and no sync mutation-lock wait, so an
78
+ * event-loop-sensitive caller (thread suspend, stale reconciliation) never parks the process on a
79
+ * contended cross-process lock. Same pre-filter, same owner-match semantics, same logging. */
80
+ async function releaseLocksOwnedByAsync(executionId) {
17
81
  if (!executionId)
18
82
  return;
19
83
  let projects;
20
84
  try {
21
- projects = fs.readdirSync(PROJECTS_DIR, { withFileTypes: true })
85
+ projects = (await fsp.readdir(PROJECTS_DIR, { withFileTypes: true }))
22
86
  .filter(d => d.isDirectory()).map(d => d.name);
23
87
  }
24
88
  catch {
25
89
  return;
26
90
  }
27
91
  for (const project of projects) {
92
+ let content;
93
+ try {
94
+ content = await fsp.readFile(path.join(PROJECTS_DIR, project, 'TASKS.yaml'), 'utf8');
95
+ }
96
+ catch {
97
+ continue;
98
+ }
99
+ if (!content.includes(executionId))
100
+ continue;
28
101
  let lock;
29
102
  try {
30
- lock = readLock(project);
103
+ lock = parseTasksFileWithLock(content, project).lock;
31
104
  }
32
105
  catch {
33
106
  continue;
@@ -35,7 +108,7 @@ function releaseLocksOwnedBy(executionId) {
35
108
  if (!lock || lock.owner !== executionId)
36
109
  continue;
37
110
  try {
38
- const r = releaseLock(project, executionId);
111
+ const r = await releaseLockAsync(project, executionId);
39
112
  if (r.released) {
40
113
  lockLog.warn(`auto-released stale lock on '${project}' held by execution ${executionId} ` +
41
114
  `(agent finished without calling cortex-task lock-release)`);
@@ -56,6 +129,10 @@ function releaseLocksOwnedBy(executionId) {
56
129
  export function releaseExecutionLocks(executionId) {
57
130
  releaseLocksOwnedBy(executionId);
58
131
  }
132
+ /** Async twin of `releaseExecutionLocks` for event-loop-sensitive callers (thread suspend path). */
133
+ export async function releaseExecutionLocksAsync(executionId) {
134
+ await releaseLocksOwnedByAsync(executionId);
135
+ }
59
136
  // --- Sync reads ---
60
137
  export function getExecution(id) {
61
138
  return executionRepo.getExecution(id);
@@ -156,13 +233,13 @@ export function teardownExecution({ executionId, status, result, error, duration
156
233
  export async function markMissingRunningExecutionsStale(keepRunning) {
157
234
  const staled = await executionRepo.markMissingRunningExecutionsStale(keepRunning);
158
235
  for (const id of staled)
159
- releaseLocksOwnedBy(id);
236
+ await releaseLocksOwnedByAsync(id);
160
237
  return staled;
161
238
  }
162
239
  export async function reconcileStaleDispatches(opts) {
163
240
  const { count, staled } = await executionRepo.reconcileStaleDispatches(opts);
164
241
  for (const id of staled)
165
- releaseLocksOwnedBy(id);
242
+ await releaseLocksOwnedByAsync(id);
166
243
  return count;
167
244
  }
168
245
  // --- Deprecated ---
@@ -241,7 +241,7 @@ function skillSnapshotTarget(parent, selection, skill) {
241
241
  function createSkillSnapshot(selection, skill, target) {
242
242
  const tmp = projectionTemp(path.dirname(target), target);
243
243
  try {
244
- copyProjectedSkillTree(selection.root.real, skill.target, skill.tree, tmp);
244
+ copyProjectedSkillTree(selection.root.real, skill.target, skill.tree, tmp, { requireSourceSignature: true });
245
245
  fs.renameSync(tmp, target);
246
246
  return true;
247
247
  }
@@ -1,13 +1,19 @@
1
1
  export interface ProjectedSkillFile {
2
2
  path: string;
3
- sha256: string;
3
+ /** Source identity (size, mtime, ctime, inode, mode) — what the copy re-validates against. */
4
+ signature: string;
5
+ /** Byte length of the source file; a materialized copy must match it. */
6
+ size: number;
4
7
  mode: number;
5
8
  }
6
9
  export interface ProjectedSkillTree {
7
10
  dirs: string[];
8
11
  files: ProjectedSkillFile[];
12
+ /** Digest of the {dirs, files} descriptor (metadata only), used as the projection cache key. */
9
13
  sha256: string;
10
14
  }
11
15
  export declare function buildProjectedSkillTree(packageRoot: string, skillRoot: string): ProjectedSkillTree;
12
- export declare function copyProjectedSkillTree(packageRoot: string, skillRoot: string, tree: ProjectedSkillTree, targetRoot: string): void;
16
+ export declare function copyProjectedSkillTree(packageRoot: string, skillRoot: string, tree: ProjectedSkillTree, targetRoot: string, opts?: {
17
+ requireSourceSignature?: boolean;
18
+ }): void;
13
19
  export declare function validateProjectedSkillTree(targetRoot: string, expected: ProjectedSkillTree): void;