@songsid/agend 2.3.5-alpha.12 → 2.3.5-alpha.14

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 (139) hide show
  1. package/THIRD_PARTY_NOTICES.md +4 -0
  2. package/dist/agent-export.d.ts +74 -0
  3. package/dist/agent-export.js +362 -0
  4. package/dist/agent-export.js.map +1 -0
  5. package/dist/agent-workspace.d.ts +1 -2
  6. package/dist/agent-workspace.js +8 -29
  7. package/dist/agent-workspace.js.map +1 -1
  8. package/dist/auth-api.js +3 -1
  9. package/dist/auth-api.js.map +1 -1
  10. package/dist/backend/codex.d.ts +7 -14
  11. package/dist/backend/codex.js +25 -29
  12. package/dist/backend/codex.js.map +1 -1
  13. package/dist/backend/grok-mcp.d.ts +5 -0
  14. package/dist/backend/grok-mcp.js +221 -0
  15. package/dist/backend/grok-mcp.js.map +1 -0
  16. package/dist/backend/grok.d.ts +0 -10
  17. package/dist/backend/grok.js +5 -82
  18. package/dist/backend/grok.js.map +1 -1
  19. package/dist/backend/types.d.ts +6 -1
  20. package/dist/backend/types.js.map +1 -1
  21. package/dist/build-provenance.json +1 -1
  22. package/dist/cli.js +45 -12
  23. package/dist/cli.js.map +1 -1
  24. package/dist/codex-pane-ownership.d.ts +13 -0
  25. package/dist/codex-pane-ownership.js +192 -0
  26. package/dist/codex-pane-ownership.js.map +1 -0
  27. package/dist/daemon.d.ts +2 -0
  28. package/dist/daemon.js +89 -8
  29. package/dist/daemon.js.map +1 -1
  30. package/dist/fleet-manager.d.ts +15 -1
  31. package/dist/fleet-manager.js +72 -17
  32. package/dist/fleet-manager.js.map +1 -1
  33. package/dist/hub/client.d.ts +1 -1
  34. package/dist/hub/client.js +11 -0
  35. package/dist/hub/client.js.map +1 -1
  36. package/dist/hub/compose/member.d.ts +2 -2
  37. package/dist/hub/compose/member.js +11 -3
  38. package/dist/hub/compose/member.js.map +1 -1
  39. package/dist/hub/join/local.d.ts +1 -0
  40. package/dist/hub/join/local.js +8 -3
  41. package/dist/hub/join/local.js.map +1 -1
  42. package/dist/hub/member/exposure-api.d.ts +2 -0
  43. package/dist/hub/member/exposure-api.js +4 -2
  44. package/dist/hub/member/exposure-api.js.map +1 -1
  45. package/dist/hub/member/pairing-api.d.ts +2 -2
  46. package/dist/hub/member/pairing-api.js +2 -2
  47. package/dist/hub/member/pairing-api.js.map +1 -1
  48. package/dist/hub/server.js +8 -0
  49. package/dist/hub/server.js.map +1 -1
  50. package/dist/hub-pairing-summary.d.ts +3 -1
  51. package/dist/hub-pairing-summary.js +6 -3
  52. package/dist/hub-pairing-summary.js.map +1 -1
  53. package/dist/install-user-systemd.d.ts +20 -0
  54. package/dist/install-user-systemd.js +55 -0
  55. package/dist/install-user-systemd.js.map +1 -0
  56. package/dist/linux-launchers.d.ts +88 -0
  57. package/dist/linux-launchers.js +296 -0
  58. package/dist/linux-launchers.js.map +1 -0
  59. package/dist/locale.js +91 -4
  60. package/dist/locale.js.map +1 -1
  61. package/dist/runtime-client-store.js +5 -0
  62. package/dist/runtime-client-store.js.map +1 -1
  63. package/dist/runtime-pane-private.d.ts +2 -0
  64. package/dist/runtime-pane-private.js +25 -0
  65. package/dist/runtime-pane-private.js.map +1 -1
  66. package/dist/runtime-pane-private.ps1 +74 -7
  67. package/dist/selection-card.d.ts +4 -3
  68. package/dist/selection-card.js +2 -1
  69. package/dist/selection-card.js.map +1 -1
  70. package/dist/service-installer.js +11 -2
  71. package/dist/service-installer.js.map +1 -1
  72. package/dist/settings-change.d.ts +2 -0
  73. package/dist/settings-change.js +74 -31
  74. package/dist/settings-change.js.map +1 -1
  75. package/dist/settings-confirmation.d.ts +23 -0
  76. package/dist/settings-confirmation.js +13 -2
  77. package/dist/settings-confirmation.js.map +1 -1
  78. package/dist/settings-effect.d.ts +4 -0
  79. package/dist/settings-effect.js +14 -14
  80. package/dist/settings-effect.js.map +1 -1
  81. package/dist/settings-http-confirmation.d.ts +3 -1
  82. package/dist/settings-http-confirmation.js +12 -7
  83. package/dist/settings-http-confirmation.js.map +1 -1
  84. package/dist/settings-summary.d.ts +24 -0
  85. package/dist/settings-summary.js +42 -0
  86. package/dist/settings-summary.js.map +1 -0
  87. package/dist/transcript-delta-reader.d.ts +9 -1
  88. package/dist/transcript-delta-reader.js +37 -8
  89. package/dist/transcript-delta-reader.js.map +1 -1
  90. package/dist/ui/agent-details-settings.js +253 -0
  91. package/dist/ui/agent-export-dialog.js +169 -0
  92. package/dist/ui/agent-export-strings.js +81 -0
  93. package/dist/ui/agent-instructions-field.js +69 -0
  94. package/dist/ui/agent-page-strings.js +148 -0
  95. package/dist/ui/chat-quote.js +12 -17
  96. package/dist/ui/hub-client.js +1 -1
  97. package/dist/ui/hub-company-join-strings.js +1 -1
  98. package/dist/ui/hub-company-join.js +7 -0
  99. package/dist/ui/hub-strings.js +4 -0
  100. package/dist/ui/native-instance-settings.js +47 -14
  101. package/dist/ui/panel-details.js +38 -14
  102. package/dist/ui/panel-fleet.js +2 -2
  103. package/dist/ui/panel-settings.js +12 -9
  104. package/dist/ui/settings-access-overview.js +24 -3
  105. package/dist/ui/settings-confirm.js +5 -5
  106. package/dist/ui/settings-dialogs.js +210 -100
  107. package/dist/ui/settings-hub-company-join.js +69 -14
  108. package/dist/ui/settings-hub.js +13 -5
  109. package/dist/ui/settings-layout.js +0 -2
  110. package/dist/ui/settings-model.js +15 -0
  111. package/dist/ui/shared/access-overview.css +48 -0
  112. package/dist/ui/shared/app-i18n.js +2 -2
  113. package/dist/ui/shared/app-shell.js +144 -3
  114. package/dist/ui/shared/app.css +74 -50
  115. package/dist/ui/shared/instance-nav.js +5 -1
  116. package/dist/ui/shared/view-strings.js +2 -0
  117. package/dist/update-dispatch.d.ts +62 -0
  118. package/dist/update-dispatch.js +69 -2
  119. package/dist/update-dispatch.js.map +1 -1
  120. package/dist/web-api.d.ts +2 -0
  121. package/dist/web-api.js +49 -0
  122. package/dist/web-api.js.map +1 -1
  123. package/dist/web-session.d.ts +4 -2
  124. package/dist/web-session.js +5 -2
  125. package/dist/web-session.js.map +1 -1
  126. package/dist/windows-shortcuts.d.ts +29 -5
  127. package/dist/windows-shortcuts.js +52 -9
  128. package/dist/windows-shortcuts.js.map +1 -1
  129. package/dist/workspace-file-policy.d.ts +2 -0
  130. package/dist/workspace-file-policy.js +31 -0
  131. package/dist/workspace-file-policy.js.map +1 -0
  132. package/dist/workspace-follow.js +2 -1
  133. package/dist/workspace-follow.js.map +1 -1
  134. package/launcher/agend-install.cjs +7 -1
  135. package/package.json +2 -2
  136. package/templates/icons/agend-restart.ico +0 -0
  137. package/templates/icons/agend.ico +0 -0
  138. package/templates/runtime-assets/runtime-pane-private.ps1 +74 -7
  139. package/templates/windows-shortcuts.ps1 +45 -12
@@ -0,0 +1,253 @@
1
+ // one agent's "Details & settings" page — the Details tab with its settings beside the read-only facts.
2
+ // Categories on the left (a tab row in the middle, a list on a phone), each one a group of the agent's settings, with the
3
+ // read-only Overview first. The fields are the ones the Settings dialogs always had (settings-dialogs.js: useAgentForm /
4
+ // AgentFields; native-instance-settings.js; useClassicForm / ClassicFields) — this file adds only where they live:
5
+ // - the categories and their nav (the shared Settings `.s-nav`, with an icon in front of every item you can open);
6
+ // - the staging: an edit is staged at once (the Settings page's own "N changes pending" bar and its confirmations),
7
+ // and the Apply is the app's runner (settings-apply.js) — nothing here writes by itself;
8
+ // - one read of the configuration the first time a settings category is opened (#1374: nothing recurring).
9
+ import { html, useEffect, useRef, useState } from "/assets/app-html.js";
10
+ import { t } from "/assets/app-i18n.js";
11
+ import { appStore, useStore } from "/assets/app-store.js";
12
+ import { navigate, setLeaveGuard } from "/assets/app-nav.js";
13
+ import { detailsPath } from "/assets/app-route.js";
14
+ import { Icon } from "/assets/ui-icons.js";
15
+ import { toast } from "/assets/ui-toast.js";
16
+ import { Skeleton, ErrorState } from "/assets/ui-states.js";
17
+ import { PageHead } from "/assets/page-head.js";
18
+ import "./settings-strings.js";
19
+ import "./settings-shared-strings.js";
20
+ import "./settings-restart-strings.js";
21
+ import "./agent-page-strings.js";
22
+ import { pt } from "./agent-page-strings.js";
23
+ import { operationActive, startOperation, takeLeftover } from "./settings-apply.js";
24
+ import { batchImpact, impactOf, shortName } from "./settings-model.js";
25
+ import { AGENT_CATEGORIES, AgentFields, CLASSIC_CATEGORIES, ClassicFields, ask, useAgentForm, useClassicForm } from "./settings-dialogs.js";
26
+ import { NATIVE_CATEGORIES, NativeFields, useNativeForm } from "./native-instance-settings.js";
27
+
28
+ const tn = (k, ...v) => t(`settings.${k}`, ...v);
29
+
30
+ /** The icon in front of each category you can open — the project's own set (ui-icons.js). */
31
+ export const CATEGORY_ICONS = { overview: "eye", basic: "idcard", runtime: "bot", work: "view", channel: "chat", adv: "code" };
32
+ /** Which kind of page this is: a ClassicBot room (classicBot.yaml), a Windows native agent, or a fleet agent. */
33
+ export const agentKind = (d, inst) => (d && d.kind === "classic" ? "classic" : inst && inst.runtime === "windows" ? "native" : "fleet");
34
+ /** The categories of a kind, Overview first. A native agent has no channel binding or idle settings; a ClassicBot room has no basic info or workspace. */
35
+ export const categoriesOf = (kind) => ["overview", ...(kind === "classic" ? CLASSIC_CATEGORIES : kind === "native" ? NATIVE_CATEGORIES : AGENT_CATEGORIES)];
36
+ export const categoryLabel = (kind, cat) => pt(kind === "classic" && cat === "channel" ? "cat_classicChannel" : `cat_${cat}`);
37
+ /** The category the address names (`?cat=`), or "" for none — the phone's list, and Overview on a wide screen. */
38
+ export function categoryFromSearch(kind, search = typeof location !== "undefined" ? location.search : "") {
39
+ const cat = new URLSearchParams(search).get("cat") || "";
40
+ if (categoriesOf(kind).includes(cat)) return cat;
41
+ // A category this kind has no page for (the sidebar's ⚙ always names Basic info) goes to its first one.
42
+ return Object.keys(CATEGORY_ICONS).includes(cat) ? categoriesOf(kind)[1] : "";
43
+ }
44
+ export const categoryPath = (name, cat) => (cat ? `${detailsPath(name)}?cat=${cat}` : detailsPath(name));
45
+
46
+ /** Which category each key of a patch belongs to (a dot on the nav says "this one has changes"). */
47
+ const AGENT_KEYS = {
48
+ basic: ["display_name", "description", "systemPrompt", "tags"],
49
+ runtime: ["backend", "model", "model_failover", "backend_options"],
50
+ work: ["working_directory", "auto_pause_after", "hang_detector", "agent_mode", "tool_set", "reply_completion_guard", "lightweight"],
51
+ channel: ["channel_id", "general_topic", "tool_progress", "cross_instance_visibility", "status_emojis"],
52
+ adv: ["log_level", "resume_interrupted_work", "mcp_proxy_reply", "board_cards_at_once", "dashboard", "office_access", "office_pack_access"],
53
+ };
54
+ const NATIVE_KEYS = { basic: ["display_name", "description", "tags"], runtime: ["model"], work: ["native_sandbox"], adv: ["systemPrompt"] };
55
+ const CLASSIC_KEYS = { runtime: ["backend", "model", "auto_pause_after"], channel: ["tool_progress", "reply_completion_guard", "reply_triggers", "collab", "web_echo", "context_lines"] };
56
+ export function dirtyCategories(kind, patch) {
57
+ const map = kind === "classic" ? CLASSIC_KEYS : kind === "native" ? NATIVE_KEYS : AGENT_KEYS;
58
+ const keys = Object.keys(patch || {});
59
+ return new Set(Object.entries(map).filter(([, list]) => keys.some((k) => list.includes(k))).map(([cat]) => cat));
60
+ }
61
+
62
+ /** What one agent's edit costs and where it is sent — the same request the dialog's Done stages (panel-settings.js makeCtx). */
63
+ export function changeFor(ctx, kind, name, inst, room, patch) {
64
+ const { schema } = ctx;
65
+ if (kind === "classic") {
66
+ const hotOnly = Object.keys(patch).every((k) => impactOf(schema, `classic.${k}`) === "now");
67
+ return { label: tn("updateAgent", room.name || room.instanceName), impact: hotOnly ? "now" : "instance",
68
+ request: { method: "PATCH", url: `/api/settings/classic/channels/${encodeURIComponent(room.key)}`, body: patch } };
69
+ }
70
+ const native = inst.runtime === "windows";
71
+ return { label: tn("updateAgent", shortName(name, { ...inst, ...patch })),
72
+ impact: native ? "now" : batchImpact(schema, Object.keys(patch), (k) => impactOf(schema, `instance.${k}`)),
73
+ request: { method: "PATCH", url: native ? `/ui/instances/${encodeURIComponent(name)}` : `/api/settings/fleet/instances/${encodeURIComponent(name)}`, body: patch } };
74
+ }
75
+
76
+ // ── The staging: this page's, with the Settings page's rules ──
77
+
78
+ let settingsModule = null;
79
+ /** panel-settings.js — its reader of the configuration, its context and its pending bar — loaded when a settings category first opens. */
80
+ const loadSettingsModule = () => (settingsModule ||= import("./panel-settings.js"));
81
+
82
+ /**
83
+ * The configuration of this page (read the first time `enabled`), the changes staged against it, and the Apply. Staged
84
+ * changes wait for the Apply bar (one runner: the app's, settings-apply.js); leaving the page with some asks first.
85
+ */
86
+ export function useAgentSettings({ name, lease, enabled, navKey }) {
87
+ const [mod, setMod] = useState(null);
88
+ const [data, setData] = useState(null);
89
+ const [staged, setStaged] = useState(() => new Map());
90
+ const stagedRef = useRef(staged);
91
+ stagedRef.current = staged;
92
+ const [epoch, setEpoch] = useState(0); // moves after a Discard and after a Save: the forms start again from what is saved
93
+ const gen = useRef(0);
94
+ const { settingsOp: op } = useStore(appStore);
95
+ const started = useRef(false);
96
+ const nameRef = useRef(name);
97
+ nameRef.current = name;
98
+ const submitted = useRef(new Map()); // the changes as they were when a Save began (what comes back after a failure keeps its confirms)
99
+
100
+ const reload = async () => {
101
+ const m = await loadSettingsModule();
102
+ const mine = ++gen.current;
103
+ const next = await m.loadAll(lease);
104
+ if (!next || mine !== gen.current || !lease.current()) return;
105
+ setMod(m);
106
+ // A read that fails after a failed Save keeps what was read before: the forms (and the draft in them) stay.
107
+ setData((prev) => (next.error && prev && !prev.error ? prev : next));
108
+ };
109
+ useEffect(() => { if (enabled && !started.current) { started.current = true; reload(); } }, [enabled]);
110
+
111
+ const stage = (key, change, quiet = true) => {
112
+ setStaged((s) => { const m = new Map(s); m.set(key, { ...change, stageKey: key }); return m; });
113
+ if (!quiet) toast(tn("queued", change.label));
114
+ return true;
115
+ };
116
+ const unstage = (key) => setStaged((s) => { if (!s.has(key)) return s; const m = new Map(s); m.delete(key); return m; });
117
+ const discard = () => { setStaged(new Map()); setEpoch((n) => n + 1); reload(); };
118
+
119
+ // Leaving the page with staged changes asks first (the Settings page's question); the same agent's other categories are not leaving.
120
+ useEffect(() => {
121
+ let asking = false;
122
+ lease.hold(setLeaveGuard((to, path) => {
123
+ const n = stagedRef.current.size;
124
+ if (!n || (to && to.panel === "details" && to.instance === nameRef.current)) return true;
125
+ if (!asking) {
126
+ asking = true;
127
+ ask(tn("discardOnLeave", n), { confirmLabel: tn("discard"), danger: true }).then((yes) => {
128
+ asking = false;
129
+ if (!yes || !lease.current()) return;
130
+ stagedRef.current = new Map();
131
+ navigate(path, { force: true });
132
+ });
133
+ }
134
+ return false;
135
+ }));
136
+ lease.on(window, "beforeunload", (e) => { if (stagedRef.current.size) { e.preventDefault(); e.returnValue = ""; } });
137
+ }, [lease]);
138
+
139
+ // Changes a failed Apply did not land come back to be staged again.
140
+ useEffect(() => {
141
+ if (!op || !op.leftover || !op.leftover.length) return;
142
+ const back = takeLeftover();
143
+ if (!back.length) return;
144
+ setStaged((s) => { const m = new Map(s); for (const c of back) { const k = c.stageKey || c.key; if (k && !m.has(k)) m.set(k, { ...(submitted.current.get(k) || {}), ...c, stageKey: k }); } return m; });
145
+ }, [op && op.leftover]);
146
+
147
+ // An Apply that finished changed the configuration: read it again, and draw the forms from it.
148
+ const lastPhase = useRef(op ? op.phase : null);
149
+ useEffect(() => {
150
+ const phase = op ? op.phase : null;
151
+ if (lastPhase.current !== phase && (phase === "done" || phase === "failed") && started.current) {
152
+ reload().finally(() => { if (phase === "done") setEpoch((n) => n + 1); });
153
+ }
154
+ lastPhase.current = phase;
155
+ }, [op && op.phase]);
156
+
157
+ const applying = useRef(false);
158
+ const apply = async () => {
159
+ if (applying.current || operationActive() || !stagedRef.current.size) return;
160
+ if ([...stagedRef.current.values()].some((c) => c.invalid)) return;
161
+ applying.current = true;
162
+ try {
163
+ for (const c of [...stagedRef.current.values()]) {
164
+ for (const k of c.confirms || []) {
165
+ const yes = await ask(k.includes(".") ? t(k) : tn(k));
166
+ if (!lease.current()) return;
167
+ if (!yes) { toast(tn("accessChangeCancelled"), false); return; }
168
+ }
169
+ }
170
+ } finally { applying.current = false; }
171
+ if (!lease.current() || operationActive()) return;
172
+ const list = [...stagedRef.current.values()].map(({ label, impact, request, stageKey, key }) => ({ label, impact, request, stageKey, key }));
173
+ if (startOperation(list)) { submitted.current = new Map(stagedRef.current); setStaged(new Map()); }
174
+ };
175
+
176
+ const ctx = mod && data && !data.error
177
+ ? mod.makeCtx(data, setData, stage, unstage, reload, reload, () => lease.current(), { drafts: new Map(), draftEpoch: epoch, staged, savingDrafts: () => null, savingStaged: () => null })
178
+ : null;
179
+ return { mod, data, ctx, staged, stage, unstage, discard, apply, op, epoch, reload };
180
+ }
181
+
182
+ // ── The nav ──
183
+
184
+ /** The categories in the shared Settings `.s-nav`: "Status" (Overview) and "Settings" (the rest), an icon in front of every item. */
185
+ export function AgentCategoryNav({ name, kind, cat, dirty }) {
186
+ const cats = categoriesOf(kind);
187
+ const item = (id) => html`<a key=${id} href=${categoryPath(name, id)} class=${`seg-item${cat === id ? " active" : ""}`} aria-current=${cat === id ? "page" : undefined} title=${categoryLabel(kind, id)}>
188
+ <${Icon} name=${CATEGORY_ICONS[id]} size=${16} /><span>${categoryLabel(kind, id)}</span>${dirty && dirty.has(id) ? html`<span class="count" role="img" aria-label=${pt("unsavedDot")} title=${pt("unsavedDot")}>●</span>` : null}</a>`;
189
+ return html`<nav data-trust="panel-navigation" class="seg s-nav" aria-label=${pt("title")}><div class="s-nav-groups">
190
+ <div class="s-nav-group" role="group" aria-labelledby="ap-grp-status"><span class="s-nav-head" id="ap-grp-status">${pt("groupStatus")}</span>${item("overview")}</div>
191
+ <div class="s-nav-group" role="group" aria-labelledby="ap-grp-settings"><span class="s-nav-head" id="ap-grp-settings">${pt("groupSettings")}</span>${cats.slice(1).map(item)}</div></div></nav>`;
192
+ }
193
+
194
+ /** The page's heading: the category's name, who it affects, and a line on what it is. */
195
+ export function AgentPageHead({ name, kind, cat, inst }) {
196
+ return html`<${PageHead} title=${categoryLabel(kind, cat)} scope=${pt("onlyThis", inst ? shortName(name, inst) : name)} lead=${cat === "overview" ? pt("leadOverview") : pt("leadSection")} />`;
197
+ }
198
+
199
+ // ── The forms ──
200
+
201
+ /**
202
+ * Every category's fields, drawn once the configuration is in and kept mounted (hidden when not current), so moving between
203
+ * categories never drops a draft. Each edit is staged as it is made; an edit put back leaves nothing staged.
204
+ */
205
+ function AgentForms({ name, kind, cat, sess, inst, room, onDirty, onDelete, deleting }) {
206
+ const { ctx } = sess;
207
+ const key = kind === "classic" ? `classic:${room.key}` : `agent:${name}`;
208
+ const form = kind === "classic" ? useClassicForm({ room, ctx }) : kind === "native" ? useNativeForm({ name, inst, ctx }) : useAgentForm({ name, inst, ctx });
209
+ const patch = form.pending();
210
+ const patchJson = JSON.stringify(patch);
211
+ const ready = form.ready;
212
+ useEffect(() => {
213
+ onDirty(dirtyCategories(kind, patch));
214
+ if (deleting) return;
215
+ if (!Object.keys(patch).length) { sess.unstage(key); return; }
216
+ const change = changeFor(ctx, kind, name, inst, room, patch);
217
+ // Turning the MCP proxy reply on is asked about first (it can post raw screen text to a channel): the Save asks.
218
+ const confirms = patch.mcp_proxy_reply === true ? ["agentPage.confirmMcpProxy"] : undefined;
219
+ sess.stage(key, { ...change, ...(confirms ? { confirms } : {}), ...(ready ? {} : { invalid: true }) });
220
+ }, [patchJson, ready, deleting]);
221
+ const cats = categoriesOf(kind).slice(1);
222
+ const Fields = kind === "classic" ? ClassicFields : kind === "native" ? NativeFields : AgentFields;
223
+ return cats.map((c) => html`<div key=${c} class="ap-panel" id=${`ap-panel-${c}`} hidden=${c !== cat}>
224
+ <${Fields} m=${form} cat=${c} onDelete=${kind === "fleet" && c === "adv" ? onDelete : undefined} /></div>`);
225
+ }
226
+
227
+ /** The settings categories' bodies: a read of the configuration first, then the forms. */
228
+ export function AgentSettingsPanels({ name, kind, cat, sess, onDirty }) {
229
+ const { data, ctx, staged, stage } = sess;
230
+ const del = staged.get(kind === "classic" ? "" : `agent:${name}`);
231
+ const deleting = !!del && del.request && del.request.method === "DELETE";
232
+ if (!data) return html`<${Skeleton} lines=${6} label=${pt("loading")} />`;
233
+ if (data.error || !ctx) return html`<${ErrorState} message=${pt("loadFailed")} onRetry=${sess.reload} />`;
234
+ const insts = (ctx.fleet && ctx.fleet.instances) || {};
235
+ const own = (o, k) => !!o && Object.prototype.hasOwnProperty.call(o, k);
236
+ let inst = null, room = null;
237
+ if (kind === "classic") {
238
+ const rooms = (ctx.classic && ctx.classic.channels) || {};
239
+ const k = Object.keys(rooms).find((x) => own(rooms, x) && rooms[x] && rooms[x].instanceName === name);
240
+ if (k) room = { key: k, ...rooms[k] };
241
+ } else if (own(insts, name)) inst = insts[name];
242
+ if (!inst && !room) return html`<p class="note">${pt("notConfigured")}</p>`;
243
+ // A deletion is staged on the same key as this agent's edits: say so, and stop staging edits over it.
244
+ const onDelete = async () => {
245
+ if (!(await ask(tn("deleteAgent", name), { confirmLabel: tn("deleteAgentMenu"), danger: true }))) return;
246
+ const native = inst.runtime === "windows";
247
+ stage(`agent:${name}`, { label: tn("deleteAgentLabel", name), impact: native ? "now" : impactOf(ctx.schema, "instance.delete"),
248
+ request: { method: "DELETE", url: native ? `/ui/instances/${encodeURIComponent(name)}` : `/api/settings/fleet/instances/${encodeURIComponent(name)}` } }, false);
249
+ };
250
+ return html`${kind === "classic" ? html`<p class="s-info"><span aria-hidden="true">ⓘ</span><span>${pt("classicNote")}</span></p>` : null}
251
+ ${deleting ? html`<p class="feedback warning" role="status">${tn("deleteAgentLabel", name)}</p>` : null}
252
+ <${AgentForms} key=${sess.epoch} name=${name} kind=${kind} cat=${cat} sess=${sess} inst=${inst} room=${room} onDirty=${onDirty} onDelete=${onDelete} deleting=${deleting} />`;
253
+ }
@@ -0,0 +1,169 @@
1
+ // AGEND-163: "Export" and "Load template" beside an agent's Agent instructions (its systemPrompt). The file (<role>.agend-agent.yaml, agend_export: 1)
2
+ // is built and read by the server (agent-export.ts: the project's own `yaml` package and one allow-list for both directions);
3
+ // this file is only the two dialogs. Loading changes nothing by itself — it fills the same form the person edits by hand, so
4
+ // the Save bar and its confirmations (tool sets, access…) apply exactly as they always did.
5
+ import { html, useEffect, useRef, useState } from "/assets/app-html.js";
6
+ import { Dialog } from "/assets/ui-dialog.js";
7
+ import { Icon } from "/assets/ui-icons.js";
8
+ import { toast } from "/assets/ui-toast.js";
9
+ import "./agent-export-strings.js";
10
+ import { xt } from "./agent-export-strings.js";
11
+
12
+ const GROUPS = ["identity", "systemPrompt", "runtime", "behavior"];
13
+ const DEFAULT_GROUPS = ["identity", "systemPrompt", "runtime", "behavior"];
14
+ /** The largest file the loader reads (agent-export.ts AGENT_EXPORT_MAX_CHARS). */
15
+ const MAX_FILE_CHARS = 200000;
16
+ /** The server reads a request body of at most 512 KiB (web-api.ts parseBody): a bigger file is refused here, with the same words. */
17
+ const MAX_FILE_BYTES = 480 * 1024;
18
+
19
+ async function post(path, body) {
20
+ const r = await fetch(path, { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
21
+ if (!r.ok) throw new Error(String(r.status));
22
+ return r.json();
23
+ }
24
+
25
+ /** The form's fields a file's values land in (names as agent-export.ts's FillValues; `inherit` = the key of "use the default"). */
26
+ const FILL = {
27
+ description: { to: "description" }, tags: { to: "tags" }, systemPrompt: { to: "systemPrompt" }, model: { to: "model" },
28
+ model_failover: { to: "model_failover", inherit: "model_failover" }, tool_set: { to: "tool_set", inherit: "tool_set" }, lightweight: { to: "lightweight", inherit: "lightweight" },
29
+ hang_detector: { to: "hang", inherit: "hang", text: true }, tool_progress: { to: "tool_progress", inherit: "tool_progress" }, reply_completion_guard: { to: "reply_completion_guard", inherit: "reply_completion_guard" },
30
+ log_level: { to: "log_level", inherit: "log_level" }, auto_pause_after: { to: "auto_pause_after", inherit: "auto_pause_after", text: true }, agent_mode: { to: "agent_mode", inherit: "agent_mode" },
31
+ cross_instance_visibility: { to: "cross_instance_visibility", inherit: "cross_instance_visibility" }, board_cards_at_once: { to: "board_cards_at_once", text: true }, resume_interrupted_work: { to: "resume_interrupted_work" },
32
+ };
33
+ export const FILL_KEYS = Object.keys(FILL);
34
+
35
+ /** Put the values of a checked file into the agent form (useAgentForm's setF). A setting a file names stops following the default. */
36
+ export function applyFill(setF, fill) {
37
+ setF((form) => {
38
+ const next = { ...form, inherit: { ...form.inherit } };
39
+ for (const [key, value] of Object.entries(fill)) {
40
+ const spec = Object.prototype.hasOwnProperty.call(FILL, key) ? FILL[key] : null;
41
+ if (!spec) continue;
42
+ next[spec.to] = spec.text ? String(value) : Array.isArray(value) ? [...value] : value;
43
+ if (spec.inherit) next.inherit[spec.inherit] = false;
44
+ }
45
+ return next;
46
+ });
47
+ }
48
+
49
+ const shortValue = (v) => {
50
+ const s = Array.isArray(v) ? v.join(", ") : typeof v === "boolean" ? (v ? "on" : "off") : String(v);
51
+ const one = s.replace(/\s+/g, " ").trim();
52
+ return one.length > 60 ? `${one.slice(0, 60)}…` : one;
53
+ };
54
+
55
+ /** Export: what to include (left), the file as it would be written (below), secrets stopping the download. */
56
+ export function ExportDialog({ name, pending, onClose }) {
57
+ const [groups, setGroups] = useState(() => new Set(DEFAULT_GROUPS));
58
+ const [result, setResult] = useState(null);
59
+ const [failed, setFailed] = useState(false);
60
+ const seq = useRef(0);
61
+ const alive = useRef(true);
62
+ useEffect(() => () => { alive.current = false; }, []);
63
+ useEffect(() => {
64
+ const mine = ++seq.current;
65
+ setFailed(false);
66
+ setResult(null); // the old preview is gone the moment the choice changes: nothing stale can be copied
67
+ post("/ui/agent-export/build", { instance: name, include: GROUPS.filter((g) => groups.has(g)) })
68
+ .then((r) => { if (alive.current && mine === seq.current) setResult(r); })
69
+ .catch(() => { if (alive.current && mine === seq.current) { setResult(null); setFailed(true); } });
70
+ }, [[...groups].sort().join(",")]);
71
+ const toggle = (g) => setGroups((s) => { const n = new Set(s); if (n.has(g)) n.delete(g); else n.add(g); return n; });
72
+ const text = result && typeof result.text === "string" ? result.text : null;
73
+ const findings = (result && result.findings) || [];
74
+ const fields = [...new Set(findings.map((f) => f.field))];
75
+ const usable = !!text && !result.empty;
76
+ const copy = async () => {
77
+ try { await navigator.clipboard.writeText(text); toast(xt("copied")); } catch { toast(xt("copyFailed"), false); }
78
+ };
79
+ const download = () => {
80
+ const url = URL.createObjectURL(new Blob([text], { type: "text/yaml;charset=utf-8" }));
81
+ const a = document.createElement("a");
82
+ a.href = url; a.download = `${name}.agend-agent.yaml`;
83
+ document.body.appendChild(a); a.click(); a.remove();
84
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
85
+ };
86
+ return html`<${Dialog} title=${xt("exportTitle")} onClose=${onClose} wide=${true}
87
+ actions=${html`<button type="button" class="btn" onClick=${copy} disabled=${!usable} data-export-copy><${Icon} name="copy" size=${15} /> ${xt("copy")}</button>
88
+ <button type="button" class="btn btn-primary" onClick=${download} disabled=${!usable} data-export-download><${Icon} name="download" size=${15} /> ${xt("download")}</button>`}>
89
+ <div class="form">
90
+ <p class="note">${xt("exportLead")}</p>
91
+ ${pending ? html`<p class="feedback warning" role="status">${xt("pending")}</p>` : null}
92
+ <fieldset class="field"><legend>${xt("pick")}</legend>
93
+ ${GROUPS.map((g) => html`<label class="check" key=${g}><input type="checkbox" checked=${groups.has(g)} data-export-group=${g} onChange=${() => toggle(g)} /><span>${xt(`g_${g}`)}</span></label>`)}</fieldset>
94
+ ${findings.length ? html`<div class="feedback error" role="alert" data-export-secret><strong>${xt("secretTitle")}</strong>
95
+ <p>${xt("secretBody", fields.join(", "))}</p>
96
+ <ul>${findings.map((f, i) => html`<li key=${i}>${xt("secretAt", f.field, f.line)} — ${xt(`kind_${f.kind}`)}</li>`)}</ul></div>` : null}
97
+ ${failed ? html`<p class="feedback error" role="alert">${xt("exportFailed")}</p>` : null}
98
+ ${(result && result.omitted || []).map((o) => html`<p class="feedback warning" role="status" key=${o.field + o.reason} data-export-omitted=${o.reason}>${xt(`o_${o.reason}`)}</p>`)}
99
+ ${result && result.empty && !findings.length ? html`<p class="note">${xt("nothing")}</p>` : null}
100
+ <div class="field"><label for="ag-export-preview">${xt("previewLabel")}</label>
101
+ <textarea id="ag-export-preview" rows="14" readonly spellcheck=${false} value=${text === null ? (result ? "" : xt("building")) : text} data-export-preview /></div>
102
+ <details class="field"><summary>${xt("notExported")}</summary><p class="note">${xt("notExportedBody")}</p></details>
103
+ </div></${Dialog}>`;
104
+ }
105
+
106
+ /** Load template: choose or paste, see what would be filled and what skipped (with why), then fill the form. */
107
+ export function LoadDialog({ current, onFill, onClose }) {
108
+ const [text, setText] = useState("");
109
+ const [busy, setBusy] = useState(false);
110
+ const [res, setRes] = useState(null); // the server's reading of `text`, or { error }
111
+ const [note, setNote] = useState("");
112
+ const alive = useRef(true);
113
+ const seq = useRef(0);
114
+ useEffect(() => () => { alive.current = false; }, []);
115
+ const edit = (value) => { seq.current++; setText(value); setRes(null); setNote(""); setBusy(false); };
116
+ const onFile = async (e) => {
117
+ const file = e.target.files && e.target.files[0];
118
+ e.target.value = "";
119
+ if (!file) return;
120
+ if (file.size > MAX_FILE_BYTES) { setRes({ error: "too_large" }); setNote(xt("fileTooLarge")); return; }
121
+ try { edit(await file.text()); } catch { setRes({ error: "read" }); setNote(xt("readFailed")); }
122
+ };
123
+ const check = async () => {
124
+ const mine = ++seq.current;
125
+ setBusy(true);
126
+ try {
127
+ const r = await post("/ui/agent-export/parse", { text });
128
+ if (alive.current && mine === seq.current) setRes(r.ok ? r : { error: r.error });
129
+ } catch { if (alive.current && mine === seq.current) setRes({ error: "failed" }); }
130
+ finally { if (alive.current && mine === seq.current) setBusy(false); }
131
+ };
132
+ const ok = res && res.ok;
133
+ const fillKeys = ok ? FILL_KEYS.filter((k) => Object.prototype.hasOwnProperty.call(res.fill, k)) : [];
134
+ const replaces = (k) => (k === "description" || k === "systemPrompt") && current && String(current[k] || "").trim() !== "" && current[k] !== res.fill[k];
135
+ const doFill = () => { onFill(res.fill); toast(xt("filled", fillKeys.length)); onClose(); };
136
+ return html`<${Dialog} title=${xt("loadTitle")} onClose=${onClose} wide=${true} busy=${busy}
137
+ actions=${html`<button type="button" class="btn" onClick=${check} disabled=${busy || !text.trim()} data-load-check>${busy ? xt("checking") : xt("check")}</button>
138
+ <button type="button" class="btn btn-primary" onClick=${doFill} disabled=${!ok || !fillKeys.length} data-load-fill>${xt("fill")}</button>`}>
139
+ <div class="form">
140
+ <p class="note">${xt("loadLead")}</p>
141
+ <div class="field"><label class="btn btn-sm"><${Icon} name="file" size=${15} /> ${xt("chooseFile")}<input type="file" accept=".yaml,.yml,.txt,text/yaml,text/plain" hidden data-load-file onChange=${onFile} /></label></div>
142
+ <div class="field"><label for="ag-load-text">${xt("pasteLabel")}</label>
143
+ <textarea id="ag-load-text" rows="10" spellcheck=${false} placeholder=${xt("pastePlaceholder")} value=${text} data-load-text onInput=${(e) => edit(e.target.value)} /></div>
144
+ ${note ? html`<p class="feedback error" role="alert">${note}</p>` : null}
145
+ ${res && res.error && !note ? html`<p class="feedback error" role="alert" data-load-error>${xt(`e_${res.error}`)}</p>` : null}
146
+ ${ok ? html`<div data-load-preview>
147
+ <p><strong>${xt("willFill", fillKeys.length)}</strong></p>
148
+ ${fillKeys.length ? html`<ul>${fillKeys.map((k) => html`<li key=${k} data-fill=${k}><strong>${xt(`f_${k}`)}</strong>: ${k === "systemPrompt" ? xt("nChars", String(res.fill[k]).length.toLocaleString("en-US")) : shortValue(res.fill[k])}${replaces(k) ? ` — ${xt("replaces")}` : ""}</li>`)}</ul>` : html`<p class="note">${xt("fillNone")}</p>`}
149
+ <p><strong>${xt("willSkip", res.skipped.length)}</strong></p>
150
+ ${res.skipped.length ? html`<ul>${res.skipped.map((s, i) => html`<li key=${i} data-skip=${s.path}><code>${s.path}</code> — ${xt(`r_${s.reason}`)}</li>`)}</ul>` : html`<p class="note">${xt("skipNone")}</p>`}
151
+ ${res.role ? html`<p class="note">${xt("roleHint", res.role)}</p>` : null}
152
+ ${res.libraryUsed ? html`<p class="note" data-load-library>${xt("libraryNote")}</p>` : null}
153
+ ${res.extraFailover ? html`<p class="note">${xt("failoverNote")}</p>` : null}
154
+ ${Object.prototype.hasOwnProperty.call(res.fill, "model") ? html`<p class="note">${xt("modelNote")}</p>` : null}
155
+ </div>` : null}
156
+ </div></${Dialog}>`;
157
+ }
158
+
159
+ /** The two buttons under the Instructions field, and the dialogs they open. `m`: useAgentForm's result. */
160
+ export function AgentTemplateTools({ name, m }) {
161
+ const [open, setOpen] = useState(null);
162
+ const pending = Object.keys(m.pending()).length > 0;
163
+ return html`<div class="field template-tools"><p class="note">${xt("fieldsHint")}</p>
164
+ <div class="seg-inline" role="group" aria-label=${xt("loadTemplate")}>
165
+ <button type="button" class="btn btn-sm" data-template-load onClick=${() => setOpen("load")}><${Icon} name="file" size=${15} /> ${xt("loadTemplate")}</button>
166
+ <button type="button" class="btn btn-sm" data-template-export onClick=${() => setOpen("export")}><${Icon} name="download" size=${15} /> ${xt("exportBtn")}</button></div>
167
+ ${open === "export" ? html`<${ExportDialog} name=${name} pending=${pending} onClose=${() => setOpen(null)} />` : null}
168
+ ${open === "load" ? html`<${LoadDialog} current=${m.f} onFill=${(fill) => applyFill(m.setF, fill)} onClose=${() => setOpen(null)} />` : null}</div>`;
169
+ }
@@ -0,0 +1,81 @@
1
+ // AGEND-163: the words of an agent's Export and Load-template dialogs (agent-export-dialog.js). Its own namespace and file, as
2
+ // agent-page-strings.js is: no tab holding an older strings file can be missing them.
3
+ import { register, t } from "/assets/app-i18n.js";
4
+
5
+ register("agentExport", {
6
+ en: {
7
+ loadTemplate: "Load template", exportBtn: "Export", fieldsHint: "A template is one file of this agent's portable settings (Agent instructions, model, behaviour…). Account, folder, channel and permission settings are never in it.",
8
+ // Export
9
+ exportTitle: "Export this agent's settings", exportLead: "A file you can share or load into another agent with Load template. It holds what this agent has saved (not unsaved edits).",
10
+ pending: "You have unsaved changes on this page; the file holds the saved settings only.",
11
+ pick: "What to include", g_identity: "Description and tags", g_systemPrompt: "Agent instructions — written text only (a file: reference is not exported)",
12
+ g_runtime: "Model, tool set and lightweight", g_behavior: "Behaviour (hang detection, tool progress, logging, …)",
13
+ previewLabel: "Preview of the file", nothing: "Nothing to export: this agent has not saved any of the chosen settings.",
14
+ secretTitle: "Something here looks like a secret", secretBody: "Remove it from {0} first — then the file can be copied or downloaded.",
15
+ secretAt: "{0}, line {1}", kind_private_key: "a private key", kind_api_key: "an API key or token", kind_bot_token: "a bot token", kind_discord_token: "a Discord bot token", kind_webhook: "a webhook address (it is a secret)", nChars: "{0} chars", kind_jwt: "a signed token (JWT)",
16
+ kind_bearer: "an authorization header value", kind_assignment: "a key, token or password assigned a value", kind_url_password: "a password inside a web address",
17
+ o_fileRef: "This agent\u2019s Agent instructions use a file: reference, which names a file on this computer, so they are left out of the file. Write the text into the field to export it.",
18
+ o_tooLong: "This agent\u2019s Agent instructions are longer than the 24,000 characters a template may hold, so they are left out of the file (loading it would refuse them).",
19
+ notExported: "Never exported", notExportedBody: "Account and sign-in names, API keys, channel and topic ids, working folder, machine ids, permissions (dashboard, skip permissions), pre-task command, status emojis, quota notice, and display name.",
20
+ copy: "Copy", download: "Download", copied: "Copied the file to the clipboard.", copyFailed: "Could not copy; select the text in the preview and copy it by hand.",
21
+ exportFailed: "Could not build the file.", close: "Close", building: "Building…",
22
+ // Load
23
+ loadTitle: "Load a template", loadLead: "Pick a template file or paste its text. Nothing is changed yet: you see what would be filled in, then fill the form, then press Save as usual.",
24
+ chooseFile: "Choose a file", pasteLabel: "Or paste the file's text", pastePlaceholder: "agend_export: 1\nkind: agent\nagent:\n description: …",
25
+ fileTooLarge: "That file is too large for a template.", readFailed: "Could not read that file.",
26
+ check: "Check", checking: "Checking…", fill: "Fill the form", cancel: "Cancel",
27
+ willFill: "Will fill in {0}", willSkip: "Will skip {0}", fillNone: "Nothing in this file can be filled in.", skipNone: "Nothing skipped.",
28
+ replaces: "replaces what is there now", filled: "Filled in {0}. Press Save to apply them.", roleHint: "The file suggests the role name “{0}”.",
29
+ libraryNote: "The file lists skills or tools from a library. The library is not available yet, so they are not loaded.",
30
+ failoverNote: "The file lists several fallback models; only the first is used.", modelNote: "The model is loaded as written; whether it works depends on this agent's CLI and account.",
31
+ f_description: "Description", f_tags: "Tags", f_systemPrompt: "Agent instructions", f_model: "Model", f_model_failover: "Fallback model", f_tool_set: "Tool set",
32
+ f_lightweight: "Lightweight", f_hang_detector: "Hang detection (minutes)", f_tool_progress: "Tool progress", f_reply_completion_guard: "Reply guard", f_log_level: "Log level",
33
+ f_auto_pause_after: "Auto-pause after (minutes)", f_agent_mode: "Agent mode", f_cross_instance_visibility: "Cross-agent visibility", f_board_cards_at_once: "Board cards at once",
34
+ f_resume_interrupted_work: "Resume interrupted work",
35
+ r_machine: "belongs to one computer", r_binding: "tied to this fleet's channels", r_account: "an account or sign-in name; sharing it would leak it", r_permission: "a permission; a file never loosens it",
36
+ r_command: "a command; a file may not carry one", r_emoji: "tied to one chat server", r_notice: "an account-level reminder rule", r_fleetOnly: "not a setting of this page (fleet.yaml only)",
37
+ r_name: "each person names their own agent", r_runtimeSwitch: "change the CLI with “Switch runtime / CLI” instead", r_fileRef: "a file: reference points at a file on one computer; write the text instead",
38
+ r_unknown: "not a field this version knows", r_badValue: "the value is not valid", r_tooLong: "too long",
39
+ e_empty: "Choose a file or paste its text first.", e_too_large: "The text is too large for a template.", e_invalid_yaml: "That is not valid YAML.",
40
+ e_not_export: "That is not an AgEnD export file (it has no “agend_export” line).", e_unsupported_version: "This file is from a newer format than this version can read.",
41
+ e_wrong_kind: "This file is not an agent export.", e_failed: "Could not check the file.",
42
+ },
43
+ "zh-TW": {
44
+ loadTemplate: "載入範本", exportBtn: "導出", fieldsHint: "範本是一個檔案,放這個 Agent 可攜的設定(Agent 指示、模型、行為…)。帳號、資料夾、頻道和權限類設定一律不會出現在裡面。",
45
+ exportTitle: "導出這個 Agent 的設定", exportLead: "產生一個可以分享、也可以用「載入範本」載入到別的 Agent 的檔案。內容是這個 Agent 已儲存的設定(不含還沒儲存的修改)。",
46
+ pending: "這一頁有尚未儲存的修改;檔案只包含已儲存的設定。",
47
+ pick: "要導出的內容", g_identity: "描述與標籤", g_systemPrompt: "Agent 指示 — 只導出寫出來的文字(file: 引用不導出)",
48
+ g_runtime: "模型、工具組與輕量模式", g_behavior: "行為設定(卡住偵測、工具進度、記錄等級…)",
49
+ previewLabel: "檔案預覽", nothing: "沒有可以導出的內容:這個 Agent 沒有儲存任何所選的設定。",
50
+ secretTitle: "這裡面有內容看起來像密鑰", secretBody: "請先從 {0} 移除,才能複製或下載檔案。",
51
+ secretAt: "{0},第 {1} 行", kind_private_key: "私鑰", kind_api_key: "API key 或 token", kind_bot_token: "機器人 token", kind_discord_token: "Discord 機器人 token", kind_webhook: "Webhook 位址(等同密鑰)", nChars: "{0} 字元", kind_jwt: "簽章 token(JWT)",
52
+ kind_bearer: "授權標頭的值", kind_assignment: "被指定了值的 key、token 或密碼", kind_url_password: "網址裡的密碼",
53
+ o_fileRef: "這個 Agent 的 Agent 指示使用 file: 引用(指向這台電腦上的檔案),所以沒有放進檔案。要導出請把文字直接寫進欄位。",
54
+ o_tooLong: "這個 Agent 的 Agent 指示超過範本可放的 24,000 字元,所以沒有放進檔案(載入時也會被拒絕)。",
55
+ notExported: "不會導出的項目", notExportedBody: "帳號與登入名稱、API key、頻道與討論串 ID、工作目錄、機器 ID、權限類(dashboard、skipPermissions)、任務前指令、Status emojis、用量提醒,以及顯示名稱。",
56
+ copy: "複製", download: "下載", copied: "已把檔案複製到剪貼簿。", copyFailed: "無法複製;請在預覽中選取文字手動複製。",
57
+ exportFailed: "無法產生檔案。", close: "關閉", building: "產生中…",
58
+ loadTitle: "載入範本", loadLead: "選一個範本檔案,或貼上內容。這一步還不會改任何東西:先看會填入什麼,再填入表單,最後照常按「儲存」。",
59
+ chooseFile: "選擇檔案", pasteLabel: "或貼上檔案內容", pastePlaceholder: "agend_export: 1\nkind: agent\nagent:\n description: …",
60
+ fileTooLarge: "這個檔案太大,不像是範本。", readFailed: "無法讀取這個檔案。",
61
+ check: "檢查", checking: "檢查中…", fill: "填入表單", cancel: "取消",
62
+ willFill: "將填入 {0} 項", willSkip: "將略過 {0} 項", fillNone: "這個檔案裡沒有可以填入的項目。", skipNone: "沒有略過的項目。",
63
+ replaces: "會取代目前的內容", filled: "已填入 {0} 項,按「儲存」才會套用。", roleHint: "檔案建議的角色名稱:「{0}」。",
64
+ libraryNote: "檔案列了庫裡的 Skill 或工具。庫還沒有提供,所以這次不載入。",
65
+ failoverNote: "檔案列了多個備援模型,只會用第一個。", modelNote: "模型照檔案內容填入;能不能用取決於這個 Agent 的 CLI 與帳號。",
66
+ f_description: "描述", f_tags: "標籤", f_systemPrompt: "Agent 指示", f_model: "模型", f_model_failover: "備援模型", f_tool_set: "工具組",
67
+ f_lightweight: "輕量模式", f_hang_detector: "卡住偵測(分鐘)", f_tool_progress: "工具進度", f_reply_completion_guard: "回覆提醒", f_log_level: "記錄等級",
68
+ f_auto_pause_after: "閒置自動暫停(分鐘)", f_agent_mode: "Agent 模式", f_cross_instance_visibility: "跨 Agent 訊息可見度", f_board_cards_at_once: "同時進行的看板卡片",
69
+ f_resume_interrupted_work: "中斷後繼續未完成的工作",
70
+ r_machine: "屬於某一台電腦", r_binding: "綁定這個 fleet 的頻道", r_account: "帳號或登入名稱,分享會洩漏", r_permission: "權限類,從檔案載入不會放寬",
71
+ r_command: "指令,檔案不能夾帶", r_emoji: "綁定某個聊天伺服器", r_notice: "帳號層級的提醒規則", r_fleetOnly: "不是這一頁的設定(只有 fleet.yaml 有)",
72
+ r_name: "每個人替自己的 Agent 命名", r_runtimeSwitch: "要換 CLI 請用「切換 Runtime/CLI」", r_fileRef: "file: 引用指向某台電腦上的檔案,請改成直接寫文字",
73
+ r_unknown: "這個版本不認得的欄位", r_badValue: "值不合法", r_tooLong: "太長",
74
+ e_empty: "請先選擇檔案或貼上內容。", e_too_large: "內容太大,不像是範本。", e_invalid_yaml: "這不是合法的 YAML。",
75
+ e_not_export: "這不是 AgEnD 導出檔(沒有「agend_export」這一行)。", e_unsupported_version: "這個檔案的格式比目前版本新,讀不了。",
76
+ e_wrong_kind: "這個檔案不是 Agent 導出檔。", e_failed: "無法檢查這個檔案。",
77
+ },
78
+ });
79
+
80
+ /** A word of these dialogs (agentExport.*). */
81
+ export const xt = (key, ...values) => t(`agentExport.${key}`, ...values);
@@ -0,0 +1,69 @@
1
+ // The "Agent instructions" field of an agent's Basic info — the agent's `systemPrompt` (what Settings used to call "System
2
+ // prompt"; same key, same place in what the AI is told), edited as Markdown with an Edit / Preview switch. The preview is
3
+ // the chat's own Markdown renderer (chat-thread.js drawMarkdown → chat-render.js: it escapes the text first, so nothing
4
+ // typed here becomes markup); nothing is rendered by this file. A `file:` reference stays one: the preview lists the
5
+ // file instead of reading it (the daemon reads it when the agent starts).
6
+ import { html, useEffect, useRef, useState } from "/assets/app-html.js";
7
+ import "/assets/chat-render.js";
8
+ import { drawMarkdown } from "/assets/chat-thread.js";
9
+ import { pt } from "./agent-page-strings.js";
10
+
11
+ /** The most the editor lets Save write, in characters. */
12
+ export const INSTRUCTIONS_MAX_CHARS = 24000;
13
+ /**
14
+ * Codex reads at most 32 KiB of AGENTS.md in total (backend/codex.ts) and AgEnD's own guidance already takes about 12 KiB
15
+ * of it, so past this many bytes of instructions the end — they come last — may be cut.
16
+ */
17
+ export const CODEX_AGENTS_MD_BYTES = 32 * 1024;
18
+ export const CODEX_NOTE_BYTES = 16 * 1024;
19
+
20
+ const utf8Bytes = (text) => (typeof TextEncoder === "function" ? new TextEncoder().encode(text).length : text.length);
21
+ /** What the counter shows: characters (what the limit counts) and bytes (what Codex counts). */
22
+ export const instructionsSize = (text) => ({ chars: text.length, bytes: utf8Bytes(text) });
23
+ const fmt = (n) => Number(n).toLocaleString("en-US");
24
+
25
+ /**
26
+ * The parts of a systemPrompt, as prompt-file-ref.ts systemPromptParts reads them: comma-separated only when at least one
27
+ * part is a `file:` reference ("file:role.md, file:rules.md", inline text allowed between them); otherwise the whole value
28
+ * is one inline text, commas and all. (tests/agent-instructions-ui.test.ts keeps the two equal.)
29
+ */
30
+ export function promptParts(value) {
31
+ const parts = value.split(",").map((part) => part.trim());
32
+ return parts.some((part) => part.startsWith("file:")) ? parts : [value];
33
+ }
34
+ const hasFileRef = (value) => promptParts(value).some((part) => part.startsWith("file:"));
35
+
36
+ function Markdown({ text }) {
37
+ const ref = useRef(null);
38
+ useEffect(() => { if (ref.current) drawMarkdown(ref.current, text); }, [text]);
39
+ return html`<div ref=${ref} class="pv-code pv-md" data-instructions-preview />`;
40
+ }
41
+
42
+ /** The preview: inline text through the chat's Markdown renderer; a `file:` part as the file it names. */
43
+ function InstructionsPreview({ text }) {
44
+ if (!text.trim()) return html`<p class="note">${pt("instrPreviewEmpty")}</p>`;
45
+ if (!hasFileRef(text)) return html`<${Markdown} text=${text} />`;
46
+ return html`<div class="instructions-parts">${promptParts(text).filter(Boolean).map((part, i) => part.startsWith("file:")
47
+ ? html`<p key=${i} class="note" data-instructions-file><code>${part.slice(5).trim()}</code> — ${pt("instrFileRead")}</p>`
48
+ : html`<${Markdown} key=${i} text=${part} />`)}</div>`;
49
+ }
50
+
51
+ /** `id`: the textarea's id (the field's label points at it). `value`/`onChange`: the draft. `saved`: the value on disk (an over-long one already there is not an error until it is edited). */
52
+ export function InstructionsField({ id, value, onChange, saved }) {
53
+ const [mode, setMode] = useState("edit");
54
+ const { chars, bytes } = instructionsSize(value);
55
+ const over = chars > INSTRUCTIONS_MAX_CHARS && value !== saved;
56
+ const files = hasFileRef(value);
57
+ const codexNear = !files && bytes > CODEX_NOTE_BYTES;
58
+ const modeBtn = (m, label) => html`<button type="button" class=${`btn btn-sm${mode === m ? " btn-primary" : ""}`} aria-pressed=${mode === m ? "true" : "false"} data-instructions-mode=${m}
59
+ onClick=${() => setMode(m)}>${label}</button>`;
60
+ return html`<div class="instructions-field">
61
+ <div class="seg-inline" role="group" aria-label=${pt("lbl_instructions")}>${modeBtn("edit", pt("instrEdit"))}${modeBtn("preview", pt("instrPreview"))}</div>
62
+ ${mode === "edit"
63
+ ? html`<textarea id=${id} rows="12" spellcheck=${false} aria-describedby=${`${id}-size`} class=${over ? "invalid" : ""} placeholder=${pt("instrPlaceholder")} value=${value}
64
+ onInput=${(e) => onChange(e.target.value)} />`
65
+ : html`<${InstructionsPreview} text=${value} />`}
66
+ <p class=${`note${over ? " feedback error" : ""}`} id=${`${id}-size`} role=${over ? "alert" : undefined} data-instructions-size>${over ? pt("instrTooLong", fmt(chars), fmt(INSTRUCTIONS_MAX_CHARS)) : pt("instrSize", fmt(chars), fmt(INSTRUCTIONS_MAX_CHARS), fmt(bytes))}</p>
67
+ <p class=${`note${codexNear ? " feedback warning" : ""}`} data-instructions-codex>${pt(files ? "instrCodexFiles" : codexNear ? "instrCodexNear" : "instrCodex")}</p>
68
+ </div>`;
69
+ }