@eum-agent/agent-management 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.js +735 -32
  2. package/package.json +2 -2
  3. package/ui/ui.js +1623 -1599
package/ui/ui.js CHANGED
@@ -1,5 +1,5 @@
1
- import { Alert, AlertDialog, Avatar, Button, Checkbox, Dialog, DialogContent, DialogHeader, DialogTitle, EmptyState, Failure, Field, FilterChips, FormFailure, Input, InputNumber, PLUGIN_ICONS, Panel, ReadFailure, RenderingRegion, Segmented, Select, SlotOutlet, Switch, Tabs, TabsContent, TabsList, TabsTrigger, Textarea, Tooltip, TooltipContent, TooltipHint, TooltipTrigger, Warning, agentDeleted, agentOf, cn, codePoints, contributionsIn, failureText, goToSession, i18next, localeLeaves, pictureOf, pngDataUrl, resolveLabel, useAgents, useAvatarPicker, useGateway, useGatewayAction, useGatewayRead, useNavigation, usePlugins, useToast, useTranslation, uuid } from "@eum-agent/host/framework";
2
- import { createContext, createElement, forwardRef, useCallback, useContext, useEffect, useId, useMemo, useRef, useState } from "react";
1
+ import { Alert, AlertDialog, Avatar, Button, DataTable, Dialog, DialogContent, DialogHeader, DialogTitle, EmptyState, Failure, Field, FormFailure, Input, InputNumber, PLUGIN_ICONS, Panel, ReadFailure, RenderingRegion, Segmented, Select, SlotOutlet, Switch, Tabs, TabsContent, TabsList, TabsTrigger, Textarea, Tooltip, TooltipContent, TooltipHint, TooltipTrigger, Warning, agentDeleted, agentOf, cn, codePoints, contributionsIn, failureText, goToSession, i18next, localeLeaves, pictureOf, pngDataUrl, resolveLabel, useAgents, useAvatarPicker, useBrowserService, useGateway, useGatewayAction, useGatewayRead, useNavigation, usePlugins, useToast, useTranslation, uuid } from "@eum-agent/host/framework";
2
+ import { createContext, createElement, forwardRef, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
3
3
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4
4
  //#region ui-src/styles.css?raw
5
5
  var styles_default = "@layer components {\n [data-slot=\"settings-panel\"] {\n container-type: inline-size;\n }\n}\n\n.ag-shell {\n display: grid;\n flex: 1;\n min-height: 0;\n grid-template-columns: 15rem minmax(0, 1fr);\n}\n.ag-list {\n display: flex;\n flex-direction: column;\n min-height: 0;\n padding: 0 0.75rem 0.75rem;\n border-inline-end: 1px solid var(--border);\n}\n.ag-list-title {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 0.5rem;\n flex: none;\n height: 4rem;\n padding-inline: 0.625rem 0;\n}\n.ag-list-title h2 {\n font-size: 1.125rem;\n font-weight: 600;\n}\n.ag-list-title [data-slot=\"button\"],\n.ag-list-title [data-slot=\"tooltip-trigger\"] {\n color: var(--muted-foreground);\n}\n.ag-rows {\n display: flex;\n flex: 1;\n flex-direction: column;\n min-height: 0;\n overflow-y: auto;\n}\n.ag-group {\n display: flex;\n flex-direction: column;\n gap: 2px;\n margin: 0;\n padding: 0;\n list-style: none;\n}\n.ag-group-title {\n margin: 1rem 0 0.25rem;\n padding-inline: 0.625rem;\n font-size: 0.75rem;\n color: var(--muted-foreground);\n}\n.ag-row {\n --row-fill: var(--card);\n position: relative;\n min-width: 0;\n border-radius: var(--radius-control);\n background: var(--row-fill);\n transition: background-color 150ms ease;\n}\n.ag-row:hover {\n --row-fill: var(--muted);\n}\n.ag-row[data-active] {\n --row-fill: var(--accent);\n}\n.ag .ag-row-open {\n display: flex;\n align-items: center;\n gap: 0.75rem;\n width: 100%;\n min-width: 0;\n padding: 0.625rem;\n border-radius: var(--radius-control);\n text-align: start;\n cursor: pointer;\n}\n.ag .ag-row-open:focus-visible {\n outline: none;\n}\n.ag-row:has(> .ag-row-open:focus-visible) {\n outline: var(--focus-ring-width) solid var(--focus-ring-color);\n}\n.ag-row-name {\n display: flex;\n flex: 1;\n flex-direction: column;\n min-width: 0;\n}\n.ag-row-name strong,\n.ag-row-name small {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n.ag-row-name strong {\n font-size: 0.875rem;\n font-weight: 500;\n}\n.ag-row[data-active] .ag-row-name strong {\n color: var(--accent-foreground);\n}\n.ag-row-name small {\n margin-top: 0.125rem;\n font-size: 0.75rem;\n color: var(--muted-foreground);\n}\n.ag-chapter-icon {\n display: grid;\n flex: none;\n place-items: center;\n width: 2rem;\n height: 2rem;\n border-radius: var(--radius-pill);\n background: var(--muted);\n color: var(--muted-foreground);\n}\n.ag-row:is(:hover, [data-active]) .ag-chapter-icon {\n background: var(--card);\n}\n/* Hover actions fade into the row, as the model and MCP lists do. */\n.ag-row-actions {\n position: absolute;\n inset-block: 0;\n inset-inline-end: 0;\n display: flex;\n align-items: center;\n gap: 0.125rem;\n padding-inline: 1.25rem 0.375rem;\n border-radius: var(--radius-control);\n background: linear-gradient(to right, transparent, var(--row-fill) 1rem);\n opacity: 0;\n pointer-events: none;\n transition: opacity 150ms ease;\n}\n.ag-row:hover .ag-row-actions,\n.ag-row:focus-within .ag-row-actions {\n opacity: 1;\n pointer-events: auto;\n}\n@media (hover: none) {\n .ag-row-actions {\n opacity: 1;\n pointer-events: auto;\n }\n}\n.ag-list-foot {\n flex: none;\n padding-top: 0.75rem;\n}\n.ag-detail {\n display: flex;\n flex-direction: column;\n min-width: 0;\n min-height: 0;\n}\n.ag-detail-header {\n display: flex;\n align-items: center;\n gap: 0.875rem;\n flex: none;\n min-height: 4.5rem;\n padding: 1rem 3.5rem 0.75rem 1.5rem;\n}\n.ag-grow {\n flex: 1;\n min-width: 0;\n}\n.ag-detail-header h3 {\n overflow: hidden;\n font-size: 1.125rem;\n font-weight: 600;\n line-height: 1.4;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n.ag-detail-header small {\n display: block;\n font-size: 0.75rem;\n color: var(--muted-foreground);\n}\n.ag-tabs {\n display: flex;\n flex: 1;\n flex-direction: column;\n min-height: 0;\n min-width: 0;\n gap: 0;\n}\n.ag-tabs > .ag-tabs-list {\n flex: none;\n margin-inline: 1.5rem;\n}\n.ag-tab {\n min-height: 0;\n overflow-y: auto;\n padding: 1rem 1.5rem 0.25rem;\n}\n.ag-tab.ag-tab-skills:not([hidden]) {\n display: flex;\n flex-direction: column;\n overflow: hidden;\n}\n.ag-tab.ag-tab-fill {\n display: flex;\n flex-direction: column;\n overflow: hidden;\n}\n.ag-chapter-body {\n flex: 1;\n min-height: 0;\n overflow-y: auto;\n padding: 0 1.5rem 1.5rem;\n}\n/* One label column with the model and MCP forms. */\n@container (min-width: 28rem) {\n .ag-detail .settings-field-row {\n grid-template-columns: 7rem minmax(0, 1fr);\n }\n}\n/* Discard and save, one equal share each, at the foot of the column. */\n/* The footer's buttons rest 0.75rem above the pane's floor, where the list\n * column's add button rests, so the two bottom rows line up. */\n.ag-footer {\n display: flex;\n flex: none;\n flex-direction: column;\n gap: 0.75rem;\n padding: 0.5rem 1.5rem 0.75rem;\n}\n.ag-footer-actions {\n display: flex;\n gap: 0.5rem;\n}\n.ag-footer-actions > * {\n flex: 1 1 0;\n min-width: 0;\n}\n@container ag (max-width: 38rem) {\n .ag-shell {\n grid-template-columns: minmax(0, 1fr);\n grid-template-rows: auto minmax(0, 1fr);\n }\n .ag-list {\n flex-direction: row;\n align-items: center;\n gap: 0.5rem;\n padding: 0.5rem 3rem 0.5rem 1rem;\n border-inline-end: 0;\n border-bottom: 1px solid var(--border);\n }\n .ag-list-title h2,\n .ag-row-name small,\n .ag-group-title {\n display: none;\n }\n .ag-list-title {\n order: 2;\n height: auto;\n padding: 0;\n }\n .ag-rows {\n flex-direction: row;\n gap: 2px;\n overflow-x: auto;\n overflow-y: hidden;\n }\n .ag-group {\n flex-direction: row;\n }\n .ag-row {\n flex: none;\n }\n .ag .ag-row-open {\n padding: 0.375rem 0.625rem 0.375rem 0.375rem;\n gap: 0.5rem;\n }\n /* The chosen chip keeps its actions inline: a strip has no hover room. */\n .ag-row[data-active] {\n display: flex;\n align-items: center;\n padding-inline-end: 0.25rem;\n }\n .ag-row .ag-row-actions {\n display: none;\n }\n .ag-row[data-active] .ag-row-actions {\n position: static;\n display: flex;\n padding: 0;\n background: none;\n opacity: 1;\n pointer-events: auto;\n }\n .ag-list-foot {\n order: 3;\n padding: 0;\n }\n .ag-list-foot [data-slot=\"button\"] {\n width: auto;\n }\n .ag-detail-header,\n .ag-tab,\n .ag-chapter-body,\n .ag-footer {\n padding-inline: 1rem;\n }\n .ag-tabs > .ag-tabs-list {\n margin-inline: 1rem;\n }\n}\n";
@@ -147,6 +147,24 @@ var catalogue$1 = {
147
147
  readFailed: "The rules file cannot be read and cannot be edited: {{reason}}"
148
148
  },
149
149
  toolSettings: {
150
+ tool: "Tool",
151
+ permitted: "Allow calls",
152
+ forbidden: "Block calls",
153
+ preload: "Preload",
154
+ preloadOn: "Preloaded. Click to load on demand.",
155
+ preloadOff: "Loaded on demand. Click to preload.",
156
+ deferred: "On demand",
157
+ cancelPreload: "Stop preloading",
158
+ defaultSuggestion: "Suggested default",
159
+ followDefault: "Following default",
160
+ customized: "Customized",
161
+ restoreDefault: "Restore default",
162
+ resetDefaultsHint: "Reset access and preload settings for every tool, including tools hidden by search",
163
+ on: "On",
164
+ off: "Off",
165
+ preloadInactive: "Calls are blocked; this preference is inactive.",
166
+ preloadUnavailable: "Preload configuration is unavailable. Saved preferences are retained.",
167
+ systemTools: "The system provides tool discovery and dispatch automatically.",
150
168
  heading: "Available tools",
151
169
  hint: "Choose which tools this agent can call. Calls still follow the safety authorization settings.",
152
170
  mode: "Tool access",
@@ -170,11 +188,11 @@ var catalogue$1 = {
170
188
  selectWholeGroup_one: "Select or clear the {{count}} tool in this group",
171
189
  unknownSource: "Unknown source",
172
190
  unrestricted: "Allow all tools",
173
- none: "This agent will have no tools at all",
191
+ none: "This agent will have no callable ordinary tools",
174
192
  selectAll: "Select all of {{group}}",
175
193
  chosen: "{{chosen}} of {{total}} chosen",
176
194
  unavailable: "Unavailable",
177
- unavailableHint: "On the whitelist, but no plugin provides it now.",
195
+ unavailableHint: "Retained preferences for tools missing from the current catalogue. These tools cannot be called.",
178
196
  all: "Select all",
179
197
  clear: "Clear"
180
198
  }
@@ -329,11 +347,29 @@ var catalogue = {
329
347
  readFailed: "无法读取规则文件,不能编辑:{{reason}}"
330
348
  },
331
349
  toolSettings: {
350
+ tool: "工具",
351
+ permitted: "允许调用",
352
+ forbidden: "禁止调用",
353
+ preload: "预加载",
354
+ preloadOn: "已预加载,点击改为按需加载",
355
+ preloadOff: "按需加载,点击开启预加载",
356
+ deferred: "按需加载",
357
+ cancelPreload: "取消预加载",
358
+ defaultSuggestion: "默认建议",
359
+ followDefault: "跟随默认",
360
+ customized: "已自定义",
361
+ restoreDefault: "恢复默认",
362
+ resetDefaultsHint: "恢复全部工具的默认调用权限和预加载设置",
363
+ on: "开启",
364
+ off: "关闭",
365
+ preloadInactive: "未允许调用,暂不生效",
366
+ preloadUnavailable: "预加载配置暂不可用,已保存的偏好会保留。",
367
+ systemTools: "系统自动提供工具检索与调用。",
332
368
  heading: "可用工具",
333
369
  hint: "决定智能体可以调用哪些工具,执行时仍遵循安全授权。",
334
370
  mode: "工具授权范围",
335
371
  custom: "自定义",
336
- allowAll: "允许全部",
372
+ allowAll: "全部允许",
337
373
  searchLabel: "搜索工具",
338
374
  searchPlaceholder: "搜索工具名称、说明或来源",
339
375
  filterLabel: "筛选工具",
@@ -350,11 +386,11 @@ var catalogue = {
350
386
  selectWholeGroup: "选择或取消本组全部 {{count}} 个工具",
351
387
  unknownSource: "未知来源",
352
388
  unrestricted: "授权所有工具调用",
353
- none: "该智能体将没有任何工具",
389
+ none: "该智能体将没有可调用的普通工具",
354
390
  selectAll: "全选 {{group}}",
355
391
  chosen: "已选 {{chosen}} 个,共 {{total}} 个",
356
392
  unavailable: "不可用",
357
- unavailableHint: "白名单里有、但当前没有插件提供的工具。",
393
+ unavailableHint: "已保留配置但当前目录中没有的工具,不能调用。",
358
394
  all: "全选",
359
395
  clear: "全不选"
360
396
  }
@@ -365,6 +401,7 @@ var catalogue = {
365
401
  //#region src/tool-names.ts
366
402
  /** Canonical names shared by tool registration and browser presentation. */
367
403
  var AGENT_TOOL_NAMES = [
404
+ "agent_list",
368
405
  "agent_read",
369
406
  "agent_update",
370
407
  "agent_create"
@@ -375,6 +412,7 @@ var CATALOGUES = {
375
412
  "en-US": {
376
413
  section: "Core capability",
377
414
  group: "Agent definition",
415
+ agent_list: "List agents",
378
416
  agent_read: "Read agent definition",
379
417
  agent_update: "Update agent definition",
380
418
  agent_create: "Create agent"
@@ -382,6 +420,7 @@ var CATALOGUES = {
382
420
  "zh-CN": {
383
421
  section: "核心能力",
384
422
  group: "智能体定义",
423
+ agent_list: "列出智能体",
385
424
  agent_read: "读取智能体设定",
386
425
  agent_update: "更新智能体设定",
387
426
  agent_create: "创建智能体"
@@ -660,1684 +699,1661 @@ var Puzzle = createLucideIcon("puzzle", [["path", {
660
699
  d: "M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z",
661
700
  key: "w46dr5"
662
701
  }]]);
702
+ //#endregion
703
+ //#region ui-src/components/settings/agent/editor.tsx
663
704
  /**
664
- * @license lucide-react v1.40.0 - ISC
705
+ * The agent detail page's one draft and its one save.
665
706
  *
666
- * This source code is licensed under the ISC license.
667
- * See the LICENSE file in the root directory of this source tree.
707
+ * Base fields, prompt slots, tool access, and opaque owner configuration stay
708
+ * in one draft until Save submits their complete changed values together.
709
+ * Owner fields are validated by their active contributions before that request.
710
+ *
711
+ * A draft remembers the saved value it was started from. When another client
712
+ * changes the agent (`config.agentChanged`, which re-reads the list and the
713
+ * prompt text), a field without a draft simply shows the new value; a field
714
+ * with one keeps it and reports `stale`, and `reload` takes the new value.
715
+ * A draft that the saved value has caught up with is no longer dirty.
668
716
  */
669
- var Search = createLucideIcon("search", [["path", {
670
- d: "m21 21-4.34-4.34",
671
- key: "14j7rj"
672
- }], ["circle", {
673
- cx: "11",
674
- cy: "11",
675
- r: "8",
676
- key: "4ej97u"
677
- }]]);
678
- //#endregion
679
- //#region ui-src/components/settings/execution-limits.tsx
680
- /** Global execution limits; each successful save applies to subsequent rounds. */
681
- function ExecutionLimits({ ctx, registerGuard }) {
682
- const host = useGateway();
683
- const gateway = ctx?.gateway ?? host;
684
- const { t } = useTranslation();
685
- const toast = useToast();
686
- const translation = useRef(t);
687
- translation.current = t;
688
- const [saved, setSaved] = useState(null);
689
- const [inputKey, setInputKey] = useState(0);
690
- const [draft, setDraft] = useState(null);
691
- const [readError, setReadError] = useState(null);
692
- const [saveError, setSaveError] = useState(null);
693
- const [reading, setReading] = useState(true);
694
- const [blocked, setBlocked] = useState(false);
695
- const [saving, setSaving] = useState(false);
696
- const [notice, setNotice] = useState(null);
697
- const [online, setOnline] = useState(gateway.connection.status === "online");
698
- const latest = useRef({
699
- draft,
700
- saved,
701
- saving
717
+ var SLOT_IDS = [
718
+ "identity",
719
+ "instructions",
720
+ "style",
721
+ "reminder"
722
+ ];
723
+ var TAB_IDS = [
724
+ "basic",
725
+ "prompts",
726
+ "tools"
727
+ ];
728
+ var TAB_OF = {
729
+ name: "basic",
730
+ description: "basic",
731
+ startsSessions: "basic",
732
+ avatar: "basic",
733
+ tools: "tools",
734
+ "prompt.identity": "prompts",
735
+ "prompt.instructions": "prompts",
736
+ "prompt.style": "prompts",
737
+ "prompt.reminder": "prompts"
738
+ };
739
+ function same(key, a, b) {
740
+ if (key === "avatar") return a === null && b === null || typeof a === "string" && a === b;
741
+ return JSON.stringify(a) === JSON.stringify(b);
742
+ }
743
+ /** Which field a gateway refusal is about, when its words say so. */
744
+ function fieldOfRefusal(reason) {
745
+ const owner = /^extensionData[.:]([^:]+):/.exec(reason)?.[1];
746
+ if (owner) return `extension:${owner}`;
747
+ if (/avatar/i.test(reason)) return "avatar";
748
+ const slot = /prompt slot (identity|instructions|style|reminder)/i.exec(reason)?.[1];
749
+ if (slot) return `prompt.${slot.toLowerCase()}`;
750
+ if (/AGENTS\.md|rules file|instructions/i.test(reason)) return "prompt.instructions";
751
+ if (/start(s)? sessions|startsSessions/i.test(reason)) return "startsSessions";
752
+ if (/description/i.test(reason)) return "description";
753
+ if (/\btool/i.test(reason)) return "tools";
754
+ if (/\bname\b/i.test(reason) && !/no such agent/i.test(reason)) return "name";
755
+ return null;
756
+ }
757
+ var EditorContext = createContext(null);
758
+ function useAgentEditor() {
759
+ const editor = useContext(EditorContext);
760
+ if (editor === null) throw new Error("useAgentEditor outside an agent editor");
761
+ return editor;
762
+ }
763
+ /** The prompt text of one agent, asked again whenever that agent changes;
764
+ * an answer to an older question is dropped. */
765
+ function usePromptSlots(agentId) {
766
+ const read = useGatewayRead("config.agent.promptSlots", {
767
+ agentIds: [agentId],
768
+ maxItemBytes: 262144,
769
+ maxTotalBytes: 8388608
702
770
  });
703
- latest.current = {
704
- draft,
705
- saved,
706
- saving
771
+ const member = read.data?.results.find((member) => member.target === agentId);
772
+ return {
773
+ slots: member?.ok ? member.value : null,
774
+ error: read.error ?? (member && !member.ok ? member.error.message : null),
775
+ pending: read.pending,
776
+ reload: read.reload
707
777
  };
708
- const invalidated = useRef(false);
709
- const uncertain = useRef(false);
710
- const lifetime = useRef(null);
711
- const controller = useRef(null);
712
- const reload = useCallback(async (notify = false) => {
713
- controller.current?.abort();
714
- const request = new AbortController();
715
- controller.current = request;
716
- setReading(true);
717
- setReadError(null);
718
- try {
719
- const result = await gateway.read("config.limits.get", {}, { signal: request.signal });
720
- if (!request.signal.aborted) {
721
- setSaved(result.limits);
722
- setBlocked(false);
723
- if (uncertain.current) setSaveError(translation.current("runSettings.unconfirmed"));
724
- if (!(latest.current.draft !== null && JSON.stringify(latest.current.draft) !== JSON.stringify(latest.current.saved))) {
725
- setDraft(null);
726
- if (JSON.stringify(result.limits) !== JSON.stringify(latest.current.saved)) setInputKey((key) => key + 1);
727
- } else if (notify) setNotice("changed");
728
- return result.limits;
729
- }
730
- } catch (error) {
731
- if (!request.signal.aborted) {
732
- setReadError(error instanceof Error ? error.message : String(error));
733
- if (error instanceof Error && "errorCode" in error && error.errorCode === "configuration_recovery_required") setBlocked(true);
734
- }
735
- } finally {
736
- if (!request.signal.aborted) setReading(false);
737
- }
738
- return null;
739
- }, [gateway]);
778
+ }
779
+ function AgentEditorProvider({ agent: listed, agents, children }) {
780
+ const { slots, error: slotsError, pending: slotsPending, reload: reloadSlots } = usePromptSlots(listed.agentId);
781
+ const contributions = usePlugins((state) => state.contributions);
782
+ const preload = useBrowserService("tool-preload:configuration");
783
+ const preloadOwner = useRef(preload?.owner);
784
+ if (preload) preloadOwner.current = preload.owner;
785
+ const definitions = useGatewayRead("config.prompt.slots");
786
+ const saving = useGatewayAction();
787
+ const remember = useAgents((state) => state.remember);
788
+ const [drafts, setDrafts] = useState(/* @__PURE__ */ new Map());
789
+ const [errors, setErrors] = useState({});
790
+ const [footerError, setFooterError] = useState(null);
791
+ const [reply, setReply] = useState(null);
792
+ const [savedSlots, setSavedSlots] = useState({});
740
793
  useEffect(() => {
741
- lifetime.current = new AbortController();
742
- reload();
743
- return () => {
744
- controller.current?.abort();
745
- lifetime.current?.abort();
746
- };
747
- }, [reload]);
794
+ setReply(null);
795
+ }, [listed]);
748
796
  useEffect(() => {
749
- let previous = gateway.connection.status;
750
- const off = gateway.watchConnection((state) => {
751
- setOnline(state.status === "online");
752
- if (state.status === "online" && previous !== "online") reload(true);
753
- previous = state.status;
797
+ setSavedSlots({});
798
+ }, [slots]);
799
+ const agent = reply ?? listed;
800
+ const revisionBase = useRef(agent);
801
+ if (drafts.size === 0) revisionBase.current = agent;
802
+ const saved = useCallback((key) => {
803
+ if (key.startsWith("extension:")) return agent.extensionData?.[key.slice(10)];
804
+ if (key.startsWith("prompt.")) {
805
+ const slot = key.slice(7);
806
+ return savedSlots[slot] ?? slots?.[slot] ?? "";
807
+ }
808
+ return agent[key];
809
+ }, [
810
+ agent,
811
+ slots,
812
+ savedSlots
813
+ ]);
814
+ const dirty = useCallback((key) => {
815
+ const draft = drafts.get(key);
816
+ return draft !== void 0 && !same(key, draft.value, saved(key));
817
+ }, [drafts, saved]);
818
+ const value = useCallback((key) => dirty(key) ? drafts.get(key)?.value : saved(key), [
819
+ drafts,
820
+ dirty,
821
+ saved
822
+ ]);
823
+ const set = useCallback((key, next) => {
824
+ setDrafts((current) => {
825
+ const copy = new Map(current);
826
+ const base = current.get(key)?.base ?? saved(key);
827
+ if (same(key, next, saved(key))) copy.delete(key);
828
+ else copy.set(key, {
829
+ value: next,
830
+ base
831
+ });
832
+ return copy;
754
833
  });
755
- const stop = gateway.subscribe((frame) => {
756
- if (frame.kind !== "config.limitsChanged") return;
757
- if (latest.current.saving) invalidated.current = true;
758
- else reload(true);
834
+ setErrors((current) => {
835
+ if (!(key in current)) return current;
836
+ const { [key]: _, ...rest } = current;
837
+ return rest;
759
838
  });
760
- return () => {
761
- off();
762
- stop();
839
+ }, [saved]);
840
+ const stale = useCallback((key) => {
841
+ const draft = drafts.get(key);
842
+ return draft !== void 0 && dirty(key) && !same(key, draft.base, saved(key));
843
+ }, [
844
+ drafts,
845
+ dirty,
846
+ saved
847
+ ]);
848
+ const reload = useCallback((key) => {
849
+ setDrafts((current) => {
850
+ const copy = new Map(current);
851
+ copy.delete(key);
852
+ return copy;
853
+ });
854
+ }, []);
855
+ const limitOf = useCallback((slot) => definitions.data?.find((one) => one.id === slot)?.maxLength, [definitions.data]);
856
+ const invalid = useCallback((key) => {
857
+ if (!dirty(key)) return false;
858
+ const current = value(key);
859
+ if (key.startsWith("extension:")) {
860
+ const owner = key.slice(10);
861
+ if (owner === preloadOwner.current) {
862
+ if (!preload) return true;
863
+ try {
864
+ preload.read(current);
865
+ } catch {
866
+ return true;
867
+ }
868
+ }
869
+ return contributions.some((entry) => entry.plugin === owner && (entry.slot === "shell.agentEditor.field" || entry.slot === "shell.agentEditor.tab") && entry.contribution.validate?.(current) != null);
870
+ }
871
+ if (key === "name") return String(current).trim() === "";
872
+ if (key === "description") return codePoints(String(current)) > 500;
873
+ if (key.startsWith("prompt.")) {
874
+ const slot = key.slice(7);
875
+ const limit = limitOf(slot);
876
+ if (slot === "instructions" && slots?.failure !== void 0) return true;
877
+ return limit !== void 0 && codePoints(String(current)) > limit;
878
+ }
879
+ return false;
880
+ }, [
881
+ dirty,
882
+ value,
883
+ limitOf,
884
+ slots,
885
+ contributions,
886
+ preload
887
+ ]);
888
+ const dirtyKeys = [.../* @__PURE__ */ new Set([...Object.keys(TAB_OF), ...drafts.keys()])].filter((key) => dirty(key));
889
+ const dirtyTabs = [...new Set(dirtyKeys.map((key) => key.startsWith("extension:") ? (() => {
890
+ const tab = contributions.find((entry) => entry.plugin === key.slice(10) && entry.slot === "shell.agentEditor.tab");
891
+ if (key.slice(10) === preloadOwner.current) return "tools";
892
+ return tab ? `plugin:${tab.key}` : "basic";
893
+ })() : TAB_OF[key]))];
894
+ const canSave = dirtyKeys.length > 0 && !dirtyKeys.some(invalid) && !saving.pending;
895
+ const save = useCallback(async () => {
896
+ if (!canSave) return false;
897
+ const params = {
898
+ agentId: agent.agentId,
899
+ expectedRevision: revisionBase.current.revision,
900
+ expectedContentHash: revisionBase.current.contentHash
763
901
  };
764
- }, [gateway, reload]);
765
- const guardState = useRef({
766
- dirty: false,
767
- pending: false
768
- });
769
- guardState.current = {
770
- dirty: draft !== null && JSON.stringify(draft) !== JSON.stringify(saved),
771
- pending: saving
772
- };
773
- useEffect(() => {
774
- registerGuard(() => guardState.current);
775
- return () => registerGuard(null);
776
- }, [registerGuard]);
777
- const values = draft ?? saved;
778
- const positive = (value) => value !== void 0 && Number.isSafeInteger(value) && value > 0;
779
- async function save() {
780
- if (values === null || saving || !online || reading || readError !== null || !positive(values.maxSteps) || values.tokenBudget !== void 0 && !positive(values.tokenBudget)) return;
781
- let committed = false;
782
- setSaving(true);
783
- uncertain.current = false;
784
- setSaveError(null);
785
- try {
786
- const result = await gateway.call("config.limits.set", { limits: values }, {
787
- timeoutMs: 5e3,
788
- signal: lifetime.current?.signal
789
- });
790
- if (lifetime.current?.signal.aborted) return;
791
- controller.current?.abort();
792
- setReading(false);
793
- committed = true;
794
- setSaved(result.limits);
795
- setDraft(null);
796
- setNotice(null);
797
- toast.add({
798
- tone: "success",
799
- title: t("runSettings.saved")
800
- });
801
- } catch (error) {
802
- if (lifetime.current?.signal.aborted) return;
803
- const code = error instanceof Error && "errorCode" in error ? error.errorCode : void 0;
804
- const refused = error instanceof Error && "failure" in error && error.failure === "refused";
805
- if (code === "configuration_write_rejected" || refused && code !== "configuration_recovery_required") setSaveError(error instanceof Error ? error.message : String(error));
806
- else {
807
- uncertain.current = true;
808
- if (code === "configuration_recovery_required") setBlocked(true);
809
- setSaveError(t("runSettings.unconfirmedFailed"));
810
- await reload();
811
- }
812
- } finally {
813
- if (!lifetime.current?.signal.aborted) {
814
- setSaving(false);
815
- if (invalidated.current) {
816
- invalidated.current = false;
817
- reload(!committed);
818
- }
819
- }
902
+ const prompts = {};
903
+ for (const key of dirtyKeys) {
904
+ const current = value(key);
905
+ if (key === "name") params.name = String(current).trim();
906
+ else if (key === "description") params.description = String(current).trim();
907
+ else if (key === "startsSessions") params.startsSessions = current;
908
+ else if (key === "tools") params.tools = current === null ? null : [...current];
909
+ else if (key === "avatar") params.avatar = current === null ? null : current.image;
910
+ else if (key.startsWith("extension:")) params.extensionData = {
911
+ ...params.extensionData,
912
+ [key.slice(10)]: current
913
+ };
914
+ else prompts[key.slice(7)] = String(current);
820
915
  }
821
- }
822
- return /* @__PURE__ */ jsxs(Fragment, { children: [
823
- /* @__PURE__ */ jsx(ReadFailure, {
824
- reason: readError,
825
- pending: reading && values === null,
826
- onRetry: () => void reload()
827
- }),
828
- blocked && !reading && /* @__PURE__ */ jsx("p", {
829
- role: "alert",
830
- className: "text-xs text-destructive",
831
- children: t("runSettings.blocked")
916
+ if (Object.keys(prompts).length > 0) params.prompts = prompts;
917
+ setErrors({});
918
+ setFooterError(null);
919
+ const sent = new Map(dirtyKeys.map((key) => [key, drafts.get(key)]));
920
+ const result = await saving.run((client) => client.call("config.agent.save", params));
921
+ if (!result.ok) return false;
922
+ const avatarDraft = sent.get("avatar")?.value;
923
+ if (avatarDraft && result.data.avatar !== null) remember(result.data.avatar, avatarDraft.preview);
924
+ setReply(result.data);
925
+ setSavedSlots((current) => {
926
+ const next = { ...current };
927
+ for (const [slot, text] of Object.entries(prompts)) next[slot] = text.trim();
928
+ return next;
929
+ });
930
+ setDrafts((current) => {
931
+ const copy = new Map(current);
932
+ for (const [key, draft] of sent) if (copy.get(key) === draft) copy.delete(key);
933
+ return copy;
934
+ });
935
+ return true;
936
+ }, [
937
+ canSave,
938
+ agent.agentId,
939
+ dirtyKeys,
940
+ value,
941
+ drafts,
942
+ saving,
943
+ remember
944
+ ]);
945
+ const lastError = useRef(null);
946
+ useEffect(() => {
947
+ if (saving.error === lastError.current) return;
948
+ lastError.current = saving.error;
949
+ if (saving.error === null) return;
950
+ const field = fieldOfRefusal(saving.error);
951
+ if (field !== null && dirty(field)) setErrors({ [field]: saving.error });
952
+ else setFooterError(saving.error);
953
+ }, [saving.error, dirty]);
954
+ const discard = useCallback(() => {
955
+ setDrafts(/* @__PURE__ */ new Map());
956
+ setErrors({});
957
+ setFooterError(null);
958
+ }, []);
959
+ const editor = {
960
+ agent,
961
+ agents,
962
+ slots,
963
+ slotsError,
964
+ slotsPending,
965
+ reloadSlots,
966
+ slotDefinitions: definitions.data,
967
+ value,
968
+ set,
969
+ dirty,
970
+ stale,
971
+ invalid,
972
+ reload,
973
+ dirtyTabs,
974
+ error: (key) => errors[key] ?? null,
975
+ footerError,
976
+ pending: saving.pending,
977
+ canSave,
978
+ save,
979
+ extension: (owner) => ({
980
+ read: (fallback) => value(`extension:${owner}`) ?? fallback,
981
+ update: (next) => set(`extension:${owner}`, next),
982
+ pending: saving.pending,
983
+ tools: value("tools"),
984
+ error: errors[`extension:${owner}`] ?? (dirty(`extension:${owner}`) ? contributions.flatMap((entry) => entry.plugin === owner && (entry.slot === "shell.agentEditor.field" || entry.slot === "shell.agentEditor.tab") ? [entry.contribution.validate?.(value(`extension:${owner}`))] : []).find((message) => message != null) ?? null : null)
832
985
  }),
833
- values && /* @__PURE__ */ jsxs("form", {
834
- className: "flex flex-col gap-6",
835
- onSubmit: (event) => {
836
- event.preventDefault();
837
- save();
838
- },
839
- children: [
840
- /* @__PURE__ */ jsx("p", {
841
- className: "text-xs text-muted-foreground",
842
- children: t("runSettings.timing")
843
- }),
844
- /* @__PURE__ */ jsx(Field, {
845
- label: t("runSettings.maxSteps"),
846
- required: true,
847
- inline: true,
848
- error: positive(values.maxSteps) ? void 0 : t("runSettings.positive"),
849
- children: (binding) => /* @__PURE__ */ jsx(InputNumber, {
850
- ...binding,
851
- label: t("runSettings.maxSteps"),
852
- incrementLabel: t("common.increase"),
853
- decrementLabel: t("common.decrease"),
854
- min: 1,
855
- step: 1,
856
- disabled: saving,
857
- value: values.maxSteps || null,
858
- onValueChange: (value) => setDraft({
859
- ...values,
860
- maxSteps: value ?? 0
861
- })
862
- }, inputKey)
863
- }),
864
- /* @__PURE__ */ jsx(Field, {
865
- label: t("runSettings.budgetEnabled"),
866
- inline: true,
867
- children: (binding) => /* @__PURE__ */ jsx(Switch, {
868
- ...binding,
869
- checked: values.tokenBudget !== void 0,
870
- disabled: saving,
871
- onCheckedChange: (checked) => setDraft(checked ? {
872
- ...values,
873
- tokenBudget: 0
874
- } : { maxSteps: values.maxSteps })
875
- })
876
- }),
877
- values.tokenBudget !== void 0 && /* @__PURE__ */ jsx(Field, {
878
- label: t("runSettings.tokenBudget"),
879
- required: true,
880
- inline: true,
881
- error: positive(values.tokenBudget) ? void 0 : t("runSettings.positive"),
882
- children: (binding) => /* @__PURE__ */ jsx(InputNumber, {
883
- ...binding,
884
- label: t("runSettings.tokenBudget"),
885
- incrementLabel: t("common.increase"),
886
- decrementLabel: t("common.decrease"),
887
- min: 1,
888
- step: 1,
889
- disabled: saving,
890
- value: values.tokenBudget || null,
891
- onValueChange: (value) => setDraft({
892
- ...values,
893
- tokenBudget: value ?? 0
894
- })
895
- }, inputKey)
896
- }),
897
- notice && /* @__PURE__ */ jsx("p", {
898
- role: "status",
899
- className: "text-xs text-muted-foreground",
900
- children: t("runSettings.changed")
901
- }),
902
- /* @__PURE__ */ jsx(FormFailure, { reason: saveError }),
903
- uncertain.current && saved && readError === null && !reading && /* @__PURE__ */ jsx("p", {
904
- className: "text-xs text-muted-foreground",
905
- children: t("runSettings.current", {
906
- steps: saved.maxSteps,
907
- budget: saved.tokenBudget ?? t("runSettings.unlimited")
908
- })
909
- }),
910
- /* @__PURE__ */ jsx("div", {
911
- className: "flex justify-end",
912
- children: /* @__PURE__ */ jsx(Button, {
913
- variant: "primary",
914
- type: "submit",
915
- loading: saving,
916
- disabled: !online || reading || readError !== null || !positive(values.maxSteps) || values.tokenBudget !== void 0 && !positive(values.tokenBudget),
917
- children: t("common.save")
918
- })
919
- })
920
- ]
921
- })
922
- ] });
986
+ discard
987
+ };
988
+ return /* @__PURE__ */ jsx(EditorContext.Provider, {
989
+ value: editor,
990
+ children
991
+ });
923
992
  }
924
993
  //#endregion
925
- //#region ui-src/components/settings/run-settings.tsx
926
- /** Fixed global running-settings entrance owned by Agent management. */
927
- function RunSettingsButton({ ctx }) {
994
+ //#region ui-src/components/settings/agent/parts.tsx
995
+ /** Pieces shared by the agent editor's tabs. */
996
+ /** Says a field with a draft was changed elsewhere, and takes the new value
997
+ * on request. Renders nothing while none of `fields` is stale. */
998
+ function ChangedElsewhere({ fields }) {
928
999
  const { t } = useTranslation();
929
- const [open, setOpen] = useState(false);
930
- return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(TooltipHint, {
931
- content: t("runSettings.title"),
932
- children: /* @__PURE__ */ jsx(Button, {
933
- variant: "plain",
934
- size: "sm",
935
- icon: "settings",
936
- "aria-label": t("runSettings.title"),
937
- onClick: () => setOpen(true)
938
- })
939
- }), open && /* @__PURE__ */ jsx(RunSettingsDialog, {
940
- ctx,
941
- onClose: () => setOpen(false)
942
- })] });
1000
+ const editor = useAgentEditor();
1001
+ const stale = fields.filter((key) => editor.stale(key));
1002
+ if (stale.length === 0) return null;
1003
+ return /* @__PURE__ */ jsx(Alert, {
1004
+ tone: "warning",
1005
+ variant: "soft",
1006
+ "data-slot": "agent-changed-elsewhere",
1007
+ className: "text-xs",
1008
+ children: /* @__PURE__ */ jsxs("div", {
1009
+ className: "flex flex-wrap items-start justify-between gap-3",
1010
+ children: [/* @__PURE__ */ jsx("span", { children: t("agents.changedElsewhere") }), /* @__PURE__ */ jsx(Button, {
1011
+ size: "sm",
1012
+ variant: "ghost",
1013
+ onClick: () => {
1014
+ for (const key of stale) editor.reload(key);
1015
+ },
1016
+ children: t("agents.loadRemote")
1017
+ })]
1018
+ })
1019
+ });
943
1020
  }
944
- /** One retained page per live owner, with a shared close guard and independent saves. */
945
- function RunSettingsDialog({ ctx, onClose }) {
1021
+ //#endregion
1022
+ //#region ui-src/components/settings/agent/basic.tsx
1023
+ /**
1024
+ * The basic-information tab: picture, name, description and the
1025
+ * model cell. Every field, the model cell's included, is part of the editor's
1026
+ * one draft. Whether a person can chat with the agent directly is a toggle on
1027
+ * the agent list, not here.
1028
+ *
1029
+ * The picture is its own upload control: pressing it picks an image, and the
1030
+ * crop shows in place until the save. While the agent has a picture — saved,
1031
+ * or a crop waiting for the save — 恢复默认 beside it drafts the return to the
1032
+ * derived letters face, which the same save applies.
1033
+ */
1034
+ /** The factory agent, whose session switch the gateway keeps on. */
1035
+ function AvatarField() {
946
1036
  const { t } = useTranslation();
947
- const state = usePlugins((state) => state);
948
- const pages = contributionsIn(state, "shell.agentRunSettings.section");
949
- const [selected, setSelected] = useState("execution");
950
- const shown = selected === "execution" || pages.some((page) => page.key === selected) ? selected : "execution";
951
- useEffect(() => {
952
- if (shown !== selected) setSelected(shown);
953
- }, [shown, selected]);
954
- const guards = useRef(/* @__PURE__ */ new Map());
955
- const register = useCallback((key, guard) => {
956
- if (guard) guards.current.set(key, guard);
957
- else guards.current.delete(key);
958
- }, []);
959
- const labels = new Map([["execution", t("runSettings.execution")], ...pages.map((page) => [page.key, resolveLabel(page.contribution.label, page.key)])]);
960
- const [asking, setAsking] = useState(null);
961
- const requestClose = () => {
962
- const valid = [...guards.current].filter(([key]) => labels.has(key));
963
- if (valid.some(([, guard]) => guard().pending)) return;
964
- const dirty = valid.filter(([, guard]) => guard().dirty).map(([key]) => key);
965
- if (dirty.length > 0) setAsking(dirty);
966
- else onClose();
967
- };
968
- const executionGuard = useCallback((guard) => register("execution", guard), [register]);
969
- return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Dialog, {
970
- open: true,
971
- onOpenChange: (next) => {
972
- if (!next) requestClose();
973
- },
974
- children: /* @__PURE__ */ jsxs(DialogContent, {
975
- closeLabel: t("settings.close"),
976
- overlayProps: {
977
- forceRender: true,
978
- className: "file-picker-backdrop"
979
- },
980
- className: "@container max-w-md gap-5 p-6 sm:max-w-md",
981
- children: [/* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: t("runSettings.title") }) }), /* @__PURE__ */ jsxs(Tabs, {
982
- value: shown,
983
- onValueChange: (next) => setSelected(String(next)),
984
- children: [
985
- /* @__PURE__ */ jsxs(TabsList, {
986
- "aria-label": t("runSettings.title"),
987
- className: "mb-5 w-full",
988
- children: [/* @__PURE__ */ jsx(TabsTrigger, {
989
- value: "execution",
990
- children: t("runSettings.execution")
991
- }), pages.map((page) => /* @__PURE__ */ jsx(TabsTrigger, {
992
- value: page.key,
993
- "data-plugin": page.owner,
994
- children: labels.get(page.key)
995
- }, page.key))]
996
- }),
997
- /* @__PURE__ */ jsx(TabsContent, {
998
- value: "execution",
999
- keepMounted: true,
1000
- children: /* @__PURE__ */ jsx(ExecutionLimits, {
1001
- ctx,
1002
- registerGuard: executionGuard,
1003
- requestClose
1004
- })
1037
+ const editor = useAgentEditor();
1038
+ const { agent } = editor;
1039
+ const picker = useAvatarPicker((base64) => {
1040
+ editor.set("avatar", {
1041
+ image: base64,
1042
+ preview: pngDataUrl(base64)
1043
+ });
1044
+ });
1045
+ const draft = editor.dirty("avatar") ? editor.value("avatar") : void 0;
1046
+ const pictured = draft === void 0 ? agent.avatar !== null : draft !== null;
1047
+ return /* @__PURE__ */ jsxs(Panel, {
1048
+ title: t("agents.avatar"),
1049
+ level: "field",
1050
+ inline: true,
1051
+ children: [
1052
+ /* @__PURE__ */ jsxs("div", {
1053
+ className: "flex min-w-0 items-center",
1054
+ children: [/* @__PURE__ */ jsxs(Tooltip, { children: [/* @__PURE__ */ jsxs(TooltipTrigger, {
1055
+ render: /* @__PURE__ */ jsx(Button, {
1056
+ variant: "plain",
1057
+ "data-slot": "agent-avatar-trigger",
1058
+ className: "group relative size-11 shrink-0 cursor-pointer rounded-pill outline-none focus-visible:ring-3 focus-visible:ring-ring/50",
1059
+ onClick: () => void picker.pick()
1005
1060
  }),
1006
- pages.map((page) => /* @__PURE__ */ jsx(TabsContent, {
1007
- value: page.key,
1008
- keepMounted: true,
1009
- children: /* @__PURE__ */ jsx(OwnerSection, {
1010
- registrationKey: page.key,
1011
- register,
1012
- requestClose
1061
+ "aria-label": t("avatar.change"),
1062
+ children: [/* @__PURE__ */ jsx(AgentAvatar, {
1063
+ agentId: agent.agentId,
1064
+ name: editor.value("name") || agent.name,
1065
+ avatar: draft === null ? null : agent.avatar,
1066
+ ...draft ? { src: draft.preview } : {},
1067
+ size: "lg",
1068
+ decorative: true,
1069
+ className: "size-11 text-sm"
1070
+ }), /* @__PURE__ */ jsx("span", {
1071
+ "data-slot": "agent-avatar-overlay",
1072
+ "aria-hidden": "true",
1073
+ className: "absolute inset-0 grid place-items-center rounded-pill bg-foreground/60 text-background opacity-0 transition-opacity duration-150 group-hover:opacity-100 group-focus-visible:opacity-100",
1074
+ children: /* @__PURE__ */ jsx(Camera, {
1075
+ className: "size-4",
1076
+ strokeWidth: 1.75
1013
1077
  })
1014
- }, page.key))
1015
- ]
1016
- })]
1017
- })
1018
- }), /* @__PURE__ */ jsxs(AlertDialog, {
1019
- open: asking !== null,
1020
- onOpenChange: (next) => {
1021
- if (!next) setAsking(null);
1022
- },
1023
- title: t("agents.leaveTitle"),
1024
- actions: /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Button, {
1025
- variant: "ghost",
1026
- onClick: () => setAsking(null),
1027
- children: t("agents.leaveStay")
1028
- }), /* @__PURE__ */ jsx(Button, {
1029
- variant: "destructive",
1030
- onClick: onClose,
1031
- children: t("agents.discard")
1032
- })] }),
1033
- children: [/* @__PURE__ */ jsx("p", { children: t("agents.leaveBody") }), /* @__PURE__ */ jsx("ul", {
1034
- className: "list-disc ps-5",
1035
- children: asking?.filter((key) => labels.has(key)).map((key) => /* @__PURE__ */ jsx("li", { children: labels.get(key) }, key))
1036
- })]
1037
- })] });
1078
+ })]
1079
+ }), /* @__PURE__ */ jsx(TooltipContent, {
1080
+ side: "top",
1081
+ children: t("avatar.change")
1082
+ })] }), pictured && /* @__PURE__ */ jsx(Button, {
1083
+ variant: "ghost",
1084
+ size: "sm",
1085
+ "data-slot": "agent-avatar-reset",
1086
+ className: "ml-3",
1087
+ onClick: () => {
1088
+ picker.clearRefusal();
1089
+ editor.set("avatar", null);
1090
+ },
1091
+ children: t("avatar.reset")
1092
+ })]
1093
+ }),
1094
+ /* @__PURE__ */ jsx(FormFailure, { reason: picker.refusal ?? editor.error("avatar") }),
1095
+ picker.dialog
1096
+ ]
1097
+ });
1038
1098
  }
1039
- function OwnerSection({ registrationKey, register, requestClose }) {
1040
- const registerGuard = useCallback((guard) => register(registrationKey, guard), [registrationKey, register]);
1041
- useEffect(() => () => registerGuard(null), [registerGuard]);
1042
- return /* @__PURE__ */ jsx(SlotOutlet, {
1043
- slot: "shell.agentRunSettings.section",
1044
- only: registrationKey,
1045
- props: {
1046
- registerGuard,
1047
- requestClose
1048
- }
1099
+ function BasicTab() {
1100
+ const { t } = useTranslation();
1101
+ const editor = useAgentEditor();
1102
+ const { agent } = editor;
1103
+ const name = editor.value("name");
1104
+ const description = editor.value("description");
1105
+ const pluginState = usePlugins((state) => state);
1106
+ const registrations = contributionsIn(pluginState, "shell.agentEditor.field");
1107
+ return /* @__PURE__ */ jsxs("div", {
1108
+ className: "flex min-w-0 flex-col gap-5",
1109
+ children: [
1110
+ /* @__PURE__ */ jsx(ChangedElsewhere, { fields: [
1111
+ "name",
1112
+ "description",
1113
+ "avatar",
1114
+ ...registrations.map((one) => `extension:${one.plugin}`)
1115
+ ] }),
1116
+ /* @__PURE__ */ jsx(AvatarField, {}),
1117
+ /* @__PURE__ */ jsx(Field, {
1118
+ label: t("agents.name"),
1119
+ required: true,
1120
+ inline: true,
1121
+ className: "settings-field-row",
1122
+ error: editor.error("name") ?? (editor.invalid("name") ? t("agents.nameRequired") : void 0),
1123
+ children: (binding) => /* @__PURE__ */ jsx(Input, {
1124
+ ...binding,
1125
+ value: name,
1126
+ placeholder: t("agents.namePlaceholder"),
1127
+ onChange: (event) => editor.set("name", event.target.value),
1128
+ onKeyDown: (event) => {
1129
+ if (event.key === "Escape" && !event.nativeEvent.isComposing) editor.reload("name");
1130
+ }
1131
+ })
1132
+ }),
1133
+ /* @__PURE__ */ jsx(Field, {
1134
+ label: t("agents.description"),
1135
+ inline: true,
1136
+ className: "settings-field-row",
1137
+ error: editor.error("description") ?? (editor.invalid("description") ? t("agents.descriptionTooLong", { limit: 500 }) : void 0),
1138
+ children: (binding) => /* @__PURE__ */ jsx(Textarea, {
1139
+ ...binding,
1140
+ limit: 500,
1141
+ rows: 5,
1142
+ className: "h-[calc(5lh+1rem)] resize-none [field-sizing:fixed]",
1143
+ value: description,
1144
+ placeholder: t("agents.descriptionPlaceholder"),
1145
+ onChange: (event) => editor.set("description", event.target.value)
1146
+ })
1147
+ }),
1148
+ registrations.map((one) => /* @__PURE__ */ jsx(SlotOutlet, {
1149
+ slot: "shell.agentEditor.field",
1150
+ only: one.key,
1151
+ props: {
1152
+ agentId: agent.agentId,
1153
+ editor: editor.extension(one.plugin),
1154
+ errors: { owner: editor.error(`extension:${one.plugin}`) }
1155
+ }
1156
+ }, one.key))
1157
+ ]
1049
1158
  });
1050
1159
  }
1051
1160
  //#endregion
1052
- //#region ui-src/components/settings/agent/editor.tsx
1053
- var SLOT_IDS = [
1161
+ //#region ui-src/components/settings/agent/prompts.tsx
1162
+ /**
1163
+ * The prompt tab: the four slots, one edited at a time, listed as identity,
1164
+ * style, reminder, AGENTS.md — the slots `config.prompt.slots` declares, in
1165
+ * this tab's own order, with their limits from that listing. Each slot keeps
1166
+ * its own draft in the editor, so switching slots asks nothing; the text area
1167
+ * fills the tab and is its only scroller. Above the text area the chosen
1168
+ * slot says what to write there and where the text lands in the model's input.
1169
+ */
1170
+ /** A dot that says a slot or tab has an unsaved change, to eyes and ears. */
1171
+ /** The slot's identifier as the list's second line. Identifiers, not copy:
1172
+ * the same in every language. Only AGENTS.md is a file. */
1173
+ var SLOT_TAGS = {
1174
+ identity: "IDENTITY Slot",
1175
+ style: "SOUL Slot",
1176
+ reminder: "REMINDER Slot",
1177
+ instructions: "AGENTS.md"
1178
+ };
1179
+ function UnsavedDot() {
1180
+ const { t } = useTranslation();
1181
+ return /* @__PURE__ */ jsxs("span", {
1182
+ "data-slot": "unsaved-dot",
1183
+ className: "inline-flex shrink-0 items-center",
1184
+ children: [/* @__PURE__ */ jsx("span", {
1185
+ "aria-hidden": "true",
1186
+ className: "size-1.5 rounded-pill bg-primary"
1187
+ }), /* @__PURE__ */ jsx("span", {
1188
+ className: "sr-only",
1189
+ children: t("agents.unsaved")
1190
+ })]
1191
+ });
1192
+ }
1193
+ /** The order this tab lists the slots in. */
1194
+ var DISPLAY_ORDER = [
1054
1195
  "identity",
1055
- "instructions",
1056
1196
  "style",
1057
- "reminder"
1197
+ "reminder",
1198
+ "instructions"
1058
1199
  ];
1059
- var TAB_IDS = [
1060
- "basic",
1061
- "prompts",
1062
- "tools"
1200
+ var NOTES = [
1201
+ "where",
1202
+ "scope",
1203
+ "cache",
1204
+ "tip"
1063
1205
  ];
1064
- var TAB_OF = {
1065
- name: "basic",
1066
- description: "basic",
1067
- startsSessions: "basic",
1068
- avatar: "basic",
1069
- tools: "tools",
1070
- "prompt.identity": "prompts",
1071
- "prompt.instructions": "prompts",
1072
- "prompt.style": "prompts",
1073
- "prompt.reminder": "prompts"
1074
- };
1075
- function same(key, a, b) {
1076
- if (key === "avatar") return a === null && b === null || typeof a === "string" && a === b;
1077
- return JSON.stringify(a) === JSON.stringify(b);
1078
- }
1079
- /** Which field a gateway refusal is about, when its words say so. */
1080
- function fieldOfRefusal(reason) {
1081
- const owner = /^extensionData[.:]([^:]+):/.exec(reason)?.[1];
1082
- if (owner) return `extension:${owner}`;
1083
- if (/avatar/i.test(reason)) return "avatar";
1084
- const slot = /prompt slot (identity|instructions|style|reminder)/i.exec(reason)?.[1];
1085
- if (slot) return `prompt.${slot.toLowerCase()}`;
1086
- if (/AGENTS\.md|rules file|instructions/i.test(reason)) return "prompt.instructions";
1087
- if (/start(s)? sessions|startsSessions/i.test(reason)) return "startsSessions";
1088
- if (/description/i.test(reason)) return "description";
1089
- if (/\btool/i.test(reason)) return "tools";
1090
- if (/\bname\b/i.test(reason) && !/no such agent/i.test(reason)) return "name";
1091
- return null;
1092
- }
1093
- var EditorContext = createContext(null);
1094
- function useAgentEditor() {
1095
- const editor = useContext(EditorContext);
1096
- if (editor === null) throw new Error("useAgentEditor outside an agent editor");
1097
- return editor;
1206
+ /** What the chosen slot is for and where it goes, shown above its editor for
1207
+ * as long as it is chosen: the purpose with an example, then the placement. */
1208
+ function SlotAbout({ slot, limit, path }) {
1209
+ const { t } = useTranslation();
1210
+ return /* @__PURE__ */ jsxs("section", {
1211
+ "aria-label": t("agents.prompts.about", { slot: t(`agents.prompts.${slot}`) }),
1212
+ "data-slot": "prompt-slot-about",
1213
+ className: "flex shrink-0 flex-col gap-2 rounded-control bg-muted/60 px-3 py-2.5 text-xs leading-relaxed @xl:flex-row @xl:gap-6",
1214
+ children: [/* @__PURE__ */ jsxs("div", {
1215
+ className: "flex min-w-0 flex-col gap-1 @xl:flex-1",
1216
+ children: [
1217
+ /* @__PURE__ */ jsx("h4", {
1218
+ className: "font-medium text-foreground",
1219
+ children: t("agents.prompts.purpose")
1220
+ }),
1221
+ /* @__PURE__ */ jsx("p", {
1222
+ className: "text-muted-foreground",
1223
+ children: t(`agents.prompts.info.${slot}.purpose`)
1224
+ }),
1225
+ /* @__PURE__ */ jsx("p", {
1226
+ className: "text-muted-foreground",
1227
+ children: t("agents.prompts.example", { text: t(`agents.prompts.info.${slot}.example`) })
1228
+ })
1229
+ ]
1230
+ }), /* @__PURE__ */ jsxs("div", {
1231
+ className: "flex min-w-0 flex-col gap-1 @xl:flex-1",
1232
+ children: [/* @__PURE__ */ jsx("h4", {
1233
+ className: "font-medium text-foreground",
1234
+ children: t("agents.prompts.placement")
1235
+ }), /* @__PURE__ */ jsx("ul", {
1236
+ className: "flex list-disc flex-col gap-0.5 ps-4 text-muted-foreground",
1237
+ children: NOTES.map((note) => /* @__PURE__ */ jsx("li", {
1238
+ className: "break-words",
1239
+ children: t(`agents.prompts.info.${slot}.${note}`, {
1240
+ path,
1241
+ limit: limit ?? ""
1242
+ })
1243
+ }, note))
1244
+ })]
1245
+ })]
1246
+ });
1098
1247
  }
1099
- /** The prompt text of one agent, asked again whenever that agent changes;
1100
- * an answer to an older question is dropped. */
1101
- function usePromptSlots(agentId) {
1102
- const read = useGatewayRead("config.agent.promptSlots", { agentId });
1103
- return {
1104
- slots: read.data,
1105
- error: read.error,
1106
- pending: read.pending,
1107
- reload: read.reload
1108
- };
1248
+ function PromptsTab() {
1249
+ const { t } = useTranslation();
1250
+ const editor = useAgentEditor();
1251
+ const declared = editor.slotDefinitions?.map((one) => one.id);
1252
+ const order = DISPLAY_ORDER.filter((id) => declared?.includes(id) ?? true);
1253
+ const [picked, setPicked] = useState(order[0] ?? "identity");
1254
+ const slot = order.includes(picked) ? picked : order[0] ?? "identity";
1255
+ const key = `prompt.${slot}`;
1256
+ const limit = editor.slotDefinitions?.find((one) => one.id === slot)?.maxLength;
1257
+ const failure = slot === "instructions" ? editor.slots?.failure : void 0;
1258
+ const label = (id) => t(`agents.prompts.${id}`);
1259
+ const rulesPath = editor.slots?.path ?? `agents/${editor.agent.agentId}/AGENTS.md`;
1260
+ if (editor.slots === null) return /* @__PURE__ */ jsx(ReadFailure, {
1261
+ reason: editor.slotsError,
1262
+ pending: editor.slotsPending,
1263
+ onRetry: editor.reloadSlots
1264
+ });
1265
+ return /* @__PURE__ */ jsxs("div", {
1266
+ className: "@container flex min-h-0 min-w-0 flex-1 flex-col gap-3",
1267
+ children: [/* @__PURE__ */ jsx(ChangedElsewhere, { fields: SLOT_IDS.map((id) => `prompt.${id}`) }), /* @__PURE__ */ jsxs("div", {
1268
+ className: "flex min-h-0 min-w-0 flex-1 flex-col gap-4 @2xl:flex-row",
1269
+ children: [
1270
+ /* @__PURE__ */ jsx("nav", {
1271
+ "aria-label": t("agents.prompts.slots"),
1272
+ "data-slot": "prompt-slot-list",
1273
+ className: "hidden w-52 shrink-0 flex-col gap-1 @2xl:flex",
1274
+ children: order.map((id) => /* @__PURE__ */ jsx("div", {
1275
+ "data-slot": "prompt-slot",
1276
+ className: cn("flex min-w-0 items-center gap-1 rounded-control pe-1", id === slot ? "bg-accent text-accent-foreground" : "hover:bg-muted"),
1277
+ children: /* @__PURE__ */ jsxs(Button, {
1278
+ variant: "plain",
1279
+ "data-slot": "prompt-slot-select",
1280
+ "aria-current": id === slot,
1281
+ onClick: () => setPicked(id),
1282
+ className: "flex h-auto min-w-0 flex-1 items-center justify-start gap-2 px-3 py-1.5 text-left",
1283
+ children: [/* @__PURE__ */ jsxs("span", {
1284
+ className: "flex min-w-0 flex-col",
1285
+ children: [/* @__PURE__ */ jsx("span", {
1286
+ className: "truncate text-sm font-medium",
1287
+ children: label(id)
1288
+ }), /* @__PURE__ */ jsx("span", {
1289
+ className: "truncate font-mono text-2xs text-muted-foreground",
1290
+ children: SLOT_TAGS[id]
1291
+ })]
1292
+ }), editor.dirty(`prompt.${id}`) && /* @__PURE__ */ jsx(UnsavedDot, {})]
1293
+ })
1294
+ }, id))
1295
+ }),
1296
+ /* @__PURE__ */ jsx("div", {
1297
+ "data-slot": "prompt-slot-switch",
1298
+ className: "min-w-0 @2xl:hidden",
1299
+ children: /* @__PURE__ */ jsx(Segmented, {
1300
+ fullWidth: true,
1301
+ label: t("agents.prompts.slots"),
1302
+ value: slot,
1303
+ options: order.map((id) => ({
1304
+ value: id,
1305
+ label: editor.dirty(`prompt.${id}`) ? `${label(id)} •` : label(id)
1306
+ })),
1307
+ onSelect: setPicked
1308
+ })
1309
+ }),
1310
+ /* @__PURE__ */ jsxs("section", {
1311
+ "aria-label": label(slot),
1312
+ "data-slot": "prompt-editor",
1313
+ className: "flex min-h-0 min-w-0 flex-1 flex-col gap-2",
1314
+ children: [
1315
+ /* @__PURE__ */ jsx(SlotAbout, {
1316
+ slot,
1317
+ limit,
1318
+ path: rulesPath
1319
+ }),
1320
+ failure !== void 0 && /* @__PURE__ */ jsx(Failure, { reason: t("agents.prompts.readFailed", { reason: failure }) }),
1321
+ /* @__PURE__ */ jsx(Textarea, {
1322
+ "aria-label": label(slot),
1323
+ fill: true,
1324
+ ...limit === void 0 ? {} : { limit },
1325
+ readOnly: failure !== void 0,
1326
+ value: editor.value(key),
1327
+ onChange: (event) => editor.set(key, event.target.value),
1328
+ className: "font-mono"
1329
+ }, slot),
1330
+ /* @__PURE__ */ jsx(FormFailure, { reason: editor.error(key) })
1331
+ ]
1332
+ })
1333
+ ]
1334
+ })]
1335
+ });
1109
1336
  }
1110
- function AgentEditorProvider({ agent: listed, agents, children }) {
1111
- const { slots, error: slotsError, pending: slotsPending, reload: reloadSlots } = usePromptSlots(listed.agentId);
1112
- const contributions = usePlugins((state) => state.contributions);
1113
- const definitions = useGatewayRead("config.prompt.slots");
1114
- const saving = useGatewayAction();
1115
- const remember = useAgents((state) => state.remember);
1116
- const [drafts, setDrafts] = useState(/* @__PURE__ */ new Map());
1117
- const [errors, setErrors] = useState({});
1118
- const [footerError, setFooterError] = useState(null);
1119
- const [reply, setReply] = useState(null);
1120
- const [savedSlots, setSavedSlots] = useState({});
1121
- useEffect(() => {
1122
- setReply(null);
1123
- }, [listed]);
1124
- useEffect(() => {
1125
- setSavedSlots({});
1126
- }, [slots]);
1127
- const agent = reply ?? listed;
1128
- const revisionBase = useRef(agent);
1129
- if (drafts.size === 0) revisionBase.current = agent;
1130
- const saved = useCallback((key) => {
1131
- if (key.startsWith("extension:")) return agent.extensionData?.[key.slice(10)];
1132
- if (key.startsWith("prompt.")) {
1133
- const slot = key.slice(7);
1134
- return savedSlots[slot] ?? slots?.[slot] ?? "";
1135
- }
1136
- return agent[key];
1137
- }, [
1138
- agent,
1139
- slots,
1140
- savedSlots
1141
- ]);
1142
- const dirty = useCallback((key) => {
1143
- const draft = drafts.get(key);
1144
- return draft !== void 0 && !same(key, draft.value, saved(key));
1145
- }, [drafts, saved]);
1146
- const value = useCallback((key) => dirty(key) ? drafts.get(key)?.value : saved(key), [
1147
- drafts,
1148
- dirty,
1149
- saved
1150
- ]);
1151
- const set = useCallback((key, next) => {
1152
- setDrafts((current) => {
1153
- const copy = new Map(current);
1154
- const base = current.get(key)?.base ?? saved(key);
1155
- if (same(key, next, saved(key))) copy.delete(key);
1156
- else copy.set(key, {
1157
- value: next,
1158
- base
1337
+ //#endregion
1338
+ //#region ui-src/components/settings/agent/revisions.tsx
1339
+ /** Compact history with explicit comparison and a retryable restore confirmation. */
1340
+ function AgentRevisions({ agentId, onClose, beforeLeave }) {
1341
+ const { t, i18n } = useTranslation();
1342
+ const client = useGateway();
1343
+ const observedRevision = useAgents((state) => state.agents.find((agent) => agent.agentId === agentId)?.revision);
1344
+ const [items, setItems] = useState([]);
1345
+ const [current, setCurrent] = useState(0);
1346
+ const [cursor, setCursor] = useState();
1347
+ const [selected, setSelected] = useState();
1348
+ const [compareTo, setCompareTo] = useState();
1349
+ const [changes, setChanges] = useState([]);
1350
+ const [comparing, setComparing] = useState(false);
1351
+ const [comparisonError, setComparisonError] = useState("");
1352
+ const [preview, setPreview] = useState();
1353
+ const [request, setRequest] = useState();
1354
+ const [busy, setBusy] = useState(false);
1355
+ const [error, setError] = useState("");
1356
+ const [notice, setNotice] = useState("");
1357
+ const [persistent, setPersistent] = useState(true);
1358
+ const generation = useRef(0);
1359
+ const restoring = useRef(false);
1360
+ const comparison = useRef(0);
1361
+ const reason = (cause) => failureText(cause, () => "") ?? "";
1362
+ const read = useCallback(async (next) => {
1363
+ const token = ++generation.current;
1364
+ setBusy(true);
1365
+ setError("");
1366
+ try {
1367
+ const page = await client.call("config.agent.revisions", {
1368
+ agentId,
1369
+ ...next ? { cursor: next } : {}
1159
1370
  });
1160
- return copy;
1161
- });
1162
- setErrors((current) => {
1163
- if (!(key in current)) return current;
1164
- const { [key]: _, ...rest } = current;
1165
- return rest;
1166
- });
1167
- }, [saved]);
1168
- const stale = useCallback((key) => {
1169
- const draft = drafts.get(key);
1170
- return draft !== void 0 && dirty(key) && !same(key, draft.base, saved(key));
1171
- }, [
1172
- drafts,
1173
- dirty,
1174
- saved
1175
- ]);
1176
- const reload = useCallback((key) => {
1177
- setDrafts((current) => {
1178
- const copy = new Map(current);
1179
- copy.delete(key);
1180
- return copy;
1181
- });
1182
- }, []);
1183
- const limitOf = useCallback((slot) => definitions.data?.find((one) => one.id === slot)?.maxLength, [definitions.data]);
1184
- const invalid = useCallback((key) => {
1185
- if (!dirty(key)) return false;
1186
- const current = value(key);
1187
- if (key.startsWith("extension:")) {
1188
- const owner = key.slice(10);
1189
- return contributions.some((entry) => entry.plugin === owner && (entry.slot === "shell.agentEditor.field" || entry.slot === "shell.agentEditor.tab") && entry.contribution.validate?.(current) != null);
1190
- }
1191
- if (key === "name") return String(current).trim() === "";
1192
- if (key === "description") return codePoints(String(current)) > 500;
1193
- if (key.startsWith("prompt.")) {
1194
- const slot = key.slice(7);
1195
- const limit = limitOf(slot);
1196
- if (slot === "instructions" && slots?.failure !== void 0) return true;
1197
- return limit !== void 0 && codePoints(String(current)) > limit;
1371
+ if (generation.current !== token) return;
1372
+ setItems((old) => next ? [...old, ...page.items.filter((row) => !old.some((item) => item.revision === row.revision))] : page.items);
1373
+ setCurrent(page.currentRevision);
1374
+ setCursor(page.nextCursor);
1375
+ setPersistent(page.persistent);
1376
+ } catch (cause) {
1377
+ if (generation.current === token) setError(reason(cause));
1378
+ } finally {
1379
+ if (generation.current === token) setBusy(false);
1198
1380
  }
1199
- return false;
1200
- }, [
1201
- dirty,
1202
- value,
1203
- limitOf,
1204
- slots,
1205
- contributions
1206
- ]);
1207
- const dirtyKeys = [.../* @__PURE__ */ new Set([...Object.keys(TAB_OF), ...drafts.keys()])].filter((key) => dirty(key));
1208
- const dirtyTabs = [...new Set(dirtyKeys.map((key) => key.startsWith("extension:") ? (() => {
1209
- const tab = contributions.find((entry) => entry.plugin === key.slice(10) && entry.slot === "shell.agentEditor.tab");
1210
- return tab ? `plugin:${tab.key}` : "basic";
1211
- })() : TAB_OF[key]))];
1212
- const canSave = dirtyKeys.length > 0 && !dirtyKeys.some(invalid) && !saving.pending;
1213
- const save = useCallback(async () => {
1214
- if (!canSave) return false;
1215
- const params = {
1216
- agentId: agent.agentId,
1217
- expectedRevision: revisionBase.current.revision,
1218
- expectedContentHash: revisionBase.current.contentHash
1381
+ }, [client, agentId]);
1382
+ useEffect(() => {
1383
+ read();
1384
+ return () => {
1385
+ generation.current++;
1386
+ comparison.current++;
1219
1387
  };
1220
- const prompts = {};
1221
- for (const key of dirtyKeys) {
1222
- const current = value(key);
1223
- if (key === "name") params.name = String(current).trim();
1224
- else if (key === "description") params.description = String(current).trim();
1225
- else if (key === "startsSessions") params.startsSessions = current;
1226
- else if (key === "tools") params.tools = current === null ? null : [...current];
1227
- else if (key === "avatar") params.avatar = current === null ? null : current.image;
1228
- else if (key.startsWith("extension:")) params.extensionData = {
1229
- ...params.extensionData,
1230
- [key.slice(10)]: current
1231
- };
1232
- else prompts[key.slice(7)] = String(current);
1233
- }
1234
- if (Object.keys(prompts).length > 0) params.prompts = prompts;
1235
- setErrors({});
1236
- setFooterError(null);
1237
- const sent = new Map(dirtyKeys.map((key) => [key, drafts.get(key)]));
1238
- const result = await saving.run((client) => client.call("config.agent.save", params));
1239
- if (!result.ok) return false;
1240
- const avatarDraft = sent.get("avatar")?.value;
1241
- if (avatarDraft && result.data.avatar !== null) remember(result.data.avatar, avatarDraft.preview);
1242
- setReply(result.data);
1243
- setSavedSlots((current) => {
1244
- const next = { ...current };
1245
- for (const [slot, text] of Object.entries(prompts)) next[slot] = text.trim();
1246
- return next;
1388
+ }, [read, observedRevision]);
1389
+ useEffect(() => {
1390
+ let previous = client.connection.status;
1391
+ return client.watchConnection((connection) => {
1392
+ if (connection.status === "online" && previous !== "online") read();
1393
+ previous = connection.status;
1247
1394
  });
1248
- setDrafts((current) => {
1249
- const copy = new Map(current);
1250
- for (const [key, draft] of sent) if (copy.get(key) === draft) copy.delete(key);
1251
- return copy;
1395
+ }, [client, read]);
1396
+ useEffect(() => {
1397
+ const token = ++comparison.current;
1398
+ setChanges([]);
1399
+ setComparisonError("");
1400
+ setComparing(false);
1401
+ if (selected === void 0 || compareTo === void 0 || selected === compareTo) return;
1402
+ setComparing(true);
1403
+ client.call("config.agent.compareRevisions", {
1404
+ agentId,
1405
+ fromRevision: selected,
1406
+ toRevision: compareTo
1407
+ }).then((result) => {
1408
+ if (token === comparison.current) setChanges(result.changes);
1409
+ }).catch((cause) => {
1410
+ if (token === comparison.current) setComparisonError(reason(cause));
1411
+ }).finally(() => {
1412
+ if (token === comparison.current) setComparing(false);
1252
1413
  });
1253
- return true;
1254
1414
  }, [
1255
- canSave,
1256
- agent.agentId,
1257
- dirtyKeys,
1258
- value,
1259
- drafts,
1260
- saving,
1261
- remember
1415
+ client,
1416
+ agentId,
1417
+ selected,
1418
+ compareTo,
1419
+ current
1262
1420
  ]);
1263
- const lastError = useRef(null);
1264
- useEffect(() => {
1265
- if (saving.error === lastError.current) return;
1266
- lastError.current = saving.error;
1267
- if (saving.error === null) return;
1268
- const field = fieldOfRefusal(saving.error);
1269
- if (field !== null && dirty(field)) setErrors({ [field]: saving.error });
1270
- else setFooterError(saving.error);
1271
- }, [saving.error, dirty]);
1272
- const discard = useCallback(() => {
1273
- setDrafts(/* @__PURE__ */ new Map());
1274
- setErrors({});
1275
- setFooterError(null);
1276
- }, []);
1277
- const editor = {
1278
- agent,
1279
- agents,
1280
- slots,
1281
- slotsError,
1282
- slotsPending,
1283
- reloadSlots,
1284
- slotDefinitions: definitions.data,
1285
- value,
1286
- set,
1287
- dirty,
1288
- stale,
1289
- invalid,
1290
- reload,
1291
- dirtyTabs,
1292
- error: (key) => errors[key] ?? null,
1293
- footerError,
1294
- pending: saving.pending,
1295
- canSave,
1296
- save,
1297
- extension: (owner) => ({
1298
- read: (fallback) => value(`extension:${owner}`) ?? fallback,
1299
- update: (next) => set(`extension:${owner}`, next),
1300
- pending: saving.pending,
1301
- tools: value("tools"),
1302
- error: errors[`extension:${owner}`] ?? (dirty(`extension:${owner}`) ? contributions.flatMap((entry) => entry.plugin === owner && (entry.slot === "shell.agentEditor.field" || entry.slot === "shell.agentEditor.tab") ? [entry.contribution.validate?.(value(`extension:${owner}`))] : []).find((message) => message != null) ?? null : null)
1303
- }),
1304
- discard
1305
- };
1306
- return /* @__PURE__ */ jsx(EditorContext.Provider, {
1307
- value: editor,
1308
- children
1309
- });
1310
- }
1311
- //#endregion
1312
- //#region ui-src/components/settings/agent/parts.tsx
1313
- /** Pieces shared by the agent editor's tabs. */
1314
- /** Says a field with a draft was changed elsewhere, and takes the new value
1315
- * on request. Renders nothing while none of `fields` is stale. */
1316
- function ChangedElsewhere({ fields }) {
1317
- const { t } = useTranslation();
1318
- const editor = useAgentEditor();
1319
- const stale = fields.filter((key) => editor.stale(key));
1320
- if (stale.length === 0) return null;
1321
- return /* @__PURE__ */ jsx(Alert, {
1322
- tone: "warning",
1323
- variant: "soft",
1324
- "data-slot": "agent-changed-elsewhere",
1325
- className: "text-xs",
1326
- children: /* @__PURE__ */ jsxs("div", {
1327
- className: "flex flex-wrap items-start justify-between gap-3",
1328
- children: [/* @__PURE__ */ jsx("span", { children: t("agents.changedElsewhere") }), /* @__PURE__ */ jsx(Button, {
1329
- size: "sm",
1330
- variant: "ghost",
1331
- onClick: () => {
1332
- for (const key of stale) editor.reload(key);
1333
- },
1334
- children: t("agents.loadRemote")
1421
+ async function prepare(targetRevision) {
1422
+ if (beforeLeave && !await beforeLeave()) return;
1423
+ setBusy(true);
1424
+ setError("");
1425
+ setRequest(void 0);
1426
+ try {
1427
+ const value = await client.call("config.agent.previewRestore", {
1428
+ agentId,
1429
+ targetRevision
1430
+ });
1431
+ setPreview(value);
1432
+ setRequest({
1433
+ targetRevision,
1434
+ expectedRevision: value.expectedRevision,
1435
+ expectedContentHash: value.expectedContentHash,
1436
+ restoreRequestId: uuid()
1437
+ });
1438
+ } catch (cause) {
1439
+ setError(reason(cause));
1440
+ } finally {
1441
+ setBusy(false);
1442
+ }
1443
+ }
1444
+ async function restore() {
1445
+ if (!request || busy || restoring.current) return;
1446
+ restoring.current = true;
1447
+ setBusy(true);
1448
+ setError("");
1449
+ try {
1450
+ const result = await client.call("config.agent.restoreRevision", {
1451
+ agentId,
1452
+ ...request
1453
+ });
1454
+ useAgents.getState().consume({
1455
+ kind: "config.agentChanged",
1456
+ agent: result.agent
1457
+ });
1458
+ setNotice(t("revisions.saved", {
1459
+ revision: result.revision,
1460
+ current: result.currentRevision
1461
+ }));
1462
+ setPreview(void 0);
1463
+ setRequest(void 0);
1464
+ await read();
1465
+ } catch (cause) {
1466
+ setError(reason(cause));
1467
+ } finally {
1468
+ restoring.current = false;
1469
+ setBusy(false);
1470
+ }
1471
+ }
1472
+ const diff = (rows) => /* @__PURE__ */ jsx("div", {
1473
+ className: "space-y-4",
1474
+ children: rows.map((row) => /* @__PURE__ */ jsxs("div", {
1475
+ className: "space-y-2",
1476
+ children: [/* @__PURE__ */ jsx("p", {
1477
+ className: "text-xs font-medium",
1478
+ children: t(`revisions.fields.${row.path}`, { defaultValue: row.path })
1479
+ }), /* @__PURE__ */ jsx("div", {
1480
+ className: "grid gap-2 sm:grid-cols-2",
1481
+ children: [row.before, row.after].map((value, index) => /* @__PURE__ */ jsxs("div", {
1482
+ className: "min-w-0 rounded-control bg-muted/40 p-3",
1483
+ children: [/* @__PURE__ */ jsx("p", {
1484
+ className: "mb-2 text-xs text-muted-foreground",
1485
+ children: t(index === 0 ? "revisions.before" : "revisions.after")
1486
+ }), row.path === "avatar" && typeof value === "string" ? /* @__PURE__ */ jsx("img", {
1487
+ src: `data:image/png;base64,${value}`,
1488
+ alt: t(index === 0 ? "revisions.before" : "revisions.after"),
1489
+ className: "size-16 rounded-pill"
1490
+ }) : /* @__PURE__ */ jsx("pre", {
1491
+ className: "max-h-64 overflow-auto whitespace-pre-wrap break-words text-xs",
1492
+ children: typeof value === "string" ? value || "∅" : JSON.stringify(value, null, 2)
1493
+ })]
1494
+ }, index === 0 ? "before" : "after"))
1335
1495
  })]
1336
- })
1337
- });
1338
- }
1339
- //#endregion
1340
- //#region ui-src/components/settings/agent/basic.tsx
1341
- /**
1342
- * The basic-information tab: picture, name, description and the
1343
- * model cell. Every field, the model cell's included, is part of the editor's
1344
- * one draft. Whether a person can chat with the agent directly is a toggle on
1345
- * the agent list, not here.
1346
- *
1347
- * The picture is its own upload control: pressing it picks an image, and the
1348
- * crop shows in place until the save. While the agent has a picture — saved,
1349
- * or a crop waiting for the save — 恢复默认 beside it drafts the return to the
1350
- * derived letters face, which the same save applies.
1351
- */
1352
- /** The factory agent, whose session switch the gateway keeps on. */
1353
- function AvatarField() {
1354
- const { t } = useTranslation();
1355
- const editor = useAgentEditor();
1356
- const { agent } = editor;
1357
- const picker = useAvatarPicker((base64) => {
1358
- editor.set("avatar", {
1359
- image: base64,
1360
- preview: pngDataUrl(base64)
1361
- });
1496
+ }, row.path))
1362
1497
  });
1363
- const draft = editor.dirty("avatar") ? editor.value("avatar") : void 0;
1364
- const pictured = draft === void 0 ? agent.avatar !== null : draft !== null;
1365
- return /* @__PURE__ */ jsxs(Panel, {
1366
- title: t("agents.avatar"),
1367
- level: "field",
1368
- inline: true,
1498
+ return /* @__PURE__ */ jsxs("section", {
1499
+ className: "min-h-0 flex-1 space-y-4 overflow-auto px-6 pb-6",
1500
+ "aria-label": t("revisions.title"),
1369
1501
  children: [
1370
1502
  /* @__PURE__ */ jsxs("div", {
1371
- className: "flex min-w-0 items-center",
1372
- children: [/* @__PURE__ */ jsxs(Tooltip, { children: [/* @__PURE__ */ jsxs(TooltipTrigger, {
1373
- render: /* @__PURE__ */ jsx(Button, {
1374
- variant: "plain",
1375
- "data-slot": "agent-avatar-trigger",
1376
- className: "group relative size-11 shrink-0 cursor-pointer rounded-pill outline-none focus-visible:ring-3 focus-visible:ring-ring/50",
1377
- onClick: () => void picker.pick()
1378
- }),
1379
- "aria-label": t("avatar.change"),
1380
- children: [/* @__PURE__ */ jsx(AgentAvatar, {
1381
- agentId: agent.agentId,
1382
- name: editor.value("name") || agent.name,
1383
- avatar: draft === null ? null : agent.avatar,
1384
- ...draft ? { src: draft.preview } : {},
1385
- size: "lg",
1386
- decorative: true,
1387
- className: "size-11 text-sm"
1388
- }), /* @__PURE__ */ jsx("span", {
1389
- "data-slot": "agent-avatar-overlay",
1390
- "aria-hidden": "true",
1391
- className: "absolute inset-0 grid place-items-center rounded-pill bg-foreground/60 text-background opacity-0 transition-opacity duration-150 group-hover:opacity-100 group-focus-visible:opacity-100",
1392
- children: /* @__PURE__ */ jsx(Camera, {
1393
- className: "size-4",
1394
- strokeWidth: 1.75
1395
- })
1396
- })]
1397
- }), /* @__PURE__ */ jsx(TooltipContent, {
1398
- side: "top",
1399
- children: t("avatar.change")
1400
- })] }), pictured && /* @__PURE__ */ jsx(Button, {
1503
+ className: "flex items-center justify-between",
1504
+ children: [/* @__PURE__ */ jsx(Button, {
1401
1505
  variant: "ghost",
1402
1506
  size: "sm",
1403
- "data-slot": "agent-avatar-reset",
1404
- className: "ml-3",
1405
- onClick: () => {
1406
- picker.clearRefusal();
1407
- editor.set("avatar", null);
1408
- },
1409
- children: t("avatar.reset")
1507
+ onClick: onClose,
1508
+ children: t("revisions.back")
1509
+ }), /* @__PURE__ */ jsx(Button, {
1510
+ variant: "ghost",
1511
+ size: "sm",
1512
+ disabled: busy,
1513
+ onClick: () => void read(),
1514
+ children: t("revisions.refresh")
1410
1515
  })]
1411
1516
  }),
1412
- /* @__PURE__ */ jsx(FormFailure, { reason: picker.refusal ?? editor.error("avatar") }),
1413
- picker.dialog
1414
- ]
1415
- });
1416
- }
1417
- function BasicTab() {
1418
- const { t } = useTranslation();
1419
- const editor = useAgentEditor();
1420
- const { agent } = editor;
1421
- const name = editor.value("name");
1422
- const description = editor.value("description");
1423
- const pluginState = usePlugins((state) => state);
1424
- const registrations = contributionsIn(pluginState, "shell.agentEditor.field");
1425
- return /* @__PURE__ */ jsxs("div", {
1426
- className: "flex min-w-0 flex-col gap-5",
1427
- children: [
1428
- /* @__PURE__ */ jsx(ChangedElsewhere, { fields: [
1429
- "name",
1430
- "description",
1431
- "avatar",
1432
- ...registrations.map((one) => `extension:${one.plugin}`)
1433
- ] }),
1434
- /* @__PURE__ */ jsx(AvatarField, {}),
1435
- /* @__PURE__ */ jsx(Field, {
1436
- label: t("agents.name"),
1437
- required: true,
1438
- inline: true,
1439
- className: "settings-field-row",
1440
- error: editor.error("name") ?? (editor.invalid("name") ? t("agents.nameRequired") : void 0),
1441
- children: (binding) => /* @__PURE__ */ jsx(Input, {
1442
- ...binding,
1443
- value: name,
1444
- placeholder: t("agents.namePlaceholder"),
1445
- onChange: (event) => editor.set("name", event.target.value),
1446
- onKeyDown: (event) => {
1447
- if (event.key === "Escape" && !event.nativeEvent.isComposing) editor.reload("name");
1448
- }
1449
- })
1517
+ !persistent && /* @__PURE__ */ jsx("p", {
1518
+ className: "text-xs text-muted-foreground",
1519
+ children: t("revisions.memory")
1450
1520
  }),
1451
- /* @__PURE__ */ jsx(Field, {
1452
- label: t("agents.description"),
1453
- inline: true,
1454
- className: "settings-field-row",
1455
- error: editor.error("description") ?? (editor.invalid("description") ? t("agents.descriptionTooLong", { limit: 500 }) : void 0),
1456
- children: (binding) => /* @__PURE__ */ jsx(Textarea, {
1457
- ...binding,
1458
- limit: 500,
1459
- rows: 5,
1460
- className: "h-[calc(5lh+1rem)] resize-none [field-sizing:fixed]",
1461
- value: description,
1462
- placeholder: t("agents.descriptionPlaceholder"),
1463
- onChange: (event) => editor.set("description", event.target.value)
1464
- })
1521
+ error && /* @__PURE__ */ jsx("p", {
1522
+ role: "alert",
1523
+ className: "text-sm text-destructive",
1524
+ children: error
1465
1525
  }),
1466
- registrations.map((one) => /* @__PURE__ */ jsx(SlotOutlet, {
1467
- slot: "shell.agentEditor.field",
1468
- only: one.key,
1469
- props: {
1470
- agentId: agent.agentId,
1471
- editor: editor.extension(one.plugin),
1472
- errors: { owner: editor.error(`extension:${one.plugin}`) }
1473
- }
1474
- }, one.key))
1475
- ]
1476
- });
1477
- }
1478
- //#endregion
1479
- //#region ui-src/components/settings/agent/prompts.tsx
1480
- /**
1481
- * The prompt tab: the four slots, one edited at a time, listed as identity,
1482
- * style, reminder, AGENTS.md — the slots `config.prompt.slots` declares, in
1483
- * this tab's own order, with their limits from that listing. Each slot keeps
1484
- * its own draft in the editor, so switching slots asks nothing; the text area
1485
- * fills the tab and is its only scroller. Above the text area the chosen
1486
- * slot says what to write there and where the text lands in the model's input.
1487
- */
1488
- /** A dot that says a slot or tab has an unsaved change, to eyes and ears. */
1489
- /** The slot's identifier as the list's second line. Identifiers, not copy:
1490
- * the same in every language. Only AGENTS.md is a file. */
1491
- var SLOT_TAGS = {
1492
- identity: "IDENTITY Slot",
1493
- style: "SOUL Slot",
1494
- reminder: "REMINDER Slot",
1495
- instructions: "AGENTS.md"
1496
- };
1497
- function UnsavedDot() {
1498
- const { t } = useTranslation();
1499
- return /* @__PURE__ */ jsxs("span", {
1500
- "data-slot": "unsaved-dot",
1501
- className: "inline-flex shrink-0 items-center",
1502
- children: [/* @__PURE__ */ jsx("span", {
1503
- "aria-hidden": "true",
1504
- className: "size-1.5 rounded-pill bg-primary"
1505
- }), /* @__PURE__ */ jsx("span", {
1506
- className: "sr-only",
1507
- children: t("agents.unsaved")
1508
- })]
1509
- });
1510
- }
1511
- /** The order this tab lists the slots in. */
1512
- var DISPLAY_ORDER = [
1513
- "identity",
1514
- "style",
1515
- "reminder",
1516
- "instructions"
1517
- ];
1518
- var NOTES = [
1519
- "where",
1520
- "scope",
1521
- "cache",
1522
- "tip"
1523
- ];
1524
- /** What the chosen slot is for and where it goes, shown above its editor for
1525
- * as long as it is chosen: the purpose with an example, then the placement. */
1526
- function SlotAbout({ slot, limit, path }) {
1527
- const { t } = useTranslation();
1528
- return /* @__PURE__ */ jsxs("section", {
1529
- "aria-label": t("agents.prompts.about", { slot: t(`agents.prompts.${slot}`) }),
1530
- "data-slot": "prompt-slot-about",
1531
- className: "flex shrink-0 flex-col gap-2 rounded-control bg-muted/60 px-3 py-2.5 text-xs leading-relaxed @xl:flex-row @xl:gap-6",
1532
- children: [/* @__PURE__ */ jsxs("div", {
1533
- className: "flex min-w-0 flex-col gap-1 @xl:flex-1",
1534
- children: [
1535
- /* @__PURE__ */ jsx("h4", {
1536
- className: "font-medium text-foreground",
1537
- children: t("agents.prompts.purpose")
1538
- }),
1539
- /* @__PURE__ */ jsx("p", {
1540
- className: "text-muted-foreground",
1541
- children: t(`agents.prompts.info.${slot}.purpose`)
1542
- }),
1543
- /* @__PURE__ */ jsx("p", {
1544
- className: "text-muted-foreground",
1545
- children: t("agents.prompts.example", { text: t(`agents.prompts.info.${slot}.example`) })
1546
- })
1547
- ]
1548
- }), /* @__PURE__ */ jsxs("div", {
1549
- className: "flex min-w-0 flex-col gap-1 @xl:flex-1",
1550
- children: [/* @__PURE__ */ jsx("h4", {
1551
- className: "font-medium text-foreground",
1552
- children: t("agents.prompts.placement")
1553
- }), /* @__PURE__ */ jsx("ul", {
1554
- className: "flex list-disc flex-col gap-0.5 ps-4 text-muted-foreground",
1555
- children: NOTES.map((note) => /* @__PURE__ */ jsx("li", {
1556
- className: "break-words",
1557
- children: t(`agents.prompts.info.${slot}.${note}`, {
1558
- path,
1559
- limit: limit ?? ""
1526
+ notice && /* @__PURE__ */ jsx("p", {
1527
+ role: "status",
1528
+ className: "text-sm",
1529
+ children: notice
1530
+ }),
1531
+ busy && /* @__PURE__ */ jsx("p", {
1532
+ role: "status",
1533
+ className: "text-sm text-muted-foreground",
1534
+ children: t("revisions.loading")
1535
+ }),
1536
+ preview && /* @__PURE__ */ jsxs("div", {
1537
+ className: "space-y-4 rounded-control border p-4",
1538
+ children: [
1539
+ /* @__PURE__ */ jsx("h4", { children: t("revisions.confirm", {
1540
+ from: preview.expectedRevision,
1541
+ to: preview.targetRevision
1542
+ }) }),
1543
+ /* @__PURE__ */ jsx("p", {
1544
+ className: "text-xs text-muted-foreground",
1545
+ children: t("revisions.timing")
1546
+ }),
1547
+ diff(preview.changes),
1548
+ preview.blockers.map((blocker) => /* @__PURE__ */ jsxs("p", {
1549
+ className: "text-sm text-destructive",
1550
+ children: [
1551
+ blocker.path,
1552
+ ": ",
1553
+ blocker.reason
1554
+ ]
1555
+ }, blocker.path + blocker.reason)),
1556
+ preview.unchanged && /* @__PURE__ */ jsx("p", { children: t("revisions.unchanged") }),
1557
+ /* @__PURE__ */ jsxs("div", {
1558
+ className: "flex gap-2",
1559
+ children: [
1560
+ /* @__PURE__ */ jsx(Button, {
1561
+ disabled: busy || preview.unchanged || preview.blockers.length > 0,
1562
+ onClick: () => void restore(),
1563
+ children: t("revisions.restore")
1564
+ }),
1565
+ /* @__PURE__ */ jsx(Button, {
1566
+ variant: "ghost",
1567
+ disabled: busy,
1568
+ onClick: () => void prepare(preview.targetRevision),
1569
+ children: t("revisions.refresh")
1570
+ }),
1571
+ /* @__PURE__ */ jsx(Button, {
1572
+ variant: "ghost",
1573
+ disabled: busy,
1574
+ onClick: () => {
1575
+ setPreview(void 0);
1576
+ setRequest(void 0);
1577
+ },
1578
+ children: t("revisions.cancel")
1579
+ })
1580
+ ]
1560
1581
  })
1561
- }, note))
1562
- })]
1563
- })]
1582
+ ]
1583
+ }),
1584
+ /* @__PURE__ */ jsx("ol", {
1585
+ className: "divide-y",
1586
+ children: items.map((item) => {
1587
+ const expanded = selected === item.revision;
1588
+ const canExpand = items.length > 1 || item.revision !== current || !!item.source.sessionId;
1589
+ const heading = /* @__PURE__ */ jsxs("span", {
1590
+ className: "min-w-0 flex-1 space-y-1",
1591
+ children: [/* @__PURE__ */ jsxs("span", {
1592
+ className: "block text-sm font-medium break-words",
1593
+ children: [
1594
+ "v",
1595
+ item.revision,
1596
+ " · ",
1597
+ item.summary
1598
+ ]
1599
+ }), /* @__PURE__ */ jsxs("span", {
1600
+ className: "block text-xs text-muted-foreground",
1601
+ children: [
1602
+ new Date(item.createdAt).toLocaleString(i18n.language),
1603
+ " ·",
1604
+ " ",
1605
+ t(`revisions.${item.source.kind}`)
1606
+ ]
1607
+ })]
1608
+ });
1609
+ const currentMark = item.revision === current && /* @__PURE__ */ jsx("span", {
1610
+ className: "shrink-0 rounded-control bg-muted px-2 py-1 text-xs text-muted-foreground",
1611
+ children: t("revisions.current")
1612
+ });
1613
+ return /* @__PURE__ */ jsxs("li", {
1614
+ className: "py-2",
1615
+ children: [canExpand ? /* @__PURE__ */ jsxs(Button, {
1616
+ variant: "plain",
1617
+ "aria-expanded": expanded,
1618
+ className: "flex w-full items-center gap-3 rounded-control p-3 text-start hover:bg-muted/50 focus-visible:ring-2 focus-visible:ring-ring",
1619
+ onClick: () => {
1620
+ setSelected(expanded ? void 0 : item.revision);
1621
+ setCompareTo(item.revision === current ? items.find((option) => option.revision !== item.revision)?.revision : current);
1622
+ },
1623
+ children: [
1624
+ heading,
1625
+ currentMark,
1626
+ /* @__PURE__ */ jsx(ChevronDown, {
1627
+ "aria-hidden": "true",
1628
+ className: `size-4 shrink-0 text-muted-foreground transition-transform ${expanded ? "rotate-180" : ""}`
1629
+ })
1630
+ ]
1631
+ }) : /* @__PURE__ */ jsxs("div", {
1632
+ className: "flex items-center gap-3 p-3",
1633
+ children: [heading, currentMark]
1634
+ }), expanded && /* @__PURE__ */ jsxs("div", {
1635
+ className: "space-y-4 px-3 pt-3 pb-2",
1636
+ children: [compareTo !== void 0 && compareTo !== item.revision && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("label", {
1637
+ className: "flex flex-wrap items-center gap-2 text-xs text-muted-foreground",
1638
+ children: [
1639
+ t("revisions.compare"),
1640
+ " · v",
1641
+ item.revision,
1642
+ " →",
1643
+ /* @__PURE__ */ jsx(Select, {
1644
+ size: "sm",
1645
+ "aria-label": t("revisions.compare"),
1646
+ value: String(compareTo),
1647
+ onValueChange: (value) => setCompareTo(Number(value)),
1648
+ children: items.filter((option) => option.revision !== item.revision).map((option) => /* @__PURE__ */ jsxs("option", {
1649
+ value: option.revision,
1650
+ children: ["v", option.revision]
1651
+ }, option.revision))
1652
+ })
1653
+ ]
1654
+ }), comparing ? /* @__PURE__ */ jsx("p", {
1655
+ role: "status",
1656
+ className: "text-xs text-muted-foreground",
1657
+ children: t("revisions.loading")
1658
+ }) : comparisonError ? /* @__PURE__ */ jsx("p", {
1659
+ role: "alert",
1660
+ className: "text-xs text-destructive",
1661
+ children: comparisonError
1662
+ }) : changes.length === 0 ? /* @__PURE__ */ jsx("p", {
1663
+ className: "text-xs text-muted-foreground",
1664
+ children: t("revisions.noDifference")
1665
+ }) : diff(changes)] }), /* @__PURE__ */ jsxs("div", {
1666
+ className: "flex flex-wrap gap-2",
1667
+ children: [item.revision !== current && /* @__PURE__ */ jsx(Button, {
1668
+ variant: "outline",
1669
+ size: "sm",
1670
+ disabled: busy,
1671
+ onClick: () => void prepare(item.revision),
1672
+ children: t("revisions.restore")
1673
+ }), item.source.sessionId && /* @__PURE__ */ jsx(Button, {
1674
+ variant: "ghost",
1675
+ size: "sm",
1676
+ onClick: async () => {
1677
+ if (beforeLeave && !await beforeLeave()) return;
1678
+ if (!await goToSession(client, item.source.sessionId)) setError(t("revisions.sourceMissing"));
1679
+ else useNavigation.getState().openSettings(false);
1680
+ },
1681
+ children: t("revisions.source")
1682
+ })]
1683
+ })]
1684
+ })]
1685
+ }, item.revision);
1686
+ })
1687
+ }),
1688
+ cursor && /* @__PURE__ */ jsx(Button, {
1689
+ variant: "ghost",
1690
+ disabled: busy,
1691
+ onClick: () => void read(cursor),
1692
+ children: t("revisions.more")
1693
+ })
1694
+ ]
1564
1695
  });
1565
1696
  }
1566
- function PromptsTab() {
1697
+ //#endregion
1698
+ //#region ui-src/components/settings/agent/tools.tsx
1699
+ /** Agent tool access and preload preferences grouped from the live tool list. */
1700
+ /** Uses extension metadata without interpreting package names or tool naming conventions. */
1701
+ function groupsOf(tools, describe, unknownSource) {
1702
+ const groups = /* @__PURE__ */ new Map();
1703
+ for (const tool of tools) {
1704
+ const existing = groups.get(tool.plugin);
1705
+ const presentation = describe(tool);
1706
+ const facts = (presentation?.source === tool.plugin ? presentation : existing) ?? {
1707
+ label: tool.plugin || unknownSource,
1708
+ sectionLabel: unknownSource,
1709
+ sectionOrder: 2,
1710
+ order: 0
1711
+ };
1712
+ groups.set(tool.plugin, {
1713
+ ...facts,
1714
+ key: `plugin:${tool.plugin}`,
1715
+ source: tool.plugin || unknownSource,
1716
+ tools: [...existing?.tools ?? [], tool]
1717
+ });
1718
+ }
1719
+ return [...groups.values()].map((group) => ({
1720
+ ...group,
1721
+ tools: [...group.tools].sort((a, b) => a.name.localeCompare(b.name))
1722
+ })).sort((a, b) => a.sectionOrder - b.sectionOrder || a.order - b.order || a.label.localeCompare(b.label));
1723
+ }
1724
+ /** Tool permissions and independent preload preferences share the Agent editor transaction. */
1725
+ function ToolsTab() {
1567
1726
  const { t } = useTranslation();
1568
1727
  const editor = useAgentEditor();
1569
- const declared = editor.slotDefinitions?.map((one) => one.id);
1570
- const order = DISPLAY_ORDER.filter((id) => declared?.includes(id) ?? true);
1571
- const [picked, setPicked] = useState(order[0] ?? "identity");
1572
- const slot = order.includes(picked) ? picked : order[0] ?? "identity";
1573
- const key = `prompt.${slot}`;
1574
- const limit = editor.slotDefinitions?.find((one) => one.id === slot)?.maxLength;
1575
- const failure = slot === "instructions" ? editor.slots?.failure : void 0;
1576
- const label = (id) => t(`agents.prompts.${id}`);
1577
- const rulesPath = editor.slots?.path ?? `agents/${editor.agent.agentId}/AGENTS.md`;
1578
- if (editor.slots === null) return /* @__PURE__ */ jsx(ReadFailure, {
1579
- reason: editor.slotsError,
1580
- pending: editor.slotsPending,
1581
- onRetry: editor.reloadSlots
1728
+ const { agent } = editor;
1729
+ const preload = useBrowserService("tool-preload:configuration");
1730
+ const rememberedOwner = useRef(preload?.owner);
1731
+ if (preload) rememberedOwner.current = preload.owner;
1732
+ const owner = preload?.owner ?? rememberedOwner.current;
1733
+ const ownerKey = owner ? `extension:${owner}` : void 0;
1734
+ const ownerValue = ownerKey ? editor.value(ownerKey) : void 0;
1735
+ const lastOverrides = useRef({});
1736
+ let overrides = lastOverrides.current;
1737
+ let preloadError = null;
1738
+ try {
1739
+ if (preload) {
1740
+ overrides = preload.read(ownerValue);
1741
+ lastOverrides.current = overrides;
1742
+ }
1743
+ } catch (error) {
1744
+ preloadError = error instanceof Error ? error.message : String(error);
1745
+ }
1746
+ const listing = useGatewayRead("config.tool.list", {
1747
+ agentIds: [agent.agentId],
1748
+ maxItemBytes: 262144,
1749
+ maxTotalBytes: 8388608
1582
1750
  });
1751
+ const member = listing.data?.results.find((one) => one.target === agent.agentId);
1752
+ const tools = member?.ok && member.value.agentId === agent.agentId ? member.value.tools : null;
1753
+ const whitelist = editor.value("tools");
1754
+ const unrestricted = whitelist === null;
1755
+ const permitted = (name) => unrestricted || whitelist.includes(name);
1756
+ const pluginState = usePlugins((state) => state);
1757
+ const presentations = contributionsIn(pluginState, "shell.tools.group");
1758
+ const labels = contributionsIn(pluginState, "chat.tool.presentation");
1759
+ const titleOf = (tool) => {
1760
+ for (const entry of labels) {
1761
+ if (entry.plugin !== tool.plugin) continue;
1762
+ try {
1763
+ const label = entry.contribution.describe({
1764
+ call: {
1765
+ id: tool.name,
1766
+ name: tool.name,
1767
+ input: {}
1768
+ },
1769
+ result: void 0
1770
+ })?.label;
1771
+ if (label) return label;
1772
+ } catch {}
1773
+ }
1774
+ return tool.name;
1775
+ };
1776
+ const groups = groupsOf(tools ?? [], (tool) => presentations.map((one) => one.contribution.describe(tool)).find((value) => value !== void 0), t("agents.toolSettings.unknownSource"));
1777
+ const groupFor = new Map(groups.flatMap((group) => group.tools.map((tool) => [tool.name, group])));
1778
+ const rows = groups.flatMap((group) => group.tools);
1779
+ const known = new Set(rows.map((tool) => tool.name));
1780
+ const unavailable = tools === null ? [] : [.../* @__PURE__ */ new Set([...Object.keys(overrides).filter((name) => !known.has(name)), ...unrestricted ? [] : whitelist.filter((name) => !known.has(name))])];
1781
+ const overridden = (name) => Object.hasOwn(overrides, name);
1782
+ const effective = (tool) => overridden(tool.name) ? overrides[tool.name] === true : tool.preloadDefault;
1783
+ const blocked = !preload || preloadError !== null || editor.pending;
1784
+ const loading = listing.pending && tools === null;
1785
+ function changePermission(names, on) {
1786
+ if (on && whitelist === null) return;
1787
+ const without = (whitelist ?? rows.map((tool) => tool.name)).filter((name) => !names.includes(name));
1788
+ editor.set("tools", on ? [...without, ...names] : without);
1789
+ }
1790
+ function changePreload(names, on) {
1791
+ if (!preload || blocked || !ownerKey) return;
1792
+ const next = { ...overrides };
1793
+ for (const name of names) if (on === void 0) delete next[name];
1794
+ else next[name] = on;
1795
+ editor.set(ownerKey, preload.replace(ownerValue, next));
1796
+ }
1797
+ function resetDefaults() {
1798
+ if (!preload || blocked || !ownerKey) return;
1799
+ const next = preload.replace(ownerValue, {});
1800
+ editor.set("tools", null);
1801
+ editor.set(ownerKey, next);
1802
+ }
1583
1803
  return /* @__PURE__ */ jsxs("div", {
1584
- className: "@container flex min-h-0 min-w-0 flex-1 flex-col gap-3",
1585
- children: [/* @__PURE__ */ jsx(ChangedElsewhere, { fields: SLOT_IDS.map((id) => `prompt.${id}`) }), /* @__PURE__ */ jsxs("div", {
1586
- className: "flex min-h-0 min-w-0 flex-1 flex-col gap-4 @2xl:flex-row",
1587
- children: [
1588
- /* @__PURE__ */ jsx("nav", {
1589
- "aria-label": t("agents.prompts.slots"),
1590
- "data-slot": "prompt-slot-list",
1591
- className: "hidden w-52 shrink-0 flex-col gap-1 @2xl:flex",
1592
- children: order.map((id) => /* @__PURE__ */ jsx("div", {
1593
- "data-slot": "prompt-slot",
1594
- className: cn("flex min-w-0 items-center gap-1 rounded-control pe-1", id === slot ? "bg-accent text-accent-foreground" : "hover:bg-muted"),
1595
- children: /* @__PURE__ */ jsxs(Button, {
1596
- variant: "plain",
1597
- "data-slot": "prompt-slot-select",
1598
- "aria-current": id === slot,
1599
- onClick: () => setPicked(id),
1600
- className: "flex h-auto min-w-0 flex-1 items-center justify-start gap-2 px-3 py-1.5 text-left",
1601
- children: [/* @__PURE__ */ jsxs("span", {
1602
- className: "flex min-w-0 flex-col",
1804
+ className: "@container flex min-w-0 flex-col gap-4",
1805
+ children: [
1806
+ /* @__PURE__ */ jsx(ChangedElsewhere, { fields: ownerKey ? ["tools", ownerKey] : ["tools"] }),
1807
+ /* @__PURE__ */ jsxs("div", {
1808
+ className: "min-w-0",
1809
+ children: [/* @__PURE__ */ jsxs("div", {
1810
+ className: "flex min-w-0 items-center justify-between gap-3",
1811
+ children: [/* @__PURE__ */ jsx("h3", {
1812
+ className: "text-sm font-semibold",
1813
+ children: t("agents.toolSettings.heading")
1814
+ }), /* @__PURE__ */ jsx(Segmented, {
1815
+ label: t("agents.toolSettings.mode"),
1816
+ value: unrestricted ? "all" : "custom",
1817
+ disabled: tools === null || editor.pending,
1818
+ options: [{
1819
+ value: "custom",
1820
+ label: t("agents.toolSettings.custom")
1821
+ }, {
1822
+ value: "all",
1823
+ label: t("agents.toolSettings.allowAll")
1824
+ }],
1825
+ onSelect: (mode) => editor.set("tools", mode === "all" ? null : rows.filter((tool) => permitted(tool.name)).map((tool) => tool.name))
1826
+ })]
1827
+ }), /* @__PURE__ */ jsx("p", {
1828
+ className: "mt-1 text-xs leading-relaxed text-muted-foreground",
1829
+ children: t("agents.toolSettings.hint")
1830
+ })]
1831
+ }),
1832
+ /* @__PURE__ */ jsx(ReadFailure, {
1833
+ reason: listing.error ?? (member && !member.ok ? member.error.message : null),
1834
+ pending: loading,
1835
+ onRetry: listing.reload
1836
+ }),
1837
+ !preload && /* @__PURE__ */ jsx(Warning, { children: t("agents.toolSettings.preloadUnavailable") }),
1838
+ /* @__PURE__ */ jsx(FormFailure, { reason: preloadError }),
1839
+ (tools !== null || loading) && /* @__PURE__ */ jsx(DataTable, {
1840
+ defaultExpandedGroups: [],
1841
+ ariaLabel: t("agents.toolSettings.heading"),
1842
+ items: rows,
1843
+ keyOf: (tool) => tool.name,
1844
+ labelOf: (tool) => tool.name,
1845
+ searchOf: (tool) => `${titleOf(tool)} ${tool.name} ${tool.description} ${tool.plugin}`,
1846
+ groupSelectionScope: "matching",
1847
+ toolbar: /* @__PURE__ */ jsx(TooltipHint, {
1848
+ content: t("agents.toolSettings.resetDefaultsHint"),
1849
+ children: /* @__PURE__ */ jsx(Button, {
1850
+ size: "sm",
1851
+ variant: "ghost",
1852
+ icon: "reset",
1853
+ className: "w-[var(--control-height)] p-0",
1854
+ "aria-label": t("agents.toolSettings.restoreDefault"),
1855
+ disabled: blocked || tools === null,
1856
+ onClick: resetDefaults
1857
+ })
1858
+ }),
1859
+ groupOf: (tool) => {
1860
+ const group = groupFor.get(tool.name);
1861
+ return {
1862
+ key: group.key,
1863
+ label: group.label,
1864
+ hint: group.source
1865
+ };
1866
+ },
1867
+ columns: [{
1868
+ id: "tool",
1869
+ label: t("agents.toolSettings.tool"),
1870
+ render: (tool) => {
1871
+ const title = titleOf(tool);
1872
+ return /* @__PURE__ */ jsxs("div", {
1873
+ className: "flex w-full min-w-0 max-w-full flex-col gap-1",
1874
+ children: [/* @__PURE__ */ jsxs("div", {
1875
+ className: "flex min-w-0 items-center gap-2 whitespace-nowrap",
1603
1876
  children: [/* @__PURE__ */ jsx("span", {
1604
- className: "truncate text-sm font-medium",
1605
- children: label(id)
1606
- }), /* @__PURE__ */ jsx("span", {
1607
- className: "truncate font-mono text-2xs text-muted-foreground",
1608
- children: SLOT_TAGS[id]
1877
+ title: tool.name,
1878
+ className: title === tool.name ? "min-w-0 truncate font-mono text-xs text-foreground" : "min-w-0 max-w-[65%] truncate font-mono text-xs text-foreground",
1879
+ children: tool.name
1880
+ }), title !== tool.name && /* @__PURE__ */ jsx("span", {
1881
+ title,
1882
+ className: "min-w-0 truncate text-xs font-medium text-muted-foreground",
1883
+ children: title
1609
1884
  })]
1610
- }), editor.dirty(`prompt.${id}`) && /* @__PURE__ */ jsx(UnsavedDot, {})]
1885
+ }), /* @__PURE__ */ jsx(TooltipHint, {
1886
+ content: /* @__PURE__ */ jsx("span", {
1887
+ className: "max-h-64 overflow-y-auto whitespace-pre-wrap",
1888
+ children: tool.description
1889
+ }),
1890
+ side: "bottom",
1891
+ closeOnClick: false,
1892
+ children: /* @__PURE__ */ jsx("button", {
1893
+ type: "button",
1894
+ "data-slot": "tool-description",
1895
+ className: "block w-full max-w-full truncate rounded-sm border-0 bg-transparent p-0 text-left text-xs text-muted-foreground focus-visible:outline-2 focus-visible:outline-ring",
1896
+ children: tool.description
1897
+ })
1898
+ })]
1899
+ });
1900
+ }
1901
+ }, {
1902
+ id: "preload",
1903
+ label: t("agents.toolSettings.preload"),
1904
+ width: "4rem",
1905
+ render: (tool) => /* @__PURE__ */ jsx("div", {
1906
+ className: "flex items-center gap-1",
1907
+ children: /* @__PURE__ */ jsx(TooltipHint, {
1908
+ content: t(effective(tool) ? "agents.toolSettings.preloadOn" : "agents.toolSettings.preloadOff"),
1909
+ children: /* @__PURE__ */ jsx(Button, {
1910
+ size: "sm",
1911
+ variant: "ghost",
1912
+ className: effective(tool) ? "w-8 p-0 text-yellow-500" : "w-8 p-0 text-muted-foreground",
1913
+ "aria-label": `${t("agents.toolSettings.preload")} ${tool.name}`,
1914
+ "aria-pressed": effective(tool),
1915
+ disabled: blocked,
1916
+ onClick: () => changePreload([tool.name], !effective(tool)),
1917
+ children: /* @__PURE__ */ jsx("svg", {
1918
+ viewBox: "0 0 24 24",
1919
+ width: "16",
1920
+ height: "16",
1921
+ fill: effective(tool) ? "currentColor" : "none",
1922
+ stroke: "currentColor",
1923
+ strokeWidth: "1.6",
1924
+ strokeLinejoin: "round",
1925
+ "aria-hidden": "true",
1926
+ children: /* @__PURE__ */ jsx("path", { d: "m13 2-9 12h7l-1 8 10-13h-7l1-7Z" })
1927
+ })
1928
+ })
1611
1929
  })
1612
- }, id))
1613
- }),
1614
- /* @__PURE__ */ jsx("div", {
1615
- "data-slot": "prompt-slot-switch",
1616
- className: "min-w-0 @2xl:hidden",
1617
- children: /* @__PURE__ */ jsx(Segmented, {
1618
- fullWidth: true,
1619
- label: t("agents.prompts.slots"),
1620
- value: slot,
1621
- options: order.map((id) => ({
1622
- value: id,
1623
- label: editor.dirty(`prompt.${id}`) ? `${label(id)} •` : label(id)
1624
- })),
1625
- onSelect: setPicked
1626
1930
  })
1931
+ }],
1932
+ selection: {
1933
+ keys: new Set(unrestricted ? rows.map((tool) => tool.name) : whitelist),
1934
+ mode: "enablement",
1935
+ onChange: (next) => {
1936
+ if (unrestricted && rows.every((tool) => next.has(tool.name))) return;
1937
+ editor.set("tools", [...next]);
1938
+ },
1939
+ disabled: editor.pending
1940
+ },
1941
+ loading,
1942
+ size: "sm",
1943
+ empty: /* @__PURE__ */ jsx("p", {
1944
+ className: "text-xs text-muted-foreground",
1945
+ children: t("agents.toolsEmpty")
1627
1946
  }),
1628
- /* @__PURE__ */ jsxs("section", {
1629
- "aria-label": label(slot),
1630
- "data-slot": "prompt-editor",
1631
- className: "flex min-h-0 min-w-0 flex-1 flex-col gap-2",
1632
- children: [
1633
- /* @__PURE__ */ jsx(SlotAbout, {
1634
- slot,
1635
- limit,
1636
- path: rulesPath
1637
- }),
1638
- failure !== void 0 && /* @__PURE__ */ jsx(Failure, { reason: t("agents.prompts.readFailed", { reason: failure }) }),
1639
- /* @__PURE__ */ jsx(Textarea, {
1640
- "aria-label": label(slot),
1641
- fill: true,
1642
- ...limit === void 0 ? {} : { limit },
1643
- readOnly: failure !== void 0,
1644
- value: editor.value(key),
1645
- onChange: (event) => editor.set(key, event.target.value),
1646
- className: "font-mono"
1647
- }, slot),
1648
- /* @__PURE__ */ jsx(FormFailure, { reason: editor.error(key) })
1649
- ]
1650
- })
1651
- ]
1652
- })]
1947
+ className: "w-full min-w-0 [&_table]:table-fixed"
1948
+ }, `${agent.agentId}:${tools === null ? "loading" : "ready"}`),
1949
+ unavailable.length > 0 && /* @__PURE__ */ jsxs("section", {
1950
+ "data-slot": "tool-unavailable",
1951
+ "aria-label": t("agents.toolSettings.unavailable"),
1952
+ className: "rounded-control border border-dashed border-border p-3",
1953
+ children: [
1954
+ /* @__PURE__ */ jsx("h4", {
1955
+ className: "text-xs font-medium",
1956
+ children: t("agents.toolSettings.unavailable")
1957
+ }),
1958
+ /* @__PURE__ */ jsx("p", {
1959
+ className: "mt-1 text-2xs text-muted-foreground",
1960
+ children: t("agents.toolSettings.unavailableHint")
1961
+ }),
1962
+ /* @__PURE__ */ jsx("ul", {
1963
+ className: "mt-2 flex flex-col gap-1",
1964
+ children: unavailable.map((name) => /* @__PURE__ */ jsxs("li", {
1965
+ className: "flex min-w-0 flex-wrap items-center gap-2",
1966
+ children: [/* @__PURE__ */ jsx("span", {
1967
+ className: "min-w-0 flex-1 break-all font-mono text-xs text-muted-foreground",
1968
+ children: name
1969
+ }), !unrestricted && whitelist.includes(name) && /* @__PURE__ */ jsx(Button, {
1970
+ size: "sm",
1971
+ variant: "ghost",
1972
+ "aria-label": `${t("common.remove")} ${name}`,
1973
+ disabled: editor.pending,
1974
+ onClick: () => changePermission([name], false),
1975
+ children: t("common.remove")
1976
+ })]
1977
+ }, name))
1978
+ })
1979
+ ]
1980
+ }),
1981
+ /* @__PURE__ */ jsx(FormFailure, { reason: editor.error("tools") }),
1982
+ ownerKey && /* @__PURE__ */ jsx(FormFailure, { reason: editor.error(ownerKey) })
1983
+ ]
1653
1984
  });
1654
1985
  }
1655
1986
  //#endregion
1656
- //#region ui-src/components/settings/agent/revisions.tsx
1657
- /** Compact history with explicit comparison and a retryable restore confirmation. */
1658
- function AgentRevisions({ agentId, onClose, beforeLeave }) {
1659
- const { t, i18n } = useTranslation();
1660
- const client = useGateway();
1661
- const observedRevision = useAgents((state) => state.agents.find((agent) => agent.agentId === agentId)?.revision);
1662
- const [items, setItems] = useState([]);
1663
- const [current, setCurrent] = useState(0);
1664
- const [cursor, setCursor] = useState();
1665
- const [selected, setSelected] = useState();
1666
- const [compareTo, setCompareTo] = useState();
1667
- const [changes, setChanges] = useState([]);
1668
- const [comparing, setComparing] = useState(false);
1669
- const [comparisonError, setComparisonError] = useState("");
1670
- const [preview, setPreview] = useState();
1671
- const [request, setRequest] = useState();
1672
- const [busy, setBusy] = useState(false);
1673
- const [error, setError] = useState("");
1674
- const [notice, setNotice] = useState("");
1675
- const [persistent, setPersistent] = useState(true);
1676
- const generation = useRef(0);
1677
- const restoring = useRef(false);
1678
- const comparison = useRef(0);
1679
- const reason = (cause) => failureText(cause, () => "") ?? "";
1680
- const read = useCallback(async (next) => {
1681
- const token = ++generation.current;
1682
- setBusy(true);
1683
- setError("");
1987
+ //#region ui-src/components/settings/execution-limits.tsx
1988
+ /** Global execution limits; each successful save applies to subsequent rounds. */
1989
+ function ExecutionLimits({ ctx, registerGuard }) {
1990
+ const host = useGateway();
1991
+ const gateway = ctx?.gateway ?? host;
1992
+ const { t } = useTranslation();
1993
+ const toast = useToast();
1994
+ const translation = useRef(t);
1995
+ translation.current = t;
1996
+ const [saved, setSaved] = useState(null);
1997
+ const [inputKey, setInputKey] = useState(0);
1998
+ const [draft, setDraft] = useState(null);
1999
+ const [readError, setReadError] = useState(null);
2000
+ const [saveError, setSaveError] = useState(null);
2001
+ const [reading, setReading] = useState(true);
2002
+ const [blocked, setBlocked] = useState(false);
2003
+ const [saving, setSaving] = useState(false);
2004
+ const [notice, setNotice] = useState(null);
2005
+ const [online, setOnline] = useState(gateway.connection.status === "online");
2006
+ const latest = useRef({
2007
+ draft,
2008
+ saved,
2009
+ saving
2010
+ });
2011
+ latest.current = {
2012
+ draft,
2013
+ saved,
2014
+ saving
2015
+ };
2016
+ const invalidated = useRef(false);
2017
+ const uncertain = useRef(false);
2018
+ const lifetime = useRef(null);
2019
+ const controller = useRef(null);
2020
+ const reload = useCallback(async (notify = false) => {
2021
+ controller.current?.abort();
2022
+ const request = new AbortController();
2023
+ controller.current = request;
2024
+ setReading(true);
2025
+ setReadError(null);
1684
2026
  try {
1685
- const page = await client.call("config.agent.revisions", {
1686
- agentId,
1687
- ...next ? { cursor: next } : {}
1688
- });
1689
- if (generation.current !== token) return;
1690
- setItems((old) => next ? [...old, ...page.items.filter((row) => !old.some((item) => item.revision === row.revision))] : page.items);
1691
- setCurrent(page.currentRevision);
1692
- setCursor(page.nextCursor);
1693
- setPersistent(page.persistent);
1694
- } catch (cause) {
1695
- if (generation.current === token) setError(reason(cause));
2027
+ const result = await gateway.read("config.limits.get", {}, { signal: request.signal });
2028
+ if (!request.signal.aborted) {
2029
+ setSaved(result.limits);
2030
+ setBlocked(false);
2031
+ if (uncertain.current) setSaveError(translation.current("runSettings.unconfirmed"));
2032
+ if (!(latest.current.draft !== null && JSON.stringify(latest.current.draft) !== JSON.stringify(latest.current.saved))) {
2033
+ setDraft(null);
2034
+ if (JSON.stringify(result.limits) !== JSON.stringify(latest.current.saved)) setInputKey((key) => key + 1);
2035
+ } else if (notify) setNotice("changed");
2036
+ return result.limits;
2037
+ }
2038
+ } catch (error) {
2039
+ if (!request.signal.aborted) {
2040
+ setReadError(error instanceof Error ? error.message : String(error));
2041
+ if (error instanceof Error && "errorCode" in error && error.errorCode === "configuration_recovery_required") setBlocked(true);
2042
+ }
1696
2043
  } finally {
1697
- if (generation.current === token) setBusy(false);
2044
+ if (!request.signal.aborted) setReading(false);
1698
2045
  }
1699
- }, [client, agentId]);
2046
+ return null;
2047
+ }, [gateway]);
1700
2048
  useEffect(() => {
1701
- read();
2049
+ lifetime.current = new AbortController();
2050
+ reload();
1702
2051
  return () => {
1703
- generation.current++;
1704
- comparison.current++;
2052
+ controller.current?.abort();
2053
+ lifetime.current?.abort();
1705
2054
  };
1706
- }, [read, observedRevision]);
2055
+ }, [reload]);
1707
2056
  useEffect(() => {
1708
- let previous = client.connection.status;
1709
- return client.watchConnection((connection) => {
1710
- if (connection.status === "online" && previous !== "online") read();
1711
- previous = connection.status;
2057
+ let previous = gateway.connection.status;
2058
+ const off = gateway.watchConnection((state) => {
2059
+ setOnline(state.status === "online");
2060
+ if (state.status === "online" && previous !== "online") reload(true);
2061
+ previous = state.status;
1712
2062
  });
1713
- }, [client, read]);
1714
- useEffect(() => {
1715
- const token = ++comparison.current;
1716
- setChanges([]);
1717
- setComparisonError("");
1718
- setComparing(false);
1719
- if (selected === void 0 || compareTo === void 0 || selected === compareTo) return;
1720
- setComparing(true);
1721
- client.call("config.agent.compareRevisions", {
1722
- agentId,
1723
- fromRevision: selected,
1724
- toRevision: compareTo
1725
- }).then((result) => {
1726
- if (token === comparison.current) setChanges(result.changes);
1727
- }).catch((cause) => {
1728
- if (token === comparison.current) setComparisonError(reason(cause));
1729
- }).finally(() => {
1730
- if (token === comparison.current) setComparing(false);
2063
+ const stop = gateway.subscribe((frame) => {
2064
+ if (frame.kind !== "config.limitsChanged") return;
2065
+ if (latest.current.saving) invalidated.current = true;
2066
+ else reload(true);
1731
2067
  });
1732
- }, [
1733
- client,
1734
- agentId,
1735
- selected,
1736
- compareTo,
1737
- current
1738
- ]);
1739
- async function prepare(targetRevision) {
1740
- if (beforeLeave && !await beforeLeave()) return;
1741
- setBusy(true);
1742
- setError("");
1743
- setRequest(void 0);
1744
- try {
1745
- const value = await client.call("config.agent.previewRestore", {
1746
- agentId,
1747
- targetRevision
1748
- });
1749
- setPreview(value);
1750
- setRequest({
1751
- targetRevision,
1752
- expectedRevision: value.expectedRevision,
1753
- expectedContentHash: value.expectedContentHash,
1754
- restoreRequestId: uuid()
1755
- });
1756
- } catch (cause) {
1757
- setError(reason(cause));
1758
- } finally {
1759
- setBusy(false);
1760
- }
1761
- }
1762
- async function restore() {
1763
- if (!request || busy || restoring.current) return;
1764
- restoring.current = true;
1765
- setBusy(true);
1766
- setError("");
2068
+ return () => {
2069
+ off();
2070
+ stop();
2071
+ };
2072
+ }, [gateway, reload]);
2073
+ const guardState = useRef({
2074
+ dirty: false,
2075
+ pending: false
2076
+ });
2077
+ guardState.current = {
2078
+ dirty: draft !== null && JSON.stringify(draft) !== JSON.stringify(saved),
2079
+ pending: saving
2080
+ };
2081
+ useEffect(() => {
2082
+ registerGuard(() => guardState.current);
2083
+ return () => registerGuard(null);
2084
+ }, [registerGuard]);
2085
+ const values = draft ?? saved;
2086
+ const positive = (value) => value !== void 0 && Number.isSafeInteger(value) && value > 0;
2087
+ async function save() {
2088
+ if (values === null || saving || !online || reading || readError !== null || !positive(values.maxSteps) || values.tokenBudget !== void 0 && !positive(values.tokenBudget)) return;
2089
+ let committed = false;
2090
+ setSaving(true);
2091
+ uncertain.current = false;
2092
+ setSaveError(null);
1767
2093
  try {
1768
- const result = await client.call("config.agent.restoreRevision", {
1769
- agentId,
1770
- ...request
2094
+ const result = await gateway.call("config.limits.set", { limits: values }, {
2095
+ timeoutMs: 5e3,
2096
+ signal: lifetime.current?.signal
1771
2097
  });
1772
- useAgents.getState().consume({
1773
- kind: "config.agentChanged",
1774
- agent: result.agent
2098
+ if (lifetime.current?.signal.aborted) return;
2099
+ controller.current?.abort();
2100
+ setReading(false);
2101
+ committed = true;
2102
+ setSaved(result.limits);
2103
+ setDraft(null);
2104
+ setNotice(null);
2105
+ toast.add({
2106
+ tone: "success",
2107
+ title: t("runSettings.saved")
1775
2108
  });
1776
- setNotice(t("revisions.saved", {
1777
- revision: result.revision,
1778
- current: result.currentRevision
1779
- }));
1780
- setPreview(void 0);
1781
- setRequest(void 0);
1782
- await read();
1783
- } catch (cause) {
1784
- setError(reason(cause));
2109
+ } catch (error) {
2110
+ if (lifetime.current?.signal.aborted) return;
2111
+ const code = error instanceof Error && "errorCode" in error ? error.errorCode : void 0;
2112
+ const refused = error instanceof Error && "failure" in error && error.failure === "refused";
2113
+ if (code === "configuration_write_rejected" || refused && code !== "configuration_recovery_required") setSaveError(error instanceof Error ? error.message : String(error));
2114
+ else {
2115
+ uncertain.current = true;
2116
+ if (code === "configuration_recovery_required") setBlocked(true);
2117
+ setSaveError(t("runSettings.unconfirmedFailed"));
2118
+ await reload();
2119
+ }
1785
2120
  } finally {
1786
- restoring.current = false;
1787
- setBusy(false);
2121
+ if (!lifetime.current?.signal.aborted) {
2122
+ setSaving(false);
2123
+ if (invalidated.current) {
2124
+ invalidated.current = false;
2125
+ reload(!committed);
2126
+ }
2127
+ }
1788
2128
  }
1789
2129
  }
1790
- const diff = (rows) => /* @__PURE__ */ jsx("div", {
1791
- className: "space-y-4",
1792
- children: rows.map((row) => /* @__PURE__ */ jsxs("div", {
1793
- className: "space-y-2",
1794
- children: [/* @__PURE__ */ jsx("p", {
1795
- className: "text-xs font-medium",
1796
- children: t(`revisions.fields.${row.path}`, { defaultValue: row.path })
1797
- }), /* @__PURE__ */ jsx("div", {
1798
- className: "grid gap-2 sm:grid-cols-2",
1799
- children: [row.before, row.after].map((value, index) => /* @__PURE__ */ jsxs("div", {
1800
- className: "min-w-0 rounded-control bg-muted/40 p-3",
1801
- children: [/* @__PURE__ */ jsx("p", {
1802
- className: "mb-2 text-xs text-muted-foreground",
1803
- children: t(index === 0 ? "revisions.before" : "revisions.after")
1804
- }), row.path === "avatar" && typeof value === "string" ? /* @__PURE__ */ jsx("img", {
1805
- src: `data:image/png;base64,${value}`,
1806
- alt: t(index === 0 ? "revisions.before" : "revisions.after"),
1807
- className: "size-16 rounded-pill"
1808
- }) : /* @__PURE__ */ jsx("pre", {
1809
- className: "max-h-64 overflow-auto whitespace-pre-wrap break-words text-xs",
1810
- children: typeof value === "string" ? value || "∅" : JSON.stringify(value, null, 2)
1811
- })]
1812
- }, index === 0 ? "before" : "after"))
1813
- })]
1814
- }, row.path))
1815
- });
1816
- return /* @__PURE__ */ jsxs("section", {
1817
- className: "min-h-0 flex-1 space-y-4 overflow-auto px-6 pb-6",
1818
- "aria-label": t("revisions.title"),
1819
- children: [
1820
- /* @__PURE__ */ jsxs("div", {
1821
- className: "flex items-center justify-between",
1822
- children: [/* @__PURE__ */ jsx(Button, {
1823
- variant: "ghost",
1824
- size: "sm",
1825
- onClick: onClose,
1826
- children: t("revisions.back")
1827
- }), /* @__PURE__ */ jsx(Button, {
1828
- variant: "ghost",
1829
- size: "sm",
1830
- disabled: busy,
1831
- onClick: () => void read(),
1832
- children: t("revisions.refresh")
1833
- })]
1834
- }),
1835
- !persistent && /* @__PURE__ */ jsx("p", {
1836
- className: "text-xs text-muted-foreground",
1837
- children: t("revisions.memory")
1838
- }),
1839
- error && /* @__PURE__ */ jsx("p", {
1840
- role: "alert",
1841
- className: "text-sm text-destructive",
1842
- children: error
1843
- }),
1844
- notice && /* @__PURE__ */ jsx("p", {
1845
- role: "status",
1846
- className: "text-sm",
1847
- children: notice
1848
- }),
1849
- busy && /* @__PURE__ */ jsx("p", {
1850
- role: "status",
1851
- className: "text-sm text-muted-foreground",
1852
- children: t("revisions.loading")
1853
- }),
1854
- preview && /* @__PURE__ */ jsxs("div", {
1855
- className: "space-y-4 rounded-control border p-4",
1856
- children: [
1857
- /* @__PURE__ */ jsx("h4", { children: t("revisions.confirm", {
1858
- from: preview.expectedRevision,
1859
- to: preview.targetRevision
1860
- }) }),
1861
- /* @__PURE__ */ jsx("p", {
1862
- className: "text-xs text-muted-foreground",
1863
- children: t("revisions.timing")
1864
- }),
1865
- diff(preview.changes),
1866
- preview.blockers.map((blocker) => /* @__PURE__ */ jsxs("p", {
1867
- className: "text-sm text-destructive",
1868
- children: [
1869
- blocker.path,
1870
- ": ",
1871
- blocker.reason
1872
- ]
1873
- }, blocker.path + blocker.reason)),
1874
- preview.unchanged && /* @__PURE__ */ jsx("p", { children: t("revisions.unchanged") }),
1875
- /* @__PURE__ */ jsxs("div", {
1876
- className: "flex gap-2",
1877
- children: [
1878
- /* @__PURE__ */ jsx(Button, {
1879
- disabled: busy || preview.unchanged || preview.blockers.length > 0,
1880
- onClick: () => void restore(),
1881
- children: t("revisions.restore")
1882
- }),
1883
- /* @__PURE__ */ jsx(Button, {
1884
- variant: "ghost",
1885
- disabled: busy,
1886
- onClick: () => void prepare(preview.targetRevision),
1887
- children: t("revisions.refresh")
1888
- }),
1889
- /* @__PURE__ */ jsx(Button, {
1890
- variant: "ghost",
1891
- disabled: busy,
1892
- onClick: () => {
1893
- setPreview(void 0);
1894
- setRequest(void 0);
1895
- },
1896
- children: t("revisions.cancel")
1897
- })
1898
- ]
2130
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
2131
+ /* @__PURE__ */ jsx(ReadFailure, {
2132
+ reason: readError,
2133
+ pending: reading && values === null,
2134
+ onRetry: () => void reload()
2135
+ }),
2136
+ blocked && !reading && /* @__PURE__ */ jsx("p", {
2137
+ role: "alert",
2138
+ className: "text-xs text-destructive",
2139
+ children: t("runSettings.blocked")
2140
+ }),
2141
+ values && /* @__PURE__ */ jsxs("form", {
2142
+ className: "flex flex-col gap-6",
2143
+ onSubmit: (event) => {
2144
+ event.preventDefault();
2145
+ save();
2146
+ },
2147
+ children: [
2148
+ /* @__PURE__ */ jsx("p", {
2149
+ className: "text-xs text-muted-foreground",
2150
+ children: t("runSettings.timing")
2151
+ }),
2152
+ /* @__PURE__ */ jsx(Field, {
2153
+ label: t("runSettings.maxSteps"),
2154
+ required: true,
2155
+ inline: true,
2156
+ error: positive(values.maxSteps) ? void 0 : t("runSettings.positive"),
2157
+ children: (binding) => /* @__PURE__ */ jsx(InputNumber, {
2158
+ ...binding,
2159
+ label: t("runSettings.maxSteps"),
2160
+ incrementLabel: t("common.increase"),
2161
+ decrementLabel: t("common.decrease"),
2162
+ min: 1,
2163
+ step: 1,
2164
+ disabled: saving,
2165
+ value: values.maxSteps || null,
2166
+ onValueChange: (value) => setDraft({
2167
+ ...values,
2168
+ maxSteps: value ?? 0
2169
+ })
2170
+ }, inputKey)
2171
+ }),
2172
+ /* @__PURE__ */ jsx(Field, {
2173
+ label: t("runSettings.budgetEnabled"),
2174
+ inline: true,
2175
+ children: (binding) => /* @__PURE__ */ jsx(Switch, {
2176
+ ...binding,
2177
+ checked: values.tokenBudget !== void 0,
2178
+ disabled: saving,
2179
+ onCheckedChange: (checked) => setDraft(checked ? {
2180
+ ...values,
2181
+ tokenBudget: 0
2182
+ } : { maxSteps: values.maxSteps })
2183
+ })
2184
+ }),
2185
+ values.tokenBudget !== void 0 && /* @__PURE__ */ jsx(Field, {
2186
+ label: t("runSettings.tokenBudget"),
2187
+ required: true,
2188
+ inline: true,
2189
+ error: positive(values.tokenBudget) ? void 0 : t("runSettings.positive"),
2190
+ children: (binding) => /* @__PURE__ */ jsx(InputNumber, {
2191
+ ...binding,
2192
+ label: t("runSettings.tokenBudget"),
2193
+ incrementLabel: t("common.increase"),
2194
+ decrementLabel: t("common.decrease"),
2195
+ min: 1,
2196
+ step: 1,
2197
+ disabled: saving,
2198
+ value: values.tokenBudget || null,
2199
+ onValueChange: (value) => setDraft({
2200
+ ...values,
2201
+ tokenBudget: value ?? 0
2202
+ })
2203
+ }, inputKey)
2204
+ }),
2205
+ notice && /* @__PURE__ */ jsx("p", {
2206
+ role: "status",
2207
+ className: "text-xs text-muted-foreground",
2208
+ children: t("runSettings.changed")
2209
+ }),
2210
+ /* @__PURE__ */ jsx(FormFailure, { reason: saveError }),
2211
+ uncertain.current && saved && readError === null && !reading && /* @__PURE__ */ jsx("p", {
2212
+ className: "text-xs text-muted-foreground",
2213
+ children: t("runSettings.current", {
2214
+ steps: saved.maxSteps,
2215
+ budget: saved.tokenBudget ?? t("runSettings.unlimited")
2216
+ })
2217
+ }),
2218
+ /* @__PURE__ */ jsx("div", {
2219
+ className: "flex justify-end",
2220
+ children: /* @__PURE__ */ jsx(Button, {
2221
+ variant: "primary",
2222
+ type: "submit",
2223
+ loading: saving,
2224
+ disabled: !online || reading || readError !== null || !positive(values.maxSteps) || values.tokenBudget !== void 0 && !positive(values.tokenBudget),
2225
+ children: t("common.save")
1899
2226
  })
1900
- ]
1901
- }),
1902
- /* @__PURE__ */ jsx("ol", {
1903
- className: "divide-y",
1904
- children: items.map((item) => {
1905
- const expanded = selected === item.revision;
1906
- const canExpand = items.length > 1 || item.revision !== current || !!item.source.sessionId;
1907
- const heading = /* @__PURE__ */ jsxs("span", {
1908
- className: "min-w-0 flex-1 space-y-1",
1909
- children: [/* @__PURE__ */ jsxs("span", {
1910
- className: "block text-sm font-medium break-words",
1911
- children: [
1912
- "v",
1913
- item.revision,
1914
- " · ",
1915
- item.summary
1916
- ]
1917
- }), /* @__PURE__ */ jsxs("span", {
1918
- className: "block text-xs text-muted-foreground",
1919
- children: [
1920
- new Date(item.createdAt).toLocaleString(i18n.language),
1921
- " ·",
1922
- " ",
1923
- t(`revisions.${item.source.kind}`)
1924
- ]
1925
- })]
1926
- });
1927
- const currentMark = item.revision === current && /* @__PURE__ */ jsx("span", {
1928
- className: "shrink-0 rounded-control bg-muted px-2 py-1 text-xs text-muted-foreground",
1929
- children: t("revisions.current")
1930
- });
1931
- return /* @__PURE__ */ jsxs("li", {
1932
- className: "py-2",
1933
- children: [canExpand ? /* @__PURE__ */ jsxs(Button, {
1934
- variant: "plain",
1935
- "aria-expanded": expanded,
1936
- className: "flex w-full items-center gap-3 rounded-control p-3 text-start hover:bg-muted/50 focus-visible:ring-2 focus-visible:ring-ring",
1937
- onClick: () => {
1938
- setSelected(expanded ? void 0 : item.revision);
1939
- setCompareTo(item.revision === current ? items.find((option) => option.revision !== item.revision)?.revision : current);
1940
- },
1941
- children: [
1942
- heading,
1943
- currentMark,
1944
- /* @__PURE__ */ jsx(ChevronDown, {
1945
- "aria-hidden": "true",
1946
- className: `size-4 shrink-0 text-muted-foreground transition-transform ${expanded ? "rotate-180" : ""}`
1947
- })
1948
- ]
1949
- }) : /* @__PURE__ */ jsxs("div", {
1950
- className: "flex items-center gap-3 p-3",
1951
- children: [heading, currentMark]
1952
- }), expanded && /* @__PURE__ */ jsxs("div", {
1953
- className: "space-y-4 px-3 pt-3 pb-2",
1954
- children: [compareTo !== void 0 && compareTo !== item.revision && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("label", {
1955
- className: "flex flex-wrap items-center gap-2 text-xs text-muted-foreground",
1956
- children: [
1957
- t("revisions.compare"),
1958
- " · v",
1959
- item.revision,
1960
- " →",
1961
- /* @__PURE__ */ jsx(Select, {
1962
- size: "sm",
1963
- "aria-label": t("revisions.compare"),
1964
- value: String(compareTo),
1965
- onValueChange: (value) => setCompareTo(Number(value)),
1966
- children: items.filter((option) => option.revision !== item.revision).map((option) => /* @__PURE__ */ jsxs("option", {
1967
- value: option.revision,
1968
- children: ["v", option.revision]
1969
- }, option.revision))
1970
- })
1971
- ]
1972
- }), comparing ? /* @__PURE__ */ jsx("p", {
1973
- role: "status",
1974
- className: "text-xs text-muted-foreground",
1975
- children: t("revisions.loading")
1976
- }) : comparisonError ? /* @__PURE__ */ jsx("p", {
1977
- role: "alert",
1978
- className: "text-xs text-destructive",
1979
- children: comparisonError
1980
- }) : changes.length === 0 ? /* @__PURE__ */ jsx("p", {
1981
- className: "text-xs text-muted-foreground",
1982
- children: t("revisions.noDifference")
1983
- }) : diff(changes)] }), /* @__PURE__ */ jsxs("div", {
1984
- className: "flex flex-wrap gap-2",
1985
- children: [item.revision !== current && /* @__PURE__ */ jsx(Button, {
1986
- variant: "outline",
1987
- size: "sm",
1988
- disabled: busy,
1989
- onClick: () => void prepare(item.revision),
1990
- children: t("revisions.restore")
1991
- }), item.source.sessionId && /* @__PURE__ */ jsx(Button, {
1992
- variant: "ghost",
1993
- size: "sm",
1994
- onClick: async () => {
1995
- if (beforeLeave && !await beforeLeave()) return;
1996
- if (!await goToSession(client, item.source.sessionId)) setError(t("revisions.sourceMissing"));
1997
- else useNavigation.getState().openSettings(false);
1998
- },
1999
- children: t("revisions.source")
2000
- })]
2001
- })]
2002
- })]
2003
- }, item.revision);
2004
2227
  })
2005
- }),
2006
- cursor && /* @__PURE__ */ jsx(Button, {
2007
- variant: "ghost",
2008
- disabled: busy,
2009
- onClick: () => void read(cursor),
2010
- children: t("revisions.more")
2011
- })
2012
- ]
2013
- });
2228
+ ]
2229
+ })
2230
+ ] });
2014
2231
  }
2015
2232
  //#endregion
2016
- //#region ui-src/components/settings/agent/tools.tsx
2017
- /** Uses extension metadata without interpreting package names or tool naming conventions. */
2018
- function groupsOf(tools, describe, unknownSource) {
2019
- const groups = /* @__PURE__ */ new Map();
2020
- for (const tool of tools) {
2021
- const facts = describe(tool) ?? {
2022
- key: `plugin:${tool.plugin}`,
2023
- label: tool.plugin || unknownSource,
2024
- source: tool.plugin || unknownSource,
2025
- sectionLabel: unknownSource,
2026
- sectionOrder: 2,
2027
- order: 0
2028
- };
2029
- const group = groups.get(facts.key) ?? {
2030
- ...facts,
2031
- tools: []
2032
- };
2033
- groups.set(facts.key, {
2034
- ...group,
2035
- tools: [...group.tools, tool]
2036
- });
2037
- }
2038
- return [...groups.values()].map((group) => ({
2039
- ...group,
2040
- tools: [...group.tools].sort((a, b) => a.name.localeCompare(b.name))
2041
- })).sort((a, b) => a.sectionOrder - b.sectionOrder || a.order - b.order || a.label.localeCompare(b.label));
2233
+ //#region ui-src/components/settings/run-settings.tsx
2234
+ /** Fixed global running-settings entrance owned by Agent management. */
2235
+ function RunSettingsButton({ ctx }) {
2236
+ const { t } = useTranslation();
2237
+ const [open, setOpen] = useState(false);
2238
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(TooltipHint, {
2239
+ content: t("runSettings.title"),
2240
+ children: /* @__PURE__ */ jsx(Button, {
2241
+ variant: "plain",
2242
+ size: "sm",
2243
+ icon: "settings",
2244
+ "aria-label": t("runSettings.title"),
2245
+ onClick: () => setOpen(true)
2246
+ })
2247
+ }), open && /* @__PURE__ */ jsx(RunSettingsDialog, {
2248
+ ctx,
2249
+ onClose: () => setOpen(false)
2250
+ })] });
2042
2251
  }
2043
- function SelectAll({ group, chosen, onChange }) {
2252
+ /** One retained page per live owner, with a shared close guard and independent saves. */
2253
+ function RunSettingsDialog({ ctx, onClose }) {
2044
2254
  const { t } = useTranslation();
2045
- const count = group.tools.filter((tool) => chosen.has(tool.name)).length;
2046
- return /* @__PURE__ */ jsx(Checkbox, {
2047
- "aria-label": t("agents.toolSettings.selectAll", { group: group.label }),
2048
- title: t("agents.toolSettings.selectWholeGroup", { count: group.tools.length }),
2049
- checked: count === group.tools.length,
2050
- ref: (element) => {
2051
- if (element) element.indeterminate = count > 0 && count < group.tools.length;
2255
+ const state = usePlugins((state) => state);
2256
+ const pages = contributionsIn(state, "shell.agentRunSettings.section");
2257
+ const [selected, setSelected] = useState("execution");
2258
+ const shown = selected === "execution" || pages.some((page) => page.key === selected) ? selected : "execution";
2259
+ useEffect(() => {
2260
+ if (shown !== selected) setSelected(shown);
2261
+ }, [shown, selected]);
2262
+ const guards = useRef(/* @__PURE__ */ new Map());
2263
+ const register = useCallback((key, guard) => {
2264
+ if (guard) guards.current.set(key, guard);
2265
+ else guards.current.delete(key);
2266
+ }, []);
2267
+ const labels = new Map([["execution", t("runSettings.execution")], ...pages.map((page) => [page.key, resolveLabel(page.contribution.label, page.key)])]);
2268
+ const [asking, setAsking] = useState(null);
2269
+ const requestClose = () => {
2270
+ const valid = [...guards.current].filter(([key]) => labels.has(key));
2271
+ if (valid.some(([, guard]) => guard().pending)) return;
2272
+ const dirty = valid.filter(([, guard]) => guard().dirty).map(([key]) => key);
2273
+ if (dirty.length > 0) setAsking(dirty);
2274
+ else onClose();
2275
+ };
2276
+ const executionGuard = useCallback((guard) => register("execution", guard), [register]);
2277
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Dialog, {
2278
+ open: true,
2279
+ onOpenChange: (next) => {
2280
+ if (!next) requestClose();
2052
2281
  },
2053
- onChange: (event) => onChange(group.tools.map((tool) => tool.name), event.target.checked),
2054
- className: "shrink-0"
2055
- });
2056
- }
2057
- function ToolRow({ tool, checked, onChange }) {
2058
- const describedBy = useId();
2059
- return /* @__PURE__ */ jsx("li", {
2060
- className: "border-t border-border/60 first:border-t-0",
2061
- children: /* @__PURE__ */ jsxs("label", {
2062
- className: "flex min-w-0 cursor-pointer items-start gap-2.5 px-3 py-2 hover:bg-muted/50",
2063
- children: [/* @__PURE__ */ jsx(Checkbox, {
2064
- "aria-label": tool.name,
2065
- "aria-describedby": tool.description ? describedBy : void 0,
2066
- checked,
2067
- onChange: (event) => onChange(event.target.checked),
2068
- className: "mt-0.5 shrink-0"
2069
- }), /* @__PURE__ */ jsxs("span", {
2070
- className: "flex min-w-0 flex-1 flex-col gap-0.5 @lg:flex-row @lg:items-baseline @lg:gap-3",
2071
- children: [/* @__PURE__ */ jsx("span", {
2072
- className: "min-w-0 shrink-0 break-all font-mono text-xs text-foreground @lg:w-40",
2073
- children: tool.name
2074
- }), tool.description && /* @__PURE__ */ jsx("span", {
2075
- id: describedBy,
2076
- "data-slot": "tool-description",
2077
- title: tool.description,
2078
- className: "line-clamp-2 min-w-0 flex-1 text-xs text-muted-foreground @lg:line-clamp-1",
2079
- children: tool.description
2080
- })]
2282
+ children: /* @__PURE__ */ jsxs(DialogContent, {
2283
+ closeLabel: t("settings.close"),
2284
+ overlayProps: {
2285
+ forceRender: true,
2286
+ className: "file-picker-backdrop"
2287
+ },
2288
+ className: "@container max-w-md gap-5 p-6 sm:max-w-md",
2289
+ children: [/* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: t("runSettings.title") }) }), /* @__PURE__ */ jsxs(Tabs, {
2290
+ value: shown,
2291
+ onValueChange: (next) => setSelected(String(next)),
2292
+ children: [
2293
+ /* @__PURE__ */ jsxs(TabsList, {
2294
+ "aria-label": t("runSettings.title"),
2295
+ className: "mb-5 w-full",
2296
+ children: [/* @__PURE__ */ jsx(TabsTrigger, {
2297
+ value: "execution",
2298
+ children: t("runSettings.execution")
2299
+ }), pages.map((page) => /* @__PURE__ */ jsx(TabsTrigger, {
2300
+ value: page.key,
2301
+ "data-plugin": page.owner,
2302
+ children: labels.get(page.key)
2303
+ }, page.key))]
2304
+ }),
2305
+ /* @__PURE__ */ jsx(TabsContent, {
2306
+ value: "execution",
2307
+ keepMounted: true,
2308
+ children: /* @__PURE__ */ jsx(ExecutionLimits, {
2309
+ ctx,
2310
+ registerGuard: executionGuard,
2311
+ requestClose
2312
+ })
2313
+ }),
2314
+ pages.map((page) => /* @__PURE__ */ jsx(TabsContent, {
2315
+ value: page.key,
2316
+ keepMounted: true,
2317
+ children: /* @__PURE__ */ jsx(OwnerSection, {
2318
+ registrationKey: page.key,
2319
+ register,
2320
+ requestClose
2321
+ })
2322
+ }, page.key))
2323
+ ]
2081
2324
  })]
2082
2325
  })
2083
- });
2326
+ }), /* @__PURE__ */ jsxs(AlertDialog, {
2327
+ open: asking !== null,
2328
+ onOpenChange: (next) => {
2329
+ if (!next) setAsking(null);
2330
+ },
2331
+ title: t("agents.leaveTitle"),
2332
+ actions: /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Button, {
2333
+ variant: "ghost",
2334
+ onClick: () => setAsking(null),
2335
+ children: t("agents.leaveStay")
2336
+ }), /* @__PURE__ */ jsx(Button, {
2337
+ variant: "destructive",
2338
+ onClick: onClose,
2339
+ children: t("agents.discard")
2340
+ })] }),
2341
+ children: [/* @__PURE__ */ jsx("p", { children: t("agents.leaveBody") }), /* @__PURE__ */ jsx("ul", {
2342
+ className: "list-disc ps-5",
2343
+ children: asking?.filter((key) => labels.has(key)).map((key) => /* @__PURE__ */ jsx("li", { children: labels.get(key) }, key))
2344
+ })]
2345
+ })] });
2084
2346
  }
2085
- /** Tool access tab; selection changes stay in the shared agent editor draft. */
2086
- function ToolsTab() {
2087
- const { t } = useTranslation();
2088
- const editor = useAgentEditor();
2089
- const { agent } = editor;
2090
- const listing = useGatewayRead("config.tool.list", { agentId: agent.agentId });
2091
- const tools = listing.data?.agentId === agent.agentId ? listing.data.tools : null;
2092
- const whitelist = editor.value("tools");
2093
- const unrestricted = whitelist === null;
2094
- const chosen = new Set(unrestricted ? [] : whitelist);
2095
- const known = new Set((tools ?? []).map((tool) => tool.name));
2096
- const unavailable = unrestricted ? [] : whitelist.filter((name) => !known.has(name));
2097
- const [query, setQuery] = useState("");
2098
- const [filter, setFilter] = useState("all");
2099
- const [expanded, setExpanded] = useState(/* @__PURE__ */ new Set());
2100
- const [collapsed, setCollapsed] = useState(/* @__PURE__ */ new Set());
2101
- const pluginState = usePlugins((state) => state);
2102
- const presentations = contributionsIn(pluginState, "shell.tools.group");
2103
- const groups = groupsOf(tools ?? [], (tool) => presentations.map((one) => one.contribution.describe(tool)).find((value) => value !== void 0), t("agents.toolSettings.unknownSource"));
2104
- const search = query.trim().toLocaleLowerCase();
2105
- const visible = groups.map((group) => ({
2106
- group,
2107
- tools: group.tools.filter((tool) => (!search || [
2108
- tool.name,
2109
- tool.description,
2110
- group.label,
2111
- group.source
2112
- ].some((value) => value.toLocaleLowerCase().includes(search))) && (filter === "all" || filter === "selected" === chosen.has(tool.name)))
2113
- })).filter(({ tools: members }) => members.length > 0);
2114
- const matching = visible.reduce((total, one) => total + one.tools.length, 0);
2115
- const allExpanded = visible.every(({ group }) => expanded.has(group.key) || group.defaultExpanded === true && !collapsed.has(group.key));
2116
- function change(names, on) {
2117
- if (whitelist === null) return;
2118
- const without = whitelist.filter((name) => !names.includes(name));
2119
- editor.set("tools", on ? [...without, ...names] : without);
2120
- }
2121
- function toggle(key) {
2122
- const next = new Set(expanded);
2123
- const isOpen = next.has(key) || groups.find((one) => one.key === key)?.defaultExpanded === true && !collapsed.has(key);
2124
- const hidden = new Set(collapsed);
2125
- if (isOpen) {
2126
- next.delete(key);
2127
- hidden.add(key);
2128
- } else {
2129
- next.add(key);
2130
- hidden.delete(key);
2347
+ function OwnerSection({ registrationKey, register, requestClose }) {
2348
+ const registerGuard = useCallback((guard) => register(registrationKey, guard), [registrationKey, register]);
2349
+ useEffect(() => () => registerGuard(null), [registerGuard]);
2350
+ return /* @__PURE__ */ jsx(SlotOutlet, {
2351
+ slot: "shell.agentRunSettings.section",
2352
+ only: registrationKey,
2353
+ props: {
2354
+ registerGuard,
2355
+ requestClose
2131
2356
  }
2132
- setCollapsed(hidden);
2133
- setExpanded(next);
2134
- }
2135
- return /* @__PURE__ */ jsxs("div", {
2136
- className: "@container flex min-w-0 flex-col gap-4",
2137
- children: [
2138
- /* @__PURE__ */ jsx(ChangedElsewhere, { fields: ["tools"] }),
2139
- /* @__PURE__ */ jsxs("div", {
2140
- className: "flex min-w-0 flex-col gap-3 @lg:flex-row @lg:items-start @lg:justify-between",
2141
- children: [/* @__PURE__ */ jsxs("div", {
2142
- className: "min-w-0",
2143
- children: [/* @__PURE__ */ jsx("h3", {
2144
- className: "text-sm font-semibold",
2145
- children: t("agents.toolSettings.heading")
2146
- }), /* @__PURE__ */ jsx("p", {
2147
- className: "mt-1 text-xs leading-relaxed text-muted-foreground",
2148
- children: t("agents.toolSettings.hint")
2149
- })]
2150
- }), /* @__PURE__ */ jsx(Segmented, {
2151
- label: t("agents.toolSettings.mode"),
2152
- value: unrestricted ? "all" : "custom",
2153
- disabled: tools === null && unrestricted,
2154
- options: [{
2155
- value: "custom",
2156
- label: t("agents.toolSettings.custom")
2157
- }, {
2158
- value: "all",
2159
- label: t("agents.toolSettings.allowAll")
2160
- }],
2161
- onSelect: (mode) => editor.set("tools", mode === "all" ? null : (tools ?? []).filter((tool) => tool.permitted).map((tool) => tool.name))
2162
- })]
2163
- }),
2164
- /* @__PURE__ */ jsx(ReadFailure, {
2165
- reason: listing.error,
2166
- pending: listing.pending && listing.data === null,
2167
- onRetry: listing.reload
2168
- }),
2169
- !unrestricted && /* @__PURE__ */ jsxs(Fragment, { children: [
2170
- /* @__PURE__ */ jsx("div", {
2171
- "data-slot": "tool-search-divider",
2172
- className: "border-t border-border"
2173
- }),
2174
- /* @__PURE__ */ jsxs("div", {
2175
- className: "flex min-w-0 flex-col gap-2 @lg:flex-row @lg:items-center",
2176
- children: [/* @__PURE__ */ jsxs("label", {
2177
- className: "flex min-w-0 flex-1 items-center gap-2 rounded-control border border-border bg-input/30 px-2.5 focus-within:border-ring",
2178
- children: [/* @__PURE__ */ jsx(Search, {
2179
- className: "size-4 shrink-0 text-muted-foreground",
2180
- "aria-hidden": "true"
2181
- }), /* @__PURE__ */ jsx(Input, {
2182
- type: "search",
2183
- "aria-label": t("agents.toolSettings.searchLabel"),
2184
- placeholder: t("agents.toolSettings.searchPlaceholder"),
2185
- value: query,
2186
- onChange: (event) => setQuery(event.target.value),
2187
- className: "h-8 min-w-0 flex-1 border-0 bg-transparent text-xs outline-none focus-visible:border-0 placeholder:text-muted-foreground"
2188
- })]
2189
- }), /* @__PURE__ */ jsx(FilterChips, {
2190
- label: t("agents.toolSettings.filterLabel"),
2191
- value: filter,
2192
- options: [
2193
- {
2194
- value: "all",
2195
- label: t("agents.toolSettings.filterAll")
2196
- },
2197
- {
2198
- value: "selected",
2199
- label: t("agents.toolSettings.filterSelected")
2200
- },
2201
- {
2202
- value: "unselected",
2203
- label: t("agents.toolSettings.filterUnselected")
2204
- }
2205
- ],
2206
- onSelect: (value) => setFilter(value)
2207
- })]
2208
- }),
2209
- whitelist.length === 0 && /* @__PURE__ */ jsx(Warning, { children: t("agents.toolSettings.none") }),
2210
- tools !== null && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("div", {
2211
- className: "flex items-center gap-2 text-xs text-muted-foreground",
2212
- children: [
2213
- /* @__PURE__ */ jsx("span", { children: t("agents.toolSettings.chosen", {
2214
- chosen: tools.filter((tool) => chosen.has(tool.name)).length,
2215
- total: tools.length
2216
- }) }),
2217
- (search || filter !== "all") && /* @__PURE__ */ jsx("span", { children: t("agents.toolSettings.matching", { count: matching }) }),
2218
- visible.length > 0 && !search && filter === "all" && /* @__PURE__ */ jsx(Button, {
2219
- variant: "ghost",
2220
- size: "sm",
2221
- className: "ms-auto h-7 text-xs",
2222
- onClick: () => {
2223
- setExpanded(allExpanded ? /* @__PURE__ */ new Set() : new Set(groups.map((group) => group.key)));
2224
- setCollapsed(allExpanded ? new Set(groups.map((group) => group.key)) : /* @__PURE__ */ new Set());
2225
- },
2226
- children: t(allExpanded ? "agents.toolSettings.collapseAll" : "agents.toolSettings.expandAll")
2227
- })
2228
- ]
2229
- }), /* @__PURE__ */ jsxs("div", {
2230
- "data-slot": "tool-list",
2231
- className: "flex min-w-0 flex-col gap-3",
2232
- children: [
2233
- tools.length === 0 && unavailable.length === 0 && /* @__PURE__ */ jsx("p", {
2234
- className: "text-xs text-muted-foreground",
2235
- children: t("agents.toolsEmpty")
2236
- }),
2237
- matching === 0 && tools.length > 0 && /* @__PURE__ */ jsxs("div", {
2238
- className: "flex flex-col items-center gap-2 py-6 text-center text-xs text-muted-foreground",
2239
- children: [/* @__PURE__ */ jsx("p", { children: t("agents.toolSettings.noMatches") }), /* @__PURE__ */ jsx(Button, {
2240
- variant: "outline",
2241
- size: "sm",
2242
- onClick: () => {
2243
- setQuery("");
2244
- setFilter("all");
2245
- },
2246
- children: t("agents.toolSettings.clearFilters")
2247
- })]
2248
- }),
2249
- visible.map(({ group, tools: members }, index) => {
2250
- const forcedOpen = Boolean(search || filter !== "all");
2251
- const open = forcedOpen || expanded.has(group.key) || group.defaultExpanded === true && !collapsed.has(group.key);
2252
- const count = group.tools.filter((tool) => chosen.has(tool.name)).length;
2253
- const previous = visible[index - 1]?.group.sectionOrder;
2254
- return /* @__PURE__ */ jsxs("div", { children: [group.sectionOrder !== previous && /* @__PURE__ */ jsx("p", {
2255
- className: "mb-2 text-xs text-muted-foreground",
2256
- children: group.sectionLabel
2257
- }), /* @__PURE__ */ jsxs("section", {
2258
- "aria-label": group.label,
2259
- "data-slot": "tool-group",
2260
- className: "min-w-0 overflow-hidden rounded-control border border-border",
2261
- children: [/* @__PURE__ */ jsxs("header", {
2262
- className: "flex min-w-0 items-center gap-2 px-3 py-2",
2263
- children: [/* @__PURE__ */ jsx(SelectAll, {
2264
- group,
2265
- chosen,
2266
- onChange: change
2267
- }), /* @__PURE__ */ jsxs(Button, {
2268
- variant: "plain",
2269
- "aria-label": t(open ? "agents.toolSettings.collapse" : "agents.toolSettings.expand", { group: group.label }),
2270
- "aria-expanded": open,
2271
- disabled: forcedOpen,
2272
- onClick: () => toggle(group.key),
2273
- className: "flex min-w-0 flex-1 items-center gap-2 text-start disabled:opacity-100",
2274
- children: [
2275
- /* @__PURE__ */ jsx("span", {
2276
- className: "min-w-0 truncate text-xs font-medium",
2277
- children: group.label
2278
- }),
2279
- /* @__PURE__ */ jsx("span", {
2280
- className: "min-w-0 truncate font-mono text-2xs text-muted-foreground",
2281
- children: group.source
2282
- }),
2283
- /* @__PURE__ */ jsxs("span", {
2284
- "data-slot": "tool-group-count",
2285
- className: "ms-auto shrink-0 text-2xs tabular-nums text-muted-foreground",
2286
- children: [
2287
- count,
2288
- "/",
2289
- group.tools.length
2290
- ]
2291
- }),
2292
- /* @__PURE__ */ jsx(ChevronDown, { className: cn("size-4 shrink-0 text-muted-foreground transition-transform", open && "rotate-180") })
2293
- ]
2294
- })]
2295
- }), open && /* @__PURE__ */ jsx("ul", {
2296
- className: "border-t border-border",
2297
- children: members.map((tool) => /* @__PURE__ */ jsx(ToolRow, {
2298
- tool,
2299
- checked: chosen.has(tool.name),
2300
- onChange: (on) => change([tool.name], on)
2301
- }, tool.name))
2302
- })]
2303
- })] }, group.key);
2304
- }),
2305
- unavailable.length > 0 && !search && filter !== "unselected" && /* @__PURE__ */ jsxs("section", {
2306
- "aria-label": t("agents.toolSettings.unavailable"),
2307
- "data-slot": "tool-unavailable",
2308
- className: "rounded-control border border-dashed border-border px-3 py-2",
2309
- children: [
2310
- /* @__PURE__ */ jsx("h4", {
2311
- className: "text-xs font-medium",
2312
- children: t("agents.toolSettings.unavailable")
2313
- }),
2314
- /* @__PURE__ */ jsx("p", {
2315
- className: "mt-1 text-2xs text-muted-foreground",
2316
- children: t("agents.toolSettings.unavailableHint")
2317
- }),
2318
- /* @__PURE__ */ jsx("ul", {
2319
- className: "mt-2 flex flex-col gap-1",
2320
- children: unavailable.map((name) => /* @__PURE__ */ jsxs("li", {
2321
- className: "flex min-w-0 items-center gap-2",
2322
- children: [/* @__PURE__ */ jsx("span", {
2323
- className: "min-w-0 flex-1 truncate font-mono text-xs text-muted-foreground line-through",
2324
- children: name
2325
- }), /* @__PURE__ */ jsx(Button, {
2326
- size: "sm",
2327
- variant: "ghost",
2328
- "aria-label": `${t("common.remove")} ${name}`,
2329
- onClick: () => change([name], false),
2330
- children: t("common.remove")
2331
- })]
2332
- }, name))
2333
- })
2334
- ]
2335
- })
2336
- ]
2337
- })] })
2338
- ] }),
2339
- /* @__PURE__ */ jsx(FormFailure, { reason: editor.error("tools") })
2340
- ]
2341
2357
  });
2342
2358
  }
2343
2359
  //#endregion
@@ -2853,6 +2869,7 @@ function DirectChatToggle({ agent, onChanged }) {
2853
2869
  function RemoveAgentButton({ agent, onRemoved }) {
2854
2870
  const { t } = useTranslation();
2855
2871
  const remove = useGatewayAction();
2872
+ const operationId = useRef(uuid());
2856
2873
  const [asking, setAsking] = useState(false);
2857
2874
  return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs(Tooltip, { children: [/* @__PURE__ */ jsx(TooltipTrigger, {
2858
2875
  "aria-label": `${t("agents.remove")} ${agent.name}`,
@@ -2886,7 +2903,14 @@ function RemoveAgentButton({ agent, onRemoved }) {
2886
2903
  variant: "destructive",
2887
2904
  disabled: remove.pending,
2888
2905
  onClick: () => {
2889
- remove.run((client) => client.call("config.agent.remove", { agentId: agent.agentId })).then((done) => {
2906
+ remove.run(async (client) => {
2907
+ const result = await client.call("config.agent.remove", {
2908
+ operationId: operationId.current,
2909
+ agentIds: [agent.agentId]
2910
+ });
2911
+ if (result.operationState === "admitted") throw new Error(t("common.working"));
2912
+ return result;
2913
+ }).then((done) => {
2890
2914
  if (!done.ok) return;
2891
2915
  setAsking(false);
2892
2916
  onRemoved();