@skyhook-io/radar-app 1.22.2 → 1.23.0

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 (196) hide show
  1. package/package.json +8 -8
  2. package/src/App.tsx +35 -10
  3. package/src/RadarApp.basename.test.tsx +177 -0
  4. package/src/RadarApp.settings.test.tsx +33 -0
  5. package/src/api/agentSandbox.ts +259 -0
  6. package/src/api/client.autoPromConnect.test.tsx +43 -0
  7. package/src/api/client.metricsRelayCheck.test.tsx +134 -0
  8. package/src/api/client.ts +122 -24
  9. package/src/api/cloudInstallDiscover.test.tsx +76 -0
  10. package/src/api/diagnose.ts +4 -0
  11. package/src/api/kagent.test.ts +82 -0
  12. package/src/api/kagent.ts +230 -0
  13. package/src/api/prometheusCharts.ts +5 -0
  14. package/src/api/radarFeatures.test.ts +9 -0
  15. package/src/api/radarFeatures.ts +13 -0
  16. package/src/api/substrateWorkspace.test.ts +72 -0
  17. package/src/api/substrateWorkspace.ts +1394 -0
  18. package/src/api/vulnerabilities.ts +207 -9
  19. package/src/api/workloadSource.test.tsx +315 -0
  20. package/src/api/workloadSource.ts +128 -12
  21. package/src/components/CloudConnectFlow.tsx +46 -7
  22. package/src/components/CloudFunnelButton.test.tsx +193 -7
  23. package/src/components/CloudFunnelButton.tsx +127 -32
  24. package/src/components/SelfManagedStart.tsx +12 -2
  25. package/src/components/agentsandbox/AgentSandboxKindLists.tsx +41 -0
  26. package/src/components/agentsandbox/AgentSandboxLists.test.tsx +410 -0
  27. package/src/components/agentsandbox/AgentSandboxOverview.test.tsx +333 -0
  28. package/src/components/agentsandbox/AgentSandboxOverview.tsx +555 -0
  29. package/src/components/agentsandbox/AgentSandboxSidebar.test.tsx +97 -0
  30. package/src/components/agentsandbox/AgentSandboxSummary.test.tsx +439 -0
  31. package/src/components/agentsandbox/AgentSandboxSummary.tsx +956 -0
  32. package/src/components/agentsandbox/AgentSandboxTables.tsx +966 -0
  33. package/src/components/agentsandbox/AgentSandboxView.tsx +34 -0
  34. package/src/components/agentsandbox/agentsandbox.fixtures.ts +135 -0
  35. package/src/components/agentsandbox/data.ts +135 -0
  36. package/src/components/agentsandbox/host.test.ts +27 -0
  37. package/src/components/agentsandbox/host.tsx +85 -0
  38. package/src/components/agentsandbox/labels.test.ts +42 -0
  39. package/src/components/agentsandbox/labels.ts +146 -0
  40. package/src/components/agentsandbox/listFilters.ts +85 -0
  41. package/src/components/agentsandbox/lists.ts +52 -0
  42. package/src/components/agentsandbox/routes.ts +23 -0
  43. package/src/components/agentsandbox/shared.tsx +321 -0
  44. package/src/components/agentsandbox/useAgentSandboxSidebarWorkspace.ts +69 -0
  45. package/src/components/agentsandbox/workspace.fixtures.ts +125 -0
  46. package/src/components/agentsandbox/workspace.tsx +258 -0
  47. package/src/components/agentsandbox/workspaceRoute.ts +18 -0
  48. package/src/components/applications/ApplicationsView.openResource.test.tsx +248 -3
  49. package/src/components/applications/ApplicationsView.tsx +156 -3
  50. package/src/components/audit/VulnerabilitiesColumns.test.tsx +487 -0
  51. package/src/components/audit/VulnerabilitiesRisk.test.tsx +318 -0
  52. package/src/components/audit/VulnerabilitiesView.test.tsx +458 -13
  53. package/src/components/audit/VulnerabilitiesView.tsx +639 -199
  54. package/src/components/cloudHints/AgentSetupCloudRow.tsx +28 -0
  55. package/src/components/cloudHints/CloudHintLink.tsx +29 -0
  56. package/src/components/cloudHints/SharedInstallAiLine.tsx +36 -0
  57. package/src/components/cloudHints/cloudHints.test.ts +126 -0
  58. package/src/components/cloudHints/cloudHints.ts +131 -0
  59. package/src/components/cloudHints/cloudHintsGate.test.tsx +70 -0
  60. package/src/components/cloudHints/cloudLinks.test.ts +52 -0
  61. package/src/components/cloudHints/cloudLinks.ts +31 -0
  62. package/src/components/cloudHints/hintStorage.ts +28 -0
  63. package/src/components/cnpg/CNPGView.tsx +4 -7
  64. package/src/components/diagnose/AgentSetupNotice.tsx +5 -0
  65. package/src/components/diagnose/DiagnoseContext.tsx +7 -0
  66. package/src/components/diagnose/DiagnoseSurface.escape.test.tsx +215 -0
  67. package/src/components/diagnose/DiagnoseSurface.tsx +57 -1
  68. package/src/components/gitops/RemoteDestinationCloudHint.tsx +6 -14
  69. package/src/components/home/HomeAgentBlock.tsx +2 -0
  70. package/src/components/home/HomeView.tsx +3 -3
  71. package/src/components/home/MCPSetupDialog.test.tsx +9 -0
  72. package/src/components/home/MCPSetupDialog.tsx +6 -2
  73. package/src/components/home/McpCloudLine.test.tsx +162 -0
  74. package/src/components/home/McpCloudLine.tsx +95 -0
  75. package/src/components/home/ProblemsPanel.investigate.test.tsx +2 -2
  76. package/src/components/home/mcpToolCatalog.test.ts +10 -0
  77. package/src/components/home/mcpToolCatalog.ts +4 -4
  78. package/src/components/issues/ClusterSchedulingBlockerRow.tsx +35 -0
  79. package/src/components/issues/IssuesPane.render.test.tsx +36 -1
  80. package/src/components/issues/IssuesPane.tsx +181 -23
  81. package/src/components/issues/SinceLastVisitRow.render.test.tsx +302 -0
  82. package/src/components/issues/SinceLastVisitRow.tsx +71 -0
  83. package/src/components/issues/sinceLastVisit.test.ts +266 -0
  84. package/src/components/issues/sinceLastVisit.ts +439 -0
  85. package/src/components/kagent/KagentAgentRenderer.test.ts +32 -0
  86. package/src/components/kagent/KagentAgentRenderer.tsx +87 -0
  87. package/src/components/kagent/KagentAgentSessions.test.tsx +166 -0
  88. package/src/components/kagent/KagentAgentSessions.tsx +124 -0
  89. package/src/components/kagent/KagentDetailPage.tsx +106 -0
  90. package/src/components/kagent/KagentLists.tsx +412 -0
  91. package/src/components/kagent/KagentOverview.tsx +234 -0
  92. package/src/components/kagent/KagentPages.tsx +690 -0
  93. package/src/components/kagent/KagentRuntimeTabs.test.tsx +219 -0
  94. package/src/components/kagent/KagentRuntimeTabs.tsx +283 -0
  95. package/src/components/kagent/KagentSidebar.test.tsx +112 -0
  96. package/src/components/kagent/KagentView.tsx +109 -0
  97. package/src/components/kagent/KagentWorkspace.test.tsx +876 -0
  98. package/src/components/kagent/host.tsx +144 -0
  99. package/src/components/kagent/routes.ts +31 -0
  100. package/src/components/kagent/shared.tsx +336 -0
  101. package/src/components/kagent/useKagentRuntime.test.tsx +77 -0
  102. package/src/components/kagent/useKagentSidebarWorkspace.ts +67 -0
  103. package/src/components/kagent/workspace.fixtures.ts +108 -0
  104. package/src/components/kagent/workspaceRoute.ts +18 -0
  105. package/src/components/resource/MetricsNotConnected.test.tsx +28 -0
  106. package/src/components/resource/MetricsNotConnected.tsx +10 -7
  107. package/src/components/resource/PrometheusCharts.tsx +10 -1
  108. package/src/components/resource/PrometheusChartsGrid.render.test.tsx +9 -0
  109. package/src/components/resource/PrometheusChartsGrid.tsx +3 -3
  110. package/src/components/resource/SubstrateHealthCharts.test.tsx +13 -1
  111. package/src/components/resource/SubstrateHealthCharts.tsx +9 -15
  112. package/src/components/resources/ResourceDetailDrawer.tsx +1 -0
  113. package/src/components/resources/ResourcesView.tsx +2 -6
  114. package/src/components/resources/renderers/PodRenderer.tsx +8 -2
  115. package/src/components/settings/LocalIntegrationStatus.test.tsx +1 -0
  116. package/src/components/settings/LocalIntegrationStatus.tsx +3 -2
  117. package/src/components/settings/SettingsDialog.tsx +84 -16
  118. package/src/components/settings/SubstrateSettings.lifecycle.test.tsx +210 -0
  119. package/src/components/settings/SubstrateSettings.test.tsx +131 -0
  120. package/src/components/settings/SubstrateSettings.tsx +544 -0
  121. package/src/components/settings/settings-state.test.ts +21 -3
  122. package/src/components/settings/settings-state.ts +13 -3
  123. package/src/components/share/ShareLinkButton.test.tsx +360 -0
  124. package/src/components/share/ShareLinkButton.tsx +391 -0
  125. package/src/components/share/openShareInCloud.test.ts +29 -0
  126. package/src/components/share/openShareInCloud.ts +10 -0
  127. package/src/components/share/shareLink.test.ts +129 -0
  128. package/src/components/share/shareLink.ts +175 -0
  129. package/src/components/substrate/SubstrateActorDrawer.tsx +87 -0
  130. package/src/components/substrate/SubstrateActorOverview.tsx +489 -0
  131. package/src/components/substrate/SubstrateActorPage.tsx +384 -0
  132. package/src/components/substrate/SubstrateActors.test.tsx +1094 -0
  133. package/src/components/substrate/SubstrateActors.tsx +612 -0
  134. package/src/components/substrate/SubstrateAttentionList.tsx +441 -0
  135. package/src/components/substrate/SubstrateConnect.tsx +88 -0
  136. package/src/components/substrate/SubstrateOverview.test.tsx +396 -0
  137. package/src/components/substrate/SubstrateOverview.tsx +575 -0
  138. package/src/components/substrate/SubstratePages.test.tsx +478 -0
  139. package/src/components/substrate/SubstratePool.test.tsx +462 -0
  140. package/src/components/substrate/SubstratePoolPage.tsx +95 -0
  141. package/src/components/substrate/SubstratePoolSummary.tsx +485 -0
  142. package/src/components/substrate/SubstrateSidebar.test.tsx +101 -0
  143. package/src/components/substrate/SubstrateStateBar.tsx +63 -0
  144. package/src/components/substrate/SubstrateTemplates.tsx +376 -0
  145. package/src/components/substrate/SubstrateView.tsx +173 -0
  146. package/src/components/substrate/SubstrateWorkerPodContext.tsx +73 -0
  147. package/src/components/substrate/SubstrateWorkers.tsx +389 -0
  148. package/src/components/substrate/attention.ts +81 -0
  149. package/src/components/substrate/contextPin.tsx +69 -0
  150. package/src/components/substrate/host.tsx +83 -0
  151. package/src/components/substrate/kubectlTarget.test.tsx +77 -0
  152. package/src/components/substrate/readings.test.ts +484 -0
  153. package/src/components/substrate/readings.ts +997 -0
  154. package/src/components/substrate/routes.ts +103 -0
  155. package/src/components/substrate/shared.tsx +426 -0
  156. package/src/components/substrate/substrate.fixtures.ts +325 -0
  157. package/src/components/substrate/useSubstrateSidebarWorkspace.ts +87 -0
  158. package/src/components/substrate/workspaceRoute.ts +23 -0
  159. package/src/components/traffic/TrafficConnectionsTable.test.tsx +9 -0
  160. package/src/components/traffic/TrafficConnectionsTable.tsx +4 -2
  161. package/src/components/traffic/TrafficFilterSidebar.tsx +19 -14
  162. package/src/components/traffic/TrafficFlowList.test.tsx +63 -0
  163. package/src/components/traffic/TrafficFlowList.tsx +9 -5
  164. package/src/components/traffic/TrafficGraph.test.tsx +26 -0
  165. package/src/components/traffic/TrafficGraph.tsx +17 -14
  166. package/src/components/traffic/TrafficGraphTooLarge.tsx +2 -0
  167. package/src/components/traffic/TrafficGraphUnavailable.tsx +3 -1
  168. package/src/components/traffic/TrafficView.tsx +26 -56
  169. package/src/components/traffic/trafficFilters.test.ts +61 -1
  170. package/src/components/traffic/trafficFilters.ts +68 -8
  171. package/src/components/velero/VeleroOverview.tsx +2 -2
  172. package/src/components/velero/VeleroView.tsx +3 -6
  173. package/src/components/vulnerabilities/columns.tsx +132 -0
  174. package/src/components/vulnerabilities/filters.tsx +317 -0
  175. package/src/components/vulnerabilities/owner.test.ts +54 -0
  176. package/src/components/vulnerabilities/owner.tsx +163 -0
  177. package/src/components/vulnerabilities/parts.test.ts +126 -12
  178. package/src/components/vulnerabilities/parts.tsx +612 -52
  179. package/src/components/vulnerabilities/traffic.test.tsx +65 -0
  180. package/src/components/vulnerabilities/traffic.tsx +40 -0
  181. package/src/components/workload/WorkloadView.substrateVersion.test.tsx +88 -0
  182. package/src/components/workload/WorkloadView.tsx +52 -13
  183. package/src/components/workspace/layout.tsx +13 -7
  184. package/src/components/workspace/sidebar.test.ts +48 -0
  185. package/src/components/workspace/sidebar.ts +73 -3
  186. package/src/components/workspace/table.ts +2 -1
  187. package/src/contexts/RegistryAccessMode.test.tsx +51 -0
  188. package/src/contexts/RegistryAccessMode.tsx +25 -0
  189. package/src/integrations/resourceHost.ts +12 -6
  190. package/src/integrations/resourceHosts.test.tsx +27 -1
  191. package/src/integrations/resourceHosts.tsx +15 -7
  192. package/src/integrations/sidebarWorkspaces.test.tsx +63 -0
  193. package/src/integrations/sidebarWorkspaces.ts +41 -0
  194. package/src/integrations/workspaceRoute.ts +1 -1
  195. package/src/integrations/workspaceRoutes.ts +7 -1
  196. package/src/integrations/workspaceScreens.tsx +6 -0
@@ -0,0 +1,1394 @@
1
+ import { useMutation, useQuery, useQueryClient, type QueryKey } from '@tanstack/react-query'
2
+ import { getApiBase } from './config'
3
+ import { ApiError, apiFetch, fetchJSON, useClusterInfo, useRadarFeature } from './client'
4
+ import { httpStatusMessage, readErrorBody } from './httpErrors'
5
+
6
+ // Agent Substrate workspace: /api/substrate/*. Wire shapes mirror
7
+ // pkg/substrate (read model, derivations) and
8
+ // internal/server/substrate_workspace_handlers.go.
9
+ //
10
+ // What an absent field means depends on the field, and each says which:
11
+ // - an object or a measurement (a count, a duration, a reading): unknown,
12
+ // not reported or not read, never zero;
13
+ // - a list or map on something Substrate returned: empty (snapshots: none;
14
+ // a workerSelector: matches every pool), and a template's cpu/memory: 0;
15
+ // - a boolean: false;
16
+ // - a list a response builds from reads (rows, assigned actors, atespaces,
17
+ // freeSlots): [] when read and empty, absent when not read.
18
+ //
19
+ // A private local Radar reads the API tier (actors, templates, workers) with
20
+ // the context's saved identity. Managed installations read as ate-client
21
+ // using each signed-in caller's Kubernetes access to mint the token, when
22
+ // the operator enables API access.
23
+
24
+ export type SubstrateActorState =
25
+ | 'running'
26
+ | 'suspended'
27
+ | 'resuming'
28
+ | 'suspending'
29
+ | 'reverting'
30
+ | 'crashed'
31
+ | 'deleting'
32
+ | 'unknown'
33
+
34
+ /**
35
+ * connected: a snapshot was read (it may be stale: see refreshing/lastError).
36
+ * connecting: the first read is running for the saved or managed connection.
37
+ * notConfigured: no identity saved for this local context.
38
+ * disabled: this Radar does not read Substrate's API for this request (code
39
+ * sharedRadar: a shared Radar without sign-in; apiDisabled: turned off by the
40
+ * operator). failed: the connection could not be established or no usable
41
+ * snapshot could be read.
42
+ */
43
+ export type SubstrateTierState = 'connected' | 'connecting' | 'notConfigured' | 'disabled' | 'failed'
44
+
45
+ /** Shared by apiTier.code, coverage codes and error_code on error responses. */
46
+ export type SubstrateCode =
47
+ /** A shared Radar without sign-in: it cannot tell who is asking, so it does not read Substrate's API (403). */
48
+ | 'sharedRadar'
49
+ /** The operator turned Substrate's API off for this Radar (Helm substrate.api.enabled: false) (403). */
50
+ | 'apiDisabled'
51
+ /** The installation's connection settings are operator-managed (PUT /connection, 403). */
52
+ | 'operator_managed'
53
+ /** Radar cannot mint ate-system/ate-client using the Kubernetes credentials for this read (403). */
54
+ | 'mintDenied'
55
+ /** User-token mode requires a Kubernetes token on this request (403). */
56
+ | 'userTokenRequired'
57
+ | 'notConfigured'
58
+ /** The current Kubernetes target differs from the reviewed or saved target. */
59
+ | 'targetChanged'
60
+ | 'notInstalled'
61
+ | 'tls'
62
+ | 'unreachable'
63
+ | 'unauthenticated'
64
+ | 'denied'
65
+ | 'notFound'
66
+ | 'capExceeded'
67
+ /** Substrate would not list atespaces; Radar read only the settings' atespaces, others are unknown. */
68
+ | 'scoped'
69
+ /** The cluster connection or the settings changed during the read; safe to retry. */
70
+ | 'contextChanged'
71
+ /** A read failed, including a snapshot read with no usable kind and at least one failed kind. */
72
+ | 'failed'
73
+ /** Invalid connection input, invalid installation settings, or an unavailable token file. */
74
+ | 'invalidSettings'
75
+ /** Radar could not read or write ~/.radar/substrate.json. */
76
+ | 'settingsFile'
77
+ /** The saved revision changed, or the file is being updated (PUT /connection, 409). */
78
+ | 'conflict'
79
+ /** The save keeps the saved credential but sends it to a new endpoint, CA or server name (PUT /connection, 409). */
80
+ | 'confirmDestination'
81
+ /** The worker Pod's log could not be read (the logs endpoint only, 502). */
82
+ | 'logsUnavailable'
83
+ /** Radar read too little to say whether the WorkerPool exists (pool detail, 503). */
84
+ | 'incomplete'
85
+ | 'outside_namespace_pin'
86
+
87
+ export interface SubstrateIdentity {
88
+ /**
89
+ * shared: ate-system/ate-client, minted with Radar's Kubernetes access. sharedAsCaller: the same
90
+ * identity, minted with the signed-in person's own access; implicit, nothing to save or edit.
91
+ */
92
+ mode: 'shared' | 'tokenFile' | 'sharedAsCaller'
93
+ /** Who Substrate sees. Absent for tokenFile: Substrate does not tell a client who its token is. */
94
+ principal?: string
95
+ }
96
+
97
+ export interface SubstrateAPITier {
98
+ state: SubstrateTierState
99
+ /** Why, in a sentence; absent when connected. */
100
+ reason?: string
101
+ /**
102
+ * Set with notConfigured, disabled (sharedRadar or apiDisabled), or failed
103
+ * (targetChanged, contextChanged, notInstalled, tls, unreachable,
104
+ * unauthenticated, mintDenied, userTokenRequired, invalidSettings, settingsFile or failed).
105
+ */
106
+ code?: SubstrateCode
107
+ /** The saved or managed connection’s identity and endpoint, when known. */
108
+ identity?: SubstrateIdentity
109
+ endpoint?: string
110
+ /**
111
+ * RFC 3339. The read that produced the snapshot served ran from
112
+ * readStartedAt to readAt (its completion); its counts were observed over
113
+ * that interval, not at one instant. Absent when no read has completed.
114
+ */
115
+ readStartedAt?: string
116
+ readAt?: string
117
+ /** The snapshot served is older than ~5s and a newer read is running, or the newest one failed (lastError). Served for up to 2 min. */
118
+ refreshing?: boolean
119
+ /** The newest read's failure while an older snapshot is served, including a failure with no usable kind. */
120
+ lastError?: { code: SubstrateCode; message: string; at: string }
121
+ }
122
+
123
+ export interface SubstrateCoverage {
124
+ /**
125
+ * full: every page of every scope (the same word as KindCoverage). partial:
126
+ * some atespaces denied, unread or not named, or the budget reached.
127
+ */
128
+ state: 'full' | 'partial' | 'denied' | 'failed'
129
+ code?: SubstrateCode
130
+ message?: string
131
+ /**
132
+ * The atespaces read one by one: in a snapshot when the list across
133
+ * atespaces was denied; on /actors?atespace= the one read directly. Listed
134
+ * is not complete: with code capExceeded the budget may have cut any short.
135
+ */
136
+ readAtespaces?: string[]
137
+ deniedAtespaces?: string[]
138
+ /** Atespaces not read because the read's budget ran out first; what they hold is unknown. */
139
+ unreadAtespaces?: string[]
140
+ /** Items read; absent when none could be. */
141
+ count?: number
142
+ /** The limit reached, with code capExceeded. */
143
+ cap?: number
144
+ }
145
+
146
+ export interface SubstrateSnapshotCoverage {
147
+ actors: SubstrateCoverage
148
+ templates: SubstrateCoverage
149
+ workers: SubstrateCoverage
150
+ atespaces: SubstrateCoverage
151
+ }
152
+
153
+ /**
154
+ * The Kubernetes side: WorkerPools as the caller may list them, in the shape
155
+ * every workspace serves per kind (integration.KindCoverage). Only full and
156
+ * notInstalled are complete enough to say a pool does not exist; syncing,
157
+ * uncached, denied and error mean the pools are unknown, not none.
158
+ */
159
+ export interface SubstratePoolsCoverage {
160
+ state: 'full' | 'partial' | 'denied' | 'uncached' | 'notInstalled' | 'syncing' | 'error'
161
+ /** In-scope namespaces the caller cannot list. */
162
+ deniedNamespaces?: string[]
163
+ /** In-scope namespaces the caller can list and Radar has not collected. */
164
+ uncachedNamespaces?: string[]
165
+ /** On a partial read, the namespaces Radar read. */
166
+ allowedNamespaces?: string[]
167
+ }
168
+
169
+ export interface SubstrateRef {
170
+ atespace: string
171
+ name: string
172
+ }
173
+
174
+ /** A kagent Agent (api.kagent.dev), a Kubernetes object. */
175
+ export interface KagentAgentRef {
176
+ namespace: string
177
+ name: string
178
+ }
179
+
180
+ /** Why a kagent session's actor is tied to no Agent; see pkg/substrate KagentAttribution. */
181
+ export type KagentUnattributedReason =
182
+ /** Its template is named for an Agent the caller reads, for neither current revision, and Radar can't prove it is that Agent's: the template predates the Agent, a time is missing, or the name was cut. */
183
+ | 'earlierRevision'
184
+ /** The caller can't read Agents in the template's namespace, or Radar hasn't read them there. */
185
+ | 'agentNotReadable'
186
+ /** No Agent read in that namespace produces the template's name. */
187
+ | 'noAgent'
188
+ /** Current revisions of more than one Agent produce the template's name. */
189
+ | 'ambiguous'
190
+ /** kagent's naming could not have produced the template, or it is in another atespace than the actor. */
191
+ | 'templateUnknown'
192
+
193
+ /**
194
+ * Which kagent Agent an actor or template belongs to, judged against the Agents the caller can read,
195
+ * per request. agentSession: exactly the template of one Agent's current revision. Only exact matches:
196
+ * a hint (candidates) is never counted as an Agent's.
197
+ */
198
+ export type KagentAttribution = KagentAgentAttribution | KagentSandboxAttribution | KagentUnattributed
199
+
200
+ /** agentSession: the template is one Agent's, so the actors on it are that Agent's sessions. */
201
+ export interface KagentAgentAttribution {
202
+ kind: 'agentSession'
203
+ agent: KagentAgentRef
204
+ /** The Agent revision's full digest; on an earlier revision, the 12 hex its template's name carries. */
205
+ revision: string
206
+ /** The revision is the Agent's latestSuccessfulRevision, which kagent starts new sessions on. */
207
+ newSessions?: boolean
208
+ /** The revision is the Agent's desiredRevision. */
209
+ desired?: boolean
210
+ /**
211
+ * The template is the Agent's for an earlier revision: Substrate created it at least 2s after the Agent,
212
+ * and a kagent session runs on it.
213
+ */
214
+ earlierRevision?: boolean
215
+ }
216
+
217
+ /** The template is a kagent sandbox's; no Agent is needed. */
218
+ export interface KagentSandboxAttribution {
219
+ kind: 'sandbox'
220
+ }
221
+
222
+ export interface KagentUnattributed {
223
+ kind: 'unattributed'
224
+ reason: KagentUnattributedReason
225
+ /** earlierRevision: the Agents the template is named for; ambiguous: the Agents it matches. A hint only. */
226
+ candidates?: KagentAgentRef[]
227
+ }
228
+
229
+ /** A kagent session's actor with its attribution. */
230
+ export type KagentActor = KagentAttribution & { sessionId: string }
231
+
232
+ export interface SubstratePoolRef {
233
+ namespace: string
234
+ name: string
235
+ }
236
+
237
+ export interface SubstrateSnapshot {
238
+ generation: number
239
+ fidelity?: 'memory' | 'rootfs' | 'volumes'
240
+ owner?: 'actor' | 'tag'
241
+ /** The node holding the snapshot's files; absent once detached. */
242
+ locality?: string
243
+ /** none: no durable copy recorded; the files exist only on `locality`, if any. */
244
+ durable: 'pending' | 'completed' | 'none'
245
+ sandboxClass?: string
246
+ }
247
+
248
+ export interface SubstrateAssignment {
249
+ /** Substrate's opaque Worker name. */
250
+ worker: string
251
+ namespace: string
252
+ pool: string
253
+ pod: string
254
+ node: string
255
+ epoch?: number
256
+ sandboxClass?: string
257
+ }
258
+
259
+ export interface SubstrateActor {
260
+ atespace: string
261
+ name: string
262
+ uid?: string
263
+ template: SubstrateRef
264
+ /** Absent when the actor started from its template. */
265
+ sourceTag?: SubstrateRef
266
+ state: SubstrateActorState
267
+ /** Absent whenever the actor has no worker (suspended, crashed). */
268
+ assignment?: SubstrateAssignment
269
+ /** The last node Substrate recorded, even after it clears assignment. */
270
+ assignedNode?: string
271
+ crash?: { message?: string; time?: string }
272
+ snapshots?: SubstrateSnapshot[]
273
+ workerSelector?: Record<string, string>
274
+ createTime?: string
275
+ /** Substrate's last change; the current state has held at least since then. */
276
+ updateTime?: string
277
+ /**
278
+ * Possible kagent session: the actor name follows session-<uuid> on a cluster
279
+ * serving kagent's API. Radar infers this from naming alone.
280
+ */
281
+ kagent?: {
282
+ sessionId: string
283
+ /** A standalone kagent sandbox (template sandbox-<40 hex>): no chat and no RevertSession; kagent's SandboxService deletes it. */
284
+ sandbox?: boolean
285
+ }
286
+ }
287
+
288
+ export type SubstrateResumesWith = 'memory' | 'filesystem' | 'volumes' | 'cold' | 'unknown'
289
+
290
+ export interface SubstrateWorkerPodRef {
291
+ worker: string
292
+ namespace: string
293
+ pool: string
294
+ pod: string
295
+ }
296
+
297
+ export interface SubstrateActorRow {
298
+ atespace: string
299
+ name: string
300
+ state: SubstrateActorState
301
+ /** Crash message, transition age, or pending upload with time since last update. */
302
+ reason?: string
303
+ /** A crash's cause, where Substrate's message names it; absent otherwise. */
304
+ cause?: 'memoryLimit'
305
+ template: SubstrateRef
306
+ /** Absent when the actor has no worker. */
307
+ worker?: SubstrateWorkerPodRef
308
+ /** The node it is on or was last on. */
309
+ node?: string
310
+ /** The highest generation, finished or not. */
311
+ newestSnapshot?: SubstrateSnapshot
312
+ /**
313
+ * The generation a resume restores from, as Substrate picks it: the newest
314
+ * with local files or a completed durable copy. Absent when it boots cold.
315
+ */
316
+ resumeGeneration?: number
317
+ /**
318
+ * What that resume restores. volumes when the snapshot was captured under a
319
+ * template the actor no longer runs; unknown when that cannot be checked.
320
+ * memory holds only on a worker whose runtime matches the snapshot's;
321
+ * elsewhere Substrate restores the filesystem.
322
+ */
323
+ resumesWith: SubstrateResumesWith
324
+ /**
325
+ * When resumesWith holds only on a condition. compatibleRuntime: memory if
326
+ * the worker it lands on runs a compatible runtime, else the filesystem.
327
+ * runtimeMismatch: a known downgrade, the runtime that would host it cannot
328
+ * restore the memory. Absent when unconditional.
329
+ */
330
+ resumeCondition?: 'compatibleRuntime' | 'runtimeMismatch'
331
+ /** Where a resuming, suspending, reverting or deleting actor waits; absent in other states. */
332
+ waitingOn?: SubstrateWaiting
333
+ /** What its worker's state means for it; absent when the worker means nothing for it or was not read. */
334
+ workerImpact?: SubstrateWorkerImpact
335
+ /** A kagent session's Agent for this caller; absent for other actors, and from a Radar without kagentAttribution. */
336
+ kagent?: KagentActor
337
+ createTime?: string
338
+ updateTime?: string
339
+ }
340
+
341
+ export interface SubstrateStateCounts {
342
+ total: number
343
+ /** Every state is present, at zero when it has no actors. */
344
+ byState: Record<SubstrateActorState, number>
345
+ }
346
+
347
+ export interface SubstrateResources {
348
+ cpuMillicores: number
349
+ memoryBytes: number
350
+ /** Substrate counts an unreported dimension as zero: capacity 0 actors is 0 slots. */
351
+ actors: number
352
+ }
353
+
354
+ export interface SubstrateWorkerCounts {
355
+ total: number
356
+ active: number
357
+ draining: number
358
+ unavailable: number
359
+ }
360
+
361
+ export interface SubstrateUsage {
362
+ used: number
363
+ total: number
364
+ }
365
+
366
+ /** Totals over active workers, the only ones Substrate places on. */
367
+ export interface SubstratePlacement {
368
+ workers: SubstrateWorkerCounts
369
+ slots: SubstrateUsage
370
+ cpuMillicores: SubstrateUsage
371
+ memoryBytes: SubstrateUsage
372
+ /**
373
+ * Every Substrate worker was read. When false (a capped or partly denied read) the totals are
374
+ * lower bounds: they show what was observed, never that a pool lacks workers or free slots.
375
+ */
376
+ complete: boolean
377
+ }
378
+
379
+ /** A pool's worker Pods, those labelled with its name. */
380
+ export interface SubstratePoolPods {
381
+ /** Not being deleted. */
382
+ created: number
383
+ /** Of those, Ready. */
384
+ ready: number
385
+ /** Being deleted; a Deployment's ready count leaves them out even while Ready. */
386
+ terminating: number
387
+ /** Earliest Ready transition, or creation when unavailable, among current unready worker Pods. */
388
+ oldestNotReadySince?: string
389
+ }
390
+
391
+ export interface SubstrateK8sPool {
392
+ namespace: string
393
+ name: string
394
+ /** spec.replicas; absent when unset. */
395
+ desired?: number
396
+ /** status.readyReplicas when reported by the controller. Prefer pods.ready when present. */
397
+ reportedReady?: number
398
+ /** The pool's worker Pods in Radar's cache; absent when the caller can't list Pods there or the cache doesn't hold them. */
399
+ pods?: SubstratePoolPods
400
+ sandboxClasses?: string[]
401
+ /** Radar's WorkerPool verdict (pkg/health). */
402
+ health: string
403
+ healthReason: string
404
+ healthDetail?: string
405
+ createTime?: string
406
+ }
407
+
408
+ export type SubstratePoolCapacity = 'short' | 'full' | 'noRoom' | 'free'
409
+
410
+ /** What a pool's free slots lack for an actor. */
411
+ export type SubstrateLacking = 'cpu' | 'memory' | 'cpuAndMemory'
412
+
413
+ export interface SubstratePoolRow {
414
+ namespace: string
415
+ name: string
416
+ /** Absent when only Substrate's workers name the pool. */
417
+ kubernetes?: SubstrateK8sPool
418
+ /** Absent when Substrate's workers were not read. */
419
+ placement?: SubstratePlacement
420
+ /** Actors assigned to its workers; absent when actors were not read. */
421
+ actors?: number
422
+ sandboxClasses?: string[]
423
+ /**
424
+ * Absent when neither side was read well enough to say. noRoom: free slots,
425
+ * but no active worker has the CPU or memory for an actor of any template
426
+ * that can run on the pool (judged only on complete worker and template
427
+ * lists). free: a slot is free; whether an actor fits is judged only then.
428
+ */
429
+ capacity?: SubstratePoolCapacity
430
+ /** With capacity noRoom: what the free slots lack. */
431
+ lacking?: SubstrateLacking
432
+ /** Substrate's own measurements from Prometheus; absent when not read for this pool. */
433
+ service?: SubstratePoolService
434
+ }
435
+
436
+ export type SubstrateServiceVerdict =
437
+ | 'workerShortfall'
438
+ | 'noFreeActorSlots'
439
+ | 'freeActorSlots'
440
+ | 'noSchedulableWorkers'
441
+ | 'unknown'
442
+
443
+ /** One pool's Prometheus verdict and facts. An absent fact is unknown; reason says why when the verdict is unknown. */
444
+ export interface SubstratePoolService {
445
+ verdict: SubstrateServiceVerdict
446
+ reason?: string
447
+ /** Over resumes placed on the pool; a resume that fails before placement names no pool. */
448
+ resumeP95Seconds?: number
449
+ failedResumesPercent?: number
450
+ crashes?: number
451
+ /** When the pool is short: schedulable out of desired. */
452
+ schedulableWorkers?: number
453
+ desiredWorkers?: number
454
+ }
455
+
456
+ /** The workspace's one-line reading of the Prometheus measurements. */
457
+ export interface SubstrateServiceSummary {
458
+ read: boolean
459
+ /** Why they were not read: Prometheus not connected, or the first collection still running. */
460
+ why?: string
461
+ /** Not read only because Radar's first collection from a connected Prometheus hasn't answered yet; a later read has it. */
462
+ collecting?: boolean
463
+ /** When the measurements were collected. */
464
+ readAt?: string
465
+ /** The range the resume and crash facts cover, such as 1h. */
466
+ window?: string
467
+ /** Summed over pools that reported crashes; absent when none did. */
468
+ crashes?: number
469
+ /** value in seconds (resume p95). */
470
+ slowestResume?: { pool: SubstratePoolRef; value: number }
471
+ /** Highest positive failed-resume percentage. Absent when no pool reported a positive share. */
472
+ mostFailedResumes?: { pool: SubstratePoolRef; value: number }
473
+ /** These counters carry no observations when read is false. */
474
+ poolsUnknown: number
475
+ nodesOverdue: number
476
+ nodesUnknown: number
477
+ }
478
+
479
+ /** One needs-attention rule and whether it ran on this read. */
480
+ export interface SubstrateCheck {
481
+ /** An attention rule, or poolService (the pool verdicts from Prometheus). */
482
+ rule: SubstrateAttentionRule | 'poolService'
483
+ label: string
484
+ ran: boolean
485
+ /** What was missing when it did not run. */
486
+ why?: string
487
+ /** It did not run only because its input is still being collected (service.collecting); it runs on a later read. */
488
+ collecting?: boolean
489
+ }
490
+
491
+ export interface SubstrateGolden {
492
+ state: 'ready' | 'failed' | 'building' | 'disabled'
493
+ tag?: SubstrateRef
494
+ /** When warm-up ended (ready) or the template last changed (failed). */
495
+ time?: string
496
+ error?: string
497
+ /** memoryLimit when error says the golden actor was killed over its memory limit. */
498
+ cause?: 'memoryLimit'
499
+ /**
500
+ * Why a building snapshot cannot progress. noMatchingPool (the same word as
501
+ * the rule): the complete pool list holds no pool the selector matches;
502
+ * Substrate runs the golden actor like any actor, so the build retries
503
+ * without end and never fails.
504
+ */
505
+ blocked?: 'noMatchingPool'
506
+ }
507
+
508
+ export interface SubstrateTemplateRow {
509
+ atespace: string
510
+ name: string
511
+ golden: SubstrateGolden
512
+ /** Absent when actors were not read. */
513
+ actors?: SubstrateStateCounts
514
+ attentionCount?: number
515
+ /**
516
+ * Pools the selector matches. null when Radar cannot say (no pool list, or
517
+ * none of a partial list matches); [] only when the list is complete and
518
+ * nothing matches.
519
+ */
520
+ matchingPools: SubstratePoolRef[] | null
521
+ /** The pool list matched against is complete. */
522
+ matchingPoolsComplete: boolean
523
+ sandboxClasses?: string[]
524
+ workerSelector?: Record<string, string>
525
+ cpuMillicores?: number
526
+ memoryBytes?: number
527
+ preferredFidelity: 'memory' | 'rootfs' | 'volumes'
528
+ /** Absent: the API server's default location. */
529
+ storageLocation?: string
530
+ /** Container names. The detail spec carries full container definitions. */
531
+ containers?: string[]
532
+ updateTime?: string
533
+ /** Set when the template is a kagent Agent revision's (kind agentSession, naming the Agent) or a kagent sandbox's. */
534
+ kagent?: KagentAttribution
535
+ }
536
+
537
+ /** Agent is the UI's own link to a kagent Agent; the server's subjects never name one. */
538
+ export type SubstrateSubjectKind = 'Actor' | 'ActorTemplate' | 'Worker' | 'WorkerPool' | 'Node' | 'Pod' | 'Actors' | 'Agent'
539
+
540
+ export interface SubstrateSubject {
541
+ kind: SubstrateSubjectKind
542
+ atespace?: string
543
+ namespace?: string
544
+ name?: string
545
+ /** For kind Actors: the /actors query parameters. */
546
+ filter?: Record<string, string>
547
+ }
548
+
549
+ export interface SubstrateTally {
550
+ subject?: SubstrateSubject
551
+ text?: string
552
+ count: number
553
+ /** What every crash in a template group shares, when Substrate's messages name it: memoryLimit, a kill for exceeding the actor's memory limit. */
554
+ cause?: 'memoryLimit'
555
+ /**
556
+ * The group's remedy when cause names one; its commands may hold `<name>`, `<atespace>` and
557
+ * `<new-template>` placeholders. thenCommand runs after command when the remedy takes two.
558
+ */
559
+ nextStep?: string
560
+ command?: string
561
+ thenCommand?: string
562
+ /** Some actor in the group is kagent's (a session or a sandbox), which kagent recovers: nextStep names kagent and no command is offered. */
563
+ kagent?: boolean
564
+ }
565
+
566
+ export type SubstrateAttentionRule =
567
+ | 'crashedActors'
568
+ | 'stuckTransition'
569
+ | 'goldenSnapshotFailed'
570
+ | 'noMatchingPool'
571
+ /** Actors naming a template Substrate does not have. */
572
+ | 'missingTemplate'
573
+ | 'workerUnavailable'
574
+ | 'workerDraining'
575
+ | 'workerRestarting'
576
+ | 'poolShort'
577
+ | 'poolFull'
578
+ /** Pools whose free slots lack the CPU or memory an actor of any template that can run on them books. */
579
+ | 'poolNoRoom'
580
+ | 'uploadOverdue'
581
+ /** Nodes whose atelet counts snapshot uploads past their deadline (Prometheus). */
582
+ | 'nodeUploadsOverdue'
583
+
584
+ export interface SubstrateAttention {
585
+ /** Stable across reads for the same rule and subject. */
586
+ id: string
587
+ rule: SubstrateAttentionRule
588
+ /**
589
+ * critical: something is already lost or down. alert: at risk, nothing lost
590
+ * yet. info: expected and still within its budget (a drain before its Pod's
591
+ * deadline).
592
+ */
593
+ severity: 'critical' | 'alert' | 'warning' | 'info'
594
+ title: string
595
+ reading: string
596
+ /** One action in a short sentence. */
597
+ nextStep: string
598
+ /**
599
+ * The command that runs the next step, when one does. A row covering several actors writes
600
+ * `<name>` and `<atespace>` for them; an actor page's rows have them filled in.
601
+ */
602
+ command?: string
603
+ /** Runs after command when the step takes two: a memory-limit crash's revert, then its template update. */
604
+ thenCommand?: string
605
+ subject: SubstrateSubject
606
+ related?: SubstrateSubject[]
607
+ count: number
608
+ /** Newest change among them; a lower bound on how long the condition has held. */
609
+ since?: string
610
+ /** Crashes by template, largest first. */
611
+ groups?: SubstrateTally[]
612
+ /** Most common Substrate messages, largest first. */
613
+ messages?: SubstrateTally[]
614
+ /** uploadOverdue only: the nodes holding the unstored snapshots, most actors first. */
615
+ nodes?: SubstrateUploadNode[]
616
+ /** Up to 20 of the actors covered, for display; not which actors the row covers. */
617
+ sample?: SubstrateRef[]
618
+ }
619
+
620
+ export interface SubstrateUploadNode {
621
+ /** Empty when Substrate names no node. */
622
+ node: string
623
+ /** gone: Radar's Node list does not hold it. unknown: Nodes not read, or no node named. */
624
+ state: 'ready' | 'notReady' | 'gone' | 'unknown'
625
+ count: number
626
+ /** The earliest last update among them; the wait is at least since then. */
627
+ oldest?: string
628
+ }
629
+
630
+ export interface SubstrateStatus {
631
+ /** The cluster serves Substrate's WorkerPool kind. */
632
+ installed: boolean
633
+ apiService: {
634
+ namespace: string
635
+ name: string
636
+ port: number
637
+ /** Whether Radar cached the Service. Absent when the Service cache is unavailable or the caller lacks get services. */
638
+ found?: boolean
639
+ }
640
+ apiTier: SubstrateAPITier
641
+ /** The caller's WorkerPool read, under the same name as on every Substrate response. */
642
+ coverage: { pools: SubstratePoolsCoverage }
643
+ /** Whether this private local Radar allows editing its saved connection. */
644
+ canConfigure: boolean
645
+ }
646
+
647
+ export interface SubstrateSettings {
648
+ identity: 'shared' | 'tokenFile'
649
+ tokenFile?: string
650
+ /**
651
+ * Atespaces to read when the identity may not list atespaces (a token with
652
+ * viewer on some atespaces only). Others stay unknown. Ignored when
653
+ * Substrate lists atespaces.
654
+ */
655
+ atespaces?: string[]
656
+ /** host:port; dials directly instead of port-forwarding to ate-system/api. */
657
+ endpoint?: string
658
+ caFile?: string
659
+ serverName?: string
660
+ }
661
+
662
+ /**
663
+ * The context and cluster a connection view was read for (k8s.ProfileTarget).
664
+ * Send it back unchanged with a save or disconnect.
665
+ */
666
+ export interface SubstrateConnectionTarget {
667
+ binding: string
668
+ context: string
669
+ fingerprint: string
670
+ clientGeneration: number
671
+ operationGeneration: number
672
+ /** The kubeconfig file the context comes from, and its name there: what a copied kubectl command needs to reach the same cluster. */
673
+ source?: string
674
+ inFileName?: string
675
+ [field: string]: unknown
676
+ }
677
+
678
+ /** How this Radar reads Substrate's API, when its operator sets it (in-cluster and Radar Hub). */
679
+ export interface SubstrateManagedConnection {
680
+ /** false: the operator turned the API off, or this shared Radar has no sign-in. */
681
+ enabled: boolean
682
+ /** eachUser: ate-client, its token minted with each signed-in person's own Kubernetes access. */
683
+ readsAs: 'eachUser' | 'none'
684
+ /** Both are blank when the operator disables the API or installation settings fail validation. */
685
+ endpoint: string
686
+ serverName: string
687
+ /** Where the server certificate is verified from; never a path. */
688
+ trust: 'clusterTrustBundle' | 'caFile'
689
+ /** Fallback atespaces; only present when this caller is connected. */
690
+ atespaces?: string[]
691
+ /** The Helm values that set each part. */
692
+ helm: { api: string; endpoint: string; serverName: string; ca: string; atespaces: string }
693
+ }
694
+
695
+ interface SubstrateConnectionBase {
696
+ /** Who the shared identity authenticates as. */
697
+ sharedPrincipal: string
698
+ /** This caller's own outcome, as status's apiTier. */
699
+ access: SubstrateAPITier
700
+ }
701
+
702
+ /** A local private Radar: this context's saved connection, editable. */
703
+ export interface SubstrateLocalConnection extends SubstrateConnectionBase {
704
+ view: 'local'
705
+ /** The context (target.context) and cluster this view was read for. Send back with PUT; a save for a context that has since moved is refused with 409 targetChanged. */
706
+ target: SubstrateConnectionTarget
707
+ /** The saved file's revision; send back with PUT. A save over a newer revision is refused with 409 conflict. */
708
+ revision: string
709
+ saved: boolean
710
+ /** Saved for another cluster than this context points at now, so not used. */
711
+ targetChanged?: boolean
712
+ settings: SubstrateSettings | null
713
+ }
714
+
715
+ /** In-cluster and Radar Hub: the installation's settings, read-only. */
716
+ export interface SubstrateManagedConnectionView extends SubstrateConnectionBase {
717
+ view: 'managed'
718
+ managed: SubstrateManagedConnection
719
+ }
720
+
721
+ export type SubstrateConnection = SubstrateLocalConnection | SubstrateManagedConnectionView
722
+
723
+ /**
724
+ * PUT /connection's body: the target the connection view returned, and
725
+ * settings shaped exactly as GET returns them. settings {identity: 'none'},
726
+ * with no other field, removes this context's settings. The save applies only
727
+ * if the context is still the target.
728
+ * A save first dials the settings and reads once; if that fails it answers
729
+ * 502 with the tier code (unreachable, unauthenticated, tls, notInstalled…)
730
+ * and saves nothing. An identity Substrate authenticates but denies the
731
+ * atespace list is accepted: it is scoped.
732
+ */
733
+ export interface SubstrateConnectionUpdate {
734
+ target: SubstrateConnectionTarget
735
+ revision: string
736
+ settings: SubstrateSettings | { identity: 'none' }
737
+ /** reconfirm: keep the saved settings for the cluster this context now points at. */
738
+ action?: 'save' | 'reconfirm'
739
+ /** The user agreed to send the saved credential to a changed endpoint, CA or server name. */
740
+ confirmDestination?: boolean
741
+ }
742
+
743
+ export interface SubstrateWorkspace {
744
+ apiTier: SubstrateAPITier
745
+ /** pools is always present; the API-tier kinds are absent unless the API tier is connected. */
746
+ coverage: Partial<SubstrateSnapshotCoverage> & { pools: SubstratePoolsCoverage }
747
+ /** Each part is absent when what it counts was not read. */
748
+ summary: {
749
+ /** Absent unless WorkerPools or workers were read; a partial pool list counts what was read. */
750
+ pools?: { total: number; short: number; full: number; noRoom: number }
751
+ workers?: SubstrateWorkerCounts
752
+ slots?: SubstrateUsage
753
+ /** Free actor slots per pool, largest first; [] when workers were read and none is free. lacking: the pool's free slots fit no actor of its templates. */
754
+ freeSlots?: { pool: SubstratePoolRef; free: number; lacking?: SubstrateLacking }[]
755
+ actors?: { total: number; crashed: number; attentionCount: number }
756
+ /** noMatchingPool counts templates whose selector matches no pool; absent unless the pool list is complete. */
757
+ templates?: { total: number; goldenFailed: number; attentionCount: number; noMatchingPool?: number }
758
+ }
759
+ actorStates?: SubstrateStateCounts
760
+ needsAttention: SubstrateAttention[]
761
+ /** Every rule and whether it ran, so an empty needsAttention says what was checked. */
762
+ checks: SubstrateCheck[]
763
+ /** Health surfaces no check reads: an empty needsAttention never means they are healthy. */
764
+ notAssessed: string[]
765
+ service: SubstrateServiceSummary
766
+ pools: SubstratePoolRow[]
767
+ /** Absent unless atespaces were listed or read through the settings' scope; [] when none. */
768
+ atespaces?: {
769
+ name: string
770
+ /**
771
+ * How much of each kind was read for this atespace. partial: the read's
772
+ * budget ran out, so the count is a lower bound. unread: not reached, or
773
+ * not named by the settings' scope. The count is present only for full
774
+ * and partial: never 0 for an atespace that was not read.
775
+ */
776
+ actorsRead: SubstrateAtespaceRead
777
+ actors?: SubstrateStateCounts
778
+ templatesRead: SubstrateAtespaceRead
779
+ templates?: number
780
+ }[]
781
+ }
782
+
783
+ export type SubstrateAtespaceRead = 'full' | 'partial' | 'denied' | 'unread'
784
+
785
+ export interface SubstrateActorsQuery {
786
+ /** 1 selects reported crashes, worker disruptions and stuck transitions. */
787
+ attention?: 1
788
+ atespace?: string
789
+ /** name, or atespace/name */
790
+ template?: string
791
+ /** name, or namespace/name */
792
+ pool?: string
793
+ /** worker Pod name or Substrate worker name */
794
+ worker?: string
795
+ /**
796
+ * updated (default): newest change first. attention: crashed, then assigned
797
+ * to unavailable or restarted workers, then stuck transitions, then the rest.
798
+ * Stuck transitions are longest-waiting first. The other groups are newest
799
+ * first. name: by atespace and name. Paging applies after the sort.
800
+ */
801
+ sort?: 'updated' | 'attention' | 'name'
802
+ /** With nodeHas: running = the actor's worker is on node; localSnapshot = its newest snapshot is not durably stored and its files are on node. */
803
+ node?: string
804
+ nodeHas?: 'running' | 'localSnapshot'
805
+ /** Only actors whose worker's state means this for them (SubstrateWorkerImpact.kind); with worker, a worker row's "Show the N actors". */
806
+ impact?: SubstrateWorkerImpact['kind']
807
+ /** One state, or several (sent comma-separated); rows match any of them. */
808
+ state?: SubstrateActorState | SubstrateActorState[]
809
+ q?: string
810
+ /** namespace/name: the sessions attributed to that kagent Agent. Send only to a Radar with kagentAttribution: an older one ignores it. */
811
+ agent?: string
812
+ /** The kagent sessions of one kind. Send only to a Radar with kagentAttribution. */
813
+ kagent?: KagentAttribution['kind'] | 'sessions'
814
+ namespaces?: string
815
+ limit?: number
816
+ offset?: number
817
+ }
818
+
819
+ export interface SubstrateActors {
820
+ apiTier: SubstrateAPITier
821
+ /** Coverage of the source that answered. */
822
+ coverage: SubstrateCoverage
823
+ /** Worker coverage qualifies attention counts and worker impact. */
824
+ workerCoverage: SubstrateCoverage
825
+ /**
826
+ * What answered: snapshot (the shared read); atespace (a direct read of the
827
+ * atespace filter, when the snapshot does not hold all of it); actor (a
828
+ * direct read of the exact name searched, when that atespace read is itself
829
+ * capped).
830
+ */
831
+ sources: ('snapshot' | 'atespace' | 'actor')[]
832
+ /** After all filters, before paging. Absent when actors could not be read. */
833
+ total?: number
834
+ /** Per state, before applying state, attention or paging. */
835
+ counts?: SubstrateStateCounts
836
+ /** Actors matching the attention filter, counted before state, attention or paging. */
837
+ attentionCount?: number
838
+ rows: SubstrateActorRow[]
839
+ limit: number
840
+ offset: number
841
+ /** The caller's read of kagent's Agents the rows' kagent and the agent/kagent filters were judged against; absent without kagent. */
842
+ kagentAgents?: SubstratePoolsCoverage
843
+ /**
844
+ * With an agent or kagent filter other than sandbox: the atespaces holding kagent sessions whose Agents
845
+ * weren't read (kagentAgents says why). There an Agent's counts are lower bounds and an unattributed
846
+ * session may belong to an Agent.
847
+ */
848
+ kagentUnread?: string[]
849
+ /** Unread templates could tie more earlier-revision sessions to the filtered Agent(s). */
850
+ kagentTemplatesPartial?: boolean
851
+ }
852
+
853
+ export interface SubstrateEgress {
854
+ /** set: a policy exists. none: no policy, so Substrate's egress gateway denies all outbound traffic. */
855
+ state: 'set' | 'none' | 'denied' | 'failed'
856
+ rules: number
857
+ /** Hostnames the rules name, deduplicated, at most 20. */
858
+ destinations?: string[]
859
+ more?: number
860
+ message?: string
861
+ }
862
+
863
+ export interface SubstrateWorkerRow {
864
+ name: string
865
+ namespace: string
866
+ pool: string
867
+ pod: string
868
+ node: string
869
+ state: 'active' | 'draining' | 'unavailable' | 'unknown'
870
+ capacity?: SubstrateResources
871
+ allocated?: SubstrateResources
872
+ /** Above observedEpoch: the worker restarted and Substrate has not yet crashed its earlier actors. */
873
+ registeredEpoch: number
874
+ observedEpoch: number
875
+ sandboxClasses?: string[]
876
+ updateTime?: string
877
+ /** An actor slot is left. Slots only: CPU or memory can still be short. */
878
+ hasFreeSlot: boolean
879
+ /** How long the state has held, at least: since Substrate's last update to the worker. Absent when it reported no update time. */
880
+ heldForSeconds?: number
881
+ /** The worker Pod's Ready condition; absent when the Pod is not cached. */
882
+ podReady?: boolean
883
+ /** The cached Pod has a deletion deadline. Unknown when podReady is absent. */
884
+ podTerminating?: boolean
885
+ /** What its state means for its actors; absent for an active worker whose registration Substrate has observed. */
886
+ workerState?: SubstrateWorkerReading
887
+ /** Strongest worker finding, including an in-budget drain (info). */
888
+ attentionSeverity?: SubstrateAttention['severity']
889
+ /** Observed assignments, possibly partial. Absent when unread or omitted on actor detail. */
890
+ actors?: SubstrateAssignedActor[]
891
+ }
892
+
893
+ /**
894
+ * draining or unavailable: Substrate's state. reconciling: active, but its process restarted and Substrate
895
+ * hasn't reconciled it; with lost > 0 those actors' sandboxes are gone (show it amber, "Active · reconciling").
896
+ */
897
+ export interface SubstrateWorkerReading {
898
+ kind: 'draining' | 'unavailable' | 'reconciling'
899
+ /** Actors still assigned; absent unless the actor read is complete. */
900
+ assigned?: number
901
+ /** Assigned actors that ran under an earlier process and lost their sandboxes; absent unless the actor read is complete. */
902
+ lost?: number
903
+ reading: string
904
+ }
905
+
906
+ export interface SubstrateAssignedActor {
907
+ atespace: string
908
+ name: string
909
+ state: SubstrateActorState
910
+ template: SubstrateRef
911
+ /** The actor's last change: tells a stuck transition from one within its budget. */
912
+ updateTime?: string
913
+ /** What this worker's state means for the actor; absent when it means nothing. */
914
+ workerImpact?: SubstrateWorkerImpact
915
+ /** A kagent session's Agent for this caller; absent for other actors. */
916
+ kagent?: KagentActor
917
+ }
918
+
919
+ export interface SubstrateActorDetail {
920
+ apiTier: SubstrateAPITier
921
+ /** Read fresh from Substrate. */
922
+ actor: SubstrateActor
923
+ row: SubstrateActorRow
924
+ template?: SubstrateTemplateRow
925
+ /** The assigned worker; absent when the actor has none or workers were not read. */
926
+ worker?: SubstrateWorkerRow
927
+ egress: SubstrateEgress
928
+ related: SubstrateSubject[]
929
+ /** Needs-attention rows that cover this actor, judged on the fresh read. */
930
+ attention: SubstrateAttention[]
931
+ /** What a revert would leave; absent when Substrate would refuse to revert this actor. */
932
+ recovery?: SubstrateRecovery
933
+ /**
934
+ * Pools matching both the template's selector and the actor's own. null
935
+ * when the template or pool list was not read, or a partial list matches
936
+ * none; [] only when the list is complete and nothing matches.
937
+ */
938
+ matchingPools: SubstratePoolRef[] | null
939
+ matchingPoolsComplete: boolean
940
+ /** Coverage of the reads the template, worker, pool and attention readings come from. */
941
+ coverage: { actors: SubstrateCoverage; templates: SubstrateCoverage; workers: SubstrateCoverage; pools: SubstratePoolsCoverage; kagentAgents?: SubstratePoolsCoverage }
942
+ }
943
+
944
+ export interface SubstrateRecovery {
945
+ /** The recovery source; absent when nothing is stored, so the actor boots cold after a revert. */
946
+ generation?: number
947
+ fidelity?: 'memory' | 'rootfs' | 'volumes'
948
+ resumesWith: SubstrateResumesWith
949
+ resumeCondition?: 'compatibleRuntime' | 'runtimeMismatch'
950
+ /** Newer generations a revert drops, newest first. */
951
+ discarded: { generation: number; fidelity?: 'memory' | 'rootfs' | 'volumes'; why: 'localOnly' | 'uploadPending' | 'uploadAbandoned' | 'incomplete' }[]
952
+ }
953
+
954
+ /**
955
+ * containers and lifecycle are kubectl ate logs actor's --source. worker is
956
+ * the worker process's own records about this actor ("Killing a sandbox over
957
+ * its memory limit", "Sandbox died"), matched by UID or by atespace and name
958
+ * for records without a UID. all selects all sources, restricted by any container filter.
959
+ */
960
+ export type SubstrateLogSource = 'all' | 'containers' | 'lifecycle' | 'worker'
961
+
962
+ export interface SubstrateLogLine {
963
+ /** Which source the line belongs to. */
964
+ kind: 'container' | 'lifecycle' | 'worker'
965
+ time?: string
966
+ /** Absent for a lifecycle event or a worker record. */
967
+ container?: string
968
+ severity?: string
969
+ message?: string
970
+ /** The record as kubectl ate prints it (a worker record without its identity keys). */
971
+ text: string
972
+ /** On a worker's memory-limit kill: the limit, and the usage that crossed it. */
973
+ memoryLimitBytes?: number
974
+ memoryUsageBytes?: number
975
+ }
976
+
977
+ /**
978
+ * Where a transitional actor waits, as Substrate's workflows run it. A
979
+ * resuming actor is always placed (Substrate sets RESUMING and the worker in
980
+ * one write; one no worker can take stays suspended). An unfinished resume or
981
+ * suspend continues only on the next resume or suspend call.
982
+ * restore: placed, restoring on worker. checkpoint: checkpointing on worker
983
+ * (a synchronous suspend also waits for the upload). revert, delete: in the
984
+ * API server. unrecorded: no worker recorded, which Substrate never leaves.
985
+ */
986
+ export interface SubstrateWaiting {
987
+ on: 'restore' | 'checkpoint' | 'revert' | 'delete' | 'unrecorded'
988
+ /** The worker for a recorded restore or checkpoint. */
989
+ worker?: SubstrateWorkerPodRef
990
+ node?: string
991
+ reading: string
992
+ }
993
+
994
+ /**
995
+ * unavailable: Substrate marks the worker unavailable, which its controller does while the
996
+ * worker Pod is not Ready or has no IP; nothing new is placed there and the actor may not be
997
+ * served, though Substrate still records it running. podState says which side holds it back.
998
+ * draining: the Pod is terminating; when it is gone Substrate crashes the actor. restarted: the
999
+ * worker process restarted under the actor, so its sandbox is gone; Substrate crashes it when it
1000
+ * reconciles.
1001
+ */
1002
+ export interface SubstrateWorkerImpact {
1003
+ kind: 'unavailable' | 'draining' | 'restarted'
1004
+ reading: string
1005
+ /**
1006
+ * An unavailable worker's Pod in Radar's cache. notReady, noIP: Kubernetes is the cause.
1007
+ * ready: Ready with an IP, so Kubernetes is not the cause; Substrate's controller has not marked
1008
+ * the worker available again. unread: the cache does not hold the Pod. Absent for other kinds.
1009
+ */
1010
+ podState?: 'notReady' | 'noIP' | 'ready' | 'unread'
1011
+ /** When a draining worker's Pod is due to be gone; absent when unknown. */
1012
+ deadline?: string
1013
+ /**
1014
+ * One action for this actor, and the command that runs it with the actor's and worker Pod's names filled in.
1015
+ * Unavailable uses the worker’s Pod state. Draining and restarted use the actor’s phase.
1016
+ */
1017
+ nextStep: string
1018
+ command?: string
1019
+ }
1020
+
1021
+ /** A worker Pod whose log was searched. */
1022
+ export interface SubstrateSearchedPod {
1023
+ namespace: string
1024
+ pod: string
1025
+ /** gone: the Pod no longer exists. denied: the caller may not get pods/log there. */
1026
+ outcome: 'read' | 'denied' | 'gone' | 'failed'
1027
+ message?: string
1028
+ scanned: number
1029
+ /** The read reached its 20,000-line window or 8 MiB per fetch: older lines may exist. */
1030
+ windowFull: boolean
1031
+ /** The byte limit cut off the newest lines even after requesting a shorter tail. */
1032
+ truncated?: boolean
1033
+ /** All matches in the scan, before limiting the returned lines to the requested tail. */
1034
+ matched: number
1035
+ }
1036
+
1037
+ export interface SubstrateActorLogs {
1038
+ actor: SubstrateRef
1039
+ state: SubstrateActorState
1040
+ /**
1041
+ * worker: read from the worker Pod Substrate assigns it now. lastNode: it has
1042
+ * no worker, so the worker Pods on the node it was last on (assignedNode, or
1043
+ * its newest snapshot's locality) were searched for its lines; Substrate does
1044
+ * not record which Pod it ran in, so these are candidates, each line naming
1045
+ * its Pod. none: nothing to read.
1046
+ */
1047
+ origin: 'worker' | 'lastNode' | 'none'
1048
+ /** The assigned worker, for origin worker. */
1049
+ worker?: SubstrateWorkerPodRef
1050
+ /** The worker's node, or the node searched. */
1051
+ node?: string
1052
+ /**
1053
+ * noWorker: no worker and no node recorded. nodeGone. noWorkerPods: no worker
1054
+ * Pod on that node now (the one it ran in is gone). workerPodGone: its
1055
+ * assigned worker's Pod no longer exists. podsDenied: cannot list worker
1056
+ * Pods. logsDenied: cannot get their logs.
1057
+ * noMatch: At least one Pod log was read, and none read holds its lines. candidates: lines found on
1058
+ * the last node. podsNotCollected: Radar doesn't hold Pods in every
1059
+ * namespace, so the node can't be searched.
1060
+ */
1061
+ reasonCode?: 'noWorker' | 'nodeGone' | 'noWorkerPods' | 'workerPodGone' | 'podsDenied' | 'logsDenied' | 'noMatch' | 'candidates' | 'podsNotCollected'
1062
+ reason?: string
1063
+ source: SubstrateLogSource
1064
+ /** Newest matches in the parts read, oldest first, each with its Pod and namespace. */
1065
+ lines: (SubstrateLogLine & { pod: string; namespace: string })[]
1066
+ /** Candidate Pod log outcomes, including unread logs. A last-node search attempts up to 6 streams. */
1067
+ searched: SubstrateSearchedPod[]
1068
+ /** Worker Pods on the node left unsearched. */
1069
+ morePods?: number
1070
+ /** A last-node search where some Pod logs could not be searched. */
1071
+ partial?: boolean
1072
+ scanned: number
1073
+ /** Some read reached its window: older lines of this actor may exist beyond it. */
1074
+ windowFull: boolean
1075
+ /**
1076
+ * The newest worker record among the lines of the worker killing this
1077
+ * actor's sandbox over its memory limit; absent when no line read says so.
1078
+ * It is causal only when Substrate also recorded a memory-limit crash.
1079
+ */
1080
+ memoryKill?: {
1081
+ time?: string
1082
+ pod: string
1083
+ namespace: string
1084
+ limitBytes: number
1085
+ usageBytes?: number
1086
+ /**
1087
+ * The kill is tied to the actor's present crash: at most 10 minutes before it, with no start
1088
+ * or restore between them, and no subsequent failed-kill record. When false, the log
1089
+ * is evidence of a kill attempt with no confirmed tie to the current crash.
1090
+ */
1091
+ current: boolean
1092
+ /** The remedy, the crash step: command reverts the actor, thenCommand updates its template. Absent unless current. */
1093
+ nextStep?: string
1094
+ command?: string
1095
+ thenCommand?: string
1096
+ }
1097
+ }
1098
+
1099
+ export interface SubstrateWorkers {
1100
+ apiTier: SubstrateAPITier
1101
+ coverage: { workers: SubstrateCoverage; actors: SubstrateCoverage }
1102
+ counts?: SubstrateWorkerCounts
1103
+ workers: SubstrateWorkerRow[]
1104
+ }
1105
+
1106
+ export interface SubstrateTemplates {
1107
+ apiTier: SubstrateAPITier
1108
+ coverage: { templates: SubstrateCoverage; actors: SubstrateCoverage; workers: SubstrateCoverage; pools: SubstratePoolsCoverage }
1109
+ templates: SubstrateTemplateRow[]
1110
+ }
1111
+
1112
+ /**
1113
+ * A template's definition, read fresh, for display only. Secret-shaped values
1114
+ * are redacted using Radar's AI context rules. A nonempty value under a
1115
+ * sensitive env name is replaced entirely. Other values, commands and
1116
+ * arguments are redacted by pattern. redacted is true when an env value was replaced.
1117
+ */
1118
+ export interface SubstrateTemplateSpec {
1119
+ containers: {
1120
+ name: string
1121
+ image: string
1122
+ command?: string[]
1123
+ args?: string[]
1124
+ env?: { name: string; value: string; redacted?: boolean }[]
1125
+ volumeMounts?: { name: string; mountPath: string }[]
1126
+ /** HTTP path Substrate probes after a resume. */
1127
+ wakeupProbe?: string
1128
+ }[]
1129
+ volumes: { name: string; kind: 'durableDir' | 'external' | 'systemInfo' | 'image' | 'unknown'; image?: string }[]
1130
+ workerSelector?: Record<string, string>
1131
+ cpuMillicores?: number
1132
+ memoryBytes?: number
1133
+ snapshot: { preferredFidelity: 'memory' | 'rootfs' | 'volumes'; storageLocation?: string; golden: 'enabled' | 'disabled' }
1134
+ /** Rules of the egress policy the golden actor warms up under; absent when none. */
1135
+ goldenEgressRules?: number
1136
+ createTime?: string
1137
+ }
1138
+
1139
+ export interface SubstrateTemplate {
1140
+ apiTier: SubstrateAPITier
1141
+ template: SubstrateTemplateRow
1142
+ /** Absent when the fresh read failed; specUnavailable says why. */
1143
+ spec?: SubstrateTemplateSpec
1144
+ specUnavailable?: string
1145
+ /** Coverage of the reads its actor counts and eligible pools come from. */
1146
+ coverage: { templates: SubstrateCoverage; actors: SubstrateCoverage; workers: SubstrateCoverage; pools: SubstratePoolsCoverage }
1147
+ }
1148
+
1149
+ export interface SubstratePool {
1150
+ /** Why observed Pod counts are absent for this WorkerPool. */
1151
+ podRead?: 'denied' | 'uncollected'
1152
+ apiTier: SubstrateAPITier
1153
+ pool: SubstratePoolRow
1154
+ attention?: SubstrateAttention
1155
+ workers: SubstrateWorkerRow[]
1156
+ /** Templates whose selector matches this pool; absent when templates were not read, [] when none. */
1157
+ templates?: SubstrateRef[]
1158
+ coverage: { workers: SubstrateCoverage; actors: SubstrateCoverage; templates: SubstrateCoverage; pools: SubstratePoolsCoverage }
1159
+ }
1160
+
1161
+ /** One current revision of a kagent Agent and its template. */
1162
+ export interface KagentAgentRevision {
1163
+ revision: string
1164
+ template: SubstrateRef
1165
+ /** The latestSuccessfulRevision: new sessions start on it. */
1166
+ newSessions?: boolean
1167
+ /** The desiredRevision. While it differs from the latest successful one, new sessions still start on that one. */
1168
+ desired?: boolean
1169
+ /** Another Agent's revision produces the same template name, so its actors are counted for neither. */
1170
+ ambiguous?: boolean
1171
+ sessions: number
1172
+ }
1173
+
1174
+ /** GET /api/substrate/kagent/agents/{namespace}/{name}/sessions. */
1175
+ export interface KagentAgentSessions {
1176
+ apiTier: SubstrateAPITier
1177
+ agent: { namespace: string; name: string; uid?: string; desiredRevision?: string; latestSuccessfulRevision?: string; created?: string }
1178
+ revisions: KagentAgentRevision[]
1179
+ /** The attributed session actors by state, on current and earlier revisions. */
1180
+ sessions: SubstrateStateCounts
1181
+ /** How many of sessions run on an earlier revision's template; the rest are on revisions. */
1182
+ onEarlierRevisions: number
1183
+ /** Every actor in the Agent's atespace was read: sessions and earlierRevisions are exact; otherwise lower bounds. */
1184
+ complete: boolean
1185
+ /** Sessions crashed or stuck in a transition past 5 minutes; attention holds the first few, crashed first. */
1186
+ needAttention: number
1187
+ attention: SubstrateActorRow[]
1188
+ /** Sessions on templates named for this Agent, for no current revision, that Radar can't prove are its: a hint, not part of sessions. */
1189
+ hintedEarlierRevisions: number
1190
+ /** Some of those templates' names also fit another Agent. */
1191
+ hintShared?: boolean
1192
+ sources: ('snapshot' | 'atespace')[]
1193
+ /** templates: a partial template read can leave a session a hint, so counts with hints are then lower bounds. */
1194
+ coverage: { actors: SubstrateCoverage; templates: SubstrateCoverage }
1195
+ }
1196
+
1197
+ /** The error_code of a failed substrate request, when it carries one. */
1198
+ export function substrateErrorCode(error: unknown): SubstrateCode | undefined {
1199
+ if (error instanceof ApiError && typeof error.data?.error_code === 'string') {
1200
+ return error.data.error_code as SubstrateCode
1201
+ }
1202
+ return undefined
1203
+ }
1204
+
1205
+ const SNAPSHOT_STALE_MS = 5_000
1206
+ const POLL_MS = 15_000
1207
+
1208
+ // A denial, a missing actor or an unconfigured tier will not change on retry;
1209
+ // an unreachable API might, once.
1210
+ function retrySubstrate(failureCount: number, error: unknown) {
1211
+ const code = substrateErrorCode(error)
1212
+ return failureCount < 1 && (code === 'unreachable' || code === 'contextChanged' || (error instanceof ApiError && error.status === 409 && !code))
1213
+ }
1214
+
1215
+ const enc = encodeURIComponent
1216
+
1217
+ /** pollMs: refetch interval; false stops polling. Defaults to 15s. */
1218
+ export interface SubstratePollOptions {
1219
+ pollMs?: number | false
1220
+ }
1221
+
1222
+ /**
1223
+ * One Substrate read. The key is ['substrate', apiBase, context, ...key, ...gatedKey]. There is no
1224
+ * placeholder unless `keepWhile` says the previous key is the same logical list: a detail shown
1225
+ * under another object's name, cluster or API base would be another object's facts.
1226
+ */
1227
+ function useSubstrateQuery<T>(
1228
+ key: unknown[],
1229
+ path: string,
1230
+ enabled = true,
1231
+ poll: number | false = POLL_MS,
1232
+ keepWhile?: (previous: QueryKey, next: QueryKey) => boolean,
1233
+ ) {
1234
+ const { data: cluster } = useClusterInfo()
1235
+ const { guard, gatedKey, upgrade, blockedReason, support } = useRadarFeature('substrateWorkspace')
1236
+ const queryKey: QueryKey = ['substrate', getApiBase(), cluster?.context, ...key, ...gatedKey]
1237
+ const query = useQuery<T>({
1238
+ queryKey,
1239
+ // guard refuses a Radar known not to serve the route and still tries one whose support is unknown.
1240
+ queryFn: ({ signal }) => guard(() => fetchJSON<T>(path, signal)),
1241
+ enabled,
1242
+ staleTime: SNAPSHOT_STALE_MS,
1243
+ refetchInterval: poll,
1244
+ retry: retrySubstrate,
1245
+ placeholderData: keepWhile
1246
+ ? (previous, previousQuery) => (previousQuery && keepWhile(previousQuery.queryKey, queryKey) ? previous : undefined)
1247
+ : undefined,
1248
+ })
1249
+ return { ...query, upgrade, blockedReason, support }
1250
+ }
1251
+
1252
+ /**
1253
+ * Keep rows between pages of the same actor list only while the API base,
1254
+ * context, filters and feature gate still match.
1255
+ */
1256
+ export function sameSubstrateActorList(previous: QueryKey, next: QueryKey): boolean {
1257
+ return (
1258
+ previous[0] === 'substrate' &&
1259
+ previous[1] === next[1] &&
1260
+ previous[2] === next[2] &&
1261
+ previous[3] === 'actors' &&
1262
+ next[3] === 'actors' &&
1263
+ previous[4] === next[4] &&
1264
+ previous.length === next.length &&
1265
+ previous.slice(6).every((part, i) => part === next[i + 6])
1266
+ )
1267
+ }
1268
+
1269
+ export function useSubstrateStatus(enabled = true, options: SubstratePollOptions = {}) {
1270
+ return useSubstrateQuery<SubstrateStatus>(['status'], '/substrate/status', enabled, options.pollMs ?? POLL_MS)
1271
+ }
1272
+
1273
+ /** How this Radar reads Substrate's API: the saved connection (view local) or the installation's (view managed). */
1274
+ export function useSubstrateConnection(enabled = true) {
1275
+ return useSubstrateQuery<SubstrateConnection>(['connection'], '/substrate/connection', enabled, false)
1276
+ }
1277
+
1278
+ /** The sidebar passes a slower pollMs while no Substrate screen is open. */
1279
+ export function useSubstrateWorkspace(enabled = true, options: SubstratePollOptions = {}) {
1280
+ return useSubstrateQuery<SubstrateWorkspace>(['workspace'], '/substrate/workspace', enabled, options.pollMs ?? POLL_MS)
1281
+ }
1282
+
1283
+ export function useSubstrateActors(query: SubstrateActorsQuery, enabled = true) {
1284
+ const params = new URLSearchParams()
1285
+ const filters = new URLSearchParams()
1286
+ for (const [k, v] of Object.entries(query)) {
1287
+ const value = Array.isArray(v) ? v.join(',') : v
1288
+ if (value === undefined || value === '') continue
1289
+ params.set(k, String(value))
1290
+ if (k !== 'offset' && k !== 'limit') filters.set(k, String(value))
1291
+ }
1292
+ const qs = params.toString()
1293
+ return useSubstrateQuery<SubstrateActors>(
1294
+ ['actors', filters.toString(), qs],
1295
+ `/substrate/actors${qs ? `?${qs}` : ''}`,
1296
+ enabled,
1297
+ POLL_MS,
1298
+ sameSubstrateActorList,
1299
+ )
1300
+ }
1301
+
1302
+ /**
1303
+ * The sessions summary of one kagent Agent. Needs Substrate's API and kagentAttribution: an older Radar
1304
+ * reads as unsupported (upgrade), never as an error.
1305
+ */
1306
+ export function useKagentAgentSessions(agent: KagentAgentRef | null) {
1307
+ const kagent = useRadarFeature('kagentAttribution')
1308
+ const query = useSubstrateQuery<KagentAgentSessions>(
1309
+ ['kagent-agent-sessions', agent?.namespace, agent?.name, ...kagent.gatedKey],
1310
+ `/substrate/kagent/agents/${enc(agent?.namespace ?? '')}/${enc(agent?.name ?? '')}/sessions`,
1311
+ !!agent && kagent.support === 'supported',
1312
+ )
1313
+ return { ...query, kagentSupport: kagent.support, kagentUpgrade: kagent.upgrade }
1314
+ }
1315
+
1316
+ export function useSubstrateActor(ref: SubstrateRef | null) {
1317
+ return useSubstrateQuery<SubstrateActorDetail>(
1318
+ ['actor', ref?.atespace, ref?.name],
1319
+ `/substrate/actors/${enc(ref?.atespace ?? '')}/${enc(ref?.name ?? '')}`,
1320
+ !!ref,
1321
+ )
1322
+ }
1323
+
1324
+ export function useSubstrateActorLogs(
1325
+ ref: Pick<SubstrateActor, 'atespace' | 'name' | 'state' | 'assignment' | 'crash'> | null,
1326
+ options: { source?: SubstrateLogSource; container?: string; tailLines?: number } & SubstratePollOptions = {},
1327
+ ) {
1328
+ const params = new URLSearchParams()
1329
+ if (options.source) params.set('source', options.source)
1330
+ if (options.container) params.set('container', options.container)
1331
+ if (options.tailLines) params.set('tailLines', String(options.tailLines))
1332
+ const qs = params.toString()
1333
+ return useSubstrateQuery<SubstrateActorLogs>(
1334
+ ['actor-logs', ref?.atespace, ref?.name, qs, ref?.state, ref?.assignment?.worker, ref?.crash?.time],
1335
+ `/substrate/actors/${enc(ref?.atespace ?? '')}/${enc(ref?.name ?? '')}/logs${qs ? `?${qs}` : ''}`,
1336
+ !!ref,
1337
+ options.pollMs ?? POLL_MS,
1338
+ )
1339
+ }
1340
+
1341
+ /** pool: name, or namespace/name. */
1342
+ export function useSubstrateWorkers(pool?: string, enabled = true) {
1343
+ const qs = pool ? `?pool=${enc(pool)}` : ''
1344
+ return useSubstrateQuery<SubstrateWorkers>(['workers', pool ?? ''], `/substrate/workers${qs}`, enabled)
1345
+ }
1346
+
1347
+ export function useSubstrateTemplates(enabled = true) {
1348
+ return useSubstrateQuery<SubstrateTemplates>(['templates'], '/substrate/templates', enabled)
1349
+ }
1350
+
1351
+ export function useSubstrateTemplate(ref: SubstrateRef | null) {
1352
+ return useSubstrateQuery<SubstrateTemplate>(
1353
+ ['template', ref?.atespace, ref?.name],
1354
+ `/substrate/templates/${enc(ref?.atespace ?? '')}/${enc(ref?.name ?? '')}`,
1355
+ !!ref,
1356
+ )
1357
+ }
1358
+
1359
+ export function useSubstratePool(ref: SubstratePoolRef | null) {
1360
+ return useSubstrateQuery<SubstratePool>(
1361
+ ['pool', ref?.namespace, ref?.name],
1362
+ `/substrate/workerpools/${enc(ref?.namespace ?? '')}/${enc(ref?.name ?? '')}`,
1363
+ !!ref,
1364
+ )
1365
+ }
1366
+
1367
+ /**
1368
+ * Saves this context's connection; every substrate query then reads through
1369
+ * it. A save whose target no longer matches the context answers 409
1370
+ * targetChanged and saves nothing; queries refetch either way, so the form
1371
+ * shows the current context's connection and target to review again.
1372
+ */
1373
+ export function useUpdateSubstrateConnection() {
1374
+ const queryClient = useQueryClient()
1375
+ const feature = useRadarFeature('substrateWorkspace')
1376
+ return useMutation({
1377
+ mutationFn: (update: SubstrateConnectionUpdate) =>
1378
+ feature.guard(async () => {
1379
+ const resp = await apiFetch(`${getApiBase()}/substrate/connection`, {
1380
+ method: 'PUT',
1381
+ headers: { 'Content-Type': 'application/json' },
1382
+ body: JSON.stringify(update),
1383
+ })
1384
+ if (!resp.ok) {
1385
+ const body = await readErrorBody(resp)
1386
+ throw new ApiError(body.error || httpStatusMessage(resp.status, resp.statusText), resp.status, body as Record<string, unknown>)
1387
+ }
1388
+ return (await resp.json()) as SubstrateConnection
1389
+ }),
1390
+ onSettled: () => {
1391
+ queryClient.invalidateQueries({ queryKey: ['substrate', getApiBase()] })
1392
+ },
1393
+ })
1394
+ }