@botmanor/fe-sdk 0.0.0-stage → 2026.1203.2

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 ADDED
@@ -0,0 +1,1352 @@
1
+ "use client";
2
+ import { createContext, use, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
3
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4
+
5
+ // src/graphql/client.ts
6
+ /** Failure from the gateway: a transport status or a GraphQL error code. */
7
+ var StewardsRequestError = class extends Error {
8
+ code;
9
+ status;
10
+ constructor(message, code, status) {
11
+ super(message);
12
+ this.name = "StewardsRequestError";
13
+ this.code = code;
14
+ this.status = status;
15
+ }
16
+ };
17
+ const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
18
+ "localhost",
19
+ "127.0.0.1",
20
+ "[::1]"
21
+ ]);
22
+ /**
23
+ * The gateway URL is part of the host's config, but the SDK still refuses
24
+ * shapes that would put a secret in a URL or send a token over cleartext.
25
+ */
26
+ function assertSafeGatewayUrl(raw) {
27
+ let url;
28
+ try {
29
+ url = new URL(raw);
30
+ } catch {
31
+ throw new StewardsRequestError("gatewayUrl is not a valid URL", "INVALID_CONFIG");
32
+ }
33
+ if (url.username || url.password || url.search || url.hash) throw new StewardsRequestError("gatewayUrl must not carry credentials, a query string or a fragment", "INVALID_CONFIG");
34
+ if (!(url.protocol === "https:" || url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname))) throw new StewardsRequestError("gatewayUrl must use https (http is allowed only for loopback)", "INVALID_CONFIG");
35
+ return url;
36
+ }
37
+ /**
38
+ * GraphQL transport over the public workspace gateway. The access token goes
39
+ * in the `Authorization` header only (never in the URL or body), cookies are
40
+ * not sent (`credentials: "omit"`), and no referrer leaks the embedding page.
41
+ */
42
+ function createStewardsClient(options) {
43
+ return { async request(document, variables = {}, signal) {
44
+ const config = options.getConfig();
45
+ const url = assertSafeGatewayUrl(config.gatewayUrl);
46
+ const token = await options.resolveToken();
47
+ const doFetch = options.fetchImpl ?? fetch;
48
+ let response;
49
+ try {
50
+ response = await doFetch(url.toString(), {
51
+ method: "POST",
52
+ headers: {
53
+ "content-type": "application/json",
54
+ accept: "application/json",
55
+ authorization: `Bearer ${token}`,
56
+ "x-workspace-id": config.workspaceId
57
+ },
58
+ body: JSON.stringify({
59
+ query: document,
60
+ variables
61
+ }),
62
+ credentials: "omit",
63
+ referrerPolicy: "no-referrer",
64
+ signal
65
+ });
66
+ } catch (err) {
67
+ if (signal?.aborted) throw err;
68
+ throw new StewardsRequestError("The Stewards service could not be reached", "NETWORK");
69
+ }
70
+ if (response.status === 401) {
71
+ options.reportAuthExpired("gateway answered 401");
72
+ throw new StewardsRequestError("Your session has expired", "UNAUTHENTICATED", 401);
73
+ }
74
+ let body;
75
+ try {
76
+ body = await response.json();
77
+ } catch {
78
+ throw new StewardsRequestError(`Unexpected response from the Stewards service (${response.status})`, "BAD_RESPONSE", response.status);
79
+ }
80
+ const first = body.errors?.[0];
81
+ if (first) {
82
+ const code = typeof first.extensions?.code === "string" ? first.extensions.code : "GRAPHQL_ERROR";
83
+ if (code === "UNAUTHENTICATED") options.reportAuthExpired("gateway rejected the token");
84
+ throw new StewardsRequestError(first.message ?? "Request failed", code, response.status);
85
+ }
86
+ if (!response.ok || body.data == null) throw new StewardsRequestError(`Unexpected response from the Stewards service (${response.status})`, "BAD_RESPONSE", response.status);
87
+ return body.data;
88
+ } };
89
+ }
90
+
91
+ // src/events/eventBus.ts
92
+ /**
93
+ * A new, independent bus. The SDK never keeps one at module level: each
94
+ * provider instance owns its own, so two embeds on one page never cross-talk
95
+ * (the FluidGrids SDK singleton lesson, plan §5.8).
96
+ */
97
+ function createStewardsEventBus() {
98
+ const handlers = /* @__PURE__ */ new Map();
99
+ const anyHandlers = /* @__PURE__ */ new Set();
100
+ return {
101
+ emit(type, payload) {
102
+ for (const handler of handlers.get(type) ?? []) handler(payload);
103
+ const event = {
104
+ type,
105
+ payload
106
+ };
107
+ for (const handler of anyHandlers) handler(event);
108
+ },
109
+ on(type, handler) {
110
+ let set = handlers.get(type);
111
+ if (!set) {
112
+ set = /* @__PURE__ */ new Set();
113
+ handlers.set(type, set);
114
+ }
115
+ const stored = handler;
116
+ set.add(stored);
117
+ return () => {
118
+ set.delete(stored);
119
+ };
120
+ },
121
+ onAny(handler) {
122
+ anyHandlers.add(handler);
123
+ return () => {
124
+ anyHandlers.delete(handler);
125
+ };
126
+ }
127
+ };
128
+ }
129
+
130
+ // src/provider/StewardsSdkProvider.tsx
131
+ const StewardsSdkContext = createContext(null);
132
+ /**
133
+ * Root of every embedded Stewards surface. Each instance owns its own event
134
+ * bus and config: the SDK holds no module-level state, so several providers
135
+ * (two workspaces, or two embeds) can share a page.
136
+ */
137
+ function StewardsSdkProvider({ children, ...config }) {
138
+ const [events] = useState(createStewardsEventBus);
139
+ const { onEvent } = config;
140
+ const configRef = useRef(config);
141
+ useLayoutEffect(() => {
142
+ configRef.current = config;
143
+ });
144
+ useEffect(() => {
145
+ if (!onEvent) return void 0;
146
+ return events.onAny(onEvent);
147
+ }, [events, onEvent]);
148
+ const [services] = useState(() => {
149
+ const reportAuthExpired = (reason) => {
150
+ configRef.current.onTokenExpired?.(reason);
151
+ events.emit("auth.expired", { reason });
152
+ };
153
+ const resolveToken = async () => {
154
+ try {
155
+ const token = await configRef.current.getAccessToken();
156
+ if (!token) throw new Error("empty access token");
157
+ return token;
158
+ } catch (err) {
159
+ reportAuthExpired(err instanceof Error ? err.message : String(err));
160
+ throw err;
161
+ }
162
+ };
163
+ return {
164
+ reportAuthExpired,
165
+ resolveToken,
166
+ client: createStewardsClient({
167
+ getConfig: () => configRef.current,
168
+ resolveToken,
169
+ reportAuthExpired
170
+ })
171
+ };
172
+ });
173
+ const { gatewayUrl, workspaceId, getAccessToken, onTokenExpired, theme } = config;
174
+ const value = useMemo(() => ({
175
+ config: {
176
+ gatewayUrl,
177
+ workspaceId,
178
+ getAccessToken,
179
+ ...onTokenExpired ? { onTokenExpired } : {},
180
+ ...onEvent ? { onEvent } : {},
181
+ ...theme ? { theme } : {}
182
+ },
183
+ events,
184
+ ...services
185
+ }), [
186
+ gatewayUrl,
187
+ workspaceId,
188
+ getAccessToken,
189
+ onTokenExpired,
190
+ onEvent,
191
+ theme,
192
+ events,
193
+ services
194
+ ]);
195
+ return /* @__PURE__ */ jsx(StewardsSdkContext, {
196
+ value,
197
+ children
198
+ });
199
+ }
200
+ function useStewardsSdk() {
201
+ const value = use(StewardsSdkContext);
202
+ if (!value) throw new Error("Stewards SDK components must be rendered inside <StewardsSdkProvider>");
203
+ return value;
204
+ }
205
+
206
+ // src/events/useStewardsEvent.ts
207
+ /** Subscribe to one SDK event for the lifetime of the calling component. */
208
+ function useStewardsEvent(type, handler) {
209
+ const { events } = useStewardsSdk();
210
+ const latest = useRef(handler);
211
+ useEffect(() => {
212
+ latest.current = handler;
213
+ });
214
+ useEffect(() => {
215
+ const unsubscribe = events.on(type, (payload) => latest.current(payload));
216
+ return () => unsubscribe();
217
+ }, [events, type]);
218
+ }
219
+
220
+ // src/theme/theme.ts
221
+ /**
222
+ * Defaults reference the fe-libs semantic tokens, so inside a Burdenoff shell
223
+ * the SDK matches the app's light/dark theme with no configuration. A
224
+ * third-party page that does not load the fe-libs token stylesheet passes its
225
+ * own `theme`.
226
+ */
227
+ const DEFAULT_STEWARDS_THEME = {
228
+ surface: "var(--color-bg-surface)",
229
+ surfaceMuted: "var(--color-bg-sunken)",
230
+ text: "var(--color-text-primary)",
231
+ textMuted: "var(--color-text-secondary)",
232
+ border: "var(--color-border-subtle)",
233
+ accent: "var(--color-action-primary-bg)",
234
+ accentText: "var(--color-action-primary-text)",
235
+ danger: "var(--color-action-danger-text)",
236
+ radius: "8px",
237
+ fontFamily: "inherit"
238
+ };
239
+ const CSS_VAR_PREFIX = "--bm-sdk-";
240
+ function kebab(key) {
241
+ return key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
242
+ }
243
+ /** The wrapper's inline style: one custom property per theme key. */
244
+ function themeToStyle(theme = {}) {
245
+ const merged = {
246
+ ...DEFAULT_STEWARDS_THEME,
247
+ ...theme
248
+ };
249
+ const style = {};
250
+ for (const [key, value] of Object.entries(merged)) style[`${CSS_VAR_PREFIX}${kebab(key)}`] = value;
251
+ return style;
252
+ }
253
+ /** `var(--bm-sdk-<key>)`, for component styles. */
254
+ function themeVar(key) {
255
+ return `var(${CSS_VAR_PREFIX}${kebab(key)})`;
256
+ }
257
+
258
+ // src/graphql/documents.ts
259
+ /**
260
+ * GraphQL documents the SDK sends. They match the operations in
261
+ * `@burdenoff/microfe-stewards` (src/operations/wspace/stewards) field for
262
+ * field, trimmed to what the embeddable surfaces render. Every field is part
263
+ * of the `Botmanor*` schema in the Hive supergraph.
264
+ */
265
+ const BUDGET = `credits deskMinutes steps wallSeconds connectorSpendMinor`;
266
+ const RUN_SUMMARY = `
267
+ id stewardId trigger status trustLevel initialTrustLevel dryRun stepCount
268
+ stopReason startedAt finishedAt createdAt
269
+ budgetUsed { ${BUDGET} }`;
270
+ const STEWARD_DETAIL = `
271
+ id agentId ownerActorId status defaultDeskKind pendingApprovalCount
272
+ createdAt updatedAt
273
+ agent { id name capabilities }
274
+ charter {
275
+ autonomyLevel charterText charterVersion allowedToolKeys
276
+ allowedConnectionIds timezone dryRunDefault
277
+ budgetPerRun { ${BUDGET} }
278
+ budgetPerDay { ${BUDGET} }
279
+ budgetTotal { ${BUDGET} }
280
+ }
281
+ usageToday { ${BUDGET} }
282
+ lastRun { id status startedAt }`;
283
+ const LIST_STEWARDS = `query ListBotmanorStewards($filter: BotmanorStewardFilterInput, $pagination: PaginationInput) {
284
+ listBotmanorStewards(filter: $filter, pagination: $pagination) {
285
+ id agentId status defaultDeskKind pendingApprovalCount
286
+ agent { id name }
287
+ charter { autonomyLevel budgetPerDay { credits } }
288
+ usageToday { credits }
289
+ lastRun { id status startedAt }
290
+ }
291
+ }`;
292
+ const GET_STEWARD = `query GetBotmanorSteward($id: ID!) {
293
+ getBotmanorSteward(id: $id) { ${STEWARD_DETAIL} }
294
+ }`;
295
+ const LIST_STEWARD_RUNS = `query ListBotmanorStewardRuns($filter: BotmanorStewardRunFilterInput, $pagination: PaginationInput) {
296
+ listBotmanorStewardRuns(filter: $filter, pagination: $pagination) { ${RUN_SUMMARY} }
297
+ }`;
298
+ const GET_STEWARD_RUN = `query GetBotmanorStewardRun($id: ID!) {
299
+ getBotmanorStewardRun(id: $id) {
300
+ ${RUN_SUMMARY}
301
+ steps {
302
+ id seq kind toolKey targetSummary resultSummary classification verdict
303
+ verdictReasons approvalRequestId creditsUsed startedAt finishedAt
304
+ }
305
+ approvals {
306
+ id toolName riskLevel status requestedScope grantedScope expiresAt
307
+ decidedAt createdAt
308
+ }
309
+ }
310
+ }`;
311
+ const RUN_STEWARD = `mutation RunBotmanorSteward($input: RunBotmanorStewardInput!) {
312
+ runBotmanorSteward(input: $input) { ${RUN_SUMMARY} }
313
+ }`;
314
+ const CANCEL_STEWARD_RUN = `mutation CancelBotmanorStewardRun($id: ID!) {
315
+ cancelBotmanorStewardRun(id: $id) { ${RUN_SUMMARY} }
316
+ }`;
317
+ const CREATE_STEWARD = `mutation CreateBotmanorSteward($input: CreateBotmanorStewardInput!) {
318
+ createBotmanorSteward(input: $input) { ${STEWARD_DETAIL} }
319
+ }`;
320
+ const UPDATE_STEWARD_CHARTER = `mutation UpdateBotmanorStewardCharter($id: ID!, $input: UpdateBotmanorStewardCharterInput!) {
321
+ updateBotmanorStewardCharter(id: $id, input: $input) { ${STEWARD_DETAIL} }
322
+ }`;
323
+ const LIST_AGENT_CANDIDATES = `query ListStewardAgentCandidates($filters: BotmanorAgentFilterInput) {
324
+ listBotmanorAgents(filters: $filters) { id name description status capabilities }
325
+ }`;
326
+ const LIST_STEWARD_APPROVALS = `query ListBotmanorToolApprovals($filter: BotmanorToolApprovalFilterInput, $pagination: PaginationInput) {
327
+ listBotmanorToolApprovals(filter: $filter, pagination: $pagination) {
328
+ id agentName stewardId stewardRunId toolName riskLevel destination purpose
329
+ reasons fixedDefault requestedScope status expiresAt createdAt
330
+ }
331
+ }`;
332
+ const DECIDE_APPROVAL = `mutation DecideBotmanorToolApproval($id: ID!, $decision: BotmanorToolApprovalDecision!, $scope: BotmanorApprovalScope, $note: String) {
333
+ decideBotmanorToolApproval(id: $id, decision: $decision, scope: $scope, note: $note) {
334
+ id status grantedScope decidedAt
335
+ }
336
+ }`;
337
+
338
+ // src/graphql/hooks.ts
339
+ function asError(err) {
340
+ return err instanceof Error ? err : new Error(String(err));
341
+ }
342
+ /**
343
+ * Minimal query hook over the provider's client: loads on mount and whenever
344
+ * the document, the variables, the workspace or the gateway change,
345
+ * optionally polls, and drops stale results. The SDK stays free of an
346
+ * Apollo / React Query peer dependency on purpose.
347
+ *
348
+ * Loading and polling are two effects on purpose. The load effect owns one
349
+ * request: its cleanup aborts it and flips `active`, so a slow response for
350
+ * an old request can never overwrite newer state. The poll effect owns one
351
+ * timer: it runs after each successful result, asks `pollMs` for the next
352
+ * delay and clears the timer in its cleanup. A failed poll keeps the last
353
+ * good data and stops polling until the caller refetches.
354
+ *
355
+ * Every settled result is tagged with the request it answers, and what the
356
+ * hook returns is derived from that tag during render. So a new workspace,
357
+ * gateway, document or variables never shows the previous request's data,
358
+ * and `loading` is true from the first render of a new request or a refetch
359
+ * until it settles. A refetch of the same request keeps its data on screen
360
+ * while it loads.
361
+ */
362
+ function useStewardsQuery(document, variables, options = {}) {
363
+ const { client, config: { workspaceId, gatewayUrl } } = useStewardsSdk();
364
+ const [result, setResult] = useState(void 0);
365
+ const [nonce, setNonce] = useState(0);
366
+ const refetch = useCallback(() => setNonce((n) => n + 1), []);
367
+ const pollRef = useRef(options.pollMs);
368
+ useEffect(() => {
369
+ pollRef.current = options.pollMs;
370
+ });
371
+ const variablesKey = JSON.stringify(variables);
372
+ const requestKey = JSON.stringify([
373
+ gatewayUrl,
374
+ workspaceId,
375
+ document,
376
+ variablesKey
377
+ ]);
378
+ const skip = options.skip === true;
379
+ useEffect(() => {
380
+ if (skip) return void 0;
381
+ let active = true;
382
+ const controller = new AbortController();
383
+ const vars = JSON.parse(variablesKey);
384
+ client.request(document, vars, controller.signal).then((data) => {
385
+ if (!active) return;
386
+ setResult({
387
+ key: requestKey,
388
+ nonce,
389
+ data,
390
+ error: void 0
391
+ });
392
+ }, (err) => {
393
+ if (!active) return;
394
+ setResult((prev) => ({
395
+ key: requestKey,
396
+ nonce,
397
+ data: prev?.key === requestKey ? prev.data : void 0,
398
+ error: asError(err)
399
+ }));
400
+ });
401
+ return () => {
402
+ active = false;
403
+ controller.abort();
404
+ };
405
+ }, [
406
+ client,
407
+ document,
408
+ variablesKey,
409
+ requestKey,
410
+ skip,
411
+ nonce
412
+ ]);
413
+ const current = result?.key === requestKey ? result : void 0;
414
+ const data = current?.data;
415
+ const error = current?.error;
416
+ const loading = !skip && (current === void 0 || current.nonce !== nonce);
417
+ useEffect(() => {
418
+ if (skip || data === void 0 || error !== void 0) return void 0;
419
+ const next = pollRef.current?.(data);
420
+ if (typeof next !== "number") return void 0;
421
+ const timer = setTimeout(refetch, next);
422
+ return () => clearTimeout(timer);
423
+ }, [
424
+ data,
425
+ error,
426
+ skip,
427
+ refetch
428
+ ]);
429
+ return {
430
+ data,
431
+ error,
432
+ loading,
433
+ refetch
434
+ };
435
+ }
436
+ /** One-shot mutation. Resolves to `undefined` on failure; the error is in state. */
437
+ function useStewardsMutation(document) {
438
+ const { client } = useStewardsSdk();
439
+ const [loading, setLoading] = useState(false);
440
+ const [error, setError] = useState(void 0);
441
+ return {
442
+ mutate: useCallback(async (variables) => {
443
+ setLoading(true);
444
+ setError(void 0);
445
+ try {
446
+ return await client.request(document, variables);
447
+ } catch (err) {
448
+ setError(asError(err));
449
+ return;
450
+ } finally {
451
+ setLoading(false);
452
+ }
453
+ }, [client, document]),
454
+ loading,
455
+ error
456
+ };
457
+ }
458
+
459
+ // src/theme/ScopedTheme.tsx
460
+ /** The SDK's only styling root: theme variables live on this element alone. */
461
+ function ScopedTheme({ theme, label, component, children }) {
462
+ return /* @__PURE__ */ jsx("section", {
463
+ "aria-label": label,
464
+ "data-botmanor-sdk": component,
465
+ style: {
466
+ ...themeToStyle(theme),
467
+ background: themeVar("surface"),
468
+ color: themeVar("text"),
469
+ border: `1px solid ${themeVar("border")}`,
470
+ borderRadius: themeVar("radius"),
471
+ fontFamily: themeVar("fontFamily"),
472
+ padding: "16px"
473
+ },
474
+ children
475
+ });
476
+ }
477
+
478
+ // src/components/ui.tsx
479
+ /** Shared, token-only building blocks for the four SDK surfaces. */
480
+ const headingStyle = {
481
+ margin: 0,
482
+ fontSize: "16px",
483
+ fontWeight: 600
484
+ };
485
+ const mutedStyle = {
486
+ margin: "8px 0 0",
487
+ color: themeVar("textMuted"),
488
+ fontSize: "14px"
489
+ };
490
+ function Muted({ children }) {
491
+ return /* @__PURE__ */ jsx("p", {
492
+ style: mutedStyle,
493
+ children
494
+ });
495
+ }
496
+ function ErrorNote({ error }) {
497
+ if (!error) return null;
498
+ return /* @__PURE__ */ jsx("p", {
499
+ role: "alert",
500
+ style: {
501
+ ...mutedStyle,
502
+ color: themeVar("danger"),
503
+ fontWeight: 500
504
+ },
505
+ children: error.message
506
+ });
507
+ }
508
+ function Badge({ children }) {
509
+ return /* @__PURE__ */ jsx("span", {
510
+ style: {
511
+ background: themeVar("surfaceMuted"),
512
+ border: `1px solid ${themeVar("border")}`,
513
+ borderRadius: themeVar("radius"),
514
+ fontSize: "12px",
515
+ padding: "1px 8px",
516
+ whiteSpace: "nowrap"
517
+ },
518
+ children
519
+ });
520
+ }
521
+ function Button({ children, onClick, type = "button", disabled, kind = "secondary", label }) {
522
+ const primary = kind === "primary";
523
+ return /* @__PURE__ */ jsx("button", {
524
+ type,
525
+ onClick,
526
+ disabled,
527
+ "aria-label": label,
528
+ style: {
529
+ background: primary ? themeVar("accent") : "transparent",
530
+ color: primary ? themeVar("accentText") : kind === "danger" ? themeVar("danger") : themeVar("text"),
531
+ border: `1px solid ${primary ? themeVar("accent") : themeVar("border")}`,
532
+ borderRadius: themeVar("radius"),
533
+ cursor: disabled ? "not-allowed" : "pointer",
534
+ font: "inherit",
535
+ fontSize: "13px",
536
+ opacity: disabled ? .6 : 1,
537
+ padding: "4px 12px"
538
+ },
539
+ children
540
+ });
541
+ }
542
+ const fieldStyle = {
543
+ background: themeVar("surface"),
544
+ border: `1px solid ${themeVar("border")}`,
545
+ borderRadius: themeVar("radius"),
546
+ boxSizing: "border-box",
547
+ color: themeVar("text"),
548
+ font: "inherit",
549
+ fontSize: "14px",
550
+ padding: "6px 8px",
551
+ width: "100%"
552
+ };
553
+ function Field({ label, htmlFor, children }) {
554
+ return /* @__PURE__ */ jsxs("div", {
555
+ style: {
556
+ display: "grid",
557
+ gap: "4px",
558
+ marginTop: "12px"
559
+ },
560
+ children: [/* @__PURE__ */ jsx("label", {
561
+ htmlFor,
562
+ style: {
563
+ fontSize: "13px",
564
+ fontWeight: 500
565
+ },
566
+ children: label
567
+ }), children]
568
+ });
569
+ }
570
+ const listStyle = {
571
+ listStyle: "none",
572
+ margin: "12px 0 0",
573
+ padding: 0,
574
+ display: "grid",
575
+ gap: "8px"
576
+ };
577
+ const rowStyle = {
578
+ border: `1px solid ${themeVar("border")}`,
579
+ borderRadius: themeVar("radius"),
580
+ padding: "8px 12px"
581
+ };
582
+ function formatDate(iso) {
583
+ if (!iso) return "—";
584
+ const d = new Date(iso);
585
+ return Number.isNaN(d.getTime()) ? "—" : d.toISOString().slice(0, 16).replace("T", " ") + " UTC";
586
+ }
587
+ const TERMINAL = /* @__PURE__ */ new Set([
588
+ "CANCELLED",
589
+ "COMPLETED",
590
+ "FAILED",
591
+ "STOPPED"
592
+ ]);
593
+ /** Statuses after which a run cannot change any more. */
594
+ function isTerminalRunStatus(status) {
595
+ return TERMINAL.has(status);
596
+ }
597
+ function humanize(value) {
598
+ const s = value.toLowerCase().replace(/_/g, " ");
599
+ return s.charAt(0).toUpperCase() + s.slice(1);
600
+ }
601
+
602
+ // src/components/StewardRunView.tsx
603
+ const WAITING_REASON = {
604
+ WAITING_APPROVAL: "APPROVAL",
605
+ WAITING_TAKEOVER: "TAKEOVER",
606
+ PAUSED_BUDGET: "BUDGET"
607
+ };
608
+ /**
609
+ * Emits `run.completed`, `run.failed` and `run.waiting` when a run's status
610
+ * changes. The first sighting of a status is not a transition: a host that
611
+ * mounts an already finished run gets no completion event for it.
612
+ */
613
+ function useRunTransitionEvents(runId, run) {
614
+ const { events } = useStewardsSdk();
615
+ const lastStatus = useRef(void 0);
616
+ const status = run?.status;
617
+ const stewardId = run?.stewardId;
618
+ const stopReason = run?.stopReason;
619
+ useEffect(() => {
620
+ if (!status || !stewardId) return;
621
+ const previous = lastStatus.current;
622
+ lastStatus.current = status;
623
+ if (previous === void 0 || previous === status) return;
624
+ if (status === "COMPLETED") events.emit("run.completed", {
625
+ runId,
626
+ stewardId
627
+ });
628
+ else if (status === "FAILED") events.emit("run.failed", {
629
+ runId,
630
+ stewardId,
631
+ message: stopReason ?? "The run failed"
632
+ });
633
+ else if (status in WAITING_REASON) events.emit("run.waiting", {
634
+ runId,
635
+ stewardId,
636
+ reason: WAITING_REASON[status]
637
+ });
638
+ }, [
639
+ status,
640
+ stewardId,
641
+ stopReason,
642
+ runId,
643
+ events
644
+ ]);
645
+ }
646
+ /**
647
+ * One run: its steps, approvals, trust level and budget. Polls the gateway
648
+ * while the run is active (the embed session is not a subscription actor) and
649
+ * emits `run.waiting`, `run.completed` and `run.failed` as the status changes.
650
+ */
651
+ function StewardRunView({ runId, pollIntervalMs = 3e3 }) {
652
+ const { config } = useStewardsSdk();
653
+ const { data, error, loading, refetch } = useStewardsQuery(GET_STEWARD_RUN, { id: runId }, { pollMs: (d) => d.getBotmanorStewardRun && !isTerminalRunStatus(d.getBotmanorStewardRun.status) ? pollIntervalMs : false });
654
+ const cancel = useStewardsMutation(CANCEL_STEWARD_RUN);
655
+ const run = data?.getBotmanorStewardRun ?? void 0;
656
+ useRunTransitionEvents(runId, run);
657
+ const onCancel = async () => {
658
+ if (await cancel.mutate({ id: runId })) refetch();
659
+ };
660
+ return /* @__PURE__ */ jsxs(ScopedTheme, {
661
+ theme: config.theme,
662
+ label: "Steward run",
663
+ component: "steward-run-view",
664
+ children: [
665
+ /* @__PURE__ */ jsx("h2", {
666
+ style: headingStyle,
667
+ children: "Steward run"
668
+ }),
669
+ loading && !run ? /* @__PURE__ */ jsx(Muted, { children: "Loading the run…" }) : null,
670
+ /* @__PURE__ */ jsx(ErrorNote, { error: error ?? cancel.error }),
671
+ !loading && !error && !run ? /* @__PURE__ */ jsx(Muted, { children: "This run was not found." }) : null,
672
+ run ? /* @__PURE__ */ jsxs(Fragment, { children: [
673
+ /* @__PURE__ */ jsx(RunHeader, {
674
+ run,
675
+ cancelling: cancel.loading,
676
+ onCancel: () => void onCancel()
677
+ }),
678
+ /* @__PURE__ */ jsx(RunSteps, { steps: run.steps }),
679
+ /* @__PURE__ */ jsx(RunApprovals, { approvals: run.approvals })
680
+ ] }) : null
681
+ ]
682
+ });
683
+ }
684
+ const subheadingStyle = {
685
+ ...headingStyle,
686
+ fontSize: "14px",
687
+ marginTop: "16px"
688
+ };
689
+ function runTimeline(run) {
690
+ const finished = run.finishedAt ? `, finished ${formatDate(run.finishedAt)}` : "";
691
+ const reason = run.stopReason ? ` — ${humanize(run.stopReason)}` : "";
692
+ return `Started ${formatDate(run.startedAt)}${finished}${reason}`;
693
+ }
694
+ function runUsage(run) {
695
+ const credits = run.budgetUsed?.credits;
696
+ const used = credits != null ? `, ${credits} credits used` : "";
697
+ return `${run.stepCount} steps${used}`;
698
+ }
699
+ /** Status, trust, budget and timeline, with Cancel while the run is active. */
700
+ function RunHeader({ run, cancelling, onCancel }) {
701
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("p", {
702
+ style: {
703
+ alignItems: "center",
704
+ display: "flex",
705
+ flexWrap: "wrap",
706
+ gap: "8px",
707
+ margin: "8px 0 0"
708
+ },
709
+ children: [
710
+ /* @__PURE__ */ jsx(Badge, { children: humanize(run.status) }),
711
+ /* @__PURE__ */ jsxs(Badge, { children: ["Trust ", humanize(run.trustLevel)] }),
712
+ run.dryRun ? /* @__PURE__ */ jsx(Badge, { children: "Dry run" }) : null,
713
+ /* @__PURE__ */ jsx("span", { children: runUsage(run) }),
714
+ !isTerminalRunStatus(run.status) ? /* @__PURE__ */ jsx(Button, {
715
+ kind: "danger",
716
+ onClick: onCancel,
717
+ disabled: cancelling,
718
+ children: "Cancel run"
719
+ }) : null
720
+ ]
721
+ }), /* @__PURE__ */ jsx(Muted, { children: runTimeline(run) })] });
722
+ }
723
+ function RunSteps({ steps }) {
724
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("h3", {
725
+ style: subheadingStyle,
726
+ children: "Steps"
727
+ }), steps.length === 0 ? /* @__PURE__ */ jsx(Muted, { children: "No steps yet." }) : /* @__PURE__ */ jsx("ol", {
728
+ style: listStyle,
729
+ "aria-label": "Run steps",
730
+ children: steps.map((step) => /* @__PURE__ */ jsxs("li", {
731
+ style: rowStyle,
732
+ children: [
733
+ /* @__PURE__ */ jsxs("strong", { children: [
734
+ step.seq,
735
+ ". ",
736
+ step.toolKey ?? humanize(step.kind)
737
+ ] }),
738
+ " ",
739
+ /* @__PURE__ */ jsx(Badge, { children: humanize(step.verdict) }),
740
+ step.targetSummary ? /* @__PURE__ */ jsx("div", { children: step.targetSummary }) : null,
741
+ step.resultSummary ? /* @__PURE__ */ jsx(Muted, { children: step.resultSummary }) : null
742
+ ]
743
+ }, step.id))
744
+ })] });
745
+ }
746
+ function RunApprovals({ approvals }) {
747
+ if (approvals.length === 0) return null;
748
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("h3", {
749
+ style: subheadingStyle,
750
+ children: "Approvals"
751
+ }), /* @__PURE__ */ jsx("ul", {
752
+ style: listStyle,
753
+ "aria-label": "Run approvals",
754
+ children: approvals.map((a) => /* @__PURE__ */ jsxs("li", {
755
+ style: rowStyle,
756
+ children: [
757
+ a.toolName,
758
+ " ",
759
+ /* @__PURE__ */ jsx(Badge, { children: humanize(a.status) }),
760
+ " ",
761
+ /* @__PURE__ */ jsxs(Badge, { children: ["Risk ", humanize(a.riskLevel)] })
762
+ ]
763
+ }, a.id))
764
+ })] });
765
+ }
766
+
767
+ // src/components/StewardConsole.tsx
768
+ /** List stewards, or open one: its charter summary, start a run, recent runs. */
769
+ function StewardConsole({ stewardId, onSelectSteward }) {
770
+ const { config } = useStewardsSdk();
771
+ const [opened, setOpened] = useState(void 0);
772
+ const current = stewardId ?? opened;
773
+ return /* @__PURE__ */ jsxs(ScopedTheme, {
774
+ theme: config.theme,
775
+ label: "Steward console",
776
+ component: "steward-console",
777
+ children: [/* @__PURE__ */ jsx("h2", {
778
+ style: headingStyle,
779
+ children: "Steward console"
780
+ }), current ? /* @__PURE__ */ jsx(StewardPanel, {
781
+ stewardId: current,
782
+ onBack: stewardId ? void 0 : () => setOpened(void 0)
783
+ }) : /* @__PURE__ */ jsx(StewardList, { onSelect: (id) => {
784
+ setOpened(id);
785
+ onSelectSteward?.(id);
786
+ } })]
787
+ });
788
+ }
789
+ function StewardList({ onSelect }) {
790
+ const { data, error, loading } = useStewardsQuery(LIST_STEWARDS, { pagination: { limit: 50 } });
791
+ const stewards = data?.listBotmanorStewards;
792
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
793
+ loading && !stewards ? /* @__PURE__ */ jsx(Muted, { children: "Loading stewards…" }) : null,
794
+ /* @__PURE__ */ jsx(ErrorNote, { error }),
795
+ stewards && stewards.length === 0 ? /* @__PURE__ */ jsx(Muted, { children: "No stewards yet." }) : null,
796
+ stewards && stewards.length > 0 ? /* @__PURE__ */ jsx("ul", {
797
+ style: listStyle,
798
+ "aria-label": "Stewards",
799
+ children: stewards.map((s) => /* @__PURE__ */ jsxs("li", {
800
+ style: rowStyle,
801
+ children: [
802
+ /* @__PURE__ */ jsx("strong", { children: s.agent?.name ?? s.agentId }),
803
+ " ",
804
+ /* @__PURE__ */ jsx(Badge, { children: humanize(s.status) }),
805
+ s.charter ? /* @__PURE__ */ jsx(Badge, { children: humanize(s.charter.autonomyLevel) }) : null,
806
+ s.pendingApprovalCount > 0 ? /* @__PURE__ */ jsxs(Badge, { children: [s.pendingApprovalCount, " awaiting approval"] }) : null,
807
+ " ",
808
+ /* @__PURE__ */ jsx(Button, {
809
+ onClick: () => onSelect(s.id),
810
+ label: `Open ${s.agent?.name ?? s.id}`,
811
+ children: "Open"
812
+ }),
813
+ /* @__PURE__ */ jsx(Muted, { children: s.lastRun ? `Last run ${humanize(s.lastRun.status)}, ${formatDate(s.lastRun.startedAt)}` : "No runs yet" })
814
+ ]
815
+ }, s.id))
816
+ }) : null
817
+ ] });
818
+ }
819
+ function StewardPanel({ stewardId, onBack }) {
820
+ const steward = useStewardsQuery(GET_STEWARD, { id: stewardId });
821
+ const runs = useStewardsQuery(LIST_STEWARD_RUNS, {
822
+ filter: { stewardId },
823
+ pagination: { limit: 10 }
824
+ }, { pollMs: (d) => d.listBotmanorStewardRuns.some((r) => !isTerminalRunStatus(r.status)) ? 5e3 : false });
825
+ const [selectedRun, setSelectedRun] = useState(void 0);
826
+ const detail = steward.data?.getBotmanorSteward ?? void 0;
827
+ const notFound = !steward.loading && !steward.error && !detail;
828
+ const onStarted = (runId) => {
829
+ setSelectedRun(runId);
830
+ runs.refetch();
831
+ };
832
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
833
+ onBack ? /* @__PURE__ */ jsx("p", {
834
+ style: { margin: "8px 0 0" },
835
+ children: /* @__PURE__ */ jsx(Button, {
836
+ onClick: onBack,
837
+ children: "All stewards"
838
+ })
839
+ }) : null,
840
+ steward.loading && !detail ? /* @__PURE__ */ jsx(Muted, { children: "Loading the steward…" }) : null,
841
+ /* @__PURE__ */ jsx(ErrorNote, { error: steward.error }),
842
+ notFound ? /* @__PURE__ */ jsx(Muted, { children: "This steward was not found." }) : null,
843
+ detail ? /* @__PURE__ */ jsxs(Fragment, { children: [
844
+ /* @__PURE__ */ jsx(StewardSummary, { detail }),
845
+ detail.status === "ACTIVE" ? /* @__PURE__ */ jsx(StartRunForm, {
846
+ stewardId,
847
+ onStarted
848
+ }) : /* @__PURE__ */ jsx(Muted, { children: "Only an active steward can start a run." }),
849
+ /* @__PURE__ */ jsx(RecentRuns, {
850
+ runs: runs.data?.listBotmanorStewardRuns,
851
+ error: runs.error,
852
+ onView: setSelectedRun
853
+ }),
854
+ selectedRun ? /* @__PURE__ */ jsx("div", {
855
+ style: { marginTop: "16px" },
856
+ children: /* @__PURE__ */ jsx(StewardRunView, { runId: selectedRun })
857
+ }) : null
858
+ ] }) : null
859
+ ] });
860
+ }
861
+ function usageLine(detail) {
862
+ const credits = detail.usageToday?.credits;
863
+ const usage = credits != null ? `, ${credits} credits used today` : "";
864
+ return `${detail.pendingApprovalCount} awaiting approval${usage}`;
865
+ }
866
+ /** Name, status, autonomy, desk and today's usage of one steward. */
867
+ function StewardSummary({ detail }) {
868
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
869
+ /* @__PURE__ */ jsxs("p", {
870
+ style: { margin: "8px 0 0" },
871
+ children: [
872
+ /* @__PURE__ */ jsx("strong", { children: detail.agent?.name ?? detail.agentId }),
873
+ " ",
874
+ /* @__PURE__ */ jsx(Badge, { children: humanize(detail.status) }),
875
+ " ",
876
+ detail.charter ? /* @__PURE__ */ jsx(Badge, { children: humanize(detail.charter.autonomyLevel) }) : null,
877
+ " ",
878
+ /* @__PURE__ */ jsxs(Badge, { children: ["Desk ", humanize(detail.defaultDeskKind)] })
879
+ ]
880
+ }),
881
+ /* @__PURE__ */ jsx(Muted, { children: usageLine(detail) }),
882
+ detail.charter ? /* @__PURE__ */ jsx(Muted, { children: detail.charter.charterText }) : null
883
+ ] });
884
+ }
885
+ /**
886
+ * Prompt box that starts a run. Emits `run.started` and hands the new run id
887
+ * to the parent, which selects it and refreshes the run list.
888
+ */
889
+ function StartRunForm({ stewardId, onStarted }) {
890
+ const { events } = useStewardsSdk();
891
+ const start = useStewardsMutation(RUN_STEWARD);
892
+ const [prompt, setPrompt] = useState("");
893
+ const onSubmit = async (e) => {
894
+ e.preventDefault();
895
+ const text = prompt.trim();
896
+ if (!text) return;
897
+ const result = await start.mutate({ input: {
898
+ stewardId,
899
+ prompt: text
900
+ } });
901
+ if (!result) return;
902
+ const run = result.runBotmanorSteward;
903
+ events.emit("run.started", {
904
+ runId: run.id,
905
+ stewardId
906
+ });
907
+ setPrompt("");
908
+ onStarted(run.id);
909
+ };
910
+ return /* @__PURE__ */ jsxs("form", {
911
+ onSubmit: (e) => void onSubmit(e),
912
+ children: [
913
+ /* @__PURE__ */ jsx(Field, {
914
+ label: "Ask the steward to do something",
915
+ htmlFor: `prompt-${stewardId}`,
916
+ children: /* @__PURE__ */ jsx("textarea", {
917
+ id: `prompt-${stewardId}`,
918
+ value: prompt,
919
+ onChange: (e) => setPrompt(e.target.value),
920
+ rows: 3,
921
+ maxLength: 2e4,
922
+ style: fieldStyle
923
+ })
924
+ }),
925
+ /* @__PURE__ */ jsx("p", {
926
+ style: { margin: "8px 0 0" },
927
+ children: /* @__PURE__ */ jsx(Button, {
928
+ type: "submit",
929
+ kind: "primary",
930
+ disabled: start.loading || prompt.trim() === "",
931
+ children: "Run"
932
+ })
933
+ }),
934
+ /* @__PURE__ */ jsx(ErrorNote, { error: start.error })
935
+ ]
936
+ });
937
+ }
938
+ /** The steward's latest runs, each with a button that opens it below. */
939
+ function RecentRuns({ runs, error, onView }) {
940
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
941
+ /* @__PURE__ */ jsx("h3", {
942
+ style: {
943
+ ...headingStyle,
944
+ fontSize: "14px",
945
+ marginTop: "16px"
946
+ },
947
+ children: "Recent runs"
948
+ }),
949
+ /* @__PURE__ */ jsx(ErrorNote, { error }),
950
+ runs && runs.length === 0 ? /* @__PURE__ */ jsx(Muted, { children: "No runs yet." }) : null,
951
+ /* @__PURE__ */ jsx("ul", {
952
+ style: listStyle,
953
+ "aria-label": "Recent runs",
954
+ children: (runs ?? []).map((r) => /* @__PURE__ */ jsxs("li", {
955
+ style: rowStyle,
956
+ children: [
957
+ /* @__PURE__ */ jsx(Badge, { children: humanize(r.status) }),
958
+ " ",
959
+ humanize(r.trigger),
960
+ ",",
961
+ " ",
962
+ formatDate(r.createdAt),
963
+ " ",
964
+ /* @__PURE__ */ jsx(Button, {
965
+ onClick: () => onView(r.id),
966
+ label: `View run ${r.id}`,
967
+ children: "View"
968
+ })
969
+ ]
970
+ }, r.id))
971
+ })
972
+ ] });
973
+ }
974
+
975
+ // src/components/StewardBuilder.tsx
976
+ const AUTONOMY = [
977
+ "OBSERVE",
978
+ "ASK",
979
+ "GUIDED",
980
+ "TRUSTED"
981
+ ];
982
+ const DESKS = [
983
+ "NONE",
984
+ "BROWSER",
985
+ "CLOUD",
986
+ "OWN_MACHINE"
987
+ ];
988
+ /** Parses a non-negative credits value; empty means "no cap". `null` is invalid. */
989
+ function parseCredits(raw) {
990
+ const text = raw.trim();
991
+ if (text === "") return void 0;
992
+ const n = Number(text);
993
+ return Number.isFinite(n) && n >= 0 ? n : null;
994
+ }
995
+ /**
996
+ * Create a steward from an agent and a charter, or edit an existing charter:
997
+ * the charter text, the autonomy level and a daily credit budget. Duties and
998
+ * playbooks live in the full Stewards app.
999
+ */
1000
+ function StewardBuilder(props) {
1001
+ const { config } = useStewardsSdk();
1002
+ const editing = props.stewardId !== void 0;
1003
+ return /* @__PURE__ */ jsxs(ScopedTheme, {
1004
+ theme: config.theme,
1005
+ label: "Steward builder",
1006
+ component: "steward-builder",
1007
+ children: [/* @__PURE__ */ jsx("h2", {
1008
+ style: headingStyle,
1009
+ children: editing ? "Edit charter" : "Create a steward"
1010
+ }), props.stewardId ? /* @__PURE__ */ jsx(EditForm, {
1011
+ stewardId: props.stewardId,
1012
+ onSaved: props.onSaved
1013
+ }) : /* @__PURE__ */ jsx(CreateForm, {
1014
+ agentId: props.agentId,
1015
+ onCreated: props.onCreated
1016
+ })]
1017
+ });
1018
+ }
1019
+ function CharterFields(p) {
1020
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1021
+ /* @__PURE__ */ jsx(Field, {
1022
+ label: "Charter",
1023
+ htmlFor: `${p.idPrefix}-charter`,
1024
+ children: /* @__PURE__ */ jsx("textarea", {
1025
+ id: `${p.idPrefix}-charter`,
1026
+ value: p.charterText,
1027
+ onChange: (e) => p.setCharterText(e.target.value),
1028
+ rows: 5,
1029
+ style: fieldStyle
1030
+ })
1031
+ }),
1032
+ /* @__PURE__ */ jsx(Field, {
1033
+ label: "Autonomy",
1034
+ htmlFor: `${p.idPrefix}-autonomy`,
1035
+ children: /* @__PURE__ */ jsx("select", {
1036
+ id: `${p.idPrefix}-autonomy`,
1037
+ value: p.autonomy,
1038
+ onChange: (e) => p.setAutonomy(e.target.value),
1039
+ style: fieldStyle,
1040
+ children: AUTONOMY.map((a) => /* @__PURE__ */ jsx("option", {
1041
+ value: a,
1042
+ children: humanize(a)
1043
+ }, a))
1044
+ })
1045
+ }),
1046
+ /* @__PURE__ */ jsx(Field, {
1047
+ label: "Daily credit budget (optional)",
1048
+ htmlFor: `${p.idPrefix}-credits`,
1049
+ children: /* @__PURE__ */ jsx("input", {
1050
+ id: `${p.idPrefix}-credits`,
1051
+ value: p.credits,
1052
+ onChange: (e) => p.setCredits(e.target.value),
1053
+ inputMode: "decimal",
1054
+ style: fieldStyle
1055
+ })
1056
+ })
1057
+ ] });
1058
+ }
1059
+ function CreateForm({ agentId, onCreated }) {
1060
+ const agents = useStewardsQuery(LIST_AGENT_CANDIDATES, { filters: { status: "ACTIVE" } }, { skip: agentId !== void 0 });
1061
+ const create = useStewardsMutation(CREATE_STEWARD);
1062
+ const [pickedAgent, setPickedAgent] = useState("");
1063
+ const [charterText, setCharterText] = useState("");
1064
+ const [autonomy, setAutonomy] = useState("ASK");
1065
+ const [desk, setDesk] = useState("NONE");
1066
+ const [credits, setCredits] = useState("");
1067
+ const [validation, setValidation] = useState();
1068
+ const [createdId, setCreatedId] = useState();
1069
+ const chosenAgent = agentId ?? pickedAgent;
1070
+ const onSubmit = async (e) => {
1071
+ e.preventDefault();
1072
+ const parsed = parseCredits(credits);
1073
+ if (!chosenAgent) return setValidation("Choose an agent.");
1074
+ if (charterText.trim() === "") return setValidation("Write the charter first.");
1075
+ if (parsed === null) return setValidation("The daily budget must be a number, 0 or more.");
1076
+ setValidation(void 0);
1077
+ const result = await create.mutate({ input: {
1078
+ agentId: chosenAgent,
1079
+ charterText: charterText.trim(),
1080
+ autonomyLevel: autonomy,
1081
+ defaultDeskKind: desk,
1082
+ ...parsed !== void 0 ? { budgetPerDay: { credits: parsed } } : {}
1083
+ } });
1084
+ if (result) {
1085
+ setCreatedId(result.createBotmanorSteward.id);
1086
+ onCreated?.(result.createBotmanorSteward.id);
1087
+ }
1088
+ };
1089
+ if (createdId) return /* @__PURE__ */ jsx(Muted, { children: "Steward created." });
1090
+ return /* @__PURE__ */ jsxs("form", {
1091
+ onSubmit: (e) => void onSubmit(e),
1092
+ noValidate: true,
1093
+ children: [
1094
+ agentId ? null : /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Field, {
1095
+ label: "Agent",
1096
+ htmlFor: "steward-agent",
1097
+ children: /* @__PURE__ */ jsxs("select", {
1098
+ id: "steward-agent",
1099
+ value: pickedAgent,
1100
+ onChange: (e) => setPickedAgent(e.target.value),
1101
+ style: fieldStyle,
1102
+ children: [/* @__PURE__ */ jsx("option", {
1103
+ value: "",
1104
+ children: "Choose an agent…"
1105
+ }), (agents.data?.listBotmanorAgents ?? []).map((a) => /* @__PURE__ */ jsx("option", {
1106
+ value: a.id,
1107
+ children: a.name
1108
+ }, a.id))]
1109
+ })
1110
+ }), /* @__PURE__ */ jsx(ErrorNote, { error: agents.error })] }),
1111
+ /* @__PURE__ */ jsx(CharterFields, {
1112
+ idPrefix: "create",
1113
+ charterText,
1114
+ setCharterText,
1115
+ autonomy,
1116
+ setAutonomy,
1117
+ credits,
1118
+ setCredits
1119
+ }),
1120
+ /* @__PURE__ */ jsx(Field, {
1121
+ label: "Desk",
1122
+ htmlFor: "steward-desk",
1123
+ children: /* @__PURE__ */ jsx("select", {
1124
+ id: "steward-desk",
1125
+ value: desk,
1126
+ onChange: (e) => setDesk(e.target.value),
1127
+ style: fieldStyle,
1128
+ children: DESKS.map((d) => /* @__PURE__ */ jsx("option", {
1129
+ value: d,
1130
+ children: humanize(d)
1131
+ }, d))
1132
+ })
1133
+ }),
1134
+ validation ? /* @__PURE__ */ jsx(ErrorNote, { error: new Error(validation) }) : null,
1135
+ /* @__PURE__ */ jsx(ErrorNote, { error: create.error }),
1136
+ /* @__PURE__ */ jsx("p", {
1137
+ style: { margin: "16px 0 0" },
1138
+ children: /* @__PURE__ */ jsx(Button, {
1139
+ type: "submit",
1140
+ kind: "primary",
1141
+ disabled: create.loading,
1142
+ children: "Create steward"
1143
+ })
1144
+ })
1145
+ ]
1146
+ });
1147
+ }
1148
+ function EditForm({ stewardId, onSaved }) {
1149
+ const steward = useStewardsQuery(GET_STEWARD, { id: stewardId });
1150
+ const detail = steward.data?.getBotmanorSteward;
1151
+ if (steward.loading && !detail) return /* @__PURE__ */ jsx(Muted, { children: "Loading the charter…" });
1152
+ 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." })] });
1153
+ return /* @__PURE__ */ jsx(EditCharter, {
1154
+ detail,
1155
+ onSaved
1156
+ });
1157
+ }
1158
+ function EditCharter({ detail, onSaved }) {
1159
+ const charter = detail.charter;
1160
+ const update = useStewardsMutation(UPDATE_STEWARD_CHARTER);
1161
+ const [charterText, setCharterText] = useState(charter?.charterText ?? "");
1162
+ const [autonomy, setAutonomy] = useState(charter?.autonomyLevel ?? "ASK");
1163
+ const [credits, setCredits] = useState(charter?.budgetPerDay?.credits != null ? String(charter.budgetPerDay.credits) : "");
1164
+ const [validation, setValidation] = useState();
1165
+ const [saved, setSaved] = useState(false);
1166
+ const onSubmit = async (e) => {
1167
+ e.preventDefault();
1168
+ const parsed = parseCredits(credits);
1169
+ if (charterText.trim() === "") return setValidation("The charter cannot be empty.");
1170
+ if (parsed === null) return setValidation("The daily budget must be a number, 0 or more.");
1171
+ setValidation(void 0);
1172
+ if (await update.mutate({
1173
+ id: detail.id,
1174
+ input: {
1175
+ charterText: charterText.trim(),
1176
+ autonomyLevel: autonomy,
1177
+ ...parsed !== void 0 ? { budgetPerDay: { credits: parsed } } : {}
1178
+ }
1179
+ })) {
1180
+ setSaved(true);
1181
+ onSaved?.(detail.id);
1182
+ }
1183
+ };
1184
+ return /* @__PURE__ */ jsxs("form", {
1185
+ onSubmit: (e) => void onSubmit(e),
1186
+ noValidate: true,
1187
+ children: [
1188
+ /* @__PURE__ */ jsx(CharterFields, {
1189
+ idPrefix: "edit",
1190
+ charterText,
1191
+ setCharterText: (v) => {
1192
+ setSaved(false);
1193
+ setCharterText(v);
1194
+ },
1195
+ autonomy,
1196
+ setAutonomy: (v) => {
1197
+ setSaved(false);
1198
+ setAutonomy(v);
1199
+ },
1200
+ credits,
1201
+ setCredits: (v) => {
1202
+ setSaved(false);
1203
+ setCredits(v);
1204
+ }
1205
+ }),
1206
+ validation ? /* @__PURE__ */ jsx(ErrorNote, { error: new Error(validation) }) : null,
1207
+ /* @__PURE__ */ jsx(ErrorNote, { error: update.error }),
1208
+ saved ? /* @__PURE__ */ jsx(Muted, { children: "Charter saved." }) : null,
1209
+ /* @__PURE__ */ jsx("p", {
1210
+ style: { margin: "16px 0 0" },
1211
+ children: /* @__PURE__ */ jsx(Button, {
1212
+ type: "submit",
1213
+ kind: "primary",
1214
+ disabled: update.loading,
1215
+ children: "Save charter"
1216
+ })
1217
+ })
1218
+ ]
1219
+ });
1220
+ }
1221
+
1222
+ // src/components/ApprovalInbox.tsx
1223
+ const SCOPES = [
1224
+ "ONCE",
1225
+ "RUN",
1226
+ "DUTY",
1227
+ "TIME_LIMITED",
1228
+ "STANDING"
1229
+ ];
1230
+ /**
1231
+ * Pending steward approvals the viewer can decide, with the approval scope
1232
+ * choice. Extends the platform tool-approval queue (`source: STEWARD`,
1233
+ * `mine: true`) rather than a parallel one.
1234
+ */
1235
+ function ApprovalInbox({ stewardId, pollIntervalMs = 15e3 }) {
1236
+ const { config, events } = useStewardsSdk();
1237
+ const { data, error, loading, refetch } = useStewardsQuery(LIST_STEWARD_APPROVALS, {
1238
+ filter: {
1239
+ source: "STEWARD",
1240
+ status: "PENDING",
1241
+ mine: true,
1242
+ ...stewardId ? { stewardId } : {}
1243
+ },
1244
+ pagination: { limit: 50 }
1245
+ }, { pollMs: () => pollIntervalMs });
1246
+ const decide = useStewardsMutation(DECIDE_APPROVAL);
1247
+ const [scopes, setScopes] = useState({});
1248
+ const approvals = data?.listBotmanorToolApprovals;
1249
+ const seen = useRef(void 0);
1250
+ useEffect(() => {
1251
+ if (!approvals) return;
1252
+ const known = seen.current;
1253
+ seen.current = new Set(approvals.map((a) => a.id));
1254
+ if (!known) return;
1255
+ for (const a of approvals) if (!known.has(a.id) && a.stewardRunId) events.emit("approval.requested", {
1256
+ approvalId: a.id,
1257
+ runId: a.stewardRunId
1258
+ });
1259
+ }, [approvals, events]);
1260
+ const onDecide = async (id, decision, scope) => {
1261
+ if (await decide.mutate(decision === "APPROVE" ? {
1262
+ id,
1263
+ decision,
1264
+ scope
1265
+ } : {
1266
+ id,
1267
+ decision
1268
+ })) {
1269
+ events.emit("approval.decided", {
1270
+ approvalId: id,
1271
+ decision
1272
+ });
1273
+ refetch();
1274
+ }
1275
+ };
1276
+ return /* @__PURE__ */ jsxs(ScopedTheme, {
1277
+ theme: config.theme,
1278
+ label: "Approvals",
1279
+ component: "approval-inbox",
1280
+ children: [
1281
+ /* @__PURE__ */ jsx("h2", {
1282
+ style: headingStyle,
1283
+ children: "Approvals"
1284
+ }),
1285
+ loading && !approvals ? /* @__PURE__ */ jsx(Muted, { children: "Loading approvals…" }) : null,
1286
+ /* @__PURE__ */ jsx(ErrorNote, { error: error ?? decide.error }),
1287
+ approvals && approvals.length === 0 ? /* @__PURE__ */ jsx(Muted, { children: "Nothing is waiting for your approval." }) : null,
1288
+ approvals && approvals.length > 0 ? /* @__PURE__ */ jsx("ul", {
1289
+ style: listStyle,
1290
+ "aria-label": "Pending approvals",
1291
+ children: approvals.map((a) => {
1292
+ const scope = scopes[a.id] ?? a.requestedScope ?? "ONCE";
1293
+ return /* @__PURE__ */ jsxs("li", {
1294
+ style: rowStyle,
1295
+ children: [
1296
+ /* @__PURE__ */ jsx("strong", { children: a.toolName }),
1297
+ " ",
1298
+ /* @__PURE__ */ jsxs(Badge, { children: ["Risk ", humanize(a.riskLevel)] }),
1299
+ a.agentName ? /* @__PURE__ */ jsx(Badge, { children: a.agentName }) : null,
1300
+ a.destination ? /* @__PURE__ */ jsxs("div", { children: ["To ", a.destination] }) : null,
1301
+ a.purpose ? /* @__PURE__ */ jsx(Muted, { children: a.purpose }) : null,
1302
+ /* @__PURE__ */ jsxs(Muted, { children: ["Expires ", formatDate(a.expiresAt)] }),
1303
+ /* @__PURE__ */ jsxs("div", {
1304
+ style: {
1305
+ alignItems: "center",
1306
+ display: "flex",
1307
+ flexWrap: "wrap",
1308
+ gap: "8px",
1309
+ marginTop: "8px"
1310
+ },
1311
+ children: [
1312
+ a.fixedDefault ? null : /* @__PURE__ */ jsx("select", {
1313
+ "aria-label": `Approval scope for ${a.toolName}`,
1314
+ value: scope,
1315
+ onChange: (e) => setScopes((prev) => ({
1316
+ ...prev,
1317
+ [a.id]: e.target.value
1318
+ })),
1319
+ style: {
1320
+ ...fieldStyle,
1321
+ width: "auto"
1322
+ },
1323
+ children: SCOPES.map((s) => /* @__PURE__ */ jsx("option", {
1324
+ value: s,
1325
+ children: humanize(s)
1326
+ }, s))
1327
+ }),
1328
+ /* @__PURE__ */ jsx(Button, {
1329
+ kind: "primary",
1330
+ disabled: decide.loading,
1331
+ onClick: () => void onDecide(a.id, "APPROVE", a.fixedDefault ? "ONCE" : scope),
1332
+ label: `Approve ${a.toolName}`,
1333
+ children: "Approve"
1334
+ }),
1335
+ /* @__PURE__ */ jsx(Button, {
1336
+ kind: "danger",
1337
+ disabled: decide.loading,
1338
+ onClick: () => void onDecide(a.id, "DENY", scope),
1339
+ label: `Deny ${a.toolName}`,
1340
+ children: "Deny"
1341
+ })
1342
+ ]
1343
+ })
1344
+ ]
1345
+ }, a.id);
1346
+ })
1347
+ }) : null
1348
+ ]
1349
+ });
1350
+ }
1351
+
1352
+ export { ApprovalInbox, DEFAULT_STEWARDS_THEME, StewardBuilder, StewardConsole, StewardRunView, StewardsRequestError, StewardsSdkProvider, createStewardsEventBus, themeToStyle, useStewardsEvent, useStewardsSdk };