@cortex-agent/server 2026.8.3-2 → 2026.8.6

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 (219) hide show
  1. package/defaults/config/thread-templates/agents/benchmark-coder.json +2 -2
  2. package/defaults/config/thread-templates/agents/benchmark-fixer.json +17 -0
  3. package/defaults/config/thread-templates/agents/benchmark-reviewer.json +5 -5
  4. package/defaults/config/thread-templates/templates/benchmark-coder-review-fix.json +21 -0
  5. package/defaults/plugins/cortex-system/skills/thread/SKILL.md +1 -0
  6. package/defaults/prompts/directives/benchmark-coder.md +1 -0
  7. package/defaults/prompts/directives/benchmark-fixer.md +1 -0
  8. package/defaults/prompts/directives/benchmark-reviewer.md +1 -0
  9. package/defaults/prompts/systemPrompts/benchmark-coder.md +1 -0
  10. package/defaults/prompts/systemPrompts/benchmark-fixer.md +1 -0
  11. package/defaults/prompts/systemPrompts/benchmark-reviewer.md +1 -0
  12. package/dist/agent-adapter/capabilities.d.ts +32 -1
  13. package/dist/agent-adapter/capabilities.js +39 -1
  14. package/dist/agent-adapter/claude/adapter.d.ts +15 -0
  15. package/dist/agent-adapter/claude/adapter.js +29 -7
  16. package/dist/agent-adapter/claude/spawn-args.d.ts +5 -2
  17. package/dist/agent-adapter/claude/spawn-args.js +29 -6
  18. package/dist/agent-adapter/index.js +11 -1
  19. package/dist/agent-adapter/normalize/tool-names.d.ts +4 -0
  20. package/dist/agent-adapter/normalize/tool-names.js +10 -0
  21. package/dist/agent-adapter/pi/adapter.d.ts +20 -8
  22. package/dist/agent-adapter/pi/adapter.js +130 -35
  23. package/dist/agent-adapter/pi/agent-dir.d.ts +20 -53
  24. package/dist/agent-adapter/pi/agent-dir.js +48 -89
  25. package/dist/agent-adapter/pi/custom-catalog.d.ts +10 -0
  26. package/dist/agent-adapter/pi/custom-catalog.js +42 -0
  27. package/dist/agent-adapter/pi/defaults.d.ts +9 -0
  28. package/dist/agent-adapter/pi/defaults.js +14 -4
  29. package/dist/agent-adapter/pi/discovery.d.ts +1 -3
  30. package/dist/agent-adapter/pi/discovery.js +3 -15
  31. package/dist/agent-adapter/pi/event-parser.js +8 -0
  32. package/dist/agent-adapter/pi/mcp-bridge.d.ts +13 -0
  33. package/dist/agent-adapter/pi/mcp-bridge.js +31 -6
  34. package/dist/agent-adapter/pi/mcp-duration.d.ts +28 -0
  35. package/dist/agent-adapter/pi/mcp-duration.js +48 -0
  36. package/dist/agent-adapter/pi/policy-guard.d.ts +40 -0
  37. package/dist/agent-adapter/pi/policy-guard.js +111 -0
  38. package/dist/agent-adapter/pi/providers-config.d.ts +62 -0
  39. package/dist/agent-adapter/pi/providers-config.js +101 -0
  40. package/dist/agent-adapter/pi/quota-probe.d.ts +11 -0
  41. package/dist/agent-adapter/pi/quota-probe.js +36 -0
  42. package/dist/agent-adapter/pi/quota-sink.d.ts +25 -0
  43. package/dist/agent-adapter/pi/quota-sink.js +31 -0
  44. package/dist/agent-adapter/pi/session-files.d.ts +2 -0
  45. package/dist/agent-adapter/pi/session-files.js +19 -0
  46. package/dist/agent-adapter/pi/session-support.d.ts +14 -3
  47. package/dist/agent-adapter/pi/session-support.js +8 -0
  48. package/dist/agent-adapter/pi/spawn-args.d.ts +11 -1
  49. package/dist/agent-adapter/pi/spawn-args.js +13 -0
  50. package/dist/agent-adapter/pi/tool-shims.d.ts +2 -2
  51. package/dist/agent-adapter/pi/tool-shims.js +32 -21
  52. package/dist/agent-adapter/pi/web-search.js +36 -8
  53. package/dist/agent-adapter/types.d.ts +14 -0
  54. package/dist/core/locales/en.d.ts +54 -1
  55. package/dist/core/locales/en.js +2 -0
  56. package/dist/core/locales/slices/commands.d.ts +12 -1
  57. package/dist/core/locales/slices/commands.js +24 -2
  58. package/dist/core/locales/slices/providers.d.ts +45 -0
  59. package/dist/core/locales/slices/providers.js +95 -0
  60. package/dist/core/locales/zh.js +2 -0
  61. package/dist/core/resilient-watch.d.ts +28 -0
  62. package/dist/core/resilient-watch.js +110 -0
  63. package/dist/core/settings.js +15 -20
  64. package/dist/core/types/agent-types.d.ts +6 -0
  65. package/dist/core/types/thread-types.d.ts +21 -3
  66. package/dist/domain/agent-run/agent-run-cli.js +3 -1
  67. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.d.ts +31 -0
  68. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.js +231 -24
  69. package/dist/domain/agent-run/benchmark-thread-identity.d.ts +15 -2
  70. package/dist/domain/agent-run/benchmark-thread-identity.js +123 -34
  71. package/dist/domain/agent-run/identity.d.ts +5 -0
  72. package/dist/domain/agent-run/identity.js +4 -1
  73. package/dist/domain/agent-run/journal.d.ts +3 -2
  74. package/dist/domain/agent-run/manifest.js +11 -4
  75. package/dist/domain/agent-run/pinned-node-process.d.ts +4 -0
  76. package/dist/domain/agent-run/pinned-node-process.js +9 -0
  77. package/dist/domain/agent-run/role-surface.d.ts +2 -2
  78. package/dist/domain/agent-run/role-surface.js +7 -3
  79. package/dist/domain/agent-run/run-config.d.ts +10 -1
  80. package/dist/domain/agent-run/run-config.js +57 -6
  81. package/dist/domain/agent-run/runner.js +149 -31
  82. package/dist/domain/agents/facade.d.ts +37 -122
  83. package/dist/domain/agents/facade.js +47 -115
  84. package/dist/domain/agents/spawn-config.d.ts +135 -0
  85. package/dist/domain/agents/spawn-config.js +121 -0
  86. package/dist/domain/benchmark/accounting-reconciliation.d.ts +98 -0
  87. package/dist/domain/benchmark/accounting-reconciliation.js +218 -0
  88. package/dist/domain/benchmark/arm-schema.d.ts +43 -0
  89. package/dist/domain/benchmark/arm-schema.js +243 -0
  90. package/dist/domain/benchmark/capabilities.d.ts +4 -0
  91. package/dist/domain/benchmark/capabilities.js +54 -0
  92. package/dist/domain/benchmark/decimal-text.d.ts +27 -0
  93. package/dist/domain/benchmark/decimal-text.js +67 -0
  94. package/dist/domain/benchmark/lease-echo.d.ts +43 -0
  95. package/dist/domain/benchmark/lease-echo.js +56 -0
  96. package/dist/domain/benchmark/policy-backed-runtime-deps.d.ts +14 -0
  97. package/dist/domain/benchmark/policy-backed-runtime-deps.js +47 -0
  98. package/dist/domain/benchmark/policy-compiler.d.ts +68 -0
  99. package/dist/domain/benchmark/policy-compiler.js +680 -0
  100. package/dist/domain/benchmark/resolved-policy.d.ts +110 -0
  101. package/dist/domain/benchmark/resolved-policy.js +195 -0
  102. package/dist/domain/benchmark/trial-adapter-factory.d.ts +38 -0
  103. package/dist/domain/benchmark/trial-adapter-factory.js +165 -0
  104. package/dist/domain/benchmark/trial-thread-adapter.d.ts +25 -0
  105. package/dist/domain/benchmark/trial-thread-adapter.js +106 -0
  106. package/dist/domain/benchmark/variant-proposal.d.ts +45 -0
  107. package/dist/domain/benchmark/variant-proposal.js +42 -0
  108. package/dist/domain/benchmark/workspace-lease.d.ts +99 -0
  109. package/dist/domain/benchmark/workspace-lease.js +272 -0
  110. package/dist/domain/costs/codex-quota.d.ts +29 -0
  111. package/dist/domain/costs/codex-quota.js +102 -0
  112. package/dist/domain/costs/cost-tracker.d.ts +48 -9
  113. package/dist/domain/costs/cost-tracker.js +74 -18
  114. package/dist/domain/costs/rate-limit-throttle.d.ts +23 -1
  115. package/dist/domain/costs/rate-limit-throttle.js +61 -6
  116. package/dist/domain/costs/resume-registry.d.ts +3 -1
  117. package/dist/domain/costs/resume-registry.js +10 -1
  118. package/dist/domain/mcp/tools/benchmark-thread-run.d.ts +26 -2
  119. package/dist/domain/mcp/tools/benchmark-thread-run.js +63 -20
  120. package/dist/domain/mcp/tools/cost.js +15 -6
  121. package/dist/domain/pi-providers/custom-provider-model.d.ts +53 -0
  122. package/dist/domain/pi-providers/custom-provider-model.js +122 -0
  123. package/dist/domain/pi-providers/custom-provider-service.d.ts +59 -0
  124. package/dist/domain/pi-providers/custom-provider-service.js +143 -0
  125. package/dist/domain/pi-providers/gateway-route-store.d.ts +23 -0
  126. package/dist/domain/pi-providers/gateway-route-store.js +78 -0
  127. package/dist/domain/pi-providers/index.d.ts +4 -0
  128. package/dist/domain/pi-providers/index.js +8 -0
  129. package/dist/domain/pi-providers/models-json-store.d.ts +6 -0
  130. package/dist/domain/pi-providers/models-json-store.js +77 -0
  131. package/dist/domain/scheduling/jobs/_shared.d.ts +4 -1
  132. package/dist/domain/scheduling/jobs/_shared.js +11 -2
  133. package/dist/domain/scheduling/jobs/scheduled-task.js +1 -0
  134. package/dist/domain/scheduling/jobs/task-dispatch.js +49 -54
  135. package/dist/domain/sessions/session-lifecycle.d.ts +22 -0
  136. package/dist/domain/sessions/session-lifecycle.js +20 -1
  137. package/dist/domain/system/system-notice.d.ts +4 -1
  138. package/dist/domain/system/system-notice.js +6 -2
  139. package/dist/domain/tasks/dispatch-utils.d.ts +0 -4
  140. package/dist/domain/tasks/dispatch-utils.js +24 -37
  141. package/dist/domain/threads/runner.d.ts +16 -1
  142. package/dist/domain/threads/runner.js +62 -8
  143. package/dist/domain/threads/template-loader.d.ts +5 -0
  144. package/dist/domain/threads/template-loader.js +120 -36
  145. package/dist/domain/threads/template-validate.d.ts +244 -0
  146. package/dist/domain/threads/template-validate.js +574 -0
  147. package/dist/domain/threads/template-validate.parity.d.ts +1 -0
  148. package/dist/domain/threads/template-validate.parity.js +47 -0
  149. package/dist/domain/threads/template-writer.d.ts +55 -0
  150. package/dist/domain/threads/template-writer.js +131 -0
  151. package/dist/domain/ui-service/app-router.d.ts +143 -1
  152. package/dist/domain/ui-service/app-router.js +29 -3
  153. package/dist/domain/ui-service/input-schemas.d.ts +228 -4
  154. package/dist/domain/ui-service/input-schemas.js +132 -1
  155. package/dist/domain/ui-service/mutate/config.d.ts +10 -1
  156. package/dist/domain/ui-service/mutate/config.js +45 -5
  157. package/dist/domain/ui-service/mutate/custom-providers.d.ts +8 -0
  158. package/dist/domain/ui-service/mutate/custom-providers.js +37 -0
  159. package/dist/domain/ui-service/mutate/profiles.d.ts +21 -0
  160. package/dist/domain/ui-service/mutate/profiles.js +156 -0
  161. package/dist/domain/ui-service/mutate/schedules.d.ts +2 -1
  162. package/dist/domain/ui-service/mutate/schedules.js +53 -3
  163. package/dist/domain/ui-service/mutate/sessions.d.ts +2 -1
  164. package/dist/domain/ui-service/mutate/sessions.js +25 -1
  165. package/dist/domain/ui-service/mutate/system.d.ts +2 -1
  166. package/dist/domain/ui-service/mutate/system.js +17 -3
  167. package/dist/domain/ui-service/mutate/thread-templates.d.ts +4 -0
  168. package/dist/domain/ui-service/mutate/thread-templates.js +71 -0
  169. package/dist/domain/ui-service/query/config.js +30 -0
  170. package/dist/domain/ui-service/query/custom-providers.d.ts +8 -0
  171. package/dist/domain/ui-service/query/custom-providers.js +13 -0
  172. package/dist/domain/ui-service/query/machine-detail.d.ts +2 -0
  173. package/dist/domain/ui-service/query/machine-detail.js +56 -0
  174. package/dist/domain/ui-service/query/machine-probe.d.ts +18 -0
  175. package/dist/domain/ui-service/query/machine-probe.js +136 -0
  176. package/dist/domain/ui-service/query/schedules.js +5 -0
  177. package/dist/domain/ui-service/query/sessions.js +8 -2
  178. package/dist/domain/ui-service/query/thread-template-detail.d.ts +8 -0
  179. package/dist/domain/ui-service/query/thread-template-detail.js +94 -0
  180. package/dist/domain/ui-service/query/thread-templates.d.ts +5 -3
  181. package/dist/domain/ui-service/query/thread-templates.js +44 -7
  182. package/dist/domain/ui-service/types.d.ts +298 -7
  183. package/dist/domain/ui-service/ui-service.js +27 -3
  184. package/dist/entry/app.js +24 -3
  185. package/dist/entry/auth-cli.d.ts +4 -1
  186. package/dist/entry/auth-cli.js +10 -2
  187. package/dist/entry/cli-help.js +6 -2
  188. package/dist/entry/cli.js +2 -1
  189. package/dist/entry/daemon.d.ts +0 -11
  190. package/dist/entry/daemon.js +5 -49
  191. package/dist/entry/provider-cli.d.ts +16 -0
  192. package/dist/entry/provider-cli.js +203 -0
  193. package/dist/events/event-types.d.ts +2 -1
  194. package/dist/orchestration/agent-runner.js +3 -2
  195. package/dist/orchestration/routing/commands/cost.d.ts +8 -0
  196. package/dist/orchestration/routing/commands/cost.js +93 -21
  197. package/dist/orchestration/routing/commands/login-custom.d.ts +26 -0
  198. package/dist/orchestration/routing/commands/login-custom.js +89 -0
  199. package/dist/orchestration/routing/commands/login.d.ts +3 -0
  200. package/dist/orchestration/routing/commands/login.js +7 -0
  201. package/dist/orchestration/routing/message-router.js +48 -33
  202. package/dist/orchestration/routing/webhook.js +1 -1
  203. package/dist/orchestration/session-events.d.ts +2 -1
  204. package/dist/orchestration/session-events.js +1 -0
  205. package/dist/orchestration/thread-callback.js +1 -1
  206. package/dist/store/conversation-history-repo.d.ts +5 -1
  207. package/dist/store/conversation-history-repo.js +2 -1
  208. package/dist/store/cost-repo.d.ts +17 -0
  209. package/dist/store/cost-repo.js +47 -5
  210. package/dist/store/profile-repo.d.ts +0 -10
  211. package/dist/store/profile-repo.js +34 -56
  212. package/dist/store/session-registry-repo.d.ts +12 -0
  213. package/dist/store/session-registry-repo.js +16 -0
  214. package/package.json +1 -1
  215. package/web/dist/assets/index-DYMfaAi4.css +1 -0
  216. package/web/dist/assets/index-uOoZjGKa.js +141 -0
  217. package/web/dist/index.html +2 -2
  218. package/web/dist/assets/index-XqBCYtkw.js +0 -139
  219. package/web/dist/assets/index-zpf3OSKC.css +0 -1
@@ -0,0 +1,37 @@
1
+ // input: custom provider drafts and the stores held in UiServiceDeps
2
+ // output: upsert and remove results over the PI catalog and gateway route
3
+ // pos: Write handlers for the user-defined PI provider operations
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import { t } from '../../../core/i18n.js';
6
+ import { defaultCustomProviderStores, removeCustomProvider, upsertCustomProvider, } from '../../pi-providers/index.js';
7
+ function storesOf(deps) {
8
+ return deps.customProviderStores ?? defaultCustomProviderStores();
9
+ }
10
+ /** One message table serves every surface, so the Web text matches what the CLI prints. */
11
+ function issueText(issue) {
12
+ return t(`provider.issue.${issue}`);
13
+ }
14
+ /**
15
+ * A missing definition is a client error, a failed write is ours, and anything else is a rejected
16
+ * draft the form can correct.
17
+ */
18
+ function failure(errors) {
19
+ const code = errors.includes('not-found')
20
+ ? 'not-found'
21
+ : errors.includes('write-failed') ? 'internal' : 'invalid-args';
22
+ return { ok: false, code, message: errors.map(issueText).join(' ') };
23
+ }
24
+ /**
25
+ * Create or edit a provider. `apiKey` is optional on purpose: leaving it out keeps the stored
26
+ * upstream secret, so an edit form need not ask the operator to retype a key it never displays.
27
+ */
28
+ export async function handleCustomProviderUpsert(deps, args) {
29
+ const result = upsertCustomProvider(storesOf(deps), args);
30
+ // `=== true` rather than a truthiness test: this project typechecks with `strict: false`, where
31
+ // truthiness alone does not narrow a boolean-literal discriminant.
32
+ return result.ok === true ? { ok: true, data: result.provider } : failure(result.errors);
33
+ }
34
+ export async function handleCustomProviderRemove(deps, args) {
35
+ const result = removeCustomProvider(storesOf(deps), args.name);
36
+ return result.ok === true ? { ok: true, data: { removed: true } } : failure(result.errors);
37
+ }
@@ -0,0 +1,21 @@
1
+ import { type ProfileEntry } from '../../agents/profile-manager.js';
2
+ import type { UiServiceDeps, Result, ProfileDraftInput, ProfilesCreateArgs, ProfilesCreateReturn, ProfilesUpdateArgs, ProfilesUpdateReturn, ProfilesRemoveArgs, ProfilesRemoveReturn } from '../types.js';
3
+ /**
4
+ * Assemble the stored entry from the draft. Optional fields the draft omits are DROPPED (the draft
5
+ * is the complete desired state for everything the editor can express), while `extraEnv` and
6
+ * `fallback` are carried over from `preserved` — the UI cannot express either (extraEnv values are
7
+ * secret-bearing and never leave the server; fallback is a nested chain with no editor), so an edit
8
+ * must not silently delete them. Key order matches how init writes the file.
9
+ */
10
+ export declare function buildProfileEntry(draft: ProfileDraftInput, preserved?: ProfileEntry): ProfileEntry;
11
+ export declare function createProfile(configDir: string, args: ProfilesCreateArgs): Promise<void>;
12
+ export declare function updateProfile(configDir: string, args: ProfilesUpdateArgs): Promise<boolean>;
13
+ /**
14
+ * Deleting the profile `defaultProfile` points at would leave every agent start resolving a
15
+ * missing profile, and deleting the last one leaves nothing to resolve at all. Both are refused
16
+ * with the remedy in the message rather than written and then discovered at spawn time.
17
+ */
18
+ export declare function removeProfile(configDir: string, args: ProfilesRemoveArgs): Promise<void>;
19
+ export declare function handleProfilesCreate(_deps: UiServiceDeps, args: ProfilesCreateArgs): Promise<Result<ProfilesCreateReturn>>;
20
+ export declare function handleProfilesUpdate(_deps: UiServiceDeps, args: ProfilesUpdateArgs): Promise<Result<ProfilesUpdateReturn>>;
21
+ export declare function handleProfilesRemove(_deps: UiServiceDeps, args: ProfilesRemoveArgs): Promise<Result<ProfilesRemoveReturn>>;
@@ -0,0 +1,156 @@
1
+ // input: profiles.* schemas, CONFIG_DIR, profiles.json on disk
2
+ // output: create / update / remove writes over the profiles map
3
+ // pos: Mutation handlers for the profiles.* operations
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import path from 'node:path';
6
+ import fs from 'node:fs/promises';
7
+ import { CONFIG_DIR } from '../../../core/paths.js';
8
+ import { atomicWrite } from '../../../core/atomic-write.js';
9
+ import { validateProfilesFile } from '../../agents/profile-manager.js';
10
+ function fail(code, message) {
11
+ return Object.assign(new Error(message), { code });
12
+ }
13
+ function profilesPath(configDir) {
14
+ return path.join(configDir, 'profiles.json');
15
+ }
16
+ /** Read the file whole so every field we do not manage (defaultProfile, any future key) survives. */
17
+ async function readProfilesFile(configDir) {
18
+ let raw;
19
+ try {
20
+ raw = JSON.parse(await fs.readFile(profilesPath(configDir), 'utf8'));
21
+ }
22
+ catch {
23
+ throw fail('invalid-args', 'profiles.json is missing or unreadable');
24
+ }
25
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw) || !raw.profiles
26
+ || typeof raw.profiles !== 'object' || Array.isArray(raw.profiles)) {
27
+ throw fail('invalid-args', 'profiles.json has no profiles map');
28
+ }
29
+ return raw;
30
+ }
31
+ async function writeProfilesFile(configDir, next) {
32
+ await atomicWrite(profilesPath(configDir), JSON.stringify(next, null, 2) + '\n');
33
+ }
34
+ /**
35
+ * Assemble the stored entry from the draft. Optional fields the draft omits are DROPPED (the draft
36
+ * is the complete desired state for everything the editor can express), while `extraEnv` and
37
+ * `fallback` are carried over from `preserved` — the UI cannot express either (extraEnv values are
38
+ * secret-bearing and never leave the server; fallback is a nested chain with no editor), so an edit
39
+ * must not silently delete them. Key order matches how init writes the file.
40
+ */
41
+ export function buildProfileEntry(draft, preserved) {
42
+ const entry = { model: draft.model };
43
+ if (draft.backend !== undefined)
44
+ entry.backend = draft.backend;
45
+ if (draft.mode !== undefined)
46
+ entry.mode = draft.mode;
47
+ if (draft.provider !== undefined)
48
+ entry.provider = draft.provider;
49
+ if (preserved?.extraEnv !== undefined)
50
+ entry.extraEnv = preserved.extraEnv;
51
+ if (draft.extraOption !== undefined && Object.keys(draft.extraOption).length > 0) {
52
+ entry.extraOption = draft.extraOption;
53
+ }
54
+ if (draft.claudeBackend !== undefined)
55
+ entry.claudeBackend = draft.claudeBackend;
56
+ if (draft.thinking !== undefined)
57
+ entry.thinking = draft.thinking;
58
+ if (preserved?.fallback !== undefined)
59
+ entry.fallback = preserved.fallback;
60
+ return entry;
61
+ }
62
+ /**
63
+ * Run the shipped file validator over a ONE-ENTRY probe file rather than the assembled result.
64
+ * Same code path — name charset, backend enum, the pi-needs-a-provider rule, per-backend thinking
65
+ * levels, extraEnv/extraOption shapes, and the fallback chain re-checked against the (possibly
66
+ * changed) primary backend — but scoped to the entry being written, so a pre-existing hand-broken
67
+ * neighbour entry cannot block editing an unrelated profile.
68
+ */
69
+ function assertValidEntry(name, entry) {
70
+ try {
71
+ validateProfilesFile({ defaultProfile: name, profiles: { [name]: entry } });
72
+ }
73
+ catch (error) {
74
+ throw fail('invalid-args', error instanceof Error ? error.message : String(error));
75
+ }
76
+ }
77
+ export async function createProfile(configDir, args) {
78
+ const { name, ...draft } = args;
79
+ const raw = await readProfilesFile(configDir);
80
+ if (Object.prototype.hasOwnProperty.call(raw.profiles, name)) {
81
+ throw fail('invalid-args', `profile "${name}" already exists`);
82
+ }
83
+ const entry = buildProfileEntry(draft);
84
+ assertValidEntry(name, entry);
85
+ await writeProfilesFile(configDir, { ...raw, profiles: { ...raw.profiles, [name]: entry } });
86
+ }
87
+ export async function updateProfile(configDir, args) {
88
+ const { name, ...draft } = args;
89
+ const raw = await readProfilesFile(configDir);
90
+ const current = raw.profiles[name];
91
+ if (!current)
92
+ throw fail('not-found', `profile "${name}" not found in profiles.json`);
93
+ const entry = buildProfileEntry(draft, current);
94
+ assertValidEntry(name, entry);
95
+ const changed = JSON.stringify(entry) !== JSON.stringify(current);
96
+ if (changed) {
97
+ await writeProfilesFile(configDir, { ...raw, profiles: { ...raw.profiles, [name]: entry } });
98
+ }
99
+ return changed;
100
+ }
101
+ /**
102
+ * Deleting the profile `defaultProfile` points at would leave every agent start resolving a
103
+ * missing profile, and deleting the last one leaves nothing to resolve at all. Both are refused
104
+ * with the remedy in the message rather than written and then discovered at spawn time.
105
+ */
106
+ export async function removeProfile(configDir, args) {
107
+ const { name } = args;
108
+ const raw = await readProfilesFile(configDir);
109
+ if (!Object.prototype.hasOwnProperty.call(raw.profiles, name)) {
110
+ throw fail('not-found', `profile "${name}" not found in profiles.json`);
111
+ }
112
+ if (raw.defaultProfile === name) {
113
+ throw fail('invalid-args', `profile "${name}" is the default profile — point the default at another profile first`);
114
+ }
115
+ const rest = { ...raw.profiles };
116
+ delete rest[name];
117
+ if (Object.keys(rest).length === 0) {
118
+ throw fail('invalid-args', 'cannot remove the last profile in profiles.json');
119
+ }
120
+ await writeProfilesFile(configDir, { ...raw, profiles: rest });
121
+ }
122
+ /** Writer errors carry `code`; anything else is a genuine internal failure. */
123
+ function toErr(error) {
124
+ const code = error?.code;
125
+ return {
126
+ ok: false,
127
+ code: code === 'not-found' || code === 'invalid-args' ? code : 'internal',
128
+ message: error instanceof Error ? error.message : String(error),
129
+ };
130
+ }
131
+ export async function handleProfilesCreate(_deps, args) {
132
+ try {
133
+ await createProfile(CONFIG_DIR, args);
134
+ return { ok: true, data: { name: args.name } };
135
+ }
136
+ catch (error) {
137
+ return toErr(error);
138
+ }
139
+ }
140
+ export async function handleProfilesUpdate(_deps, args) {
141
+ try {
142
+ return { ok: true, data: { changed: await updateProfile(CONFIG_DIR, args) } };
143
+ }
144
+ catch (error) {
145
+ return toErr(error);
146
+ }
147
+ }
148
+ export async function handleProfilesRemove(_deps, args) {
149
+ try {
150
+ await removeProfile(CONFIG_DIR, args);
151
+ return { ok: true, data: { removed: true } };
152
+ }
153
+ catch (error) {
154
+ return toErr(error);
155
+ }
156
+ }
@@ -1,4 +1,4 @@
1
- import type { UiServiceDeps, Result, ScheduleAddArgs, ScheduleInfo } from '../types.js';
1
+ import type { UiServiceDeps, Result, ScheduleAddArgs, ScheduleUpdateArgs, ScheduleInfo } from '../types.js';
2
2
  export declare function handlePauseSchedule(deps: UiServiceDeps, args: {
3
3
  scheduleId: string;
4
4
  }): Promise<Result<void>>;
@@ -9,3 +9,4 @@ export declare function handleRemoveSchedule(deps: UiServiceDeps, args: {
9
9
  scheduleId: string;
10
10
  }): Promise<Result<void>>;
11
11
  export declare function handleAddSchedule(deps: UiServiceDeps, args: ScheduleAddArgs): Promise<Result<ScheduleInfo>>;
12
+ export declare function handleUpdateSchedule(deps: UiServiceDeps, args: ScheduleUpdateArgs): Promise<Result<ScheduleInfo>>;
@@ -1,6 +1,6 @@
1
- // input: UiServiceDeps + { scheduleId } | ScheduleAddArgs
2
- // output: pause/resume/remove/add schedule handlers → Ok<void|ScheduleInfo> | Err
3
- // pos: mutate handlers for 'schedules.{pause,resume,remove,add}'
1
+ // input: UiServiceDeps + { scheduleId } | ScheduleAddArgs | ScheduleUpdateArgs
2
+ // output: pause/resume/remove/add/update schedule handlers → Ok<void|ScheduleInfo> | Err
3
+ // pos: mutate handlers for 'schedules.{pause,resume,remove,add,update}'
4
4
  /** Map a persisted ScheduleTask → ScheduleInfo DTO (mirrors query/schedules.ts). */
5
5
  function toScheduleInfo(s) {
6
6
  return {
@@ -13,6 +13,11 @@ function toScheduleInfo(s) {
13
13
  lastRun: s.lastRun != null ? new Date(s.lastRun).toISOString() : null,
14
14
  paused: s.isPaused ?? false,
15
15
  pausedBy: s.pausedBy ?? null,
16
+ intervalMs: s.intervalMs ?? null,
17
+ time: s.time ?? null,
18
+ dayOfWeek: s.dayOfWeek ?? null,
19
+ target: s.target ?? null,
20
+ fallback: s.fallback ?? null,
16
21
  };
17
22
  }
18
23
  export async function handlePauseSchedule(deps, args) {
@@ -91,3 +96,48 @@ export async function handleAddSchedule(deps, args) {
91
96
  return { ok: false, code: 'internal', message: err?.message || String(err) };
92
97
  }
93
98
  }
99
+ /** Fields patchable per schedule type — mirrors scheduler.validateTaskPatch minus dispatchType/
100
+ * preCheck (not UI-editable). The type itself is immutable. */
101
+ const UPDATE_TIMING_FIELDS = {
102
+ interval: ['intervalMs'],
103
+ daily: ['time'],
104
+ weekly: ['dayOfWeek', 'time'],
105
+ once: [],
106
+ };
107
+ function buildUpdatePatch(args) {
108
+ const { scheduleId: _id, ...rest } = args;
109
+ const patch = {};
110
+ for (const [key, value] of Object.entries(rest)) {
111
+ if (value !== undefined)
112
+ patch[key] = value;
113
+ }
114
+ return patch;
115
+ }
116
+ // Patch an existing schedule. Field-allowedness is re-checked against the persisted task's type
117
+ // BEFORE calling update, so a foreign timing field is an Err with nothing written (the real
118
+ // scheduler.update would also throw — this keeps the error a typed Result instead).
119
+ export async function handleUpdateSchedule(deps, args) {
120
+ const task = await deps.scheduler.get(args.scheduleId);
121
+ if (!task) {
122
+ return { ok: false, code: 'not-found', message: `Schedule not found: ${args.scheduleId}` };
123
+ }
124
+ const patch = buildUpdatePatch(args);
125
+ if (Object.keys(patch).length === 0) {
126
+ return { ok: false, code: 'invalid-args', message: 'empty patch — provide at least one field' };
127
+ }
128
+ const allowed = new Set(['message', 'projectId', 'profile', ...UPDATE_TIMING_FIELDS[task.type]]);
129
+ const invalid = Object.keys(patch).filter((key) => !allowed.has(key));
130
+ if (invalid.length > 0) {
131
+ return { ok: false, code: 'invalid-args', message: `invalid fields for ${task.type}: ${invalid.join(', ')}` };
132
+ }
133
+ try {
134
+ const updated = await deps.scheduler.update(args.scheduleId, patch);
135
+ if (!updated) {
136
+ return { ok: false, code: 'not-found', message: `Schedule not found: ${args.scheduleId}` };
137
+ }
138
+ return { ok: true, data: toScheduleInfo(updated) };
139
+ }
140
+ catch (err) {
141
+ return { ok: false, code: 'internal', message: err?.message || String(err) };
142
+ }
143
+ }
@@ -1,4 +1,4 @@
1
- import type { UiServiceDeps, Result, SessionsCreateArgs, SessionsCreateReturn, SessionsSendArgs, SessionsSendReturn, SessionsCancelArgs, SessionsCompactArgs, SessionsCompactReturn, SessionsMarkReadArgs, SessionsCancelReturn, SessionsSetProfileArgs, SessionsSetProfileReturn, SessionsCreateAndSendArgs, SessionsCreateAndSendReturn, SessionsAnswerQuestionArgs, SessionsRespondPlanArgs, SessionsInteractionMutateReturn, SessionsRewindArgs, SessionsRewindReturn } from '../types.js';
1
+ import type { UiServiceDeps, Result, SessionsCreateArgs, SessionsCreateReturn, SessionsSendArgs, SessionsSendReturn, SessionsCancelArgs, SessionsCompactArgs, SessionsCompactReturn, SessionsMarkReadArgs, SessionsCancelReturn, SessionsSetProfileArgs, SessionsSetProfileReturn, SessionsCreateAndSendArgs, SessionsCreateAndSendReturn, SessionsAnswerQuestionArgs, SessionsRespondPlanArgs, SessionsInteractionMutateReturn, SessionsRewindArgs, SessionsRewindReturn, SessionsCancelResumeArgs, SessionsCancelResumeReturn } from '../types.js';
2
2
  export declare function handleCreateSession(deps: UiServiceDeps, args: SessionsCreateArgs): Promise<Result<SessionsCreateReturn>>;
3
3
  export declare function handleSendSession(deps: UiServiceDeps, args: SessionsSendArgs): Promise<Result<SessionsSendReturn>>;
4
4
  export declare function handleCancelSession(deps: UiServiceDeps, args: SessionsCancelArgs): Promise<Result<SessionsCancelReturn>>;
@@ -8,4 +8,5 @@ export declare function handleCreateAndSend(deps: UiServiceDeps, args: SessionsC
8
8
  export declare function handleSetProfile(deps: UiServiceDeps, args: SessionsSetProfileArgs): Promise<Result<SessionsSetProfileReturn>>;
9
9
  export declare function handleRewindSession(deps: UiServiceDeps, args: SessionsRewindArgs): Promise<Result<SessionsRewindReturn>>;
10
10
  export declare function handleAnswerQuestion(deps: UiServiceDeps, args: SessionsAnswerQuestionArgs): Promise<Result<SessionsInteractionMutateReturn>>;
11
+ export declare function handleCancelResume(args: SessionsCancelResumeArgs): Promise<Result<SessionsCancelResumeReturn>>;
11
12
  export declare function handleRespondPlan(deps: UiServiceDeps, args: SessionsRespondPlanArgs): Promise<Result<SessionsInteractionMutateReturn>>;
@@ -6,6 +6,7 @@
6
6
  // (via sessionStore) and hands off to the injected `sendSessionMessage` callback, which is wired
7
7
  // in the entry layer to the orchestration send path (agentRunner.route). Fire-and-forget: the
8
8
  // assistant reply returns over the `session.message` stream event, NOT this return.
9
+ import { removeDirectResume } from '../../costs/resume-registry.js';
9
10
  // Create a fresh, live direct session for the workbench "+ New session" control. Resolves the target
10
11
  // project (falling back to the default project when omitted), delegates the real creation to the
11
12
  // injected `createDirectSession` dep (domain primitive wired in entry/app.ts), and returns the new
@@ -23,9 +24,22 @@ export async function handleSendSession(deps, args) {
23
24
  if (!args.text.trim() && (!args.attachments || args.attachments.length === 0)) {
24
25
  return { ok: false, code: 'invalid-args', message: 'Either text or attachments required' };
25
26
  }
27
+ // Scheduled run (design 27b): a reply adopts the run as a normal direct session FIRST — its
28
+ // registry channel is the shared project channel, which a web send must never target.
29
+ let channel = session.channel;
30
+ if (session.kind === 'scheduled') {
31
+ if (!deps.adoptScheduledSession) {
32
+ return { ok: false, code: 'not-available', message: 'Replying to scheduled runs is not available' };
33
+ }
34
+ const adopted = await deps.adoptScheduledSession({ sessionId: args.sessionId });
35
+ if (!adopted) {
36
+ return { ok: false, code: 'not-found', message: `Session not found: ${args.sessionId}` };
37
+ }
38
+ channel = adopted.channel;
39
+ }
26
40
  deps.sendSessionMessage({
27
41
  sessionId: args.sessionId,
28
- channel: session.channel,
42
+ channel,
29
43
  text: args.text,
30
44
  attachments: args.attachments,
31
45
  });
@@ -181,6 +195,16 @@ export async function handleAnswerQuestion(deps, args) {
181
195
  }
182
196
  return { ok: true, data: { outcome } };
183
197
  }
198
+ // Web UI: decline the auto-resume promised when a rate limit interrupted this session's turn.
199
+ // The queue is keyed by conduit, and a web session's conduit is `web:<sessionId>`. Idempotent:
200
+ // once the window resets the entry is drained by the dispatcher, so a late click reports
201
+ // `cancelled: false` rather than failing.
202
+ export async function handleCancelResume(args) {
203
+ if (!args.sessionId) {
204
+ return { ok: false, code: 'invalid-args', message: 'sessionId required' };
205
+ }
206
+ return { ok: true, data: { cancelled: removeDirectResume(`web:${args.sessionId}`) } };
207
+ }
184
208
  // Web UI: resolve a pending plan-approval interaction. Same three-way outcome as
185
209
  // handleAnswerQuestion.
186
210
  export async function handleRespondPlan(deps, args) {
@@ -1,2 +1,3 @@
1
- import type { SystemRestartArgs, SystemRestartReturn, Result } from '../types.js';
1
+ import type { SystemRestartArgs, SystemRestartReturn, SystemClearRateLimitArgs, SystemClearRateLimitReturn, Result } from '../types.js';
2
+ export declare function handleSystemClearRateLimit(args: SystemClearRateLimitArgs): Promise<Result<SystemClearRateLimitReturn>>;
2
3
  export declare function handleSystemRestart(args: SystemRestartArgs): Promise<Result<SystemRestartReturn>>;
@@ -1,6 +1,6 @@
1
- // input: STORE_DIR paths (.restart trigger, daemon-child.pid), SIGTERM/SIGKILL
2
- // output: handleSystemRestart(args) → SystemRestartReturn
3
- // pos: mutate handler for 'system.restart'. Three levels:
1
+ // input: STORE_DIR paths (.restart trigger, daemon-child.pid), SIGTERM/SIGKILL, active throttle state
2
+ // output: handleSystemRestart(args) → SystemRestartReturn; handleSystemClearRateLimit(args) → SystemClearRateLimitReturn
3
+ // pos: mutate handlers for 'system.restart' (three levels) and 'system.clearRateLimit' (early throttle lift)
4
4
  // soft — touch STORE_DIR/.restart (daemon's fs.watch picks it up, drains, respawns)
5
5
  // hard — SIGTERM the child PID from daemon-child.pid (daemon auto-recovers)
6
6
  // force — SIGKILL the child PID (daemon auto-recovers)
@@ -9,6 +9,7 @@ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
9
9
  import { utimesSync } from 'node:fs';
10
10
  import * as path from 'node:path';
11
11
  import { STORE_DIR } from '../../../core/paths.js';
12
+ import { clearThrottle } from '../../costs/rate-limit-throttle.js';
12
13
  function readChildPid() {
13
14
  const childPidFile = path.join(STORE_DIR, 'daemon-child.pid');
14
15
  try {
@@ -33,6 +34,19 @@ function checkLiveness(pid) {
33
34
  return false;
34
35
  }
35
36
  }
37
+ export async function handleSystemClearRateLimit(args) {
38
+ try {
39
+ const result = await clearThrottle(args.provider ?? null);
40
+ return { ok: true, data: result };
41
+ }
42
+ catch (error) {
43
+ return {
44
+ ok: false,
45
+ code: 'internal',
46
+ message: `Failed to clear rate limit: ${error.message || String(error)}`,
47
+ };
48
+ }
49
+ }
36
50
  export async function handleSystemRestart(args) {
37
51
  const { kind } = args;
38
52
  // ── Soft restart: touch .restart trigger ────────────────────────
@@ -0,0 +1,4 @@
1
+ import type { UiServiceDeps, Result, ThreadTemplatesValidateArgs, ThreadTemplatesValidateReturn, ThreadTemplatesSaveArgs, ThreadTemplatesSaveReturn, ThreadTemplatesRemoveArgs, ThreadTemplatesRemoveReturn } from '../types.js';
2
+ export declare function handleThreadTemplatesValidate(_deps: UiServiceDeps, args: ThreadTemplatesValidateArgs): Promise<Result<ThreadTemplatesValidateReturn>>;
3
+ export declare function handleThreadTemplatesSave(_deps: UiServiceDeps, args: ThreadTemplatesSaveArgs): Promise<Result<ThreadTemplatesSaveReturn>>;
4
+ export declare function handleThreadTemplatesRemove(_deps: UiServiceDeps, args: ThreadTemplatesRemoveArgs): Promise<Result<ThreadTemplatesRemoveReturn>>;
@@ -0,0 +1,71 @@
1
+ // input: UiServiceDeps + thread-template validate / save / remove arguments
2
+ // output: validate/save/remove handlers → Ok | Err
3
+ // pos: mutate handlers for the 'threadTemplates.*' operations. The write path the config never
4
+ // had — see domain/threads/template-writer.ts for the rules it enforces. `validate` is a
5
+ // mutation despite being side-effect-free because it carries a whole JSON body, which does
6
+ // not belong in a batched GET url (same reasoning as hooks.test).
7
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
8
+ import { saveEntity, removeEntity } from '../../threads/template-writer.js';
9
+ import { validateEntity, withCandidate, rawRegistryFromDir, } from '../../threads/template-validate.js';
10
+ import { CONFIG_TEMPLATES_DIR, loaderRefResolver, loadConfig, } from '../../threads/template-loader.js';
11
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
12
+ import * as path from 'node:path';
13
+ const IO = {
14
+ readdirSync: (p) => readdirSync(p),
15
+ readFileSync: (p, enc) => readFileSync(p, enc),
16
+ existsSync,
17
+ join: path.join,
18
+ };
19
+ /** Writer errors carry `code`; anything else is a genuine internal failure. `conflict` reaches the
20
+ * UI intact so the editor can offer a reload instead of a generic failure toast. */
21
+ function toErr(error) {
22
+ const code = error?.code;
23
+ const known = code === 'not-found' || code === 'invalid-args' || code === 'conflict';
24
+ return {
25
+ ok: false,
26
+ code: known ? String(code) : 'internal',
27
+ message: error instanceof Error ? error.message : String(error),
28
+ };
29
+ }
30
+ function currentRegistry() {
31
+ return rawRegistryFromDir(CONFIG_TEMPLATES_DIR, IO);
32
+ }
33
+ export async function handleThreadTemplatesValidate(_deps, args) {
34
+ try {
35
+ // Judge the candidate by the world it would produce, not the one it replaces.
36
+ const registry = withCandidate(currentRegistry(), args.kind, args.name, args.body);
37
+ const { errors, warnings } = validateEntity(args.kind, args.name, args.body, registry, loaderRefResolver());
38
+ return { ok: true, data: { ok: errors.length === 0, errors, warnings } };
39
+ }
40
+ catch (error) {
41
+ return toErr(error);
42
+ }
43
+ }
44
+ export async function handleThreadTemplatesSave(_deps, args) {
45
+ try {
46
+ const result = saveEntity(CONFIG_TEMPLATES_DIR, { kind: args.kind, name: args.name, body: args.body, baseHash: args.baseHash ?? null }, loaderRefResolver());
47
+ // Reload now rather than waiting on the 300ms debounced watcher, so the response the UI gets
48
+ // back already reflects a registry that has accepted the change. The watcher still fires; a
49
+ // second load is idempotent.
50
+ if (result.changed)
51
+ loadConfig();
52
+ return {
53
+ ok: true,
54
+ data: { changed: result.changed, sha256: result.sha256, warnings: result.warnings },
55
+ };
56
+ }
57
+ catch (error) {
58
+ return toErr(error);
59
+ }
60
+ }
61
+ export async function handleThreadTemplatesRemove(_deps, args) {
62
+ try {
63
+ const result = removeEntity(CONFIG_TEMPLATES_DIR, args.kind, args.name);
64
+ if (result.removed)
65
+ loadConfig();
66
+ return { ok: true, data: { removed: result.removed } };
67
+ }
68
+ catch (error) {
69
+ return toErr(error);
70
+ }
71
+ }
@@ -27,17 +27,39 @@ async function listJsonBasenames(dir) {
27
27
  return [];
28
28
  }
29
29
  }
30
+ // Per-project overrides are pair-only: an entry missing either limit is dropped rather than
31
+ // surfaced half-null, so the panel can never render an override that does not fully exist.
32
+ function parseProjectBudgets(raw) {
33
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
34
+ return {};
35
+ const out = {};
36
+ for (const [id, value] of Object.entries(raw)) {
37
+ if (!id || !value || typeof value !== 'object')
38
+ continue;
39
+ if (typeof value.daily_usd !== 'number' || typeof value.monthly_usd !== 'number')
40
+ continue;
41
+ out[id] = { daily_usd: value.daily_usd, monthly_usd: value.monthly_usd };
42
+ }
43
+ return out;
44
+ }
30
45
  function parseBudget(raw) {
31
46
  if (!raw || typeof raw !== 'object')
32
47
  return null;
33
48
  return {
34
49
  daily_usd: typeof raw.daily_usd === 'number' ? raw.daily_usd : null,
35
50
  monthly_usd: typeof raw.monthly_usd === 'number' ? raw.monthly_usd : null,
51
+ projects: parseProjectBudgets(raw.projects),
36
52
  };
37
53
  }
38
54
  function isLiveBackend(value) {
39
55
  return value === 'claude' || value === 'pi';
40
56
  }
57
+ // extraOption is CLI flags and is returned whole — the settings editor has to round-trip it.
58
+ function parseStringMap(raw) {
59
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
60
+ return {};
61
+ return Object.fromEntries(Object.entries(raw).filter((pair) => typeof pair[1] === 'string'));
62
+ }
41
63
  function parseProfiles(raw) {
42
64
  if (!raw || typeof raw !== 'object' || !raw.profiles || typeof raw.profiles !== 'object')
43
65
  return null;
@@ -50,6 +72,14 @@ function parseProfiles(raw) {
50
72
  backend: isLiveBackend(p?.backend) ? p.backend : null,
51
73
  mode: typeof p?.mode === 'string' ? p.mode : null,
52
74
  thinking: typeof p?.thinking === 'string' ? p.thinking : null,
75
+ provider: typeof p?.provider === 'string' ? p.provider : null,
76
+ claudeBackend: p?.claudeBackend === 'print' || p?.claudeBackend === 'tui' ? p.claudeBackend : null,
77
+ extraOption: parseStringMap(p?.extraOption),
78
+ // KEYS ONLY — an extraEnv value is injected into the agent environment and may be a token.
79
+ extraEnvKeys: p?.extraEnv && typeof p.extraEnv === 'object' && !Array.isArray(p.extraEnv)
80
+ ? Object.keys(p.extraEnv).sort()
81
+ : [],
82
+ fallbackCount: Array.isArray(p?.fallback) ? p.fallback.length : 0,
53
83
  }];
54
84
  });
55
85
  const requestedDefault = typeof raw.defaultProfile === 'string' ? raw.defaultProfile : null;
@@ -0,0 +1,8 @@
1
+ import { type CustomProviderView } from '../../pi-providers/index.js';
2
+ import type { AuthCustomProvidersParams, UiServiceDeps } from '../types.js';
3
+ /**
4
+ * Every entry is derived from PI's own catalog joined with its gateway route, so the list shows the
5
+ * same definitions the terminal `pi` sees. The upstream key stays in the gateway config: the view
6
+ * reports only whether one is stored.
7
+ */
8
+ export declare function handleCustomProvidersList(deps: UiServiceDeps, _params: AuthCustomProvidersParams): Promise<CustomProviderView[]>;
@@ -0,0 +1,13 @@
1
+ // input: the custom provider stores held in UiServiceDeps
2
+ // output: the secret-free auth.customProviders listing
3
+ // pos: Read adapter for user-defined PI providers
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import { defaultCustomProviderStores, listCustomProviders, } from '../../pi-providers/index.js';
6
+ /**
7
+ * Every entry is derived from PI's own catalog joined with its gateway route, so the list shows the
8
+ * same definitions the terminal `pi` sees. The upstream key stays in the gateway config: the view
9
+ * reports only whether one is stored.
10
+ */
11
+ export async function handleCustomProvidersList(deps, _params) {
12
+ return listCustomProviders(deps.customProviderStores ?? defaultCustomProviderStores());
13
+ }
@@ -0,0 +1,2 @@
1
+ import type { UiServiceDeps, MachineDetail, MachineDetailParams } from '../types.js';
2
+ export declare function handleMachineDetail(deps: UiServiceDeps, params: MachineDetailParams): Promise<MachineDetail>;
@@ -0,0 +1,56 @@
1
+ // input: UiServiceDeps + MachineDetailParams (machine name)
2
+ // output: machines.detail handler → MachineDetail (live probe + running dispatch join)
3
+ // pos: query handler for 'machines.detail', the lazy per-machine expand
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import { buildProbeCommand, parseMachineProbe, PROBE_TIMEOUT_MS } from './machine-probe.js';
6
+ /**
7
+ * Running dispatch executions on this machine. `gpuIndices` is the ordinal set the client watcher
8
+ * actually acquired for the run — the only recorded run↔GPU link, which is what lets the UI badge a
9
+ * GPU row with its owning run. Process pids are deliberately NOT matched: dispatch.pid is the
10
+ * cortex-run launcher, not the CUDA process, so any such join would be fabricated.
11
+ */
12
+ function collectLiveRuns(deps, machine) {
13
+ return deps.executionRegistry
14
+ .getAll()
15
+ .filter((exec) => exec?.status === 'running' && exec?.dispatch?.machine === machine)
16
+ .map((exec) => ({
17
+ executionId: String(exec.id),
18
+ taskId: exec.dispatch?.taskId ?? null,
19
+ runName: exec.dispatch?.runName ?? null,
20
+ project: exec.project ?? null,
21
+ gpuIndices: Array.isArray(exec.gpu?.indices) ? exec.gpu.indices : [],
22
+ startedAt: exec.runtime?.startedAt ?? null,
23
+ }));
24
+ }
25
+ function emptyDetail(name, online, liveRuns, probeError) {
26
+ return { name, online, vitals: null, gpus: [], liveRuns, probedAt: null, probeError };
27
+ }
28
+ export async function handleMachineDetail(deps, params) {
29
+ const entry = deps.clientRegistry.getMachineRegistry()[params.machine];
30
+ if (!entry)
31
+ throw new Error(`Unknown machine: ${params.machine}`);
32
+ const liveRuns = collectLiveRuns(deps, params.machine);
33
+ // Offline devices are answered from the registry alone — never a round trip that can only time out.
34
+ if (!deps.clientRegistry.isDeviceOnline(params.machine)) {
35
+ return emptyDetail(params.machine, false, liveRuns, null);
36
+ }
37
+ const probe = deps.clientRegistry.probeMachine;
38
+ if (!probe)
39
+ return emptyDetail(params.machine, true, liveRuns, 'Probe transport unavailable');
40
+ try {
41
+ const raw = await probe(params.machine, buildProbeCommand(entry.cortexPath), PROBE_TIMEOUT_MS);
42
+ const { vitals, gpus } = parseMachineProbe(raw);
43
+ return {
44
+ name: params.machine,
45
+ online: true,
46
+ vitals,
47
+ gpus,
48
+ liveRuns,
49
+ probedAt: new Date().toISOString(),
50
+ probeError: null,
51
+ };
52
+ }
53
+ catch (err) {
54
+ return emptyDetail(params.machine, true, liveRuns, err instanceof Error ? err.message : String(err));
55
+ }
56
+ }
@@ -0,0 +1,18 @@
1
+ import type { MachineGpu, MachineVitals } from '../types.js';
2
+ /** Probe budget: one bash round trip. Above the client's own spawn latency, below a stuck device. */
3
+ export declare const PROBE_TIMEOUT_MS = 15000;
4
+ /**
5
+ * One command, one round trip. Every stage is individually failure-tolerant (`2>/dev/null`) so a
6
+ * host without nvidia-smi, /proc or `free` still returns the sections it can fill — the parser maps
7
+ * the missing ones to null rather than to zero. `df -kP` forces POSIX single-line output.
8
+ */
9
+ export declare function buildProbeCommand(cortexPath: string | null): string;
10
+ /**
11
+ * Split the probe stdout on its `##SECTION` markers, then join compute processes onto their GPU by
12
+ * uuid. The uuid is a join key only — it stays out of the DTO. Malformed lines are dropped silently
13
+ * because a partially-degraded host is the normal case, not an error worth failing the whole probe.
14
+ */
15
+ export declare function parseMachineProbe(raw: string): {
16
+ vitals: MachineVitals;
17
+ gpus: MachineGpu[];
18
+ };