@botmanor/fe-sdk 2026.1205.3 → 2026.1205.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,20 +1,41 @@
1
1
  "use client";
2
2
  import { createContext, use, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
3
3
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4
+ import { C as GUIDED_ENTRIES, D as permissionLabelKey, E as PERMISSION_LABELS, S as AGENT_STATUS_SHORT_LABELS, T as GUIDED_PERMISSIONS, _ as isDefiniteRefusal, a as fillGuidedParams, b as extractGuidedSource, c as guidedTranslateFrom, d as botmanorPath, f as crossShellUrl, g as guidedI18nBase, h as describeGuidedError, i as englishGuidedTranslate, l as planGuidedActions, m as buildGuidedError, n as stepReasonCode, o as guidedParams, p as resolveGuidedLocation, r as stopReasonLabel, s as guidedText, t as describeRunFailure, u as DEFAULT_BOTMANOR_APP_URL, v as isStaleStateError, w as STOP_REASON_LABELS, x as AGENT_STATUS_LABELS, y as reasonCamel } from "./guided-errors-D5vT9owt.js";
4
5
 
5
6
  // src/graphql/client.ts
6
7
  /** Failure from the gateway: a transport status or a GraphQL error code. */
7
8
  var StewardsRequestError = class extends Error {
8
9
  code;
9
10
  status;
10
- /** The plan quota a `QUOTA_EXHAUSTED` refusal names, e.g. `botmanor.stewards.runs`. */
11
+ /**
12
+ * The plan quota a `QUOTA_EXHAUSTED` refusal names, e.g.
13
+ * `botmanor.stewards.runs` (`extensions.quotaKey`, or the older `quotaName`).
14
+ */
11
15
  quotaName;
12
- constructor(message, code, status, quotaName) {
16
+ /**
17
+ * The GraphQL error's whole `extensions` object: `reason`, `i18nKey` and the
18
+ * context fields the guided-error catalog reads (BOFF-18785). Empty for a
19
+ * transport failure.
20
+ */
21
+ extensions;
22
+ constructor(message, code, status, quotaName, extensions = {}) {
13
23
  super(message);
14
24
  this.name = "StewardsRequestError";
15
25
  this.code = code;
16
26
  this.status = status;
17
27
  if (quotaName) this.quotaName = quotaName;
28
+ this.extensions = extensions;
29
+ }
30
+ /** `extensions.reason`, the catalog's guided code, when the service sent one. */
31
+ get reason() {
32
+ const reason = this.extensions.reason;
33
+ return typeof reason === "string" ? reason : void 0;
34
+ }
35
+ /** `extensions.i18nKey`, the service's translation key, when it sent one. */
36
+ get i18nKey() {
37
+ const key = this.extensions.i18nKey;
38
+ return typeof key === "string" ? key : void 0;
18
39
  }
19
40
  };
20
41
  const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
@@ -112,17 +133,23 @@ function createStewardsClient(options) {
112
133
  if (first) {
113
134
  const code = typeof first.extensions?.code === "string" ? first.extensions.code : "GRAPHQL_ERROR";
114
135
  if (code === "UNAUTHENTICATED") options.reportAuthExpired("gateway rejected the token");
115
- const quotaName = typeof first.extensions?.quotaName === "string" ? first.extensions.quotaName : void 0;
116
- throw new StewardsRequestError(first.message ?? "Request failed", code, response.status, quotaName);
136
+ else if (code === "FORBIDDEN" && typeof first.extensions?.authFailure === "string") options.reportAuthExpired(`gateway refused the session: ${first.extensions.authFailure}`);
137
+ const headerWait = Number(response.headers.get("retry-after"));
138
+ const extensions = first.extensions?.retryAfter === void 0 && Number.isFinite(headerWait) && headerWait > 0 ? {
139
+ ...first.extensions ?? {},
140
+ retryAfter: headerWait
141
+ } : first.extensions ?? {};
142
+ const quotaName = typeof extensions.quotaKey === "string" ? extensions.quotaKey : typeof extensions.quotaName === "string" ? extensions.quotaName : void 0;
143
+ throw new StewardsRequestError(first.message ?? "Request failed", code, response.status, quotaName, extensions);
117
144
  }
118
145
  if (!response.ok || body.data == null) throw new StewardsRequestError(`Unexpected response from the Stewards service (${response.status})`, "BAD_RESPONSE", response.status);
119
146
  return body.data;
120
147
  };
121
- return { async request(document, variables = {}, signal) {
148
+ return { async request(document, variables = {}, signal, requestOptions = {}) {
122
149
  try {
123
150
  return await send(document, variables, signal);
124
151
  } catch (err) {
125
- if (err instanceof StewardsRequestError && !signal?.aborted) options.reportFailure?.(err);
152
+ if (err instanceof StewardsRequestError && !signal?.aborted && !requestOptions.silent) options.reportFailure?.(err);
126
153
  throw err;
127
154
  }
128
155
  } };
@@ -212,13 +239,16 @@ function StewardsSdkProvider({ children, ...config }) {
212
239
  code: error.code,
213
240
  message: error.message,
214
241
  ...error.status !== void 0 ? { status: error.status } : {},
215
- ...error.quotaName ? { quotaName: error.quotaName } : {}
242
+ ...error.quotaName ? { quotaName: error.quotaName } : {},
243
+ ...error.reason ? { reason: error.reason } : {},
244
+ ...error.i18nKey ? { i18nKey: error.i18nKey } : {},
245
+ ...Object.keys(error.extensions).length > 0 ? { extensions: error.extensions } : {}
216
246
  });
217
247
  }
218
248
  })
219
249
  };
220
250
  });
221
- const { gatewayUrl, workspaceId, getAccessToken, getWorkspaceToken, sameOriginCredentials, onTokenExpired, theme } = config;
251
+ const { gatewayUrl, workspaceId, getAccessToken, getWorkspaceToken, sameOriginCredentials, onTokenExpired, theme, resolveTarget, navigate, hasPermission, viewerActorId, resolveActorName, translate, onUpgrade } = config;
222
252
  const value = useMemo(() => ({
223
253
  config: {
224
254
  gatewayUrl,
@@ -228,7 +258,14 @@ function StewardsSdkProvider({ children, ...config }) {
228
258
  ...sameOriginCredentials ? { sameOriginCredentials } : {},
229
259
  ...onTokenExpired ? { onTokenExpired } : {},
230
260
  ...onEvent ? { onEvent } : {},
231
- ...theme ? { theme } : {}
261
+ ...theme ? { theme } : {},
262
+ ...resolveTarget ? { resolveTarget } : {},
263
+ ...navigate ? { navigate } : {},
264
+ ...hasPermission ? { hasPermission } : {},
265
+ ...viewerActorId !== void 0 ? { viewerActorId } : {},
266
+ ...resolveActorName ? { resolveActorName } : {},
267
+ ...translate ? { translate } : {},
268
+ ...onUpgrade ? { onUpgrade } : {}
232
269
  },
233
270
  events,
234
271
  ...services
@@ -241,6 +278,13 @@ function StewardsSdkProvider({ children, ...config }) {
241
278
  onTokenExpired,
242
279
  onEvent,
243
280
  theme,
281
+ resolveTarget,
282
+ navigate,
283
+ hasPermission,
284
+ viewerActorId,
285
+ resolveActorName,
286
+ translate,
287
+ onUpgrade,
244
288
  events,
245
289
  services
246
290
  ]);
@@ -322,7 +366,7 @@ const RUN_SUMMARY = `
322
366
  const STEWARD_DETAIL = `
323
367
  id agentId ownerActorId status defaultDeskKind pendingApprovalCount
324
368
  createdAt updatedAt
325
- agent { id name capabilities }
369
+ agent { id name capabilities status llmModelId }
326
370
  charter {
327
371
  autonomyLevel charterText charterVersion allowedToolKeys
328
372
  allowedConnectionIds timezone dryRunDefault
@@ -335,7 +379,7 @@ const STEWARD_DETAIL = `
335
379
  const LIST_STEWARDS = `query ListBotmanorStewards($filter: BotmanorStewardFilterInput, $pagination: PaginationInput) {
336
380
  listBotmanorStewards(filter: $filter, pagination: $pagination) {
337
381
  id agentId status defaultDeskKind pendingApprovalCount
338
- agent { id name }
382
+ agent { id name status }
339
383
  charter { autonomyLevel budgetPerDay { credits } }
340
384
  usageToday { credits }
341
385
  lastRun { id status startedAt }
@@ -372,11 +416,16 @@ const CREATE_STEWARD = `mutation CreateBotmanorSteward($input: CreateBotmanorSte
372
416
  const UPDATE_STEWARD_CHARTER = `mutation UpdateBotmanorStewardCharter($id: ID!, $input: UpdateBotmanorStewardCharterInput!) {
373
417
  updateBotmanorStewardCharter(id: $id, input: $input) { ${STEWARD_DETAIL} }
374
418
  }`;
375
- const SET_STEWARD_STATUS = `mutation SetBotmanorStewardStatus($id: ID!, $status: BotmanorStewardStatus!) {
376
- setBotmanorStewardStatus(id: $id, status: $status) { id status }
377
- }`;
378
- const LIST_AGENT_CANDIDATES = `query ListStewardAgentCandidates($filters: BotmanorAgentFilterInput) {
379
- listBotmanorAgents(filters: $filters) { id name description status capabilities }
419
+ const CANDIDATE = `id name description status capabilities llmModelId`;
420
+ /**
421
+ * The agents that can become a steward, one filtered list per status, so a
422
+ * workspace with many archived or training agents never pushes an active one
423
+ * off the first page (BOFF-18785).
424
+ */
425
+ const LIST_PICKABLE_AGENTS = `query ListStewardPickableAgents($pagination: PaginationInput) {
426
+ active: listBotmanorAgents(filters: { status: ACTIVE }, pagination: $pagination) { ${CANDIDATE} }
427
+ draft: listBotmanorAgents(filters: { status: DRAFT }, pagination: $pagination) { ${CANDIDATE} }
428
+ paused: listBotmanorAgents(filters: { status: PAUSED }, pagination: $pagination) { ${CANDIDATE} }
380
429
  }`;
381
430
  const LIST_STEWARD_APPROVALS = `query ListBotmanorToolApprovals($filter: BotmanorToolApprovalFilterInput, $pagination: PaginationInput) {
382
431
  listBotmanorToolApprovals(filter: $filter, pagination: $pagination) {
@@ -410,7 +459,7 @@ const LIST_OWN_MACHINE_AGENTS = `query StewardOwnMachineAgents($pagination: Pagi
410
459
  id name hostname platform isActive ownerUserId lastHeartbeat
411
460
  }
412
461
  }`;
413
- const OWN_MACHINE_GRANT = `id agentId status expiresAt scopes`;
462
+ const OWN_MACHINE_GRANT = `id agentId status expiresAt scopes grantorActorId`;
414
463
  /**
415
464
  * The steward's active grants (VibeControls returns at most 100, newest
416
465
  * first). Pass `agentId` to look one machine up when the list may be cut off.
@@ -425,6 +474,48 @@ const GRANT_OWN_MACHINE = `mutation GrantStewardOwnMachine($input: GrantVibecont
425
474
  const REVOKE_OWN_MACHINE_GRANT = `mutation RevokeStewardOwnMachineGrant($id: ID!) {
426
475
  revokeVibecontrolsStewardGrant(id: $id) { ${OWN_MACHINE_GRANT} }
427
476
  }`;
477
+ /**
478
+ * Guided-error fixes (BOFF-18785). The agent's status and model pick the
479
+ * right guidance when an older service does not send them with the error;
480
+ * publishing, requesting activation and activating are the inline fixes.
481
+ */
482
+ const GET_AGENT_STATUS = `query GetStewardAgentStatus($id: ID!) {
483
+ getBotmanorAgent(id: $id) { id name status llmModelId }
484
+ }`;
485
+ /** Publish (or resume) an agent: `updateBotmanorAgent` with status ACTIVE. */
486
+ const PUBLISH_AGENT = `mutation PublishStewardAgent($id: ID!) {
487
+ updateBotmanorAgent(id: $id, input: { status: ACTIVE }) { id status llmModelId }
488
+ }`;
489
+ const REQUEST_AGENT_ACTIVATION = `mutation RequestStewardAgentActivation($agentId: ID!) {
490
+ requestBotmanorAgentActivation(agentId: $agentId) { id status }
491
+ }`;
492
+ /** One activation request's status: PENDING until a reviewer decides or it is withdrawn. */
493
+ const GET_AGENT_ACTIVATION_REQUEST = `query GetStewardAgentActivationRequest($id: ID!) {
494
+ getBotmanorAgentApprovalRequest(id: $id) { id status isStale }
495
+ }`;
496
+ const SET_STEWARD_STATUS = `mutation SetBotmanorStewardStatus($id: ID!, $status: BotmanorStewardStatus!) {
497
+ setBotmanorStewardStatus(id: $id, status: $status) { id status }
498
+ }`;
499
+ /** The plan's cloud desk minutes: no assignment means the plan has none. */
500
+ const CHECK_DESK_MINUTES = `query StewardDeskMinutes($workspaceId: ID!) {
501
+ checkWorkspaceQuota(quotaName: "botmanor.stewards.desk-minutes", workspaceId: $workspaceId) {
502
+ allowed assignmentId limitLeft noLimit
503
+ }
504
+ }`;
505
+ /**
506
+ * A run's structured failure (guided-error catalog section 1.2). A separate,
507
+ * silent query: a service that does not expose `failure` yet refuses the field,
508
+ * and the run view then reads the stop reason and the steps instead.
509
+ */
510
+ const GET_STEWARD_RUN_FAILURE = `query GetBotmanorStewardRunFailure($id: ID!) {
511
+ getBotmanorStewardRun(id: $id) {
512
+ id
513
+ failure {
514
+ code message agentId toolKey connectionId machineId budgetLevel budgetKey
515
+ budgetCap stepCode
516
+ }
517
+ }
518
+ }`;
428
519
 
429
520
  // src/graphql/hooks.ts
430
521
  function asError(err) {
@@ -467,12 +558,13 @@ function useStewardsQuery(document, variables, options = {}) {
467
558
  variablesKey
468
559
  ]);
469
560
  const skip = options.skip === true;
561
+ const silent = options.silent === true;
470
562
  useEffect(() => {
471
563
  if (skip) return void 0;
472
564
  let active = true;
473
565
  const controller = new AbortController();
474
566
  const vars = JSON.parse(variablesKey);
475
- client.request(document, vars, controller.signal).then((data) => {
567
+ client.request(document, vars, controller.signal, { silent }).then((data) => {
476
568
  if (!active) return;
477
569
  setResult({
478
570
  key: requestKey,
@@ -499,6 +591,7 @@ function useStewardsQuery(document, variables, options = {}) {
499
591
  variablesKey,
500
592
  requestKey,
501
593
  skip,
594
+ silent,
502
595
  nonce
503
596
  ]);
504
597
  const current = result?.key === requestKey ? result : void 0;
@@ -547,25 +640,6 @@ function useStewardsMutation(document) {
547
640
  };
548
641
  }
549
642
 
550
- // src/theme/ScopedTheme.tsx
551
- /** The SDK's only styling root: theme variables live on this element alone. */
552
- function ScopedTheme({ theme, label, component, children }) {
553
- return /* @__PURE__ */ jsx("section", {
554
- "aria-label": label,
555
- "data-botmanor-sdk": component,
556
- style: {
557
- ...themeToStyle(theme),
558
- background: themeVar("surface"),
559
- color: themeVar("text"),
560
- border: `1px solid ${themeVar("border")}`,
561
- borderRadius: themeVar("radius"),
562
- fontFamily: themeVar("fontFamily"),
563
- padding: "16px"
564
- },
565
- children
566
- });
567
- }
568
-
569
643
  // src/components/ui.tsx
570
644
  /** Shared, token-only building blocks for the four SDK surfaces. */
571
645
  const headingStyle = {
@@ -690,6 +764,452 @@ function humanize(value) {
690
764
  return s.charAt(0).toUpperCase() + s.slice(1);
691
765
  }
692
766
 
767
+ // src/components/GuidedErrorNote.tsx
768
+ /** VibeControls in production, the default target of "Open VibeControls". */
769
+ const VIBECONTROLS_APP_URL = "https://app.vibecontrols.com";
770
+ /** The inline fixes the SDK runs itself; others fall back to a link. */
771
+ const SDK_MUTATIONS = /* @__PURE__ */ new Set([
772
+ "PUBLISH_AGENT",
773
+ "REQUEST_AGENT_ACTIVATION",
774
+ "ACTIVATE_STEWARD"
775
+ ]);
776
+ const boxStyle = {
777
+ border: `1px solid ${themeVar("danger")}`,
778
+ borderRadius: themeVar("radius"),
779
+ margin: "8px 0 0",
780
+ padding: "8px 12px",
781
+ fontSize: "14px"
782
+ };
783
+ const lineStyle = { margin: "4px 0 0" };
784
+ const mutedLineStyle = {
785
+ ...lineStyle,
786
+ color: themeVar("textMuted")
787
+ };
788
+ const linkStyle = {
789
+ color: themeVar("accent"),
790
+ fontSize: "13px",
791
+ fontWeight: 500
792
+ };
793
+ /**
794
+ * Where the SDK sends a guided action: the host's resolver when it gave one,
795
+ * else BotManor's own pages on app.botmanor.com and VibeControls.
796
+ */
797
+ function useGuidedEnvironment(canRetry, mutations = SDK_MUTATIONS) {
798
+ const { config } = useStewardsSdk();
799
+ const { resolveTarget, hasPermission, viewerActorId, translate, onUpgrade } = config;
800
+ return useMemo(() => {
801
+ const href = (location) => {
802
+ if (location.kind === "href") return location.href;
803
+ if (location.kind === "route") return location.path;
804
+ return crossShellUrl(location.product === "vibecontrols" ? VIBECONTROLS_APP_URL : DEFAULT_BOTMANOR_APP_URL, location.product === "vibecontrols" ? "/" : location.path);
805
+ };
806
+ return {
807
+ shell: { kind: "other" },
808
+ locate: (target, params) => {
809
+ if (resolveTarget) {
810
+ const resolved = resolveTarget(target, params);
811
+ return resolved ? {
812
+ kind: "href",
813
+ href: resolved
814
+ } : void 0;
815
+ }
816
+ if (target === "VIBECONTROLS") return {
817
+ kind: "href",
818
+ href: `${VIBECONTROLS_APP_URL}/`
819
+ };
820
+ const path = botmanorPath(target, params);
821
+ return path ? {
822
+ kind: "href",
823
+ href: crossShellUrl(DEFAULT_BOTMANOR_APP_URL, path)
824
+ } : void 0;
825
+ },
826
+ mutations,
827
+ canRetry,
828
+ canUpgrade: !!onUpgrade || !!resolveTarget?.("BILLING_PLANS", {}),
829
+ ...hasPermission ? { hasPermission } : {},
830
+ ...viewerActorId !== void 0 ? { viewerActorId } : {},
831
+ ...translate ? { t: translate } : {},
832
+ href
833
+ };
834
+ }, [
835
+ resolveTarget,
836
+ hasPermission,
837
+ viewerActorId,
838
+ translate,
839
+ onUpgrade,
840
+ canRetry,
841
+ mutations
842
+ ]);
843
+ }
844
+ /**
845
+ * An error, explained (BOFF-18785): what happened, why, the next step, up to
846
+ * two actions the viewer may take, and who can fix it when they cannot. A
847
+ * local validation error (no code) reads as its own message, as before.
848
+ */
849
+ function GuidedErrorNote({ error, guided: given, context, onRetry, onFixed, tone = "error", canActivateSteward = true }) {
850
+ const [fixError, setFixError] = useState(void 0);
851
+ const fixFailed = !!fixError && fixError.for === (given ?? error);
852
+ const mounted = useRef(true);
853
+ useEffect(() => {
854
+ mounted.current = true;
855
+ return () => {
856
+ mounted.current = false;
857
+ };
858
+ }, []);
859
+ const isMounted = useCallback(() => mounted.current, []);
860
+ const subjectRef = useRef(given ?? error);
861
+ useEffect(() => {
862
+ subjectRef.current = given ?? error;
863
+ });
864
+ const isCurrent = useCallback((subject) => mounted.current && subjectRef.current === subject, []);
865
+ const [requestedFor, setRequestedFor] = useState(void 0);
866
+ const shownError = fixError && fixError.for === (given ?? error) ? fixError.error : error;
867
+ const base = useMemo(() => fixError && fixError.for === (given ?? error) ? describeGuidedError(fixError.error, context) : given ?? (error ? describeGuidedError(error, context) : void 0), [
868
+ given,
869
+ error,
870
+ fixError,
871
+ context
872
+ ]);
873
+ const agentId = base?.params.agentId ? String(base.params.agentId) : void 0;
874
+ const needsAgent = base?.reason === "AGENT_NOT_ACTIVE" && !!agentId && (!context?.agent?.status || context.agent.status === "ACTIVE") && typeof extractGuidedSource(shownError)?.extensions?.agentStatus !== "string";
875
+ const fetchedAgent = useStewardsQuery("query GetStewardAgentStatus($id: ID!) {\n getBotmanorAgent(id: $id) { id name status llmModelId }\n}", { id: agentId ?? "" }, {
876
+ skip: !needsAgent,
877
+ silent: true
878
+ }).data?.getBotmanorAgent ?? void 0;
879
+ const guided = useMemo(() => {
880
+ if (!base || !needsAgent || !fetchedAgent || !shownError) return base;
881
+ return describeGuidedError(shownError, {
882
+ ...context,
883
+ agent: fetchedAgent
884
+ }) ?? base;
885
+ }, [
886
+ base,
887
+ needsAgent,
888
+ fetchedAgent,
889
+ shownError,
890
+ context
891
+ ]);
892
+ if (!guided) return null;
893
+ const guidedAgent = guided.params.agentId ? String(guided.params.agentId) : void 0;
894
+ const activationGuidance = guided.reason === "AGENT_NOT_ACTIVE" || guided.reason === "AGENT_APPROVAL_REQUIRED" || guided.reason === "ACTIVATION_ALREADY_PENDING" || guided.reason === "ACTIVATION_REQUEST_STALE";
895
+ if (requestedFor && activationGuidance && guidedAgent === requestedFor.agentId) return /* @__PURE__ */ jsx(RequestedNote, {
896
+ agentId: requestedFor.agentId,
897
+ ...requestedFor.requestId ? { requestId: requestedFor.requestId } : {},
898
+ isCurrent: () => isCurrent(given ?? error),
899
+ onSettled: (published) => {
900
+ setRequestedFor(void 0);
901
+ if (published) Promise.resolve(onRetry?.());
902
+ }
903
+ });
904
+ if (guided.reason === "UNKNOWN" && !guided.code && guided.serverMessage) return /* @__PURE__ */ jsx(PlainNote, { message: guided.serverMessage });
905
+ return /* @__PURE__ */ jsx(GuidedBody, {
906
+ canActivateSteward,
907
+ guided,
908
+ tone,
909
+ onRetry,
910
+ onFixed: (mutation, params) => {
911
+ if (mutation === "REQUEST_AGENT_ACTIVATION" && params.agentId) setRequestedFor({
912
+ agentId: String(params.agentId),
913
+ ...params.activationRequestId ? { requestId: String(params.activationRequestId) } : {}
914
+ });
915
+ setFixError(void 0);
916
+ onFixed?.(mutation);
917
+ },
918
+ ...fixFailed && fixError ? { retryFix: {
919
+ mutation: fixError.mutation,
920
+ params: fixError.params
921
+ } } : {},
922
+ isMounted,
923
+ isCurrent: () => isCurrent(given ?? error),
924
+ onFixFailed: (err, mutation, params) => setFixError({
925
+ for: given ?? error,
926
+ error: err,
927
+ mutation,
928
+ params
929
+ })
930
+ }, `${guided.i18nKey}|${String(guided.params.agentId ?? "")}|${String(guided.params.stewardId ?? "")}`);
931
+ }
932
+ /**
933
+ * An activation request is waiting for a reviewer. "Check again" reads the
934
+ * agent: once it is published the note gives way to the screen (reloaded);
935
+ * while it is not, the note says it is still waiting.
936
+ */
937
+ function RequestedNote({ agentId, requestId, isCurrent, onSettled }) {
938
+ const { client, config } = useStewardsSdk();
939
+ const t = config.translate ?? englishGuidedTranslate;
940
+ const [checking, setChecking] = useState(false);
941
+ const [stillWaiting, setStillWaiting] = useState(false);
942
+ const check = async () => {
943
+ setChecking(true);
944
+ try {
945
+ const agent = await client.request(GET_AGENT_STATUS, { id: agentId }, void 0, { silent: true });
946
+ const request = agent.getBotmanorAgent?.status !== "ACTIVE" && requestId ? await client.request(GET_AGENT_ACTIVATION_REQUEST, { id: requestId }, void 0, { silent: true }) : void 0;
947
+ if (!isCurrent()) return;
948
+ const published = agent.getBotmanorAgent?.status === "ACTIVE";
949
+ const open = request?.getBotmanorAgentApprovalRequest;
950
+ const pending = !request || open?.status === "PENDING" && !open.isStale;
951
+ if (published || !pending) onSettled(published);
952
+ else setStillWaiting(true);
953
+ } catch {
954
+ if (isCurrent()) setStillWaiting(true);
955
+ } finally {
956
+ setChecking(false);
957
+ }
958
+ };
959
+ return /* @__PURE__ */ jsxs("p", {
960
+ role: "status",
961
+ style: {
962
+ ...themeToStyle(config.theme),
963
+ ...mutedLineStyle
964
+ },
965
+ children: [
966
+ stillWaiting ? t("guidedErrors.done.activationStillPending", "Still waiting for a reviewer to approve the agent.") : t("guidedErrors.done.activationRequested", "Activation requested. You can continue once a reviewer approves the agent."),
967
+ " ",
968
+ /* @__PURE__ */ jsx(Button, {
969
+ onClick: () => void check(),
970
+ disabled: checking,
971
+ children: t("guidedErrors.actions.checkAgain", "Check again")
972
+ })
973
+ ]
974
+ });
975
+ }
976
+ function PlainNote({ message }) {
977
+ const { config } = useStewardsSdk();
978
+ return /* @__PURE__ */ jsx("p", {
979
+ role: "alert",
980
+ style: {
981
+ ...themeToStyle(config.theme),
982
+ ...lineStyle,
983
+ margin: "8px 0 0",
984
+ color: themeVar("danger"),
985
+ fontWeight: 500
986
+ },
987
+ children: message
988
+ });
989
+ }
990
+ /** The SDK's fixes without activating the steward. */
991
+ const SDK_MUTATIONS_NO_ACTIVATE = /* @__PURE__ */ new Set(["PUBLISH_AGENT", "REQUEST_AGENT_ACTIVATION"]);
992
+ function GuidedBody({ canActivateSteward, guided, tone, onRetry, onFixed, retryFix, onFixFailed, isMounted, isCurrent }) {
993
+ const { client, config } = useStewardsSdk();
994
+ const requestIdRef = useRef(void 0);
995
+ const env = useGuidedEnvironment(!!onRetry || !!retryFix, canActivateSteward ? SDK_MUTATIONS : SDK_MUTATIONS_NO_ACTIVATE);
996
+ const [busy, setBusy] = useState(false);
997
+ const retryRef = useRef(onRetry);
998
+ useEffect(() => {
999
+ retryRef.current = onRetry;
1000
+ });
1001
+ const waitUntil = useMemo(() => guided.retryAfterSeconds ? Date.now() + guided.retryAfterSeconds * 1e3 : 0, [guided]);
1002
+ const [now, setNow] = useState(() => Date.now());
1003
+ const waitLeft = Math.max(0, Math.ceil((waitUntil - now) / 1e3));
1004
+ useEffect(() => {
1005
+ if (waitLeft <= 0) return void 0;
1006
+ const timer = setTimeout(() => setNow(Date.now()), 1e3);
1007
+ return () => clearTimeout(timer);
1008
+ }, [waitLeft, now]);
1009
+ const [copied, setCopied] = useState(void 0);
1010
+ const extraParams = useMemo(() => {
1011
+ const ownerId = guided.params.ownerActorId;
1012
+ const machineOwnerId = guided.params.machineOwnerActorId;
1013
+ return {
1014
+ ownerName: ownerId !== void 0 ? config.resolveActorName?.(String(ownerId)) : void 0,
1015
+ machineOwner: machineOwnerId !== void 0 ? config.resolveActorName?.(String(machineOwnerId)) : void 0
1016
+ };
1017
+ }, [guided.params, config]);
1018
+ const t = env.t ?? englishGuidedTranslate;
1019
+ const text = guidedText(guided, t, extraParams);
1020
+ const plan = planGuidedActions(guided, {
1021
+ ...env,
1022
+ extraParams
1023
+ });
1024
+ /** Runs one fix; false when it only queued something (an activation request). */
1025
+ const perform = useCallback(async (mutation, params) => {
1026
+ const agentId = params.agentId ? String(params.agentId) : void 0;
1027
+ const stewardId = params.stewardId ? String(params.stewardId) : void 0;
1028
+ if (mutation === "PUBLISH_AGENT" && agentId) {
1029
+ await client.request(PUBLISH_AGENT, { id: agentId });
1030
+ return true;
1031
+ }
1032
+ if (mutation === "REQUEST_AGENT_ACTIVATION" && agentId) {
1033
+ const made = await client.request(REQUEST_AGENT_ACTIVATION, { agentId });
1034
+ requestIdRef.current = made.requestBotmanorAgentActivation.id;
1035
+ return false;
1036
+ }
1037
+ if (mutation === "ACTIVATE_STEWARD" && stewardId) {
1038
+ await client.request(SET_STEWARD_STATUS, {
1039
+ id: stewardId,
1040
+ status: "ACTIVE"
1041
+ });
1042
+ return true;
1043
+ }
1044
+ return false;
1045
+ }, [client]);
1046
+ const runFix = useCallback(async (mutation, params = guided.params) => {
1047
+ const interrupted = retryFix && retryFix.mutation !== mutation ? retryFix : void 0;
1048
+ setBusy(true);
1049
+ let step = {
1050
+ mutation,
1051
+ params
1052
+ };
1053
+ try {
1054
+ const continues = await perform(mutation, params);
1055
+ if (!isCurrent()) return;
1056
+ if (!continues) {
1057
+ onFixed?.(mutation, requestIdRef.current ? {
1058
+ ...params,
1059
+ activationRequestId: requestIdRef.current
1060
+ } : params);
1061
+ return;
1062
+ }
1063
+ if (interrupted) {
1064
+ step = interrupted;
1065
+ const next = await perform(interrupted.mutation, interrupted.params);
1066
+ if (!isCurrent()) return;
1067
+ if (!next) {
1068
+ onFixed?.(interrupted.mutation, interrupted.params);
1069
+ return;
1070
+ }
1071
+ }
1072
+ onFixed?.(step.mutation, step.params);
1073
+ try {
1074
+ await retryRef.current?.();
1075
+ } catch {}
1076
+ } catch (err) {
1077
+ onFixFailed(err instanceof Error ? err : new Error(String(err)), step.mutation, step.params);
1078
+ } finally {
1079
+ if (isMounted()) setBusy(false);
1080
+ }
1081
+ }, [
1082
+ guided.params,
1083
+ retryFix,
1084
+ perform,
1085
+ onFixed,
1086
+ onFixFailed,
1087
+ isMounted,
1088
+ isCurrent
1089
+ ]);
1090
+ const act = (planned) => {
1091
+ const { action } = planned;
1092
+ if (action.kind === "retry") {
1093
+ if (retryFix) runFix(retryFix.mutation, retryFix.params);
1094
+ else Promise.resolve(onRetry?.());
1095
+ return;
1096
+ }
1097
+ if (action.kind === "mutation" && action.mutation) {
1098
+ runFix(action.mutation);
1099
+ return;
1100
+ }
1101
+ if (action.kind === "upgrade" && config.onUpgrade) {
1102
+ config.onUpgrade(guided);
1103
+ return;
1104
+ }
1105
+ if (planned.location) {
1106
+ const href = env.href(planned.location);
1107
+ if (href.startsWith("/") && config.navigate) config.navigate(href);
1108
+ else if (typeof window !== "undefined") window.location.assign(href);
1109
+ }
1110
+ };
1111
+ const details = [
1112
+ guided.reason,
1113
+ guided.code,
1114
+ guided.traceId ? `trace ${guided.traceId}` : void 0
1115
+ ].filter(Boolean).join(" · ");
1116
+ const copyDetails = () => {
1117
+ globalThis.navigator?.clipboard?.writeText(details).then(() => setCopied(details), () => void 0);
1118
+ };
1119
+ return /* @__PURE__ */ jsxs("div", {
1120
+ role: tone === "error" ? "alert" : "status",
1121
+ "data-guided-reason": guided.reason,
1122
+ ...guided.variant ? { "data-guided-variant": guided.variant } : {},
1123
+ style: {
1124
+ ...themeToStyle(config.theme),
1125
+ ...boxStyle,
1126
+ ...tone === "error" ? {} : { border: `1px solid ${themeVar("border")}` }
1127
+ },
1128
+ children: [
1129
+ /* @__PURE__ */ jsx("strong", {
1130
+ style: tone === "error" ? { color: themeVar("danger") } : void 0,
1131
+ children: text.title
1132
+ }),
1133
+ text.cause && text.cause !== text.title ? /* @__PURE__ */ jsx("p", {
1134
+ style: lineStyle,
1135
+ children: text.cause
1136
+ }) : null,
1137
+ text.next ? /* @__PURE__ */ jsx("p", {
1138
+ style: lineStyle,
1139
+ children: text.next
1140
+ }) : null,
1141
+ plan.askAdmin.map((line) => /* @__PURE__ */ jsx("p", {
1142
+ style: mutedLineStyle,
1143
+ children: line
1144
+ }, line)),
1145
+ plan.actions.length > 0 ? /* @__PURE__ */ jsx("div", {
1146
+ style: {
1147
+ alignItems: "center",
1148
+ display: "flex",
1149
+ flexWrap: "wrap",
1150
+ gap: "8px",
1151
+ marginTop: "8px"
1152
+ },
1153
+ children: plan.actions.map((planned, index) => planned.action.kind === "navigate" && planned.location ? /* @__PURE__ */ jsx("a", {
1154
+ href: env.href(planned.location),
1155
+ style: linkStyle,
1156
+ onClick: (e) => {
1157
+ const href = env.href(planned.location);
1158
+ if (e.button === 0 && !e.metaKey && !e.ctrlKey && !e.shiftKey && !e.altKey && href.startsWith("/") && config.navigate) {
1159
+ e.preventDefault();
1160
+ config.navigate(href);
1161
+ }
1162
+ },
1163
+ children: planned.label
1164
+ }, planned.action.id) : /* @__PURE__ */ jsx(Button, {
1165
+ kind: index === 0 ? "primary" : "secondary",
1166
+ disabled: busy || planned.action.kind === "retry" && waitLeft > 0,
1167
+ onClick: () => act(planned),
1168
+ children: planned.action.kind === "retry" && waitLeft > 0 ? t("guidedErrors.actions.retryIn", "{{label}} in {{seconds}}s", {
1169
+ label: planned.label,
1170
+ seconds: waitLeft
1171
+ }) : planned.label
1172
+ }, planned.action.id))
1173
+ }) : null,
1174
+ guided.traceId ? /* @__PURE__ */ jsx("p", {
1175
+ style: mutedLineStyle,
1176
+ children: /* @__PURE__ */ jsx("button", {
1177
+ type: "button",
1178
+ onClick: copyDetails,
1179
+ style: {
1180
+ ...linkStyle,
1181
+ background: "transparent",
1182
+ border: 0,
1183
+ cursor: "pointer",
1184
+ padding: 0,
1185
+ fontWeight: 400
1186
+ },
1187
+ children: copied === details ? t("guidedErrors.actions.copied", "Copied") : t("guidedErrors.actions.copyDetails", "Copy details")
1188
+ })
1189
+ }) : null
1190
+ ]
1191
+ });
1192
+ }
1193
+
1194
+ // src/theme/ScopedTheme.tsx
1195
+ /** The SDK's only styling root: theme variables live on this element alone. */
1196
+ function ScopedTheme({ theme, label, component, children }) {
1197
+ return /* @__PURE__ */ jsx("section", {
1198
+ "aria-label": label,
1199
+ "data-botmanor-sdk": component,
1200
+ style: {
1201
+ ...themeToStyle(theme),
1202
+ background: themeVar("surface"),
1203
+ color: themeVar("text"),
1204
+ border: `1px solid ${themeVar("border")}`,
1205
+ borderRadius: themeVar("radius"),
1206
+ fontFamily: themeVar("fontFamily"),
1207
+ padding: "16px"
1208
+ },
1209
+ children
1210
+ });
1211
+ }
1212
+
693
1213
  // src/components/StewardOwnMachineDesk.tsx
694
1214
  /** Where the person manages their VibeControls machines, by default. */
695
1215
  const DEFAULT_VIBECONTROLS_URL = "https://app.vibecontrols.com/";
@@ -715,16 +1235,32 @@ function isLive(grant, now) {
715
1235
  /**
716
1236
  * The owner's machines for the picker: the owner's agents, chosen one first,
717
1237
  * then granted ones, then by name. A grant counts while it is ACTIVE and not
718
- * past its expiry (`now`, for tests).
1238
+ * past its expiry (`now`, for tests). A live grant on any other machine
1239
+ * follows as a revoke-only row, so the person who may revoke it still can
1240
+ * (BOFF-18818); a machine the list does not hold is named by its id.
719
1241
  */
720
1242
  function ownMachineRows(agents, grants, ownerActorId, chosenAgentId, now = Date.now()) {
721
1243
  const granted = new Set(grants.filter((g) => isLive(g, now)).map((g) => g.agentId));
722
- const rank = (row) => row.chosen ? 0 : row.granted ? 1 : 2;
723
- return agents.filter((a) => a.ownerUserId === ownerActorId || a.id === chosenAgentId).map((agent) => ({
724
- agent,
725
- granted: granted.has(agent.id),
726
- chosen: agent.id === chosenAgentId
727
- })).sort((a, b) => rank(a) - rank(b) || a.agent.name.localeCompare(b.agent.name));
1244
+ const rank = (row) => row.revokeOnly ? 3 : row.chosen ? 0 : row.granted ? 1 : 2;
1245
+ const listed = new Set(agents.map((a) => a.id));
1246
+ const unlisted = [...granted].filter((id) => !listed.has(id)).map((id) => ({
1247
+ id,
1248
+ name: `Machine ${id.slice(0, 8)}`,
1249
+ hostname: "",
1250
+ platform: "",
1251
+ isActive: false,
1252
+ ownerUserId: null,
1253
+ lastHeartbeat: null
1254
+ }));
1255
+ return [...agents, ...unlisted].filter((a) => a.ownerUserId === ownerActorId || a.id === chosenAgentId || granted.has(a.id)).map((agent) => {
1256
+ const row = {
1257
+ agent,
1258
+ granted: granted.has(agent.id),
1259
+ chosen: agent.id === chosenAgentId
1260
+ };
1261
+ if (agent.ownerUserId !== ownerActorId && !row.chosen) row.revokeOnly = true;
1262
+ return row;
1263
+ }).sort((a, b) => rank(a) - rank(b) || a.agent.name.localeCompare(b.agent.name));
728
1264
  }
729
1265
  /** The expiry to send for a grant of `days`, never past the service's 30-day limit. */
730
1266
  function ownMachineGrantExpiry(days, now = Date.now()) {
@@ -756,6 +1292,21 @@ function nextOwnMachineGrantExpiry(grants, now = Date.now()) {
756
1292
  }
757
1293
  return next;
758
1294
  }
1295
+ /**
1296
+ * May the viewer revoke a steward's grant on a machine (BOFF-18818)? The
1297
+ * gateway needs agent:update, and the service then lets the grant's grantor
1298
+ * or the machine's current owner revoke it, whatever they may do with the
1299
+ * steward itself (botmanor-steward:update is not needed). As elsewhere here,
1300
+ * data the host did not give is left to the gateway.
1301
+ */
1302
+ function ownMachineCanRevoke(machineOwnerId, grantorActorId, access = {}) {
1303
+ if (access.canGrantMachines === false) return false;
1304
+ const viewer = access.viewerActorId;
1305
+ if (viewer === void 0) return true;
1306
+ if (!viewer) return false;
1307
+ if (!machineOwnerId) return true;
1308
+ return viewer === machineOwnerId || viewer === grantorActorId;
1309
+ }
759
1310
  /** What the viewer may do with the picker, from {@link OwnMachineAccess}. */
760
1311
  function ownMachineAbilities(ownerActorId, access = {}) {
761
1312
  const manage = (access.viewerActorId === void 0 || access.viewerActorId === ownerActorId) && access.canUpdateSteward !== false;
@@ -1122,12 +1673,20 @@ function StewardOwnMachineDeskPanel({ stewardId, ownerActorId, vibecontrolsUrl =
1122
1673
  busy,
1123
1674
  canChoose: abilities.manage,
1124
1675
  canGrant: abilities.grant,
1676
+ canCheck: abilities.grant || abilities.manage || access?.canGrantMachines !== false,
1677
+ canRevoke: (agent) => ownMachineCanRevoke(agent.ownerUserId, grants.find((g) => g.agentId === agent.id && isLive(g, Date.now()))?.grantorActorId, access),
1125
1678
  onCheck: (agentId) => void onCheck(agentId),
1126
1679
  onChoose: (agentId) => void onChoose(agentId),
1127
1680
  onGrant: (agentId) => void onGrant(agentId),
1128
1681
  onRevoke: (agentId) => void onRevoke(agentId)
1129
1682
  }) : /* @__PURE__ */ jsx(Muted, { children: "Your role cannot see VibeControls machines in this workspace." }),
1130
- /* @__PURE__ */ jsx(ErrorNote, { error: actionError })
1683
+ /* @__PURE__ */ jsx(GuidedErrorNote, {
1684
+ error: actionError,
1685
+ context: {
1686
+ stewardId,
1687
+ ownerActorId
1688
+ }
1689
+ })
1131
1690
  ]
1132
1691
  });
1133
1692
  }
@@ -1190,7 +1749,7 @@ function GrantOptions({ stewardId, days, onDays, appsText, onAppsText }) {
1190
1749
  function CurrentMachine({ loading, loaded, error, current, name, canClear, busy, onClear }) {
1191
1750
  return /* @__PURE__ */ jsxs(Fragment, { children: [
1192
1751
  loading ? /* @__PURE__ */ jsx(Muted, { children: "Loading the desk…" }) : null,
1193
- /* @__PURE__ */ jsx(ErrorNote, { error }),
1752
+ /* @__PURE__ */ jsx(GuidedErrorNote, { error }),
1194
1753
  current ? /* @__PURE__ */ jsxs("p", {
1195
1754
  style: { margin: "8px 0 0" },
1196
1755
  children: [
@@ -1213,7 +1772,7 @@ function CurrentMachine({ loading, loaded, error, current, name, canClear, busy,
1213
1772
  function MachineList({ loading, listed, truncated, error, rows, ...actions }) {
1214
1773
  return /* @__PURE__ */ jsxs(Fragment, { children: [
1215
1774
  loading ? /* @__PURE__ */ jsx(Muted, { children: "Loading your machines…" }) : null,
1216
- /* @__PURE__ */ jsx(ErrorNote, { error }),
1775
+ /* @__PURE__ */ jsx(GuidedErrorNote, { error }),
1217
1776
  listed && rows.length === 0 ? /* @__PURE__ */ jsx(Muted, { children: "You have no VibeControls machines in this workspace." }) : null,
1218
1777
  truncated ? /* @__PURE__ */ jsx(Muted, { children: "Only the first machines in this workspace are listed." }) : null,
1219
1778
  rows.length > 0 ? /* @__PURE__ */ jsx("ul", {
@@ -1226,7 +1785,7 @@ function MachineList({ loading, listed, truncated, error, rows, ...actions }) {
1226
1785
  }) : null
1227
1786
  ] });
1228
1787
  }
1229
- function MachineRow({ row: { agent, granted, chosen }, unchecked, ownerActorId, onCheck, busy, canChoose, canGrant, onChoose, onGrant, onRevoke }) {
1788
+ function MachineRow({ row: { agent, granted, chosen, revokeOnly }, unchecked, ownerActorId, onCheck, busy, canChoose, canGrant, canCheck, canRevoke, onChoose, onGrant, onRevoke }) {
1230
1789
  const unknown = !granted && unchecked.has(agent.id);
1231
1790
  return /* @__PURE__ */ jsxs("li", {
1232
1791
  style: rowStyle,
@@ -1241,7 +1800,9 @@ function MachineRow({ row: { agent, granted, chosen }, unchecked, ownerActorId,
1241
1800
  " ",
1242
1801
  chosen ? /* @__PURE__ */ jsx(Badge, { children: "Chosen" }) : null,
1243
1802
  " ",
1244
- (canGrant || canChoose) && unknown ? /* @__PURE__ */ jsx(Button, {
1803
+ revokeOnly ? /* @__PURE__ */ jsx(Badge, { children: "Not the steward owner's machine" }) : null,
1804
+ " ",
1805
+ canCheck && unknown ? /* @__PURE__ */ jsx(Button, {
1245
1806
  onClick: () => onCheck(agent.id),
1246
1807
  disabled: busy,
1247
1808
  label: `Check the grant on ${agent.name}`,
@@ -1255,7 +1816,7 @@ function MachineRow({ row: { agent, granted, chosen }, unchecked, ownerActorId,
1255
1816
  children: "Grant to this steward"
1256
1817
  }) : null,
1257
1818
  " ",
1258
- canChoose && granted && !chosen ? /* @__PURE__ */ jsx(Button, {
1819
+ canChoose && granted && !chosen && !revokeOnly ? /* @__PURE__ */ jsx(Button, {
1259
1820
  kind: "primary",
1260
1821
  onClick: () => onChoose(agent.id),
1261
1822
  disabled: busy,
@@ -1263,7 +1824,7 @@ function MachineRow({ row: { agent, granted, chosen }, unchecked, ownerActorId,
1263
1824
  children: "Use this machine"
1264
1825
  }) : null,
1265
1826
  " ",
1266
- canGrant && granted ? /* @__PURE__ */ jsx(Button, {
1827
+ granted && canRevoke(agent) ? /* @__PURE__ */ jsx(Button, {
1267
1828
  onClick: () => onRevoke(agent.id),
1268
1829
  disabled: busy,
1269
1830
  label: `Revoke the grant on ${agent.name}`,
@@ -1275,6 +1836,12 @@ function MachineRow({ row: { agent, granted, chosen }, unchecked, ownerActorId,
1275
1836
  }
1276
1837
 
1277
1838
  // src/components/StewardRunView.tsx
1839
+ /** Statuses after which a run's failure, if any, is known. */
1840
+ const UNFINISHED = /* @__PURE__ */ new Set([
1841
+ "FAILED",
1842
+ "STOPPED",
1843
+ "PAUSED_BUDGET"
1844
+ ]);
1278
1845
  const WAITING_REASON = {
1279
1846
  WAITING_APPROVAL: "APPROVAL",
1280
1847
  WAITING_TAKEOVER: "TAKEOVER",
@@ -1323,12 +1890,33 @@ function useRunTransitionEvents(runId, run) {
1323
1890
  * while the run is active (the embed session is not a subscription actor) and
1324
1891
  * emits `run.waiting`, `run.completed` and `run.failed` as the status changes.
1325
1892
  */
1326
- function StewardRunView({ runId, pollIntervalMs = 3e3 }) {
1893
+ function StewardRunView({ runId, pollIntervalMs = 3e3, onRunAgain, onStewardChanged, deskKind, canUpdateSteward = true }) {
1327
1894
  const { config } = useStewardsSdk();
1328
1895
  const { data, error, loading, refetch } = useStewardsQuery(GET_STEWARD_RUN, { id: runId }, { pollMs: (d) => d.getBotmanorStewardRun && !isTerminalRunStatus(d.getBotmanorStewardRun.status) ? pollIntervalMs : false });
1329
1896
  const cancel = useStewardsMutation(CANCEL_STEWARD_RUN);
1330
1897
  const run = data?.getBotmanorStewardRun ?? void 0;
1331
1898
  useRunTransitionEvents(runId, run);
1899
+ const unfinished = !!run && UNFINISHED.has(run.status);
1900
+ const failureQuery = useStewardsQuery(GET_STEWARD_RUN_FAILURE, { id: runId }, {
1901
+ skip: !unfinished,
1902
+ silent: true
1903
+ });
1904
+ const failure = failureQuery.data?.getBotmanorStewardRun?.failure ?? null;
1905
+ const guidedFailure = useMemo(() => run && !failureQuery.loading ? describeRunFailure({
1906
+ id: run.id,
1907
+ stewardId: run.stewardId,
1908
+ status: run.status,
1909
+ stopReason: run.stopReason,
1910
+ failure,
1911
+ steps: run.steps,
1912
+ stepCount: run.stepCount,
1913
+ ...deskKind ? { deskKind } : {}
1914
+ }) : void 0, [
1915
+ run,
1916
+ failure,
1917
+ failureQuery.loading,
1918
+ deskKind
1919
+ ]);
1332
1920
  const onCancel = async () => {
1333
1921
  if (await cancel.mutate({ id: runId })) refetch();
1334
1922
  };
@@ -1342,7 +1930,22 @@ function StewardRunView({ runId, pollIntervalMs = 3e3 }) {
1342
1930
  children: "Steward run"
1343
1931
  }),
1344
1932
  loading && !run ? /* @__PURE__ */ jsx(Muted, { children: "Loading the run…" }) : null,
1345
- /* @__PURE__ */ jsx(ErrorNote, { error: error ?? cancel.error }),
1933
+ /* @__PURE__ */ jsx(GuidedErrorNote, {
1934
+ error,
1935
+ context: {
1936
+ runId,
1937
+ ...run ? { stewardId: run.stewardId } : {}
1938
+ },
1939
+ onRetry: refetch
1940
+ }),
1941
+ /* @__PURE__ */ jsx(GuidedErrorNote, {
1942
+ error: error ? void 0 : cancel.error,
1943
+ context: {
1944
+ runId,
1945
+ ...run ? { stewardId: run.stewardId } : {}
1946
+ },
1947
+ ...isStaleStateError(cancel.error) ? { onRetry: refetch } : {}
1948
+ }),
1346
1949
  !loading && !error && !run ? /* @__PURE__ */ jsx(Muted, { children: "This run was not found." }) : null,
1347
1950
  run ? /* @__PURE__ */ jsxs(Fragment, { children: [
1348
1951
  /* @__PURE__ */ jsx(RunHeader, {
@@ -1350,6 +1953,16 @@ function StewardRunView({ runId, pollIntervalMs = 3e3 }) {
1350
1953
  cancelling: cancel.loading,
1351
1954
  onCancel: () => void onCancel()
1352
1955
  }),
1956
+ guidedFailure ? /* @__PURE__ */ jsx(GuidedErrorNote, {
1957
+ guided: guidedFailure,
1958
+ context: {
1959
+ runId,
1960
+ stewardId: run.stewardId
1961
+ },
1962
+ ...onRunAgain ? { onRetry: onRunAgain } : {},
1963
+ ...onStewardChanged ? { onFixed: onStewardChanged } : {},
1964
+ canActivateSteward: canUpdateSteward
1965
+ }) : null,
1353
1966
  /* @__PURE__ */ jsx(RunSteps, { steps: run.steps }),
1354
1967
  /* @__PURE__ */ jsx(RunApprovals, { approvals: run.approvals })
1355
1968
  ] }) : null
@@ -1363,7 +1976,8 @@ const subheadingStyle = {
1363
1976
  };
1364
1977
  function runTimeline(run) {
1365
1978
  const finished = run.finishedAt ? `, finished ${formatDate(run.finishedAt)}` : "";
1366
- const reason = run.stopReason ? ` — ${humanize(run.stopReason)}` : "";
1979
+ const label = stopReasonLabel(run.stopReason);
1980
+ const reason = label ? ` — ${label}` : "";
1367
1981
  return `Started ${formatDate(run.startedAt)}${finished}${reason}`;
1368
1982
  }
1369
1983
  function runUsage(run) {
@@ -1464,11 +2078,14 @@ function StewardConsole({ stewardId, onSelectSteward, vibecontrolsUrl, ownMachin
1464
2078
  });
1465
2079
  }
1466
2080
  function StewardList({ onSelect }) {
1467
- const { data, error, loading } = useStewardsQuery(LIST_STEWARDS, { pagination: { limit: 50 } });
2081
+ const { data, error, loading, refetch } = useStewardsQuery(LIST_STEWARDS, { pagination: { limit: 50 } });
1468
2082
  const stewards = data?.listBotmanorStewards;
1469
2083
  return /* @__PURE__ */ jsxs(Fragment, { children: [
1470
2084
  loading && !stewards ? /* @__PURE__ */ jsx(Muted, { children: "Loading stewards…" }) : null,
1471
- /* @__PURE__ */ jsx(ErrorNote, { error }),
2085
+ /* @__PURE__ */ jsx(GuidedErrorNote, {
2086
+ error,
2087
+ onRetry: refetch
2088
+ }),
1472
2089
  stewards && stewards.length === 0 ? /* @__PURE__ */ jsx(Muted, { children: "No stewards yet." }) : null,
1473
2090
  stewards && stewards.length > 0 ? /* @__PURE__ */ jsx("ul", {
1474
2091
  style: listStyle,
@@ -1479,6 +2096,7 @@ function StewardList({ onSelect }) {
1479
2096
  /* @__PURE__ */ jsx("strong", { children: s.agent?.name ?? s.agentId }),
1480
2097
  " ",
1481
2098
  /* @__PURE__ */ jsx(Badge, { children: humanize(s.status) }),
2099
+ s.agent?.status && s.agent.status !== "ACTIVE" ? /* @__PURE__ */ jsx(Badge, { children: agentStateLabel(s.agent.status) }) : null,
1482
2100
  s.charter ? /* @__PURE__ */ jsx(Badge, { children: humanize(s.charter.autonomyLevel) }) : null,
1483
2101
  s.pendingApprovalCount > 0 ? /* @__PURE__ */ jsxs(Badge, { children: [s.pendingApprovalCount, " awaiting approval"] }) : null,
1484
2102
  " ",
@@ -1506,11 +2124,21 @@ function StewardPanel({ stewardId, onBack, vibecontrolsUrl, ownMachineAccess })
1506
2124
  const loaded = steward.data?.getBotmanorSteward ?? void 0;
1507
2125
  const override = confirmed && confirmed.stewardId === stewardId && loaded?.id === stewardId && steward.data === confirmed.answer ? confirmed.status : void 0;
1508
2126
  if (confirmed && !override) setConfirmed(void 0);
1509
- const detail = loaded && override ? {
2127
+ const detail = useMemo(() => loaded && override ? {
1510
2128
  ...loaded,
1511
2129
  status: override
1512
- } : loaded;
2130
+ } : loaded, [loaded, override]);
1513
2131
  const notFound = !steward.loading && !steward.error && !detail;
2132
+ const context = useMemo(() => stewardContext(stewardId, detail), [stewardId, detail]);
2133
+ const onStatusChanged = (id, status) => {
2134
+ if (id !== stewardId) return;
2135
+ setConfirmed({
2136
+ stewardId: id,
2137
+ status,
2138
+ answer: latestAnswer.current
2139
+ });
2140
+ steward.refetch();
2141
+ };
1514
2142
  const onStarted = (runId) => {
1515
2143
  setSelectedRun(runId);
1516
2144
  runs.refetch();
@@ -1524,40 +2152,56 @@ function StewardPanel({ stewardId, onBack, vibecontrolsUrl, ownMachineAccess })
1524
2152
  })
1525
2153
  }) : null,
1526
2154
  steward.loading && !detail ? /* @__PURE__ */ jsx(Muted, { children: "Loading the steward…" }) : null,
1527
- /* @__PURE__ */ jsx(ErrorNote, { error: steward.error }),
2155
+ /* @__PURE__ */ jsx(GuidedErrorNote, {
2156
+ error: steward.error,
2157
+ context,
2158
+ onRetry: steward.refetch
2159
+ }),
1528
2160
  notFound ? /* @__PURE__ */ jsx(Muted, { children: "This steward was not found." }) : null,
1529
2161
  detail ? /* @__PURE__ */ jsxs(Fragment, { children: [
1530
2162
  /* @__PURE__ */ jsx(StewardSummary, { detail }),
1531
2163
  /* @__PURE__ */ jsx(StatusActions, {
1532
2164
  detail,
2165
+ context,
1533
2166
  canUpdate: ownMachineAccess?.canUpdateSteward !== false,
1534
- onChanged: (id, status) => {
1535
- if (id !== stewardId) return;
1536
- setConfirmed({
1537
- stewardId: id,
1538
- status,
1539
- answer: latestAnswer.current
1540
- });
1541
- steward.refetch();
1542
- }
2167
+ onChanged: onStatusChanged,
2168
+ onReload: steward.refetch
1543
2169
  }),
1544
2170
  /* @__PURE__ */ jsx(OwnMachineSection, {
1545
2171
  detail,
1546
2172
  vibecontrolsUrl,
1547
2173
  access: ownMachineAccess
1548
2174
  }),
1549
- detail.status === "ACTIVE" ? /* @__PURE__ */ jsx(StartRunForm, {
2175
+ /* @__PURE__ */ jsx(AgentGuidance, {
2176
+ detail,
2177
+ context,
2178
+ canUpdate: ownMachineAccess?.canUpdateSteward !== false,
2179
+ onChanged: onStatusChanged,
2180
+ onReload: steward.refetch
2181
+ }),
2182
+ detail.status === "ACTIVE" && agentIsActive(detail) ? /* @__PURE__ */ jsx(StartRunForm, {
1550
2183
  stewardId,
1551
- onStarted
1552
- }) : /* @__PURE__ */ jsx(Muted, { children: "Only an active steward can start a run." }),
2184
+ context,
2185
+ canActivateSteward: ownMachineAccess?.canUpdateSteward !== false,
2186
+ onStarted,
2187
+ onStewardChanged: steward.refetch,
2188
+ onRunsChanged: runs.refetch
2189
+ }) : detail.status === "ARCHIVED" || !agentIsActive(detail) ? null : /* @__PURE__ */ jsx(Muted, { children: "Only an active steward can start a run." }),
1553
2190
  /* @__PURE__ */ jsx(RecentRuns, {
1554
2191
  runs: runs.data?.listBotmanorStewardRuns,
1555
2192
  error: runs.error,
1556
- onView: setSelectedRun
2193
+ onView: setSelectedRun,
2194
+ onRetry: runs.refetch
1557
2195
  }),
1558
2196
  selectedRun ? /* @__PURE__ */ jsx("div", {
1559
2197
  style: { marginTop: "16px" },
1560
- children: /* @__PURE__ */ jsx(StewardRunView, { runId: selectedRun })
2198
+ children: /* @__PURE__ */ jsx(StewardRunView, {
2199
+ runId: selectedRun,
2200
+ ...detail.status === "ACTIVE" && agentIsActive(detail) ? { onRunAgain: () => focusPrompt(stewardId) } : {},
2201
+ onStewardChanged: steward.refetch,
2202
+ deskKind: detail.defaultDeskKind,
2203
+ canUpdateSteward: ownMachineAccess?.canUpdateSteward !== false
2204
+ })
1561
2205
  }) : null
1562
2206
  ] }) : null
1563
2207
  ] });
@@ -1584,10 +2228,11 @@ const NEXT_STATUS = {
1584
2228
  * Shown to a viewer with botmanor-steward:update (`canUpdateSteward`); without
1585
2229
  * an access answer the gateway decides.
1586
2230
  */
1587
- function StatusActions({ detail, canUpdate, onChanged }) {
2231
+ function StatusActions({ detail, context, canUpdate, onChanged, onReload }) {
1588
2232
  const change = useStewardsMutation(SET_STEWARD_STATUS);
1589
2233
  const next = NEXT_STATUS[detail.status];
1590
2234
  if (!next || !canUpdate) return null;
2235
+ if (next.to === "ACTIVE" && !agentIsActive(detail)) return null;
1591
2236
  const onClick = async () => {
1592
2237
  const result = await change.mutate({
1593
2238
  id: detail.id,
@@ -1601,9 +2246,95 @@ function StatusActions({ detail, canUpdate, onChanged }) {
1601
2246
  onClick: () => void onClick(),
1602
2247
  disabled: change.loading,
1603
2248
  children: next.label
1604
- }), /* @__PURE__ */ jsx(ErrorNote, { error: change.error })]
2249
+ }), /* @__PURE__ */ jsx(GuidedErrorNote, {
2250
+ error: change.error,
2251
+ context,
2252
+ ...isStaleStateError(change.error) ? { onRetry: onReload } : isDefiniteRefusal(change.error) ? { onRetry: () => void onClick() } : {},
2253
+ onFixed: onReload
2254
+ })]
1605
2255
  });
1606
2256
  }
2257
+ /**
2258
+ * What blocks a steward whose agent is not published (or is gone), or that is
2259
+ * archived, with the fix (catalog A1, A3 and A5 prevention). After the agent
2260
+ * is published here, a draft or paused steward is activated.
2261
+ */
2262
+ function AgentGuidance({ detail, context, canUpdate, onChanged, onReload }) {
2263
+ const { config } = useStewardsSdk();
2264
+ const activate = useStewardsMutation(SET_STEWARD_STATUS);
2265
+ const archived = detail.status === "ARCHIVED";
2266
+ const blocked = !detail.agent || !agentIsActive(detail);
2267
+ const preview = useMemo(() => {
2268
+ if (!archived && !blocked) return void 0;
2269
+ const reason = archived ? "STEWARD_ARCHIVED" : detail.agent ? "AGENT_NOT_ACTIVE" : "AGENT_UNAVAILABLE";
2270
+ return describeGuidedError({
2271
+ code: "BAD_USER_INPUT",
2272
+ extensions: {
2273
+ reason,
2274
+ stewardId: detail.id,
2275
+ agentId: detail.agentId
2276
+ }
2277
+ }, context);
2278
+ }, [
2279
+ archived,
2280
+ blocked,
2281
+ detail,
2282
+ context
2283
+ ]);
2284
+ const canActivate = canUpdate && config.hasPermission?.(GUIDED_PERMISSIONS.STEWARD_UPDATE) !== false;
2285
+ const afterPublish = async (mutation) => {
2286
+ if (mutation !== "PUBLISH_AGENT" || archived || detail.status === "ACTIVE" || !canActivate) {
2287
+ onReload();
2288
+ return;
2289
+ }
2290
+ const result = await activate.mutate({
2291
+ id: detail.id,
2292
+ status: "ACTIVE"
2293
+ });
2294
+ if (result) onChanged(result.setBotmanorStewardStatus.id, result.setBotmanorStewardStatus.status);
2295
+ else onReload();
2296
+ };
2297
+ return /* @__PURE__ */ jsxs(Fragment, { children: [preview ? /* @__PURE__ */ jsx(GuidedErrorNote, {
2298
+ guided: preview,
2299
+ context,
2300
+ tone: "info",
2301
+ onRetry: onReload,
2302
+ onFixed: (mutation) => void afterPublish(mutation)
2303
+ }) : null, /* @__PURE__ */ jsx(GuidedErrorNote, {
2304
+ error: activate.error,
2305
+ context,
2306
+ ...isStaleStateError(activate.error) ? { onRetry: onReload } : {},
2307
+ onFixed: onReload
2308
+ })] });
2309
+ }
2310
+ /** What the console knows about a steward and its agent, for guided errors. */
2311
+ function stewardContext(stewardId, detail) {
2312
+ return {
2313
+ stewardId,
2314
+ ...detail ? {
2315
+ stewardStatus: detail.status,
2316
+ ownerActorId: detail.ownerActorId
2317
+ } : {},
2318
+ ...detail?.agent ? { agent: {
2319
+ id: detail.agent.id,
2320
+ ...detail.agent.status ? { status: detail.agent.status } : {},
2321
+ ..."llmModelId" in detail.agent ? { llmModelId: detail.agent.llmModelId ?? null } : {}
2322
+ } } : detail ? { agent: { id: detail.agentId } } : {}
2323
+ };
2324
+ }
2325
+ /** An agent whose status is not known (an older service) counts as active. */
2326
+ function agentIsActive(detail) {
2327
+ if (!detail.agent) return false;
2328
+ const status = detail.agent.status;
2329
+ return !status || status === "ACTIVE";
2330
+ }
2331
+ function agentStateLabel(status) {
2332
+ return `Agent: ${(AGENT_STATUS_SHORT_LABELS[status] ?? humanize(status)).toLowerCase()}`;
2333
+ }
2334
+ function focusPrompt(stewardId) {
2335
+ if (typeof document === "undefined") return;
2336
+ document.getElementById(`prompt-${stewardId}`)?.focus();
2337
+ }
1607
2338
  /** The machine picker, for a steward whose desk kind is OWN_MACHINE. */
1608
2339
  function OwnMachineSection({ detail, vibecontrolsUrl, access }) {
1609
2340
  if (detail.defaultDeskKind !== "OWN_MACHINE") return null;
@@ -1633,6 +2364,7 @@ function StewardSummary({ detail }) {
1633
2364
  " ",
1634
2365
  /* @__PURE__ */ jsx(Badge, { children: humanize(detail.status) }),
1635
2366
  " ",
2367
+ detail.agent?.status ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Badge, { children: agentStateLabel(detail.agent.status) }), " "] }) : null,
1636
2368
  detail.charter ? /* @__PURE__ */ jsx(Badge, { children: humanize(detail.charter.autonomyLevel) }) : null,
1637
2369
  " ",
1638
2370
  /* @__PURE__ */ jsxs(Badge, { children: ["Desk ", humanize(detail.defaultDeskKind)] })
@@ -1646,19 +2378,22 @@ function StewardSummary({ detail }) {
1646
2378
  * Prompt box that starts a run. Emits `run.started` and hands the new run id
1647
2379
  * to the parent, which selects it and refreshes the run list.
1648
2380
  */
1649
- function StartRunForm({ stewardId, onStarted }) {
2381
+ function StartRunForm({ stewardId, context, onStarted, onStewardChanged, onRunsChanged, canActivateSteward }) {
1650
2382
  const { events } = useStewardsSdk();
1651
2383
  const start = useStewardsMutation(RUN_STEWARD);
1652
2384
  const [prompt, setPrompt] = useState("");
1653
2385
  const onSubmit = async (e) => {
1654
- e.preventDefault();
2386
+ e?.preventDefault();
1655
2387
  const text = prompt.trim();
1656
- if (!text) return;
2388
+ if (!text || start.loading) return;
1657
2389
  const result = await start.mutate({ input: {
1658
2390
  stewardId,
1659
2391
  prompt: text
1660
2392
  } });
1661
- if (!result) return;
2393
+ if (!result) {
2394
+ onRunsChanged();
2395
+ return;
2396
+ }
1662
2397
  const run = result.runBotmanorSteward;
1663
2398
  events.emit("run.started", {
1664
2399
  runId: run.id,
@@ -1691,12 +2426,18 @@ function StartRunForm({ stewardId, onStarted }) {
1691
2426
  children: "Run"
1692
2427
  })
1693
2428
  }),
1694
- /* @__PURE__ */ jsx(ErrorNote, { error: start.error })
2429
+ /* @__PURE__ */ jsx(GuidedErrorNote, {
2430
+ error: start.error,
2431
+ context,
2432
+ ...isDefiniteRefusal(start.error) && !isStaleStateError(start.error) ? { onRetry: () => void onSubmit() } : {},
2433
+ onFixed: onStewardChanged,
2434
+ canActivateSteward
2435
+ })
1695
2436
  ]
1696
2437
  });
1697
2438
  }
1698
2439
  /** The steward's latest runs, each with a button that opens it below. */
1699
- function RecentRuns({ runs, error, onView }) {
2440
+ function RecentRuns({ runs, error, onView, onRetry }) {
1700
2441
  return /* @__PURE__ */ jsxs(Fragment, { children: [
1701
2442
  /* @__PURE__ */ jsx("h3", {
1702
2443
  style: {
@@ -1706,7 +2447,10 @@ function RecentRuns({ runs, error, onView }) {
1706
2447
  },
1707
2448
  children: "Recent runs"
1708
2449
  }),
1709
- /* @__PURE__ */ jsx(ErrorNote, { error }),
2450
+ /* @__PURE__ */ jsx(GuidedErrorNote, {
2451
+ error,
2452
+ onRetry
2453
+ }),
1710
2454
  runs && runs.length === 0 ? /* @__PURE__ */ jsx(Muted, { children: "No runs yet." }) : null,
1711
2455
  /* @__PURE__ */ jsx("ul", {
1712
2456
  style: listStyle,
@@ -1745,6 +2489,43 @@ const DESKS = [
1745
2489
  "CLOUD",
1746
2490
  "OWN_MACHINE"
1747
2491
  ];
2492
+ /** Agents that can become a steward: drafts are published before the steward runs. */
2493
+ const PICKABLE_AGENT_STATUSES = /* @__PURE__ */ new Set([
2494
+ "ACTIVE",
2495
+ "DRAFT",
2496
+ "PAUSED"
2497
+ ]);
2498
+ /** What the picker says next to an agent's name. */
2499
+ function agentPickerLabel(agent, alreadySteward) {
2500
+ if (alreadySteward) return `${agent.name} (already a steward)`;
2501
+ if (agent.status === "DRAFT") return `${agent.name} (draft, publish before running)`;
2502
+ if (agent.status === "PAUSED") return `${agent.name} (paused, resume before running)`;
2503
+ return agent.name;
2504
+ }
2505
+ /**
2506
+ * The picker's agents, sorted so published agents come first: active, draft
2507
+ * and paused agents only (training, archived and deleted agents cannot become
2508
+ * a steward), each marked when it is already a steward.
2509
+ */
2510
+ function pickableAgents(agents, stewardAgentIds) {
2511
+ const order = (status) => status === "ACTIVE" ? 0 : status === "DRAFT" ? 1 : 2;
2512
+ return agents.filter((a) => PICKABLE_AGENT_STATUSES.has(a.status)).map((agent) => ({
2513
+ agent,
2514
+ alreadySteward: stewardAgentIds.has(agent.id)
2515
+ })).sort((a, b) => Number(a.alreadySteward) - Number(b.alreadySteward) || order(a.agent.status) - order(b.agent.status) || a.agent.name.localeCompare(b.agent.name));
2516
+ }
2517
+ /**
2518
+ * What the desk picker says about desks that use the plan's desk minutes
2519
+ * (browser and cloud), from the plan: `notInPlan` (no assignment), `usedUp`,
2520
+ * `available`, or `unknown` when the viewer may not check the plan.
2521
+ */
2522
+ function cloudDeskAvailability(check) {
2523
+ if (!check) return "unknown";
2524
+ if (check.noLimit) return "available";
2525
+ if (!check.assignmentId) return "notInPlan";
2526
+ if (!check.allowed || check.limitLeft != null && check.limitLeft <= 0) return "usedUp";
2527
+ return "available";
2528
+ }
1748
2529
  /** Parses a non-negative credits value; empty means "no cap". `null` is invalid. */
1749
2530
  function parseCredits(raw) {
1750
2531
  const text = raw.trim();
@@ -1836,7 +2617,12 @@ function CharterFields(p) {
1836
2617
  ] });
1837
2618
  }
1838
2619
  function CreateForm({ agentId, onCreated }) {
1839
- const agents = useStewardsQuery(LIST_AGENT_CANDIDATES, { filters: { status: "ACTIVE" } }, { skip: agentId !== void 0 });
2620
+ const { config } = useStewardsSdk();
2621
+ const agents = useStewardsQuery(LIST_PICKABLE_AGENTS, { pagination: { limit: 100 } }, { skip: agentId !== void 0 });
2622
+ const stewards = useStewardsQuery(LIST_STEWARDS, { pagination: { limit: 100 } }, {
2623
+ skip: agentId !== void 0,
2624
+ silent: true
2625
+ });
1840
2626
  const create = useStewardsMutation(CREATE_STEWARD);
1841
2627
  const [pickedAgent, setPickedAgent] = useState("");
1842
2628
  const [charterText, setCharterText] = useState("");
@@ -1846,8 +2632,21 @@ function CreateForm({ agentId, onCreated }) {
1846
2632
  const [validation, setValidation] = useState();
1847
2633
  const [createdId, setCreatedId] = useState();
1848
2634
  const chosenAgent = agentId ?? pickedAgent;
2635
+ const stewardAgentIds = useMemo(() => new Set((stewards.data?.listBotmanorStewards ?? []).map((st) => st.agentId)), [stewards.data]);
2636
+ const options = useMemo(() => pickableAgents([
2637
+ ...agents.data?.active ?? [],
2638
+ ...agents.data?.draft ?? [],
2639
+ ...agents.data?.paused ?? []
2640
+ ], stewardAgentIds), [agents.data, stewardAgentIds]);
2641
+ const picked = options.find((o) => o.agent.id === chosenAgent)?.agent;
2642
+ const context = useMemo(() => picked ? { agent: {
2643
+ id: picked.id,
2644
+ status: picked.status,
2645
+ ...picked.llmModelId !== void 0 ? { llmModelId: picked.llmModelId } : {}
2646
+ } } : chosenAgent ? { agent: { id: chosenAgent } } : {}, [picked, chosenAgent]);
2647
+ const workspaceId = config.workspaceId;
1849
2648
  const onSubmit = async (e) => {
1850
- e.preventDefault();
2649
+ e?.preventDefault();
1851
2650
  const parsed = parseCredits(credits);
1852
2651
  if (!chosenAgent) return setValidation("Choose an agent.");
1853
2652
  if (charterText.trim() === "") return setValidation("Write the charter first.");
@@ -1870,23 +2669,35 @@ function CreateForm({ agentId, onCreated }) {
1870
2669
  onSubmit: (e) => void onSubmit(e),
1871
2670
  noValidate: true,
1872
2671
  children: [
1873
- agentId ? null : /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Field, {
1874
- label: "Agent",
1875
- htmlFor: "steward-agent",
1876
- children: /* @__PURE__ */ jsxs("select", {
1877
- id: "steward-agent",
1878
- value: pickedAgent,
1879
- onChange: (e) => setPickedAgent(e.target.value),
1880
- style: fieldStyle,
1881
- children: [/* @__PURE__ */ jsx("option", {
1882
- value: "",
1883
- children: "Choose an agent…"
1884
- }), (agents.data?.listBotmanorAgents ?? []).map((a) => /* @__PURE__ */ jsx("option", {
1885
- value: a.id,
1886
- children: a.name
1887
- }, a.id))]
2672
+ agentId ? null : /* @__PURE__ */ jsxs(Fragment, { children: [
2673
+ /* @__PURE__ */ jsx(Field, {
2674
+ label: "Agent",
2675
+ htmlFor: "steward-agent",
2676
+ children: /* @__PURE__ */ jsxs("select", {
2677
+ id: "steward-agent",
2678
+ value: pickedAgent,
2679
+ onChange: (e) => setPickedAgent(e.target.value),
2680
+ style: fieldStyle,
2681
+ children: [/* @__PURE__ */ jsx("option", {
2682
+ value: "",
2683
+ children: "Choose an agent…"
2684
+ }), options.map(({ agent, alreadySteward }) => /* @__PURE__ */ jsx("option", {
2685
+ value: agent.id,
2686
+ disabled: alreadySteward,
2687
+ children: agentPickerLabel(agent, alreadySteward)
2688
+ }, agent.id))]
2689
+ })
2690
+ }),
2691
+ agents.data && options.length === 0 ? /* @__PURE__ */ jsx(Muted, { children: "No agent can become a steward yet. Create an agent first, then come back." }) : null,
2692
+ picked ? /* @__PURE__ */ jsx(AgentStateNotice, {
2693
+ agent: picked,
2694
+ onChanged: agents.refetch
2695
+ }) : null,
2696
+ /* @__PURE__ */ jsx(GuidedErrorNote, {
2697
+ error: agents.error,
2698
+ onRetry: agents.refetch
1888
2699
  })
1889
- }), /* @__PURE__ */ jsx(ErrorNote, { error: agents.error })] }),
2700
+ ] }),
1890
2701
  /* @__PURE__ */ jsx(CharterFields, {
1891
2702
  idPrefix: "create",
1892
2703
  charterText,
@@ -1910,8 +2721,18 @@ function CreateForm({ agentId, onCreated }) {
1910
2721
  }, d))
1911
2722
  })
1912
2723
  }),
2724
+ desk === "CLOUD" || desk === "BROWSER" ? /* @__PURE__ */ jsx(DeskMinutesHint, {
2725
+ workspaceId,
2726
+ desk,
2727
+ onChooseDesk: setDesk
2728
+ }) : null,
1913
2729
  validation ? /* @__PURE__ */ jsx(ErrorNote, { error: new Error(validation) }) : null,
1914
- /* @__PURE__ */ jsx(ErrorNote, { error: create.error }),
2730
+ /* @__PURE__ */ jsx(GuidedErrorNote, {
2731
+ error: create.error,
2732
+ context,
2733
+ onRetry: () => void onSubmit(),
2734
+ onFixed: agents.refetch
2735
+ }),
1915
2736
  /* @__PURE__ */ jsx("p", {
1916
2737
  style: { margin: "16px 0 0" },
1917
2738
  children: /* @__PURE__ */ jsx(Button, {
@@ -1928,7 +2749,11 @@ function EditForm({ stewardId, onSaved }) {
1928
2749
  const steward = useStewardsQuery(GET_STEWARD, { id: stewardId });
1929
2750
  const detail = steward.data?.getBotmanorSteward;
1930
2751
  if (steward.loading && !detail) return /* @__PURE__ */ jsx(Muted, { children: "Loading the charter…" });
1931
- if (!detail?.charter) return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(ErrorNote, { error: steward.error }), steward.error ? null : /* @__PURE__ */ jsx(Muted, { children: "This steward was not found." })] });
2752
+ if (!detail?.charter) return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(GuidedErrorNote, {
2753
+ error: steward.error,
2754
+ context: { stewardId },
2755
+ onRetry: steward.refetch
2756
+ }), steward.error ? null : /* @__PURE__ */ jsx(Muted, { children: "This steward was not found." })] });
1932
2757
  return /* @__PURE__ */ jsx(EditCharter, {
1933
2758
  detail,
1934
2759
  onSaved,
@@ -1950,9 +2775,10 @@ function EditCharter({ detail, onSaved, onReload, reloading, reloadError }) {
1950
2775
  const [validation, setValidation] = useState();
1951
2776
  const [saved, setSaved] = useState(false);
1952
2777
  const [conflict, setConflict] = useState(false);
1953
- if (update.error instanceof StewardsRequestError && update.error.code === "CONFLICT" && !conflict) setConflict(true);
2778
+ const refusedAsStale = update.error instanceof StewardsRequestError && update.error.code === "CONFLICT";
2779
+ if (refusedAsStale && !conflict) setConflict(true);
1954
2780
  const onSubmit = async (e) => {
1955
- e.preventDefault();
2781
+ e?.preventDefault();
1956
2782
  const parsed = parseCredits(credits);
1957
2783
  if (charterText.trim() === "") return setValidation("The charter cannot be empty.");
1958
2784
  if (parsed === null) return setValidation("The daily budget must be a number, 0 or more.");
@@ -2009,12 +2835,20 @@ function EditCharter({ detail, onSaved, onReload, reloading, reloadError }) {
2009
2835
  }
2010
2836
  }),
2011
2837
  validation ? /* @__PURE__ */ jsx(ErrorNote, { error: new Error(validation) }) : null,
2012
- /* @__PURE__ */ jsx(ErrorNote, { error: update.error }),
2838
+ /* @__PURE__ */ jsx(GuidedErrorNote, {
2839
+ error: refusedAsStale ? void 0 : update.error,
2840
+ context: {
2841
+ stewardId: detail.id,
2842
+ stewardStatus: detail.status,
2843
+ ownerActorId: detail.ownerActorId
2844
+ },
2845
+ ...isDefiniteRefusal(update.error) ? { onRetry: () => void onSubmit() } : {}
2846
+ }),
2013
2847
  conflict ? /* @__PURE__ */ jsxs("div", {
2014
2848
  style: { margin: "8px 0 0" },
2015
2849
  children: [
2016
2850
  /* @__PURE__ */ jsx(Muted, { children: "This charter was changed elsewhere. Reload it to edit the latest version; your unsaved changes here are discarded." }),
2017
- /* @__PURE__ */ jsx(ErrorNote, { error: reloadError }),
2851
+ /* @__PURE__ */ jsx(GuidedErrorNote, { error: reloadError }),
2018
2852
  /* @__PURE__ */ jsx(Button, {
2019
2853
  type: "button",
2020
2854
  onClick: onReload,
@@ -2036,6 +2870,59 @@ function EditCharter({ detail, onSaved, onReload, reloading, reloadError }) {
2036
2870
  })
2037
2871
  });
2038
2872
  }
2873
+ /**
2874
+ * What a draft or paused agent needs before its steward can run (catalog A1
2875
+ * prevention): publish it here when the viewer may, choose a model first when
2876
+ * it has none, or open the agent (or ask its owner) otherwise.
2877
+ */
2878
+ function AgentStateNotice({ agent, onChanged }) {
2879
+ const guided = useMemo(() => agent.status === "ACTIVE" ? void 0 : describeGuidedError({
2880
+ code: "BAD_USER_INPUT",
2881
+ extensions: {
2882
+ reason: "AGENT_NOT_ACTIVE",
2883
+ agentId: agent.id
2884
+ }
2885
+ }, { agent: {
2886
+ id: agent.id,
2887
+ status: agent.status,
2888
+ ...agent.llmModelId !== void 0 ? { llmModelId: agent.llmModelId } : {}
2889
+ } }), [agent]);
2890
+ if (!guided) return null;
2891
+ const state = (AGENT_STATUS_SHORT_LABELS[agent.status] ?? humanize(agent.status)).toLowerCase();
2892
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Muted, { children: `This agent is ${state === "draft" ? "still a draft" : state}. You can create the steward now; it runs once the agent is published.` }), /* @__PURE__ */ jsx(GuidedErrorNote, {
2893
+ guided,
2894
+ tone: "info",
2895
+ onRetry: onChanged
2896
+ })] });
2897
+ }
2898
+ /**
2899
+ * Browser and cloud desks run on BotManor's machines and spend the plan's desk
2900
+ * minutes (a steward on either needs at least one minute left to start). On a
2901
+ * plan without them, or with none left, the hint says so and offers the desks
2902
+ * that use none: the person's own machine, or no desk.
2903
+ */
2904
+ function DeskMinutesHint({ workspaceId, desk, onChooseDesk }) {
2905
+ const availability = cloudDeskAvailability(useStewardsQuery(CHECK_DESK_MINUTES, { workspaceId }, { silent: true }).data?.checkWorkspaceQuota);
2906
+ const kind = desk === "CLOUD" ? "cloud" : "browser";
2907
+ const message = availability === "notInPlan" ? `Desk minutes aren't part of this workspace's plan, so a steward on a ${kind} desk can't run. Choose your own machine instead, or no desk.` : availability === "usedUp" ? `This workspace's plan has no desk minutes left this month, so a steward on a ${kind} desk can't run now. Choose your own machine instead, or no desk.` : `A ${kind} desk uses the plan's desk minutes. If the plan has none, choose your own machine instead.`;
2908
+ return /* @__PURE__ */ jsxs("div", {
2909
+ role: "status",
2910
+ children: [/* @__PURE__ */ jsx(Muted, { children: message }), availability === "notInPlan" || availability === "usedUp" ? /* @__PURE__ */ jsxs("p", {
2911
+ style: {
2912
+ display: "flex",
2913
+ gap: "8px",
2914
+ margin: "8px 0 0"
2915
+ },
2916
+ children: [/* @__PURE__ */ jsx(Button, {
2917
+ onClick: () => onChooseDesk("OWN_MACHINE"),
2918
+ children: "Use my own machine"
2919
+ }), /* @__PURE__ */ jsx(Button, {
2920
+ onClick: () => onChooseDesk("NONE"),
2921
+ children: "No desk"
2922
+ })]
2923
+ }) : null]
2924
+ });
2925
+ }
2039
2926
 
2040
2927
  // src/components/ApprovalInbox.tsx
2041
2928
  const SCOPES = [
@@ -2101,7 +2988,14 @@ function ApprovalInbox({ stewardId, pollIntervalMs = 15e3 }) {
2101
2988
  children: "Approvals"
2102
2989
  }),
2103
2990
  loading && !approvals ? /* @__PURE__ */ jsx(Muted, { children: "Loading approvals…" }) : null,
2104
- /* @__PURE__ */ jsx(ErrorNote, { error: error ?? decide.error }),
2991
+ /* @__PURE__ */ jsx(GuidedErrorNote, {
2992
+ error,
2993
+ onRetry: refetch
2994
+ }),
2995
+ /* @__PURE__ */ jsx(GuidedErrorNote, {
2996
+ error: error ? void 0 : decide.error,
2997
+ ...isStaleStateError(decide.error) ? { onRetry: refetch } : {}
2998
+ }),
2105
2999
  approvals && approvals.length === 0 ? /* @__PURE__ */ jsx(Muted, { children: "Nothing is waiting for your approval." }) : null,
2106
3000
  approvals && approvals.length > 0 ? /* @__PURE__ */ jsx("ul", {
2107
3001
  style: listStyle,
@@ -2167,4 +3061,4 @@ function ApprovalInbox({ stewardId, pollIntervalMs = 15e3 }) {
2167
3061
  });
2168
3062
  }
2169
3063
 
2170
- export { ApprovalInbox, DEFAULT_STEWARDS_THEME, DEFAULT_VIBECONTROLS_URL, OWN_MACHINE_GRANT_DAYS, OWN_MACHINE_MAX_PAGES, OWN_MACHINE_PAGE_SIZE, StewardBuilder, StewardConsole, StewardOwnMachineDesk, StewardOwnMachineDeskPanel, StewardRunView, StewardsRequestError, StewardsSdkProvider, createStewardsEventBus, nextOwnMachineGrantExpiry, ownMachineAbilities, ownMachineAllowedApps, ownMachineAppCount, ownMachineGrantExpiry, ownMachineRows, themeToStyle, useStewardsEvent, useStewardsSdk };
3064
+ export { AGENT_STATUS_LABELS, AGENT_STATUS_SHORT_LABELS, ApprovalInbox, DEFAULT_BOTMANOR_APP_URL, DEFAULT_STEWARDS_THEME, DEFAULT_VIBECONTROLS_URL, GUIDED_ENTRIES, GUIDED_PERMISSIONS, GuidedErrorNote, OWN_MACHINE_GRANT_DAYS, OWN_MACHINE_MAX_PAGES, OWN_MACHINE_PAGE_SIZE, PERMISSION_LABELS, STOP_REASON_LABELS, StewardBuilder, StewardConsole, StewardOwnMachineDesk, StewardOwnMachineDeskPanel, StewardRunView, StewardsRequestError, StewardsSdkProvider, agentPickerLabel, botmanorPath, buildGuidedError, cloudDeskAvailability, createStewardsEventBus, crossShellUrl, describeGuidedError, describeRunFailure, englishGuidedTranslate, extractGuidedSource, fillGuidedParams, guidedI18nBase, guidedParams, guidedText, guidedTranslateFrom, isDefiniteRefusal, isStaleStateError, nextOwnMachineGrantExpiry, ownMachineAbilities, ownMachineAllowedApps, ownMachineAppCount, ownMachineCanRevoke, ownMachineGrantExpiry, ownMachineRows, permissionLabelKey, pickableAgents, planGuidedActions, reasonCamel, resolveGuidedLocation, stepReasonCode, stopReasonLabel, themeToStyle, useStewardsEvent, useStewardsSdk };