@songsid/agend 2.4.0-beta.13 → 2.4.0-beta.15

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 (183) hide show
  1. package/dist/agent-endpoint.js +28 -6
  2. package/dist/agent-endpoint.js.map +1 -1
  3. package/dist/auth-api.js +1 -0
  4. package/dist/auth-api.js.map +1 -1
  5. package/dist/backend/claude-code.d.ts +9 -0
  6. package/dist/backend/claude-code.js +60 -4
  7. package/dist/backend/claude-code.js.map +1 -1
  8. package/dist/backend/grok.js +11 -0
  9. package/dist/backend/grok.js.map +1 -1
  10. package/dist/backend/types.d.ts +3 -0
  11. package/dist/backend/types.js.map +1 -1
  12. package/dist/backend-availability.d.ts +1 -16
  13. package/dist/backend-availability.js +2 -91
  14. package/dist/backend-availability.js.map +1 -1
  15. package/dist/backend-version-static.d.ts +15 -0
  16. package/dist/backend-version-static.js +95 -0
  17. package/dist/backend-version-static.js.map +1 -0
  18. package/dist/build-provenance.json +1 -1
  19. package/dist/channel/adapters/telegram.js +3 -1
  20. package/dist/channel/adapters/telegram.js.map +1 -1
  21. package/dist/channel/mcp-server.js +18 -1
  22. package/dist/channel/mcp-server.js.map +1 -1
  23. package/dist/channel/tool-router.d.ts +4 -0
  24. package/dist/channel/tool-router.js +43 -19
  25. package/dist/channel/tool-router.js.map +1 -1
  26. package/dist/classic-channel-manager.d.ts +3 -0
  27. package/dist/classic-channel-manager.js +18 -0
  28. package/dist/classic-channel-manager.js.map +1 -1
  29. package/dist/classic-cli-guard.d.ts +66 -0
  30. package/dist/classic-cli-guard.js +209 -0
  31. package/dist/classic-cli-guard.js.map +1 -0
  32. package/dist/cli-audited.js +7 -5
  33. package/dist/cli-audited.js.map +1 -1
  34. package/dist/config-validator.js +3 -0
  35. package/dist/config-validator.js.map +1 -1
  36. package/dist/contact-auth-api.d.ts +17 -0
  37. package/dist/contact-auth-api.js +88 -0
  38. package/dist/contact-auth-api.js.map +1 -0
  39. package/dist/contact-auth-files.d.ts +6 -0
  40. package/dist/contact-auth-files.js +29 -0
  41. package/dist/contact-auth-files.js.map +1 -0
  42. package/dist/contact-auth-policy.d.ts +80 -0
  43. package/dist/contact-auth-policy.js +25 -0
  44. package/dist/contact-auth-policy.js.map +1 -0
  45. package/dist/contact-auth-service.d.ts +32 -0
  46. package/dist/contact-auth-service.js +99 -0
  47. package/dist/contact-auth-service.js.map +1 -0
  48. package/dist/contact-auth-store.d.ts +86 -0
  49. package/dist/contact-auth-store.js +357 -0
  50. package/dist/contact-auth-store.js.map +1 -0
  51. package/dist/contact-auth-types.d.ts +196 -0
  52. package/dist/contact-auth-types.js +7 -0
  53. package/dist/contact-auth-types.js.map +1 -0
  54. package/dist/daemon.d.ts +8 -0
  55. package/dist/daemon.js +93 -4
  56. package/dist/daemon.js.map +1 -1
  57. package/dist/delivery-outbox.d.ts +6 -0
  58. package/dist/delivery-outbox.js +19 -0
  59. package/dist/delivery-outbox.js.map +1 -1
  60. package/dist/fleet-manager.d.ts +48 -0
  61. package/dist/fleet-manager.js +484 -22
  62. package/dist/fleet-manager.js.map +1 -1
  63. package/dist/general-knowledge/skills/concepts/SKILL.md +18 -0
  64. package/dist/general-knowledge/skills/credential-profiles/SKILL.md +5 -0
  65. package/dist/general-knowledge/skills/cross-instance-messaging/SKILL.md +38 -0
  66. package/dist/general-knowledge/skills/hub/SKILL.md +6 -0
  67. package/dist/general-knowledge/skills/web-dashboard/SKILL.md +5 -0
  68. package/dist/hub/audit/index.d.ts +3 -1
  69. package/dist/hub/audit/index.js +35 -3
  70. package/dist/hub/audit/index.js.map +1 -1
  71. package/dist/hub/catalog.d.ts +8 -0
  72. package/dist/hub/catalog.js +39 -4
  73. package/dist/hub/catalog.js.map +1 -1
  74. package/dist/hub/compose/server.d.ts +2 -0
  75. package/dist/hub/compose/server.js +11 -1
  76. package/dist/hub/compose/server.js.map +1 -1
  77. package/dist/hub/directory/directory.js +5 -2
  78. package/dist/hub/directory/directory.js.map +1 -1
  79. package/dist/hub/directory/types.d.ts +5 -1
  80. package/dist/hub/directory/types.js.map +1 -1
  81. package/dist/hub/group-policy/resources.d.ts +1 -1
  82. package/dist/hub/http/compose.d.ts +2 -0
  83. package/dist/hub/http/compose.js +123 -6
  84. package/dist/hub/http/compose.js.map +1 -1
  85. package/dist/hub/http/deps.d.ts +2 -0
  86. package/dist/hub/http/schema.js +6 -1
  87. package/dist/hub/http/schema.js.map +1 -1
  88. package/dist/hub/invitations.js +15 -7
  89. package/dist/hub/invitations.js.map +1 -1
  90. package/dist/hub/roles/cutover-inventory.d.ts +3 -0
  91. package/dist/hub/roles/cutover-inventory.js +20 -4
  92. package/dist/hub/roles/cutover-inventory.js.map +1 -1
  93. package/dist/hub/roles/cutover-marker.d.ts +18 -2
  94. package/dist/hub/roles/cutover-marker.js +6 -2
  95. package/dist/hub/roles/cutover-marker.js.map +1 -1
  96. package/dist/hub/room-agent-discovery-model.d.ts +29 -0
  97. package/dist/hub/room-agent-discovery-model.js +33 -0
  98. package/dist/hub/room-agent-discovery-model.js.map +1 -0
  99. package/dist/hub/room-agent-discovery.d.ts +14 -0
  100. package/dist/hub/room-agent-discovery.js +65 -0
  101. package/dist/hub/room-agent-discovery.js.map +1 -0
  102. package/dist/hub/room-agent-requests.d.ts +71 -0
  103. package/dist/hub/room-agent-requests.js +377 -0
  104. package/dist/hub/room-agent-requests.js.map +1 -0
  105. package/dist/hub/rooms/directory.d.ts +13 -0
  106. package/dist/hub/rooms/directory.js +12 -3
  107. package/dist/hub/rooms/directory.js.map +1 -1
  108. package/dist/hub/rooms/schema.d.ts +5 -0
  109. package/dist/hub/rooms/schema.js +9 -0
  110. package/dist/hub/rooms/schema.js.map +1 -1
  111. package/dist/hub/rooms/service.d.ts +43 -19
  112. package/dist/hub/rooms/service.js +67 -11
  113. package/dist/hub/rooms/service.js.map +1 -1
  114. package/dist/hub/rooms/types.d.ts +1 -1
  115. package/dist/instance-lifecycle.d.ts +3 -1
  116. package/dist/instance-lifecycle.js +4 -1
  117. package/dist/instance-lifecycle.js.map +1 -1
  118. package/dist/locale.js +34 -4
  119. package/dist/locale.js.map +1 -1
  120. package/dist/needs-you-hub.d.ts +1 -0
  121. package/dist/needs-you-hub.js +9 -0
  122. package/dist/needs-you-hub.js.map +1 -1
  123. package/dist/needs-you.d.ts +12 -2
  124. package/dist/needs-you.js.map +1 -1
  125. package/dist/outbound-handlers.d.ts +9 -0
  126. package/dist/outbound-handlers.js +46 -10
  127. package/dist/outbound-handlers.js.map +1 -1
  128. package/dist/runtime-cli-install.js +7 -7
  129. package/dist/runtime-cli-install.js.map +1 -1
  130. package/dist/topic-commands.d.ts +1 -1
  131. package/dist/topic-commands.js +4 -6
  132. package/dist/topic-commands.js.map +1 -1
  133. package/dist/ui/agent-details-settings.js +7 -5
  134. package/dist/ui/contact-auth-client.js +50 -0
  135. package/dist/ui/contact-auth-strings.js +195 -0
  136. package/dist/ui/contact-authorizations.js +125 -0
  137. package/dist/ui/contact-needs.js +100 -0
  138. package/dist/ui/contact-permissions.js +238 -0
  139. package/dist/ui/contact-ticket-badge.js +54 -0
  140. package/dist/ui/contact-tool-groups.js +39 -0
  141. package/dist/ui/hub-client.js +30 -7
  142. package/dist/ui/hub-invitations.js +5 -1
  143. package/dist/ui/hub-room-new.js +10 -3
  144. package/dist/ui/hub-room-owner-requests-strings.js +114 -0
  145. package/dist/ui/hub-room-owner-requests.js +264 -0
  146. package/dist/ui/hub-room-pins.js +43 -0
  147. package/dist/ui/hub-room-settings.js +11 -2
  148. package/dist/ui/hub-room-strings.js +3 -0
  149. package/dist/ui/hub-room-thread.js +47 -5
  150. package/dist/ui/panel-chat.js +2 -0
  151. package/dist/ui/panel-details.js +2 -0
  152. package/dist/ui/panel-fleet.js +3 -2
  153. package/dist/ui/panel-hub.js +7 -1
  154. package/dist/ui/panel-needs.js +11 -4
  155. package/dist/ui/panel-settings.js +3 -0
  156. package/dist/ui/settings-appearance.js +6 -1
  157. package/dist/ui/settings-registry.js +1 -1
  158. package/dist/ui/shared/app-i18n.js +4 -0
  159. package/dist/ui/shared/app-route.js +1 -1
  160. package/dist/ui/shared/app-shell.js +18 -7
  161. package/dist/ui/shared/app-stream.js +3 -1
  162. package/dist/ui/shared/app.css +86 -0
  163. package/dist/ui/shared/chat-quote.js +26 -2
  164. package/dist/ui/shared/chat-thread.js +6 -2
  165. package/dist/ui/shared/hub-rooms-u2.css +22 -0
  166. package/dist/ui/shared/text-undo.js +17 -3
  167. package/dist/ui/shared/theme-picker.js +46 -0
  168. package/dist/ui/shared/theme.js +36 -3
  169. package/dist/ui/shared/tokens.css +273 -0
  170. package/dist/ui/shared/ui-confirm.js +5 -2
  171. package/dist/web-api.d.ts +10 -0
  172. package/dist/web-api.js +55 -3
  173. package/dist/web-api.js.map +1 -1
  174. package/dist/web-chat-history.d.ts +5 -0
  175. package/dist/web-chat-history.js +26 -0
  176. package/dist/web-chat-history.js.map +1 -1
  177. package/dist/web-reply-files.d.ts +1 -0
  178. package/dist/web-reply-files.js +2 -0
  179. package/dist/web-reply-files.js.map +1 -1
  180. package/dist/web-shell-routes.d.ts +1 -1
  181. package/dist/web-shell-routes.js +2 -1
  182. package/dist/web-shell-routes.js.map +1 -1
  183. package/package.json +1 -1
@@ -0,0 +1,238 @@
1
+ // M-3339 (A2): an agent page's Permissions (agent-details-settings.js, category "permissions") — on the contact
2
+ // authorization contract (src/contact-auth-types.ts; docs/design/classic-contact-authorizations.md).
3
+ // - A ClassicBot room's page: its mode (restricted, or the older setting), the command-line guard's coverage, and the
4
+ // room's tools (public reading, exact MCP tools; what would stop if a legacy room switched).
5
+ // - A worker's page: who approves requests to it (or the channel admins it inherits), and its allowed contacts.
6
+ // - Both: the history.
7
+ // Its own read and its own saves (PUT with the revision read; a 409 reads again and says so) — never staged with the
8
+ // page's settings Save. The server decides who may see or change anything (canManage / canSetMode); nothing here grants.
9
+ // It reads again on the stream's contact-auth frame for this agent (a newer revision) and when the page is shown again.
10
+ import { html, useEffect, useRef, useState } from "/assets/app-html.js";
11
+ import { appStore } from "/assets/app-store.js";
12
+ import { Icon } from "/assets/ui-icons.js";
13
+ import { toast } from "/assets/ui-toast.js";
14
+ import { Skeleton, ErrorState } from "/assets/ui-states.js";
15
+ import { confirmDialog } from "/assets/ui-confirm.js";
16
+ import { ca } from "./contact-auth-strings.js";
17
+ import { getPermissions, putPermissions, clearOrigin, shortTicketId } from "./contact-auth-client.js";
18
+ import { REASONS } from "./contact-authorizations.js";
19
+ import { groupWouldDisable } from "./contact-tool-groups.js";
20
+
21
+ const when = (iso) => { const d = new Date(iso); return Number.isFinite(d.getTime()) ? d.toLocaleString([], { dateStyle: "medium", timeStyle: "short" }) : ""; };
22
+ /** A3's guard reason codes (ContactGuardStatus.reason), each said in words (contact-auth-strings.js guardReason_<code>). */
23
+ const GUARD_REASONS = new Set(["legacy-mode", "unsupported-backend", "unsupported-platform", "unsupported-version", "cli-mode", "load-not-verified", "stale-policy",
24
+ "stale-launch", "not-running", "invalid-policy", "missing-bound-mcp", "missing-selected-mcp", "guard-files-changed", "invalid-load-receipt", "guard-unavailable", "binary-changed"]);
25
+ /**
26
+ * The leader's A3 decision (via Cairn): a restricted room whose AI tool, version, platform or mode the guard doesn't cover
27
+ * keeps running with that tool's normal permissions — only contact approval applies. Said plainly (never "ready", never only in
28
+ * a tooltip), and before the mode is set (the mode card, the switch's confirm, Needs you's suggestion). A missing selected MCP
29
+ * tool is partial coverage (the base guard runs): its own reason says which, not this.
30
+ */
31
+ export const notCovered = (g) => !!g && g.state === "not-covered" && g.reason !== "missing-selected-mcp";
32
+ const GUARD_TONE = { ready: "ok", "restart-required": "warn", "not-covered": "warn", failed: "bad" };
33
+ /** The guard's state as said — anything the contract doesn't name is never shown as ready. */
34
+ const guardState = (g) => (g && ["ready", "restart-required", "not-covered", "failed"].includes(g.state) ? g.state : "failed");
35
+ const personLabel = (p) => (p && (p.label || p.userId)) || "";
36
+
37
+ /** Keep `name`'s permissions read: once, on its contact-auth frame (a newer revision), and when the page is shown again. */
38
+ export function usePermissions(name) {
39
+ const [state, setState] = useState({ loading: true });
40
+ const rev = useRef(-1);
41
+ const originRev = useRef(-1);
42
+ const read = async () => {
43
+ const r = await getPermissions(name);
44
+ if (r.ok) { rev.current = r.data.revision; originRev.current = r.data.originState?.revision ?? -1; setState({ data: r.data }); } else setState((s) => ({ ...(s.data ? { data: s.data } : {}), error: r.code }));
45
+ return r;
46
+ };
47
+ useEffect(() => {
48
+ let live = true;
49
+ void read().then(() => { if (!live) rev.current = -1; });
50
+ const sub = appStore.get().streamOn;
51
+ const off = typeof sub === "function" ? sub("contact-auth", (d) => { if (d && d.instance === name && (!(Number(d.revision) <= rev.current) || Number(d.originRevision) > originRev.current)) void read(); }) : null;
52
+ const offMessage = typeof sub === "function" ? sub("message", (d) => { if (d?.instance === name) void read(); }) : null;
53
+ const onShow = () => { if (document.visibilityState === "visible") void read(); };
54
+ document.addEventListener("visibilitychange", onShow);
55
+ return () => { live = false; if (typeof off === "function") off(); if (typeof offMessage === "function") offMessage(); document.removeEventListener("visibilitychange", onShow); };
56
+ }, [name]);
57
+ return { ...state, read, setData: (data) => { rev.current = data.revision; originRev.current = data.originState?.revision ?? -1; setState({ data }); } };
58
+ }
59
+
60
+ /**
61
+ * What would stop if this legacy room switched — AgEnD's known removals; when the backend's own inventory couldn't be read
62
+ * (impactComplete false) that is said too, so the list is never taken as everything.
63
+ * M-3387: by kind with counts (contact-tool-groups.js), the AI tool's own tools on their own line, the two layers said, and
64
+ * every name behind "show all".
65
+ */
66
+ function WouldDisable({ tools, complete }) {
67
+ const incomplete = complete === false ? html`<p class="feedback warning contact-impact-incomplete">${ca("impactIncomplete")}</p>` : null;
68
+ if (!tools || !tools.length) return complete === false ? incomplete : html`<p class="note">${ca("wouldDisableNone")}</p>`;
69
+ const { groups, cli, agendCount } = groupWouldDisable(tools);
70
+ return html`<div class="contact-would">
71
+ ${agendCount ? html`<p>${ca("toolsLostTitle", agendCount)}</p><ul class="contact-would-groups">${groups.map((g) => html`<li key=${g.id} data-group=${g.id}>${ca("toolGroupLine", ca(`toolGroup_${g.id}`), g.tools.length)}</li>`)}</ul>` : null}
72
+ ${cli.length ? html`<p class="contact-would-cli">${ca("cliToolsLine", cli.length, cli.join(", "))}</p>` : null}
73
+ <p class="note contact-would-layers">${ca("toolLayers")}</p>
74
+ <details class="contact-would-all"><summary>${ca("showAllTools", tools.length)}</summary><ul>${tools.map((n) => html`<li key=${n} class="mono">${n}</li>`)}</ul></details>
75
+ ${incomplete}</div>`;
76
+ }
77
+ /** The same, as the confirm's text (paragraphs): the kinds with counts, the AI tool's own tools, the two layers. */
78
+ export function wouldDisableText(roomTools, guard) {
79
+ const would = roomTools?.wouldDisable || [];
80
+ const { groups, cli, agendCount } = groupWouldDisable(would);
81
+ const parts = [would.length ? "" : roomTools?.impactComplete === false ? "" : ca("wouldDisableNone")];
82
+ if (agendCount) parts.push([ca("toolsLostTitle", agendCount), ...groups.map((g) => ca("toolGroupLine", ca(`toolGroup_${g.id}`), g.tools.length))].join("\n"));
83
+ if (cli.length) parts.push(ca("cliToolsLine", cli.length, cli.join(", ")));
84
+ if (would.length) parts.push(ca("toolLayers"));
85
+ if (roomTools?.impactComplete === false) parts.push(ca("impactIncomplete"));
86
+ if (notCovered(guard)) parts.push(ca("notCoveredWarning"));
87
+ return parts.filter(Boolean).join("\n\n");
88
+ }
89
+ /** M-3387: the confirm's "show all": every name that would stop, or null when none. */
90
+ export function wouldDisableMore(roomTools) {
91
+ const would = roomTools?.wouldDisable || [];
92
+ return would.length ? { label: ca("showAllTools", would.length), lines: would } : null;
93
+ }
94
+
95
+ export function ContactPermissionsPanel({ name }) {
96
+ const perm = usePermissions(name);
97
+ const [busy, setBusy] = useState(false);
98
+ const [mcpDraft, setMcpDraft] = useState("");
99
+ const [pick, setPick] = useState("");
100
+ const p = perm.data;
101
+ if (!p && perm.loading !== false && !perm.error) return html`<${Skeleton} lines=${5} label=${ca("loading")} />`;
102
+ if (!p) return perm.error === "forbidden" ? html`<p class="note contact-forbidden">${ca("forbidden")}</p>`
103
+ : html`<${ErrorState} message=${ca(perm.error === "unavailable" ? "unavailable" : "loadFailed")} onRetry=${() => void perm.read()} />`;
104
+ // Who may change what (the server says; Sentinel's seam): the source room's admins its mode and tools (canSetMode); the
105
+ // target's approvers its approvers and allowed contacts (canManage).
106
+ const canMode = p.classicRoom && p.canSetMode === true;
107
+ const canManage = p.canManage === true;
108
+ /** One write with the revision read; a refusal says why (a stale one reads again first). */
109
+ const write = async (patch) => {
110
+ if (busy) return false;
111
+ setBusy(true);
112
+ const r = await putPermissions(name, { revision: p.revision, ...patch });
113
+ setBusy(false);
114
+ if (r.ok) { perm.setData(r.data); toast(ca("saved"), true); return true; }
115
+ if (r.code === "conflict") { await perm.read(); toast(ca("stale"), false); return false; }
116
+ toast(ca(r.code === "forbidden" ? "forbidden" : r.code === "unavailable" ? "unavailable" : r.code === "invalid-approver" ? "invalidApprover" : "saveFailed"), false);
117
+ return false;
118
+ };
119
+ const switchMode = async (mode) => {
120
+ const toRestricted = mode === "restricted";
121
+ const ok = await confirmDialog({ title: ca(toRestricted ? "confirmRestricted" : "confirmLegacy"), message: toRestricted
122
+ ? [ca("modeRestrictedNote"), ca("switchOriginNote"), wouldDisableText(p.roomTools, p.nativeGuard)].join("\n\n")
123
+ : ca("modeLegacyNote"), ...(toRestricted ? { more: wouldDisableMore(p.roomTools) } : {}),
124
+ confirmLabel: ca(toRestricted ? "switchRestricted" : "switchLegacy"), danger: !toRestricted });
125
+ if (ok) await write({ mode });
126
+ };
127
+ const clearRetainedOrigin = async () => {
128
+ if (busy || !p.originState?.canClear) return;
129
+ setBusy(true);
130
+ const confirmed = await confirmDialog({ title: ca("originClear"), message: ca("originClearConfirm"),
131
+ confirmLabel: ca("originClear"), danger: true });
132
+ if (!confirmed) { setBusy(false); return; }
133
+ const r = await clearOrigin(name, { revision: p.revision, originRevision: p.originState.revision, generation: p.originState.generation });
134
+ setBusy(false);
135
+ if (r.ok) { perm.setData(r.data); toast(ca("originCleared"), true); return; }
136
+ if (r.code === "conflict") { await perm.read(); toast(ca("stale"), false); return; }
137
+ toast(ca(r.code === "forbidden" ? "forbidden" : r.code === "unavailable" ? "unavailable" : "saveFailed"), false);
138
+ };
139
+ const tools = p.roomTools || { publicRead: false, allowedMcpTools: [], wouldDisable: [] };
140
+ const setTools = (next) => write({ roomTools: { publicRead: next.publicRead, allowedMcpTools: next.allowedMcpTools } });
141
+ const addMcp = async (e) => {
142
+ e.preventDefault();
143
+ const n = mcpDraft.trim();
144
+ if (!n || tools.allowedMcpTools.some((x) => x.name === n)) return;
145
+ if (await setTools({ ...tools, allowedMcpTools: [...tools.allowedMcpTools, { name: n, kind: "mcp", usesOwnerAccount: false }] })) setMcpDraft("");
146
+ };
147
+ const grantsWrite = (rows) => write({ grants: rows.map(({ id, person, source, target, verbs, expiresAt, remainingUses }) => ({ id, person, source, target, verbs, expiresAt, remainingUses })) });
148
+ const g = guardState(p.nativeGuard);
149
+ return html`<div class="contact-perm" aria-busy=${busy ? "true" : undefined}>
150
+ ${p.originRestriction?.active && REASONS.has(p.originRestriction.reason) ? html`<p class="feedback warning contact-origin-restriction" role="status" data-reason=${p.originRestriction.reason}>
151
+ ${ca(`reason_${p.originRestriction.reason}`)} ${ca("resetNote")}</p>` : null}
152
+ ${!canManage && !canMode ? html`<p class="s-info contact-readonly"><span aria-hidden="true">ⓘ</span><span>${ca("readOnly")}</span></p>` : null}
153
+ ${p.classicRoom ? html`<section class="card contact-mode" data-mode=${p.mode}>
154
+ <h3>${ca("modeTitle")}</h3>
155
+ ${p.suggestRestricted && p.mode !== "restricted" ? html`<p class="feedback warning contact-suggest-banner" role="status">${ca("suggestBanner")}</p>` : null}
156
+ <p class="contact-mode-line"><span class=${`contact-pill ${p.mode === "restricted" ? "ok" : "warn"}`}>${ca(p.mode === "restricted" ? "modeRestricted" : "modeLegacy")}</span></p>
157
+ ${p.mode !== "restricted" ? html`<p class="feedback warning contact-origin-switch">${ca("switchOriginNote")}</p>` : null}
158
+ <p class="note">${ca(p.mode === "restricted" ? "modeRestrictedNote" : "modeLegacyNote")}</p>
159
+ ${p.mode !== "restricted" ? html`<${WouldDisable} tools=${tools.wouldDisable} complete=${tools.impactComplete} />` : null}
160
+ ${notCovered(p.nativeGuard) ? html`<p class="feedback warning contact-not-covered" role="status">${ca("notCoveredWarning")}</p>` : null}
161
+ ${canMode ? html`<div class="field-row"><button type="button" class=${`btn btn-sm${p.mode === "restricted" ? "" : " btn-primary"}`} disabled=${busy}
162
+ onClick=${() => switchMode(p.mode === "restricted" ? "legacy" : "restricted")}>${ca(p.mode === "restricted" ? "switchLegacy" : "switchRestricted")}</button></div>` : null}
163
+ </section>
164
+ <section class="card contact-guard" data-guard=${g}>
165
+ <h3>${ca("guardTitle")}</h3>
166
+ <p><span class=${`contact-pill ${GUARD_TONE[g]}`}>${ca(`guard_${g}`)}</span>${p.nativeGuard?.backend ? html` <span class="muted">${ca("guardBackend", p.nativeGuard.version ? `${p.nativeGuard.backend} ${p.nativeGuard.version}` : p.nativeGuard.backend)}</span>` : null}</p>
167
+ ${/* A3's reason is a code (Cairn): said in words; one this page doesn't know, generically — never the code itself. */ ""}
168
+ ${notCovered(p.nativeGuard) ? html`<p class="feedback warning contact-not-covered">${ca("notCoveredWarning")}</p>` : null}
169
+ ${p.nativeGuard?.reason ? html`<p class="note contact-guard-reason">${GUARD_REASONS.has(p.nativeGuard.reason) ? ca(`guardReason_${p.nativeGuard.reason}`) : ca("guardReasonOther")}</p>` : null}
170
+ <p class="note">${ca("guardNote")}</p>
171
+ </section>
172
+ <section class="card contact-tools">
173
+ <h3>${ca("toolsTitle")}</h3>
174
+ <label class="check contact-toggle"><input type="checkbox" checked=${!!tools.publicRead} disabled=${!canMode || busy}
175
+ onChange=${(e) => void setTools({ ...tools, publicRead: e.currentTarget.checked })} /><span>${ca("publicRead")}</span></label>
176
+ <p class="note">${ca("publicReadNote")}</p>
177
+ <h4>${ca("mcpTitle")}</h4>
178
+ ${tools.allowedMcpTools.length ? html`<ul class="contact-list">${tools.allowedMcpTools.map((x) => html`<li key=${x.name}>
179
+ <span class="mono">${x.name}</span>${x.kind === "public-read" ? html` <span class="muted">${ca("mcpPublicRead")}</span>` : null}
180
+ ${x.usesOwnerAccount ? html`<p class="feedback warning contact-owner-warning"><${Icon} name="alert" size=${14} /><span>${x.accountWarning || ca("mcpOwnerWarning")}</span></p>` : null}
181
+ ${canMode ? html`<button type="button" class="icon-btn" aria-label=${ca("mcpRemove", x.name)} title=${ca("mcpRemove", x.name)} disabled=${busy}
182
+ onClick=${() => void setTools({ ...tools, allowedMcpTools: tools.allowedMcpTools.filter((y) => y.name !== x.name) })}><${Icon} name="trash" size=${16} /></button>` : null}</li>`)}</ul>`
183
+ : html`<p class="note">${ca("mcpNone")}</p>`}
184
+ ${canMode ? html`<form class="field-row contact-mcp-add" onSubmit=${addMcp}><label class="sr-only" for=${`contact-mcp-${name}`}>${ca("mcpAddLabel")}</label>
185
+ <input id=${`contact-mcp-${name}`} class="input mono" placeholder=${ca("mcpAddLabel")} value=${mcpDraft} onInput=${(e) => setMcpDraft(e.currentTarget.value)} />
186
+ <button type="submit" class="btn btn-sm" disabled=${busy || !mcpDraft.trim()}>${ca("mcpAdd")}</button></form>` : null}
187
+ <p class="note">${ca("offByDefault")}</p>
188
+ </section>` : html`<section class="card contact-approvers">
189
+ <h3>${ca("approversTitle")}</h3>
190
+ ${p.approvers.length ? html`<ul class="contact-list">${p.approvers.map((a) => html`<li key=${`${a.platform}:${a.adapterId}:${a.userId}`}><span>${personLabel(a)}</span> <span class="muted">${a.platform}</span>
191
+ ${canManage && !p.inheritedApprovers ? html`<button type="button" class="icon-btn" aria-label=${ca("approverRemove", personLabel(a))} title=${ca("approverRemove", personLabel(a))} disabled=${busy}
192
+ onClick=${() => void write({ approvers: p.approvers.filter((x) => x !== a) })}><${Icon} name="trash" size=${16} /></button>` : null}</li>`)}</ul>`
193
+ : html`<p class="feedback warning">${ca("approversNone")}</p>`}
194
+ ${p.inheritedApprovers ? html`<p class="note">${ca("approversInherited")}</p>` : canManage ? html`<button type="button" class="btn btn-sm" disabled=${busy} onClick=${() => void write({ approvers: [] })}>${ca("approversReset")}</button>` : null}
195
+ ${canManage ? (() => {
196
+ // Slice 1: an approver is one of the server's eligible people (a Fleet admin or the verified host operator) — a
197
+ // pick, never a typed name; the server refuses anyone else (invalid-approver).
198
+ const key = (x) => `${x.platform}:${x.adapterId}:${x.userId}`, have = new Set(p.approvers.map(key));
199
+ const left = (p.eligibleApprovers || []).filter((x) => !have.has(key(x)));
200
+ return left.length ? html`<form class="field-row contact-approver-add" onSubmit=${(e) => { e.preventDefault(); const who = left.find((x) => key(x) === pick); if (who) void write({ approvers: [...p.approvers, who] }).then((ok) => { if (ok) setPick(""); }); }}>
201
+ <label class="sr-only" for=${`contact-approver-${name}`}>${ca("approverPick")}</label>
202
+ <select id=${`contact-approver-${name}`} class="input" value=${pick} disabled=${busy} onChange=${(e) => setPick(e.currentTarget.value)}>
203
+ <option value="">${ca("approverNone")}</option>${left.map((x) => html`<option key=${key(x)} value=${key(x)}>${personLabel(x)} · ${x.platform}</option>`)}</select>
204
+ <button type="submit" class="btn btn-sm" disabled=${busy || !pick}>${ca("approverAdd")}</button></form>` : null;
205
+ })() : null}
206
+ <p class="note">${ca("approverAdmins")}</p>
207
+ </section>
208
+ <section class="card contact-grants">
209
+ <h3>${ca("grantsTitle")}</h3>
210
+ <p class="note">${ca("grantsNote")}</p>
211
+ ${p.grants.length ? html`<ul class="contact-list">${p.grants.map((gr) => html`<li key=${gr.id}>
212
+ <div><strong>${personLabel(gr.person)}</strong> <span class="muted">${ca("grantRow", gr.source, gr.target)}</span></div>
213
+ <div class="muted">${ca("grantVerbs", gr.verbs.map((v) => ca(`verb_${v}`)).join(", "))} · ${ca("grantExpires", when(gr.expiresAt))} · ${gr.remainingUses == null ? ca("grantUnlimited") : ca("grantUses", gr.remainingUses)}</div>
214
+ ${canManage ? html`<button type="button" class="btn btn-sm btn-ghost" disabled=${busy} onClick=${async () => {
215
+ if (await confirmDialog({ message: ca("grantRemoveConfirm"), confirmLabel: ca("grantRemove"), danger: true })) void grantsWrite(p.grants.filter((x) => x.id !== gr.id));
216
+ }}>${ca("grantRemove")}</button>` : null}</li>`)}</ul>` : html`<p class="note">${ca("grantsNone")}</p>`}
217
+ </section>`}
218
+ ${p.originState ? html`<section class="card contact-origin">
219
+ <h3>${ca("originTitle")}</h3>
220
+ <p class="contact-origin-state"><strong>${ca(`originKind_${p.originState.kind}`)}</strong></p>
221
+ <p class="note">${ca("originRetainedNote")}</p>
222
+ <p>${ca("originPeople")}</p>
223
+ ${p.originState.people.length ? html`<ul class="contact-list contact-origin-people">${p.originState.people.map((person) => html`<li key=${`${person.platform}:${person.adapterId}:${person.userId}`}>
224
+ <strong>${personLabel(person)}</strong> <span class="muted">${person.platform} · ${person.adapterId} · ${person.userId}</span></li>`)}</ul>` : html`<p class="note">${ca("originPeopleNone")}</p>`}
225
+ <p class="contact-origin-chain">${ca("originChain")}: ${p.originState.chain.length ? p.originState.chain.join(" → ") : ca("originChainNone")}</p>
226
+ <p class="note">${ca("originReceipts", p.originState.receiptCount)}</p>
227
+ ${p.originState.lastCleared ? html`<p class="contact-origin-last">${ca("originLastCleared", personLabel(p.originState.lastCleared.actor), when(p.originState.lastCleared.at))}</p>` : null}
228
+ ${p.originState.canClear ? html`<button type="button" class="btn btn-sm btn-danger contact-origin-clear" disabled=${busy} onClick=${() => void clearRetainedOrigin()}>${ca("originClear")}</button>` : null}
229
+ </section>` : null}
230
+ <section class="card contact-history">
231
+ <h3>${ca("historyTitle")}</h3>
232
+ ${p.history.length ? html`<ul class="contact-list contact-history-list">${p.history.map((h) => html`<li key=${h.id}>
233
+ <span class="mono muted">${when(h.at)}</span> <strong>${ca(`action_${h.action}`)}</strong> <span>${personLabel(h.actor)}</span>
234
+ ${h.ticketId ? html` <a href=${`/ui/fleet/authorizations?ticket=${encodeURIComponent(h.ticketId)}`} title=${h.ticketId}>#${shortTicketId(h.ticketId)}</a>` : null}
235
+ ${h.summary ? html`<div class="muted">${h.summary}</div>` : null}</li>`)}</ul>` : html`<p class="note">${ca("historyNone")}</p>`}
236
+ </section>
237
+ </div>`;
238
+ }
@@ -0,0 +1,54 @@
1
+ // M-3339 (A2): a chat message's contact badge — message.contactTicket = { id, state } (the contract's ContactBadge), on a
2
+ // ClassicBot room's held request or its status line ("聯絡申請 #R12"), and on the worker's inbound copy of an approved one
3
+ // ("已准轉交 #R12"). A link to that request (Fleet → Authorizations, where the server scopes who may read it).
4
+ // Kept current: on the stream's contact-auth frame naming a request a badge shows, that request is read again from its
5
+ // scoped route (installBadgeRefresh) and its badges change in place; later draws use that state too. A reader the route
6
+ // refuses keeps the message's own state.
7
+ // HTML text for chat-thread.js's opts.contactBadge hook (the Fleet chat's only; a Hub room passes none): every value escaped.
8
+ import { appStore } from "/assets/app-store.js";
9
+ import { ca } from "./contact-auth-strings.js";
10
+ import { getTicket, shortTicketId } from "./contact-auth-client.js";
11
+
12
+ const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
13
+ const ID = /^[A-Za-z0-9_-]{1,64}$/;
14
+ const STATES = new Set(["pending", "approved", "delivered", "declined", "expired", "unknown"]);
15
+ /** The latest state read for a request (its scoped route), over the message's own. */
16
+ const fresh = new Map();
17
+ /** Requests a badge has shown on this page (the only ones a contact-auth frame reads again). */
18
+ const shown = new Set();
19
+
20
+ const badgeText = (full, state) => { const id = shortTicketId(full); return state === "delivered" ? `${ca("forwarded")} #${id}`
21
+ : state === "pending" || !STATES.has(state) ? ca("ticket", id) : `${ca("ticket", id)} · ${ca(`state_${state}`)}`; };
22
+
23
+ export function contactBadgeHtml(x) {
24
+ const tk = x && x.contactTicket;
25
+ if (!tk || typeof tk.id !== "string" || !ID.test(tk.id)) return "";
26
+ shown.add(tk.id);
27
+ const state = fresh.get(tk.id) ?? tk.state;
28
+ const ok = state === "delivered" || state === "approved";
29
+ return `<a class="contact-badge${ok ? " ok" : ""}" data-contact-ticket="${esc(tk.id)}" href="/ui/fleet/authorizations?ticket=${encodeURIComponent(tk.id)}">${esc(badgeText(tk.id, state))}</a>`;
30
+ }
31
+
32
+ /** Read one request again and change its badges on the page in place. */
33
+ export async function refreshBadge(id, doc = typeof document !== "undefined" ? document : null) {
34
+ if (!ID.test(String(id || "")) || !shown.has(id)) return;
35
+ const r = await getTicket(id);
36
+ if (!r.ok || !STATES.has(r.data?.state)) return;
37
+ fresh.set(id, r.data.state);
38
+ for (const a of doc ? doc.querySelectorAll("a.contact-badge") : []) {
39
+ if (a.getAttribute("data-contact-ticket") !== id) continue;
40
+ a.textContent = badgeText(id, r.data.state);
41
+ a.classList.toggle("ok", r.data.state === "delivered" || r.data.state === "approved");
42
+ }
43
+ }
44
+
45
+ let installed = null;
46
+ /** Once per page: the stream's contact-auth frames with a ticketId refresh that request's badges. */
47
+ export function installBadgeRefresh() {
48
+ if (installed) return installed;
49
+ const sub = appStore.get().streamOn;
50
+ if (typeof sub !== "function") return () => {};
51
+ const off = sub("contact-auth", (d) => { if (d && typeof d.ticketId === "string") void refreshBadge(d.ticketId); });
52
+ installed = () => { if (typeof off === "function") off(); installed = null; };
53
+ return installed;
54
+ }
@@ -0,0 +1,39 @@
1
+ // M-3387 (the user, beta.14): switching a ClassicBot room to restricted mode listed ~50 raw AgEnD tool names
2
+ // (hub_room_list, get_fleet_status, set_web_theme_asset, office_pack_upload…) as what would stop. They are now said as a
3
+ // few kinds, with counts, and the names behind a "show all".
4
+ //
5
+ // Two layers stop: AgEnD's own tools (every MCP tool outside the restricted ceiling, CLASSIC_RESTRICTED_TOOLS) are taken
6
+ // away by the switch itself; the CLI's own tools (its shell, files, web — the backend's names, e.g. Bash) stop only where
7
+ // the command-line guard covers the room. A name in TOOL_GROUPS is AgEnD's; any other name in wouldDisable is the CLI's.
8
+ // tests/contact-tool-groups-m3387.test.ts pins that every AgEnD MCP tool (src/channel/mcp-tools.ts) outside the ceiling is
9
+ // in exactly one group, so a new tool can't be added without being put in one.
10
+
11
+ /** The kinds of AgEnD tools a restricted room loses, in the order they are shown; each tool in exactly one. */
12
+ export const TOOL_GROUPS = Object.freeze([
13
+ { id: "fleet", tools: ["get_fleet_status", "get_fleet_config", "validate_config", "get_effort", "list_models", "kiro_engine_status",
14
+ "update_instance_config", "update_fleet_defaults", "migrate_kiro_instance", "reconcile_kiro_instance", "get_web_settings", "set_web_settings"] },
15
+ { id: "agents", tools: ["create_instance", "delete_instance", "replace_instance", "start_instance", "stop_instance", "restart_instance",
16
+ "pause_instance", "wake_instance", "create_team", "update_team", "delete_team"] },
17
+ { id: "usage", tools: ["get_usage", "get_usage_report", "get_cache_report", "get_instance_logs"] },
18
+ { id: "schedules", tools: ["create_schedule", "list_schedules", "update_schedule", "delete_schedule"] },
19
+ { id: "tasks", tools: ["task", "post_decision", "list_decisions", "update_decision"] },
20
+ { id: "look", tools: ["set_display_name", "set_description", "set_persona_emoji", "list_emojis", "preview_emojis", "list_stickers",
21
+ "preview_stickers", "get_web_theme", "set_web_theme", "set_web_theme_asset", "reset_web_theme", "get_web_appearance",
22
+ "preview_web_appearance", "set_web_widget", "remove_web_widget", "set_web_ambient", "clear_web_ambient", "office_view", "office_set",
23
+ "office_set_style", "office_pack_check", "office_pack_list", "office_pack_upload", "office_pack_delete", "office_pack_restore"] },
24
+ { id: "repos", tools: ["checkout_repo", "release_repo", "deploy_template", "teardown_deployment", "list_deployments"] },
25
+ { id: "hub", tools: ["hub_room_list", "hub_room_post", "hub_room_members", "hub_people_search", "hub_set_intro"] },
26
+ ].map((g) => Object.freeze({ id: g.id, tools: Object.freeze(g.tools) })));
27
+
28
+ const GROUP_OF = new Map(TOOL_GROUPS.flatMap((g) => g.tools.map((tool) => [tool, g.id])));
29
+
30
+ /**
31
+ * `names` (a room's wouldDisable) split by layer: AgEnD's tools by kind (shown order; kinds with none left out) and the
32
+ * CLI's own tools (any other name), each list sorted, nothing twice.
33
+ */
34
+ export function groupWouldDisable(names) {
35
+ const unique = [...new Set((names || []).map(String))];
36
+ const groups = TOOL_GROUPS.map((g) => ({ id: g.id, tools: unique.filter((n) => GROUP_OF.get(n) === g.id).sort() })).filter((g) => g.tools.length);
37
+ const cli = unique.filter((n) => !GROUP_OF.has(n)).sort();
38
+ return { groups, cli, agendCount: groups.reduce((sum, g) => sum + g.tools.length, 0) };
39
+ }
@@ -232,7 +232,7 @@ export function createStubClient({ now = () => Date.now(), agents = () => [] } =
232
232
  export function createHubWebClient({ fetchImpl = (...a) => fetch(...a), readTimeoutMs = 120_000 } = {}) {
233
233
  // The factory override is for owned transports/rehearsals; the page uses the finite default.
234
234
  const readBudget = Number.isInteger(readTimeoutMs) && readTimeoutMs > 0 && readTimeoutMs <= 300_000 ? readTimeoutMs : 120_000;
235
- let csrf = null, codeNotices = false, roomsLive = false, teamsLive = false, generation = 0;
235
+ let csrf = null, codeNotices = false, roomsLive = false, teamsLive = false, ownerRequestsLive = false, roomDiscoveryLive = false, generation = 0;
236
236
  const ended = new Set(), pendingReads = new Map(), waits = new Set(), readControllers = new Set();
237
237
  let readTail = Promise.resolve();
238
238
  const retired = () => ({ ok: false, status: 401, code: "unauthenticated" });
@@ -302,18 +302,24 @@ export function createHubWebClient({ fetchImpl = (...a) => fetch(...a), readTime
302
302
  let json = null;
303
303
  try { json = await r.json(); } catch { json = null; }
304
304
  if (method === "GET" && signal?.aborted) return unreachable();
305
- if (r.status === 401 && mine === generation) { retireReads(); csrf = null; codeNotices = false; roomsLive = false; teamsLive = false; for (const fn of ended) { try { fn(); } catch { /* a listener's own failure */ } } }
305
+ if (r.status === 401 && mine === generation) { retireReads(); csrf = null; codeNotices = false; roomsLive = false; teamsLive = false; ownerRequestsLive = false; roomDiscoveryLive = false; for (const fn of ended) { try { fn(); } catch { /* a listener's own failure */ } } }
306
306
  if (!r.ok) return { ok: false, status: r.status, code: (json && typeof json.code === "string" && json.code) || "failed", retryAfter: Number(r.headers.get("Retry-After")) || 0,
307
307
  ...(method === "POST" && path === "/hub/v1/admin/enrolment-codes" && r.status === 429 && json?.code === "backpressure"
308
308
  && ["live-code-limit", "hourly-code-limit"].includes(json.reason) ? { reason: json.reason } : {}), ...roomRefusal(json) };
309
309
  return { ok: true, ...(json && typeof json === "object" ? json : {}) };
310
310
  }
311
311
  const id = (v) => encodeURIComponent(String(v));
312
+ const ownerRequestCall = async (scope, method, path, body) => {
313
+ if (!scope || scope !== csrf) return retired();
314
+ const mine = generation, result = await call(method, path, body);
315
+ return mine === generation && scope === csrf ? result : retired();
316
+ };
312
317
  // Track U2: a refused room write says what the person is told — 409 people-limit the room's would-be head count (the
313
318
  // deduplicated union, the creator and current members included) and the limit; 503 group-unavailable which group.
314
319
  const roomRefusal = (json) => json?.code === "people-limit" && Number.isSafeInteger(json.people)
315
320
  ? { people: json.people, limit: Number.isSafeInteger(json.limit) ? json.limit : 100 }
316
- : json?.code === "group-unavailable" && typeof json.group === "string" ? { group: json.group } : {};
321
+ : json?.code === "group-unavailable" && typeof json.group === "string" ? { group: json.group }
322
+ : json?.code === "request-limit" && Number.isSafeInteger(json.resetsAt) && json.resetsAt > 0 && json.resetsAt <= 8.64e15 ? { resetsAt: json.resetsAt } : {};
317
323
  // One stream per tab (#1580): every live subscription shares one EventSource. A Hub with rooms carries the notices on
318
324
  // its rooms stream too (`notices` = the notice version); before that the notices have their own. Listeners are kept
319
325
  // per event name; the stream closes with its last listener, and a refused (CLOSED) stream tells every subscriber once.
@@ -361,10 +367,22 @@ export function createHubWebClient({ fetchImpl = (...a) => fetch(...a), readTime
361
367
  stub: false, web: true,
362
368
  /** Hear the session end (a 401 anywhere). @returns {() => void} */
363
369
  onSignedOut(fn) { ended.add(fn); return () => ended.delete(fn); },
364
- async session() { const r = await call("GET", "/hub/v1/session"); if (r.ok) { csrf = r.signedIn ? r.csrf || null : null; codeNotices = r.signedIn === true && r.features?.includes("enrolment-code-v1") === true; roomsLive = r.signedIn === true && r.features?.includes(ROOMS_FEATURE) === true; teamsLive = r.signedIn === true && r.features?.includes(TEAMS_FEATURE) === true; } return r; },
365
- async signIn(login, password) { retireReads(); teamsLive = false; const r = await call("POST", "/hub/v1/session", { login, password }); if (r.ok) { csrf = r.csrf || null; codeNotices = r.features?.includes("enrolment-code-v1") === true; roomsLive = r.features?.includes(ROOMS_FEATURE) === true; teamsLive = r.features?.includes(TEAMS_FEATURE) === true; } return r; },
366
- async signOut() { retireReads(); const r = await call("DELETE", "/hub/v1/session"); csrf = null; codeNotices = false; roomsLive = false; teamsLive = false; return r; },
370
+ async session() { const r = await call("GET", "/hub/v1/session"); if (r.ok) { csrf = r.signedIn ? r.csrf || null : null; codeNotices = r.signedIn === true && r.features?.includes("enrolment-code-v1") === true; roomsLive = r.signedIn === true && r.features?.includes(ROOMS_FEATURE) === true; teamsLive = r.signedIn === true && r.features?.includes(TEAMS_FEATURE) === true; ownerRequestsLive = r.signedIn === true && r.features?.includes("room-owner-requests-v1") === true; roomDiscoveryLive = r.signedIn === true && r.features?.includes("room-agent-discovery-v1") === true; } return r; },
371
+ async signIn(login, password) { retireReads(); teamsLive = false; ownerRequestsLive = false; roomDiscoveryLive = false; const r = await call("POST", "/hub/v1/session", { login, password }); if (r.ok) { csrf = r.csrf || null; codeNotices = r.features?.includes("enrolment-code-v1") === true; roomsLive = r.features?.includes(ROOMS_FEATURE) === true; teamsLive = r.features?.includes(TEAMS_FEATURE) === true; ownerRequestsLive = r.features?.includes("room-owner-requests-v1") === true; roomDiscoveryLive = r.features?.includes("room-agent-discovery-v1") === true; } return r; },
372
+ async signOut() { retireReads(); const r = await call("DELETE", "/hub/v1/session"); csrf = null; codeNotices = false; roomsLive = false; teamsLive = false; ownerRequestsLive = false; roomDiscoveryLive = false; return r; },
367
373
  aiAppsScope() { return csrf; },
374
+ roomAgentRequestScope() { return csrf; },
375
+ requestRoomAgent(scope, roomId, input) { return ownerRequestCall(scope, "POST", "/hub/v1/rooms/" + id(roomId) + "/agent-requests", input); },
376
+ roomAgentRequests(scope, roomId, after) { return ownerRequestCall(scope, "GET", "/hub/v1/rooms/" + id(roomId) + "/agent-requests" + (after ? "?after=" + id(after) : "")); },
377
+ cancelRoomAgentRequest(scope, roomId, requestId) { return ownerRequestCall(scope, "DELETE", "/hub/v1/rooms/" + id(roomId) + "/agent-requests/" + id(requestId)); },
378
+ ownerRequestsLive() { return ownerRequestsLive; },
379
+ roomDiscoveryLive() { return roomDiscoveryLive; },
380
+ agentRoomDiscovery(scope, exposureId, input) { return ownerRequestCall(scope, input === undefined ? "GET" : "PUT", "/hub/v1/exposures/" + id(exposureId) + "/room-discovery", input); },
381
+ ownerAgentRequest(scope, requestId) { return ownerRequestCall(scope, "GET", "/hub/v1/agent-requests/" + id(requestId)); },
382
+ acceptOwnerAgentRequest(scope, requestId, input) { return ownerRequestCall(scope, "POST", "/hub/v1/agent-requests/" + id(requestId) + "/accept", input); },
383
+ declineOwnerAgentRequest(scope, requestId) { return ownerRequestCall(scope, "POST", "/hub/v1/agent-requests/" + id(requestId) + "/decline", {}); },
384
+ ownerAgentRequests(scope, after) { return ownerRequestCall(scope, "GET", "/hub/v1/agent-requests" + (after ? "?after=" + id(after) : "")); },
385
+ agentRequestSettings(scope, input) { return ownerRequestCall(scope, input === undefined ? "GET" : "PUT", "/hub/v1/me/agent-request-settings", input); },
368
386
  aiApps(scope) { return scope && scope === csrf ? call("GET", "/hub/v1/me/ai-apps") : Promise.resolve(retired()); },
369
387
  disconnectAiApp(scope, appId) { return scope && scope === csrf ? call("DELETE", `/hub/v1/me/ai-apps/${id(appId)}`) : Promise.resolve(retired()); },
370
388
  appConsent(scope, request) { return scope && scope === csrf ? call("GET", `/hub/v1/mcp/consent?${new URLSearchParams({request})}`) : Promise.resolve(retired()); },
@@ -443,7 +461,7 @@ export function createHubWebClient({ fetchImpl = (...a) => fetch(...a), readTime
443
461
  * server without rooms ignores the parameter (its answer is then normalised here).
444
462
  */
445
463
  async roomList() {
446
- const r = await call("GET", "/hub/v1/rooms?v=2");
464
+ const r = await call("GET", "/hub/v1/rooms?v=2" + (ownerRequestsLive ? "&ownerRequests=1" : ""));
447
465
  if (!r.ok || roomsLive) return r;
448
466
  return { ...r, rooms: (Array.isArray(r.rooms) ? r.rooms : []).map(legacyRoom).filter(Boolean) };
449
467
  },
@@ -479,6 +497,10 @@ export function createHubWebClient({ fetchImpl = (...a) => fetch(...a), readTime
479
497
  },
480
498
  /** M-3127: add (`on`) or take back my reaction `emoji` on a group-room message → { reactions }. */
481
499
  reactRoomMessage(roomId, messageId, emoji, on) { return call("POST", `/hub/v1/rooms/${id(roomId)}/messages/${id(messageId)}/reactions`, { emoji: String(emoji), on: on === true }); },
500
+ /** M-3340: my own pins in a group room (nobody else's) → { pins: [{ messageId, pinnedAt, message }] }, newest first. */
501
+ roomPins(roomId) { return call("GET", `/hub/v1/rooms/${id(roomId)}/pins`); },
502
+ /** M-3340: pin (`on`) or unpin a group-room message for me only → { pins }. Past 50: the Hub refuses (pins-full). */
503
+ pinRoomMessage(roomId, messageId, on) { return call(on ? "PUT" : "DELETE", `/hub/v1/rooms/${id(roomId)}/pins/${id(messageId)}`); },
482
504
  markRoomRead(roomId, upTo) { return call("POST", `/hub/v1/rooms/${id(roomId)}/read`, { upTo }); },
483
505
  /**
484
506
  * The one live stream of everything this person may see (seam 1): `handlers[name](data)` for each of ROOM_EVENTS,
@@ -531,6 +553,7 @@ export function createHubWebClient({ fetchImpl = (...a) => fetch(...a), readTime
531
553
  roomCandidates(q, kind, signal) {
532
554
  const s = new URLSearchParams({ q: String(q ?? "") });
533
555
  if (kind) s.set("kind", kind);
556
+ if (kind === "agent" && roomDiscoveryLive) s.set("discovery", "1");
534
557
  return call("GET", `/hub/v1/rooms/candidates?${s}`, undefined, signal);
535
558
  },
536
559
  /**
@@ -8,6 +8,7 @@ import { hubClient } from "./hub-client.js";
8
8
  import { hi } from "./hub-invitations-strings.js";
9
9
  import { hroom } from "./hub-room-strings.js";
10
10
  import { linkRoomsU2Css } from "./hub-room-new-strings.js";
11
+ import { OwnerAgentRequestsList } from "./hub-room-owner-requests.js";
11
12
 
12
13
  linkRoomsU2Css();
13
14
 
@@ -42,7 +43,10 @@ const valid = (x) => x && typeof x.id === "string" && x.room && typeof x.room.na
42
43
  * The invitations themselves, each with 同意 / 不要. Nothing when there are none (My shared agents shows no empty box).
43
44
  * heading: the list's own 「邀請」 title — false where the page already says it (the invitations page's header).
44
45
  */
45
- export function InvitationsList({ client = hubClient(), heading = true } = {}) { // onOpenRoom: not used — the owner is not a member of the inviting room
46
+ export function InvitationsList({ client = hubClient(), heading = true } = {}) {
47
+ return html`<${OwnerAgentRequestsList} client=${client} heading=${heading} /><${LegacyInvitationsList} client=${client} heading=${heading} />`;
48
+ }
49
+ function LegacyInvitationsList({ client, heading }) { // onOpenRoom: not used — the owner is not a member of the inviting room
46
50
  const { list, error, reload, answer } = useInvitations(client);
47
51
  const [busy, setBusy] = useState(null), [note, setNote] = useState(null), inflight = useRef(false);
48
52
  if (error && !list) return html`<p class="note hub-invitations-error" role="alert">${hi("loadFailed")} <button type="button" class="btn btn-link" onClick=${() => { void reload(); }}>${hi("retry")}</button></p>`;
@@ -8,6 +8,7 @@ import {RoomPurposeField,purposeCount} from "./hub-room-purpose.js";
8
8
  import { html, useEffect, useRef, useState } from "/assets/app-html.js";
9
9
  import { Dialog } from "/assets/ui-dialog.js";
10
10
  import { hubClient } from "./hub-client.js";
11
+ import { hrq } from "./hub-room-owner-requests-strings.js";
11
12
  import { hroom } from "./hub-room-strings.js";
12
13
  import { hn, linkRoomsU2Css } from "./hub-room-new-strings.js";
13
14
 
@@ -33,12 +34,17 @@ const keyOf = (item) => `${item.kind}:${item.id}`;
33
34
  * A picked AD group is read first (client.roomGroup): its tag shows its head count, and a group the directory cannot
34
35
  * read whole is not added — the other picks stay.
35
36
  */
36
- export function RoomPicker({ client, kinds, picked, onChange, placeholder, label, id, exclude = [], fixed = null, note = "" } = {}) {
37
+ export function RoomPicker({ client, kinds, picked, onChange, placeholder, label, id, exclude = [], fixed = null, note = "", searchHelp = null } = {}) {
37
38
  const [q, setQ] = useState(""), [results, setResults] = useState(null), [failed, setFailed] = useState(false), [groupNote, setGroupNote] = useState("");
38
39
  const asked = useRef(0), timer = useRef(null), latest = useRef(picked), live = useRef(true);
39
40
  latest.current = picked;
40
41
  const agents = kinds.includes("agent");
41
42
  useEffect(() => { live.current = true; return () => { live.current = false; clearTimeout(timer.current); }; }, []);
43
+ const leave = (event) => {
44
+ // Null is ambiguous on touch/Safari; retain in-field pointer selection.
45
+ if (!event.relatedTarget || event.currentTarget.contains(event.relatedTarget)) return;
46
+ clearTimeout(timer.current); ++asked.current; setResults(null);
47
+ };
42
48
  const search = (text) => {
43
49
  setQ(text); clearTimeout(timer.current);
44
50
  const mine = ++asked.current;
@@ -63,7 +69,7 @@ export function RoomPicker({ client, kinds, picked, onChange, placeholder, label
63
69
  if (!r?.ok) { setGroupNote(hn("groupUnavailable", item.name)); return; }
64
70
  onChange([...latest.current, { ...item, ...(typeof r.name === "string" && r.name ? { name: r.name } : {}), ...(Number.isSafeInteger(r.people) ? { people: r.people } : {}) }]);
65
71
  };
66
- return html`<div class="field hub-room-picker">
72
+ return html`<div class="field hub-room-picker" onFocusOut=${leave}>
67
73
  <label for=${id}><span>${label}</span></label>
68
74
  <ul class="hub-room-tags">
69
75
  ${fixed}
@@ -74,8 +80,9 @@ export function RoomPicker({ client, kinds, picked, onChange, placeholder, label
74
80
  ${failed ? html`<p class="note" role="alert">${hn("searchFailed")}</p>` : null}
75
81
  ${groupNote || note ? html`<p class="note hub-room-picker-note" role="alert">${groupNote || note}</p>` : null}
76
82
  ${results && !failed ? offer.length ? html`<ul class="hub-room-results" role="listbox" aria-label=${label}>${offer.map(c => html`<li key=${keyOf(c)}>
77
- <button type="button" role="option" class="hub-room-result" onClick=${() => { void pick(c); }}>${pickLabel(c)}${c.intro?html` <small class="note">${c.intro}</small>`:null}${c.owner?.name && c.kind === "agent" ? html` <small class="note">${c.owner.name}</small>` : null}${c.kind === "agent" && !c.mine ? html` <small class="note">${hroom("invitePending")}</small>` : null}</button></li>`)}</ul>`
83
+ <button type="button" role="option" class=${`hub-room-result${c.kind === "agent" ? " hub-room-result-agent" : ""}`} aria-label=${c.kind === "person" ? `${c.name}${c.detail ? `, ${c.detail}` : ""}` : c.kind === "agent" && !c.mine ? hrq("askOwnerLabel", c.owner?.name || "", c.name) : undefined} onClick=${() => { void pick(c); }}>${c.kind === "person" ? html`<span class="hub-room-person-label"><span class="hub-room-person-name" title=${c.name}>${c.name}</span>${c.detail ? html`<small class="note hub-room-person-detail" title=${c.detail}>${c.detail}</small>` : null}</span>` : c.kind === "agent" ? html`<span class="hub-room-agent-label"><span class="hub-room-agent-title">${c.name}${c.owner?.name ? html` <small class="note">${c.owner.name}</small>` : null}</span>${c.intro ? html`<small class="note hub-room-agent-intro" title=${c.intro}>${c.intro}</small>` : null}</span> ${!c.mine ? html`<span class="btn btn-sm hub-room-agent-action">${hrq("askOwner", c.owner?.name || "")}</span>` : null}` : pickLabel(c)}${c.kind !== "agent" && c.intro ? html` <small class="note">${c.intro}</small>` : null}</button></li>`)}</ul>`
78
84
  : html`<p class="note">${hn("noMatch")}</p>` : null}
85
+ ${q.trim() ? searchHelp : null}
79
86
  </div>`;
80
87
  }
81
88