@capybara-hq/plugin-client 0.0.0-stage → 0.1.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,2 @@
1
+ Capybara
2
+ Copyright 2026 Meta-1 (Tianjin Yuanyilian Technology Co., Ltd.)
package/README.md CHANGED
@@ -1,3 +1,22 @@
1
- # Temporary Holding Version
1
+ # @capybara-hq/plugin-client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The client SDK for writing plugin UI for [Capybara](https://github.com/capybara-hq/core), an
4
+ open-source enterprise agent platform. A plugin's client entry (`src/client.tsx`) imports from this
5
+ package: `defineClientExtension`, `defineComponent`, the hooks (`useView`, `useAction`, `useAccess`,
6
+ `useLocale`, `useRunState`, `useCapybaraEvents`, `usePrefersReducedMotion`, `useTheme`,
7
+ `useClientStorage`, `useAssetUrl`) and a versioned subset of the design components (`Button`,
8
+ `Badge`, `Icon`, `KeyValue`, `Kbd`, `Logo`, `Spinner`, `Stack`, `Text`, `Tooltip`,
9
+ `PropertySection`, `ViewBlocks`).
10
+
11
+ ```bash
12
+ npm install @capybara-hq/plugin-client
13
+ ```
14
+
15
+ In the browser the specifier `@capybara-hq/plugin-client` resolves to the host's own implementation
16
+ of this interface (through an import map); `react` is provided by the host too. The package's own
17
+ runtime serves tests and type checking: `@capybara-hq/plugin-client/testing` has
18
+ `renderWithFakeHost(element, { slot, args?, role?, locale?, runState?, view?, onAction?, events? })`,
19
+ which renders a component inside a fake host (jsdom needed).
20
+
21
+ `CLIENT_API_VERSION` (1) is bumped only when a name is removed or its props change; the host
22
+ accepts a bundle built against its own version.
@@ -0,0 +1,51 @@
1
+ import type { ComponentSlotId } from "./slots.generated.js";
2
+ import type { CapybaraEvent, ClientRole, ClientStorage, JsonValue, RunState, UiView } from "./types.js";
3
+ /** Thrown by a hook used outside a component the host rendered. */
4
+ export declare class PluginClientContextError extends Error {
5
+ constructor(hook: string);
6
+ }
7
+ export interface ViewState {
8
+ view: UiView | null;
9
+ status: "loading" | "ready" | "failed";
10
+ retry(): void;
11
+ }
12
+ export type ActionFn = (actionId: string, input?: {
13
+ payload?: JsonValue;
14
+ answer?: Record<string, unknown>;
15
+ }) => Promise<{
16
+ view?: UiView;
17
+ toast?: string;
18
+ }>;
19
+ /**
20
+ * What the host implements per rendered component; the hooks read it, nothing else. The host keeps
21
+ * the functions (`action`, `assetUrl`, `subscribe`) and `storage` referentially stable across
22
+ * renders: `useCapybaraEvents` resubscribes whenever `subscribe` changes.
23
+ */
24
+ export interface HostApi {
25
+ view: ViewState;
26
+ action: ActionFn;
27
+ orgId: string | null;
28
+ role: ClientRole;
29
+ locale: "zh" | "en";
30
+ runState: RunState;
31
+ conversationId: string | null;
32
+ reducedMotion: boolean;
33
+ theme: {
34
+ key: string | null;
35
+ scheme: "dark" | "light";
36
+ };
37
+ storage: ClientStorage;
38
+ assetUrl(path: string): string;
39
+ /** Subscribes to client events; returns the unsubscribe function. */
40
+ subscribe(handler: (e: CapybaraEvent) => void): () => void;
41
+ }
42
+ export interface HostContextValue {
43
+ plugin: string;
44
+ contribution: string;
45
+ slot: ComponentSlotId;
46
+ args: Record<string, unknown>;
47
+ api: HostApi;
48
+ }
49
+ export declare const HostContext: import("react").Context<HostContextValue | null>;
50
+ /** `localStorage` / `sessionStorage` under `cap-ext:<plugin>:`; a blocked store reads as empty. */
51
+ export declare function createPrefixedStorage(plugin: string): ClientStorage;
@@ -0,0 +1,46 @@
1
+ import { createContext } from "react";
2
+ /** Thrown by a hook used outside a component the host rendered. */
3
+ export class PluginClientContextError extends Error {
4
+ constructor(hook) {
5
+ super(`${hook}() can only be used inside a component the Capybara host rendered ` +
6
+ "(a component registered with defineComponent); there is no host context here.");
7
+ this.name = "PluginClientContextError";
8
+ }
9
+ }
10
+ export const HostContext = createContext(null);
11
+ /** `localStorage` / `sessionStorage` under `cap-ext:<plugin>:`; a blocked store reads as empty. */
12
+ export function createPrefixedStorage(plugin) {
13
+ const prefix = `cap-ext:${plugin}:`;
14
+ const store = (scope) => {
15
+ try {
16
+ return scope === "session" ? globalThis.sessionStorage : globalThis.localStorage;
17
+ }
18
+ catch {
19
+ return null;
20
+ }
21
+ };
22
+ return {
23
+ get(key, scope = "local") {
24
+ try {
25
+ return store(scope)?.getItem(prefix + key) ?? null;
26
+ }
27
+ catch {
28
+ return null;
29
+ }
30
+ },
31
+ set(key, value, scope = "local") {
32
+ try {
33
+ const s = store(scope);
34
+ if (!s)
35
+ return;
36
+ if (value === null)
37
+ s.removeItem(prefix + key);
38
+ else
39
+ s.setItem(prefix + key, value);
40
+ }
41
+ catch {
42
+ // a blocked or full store: ignore
43
+ }
44
+ },
45
+ };
46
+ }
@@ -0,0 +1,34 @@
1
+ import type { ComponentType } from "react";
2
+ import type { ComponentSlotId } from "./slots.generated.js";
3
+ import type { BaseComponentProps, CapybaraEventOf, CapybaraEventType, ClientApi, SlotComponentProps } from "./types.js";
4
+ /** Bumped only on an incompatible change of the client API. */
5
+ export declare const CLIENT_API_VERSION = 1;
6
+ export type ComponentProps<S extends ComponentSlotId> = BaseComponentProps & SlotComponentProps[S];
7
+ export interface ClientComponent<S extends ComponentSlotId = ComponentSlotId> {
8
+ readonly slot: S;
9
+ readonly render: ComponentType<ComponentProps<S>>;
10
+ }
11
+ /** Binds a component to the slot it is written for; the host checks it against the manifest. */
12
+ export declare function defineComponent<S extends ComponentSlotId>(slot: S, render: ComponentType<ComponentProps<S>>): ClientComponent<S>;
13
+ export interface ClientExtensionDefinition {
14
+ /** Equals the plugin (and extension) name. */
15
+ name: string;
16
+ /** Keyed by the `component` contribution id of the extension manifest. */
17
+ components?: Record<string, ClientComponent>;
18
+ /** Listeners alive while the extension is loaded. */
19
+ events?: Partial<{
20
+ [K in CapybaraEventType]: (e: CapybaraEventOf<K>, api: ClientApi) => void;
21
+ }>;
22
+ }
23
+ export interface ClientExtension extends ClientExtensionDefinition {
24
+ /**
25
+ * The client API version, stamped by `defineClientExtension`. In a browser that call resolves to
26
+ * the host's own implementation (the import map points `@capybara-hq/plugin-client` at the host),
27
+ * so this is the host's version, not the one the bundle was built against. The real gate is the
28
+ * kernel's: it records the build's version from the package and delivers only builds of the
29
+ * version it supports. The host's comparison is defence in depth.
30
+ */
31
+ readonly apiVersion: number;
32
+ }
33
+ /** The entry module's default export. */
34
+ export declare function defineClientExtension(def: ClientExtensionDefinition): ClientExtension;
package/dist/define.js ADDED
@@ -0,0 +1,10 @@
1
+ /** Bumped only on an incompatible change of the client API. */
2
+ export const CLIENT_API_VERSION = 1;
3
+ /** Binds a component to the slot it is written for; the host checks it against the manifest. */
4
+ export function defineComponent(slot, render) {
5
+ return { slot, render };
6
+ }
7
+ /** The entry module's default export. */
8
+ export function defineClientExtension(def) {
9
+ return { ...def, apiVersion: CLIENT_API_VERSION };
10
+ }
@@ -0,0 +1,102 @@
1
+ import { type ComponentType, type ReactNode } from "react";
2
+ import type { UiView } from "./types.js";
3
+ /** Every design name this package forwards to the host (one source for the package and its tests). */
4
+ export declare const DESIGN_NAMES: readonly ["Badge", "Button", "Icon", "Kbd", "KeyValue", "Logo", "PropertySection", "Spinner", "Stack", "Text", "Tooltip", "ViewBlocks"];
5
+ type HostDesign = Record<string, ComponentType<never>>;
6
+ interface ClientHostGlobal {
7
+ design: HostDesign;
8
+ }
9
+ /** The host's design components (the host sets the global before it loads a client entry). */
10
+ export declare function clientHost(): ClientHostGlobal | undefined;
11
+ export declare function setClientHost(host: ClientHostGlobal | undefined): void;
12
+ export interface ButtonProps {
13
+ variant?: "primary" | "secondary" | "default" | "ghost" | "danger" | "danger-solid";
14
+ loading?: boolean;
15
+ shortcut?: string;
16
+ disabled?: boolean;
17
+ type?: "button" | "submit" | "reset";
18
+ title?: string;
19
+ "aria-label"?: string;
20
+ onClick?: () => void;
21
+ children?: ReactNode;
22
+ }
23
+ export interface BadgeProps {
24
+ tone?: "default" | "accent" | "warn" | "count";
25
+ children?: ReactNode;
26
+ }
27
+ export interface IconProps {
28
+ name: string;
29
+ size?: 16 | 14 | 12;
30
+ label?: string;
31
+ }
32
+ export interface KeyValueProps {
33
+ rows: {
34
+ k: ReactNode;
35
+ v: ReactNode;
36
+ }[];
37
+ keyWidth?: `${number}ch`;
38
+ columns?: 1 | 2;
39
+ }
40
+ export interface KbdProps {
41
+ children?: ReactNode;
42
+ }
43
+ export interface LogoProps {
44
+ scale?: 2 | 3 | 6;
45
+ tone?: "accent" | "muted";
46
+ wordmark?: boolean;
47
+ }
48
+ export interface SpinnerProps {
49
+ label?: string;
50
+ size?: 12 | 16;
51
+ }
52
+ export interface StackProps {
53
+ gap?: 0 | 4 | 8 | 12 | 16 | 24 | 32;
54
+ direction?: "column" | "row";
55
+ align?: "start" | "center" | "end" | "stretch" | "baseline";
56
+ justify?: "start" | "center" | "end" | "between";
57
+ wrap?: boolean;
58
+ children?: ReactNode;
59
+ }
60
+ export interface TextProps {
61
+ variant?: "h1" | "h2" | "h3" | "body" | "small" | "micro" | "prose";
62
+ tone?: "ink" | "muted" | "faint" | "accent" | "ok" | "fail" | "warn";
63
+ truncate?: boolean;
64
+ pre?: boolean;
65
+ icon?: string;
66
+ title?: string;
67
+ children?: ReactNode;
68
+ }
69
+ export interface TooltipProps {
70
+ content: ReactNode;
71
+ side?: "top" | "right" | "bottom" | "left";
72
+ sideOffset?: number;
73
+ children: React.ReactElement;
74
+ }
75
+ export interface PropertySectionProps {
76
+ title: string;
77
+ value?: ReactNode;
78
+ valueTone?: "ink" | "muted";
79
+ state?: "loading" | "ready" | "failed";
80
+ failure?: {
81
+ reason?: string;
82
+ };
83
+ onRetry?(): void;
84
+ children?: ReactNode;
85
+ }
86
+ export interface ViewBlocksProps {
87
+ view: UiView;
88
+ }
89
+ export declare const Button: ComponentType<ButtonProps>;
90
+ export declare const Badge: ComponentType<BadgeProps>;
91
+ export declare const Icon: ComponentType<IconProps>;
92
+ export declare const KeyValue: ComponentType<KeyValueProps>;
93
+ export declare const Kbd: ComponentType<KbdProps>;
94
+ export declare const Logo: ComponentType<LogoProps>;
95
+ export declare const Spinner: ComponentType<SpinnerProps>;
96
+ export declare const Stack: ComponentType<StackProps>;
97
+ export declare const Text: ComponentType<TextProps>;
98
+ export declare const Tooltip: ComponentType<TooltipProps>;
99
+ export declare const PropertySection: ComponentType<PropertySectionProps>;
100
+ /** The host's renderer of a `UiView`. */
101
+ export declare const ViewBlocks: ComponentType<ViewBlocksProps>;
102
+ export {};
package/dist/design.js ADDED
@@ -0,0 +1,49 @@
1
+ import { createElement } from "react";
2
+ /** Every design name this package forwards to the host (one source for the package and its tests). */
3
+ export const DESIGN_NAMES = [
4
+ "Badge",
5
+ "Button",
6
+ "Icon",
7
+ "Kbd",
8
+ "KeyValue",
9
+ "Logo",
10
+ "PropertySection",
11
+ "Spinner",
12
+ "Stack",
13
+ "Text",
14
+ "Tooltip",
15
+ "ViewBlocks",
16
+ ];
17
+ const HOST_KEY = "__CAPYBARA_CLIENT_HOST__";
18
+ /** The host's design components (the host sets the global before it loads a client entry). */
19
+ export function clientHost() {
20
+ return globalThis[HOST_KEY];
21
+ }
22
+ export function setClientHost(host) {
23
+ globalThis[HOST_KEY] = host;
24
+ }
25
+ function forward(name) {
26
+ const Forwarded = (props) => {
27
+ const Target = clientHost()?.design[name];
28
+ if (!Target) {
29
+ throw new Error(`The Capybara client host provides no design component "${name}"; ` +
30
+ "this package only works inside the host or @capybara-hq/plugin-client/testing.");
31
+ }
32
+ return createElement(Target, props);
33
+ };
34
+ Forwarded.displayName = name;
35
+ return Forwarded;
36
+ }
37
+ export const Button = forward("Button");
38
+ export const Badge = forward("Badge");
39
+ export const Icon = forward("Icon");
40
+ export const KeyValue = forward("KeyValue");
41
+ export const Kbd = forward("Kbd");
42
+ export const Logo = forward("Logo");
43
+ export const Spinner = forward("Spinner");
44
+ export const Stack = forward("Stack");
45
+ export const Text = forward("Text");
46
+ export const Tooltip = forward("Tooltip");
47
+ export const PropertySection = forward("PropertySection");
48
+ /** The host's renderer of a `UiView`. */
49
+ export const ViewBlocks = forward("ViewBlocks");
@@ -0,0 +1,3 @@
1
+ import type { CapybaraEventType } from "./types.js";
2
+ /** Every client event name, for hosts and tests. */
3
+ export declare const CAPYBARA_EVENT_TYPES: readonly CapybaraEventType[];
package/dist/events.js ADDED
@@ -0,0 +1,11 @@
1
+ /** Every client event name, for hosts and tests. */
2
+ export const CAPYBARA_EVENT_TYPES = [
3
+ "run.started",
4
+ "run.finished",
5
+ "run.failed",
6
+ "message.sent",
7
+ "message.received",
8
+ "tool.started",
9
+ "tool.finished",
10
+ "approval.requested",
11
+ ];
@@ -0,0 +1,34 @@
1
+ import { type ActionFn, type ViewState } from "./context.js";
2
+ import type { CapybaraEvent, CapybaraEventType, ClientStorage, RunState } from "./types.js";
3
+ /** The view the extension registered under this component's id, refreshed like any view. */
4
+ export declare function useView(): ViewState;
5
+ /** Calls the `ctx.ui.action` registered under this component's id. */
6
+ export declare function useAction(): ActionFn;
7
+ export declare function useAccess(): {
8
+ orgId: string | null;
9
+ role: "owner" | "admin" | "member" | "guest" | "superAdmin";
10
+ atLeast(role: "guest" | "member" | "admin" | "superAdmin"): boolean;
11
+ };
12
+ export declare function useLocale(): {
13
+ locale: "zh" | "en";
14
+ t(text: {
15
+ zh: string;
16
+ en: string;
17
+ }): string;
18
+ };
19
+ /** The open conversation's run state; "idle" on pages without a conversation. */
20
+ export declare function useRunState(): {
21
+ state: RunState;
22
+ conversationId: string | null;
23
+ };
24
+ /** Calls `handler` for each client event; `types` filters. */
25
+ export declare function useCapybaraEvents(handler: (e: CapybaraEvent) => void, types?: readonly CapybaraEventType[]): void;
26
+ export declare function usePrefersReducedMotion(): boolean;
27
+ /** The resolved theme: `key` is "<plugin>/<theme file id>", null = built-in. */
28
+ export declare function useTheme(): {
29
+ key: string | null;
30
+ scheme: "dark" | "light";
31
+ };
32
+ export declare function useClientStorage(): ClientStorage;
33
+ /** URL of a file under dist/client/assets/ of this plugin's build. */
34
+ export declare function useAssetUrl(): (path: string) => string;
package/dist/hooks.js ADDED
@@ -0,0 +1,56 @@
1
+ import { useContext, useEffect, useRef } from "react";
2
+ import { HostContext, PluginClientContextError, } from "./context.js";
3
+ function useHost(hook) {
4
+ const host = useContext(HostContext);
5
+ if (!host)
6
+ throw new PluginClientContextError(hook);
7
+ return host;
8
+ }
9
+ /** The view the extension registered under this component's id, refreshed like any view. */
10
+ export function useView() {
11
+ return useHost("useView").api.view;
12
+ }
13
+ /** Calls the `ctx.ui.action` registered under this component's id. */
14
+ export function useAction() {
15
+ return useHost("useAction").api.action;
16
+ }
17
+ const ROLE_RANK = { guest: 0, member: 1, admin: 2, owner: 2, superAdmin: 3 };
18
+ export function useAccess() {
19
+ const { orgId, role } = useHost("useAccess").api;
20
+ return { orgId, role, atLeast: (min) => ROLE_RANK[role] >= ROLE_RANK[min] };
21
+ }
22
+ export function useLocale() {
23
+ const { locale } = useHost("useLocale").api;
24
+ return { locale, t: (text) => text[locale] };
25
+ }
26
+ /** The open conversation's run state; "idle" on pages without a conversation. */
27
+ export function useRunState() {
28
+ const { runState, conversationId } = useHost("useRunState").api;
29
+ return { state: runState, conversationId };
30
+ }
31
+ /** Calls `handler` for each client event; `types` filters. */
32
+ export function useCapybaraEvents(handler, types) {
33
+ const { api } = useHost("useCapybaraEvents");
34
+ const latest = useRef({ handler, types });
35
+ latest.current = { handler, types };
36
+ const { subscribe } = api;
37
+ useEffect(() => subscribe((e) => {
38
+ const { handler: h, types: t } = latest.current;
39
+ if (!t || t.includes(e.type))
40
+ h(e);
41
+ }), [subscribe]);
42
+ }
43
+ export function usePrefersReducedMotion() {
44
+ return useHost("usePrefersReducedMotion").api.reducedMotion;
45
+ }
46
+ /** The resolved theme: `key` is "<plugin>/<theme file id>", null = built-in. */
47
+ export function useTheme() {
48
+ return useHost("useTheme").api.theme;
49
+ }
50
+ export function useClientStorage() {
51
+ return useHost("useClientStorage").api.storage;
52
+ }
53
+ /** URL of a file under dist/client/assets/ of this plugin's build. */
54
+ export function useAssetUrl() {
55
+ return useHost("useAssetUrl").api.assetUrl;
56
+ }
@@ -0,0 +1,6 @@
1
+ export { type ActionFn, PluginClientContextError, type ViewState } from "./context.js";
2
+ export { CLIENT_API_VERSION, type ClientComponent, type ClientExtension, type ClientExtensionDefinition, type ComponentProps, defineClientExtension, defineComponent, } from "./define.js";
3
+ export { Badge, type BadgeProps, Button, type ButtonProps, Icon, type IconProps, Kbd, type KbdProps, KeyValue, type KeyValueProps, Logo, type LogoProps, PropertySection, type PropertySectionProps, Spinner, type SpinnerProps, Stack, type StackProps, Text, type TextProps, Tooltip, type TooltipProps, ViewBlocks, type ViewBlocksProps, } from "./design.js";
4
+ export { useAccess, useAction, useAssetUrl, useCapybaraEvents, useClientStorage, useLocale, usePrefersReducedMotion, useRunState, useTheme, useView, } from "./hooks.js";
5
+ export type { ComponentSlotId } from "./slots.generated.js";
6
+ export type { BaseComponentProps, CapybaraEvent, CapybaraEventOf, CapybaraEventType, ClientApi, ClientRole, ClientStorage, EventBase, JsonValue, RunState, SlotComponentProps, UiView, } from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { PluginClientContextError } from "./context.js";
2
+ export { CLIENT_API_VERSION, defineClientExtension, defineComponent, } from "./define.js";
3
+ export { Badge, Button, Icon, Kbd, KeyValue, Logo, PropertySection, Spinner, Stack, Text, Tooltip, ViewBlocks, } from "./design.js";
4
+ export { useAccess, useAction, useAssetUrl, useCapybaraEvents, useClientStorage, useLocale, usePrefersReducedMotion, useRunState, useTheme, useView, } from "./hooks.js";
@@ -0,0 +1,3 @@
1
+ /** The slots that accept `component`. */
2
+ export type ComponentSlotId = "conversation.panel" | "conversation.properties.section" | "conversation.tool-result.card" | "org.page" | "agent.detail.section" | "org.settings.section" | "platform.page" | "shell.brand" | "shell.overlay" | "conversation.empty" | "conversation.composer.frame";
3
+ export declare const COMPONENT_SLOT_IDS: readonly ComponentSlotId[];
@@ -0,0 +1,14 @@
1
+ // Generated by pnpm gen:ui-slots from @capybara-hq/plugin-sdk; do not edit.
2
+ export const COMPONENT_SLOT_IDS = [
3
+ "conversation.panel",
4
+ "conversation.properties.section",
5
+ "conversation.tool-result.card",
6
+ "org.page",
7
+ "agent.detail.section",
8
+ "org.settings.section",
9
+ "platform.page",
10
+ "shell.brand",
11
+ "shell.overlay",
12
+ "conversation.empty",
13
+ "conversation.composer.frame",
14
+ ];
@@ -0,0 +1,34 @@
1
+ import { type ReactElement } from "react";
2
+ import { type HostApi } from "../context.js";
3
+ import type { ClientExtension } from "../define.js";
4
+ import type { ComponentSlotId } from "../slots.generated.js";
5
+ import type { CapybaraEvent, ClientRole, RunState, UiView } from "../types.js";
6
+ export interface FakeHostOptions {
7
+ slot: ComponentSlotId;
8
+ /** The slot's render args (`conversationId`, `agentId`, ...). */
9
+ args?: Record<string, unknown>;
10
+ plugin?: string;
11
+ contribution?: string;
12
+ role?: ClientRole;
13
+ orgId?: string | null;
14
+ locale?: "zh" | "en";
15
+ runState?: RunState;
16
+ /** The view `useView` returns. */
17
+ view?: UiView;
18
+ /** Answers `useAction()` calls; default resolves `{}`. */
19
+ onAction?: HostApi["action"];
20
+ /** Listeners of a client extension's `events`, called on `emit` like in the real host. */
21
+ events?: ClientExtension["events"];
22
+ reducedMotion?: boolean;
23
+ }
24
+ export interface FakeHost {
25
+ emit(e: CapybaraEvent): void;
26
+ setRunState(s: RunState): void;
27
+ rerender(): void;
28
+ unmount(): void;
29
+ }
30
+ /**
31
+ * Renders `element` inside a fake host (what the real host provides per component): the slot, the
32
+ * role, the locale, the run state, the view and the design stand-ins. Needs a DOM (jsdom).
33
+ */
34
+ export declare function renderWithFakeHost(element: ReactElement, options: FakeHostOptions): FakeHost;
@@ -0,0 +1,96 @@
1
+ import { act, createElement, useState, } from "react";
2
+ import { createRoot } from "react-dom/client";
3
+ import { createPrefixedStorage, HostContext, } from "../context.js";
4
+ import { clientHost, DESIGN_NAMES, setClientHost } from "../design.js";
5
+ /** Plain stand-ins for the host's design components: `<span data-fake-design="Name">`. */
6
+ function fakeDesign() {
7
+ const out = {};
8
+ for (const name of DESIGN_NAMES) {
9
+ out[name] = ({ children }) => createElement("span", { "data-fake-design": name }, children);
10
+ }
11
+ return out;
12
+ }
13
+ /**
14
+ * Renders `element` inside a fake host (what the real host provides per component): the slot, the
15
+ * role, the locale, the run state, the view and the design stand-ins. Needs a DOM (jsdom).
16
+ */
17
+ export function renderWithFakeHost(element, options) {
18
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true;
19
+ const container = document.createElement("div");
20
+ document.body.appendChild(container);
21
+ const root = createRoot(container);
22
+ const plugin = options.plugin ?? "test-plugin";
23
+ const subscribers = new Set();
24
+ const storage = createPrefixedStorage(plugin);
25
+ const locale = options.locale ?? "en";
26
+ const assetUrl = (path) => `/api/v1/client/${plugin}/test-build/assets/${path}`;
27
+ const clientApi = {
28
+ locale,
29
+ reducedMotion: options.reducedMotion ?? false,
30
+ storage,
31
+ assetUrl,
32
+ };
33
+ const previousHost = clientHost();
34
+ setClientHost({ design: fakeDesign() });
35
+ // Stable across renders, like the real host's (useCapybaraEvents resubscribes on change).
36
+ const subscribe = (handler) => {
37
+ subscribers.add(handler);
38
+ return () => subscribers.delete(handler);
39
+ };
40
+ let setRun = () => { };
41
+ function Provider({ children }) {
42
+ const [runState, setRunState] = useState(options.runState ?? "idle");
43
+ setRun = setRunState;
44
+ const api = {
45
+ view: {
46
+ view: options.view ?? null,
47
+ status: options.view ? "ready" : "loading",
48
+ retry: () => { },
49
+ },
50
+ action: options.onAction ?? (async () => ({})),
51
+ orgId: options.orgId === undefined ? "org_test" : options.orgId,
52
+ role: options.role ?? "member",
53
+ locale,
54
+ runState,
55
+ conversationId: typeof options.args?.conversationId === "string" ? options.args.conversationId : null,
56
+ reducedMotion: clientApi.reducedMotion,
57
+ theme: { key: null, scheme: "dark" },
58
+ storage,
59
+ assetUrl,
60
+ subscribe,
61
+ };
62
+ const value = {
63
+ plugin,
64
+ contribution: options.contribution ?? "test",
65
+ slot: options.slot,
66
+ args: options.args ?? {},
67
+ api,
68
+ };
69
+ return createElement(HostContext.Provider, { value }, children);
70
+ }
71
+ const draw = () => act(() => {
72
+ root.render(createElement(Provider, null, element));
73
+ });
74
+ draw();
75
+ return {
76
+ emit(e) {
77
+ act(() => {
78
+ for (const s of [...subscribers])
79
+ s(e);
80
+ });
81
+ const listener = options.events?.[e.type];
82
+ listener?.(e, clientApi);
83
+ },
84
+ setRunState(s) {
85
+ act(() => setRun(s));
86
+ },
87
+ rerender() {
88
+ draw();
89
+ },
90
+ unmount() {
91
+ act(() => root.unmount());
92
+ container.remove();
93
+ setClientHost(previousHost);
94
+ },
95
+ };
96
+ }
@@ -0,0 +1,116 @@
1
+ import type { ReactNode } from "react";
2
+ /** A JSON value (what `UiView.data` and action payloads carry). */
3
+ export type JsonValue = string | number | boolean | null | JsonValue[] | {
4
+ [key: string]: JsonValue;
5
+ };
6
+ /**
7
+ * A server-rendered extension view (`ctx.ui.view`). The blocks are the SDK's `UiBlock`s; this
8
+ * package imports no SDK, so a block is typed by its `type` only.
9
+ */
10
+ export interface UiView {
11
+ badge?: string;
12
+ open?: unknown;
13
+ blocks: Array<{
14
+ type: string;
15
+ [key: string]: unknown;
16
+ }>;
17
+ /** Only a component's view carries data (at most 32 768 bytes of JSON). */
18
+ data?: JsonValue;
19
+ }
20
+ export type RunState = "idle" | "running" | "waiting" | "failed";
21
+ export type ClientRole = "owner" | "admin" | "member" | "guest" | "superAdmin";
22
+ /** localStorage / sessionStorage under the prefix "cap-ext:<plugin>:"; never throws. */
23
+ export interface ClientStorage {
24
+ get(key: string, scope?: "local" | "session"): string | null;
25
+ set(key: string, value: string | null, scope?: "local" | "session"): void;
26
+ }
27
+ export type CapybaraEventType = "run.started" | "run.finished" | "run.failed" | "message.sent" | "message.received" | "tool.started" | "tool.finished" | "approval.requested";
28
+ export interface EventBase {
29
+ conversationId: string;
30
+ seq: number;
31
+ /** ISO time of the event. */
32
+ at: string;
33
+ }
34
+ export type CapybaraEvent = ({
35
+ type: "run.started";
36
+ } & EventBase) | ({
37
+ type: "run.finished";
38
+ reason: string;
39
+ } & EventBase) | ({
40
+ type: "run.failed";
41
+ code: string;
42
+ } & EventBase) | ({
43
+ type: "message.sent";
44
+ } & EventBase) | ({
45
+ type: "message.received";
46
+ } & EventBase) | ({
47
+ type: "tool.started";
48
+ callId: string;
49
+ tool: string;
50
+ } & EventBase) | ({
51
+ type: "tool.finished";
52
+ callId: string;
53
+ tool: string;
54
+ isError: boolean;
55
+ } & EventBase) | ({
56
+ type: "approval.requested";
57
+ callId: string;
58
+ } & EventBase);
59
+ export type CapybaraEventOf<K extends CapybaraEventType> = Extract<CapybaraEvent, {
60
+ type: K;
61
+ }>;
62
+ /** What `events` listeners get (no React context there). */
63
+ export interface ClientApi {
64
+ locale: "zh" | "en";
65
+ reducedMotion: boolean;
66
+ storage: ClientStorage;
67
+ assetUrl(path: string): string;
68
+ }
69
+ /** Props every component receives, plus its slot's own. */
70
+ export interface BaseComponentProps {
71
+ plugin: string;
72
+ contribution: string;
73
+ slot: import("./slots.generated.js").ComponentSlotId;
74
+ }
75
+ export interface SlotComponentProps {
76
+ "conversation.panel": {
77
+ conversationId: string;
78
+ item?: string;
79
+ close(): void;
80
+ };
81
+ "conversation.properties.section": {
82
+ conversationId: string;
83
+ };
84
+ "conversation.tool-result.card": {
85
+ conversationId: string;
86
+ card: {
87
+ callId: string;
88
+ key?: string;
89
+ };
90
+ };
91
+ "org.page": Record<string, never>;
92
+ "agent.detail.section": {
93
+ agentId: string;
94
+ };
95
+ "org.settings.section": Record<string, never>;
96
+ "platform.page": Record<string, never>;
97
+ "shell.brand": {
98
+ builtin: ReactNode;
99
+ collapsed: boolean;
100
+ };
101
+ "shell.overlay": Record<string, never>;
102
+ "conversation.empty": {
103
+ builtin: ReactNode;
104
+ agentId: string | null;
105
+ greeting: string;
106
+ };
107
+ "conversation.composer.frame": {
108
+ /** The built-in frame with the composer inside. */
109
+ builtin: ReactNode;
110
+ /** The built-in composer inputs, without the frame; render exactly once. */
111
+ children: ReactNode;
112
+ /** null on the new-conversation page. */
113
+ conversationId: string | null;
114
+ runState: RunState;
115
+ };
116
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ export type UiPartName = "shell" | "sidebar" | "sidebar.brand" | "sidebar.item" | "title-bar" | "page-header" | "thread" | "message.user" | "message.assistant" | "tool-row" | "composer" | "properties-panel" | "section" | "right-panel" | "status-bar" | "button" | "button.primary" | "card" | "input" | "dialog";
2
+ /** Every part name plugin CSS and components may rely on. */
3
+ export declare const UI_PART_NAMES: readonly UiPartName[];
@@ -0,0 +1,24 @@
1
+ // Generated by pnpm gen:ui-parts from @capybara-hq/plugin-sdk; do not edit.
2
+ /** Every part name plugin CSS and components may rely on. */
3
+ export const UI_PART_NAMES = [
4
+ "shell",
5
+ "sidebar",
6
+ "sidebar.brand",
7
+ "sidebar.item",
8
+ "title-bar",
9
+ "page-header",
10
+ "thread",
11
+ "message.user",
12
+ "message.assistant",
13
+ "tool-row",
14
+ "composer",
15
+ "properties-panel",
16
+ "section",
17
+ "right-panel",
18
+ "status-bar",
19
+ "button",
20
+ "button.primary",
21
+ "card",
22
+ "input",
23
+ "dialog",
24
+ ];
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@capybara-hq/plugin-client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0-rc.0",
4
+ "description": "Capybara plugin client SDK: the types, hooks and design re-exports a plugin's client entry is written against",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/capybara-hq/core.git",
9
+ "directory": "packages/plugin-client"
10
+ },
11
+ "homepage": "https://github.com/capybara-hq/core/tree/main/packages/plugin-client#readme",
12
+ "type": "module",
13
+ "main": "./dist/index.js",
14
+ "types": "./dist/index.d.ts",
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "import": "./dist/index.js",
19
+ "default": "./dist/index.js"
20
+ },
21
+ "./testing": {
22
+ "types": "./dist/testing/index.d.ts",
23
+ "import": "./dist/testing/index.js",
24
+ "default": "./dist/testing/index.js"
25
+ },
26
+ "./package.json": "./package.json"
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "README.md",
31
+ "NOTICE"
32
+ ],
33
+ "peerDependencies": {
34
+ "react": "^19.3.1",
35
+ "react-dom": "^19.3.1"
36
+ },
37
+ "peerDependenciesMeta": {
38
+ "react-dom": {
39
+ "optional": true
40
+ }
41
+ },
42
+ "devDependencies": {
43
+ "@microsoft/api-extractor": "7.59.4",
44
+ "@testing-library/react": "^16.3.3",
45
+ "@types/react": "^19.3.0",
46
+ "@types/react-dom": "^19.3.0",
47
+ "react": "^19.3.1",
48
+ "react-dom": "^19.3.1"
49
+ },
50
+ "scripts": {
51
+ "build": "tsc -b"
52
+ }
6
53
  }