@stigmer/react 3.1.8 → 3.1.9

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 (72) hide show
  1. package/environment/EnvironmentPicker.d.ts +17 -1
  2. package/environment/EnvironmentPicker.d.ts.map +1 -1
  3. package/environment/EnvironmentPicker.js +3 -2
  4. package/environment/EnvironmentPicker.js.map +1 -1
  5. package/index.d.ts +2 -2
  6. package/index.d.ts.map +1 -1
  7. package/index.js +2 -2
  8. package/index.js.map +1 -1
  9. package/package.json +4 -4
  10. package/sharing/ShareAgentDialog.d.ts +10 -8
  11. package/sharing/ShareAgentDialog.d.ts.map +1 -1
  12. package/sharing/ShareAgentDialog.js +139 -54
  13. package/sharing/ShareAgentDialog.js.map +1 -1
  14. package/sharing/SharedAgentChat.d.ts +1 -1
  15. package/sharing/SharedAgentChat.d.ts.map +1 -1
  16. package/sharing/index.d.ts +4 -2
  17. package/sharing/index.d.ts.map +1 -1
  18. package/sharing/index.js +2 -1
  19. package/sharing/index.js.map +1 -1
  20. package/sharing/useAgentShare.d.ts +43 -0
  21. package/sharing/useAgentShare.d.ts.map +1 -0
  22. package/sharing/useAgentShare.js +54 -0
  23. package/sharing/useAgentShare.js.map +1 -0
  24. package/sharing/useRotateShareLink.d.ts +22 -19
  25. package/sharing/useRotateShareLink.d.ts.map +1 -1
  26. package/sharing/useRotateShareLink.js +22 -19
  27. package/sharing/useRotateShareLink.js.map +1 -1
  28. package/sharing/useSaveAgentShare.d.ts +105 -0
  29. package/sharing/useSaveAgentShare.d.ts.map +1 -0
  30. package/sharing/useSaveAgentShare.js +97 -0
  31. package/sharing/useSaveAgentShare.js.map +1 -0
  32. package/sharing/useShareAgent.d.ts +5 -4
  33. package/sharing/useShareAgent.d.ts.map +1 -1
  34. package/sharing/useShareAgent.js +5 -4
  35. package/sharing/useShareAgent.js.map +1 -1
  36. package/sharing/useShareToolReadiness.d.ts +29 -25
  37. package/sharing/useShareToolReadiness.d.ts.map +1 -1
  38. package/sharing/useShareToolReadiness.js +47 -51
  39. package/sharing/useShareToolReadiness.js.map +1 -1
  40. package/sharing/useSharedAgentProfile.d.ts +5 -4
  41. package/sharing/useSharedAgentProfile.d.ts.map +1 -1
  42. package/sharing/useSharedAgentProfile.js +6 -5
  43. package/sharing/useSharedAgentProfile.js.map +1 -1
  44. package/src/environment/EnvironmentPicker.tsx +23 -2
  45. package/src/index.ts +8 -4
  46. package/src/sharing/ShareAgentDialog.tsx +353 -119
  47. package/src/sharing/SharedAgentChat.tsx +1 -1
  48. package/src/sharing/__tests__/ShareAgentDialog.test.tsx +550 -369
  49. package/src/sharing/__tests__/useAgentShare.test.tsx +149 -0
  50. package/src/sharing/__tests__/useRotateShareLink.test.tsx +8 -8
  51. package/src/sharing/__tests__/useSaveAgentShare.test.tsx +241 -0
  52. package/src/sharing/__tests__/useShareAgent.test.tsx +6 -2
  53. package/src/sharing/__tests__/useShareToolReadiness.test.tsx +84 -47
  54. package/src/sharing/__tests__/useSharedAgentProfile.test.tsx +1 -1
  55. package/src/sharing/index.ts +9 -7
  56. package/src/sharing/useAgentShare.ts +91 -0
  57. package/src/sharing/useRotateShareLink.ts +30 -25
  58. package/src/sharing/useSaveAgentShare.ts +186 -0
  59. package/src/sharing/useShareAgent.tsx +5 -4
  60. package/src/sharing/useShareToolReadiness.ts +62 -60
  61. package/src/sharing/useSharedAgentProfile.ts +7 -6
  62. package/src/switch/Switch.tsx +6 -1
  63. package/src/switch/__tests__/Switch.test.tsx +19 -0
  64. package/switch/Switch.d.ts.map +1 -1
  65. package/switch/Switch.js +6 -1
  66. package/switch/Switch.js.map +1 -1
  67. package/sharing/useUpdateAgentSharing.d.ts +0 -86
  68. package/sharing/useUpdateAgentSharing.d.ts.map +0 -1
  69. package/sharing/useUpdateAgentSharing.js +0 -81
  70. package/sharing/useUpdateAgentSharing.js.map +0 -1
  71. package/src/sharing/__tests__/useUpdateAgentSharing.test.tsx +0 -200
  72. package/src/sharing/useUpdateAgentSharing.ts +0 -151
@@ -12,7 +12,7 @@ function createMockStigmer(overrides: {
12
12
  getSharedProfileForMember?: (...args: unknown[]) => Promise<unknown>;
13
13
  } = {}) {
14
14
  return {
15
- agent: {
15
+ agentShare: {
16
16
  getSharedProfile:
17
17
  overrides.getSharedProfile ?? vi.fn().mockResolvedValue(null),
18
18
  getSharedProfileForMember:
@@ -5,17 +5,19 @@ export type {
5
5
  } from "./useSharedAgentProfile.js";
6
6
  export { SharedAgentChat } from "./SharedAgentChat.js";
7
7
  export type { SharedAgentChatProps } from "./SharedAgentChat.js";
8
+ export { useAgentShare } from "./useAgentShare.js";
9
+ export type { UseAgentShareReturn } from "./useAgentShare.js";
8
10
  export {
9
11
  sharingAudienceFromProto,
10
- useUpdateAgentSharing,
11
- } from "./useUpdateAgentSharing.js";
12
- export { useRotateShareLink } from "./useRotateShareLink.js";
13
- export type { UseRotateShareLinkReturn } from "./useRotateShareLink.js";
12
+ useSaveAgentShare,
13
+ } from "./useSaveAgentShare.js";
14
14
  export type {
15
- AgentSharingDraft,
15
+ AgentShareDraft,
16
16
  SharingAudience,
17
- UseUpdateAgentSharingReturn,
18
- } from "./useUpdateAgentSharing.js";
17
+ UseSaveAgentShareReturn,
18
+ } from "./useSaveAgentShare.js";
19
+ export { useRotateShareLink } from "./useRotateShareLink.js";
20
+ export type { UseRotateShareLinkReturn } from "./useRotateShareLink.js";
19
21
  export { ShareAgentDialog } from "./ShareAgentDialog.js";
20
22
  export type { ShareAgentDialogProps } from "./ShareAgentDialog.js";
21
23
  export { useShareAgent } from "./useShareAgent.js";
@@ -0,0 +1,91 @@
1
+ "use client";
2
+
3
+ import { create } from "@bufbuild/protobuf";
4
+ import type { Agent } from "@stigmer/protos/ai/stigmer/agentic/agent/v1/api_pb";
5
+ import type { AgentShare } from "@stigmer/protos/ai/stigmer/agentic/agentshare/v1/api_pb";
6
+ import { GetAgentSharesByAgentRequestSchema } from "@stigmer/protos/ai/stigmer/agentic/agentshare/v1/io_pb";
7
+ import { useStigmer } from "../hooks.js";
8
+ import { useFetch } from "../internal/useFetch.js";
9
+
10
+ /** Return value of {@link useAgentShare}. */
11
+ export interface UseAgentShareReturn {
12
+ /**
13
+ * The agent's canonical share, or `null` while loading, on error, or
14
+ * when the agent has never been shared. `share === null && !isLoading
15
+ * && !error` means "no share exists yet" — the first save creates it.
16
+ */
17
+ readonly share: AgentShare | null;
18
+ /** `true` while the initial fetch or a refetch is in flight. */
19
+ readonly isLoading: boolean;
20
+ /** `true` while a background refetch is in flight and stale data is shown. */
21
+ readonly isRefetching: boolean;
22
+ /** Error from the last failed request, or `null` when healthy. */
23
+ readonly error: Error | null;
24
+ /** Discard cached data and re-fetch the share from the server. */
25
+ readonly refetch: () => void;
26
+ }
27
+
28
+ /**
29
+ * The canonical share among an agent's shares: the one whose slug equals
30
+ * the agent's slug (the server's default when a share is created without
31
+ * an explicit slug), falling back to the first entry. The data model
32
+ * allows N shares per agent (decision 011 D3); the console manages the
33
+ * canonical one in Phase A, so extra shares created via manifests never
34
+ * confuse the dialog.
35
+ */
36
+ function pickCanonicalShare(
37
+ shares: readonly AgentShare[],
38
+ agentSlug: string,
39
+ ): AgentShare | null {
40
+ return (
41
+ shares.find((share) => share.metadata?.slug === agentSlug) ??
42
+ shares[0] ??
43
+ null
44
+ );
45
+ }
46
+
47
+ /**
48
+ * Data hook that loads an agent's canonical {@link AgentShare} — the
49
+ * resource carrying the hosted-chat channel configuration (audience,
50
+ * allowed origins, visitor messages, tool credentials, link token).
51
+ *
52
+ * Sharing is channel configuration, not agent behavior (decision 011):
53
+ * it lives in its own resource, so reading the agent alone can never
54
+ * tell whether it is shared. This hook is how owner-side surfaces (the
55
+ * Share dialog) resolve that state.
56
+ *
57
+ * Pass `null` for `agent` to skip fetching (stable no-op) — useful
58
+ * while the agent is still loading. A resolved `null` share means the
59
+ * agent has never been shared; the first save creates the share.
60
+ *
61
+ * @example
62
+ * ```tsx
63
+ * const { share, isLoading } = useAgentShare(agent);
64
+ *
65
+ * if (isLoading) return <Spinner />;
66
+ * const enabled = share?.spec?.enabled ?? false;
67
+ * ```
68
+ */
69
+ export function useAgentShare(agent: Agent | null): UseAgentShareReturn {
70
+ const stigmer = useStigmer();
71
+
72
+ const agentId = agent?.metadata?.id ?? "";
73
+ const agentSlug = agent?.metadata?.slug ?? "";
74
+
75
+ const fetchFn = agentId
76
+ ? async () => {
77
+ const result = await stigmer.agentShare.getByAgent(
78
+ create(GetAgentSharesByAgentRequestSchema, { agentId }),
79
+ );
80
+ return pickCanonicalShare(result.items, agentSlug);
81
+ }
82
+ : null;
83
+
84
+ const { data: share, isLoading, isRefetching, error, refetch } = useFetch(
85
+ fetchFn,
86
+ [agentId, agentSlug, stigmer],
87
+ null as AgentShare | null,
88
+ );
89
+
90
+ return { share, isLoading, isRefetching, error, refetch };
91
+ }
@@ -2,19 +2,19 @@
2
2
 
3
3
  import { useCallback, useState } from "react";
4
4
  import { create } from "@bufbuild/protobuf";
5
- import type { Agent } from "@stigmer/protos/ai/stigmer/agentic/agent/v1/api_pb";
6
- import { RotateShareLinkInputSchema } from "@stigmer/protos/ai/stigmer/agentic/agent/v1/io_pb";
5
+ import type { AgentShare } from "@stigmer/protos/ai/stigmer/agentic/agentshare/v1/api_pb";
6
+ import { RotateShareLinkInputSchema } from "@stigmer/protos/ai/stigmer/agentic/agentshare/v1/io_pb";
7
7
  import { useStigmer } from "../hooks.js";
8
8
  import { toError } from "../internal/toError.js";
9
9
 
10
10
  /** Return value of {@link useRotateShareLink}. */
11
11
  export interface UseRotateShareLinkReturn {
12
12
  /**
13
- * Rotate the agent's share-link token via the `rotateShareLink` RPC.
14
- * Resolves with the updated agent, whose `status.shareLinkToken`
13
+ * Rotate the share's link token via the `rotateShareLink` RPC.
14
+ * Resolves with the updated share, whose `status.shareLinkToken`
15
15
  * carries the new token for building the fresh share URL.
16
16
  */
17
- readonly rotateShareLink: () => Promise<Agent | undefined>;
17
+ readonly rotateShareLink: () => Promise<AgentShare | undefined>;
18
18
  /** `true` while the RPC is in flight. */
19
19
  readonly isPending: boolean;
20
20
  /** The last error from the RPC, or `null`. */
@@ -22,47 +22,52 @@ export interface UseRotateShareLinkReturn {
22
22
  }
23
23
 
24
24
  /**
25
- * Behavior hook that rotates an agent's share-link token.
25
+ * Behavior hook that rotates a share's link token.
26
26
  *
27
- * Wraps the `stigmer.agent.rotateShareLink()` RPC (authorized by
28
- * `can_edit`) with loading and error state management. The server
29
- * generates the token — there is nothing to supply — and the previous
30
- * link stops working the moment the call resolves, including for
31
- * visitors mid-conversation. The token lives in `status.shareLinkToken`
32
- * (server-owned), so it is never part of a sharing draft and survives
33
- * manifest applies.
27
+ * Wraps the `stigmer.agentShare.rotateShareLink()` RPC (authorized by
28
+ * the share's `can_edit`) with loading and error state management. The
29
+ * server generates the token — there is nothing to supply — and the
30
+ * previous link stops working the moment the call resolves, including
31
+ * for visitors mid-conversation. The token lives in
32
+ * `status.shareLinkToken` (server-owned; this RPC is its sole writer),
33
+ * so it is never part of a share draft and survives every apply.
34
34
  *
35
- * The hook is stateless with respect to the agent — adopt the returned
36
- * agent (or refetch) so the UI shows the new tokened link, matching the
37
- * {@link useUpdateAgentSharing} convention.
35
+ * The hook is stateless with respect to the share — adopt the returned
36
+ * share (or refetch) so the UI shows the new tokened link, matching the
37
+ * {@link useSaveAgentShare} convention.
38
38
  *
39
- * Pass `null` for `agentId` to produce a stable no-op (useful while the
40
- * agent is still loading).
39
+ * Pass `null` for `shareId` to produce a stable no-op (useful while the
40
+ * share is still loading, or before the agent has ever been shared —
41
+ * there is no token to rotate until a share exists).
41
42
  *
42
43
  * @example
43
44
  * ```tsx
44
- * const { rotateShareLink, isPending } = useRotateShareLink(agent.metadata.id);
45
+ * const { rotateShareLink, isPending } = useRotateShareLink(
46
+ * share?.metadata?.id ?? null,
47
+ * );
45
48
  *
46
49
  * const updated = await rotateShareLink();
47
50
  * // updated.status.shareLinkToken is the new token
48
51
  * ```
49
52
  */
50
53
  export function useRotateShareLink(
51
- agentId: string | null,
54
+ shareId: string | null,
52
55
  ): UseRotateShareLinkReturn {
53
56
  const stigmer = useStigmer();
54
57
  const [isPending, setIsPending] = useState(false);
55
58
  const [error, setError] = useState<Error | null>(null);
56
59
 
57
- const rotateShareLink = useCallback(async (): Promise<Agent | undefined> => {
58
- if (!agentId) return undefined;
60
+ const rotateShareLink = useCallback(async (): Promise<
61
+ AgentShare | undefined
62
+ > => {
63
+ if (!shareId) return undefined;
59
64
 
60
65
  setIsPending(true);
61
66
  setError(null);
62
67
 
63
68
  try {
64
- return await stigmer.agent.rotateShareLink(
65
- create(RotateShareLinkInputSchema, { resourceId: agentId }),
69
+ return await stigmer.agentShare.rotateShareLink(
70
+ create(RotateShareLinkInputSchema, { resourceId: shareId }),
66
71
  );
67
72
  } catch (err) {
68
73
  setError(toError(err));
@@ -70,7 +75,7 @@ export function useRotateShareLink(
70
75
  } finally {
71
76
  setIsPending(false);
72
77
  }
73
- }, [agentId, stigmer]);
78
+ }, [shareId, stigmer]);
74
79
 
75
80
  return { rotateShareLink, isPending, error };
76
81
  }
@@ -0,0 +1,186 @@
1
+ "use client";
2
+
3
+ import { useCallback, useState } from "react";
4
+ import type { Agent } from "@stigmer/protos/ai/stigmer/agentic/agent/v1/api_pb";
5
+ import type { AgentShare } from "@stigmer/protos/ai/stigmer/agentic/agentshare/v1/api_pb";
6
+ import { AgentShareAudience } from "@stigmer/protos/ai/stigmer/agentic/agentshare/v1/spec_pb";
7
+ import type { ResourceRef } from "@stigmer/sdk";
8
+ import { useStigmer } from "../hooks.js";
9
+ import { toError } from "../internal/toError.js";
10
+
11
+ /**
12
+ * Who can chat with a shared agent over its hosted link.
13
+ *
14
+ * - `"public"` — anyone with the link; visitors are anonymous guests.
15
+ * - `"org"` — signed-in members of the owning organization only.
16
+ * Membership is checked on every conversation turn, so access ends the
17
+ * moment a member leaves the org.
18
+ */
19
+ export type SharingAudience = "public" | "org";
20
+
21
+ /**
22
+ * A complete share configuration to persist.
23
+ *
24
+ * Every field is required by design: saving **replaces the share's whole
25
+ * spec**, so a caller must always supply the full configuration. A
26
+ * partial type here would let a toggle change silently wipe
27
+ * `allowedOrigins`, `messages`, `environmentRefs`, or the `audience` —
28
+ * the required shape makes that mistake unrepresentable. (The rotatable
29
+ * link token is exempt: it is server-owned `status`, which survives
30
+ * every save verbatim.)
31
+ */
32
+ export interface AgentShareDraft {
33
+ /** Whether hosted-chat access for the configured audience is enabled. */
34
+ readonly enabled: boolean;
35
+ /** Who can chat: anyone with the link, or org members only. */
36
+ readonly audience: SharingAudience;
37
+ /**
38
+ * Exact web origins allowed to embed the shared agent
39
+ * (e.g. `https://example.com`). Empty list = embeddable anywhere.
40
+ * Embedding is public-audience only.
41
+ */
42
+ readonly allowedOrigins: readonly string[];
43
+ /** Owner-customized visitor refusal copy. Empty strings mean platform defaults. */
44
+ readonly messages: {
45
+ /** Shown when a visitor exceeds the message rate limit. */
46
+ readonly rateLimited: string;
47
+ /** Shown when the org's credits are exhausted (sharing fails closed). */
48
+ readonly unavailable: string;
49
+ /** Shown when a conversation hits its turn limit or inactivity timeout. */
50
+ readonly conversationEnded: string;
51
+ };
52
+ /**
53
+ * Org-shared environments whose values guest conversations receive —
54
+ * how a tool-using agent becomes chattable over a share link without
55
+ * touching its pristine default instance. Public-audience only (the
56
+ * proto CEL rule rejects bindings on org-audience shares, whose member
57
+ * sessions carry no share linkage in Phase A — decision 011 addendum).
58
+ */
59
+ readonly environmentRefs: readonly ResourceRef[];
60
+ }
61
+
62
+ /**
63
+ * Maps a proto {@link AgentShareAudience} to the SDK's string union.
64
+ * Unspecified means public by contract (a share created without an
65
+ * explicit audience is an anyone-with-link share).
66
+ */
67
+ export function sharingAudienceFromProto(
68
+ audience: AgentShareAudience | undefined,
69
+ ): SharingAudience {
70
+ return audience === AgentShareAudience.org ? "org" : "public";
71
+ }
72
+
73
+ function sharingAudienceToProto(audience: SharingAudience): AgentShareAudience {
74
+ return audience === "org"
75
+ ? AgentShareAudience.org
76
+ : AgentShareAudience.public;
77
+ }
78
+
79
+ /** Return value of {@link useSaveAgentShare}. */
80
+ export interface UseSaveAgentShareReturn {
81
+ /**
82
+ * Persist the complete share configuration. Resolves with the
83
+ * persisted {@link AgentShare} — adopt it as the new baseline (its
84
+ * `status.shareLinkToken` carries the live link token).
85
+ *
86
+ * `current` is the share being edited, or `null` when the agent has
87
+ * never been shared — the save then creates the canonical share.
88
+ */
89
+ readonly save: (
90
+ draft: AgentShareDraft,
91
+ current: AgentShare | null,
92
+ ) => Promise<AgentShare | undefined>;
93
+ /** `true` while the RPC is in flight. */
94
+ readonly isPending: boolean;
95
+ /** The last error from the RPC, or `null`. */
96
+ readonly error: Error | null;
97
+ }
98
+
99
+ /**
100
+ * Behavior hook that persists an agent's canonical share configuration.
101
+ *
102
+ * Commits via `stigmer.agentShare.apply()` — an idempotent upsert keyed
103
+ * on the share's `(org, slug)` identity — so one code path serves both
104
+ * the first enable (creates the share; the server authorizes on the
105
+ * referenced agent's `can_edit`) and every later edit. There is
106
+ * deliberately no create/update branching: the share slug is unique per
107
+ * org and defaults to the agent's slug, which makes apply-by-identity
108
+ * exact, and the generated `AgentShareInput` carries no `metadata.id`
109
+ * for an update to route by anyway.
110
+ *
111
+ * Disabling is a save with `enabled: false` — a config-preserving pause
112
+ * (decision 011 D1). Deleting the share is a separate, destructive
113
+ * operation this hook does not perform.
114
+ *
115
+ * Pass `null` for `agent` to produce a stable no-op (useful while the
116
+ * agent is still loading).
117
+ *
118
+ * @example
119
+ * ```tsx
120
+ * const { share } = useAgentShare(agent);
121
+ * const { save, isPending } = useSaveAgentShare(agent);
122
+ *
123
+ * const persisted = await save({ ...draft, enabled: true }, share);
124
+ * // persisted.status.shareLinkToken is the live link token
125
+ * ```
126
+ */
127
+ export function useSaveAgentShare(
128
+ agent: Agent | null,
129
+ ): UseSaveAgentShareReturn {
130
+ const stigmer = useStigmer();
131
+ const [isPending, setIsPending] = useState(false);
132
+ const [error, setError] = useState<Error | null>(null);
133
+
134
+ const agentOrg = agent?.metadata?.org ?? "";
135
+ const agentSlug = agent?.metadata?.slug ?? "";
136
+ const agentName = agent?.metadata?.name ?? "";
137
+
138
+ const save = useCallback(
139
+ async (
140
+ draft: AgentShareDraft,
141
+ current: AgentShare | null,
142
+ ): Promise<AgentShare | undefined> => {
143
+ if (!agentOrg || !agentSlug) return undefined;
144
+
145
+ setIsPending(true);
146
+ setError(null);
147
+
148
+ try {
149
+ return await stigmer.agentShare.apply({
150
+ // Identity: the existing share's org/slug when editing (a
151
+ // manifest-created share may carry a non-default slug — apply
152
+ // with the agent's slug would create a SECOND share), the
153
+ // agent's when creating (the server's own D2 default, made
154
+ // explicit).
155
+ org: current?.metadata?.org || agentOrg,
156
+ slug: current?.metadata?.slug || agentSlug,
157
+ name: current?.metadata?.name || agentName || agentSlug,
158
+ agentRef: { org: agentOrg, slug: agentSlug },
159
+ enabled: draft.enabled,
160
+ // Written as the explicit enum value, never left unspecified —
161
+ // a share persisted as "public" can't be silently downgraded
162
+ // by tooling that relies on the unspecified-means-public rule.
163
+ audience: sharingAudienceToProto(draft.audience),
164
+ allowedOrigins: [...draft.allowedOrigins],
165
+ messages: {
166
+ rateLimited: draft.messages.rateLimited,
167
+ unavailable: draft.messages.unavailable,
168
+ conversationEnded: draft.messages.conversationEnded,
169
+ },
170
+ environmentRefs: draft.environmentRefs.map((ref) => ({
171
+ org: ref.org,
172
+ slug: ref.slug,
173
+ })),
174
+ });
175
+ } catch (err) {
176
+ setError(toError(err));
177
+ throw err;
178
+ } finally {
179
+ setIsPending(false);
180
+ }
181
+ },
182
+ [agentOrg, agentSlug, agentName, stigmer],
183
+ );
184
+
185
+ return { save, isPending, error };
186
+ }
@@ -54,10 +54,11 @@ export interface UseShareAgentReturn {
54
54
  * the running agent (billed to the owning org).
55
55
  *
56
56
  * Owns the open-state and the `can_edit` gate — the same permission the
57
- * `updateSharing` RPC enforces, so the action never appears to a user
58
- * whose changes would be rejected. Returns a `null` action while the
59
- * agent is loading or the user cannot edit, so the host can
60
- * unconditionally fold `action` into its actions array.
57
+ * AgentShare create/apply handlers enforce on the referenced agent, so
58
+ * the action never appears to a user whose changes would be rejected.
59
+ * Returns a `null` action while the agent is loading or the user cannot
60
+ * edit, so the host can unconditionally fold `action` into its actions
61
+ * array.
61
62
  *
62
63
  * @example
63
64
  * ```tsx
@@ -1,106 +1,106 @@
1
1
  "use client";
2
2
 
3
- import { useEffect, useState } from "react";
3
+ import { useEffect, useMemo, useState } from "react";
4
4
  import type { Agent } from "@stigmer/protos/ai/stigmer/agentic/agent/v1/api_pb";
5
5
  import { ApiResourceVisibility } from "@stigmer/protos/ai/stigmer/commons/apiresource/enum_pb";
6
6
  import { useStigmer } from "../hooks.js";
7
7
  import { useDeploymentMode } from "../deployment-mode.js";
8
+ import type { AgentShareDraft } from "./useSaveAgentShare.js";
8
9
 
9
10
  /**
10
- * Readiness of a shared agent's tool credentials for visitor (and
11
- * teammate) executions.
11
+ * Readiness of a share's tool credentials for visitor executions.
12
12
  *
13
- * - `na` — nothing to check: the agent uses no MCP tools, the check is
14
- * disabled, or the deployment cannot serve guest chat (local mode).
13
+ * - `na` — nothing to check: the agent uses no MCP tools, sharing is
14
+ * off, the audience is org (bindings are public-audience only), or
15
+ * the deployment cannot serve guest chat (local mode).
16
+ * - `needs-credentials` — the agent uses MCP tools but the share has no
17
+ * environments bound: visitors' tool calls will fail until the owner
18
+ * binds credentials.
15
19
  * - `checking` — lookups in flight.
16
- * - `ready` — every environment bound to the agent's default instance is
17
- * shared with the organization.
20
+ * - `ready` — every environment bound to the share is shared with the
21
+ * organization.
18
22
  * - `blocked` — one or more bound environments are private; their
19
23
  * `org/slug` references are listed for the hint copy.
20
24
  */
21
25
  export type ShareToolReadiness =
22
26
  | { readonly status: "na" }
27
+ | { readonly status: "needs-credentials" }
23
28
  | { readonly status: "checking" }
24
29
  | { readonly status: "ready" }
25
30
  | { readonly status: "blocked"; readonly privateEnvironments: readonly string[] };
26
31
 
27
32
  const NA: ShareToolReadiness = { status: "na" };
33
+ const NEEDS_CREDENTIALS: ShareToolReadiness = { status: "needs-credentials" };
28
34
 
29
35
  /**
30
36
  * Data hook that checks whether a tool-using shared agent's credentials
31
- * will work for visitors — i.e. whether the environments bound to its
32
- * default instance are shared with the organization (`visibility_org`).
37
+ * will work for visitors — i.e. whether the share binds environments
38
+ * (`environment_refs`) and each one is shared with the organization
39
+ * (`visibility_org`).
33
40
  *
34
- * Guest and teammate executions can only use org-shared environments;
35
- * a private environment's secrets are creator-only and silently
36
- * unavailable to them, so the agent's tools would fail at runtime. This
37
- * hook powers the Share dialog's pre-flight hint, catching the
38
- * misconfiguration at share time instead of at the visitor's first
39
- * message.
41
+ * Guest executions receive credentials exclusively from the share's own
42
+ * `environment_refs`, resolved through the org-shared environment seam
43
+ * (decision 011 the agent's default instance stays pristine and is
44
+ * never consulted). So a tool-using agent with an empty binding list is
45
+ * *guaranteed* broken for visitors, and this hook says so explicitly
46
+ * (`needs-credentials`) instead of staying silent — the gap that made
47
+ * session 12's misconfiguration invisible until a visitor's first
48
+ * message failed.
40
49
  *
41
- * Scope note: environments bound via `environment_refs` are the
42
- * supported credential path for shared agents. Credentials that only
43
- * exist in the owner's personal environment are also invisible to
44
- * guests, but are not detectable from the instance binding the
45
- * runtime's enriched FAILED_PRECONDITION error covers that case.
46
- *
47
- * The check runs only when `enabled` is true, the deployment is cloud
48
- * (local mode has no guest runtime or secret gating), and the agent
49
- * declares MCP server usages. All lookups run as the owner viewing the
50
- * dialog, who can read the bound environments.
50
+ * The check runs only when the share is enabled with a public audience
51
+ * (org-audience shares reject bindings at the proto boundary), the
52
+ * deployment is cloud (local mode has no guest runtime or secret
53
+ * gating), and the agent declares MCP server usages. All lookups run as
54
+ * the owner viewing the dialog, who can read the bound environments.
51
55
  */
52
56
  export function useShareToolReadiness(
53
57
  agent: Agent,
54
- enabled: boolean,
58
+ draft: AgentShareDraft,
55
59
  ): ShareToolReadiness {
56
60
  const stigmer = useStigmer();
57
61
  const deploymentMode = useDeploymentMode();
58
- const [readiness, setReadiness] = useState<ShareToolReadiness>(NA);
62
+ const [checked, setChecked] = useState<ShareToolReadiness>(NA);
59
63
 
60
- const agentId = agent.metadata?.id ?? "";
61
64
  const hasMcpTools = (agent.spec?.mcpServerUsages?.length ?? 0) > 0;
62
- const defaultInstanceId = agent.status?.defaultInstanceId ?? "";
63
-
64
- const shouldCheck =
65
- enabled &&
65
+ const applicable =
66
+ draft.enabled &&
67
+ draft.audience === "public" &&
66
68
  deploymentMode === "cloud" &&
67
- hasMcpTools &&
68
- defaultInstanceId !== "";
69
+ hasMcpTools;
70
+
71
+ // Stable key for the effect: the visibility lookups depend only on
72
+ // which environments are bound, not on the array's identity.
73
+ const refsKey = useMemo(
74
+ () => draft.environmentRefs.map((ref) => `${ref.org}/${ref.slug}`).join(","),
75
+ [draft.environmentRefs],
76
+ );
77
+
78
+ const shouldFetch = applicable && refsKey !== "";
69
79
 
70
80
  useEffect(() => {
71
- if (!shouldCheck) {
72
- setReadiness(NA);
81
+ if (!shouldFetch) {
82
+ setChecked(NA);
73
83
  return;
74
84
  }
75
85
 
76
86
  let cancelled = false;
77
- setReadiness({ status: "checking" });
87
+ setChecked({ status: "checking" });
78
88
 
79
89
  (async (): Promise<ShareToolReadiness> => {
80
- const instance = await stigmer.agentInstance.get(defaultInstanceId);
81
- const refs = instance.spec?.environmentRefs ?? [];
82
- if (refs.length === 0) {
83
- // No bound environments to assess. The tools may need no
84
- // credentials at all — do not warn on a guess.
85
- return NA;
86
- }
87
-
88
90
  const privateRefs: string[] = [];
89
- for (const ref of refs) {
91
+ for (const ref of refsKey.split(",")) {
92
+ const [org, slug] = ref.split("/");
90
93
  try {
91
- const env = await stigmer.environment.getByReference({
92
- org: ref.org,
93
- slug: ref.slug,
94
- });
94
+ const env = await stigmer.environment.getByReference({ org, slug });
95
95
  if (
96
96
  env.metadata?.visibility !== ApiResourceVisibility.visibility_org
97
97
  ) {
98
- privateRefs.push(`${ref.org}/${ref.slug}`);
98
+ privateRefs.push(ref);
99
99
  }
100
100
  } catch {
101
- // Unreadable ref (deleted, foreign): the runtime will skip it
102
- // for visitors too — surface it as blocking.
103
- privateRefs.push(`${ref.org}/${ref.slug}`);
101
+ // Unreadable ref (deleted, foreign): the runtime's merge will
102
+ // skip it for visitors too — surface it as blocking.
103
+ privateRefs.push(ref);
104
104
  }
105
105
  }
106
106
 
@@ -109,21 +109,23 @@ export function useShareToolReadiness(
109
109
  : { status: "blocked", privateEnvironments: privateRefs };
110
110
  })().then(
111
111
  (result) => {
112
- if (!cancelled) setReadiness(result);
112
+ if (!cancelled) setChecked(result);
113
113
  },
114
114
  () => {
115
115
  // The hint is best-effort pre-flight advice — a failed check must
116
116
  // never block the dialog. The runtime error path still diagnoses.
117
- if (!cancelled) setReadiness(NA);
117
+ if (!cancelled) setChecked(NA);
118
118
  },
119
119
  );
120
120
 
121
121
  return () => {
122
122
  cancelled = true;
123
123
  };
124
- // agentId stands in for the agent object identity: the inputs that
125
- // matter (instance id, MCP usage presence) are covered explicitly.
126
- }, [shouldCheck, defaultInstanceId, agentId, stigmer]);
124
+ }, [shouldFetch, refsKey, stigmer]);
127
125
 
128
- return readiness;
126
+ if (!applicable) return NA;
127
+ // Zero bindings needs no lookup: a tool-using agent without bound
128
+ // credentials is broken for visitors by construction.
129
+ if (refsKey === "") return NEEDS_CREDENTIALS;
130
+ return checked;
129
131
  }
@@ -4,11 +4,11 @@ import { create } from "@bufbuild/protobuf";
4
4
  import {
5
5
  GetSharedProfileRequestSchema,
6
6
  type SharedAgentProfile,
7
- } from "@stigmer/protos/ai/stigmer/agentic/agent/v1/io_pb";
7
+ } from "@stigmer/protos/ai/stigmer/agentic/agentshare/v1/io_pb";
8
8
  import { isNotFound } from "@stigmer/sdk";
9
9
  import { useStigmer } from "../hooks.js";
10
10
  import { useFetch } from "../internal/useFetch.js";
11
- import type { SharingAudience } from "./useUpdateAgentSharing.js";
11
+ import type { SharingAudience } from "./useSaveAgentShare.js";
12
12
 
13
13
  /** Options for {@link useSharedAgentProfile}. */
14
14
  export interface UseSharedAgentProfileOptions {
@@ -53,8 +53,9 @@ export interface UseSharedAgentProfileReturn {
53
53
  }
54
54
 
55
55
  /**
56
- * Data hook that fetches a shared agent's public profile by
57
- * organization and agent slug.
56
+ * Data hook that fetches a shared agent's public profile by the org and
57
+ * slug from the share URL (the share's slug — it defaults to the
58
+ * agent's, so existing links resolve unchanged).
58
59
  *
59
60
  * By default this hook calls the `getSharedProfile` endpoint, which is
60
61
  * **public** — it requires no authentication. The server returns a
@@ -110,8 +111,8 @@ export function useSharedAgentProfile(
110
111
  // is gated by live membership, and token-locked public shares
111
112
  // deliberately refuse there (see getSharedProfileForMember).
112
113
  return audience === "org"
113
- ? await stigmer.agent.getSharedProfileForMember({ org, slug })
114
- : await stigmer.agent.getSharedProfile(
114
+ ? await stigmer.agentShare.getSharedProfileForMember({ org, slug })
115
+ : await stigmer.agentShare.getSharedProfile(
115
116
  create(GetSharedProfileRequestSchema, { org, slug, linkToken }),
116
117
  );
117
118
  } catch (err) {