@agentperf/react 0.1.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 +202 -0
- package/README.md +49 -0
- package/dist/index.cjs +255 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +131 -0
- package/dist/index.d.ts +131 -0
- package/dist/index.js +220 -0
- package/dist/index.js.map +1 -0
- package/package.json +56 -0
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/README.md
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# @agentperf/react
|
|
2
|
+
|
|
3
|
+
**Give your React app a second frontend — for AI agents.** Humans get your DOM;
|
|
4
|
+
agents get a token-budgeted state snapshot and typed, schema-gated actions on
|
|
5
|
+
the WebMCP standard (`document.modelContext`). One codebase, two doorways.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm i @agentperf/react zod
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```tsx
|
|
12
|
+
import { useAgentState, useAgentAction, AgentBoundary } from "@agentperf/react";
|
|
13
|
+
import { z } from "zod";
|
|
14
|
+
|
|
15
|
+
function Cart({ cart }) {
|
|
16
|
+
// agents read this through one get_page_state tool, pruned to a token budget
|
|
17
|
+
useAgentState("cart", cart);
|
|
18
|
+
|
|
19
|
+
// agents act through a schema gate — invalid input never reaches your handler,
|
|
20
|
+
// it gets a refusal naming the exact violated fields so it can self-correct
|
|
21
|
+
useAgentAction("checkout", {
|
|
22
|
+
description: "Pay for the items in the cart",
|
|
23
|
+
input: z.object({ email: z.string().email() }),
|
|
24
|
+
execute: ({ email }) => checkout(email)
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
- **No WebMCP, no problem** — in browsers without `document.modelContext`
|
|
30
|
+
everything no-ops and your app stays a normal human app. Add
|
|
31
|
+
[`@mcp-b/global`](https://github.com/WebMCP-org/npm-packages) as a polyfill
|
|
32
|
+
if you want tools everywhere.
|
|
33
|
+
- **Structured refusals** — validation failures return the violated field
|
|
34
|
+
paths and a fix-and-retry instruction, so agents correct their calls instead
|
|
35
|
+
of corrupting state. Deterministic: same input, same verdict.
|
|
36
|
+
- **Token budgeting** — `get_page_state` prunes long arrays and strings to a
|
|
37
|
+
budget (default 1,000 tokens, `setAgentStateBudget` to change), because
|
|
38
|
+
agents pay per token to read your page.
|
|
39
|
+
- **`AgentBoundary`** scopes state keys and tool names the way your component
|
|
40
|
+
tree scopes the UI.
|
|
41
|
+
- **Read-only/destructive hints** (`readOnly`, `destructive`) map to WebMCP
|
|
42
|
+
annotations; a reserved `price` field is inert today and becomes x402
|
|
43
|
+
settlement in v2 without a breaking change.
|
|
44
|
+
|
|
45
|
+
Works in Chrome 149+ (WebMCP origin trial / `chrome://flags/#enable-webmcp-testing`)
|
|
46
|
+
and the ChatGPT desktop browser. Measure what it saves your agents with
|
|
47
|
+
[the AgentPerf harness](https://github.com/N-45div/AgentPerf).
|
|
48
|
+
|
|
49
|
+
Apache-2.0
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
AgentBoundary: () => AgentBoundary,
|
|
24
|
+
DEFAULT_STATE_BUDGET: () => DEFAULT_STATE_BUDGET,
|
|
25
|
+
estimateTokens: () => estimateTokens,
|
|
26
|
+
serializeBudgeted: () => serializeBudgeted,
|
|
27
|
+
setAgentStateBudget: () => setAgentStateBudget,
|
|
28
|
+
textResult: () => textResult,
|
|
29
|
+
useAgentAction: () => useAgentAction,
|
|
30
|
+
useAgentState: () => useAgentState,
|
|
31
|
+
webmcpSupported: () => webmcpSupported
|
|
32
|
+
});
|
|
33
|
+
module.exports = __toCommonJS(index_exports);
|
|
34
|
+
|
|
35
|
+
// src/boundary.tsx
|
|
36
|
+
var import_react = require("react");
|
|
37
|
+
var import_jsx_runtime = require("react/jsx-runtime");
|
|
38
|
+
var BoundaryContext = (0, import_react.createContext)(null);
|
|
39
|
+
function scopedKey(scope, key, separator) {
|
|
40
|
+
return scope ? `${scope}${separator}${key}` : key;
|
|
41
|
+
}
|
|
42
|
+
function AgentBoundary({ name, children }) {
|
|
43
|
+
const parent = (0, import_react.useContext)(BoundaryContext);
|
|
44
|
+
const scope = parent ? `${parent}.${name}` : name;
|
|
45
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(BoundaryContext.Provider, { value: scope, children });
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// src/state.ts
|
|
49
|
+
var import_react2 = require("react");
|
|
50
|
+
|
|
51
|
+
// src/serialize.ts
|
|
52
|
+
var ELLIPSIS = "\u2026";
|
|
53
|
+
function estimateTokens(text) {
|
|
54
|
+
return Math.ceil(text.length / 4);
|
|
55
|
+
}
|
|
56
|
+
function prune(value, depth, limits) {
|
|
57
|
+
if (value === null || typeof value !== "object") {
|
|
58
|
+
if (typeof value === "string" && value.length > limits.maxStringLength) {
|
|
59
|
+
return value.slice(0, limits.maxStringLength) + ELLIPSIS;
|
|
60
|
+
}
|
|
61
|
+
return value;
|
|
62
|
+
}
|
|
63
|
+
if (depth >= limits.maxDepth) return ELLIPSIS;
|
|
64
|
+
if (Array.isArray(value)) {
|
|
65
|
+
const kept = value.slice(0, limits.maxItems).map((item) => prune(item, depth + 1, limits));
|
|
66
|
+
if (value.length > limits.maxItems) {
|
|
67
|
+
kept.push(`${ELLIPSIS} +${value.length - limits.maxItems} more`);
|
|
68
|
+
}
|
|
69
|
+
return kept;
|
|
70
|
+
}
|
|
71
|
+
const out = {};
|
|
72
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
73
|
+
if (entry === void 0 || typeof entry === "function") continue;
|
|
74
|
+
out[key] = prune(entry, depth + 1, limits);
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
function serializeBudgeted(value, budget) {
|
|
79
|
+
let limits = { maxItems: 20, maxStringLength: 200, maxDepth: 6 };
|
|
80
|
+
for (let pass = 0; pass < 6; pass++) {
|
|
81
|
+
const text = JSON.stringify(prune(value, 0, limits)) ?? "null";
|
|
82
|
+
if (estimateTokens(text) <= budget || limits.maxItems === 1 && limits.maxStringLength <= 25) {
|
|
83
|
+
return text;
|
|
84
|
+
}
|
|
85
|
+
limits = {
|
|
86
|
+
maxItems: Math.max(1, Math.floor(limits.maxItems / 2)),
|
|
87
|
+
maxStringLength: Math.max(25, Math.floor(limits.maxStringLength / 2)),
|
|
88
|
+
maxDepth: Math.max(2, limits.maxDepth - 1)
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
return JSON.stringify(prune(value, 0, limits)) ?? "null";
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// src/types.ts
|
|
95
|
+
function webmcpSupported() {
|
|
96
|
+
return typeof document !== "undefined" && typeof document.modelContext?.registerTool === "function";
|
|
97
|
+
}
|
|
98
|
+
function textResult(text, isError = false) {
|
|
99
|
+
return isError ? { content: [{ type: "text", text }], isError: true } : { content: [{ type: "text", text }] };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// src/state.ts
|
|
103
|
+
var DEFAULT_STATE_BUDGET = 1e3;
|
|
104
|
+
var PageStateStore = class {
|
|
105
|
+
entries = /* @__PURE__ */ new Map();
|
|
106
|
+
controller = null;
|
|
107
|
+
budget = DEFAULT_STATE_BUDGET;
|
|
108
|
+
add(key, entry) {
|
|
109
|
+
this.entries.set(key, entry);
|
|
110
|
+
this.ensureRegistered();
|
|
111
|
+
}
|
|
112
|
+
remove(key) {
|
|
113
|
+
this.entries.delete(key);
|
|
114
|
+
if (this.entries.size === 0 && this.controller) {
|
|
115
|
+
this.controller.abort();
|
|
116
|
+
this.controller = null;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
snapshot() {
|
|
120
|
+
const out = {};
|
|
121
|
+
for (const [key, entry] of this.entries) out[key] = entry.get();
|
|
122
|
+
return out;
|
|
123
|
+
}
|
|
124
|
+
ensureRegistered() {
|
|
125
|
+
if (this.controller || !webmcpSupported()) return;
|
|
126
|
+
const controller = new AbortController();
|
|
127
|
+
this.controller = controller;
|
|
128
|
+
Promise.resolve(
|
|
129
|
+
document.modelContext.registerTool(
|
|
130
|
+
{
|
|
131
|
+
name: "get_page_state",
|
|
132
|
+
description: "Read a live snapshot of this page's application state, as compact JSON. Call this before acting so you work from what the page actually shows, not from a guess. Long values are pruned to stay small; a trailing '\u2026 +N more' marker means an array was elided.",
|
|
133
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
|
134
|
+
annotations: { readOnlyHint: true },
|
|
135
|
+
execute: () => textResult(serializeBudgeted(this.snapshot(), this.budget))
|
|
136
|
+
},
|
|
137
|
+
{ signal: controller.signal }
|
|
138
|
+
)
|
|
139
|
+
).catch(() => {
|
|
140
|
+
if (this.controller === controller) this.controller = null;
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
/** Test-only: forget all slices and drop the registration. */
|
|
144
|
+
resetForTests() {
|
|
145
|
+
this.controller?.abort();
|
|
146
|
+
this.controller = null;
|
|
147
|
+
this.entries.clear();
|
|
148
|
+
this.budget = DEFAULT_STATE_BUDGET;
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
var pageStateStore = new PageStateStore();
|
|
152
|
+
function useAgentState(key, value, options) {
|
|
153
|
+
const scope = (0, import_react2.useContext)(BoundaryContext);
|
|
154
|
+
const fullKey = scopedKey(scope, key, ".");
|
|
155
|
+
const valueRef = (0, import_react2.useRef)(value);
|
|
156
|
+
valueRef.current = value;
|
|
157
|
+
const descriptionRef = (0, import_react2.useRef)(options?.description);
|
|
158
|
+
descriptionRef.current = options?.description;
|
|
159
|
+
(0, import_react2.useEffect)(() => {
|
|
160
|
+
pageStateStore.add(fullKey, {
|
|
161
|
+
get: () => valueRef.current,
|
|
162
|
+
description: descriptionRef.current
|
|
163
|
+
});
|
|
164
|
+
return () => pageStateStore.remove(fullKey);
|
|
165
|
+
}, [fullKey]);
|
|
166
|
+
}
|
|
167
|
+
function setAgentStateBudget(tokens) {
|
|
168
|
+
pageStateStore.budget = tokens;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// src/action.ts
|
|
172
|
+
var import_react3 = require("react");
|
|
173
|
+
var import_zod = require("zod");
|
|
174
|
+
function formatRefusal(toolName, error) {
|
|
175
|
+
const violations = error.issues.map((issue) => {
|
|
176
|
+
const path = issue.path.length > 0 ? issue.path.join(".") : "input";
|
|
177
|
+
return `- ${path}: ${issue.message}`;
|
|
178
|
+
});
|
|
179
|
+
return textResult(
|
|
180
|
+
`REFUSED: invalid input for "${toolName}".
|
|
181
|
+
Violations (${violations.length}):
|
|
182
|
+
${violations.join("\n")}
|
|
183
|
+
|
|
184
|
+
Fix the specific violations above and call the tool again. Validation is deterministic \u2014 the same input always gets the same verdict.`,
|
|
185
|
+
true
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
function toInputSchema(schema) {
|
|
189
|
+
if (!schema) return { type: "object", properties: {}, additionalProperties: false };
|
|
190
|
+
const { $schema: _discard, ...rest } = import_zod.z.toJSONSchema(schema);
|
|
191
|
+
return rest;
|
|
192
|
+
}
|
|
193
|
+
function useAgentAction(name, config) {
|
|
194
|
+
const scope = (0, import_react3.useContext)(BoundaryContext);
|
|
195
|
+
const fullName = scope ? `${scope.replace(/\./g, "_")}_${name}` : name;
|
|
196
|
+
const configRef = (0, import_react3.useRef)(config);
|
|
197
|
+
configRef.current = config;
|
|
198
|
+
const [supported, setSupported] = (0, import_react3.useState)(false);
|
|
199
|
+
(0, import_react3.useEffect)(() => {
|
|
200
|
+
if (!webmcpSupported()) return;
|
|
201
|
+
const controller = new AbortController();
|
|
202
|
+
const registeredWith = configRef.current;
|
|
203
|
+
Promise.resolve(
|
|
204
|
+
document.modelContext.registerTool(
|
|
205
|
+
{
|
|
206
|
+
name: fullName,
|
|
207
|
+
description: registeredWith.description,
|
|
208
|
+
inputSchema: toInputSchema(registeredWith.input),
|
|
209
|
+
annotations: {
|
|
210
|
+
readOnlyHint: registeredWith.readOnly === true,
|
|
211
|
+
...registeredWith.destructive !== void 0 && {
|
|
212
|
+
destructiveHint: registeredWith.destructive
|
|
213
|
+
}
|
|
214
|
+
},
|
|
215
|
+
execute: async (args) => {
|
|
216
|
+
const current = configRef.current;
|
|
217
|
+
let input = args;
|
|
218
|
+
if (current.input) {
|
|
219
|
+
const parsed = current.input.safeParse(args);
|
|
220
|
+
if (!parsed.success) return formatRefusal(fullName, parsed.error);
|
|
221
|
+
input = parsed.data;
|
|
222
|
+
}
|
|
223
|
+
try {
|
|
224
|
+
const out = await current.execute(input);
|
|
225
|
+
if (out === void 0) return textResult("Done.");
|
|
226
|
+
return textResult(typeof out === "string" ? out : JSON.stringify(out));
|
|
227
|
+
} catch (error) {
|
|
228
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
229
|
+
return textResult(`Error in "${fullName}": ${message}`, true);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
},
|
|
233
|
+
{ signal: controller.signal }
|
|
234
|
+
)
|
|
235
|
+
).then(() => {
|
|
236
|
+
if (!controller.signal.aborted) setSupported(true);
|
|
237
|
+
}).catch(() => {
|
|
238
|
+
});
|
|
239
|
+
return () => controller.abort();
|
|
240
|
+
}, [fullName]);
|
|
241
|
+
return { supported, name: fullName };
|
|
242
|
+
}
|
|
243
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
244
|
+
0 && (module.exports = {
|
|
245
|
+
AgentBoundary,
|
|
246
|
+
DEFAULT_STATE_BUDGET,
|
|
247
|
+
estimateTokens,
|
|
248
|
+
serializeBudgeted,
|
|
249
|
+
setAgentStateBudget,
|
|
250
|
+
textResult,
|
|
251
|
+
useAgentAction,
|
|
252
|
+
useAgentState,
|
|
253
|
+
webmcpSupported
|
|
254
|
+
});
|
|
255
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/boundary.tsx","../src/state.ts","../src/serialize.ts","../src/types.ts","../src/action.ts"],"sourcesContent":["export { AgentBoundary, type AgentBoundaryProps } from \"./boundary\";\nexport {\n useAgentState,\n setAgentStateBudget,\n DEFAULT_STATE_BUDGET,\n type AgentStateOptions\n} from \"./state\";\nexport {\n useAgentAction,\n type AgentActionConfig,\n type AgentActionStatus\n} from \"./action\";\nexport { estimateTokens, serializeBudgeted } from \"./serialize\";\nexport {\n webmcpSupported,\n textResult,\n type ToolDefinition,\n type ToolResult,\n type ToolAnnotations,\n type ModelContext\n} from \"./types\";\n","/**\n * Scopes the agent surface the way a component tree scopes the human one.\n * State keys inside a boundary are prefixed `name.key`; action names are\n * prefixed `name_action`. Boundaries nest.\n */\nimport { createContext, useContext, type ReactNode } from \"react\";\n\nexport const BoundaryContext = createContext<string | null>(null);\n\nexport function scopedKey(scope: string | null, key: string, separator: \".\" | \"_\"): string {\n return scope ? `${scope}${separator}${key}` : key;\n}\n\nexport interface AgentBoundaryProps {\n name: string;\n children: ReactNode;\n}\n\nexport function AgentBoundary({ name, children }: AgentBoundaryProps) {\n const parent = useContext(BoundaryContext);\n const scope = parent ? `${parent}.${name}` : name;\n return <BoundaryContext.Provider value={scope}>{children}</BoundaryContext.Provider>;\n}\n","/**\n * Live page state exposed to agents through one `get_page_state` tool.\n *\n * Components declare slices with `useAgentState(key, value)`. The store keeps\n * a getter per key — values are resolved at call time, never at registration\n * time, so re-renders never tear down and re-register the tool. The tool is\n * registered when the first slice mounts and unregistered (via its\n * AbortController) when the last one unmounts, which fires the browser's\n * `toolchange` event so an idle agent learns the surface moved.\n */\nimport { useContext, useEffect, useRef } from \"react\";\nimport { BoundaryContext, scopedKey } from \"./boundary\";\nimport { serializeBudgeted } from \"./serialize\";\nimport { textResult, webmcpSupported } from \"./types\";\n\nexport const DEFAULT_STATE_BUDGET = 1000;\n\ninterface StateEntry {\n description?: string;\n get: () => unknown;\n}\n\nclass PageStateStore {\n private entries = new Map<string, StateEntry>();\n private controller: AbortController | null = null;\n budget = DEFAULT_STATE_BUDGET;\n\n add(key: string, entry: StateEntry): void {\n this.entries.set(key, entry);\n this.ensureRegistered();\n }\n\n remove(key: string): void {\n this.entries.delete(key);\n if (this.entries.size === 0 && this.controller) {\n this.controller.abort();\n this.controller = null;\n }\n }\n\n snapshot(): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of this.entries) out[key] = entry.get();\n return out;\n }\n\n private ensureRegistered(): void {\n if (this.controller || !webmcpSupported()) return;\n const controller = new AbortController();\n this.controller = controller;\n Promise.resolve(\n document.modelContext!.registerTool(\n {\n name: \"get_page_state\",\n description:\n \"Read a live snapshot of this page's application state, as compact JSON. \" +\n \"Call this before acting so you work from what the page actually shows, \" +\n \"not from a guess. Long values are pruned to stay small; a trailing \" +\n \"'… +N more' marker means an array was elided.\",\n inputSchema: { type: \"object\", properties: {}, additionalProperties: false },\n annotations: { readOnlyHint: true },\n execute: () => textResult(serializeBudgeted(this.snapshot(), this.budget))\n },\n { signal: controller.signal }\n )\n ).catch(() => {\n if (this.controller === controller) this.controller = null;\n });\n }\n\n /** Test-only: forget all slices and drop the registration. */\n resetForTests(): void {\n this.controller?.abort();\n this.controller = null;\n this.entries.clear();\n this.budget = DEFAULT_STATE_BUDGET;\n }\n}\n\nexport const pageStateStore = new PageStateStore();\n\nexport interface AgentStateOptions {\n /** What this slice means, for future per-slice docs. */\n description?: string;\n}\n\n/**\n * Expose a slice of live app state to agents under `key`. The current value\n * is captured on every render; agents always read the latest through\n * `get_page_state`. Inside an `<AgentBoundary name=\"cart\">`, `key` becomes\n * `cart.key`.\n */\nexport function useAgentState<T>(key: string, value: T, options?: AgentStateOptions): void {\n const scope = useContext(BoundaryContext);\n const fullKey = scopedKey(scope, key, \".\");\n const valueRef = useRef<T>(value);\n valueRef.current = value;\n const descriptionRef = useRef(options?.description);\n descriptionRef.current = options?.description;\n\n useEffect(() => {\n pageStateStore.add(fullKey, {\n get: () => valueRef.current,\n description: descriptionRef.current\n });\n return () => pageStateStore.remove(fullKey);\n }, [fullKey]);\n}\n\n/** Set the total token budget for the `get_page_state` snapshot. */\nexport function setAgentStateBudget(tokens: number): void {\n pageStateStore.budget = tokens;\n}\n","/**\n * Token-budgeted serialization. Agents pay per token to read state, so the\n * snapshot an agent sees is pruned — long strings truncated, long arrays\n * elided with an explicit marker, depth capped — until it fits the budget.\n * Pruning is deterministic: the same value and budget always produce the\n * same snapshot.\n */\n\nconst ELLIPSIS = \"…\";\n\n/** Rough token estimate (~4 characters per token). */\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\ninterface PruneLimits {\n maxItems: number;\n maxStringLength: number;\n maxDepth: number;\n}\n\nfunction prune(value: unknown, depth: number, limits: PruneLimits): unknown {\n if (value === null || typeof value !== \"object\") {\n if (typeof value === \"string\" && value.length > limits.maxStringLength) {\n return value.slice(0, limits.maxStringLength) + ELLIPSIS;\n }\n return value;\n }\n if (depth >= limits.maxDepth) return ELLIPSIS;\n if (Array.isArray(value)) {\n const kept = value\n .slice(0, limits.maxItems)\n .map((item) => prune(item, depth + 1, limits));\n if (value.length > limits.maxItems) {\n kept.push(`${ELLIPSIS} +${value.length - limits.maxItems} more`);\n }\n return kept;\n }\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n if (entry === undefined || typeof entry === \"function\") continue;\n out[key] = prune(entry, depth + 1, limits);\n }\n return out;\n}\n\n/**\n * Serialize `value` as compact JSON within roughly `budget` tokens.\n * Tightens limits in deterministic steps until the snapshot fits (or the\n * limits bottom out — a pathological value can still exceed a tiny budget).\n */\nexport function serializeBudgeted(value: unknown, budget: number): string {\n let limits: PruneLimits = { maxItems: 20, maxStringLength: 200, maxDepth: 6 };\n for (let pass = 0; pass < 6; pass++) {\n const text = JSON.stringify(prune(value, 0, limits)) ?? \"null\";\n if (estimateTokens(text) <= budget || (limits.maxItems === 1 && limits.maxStringLength <= 25)) {\n return text;\n }\n limits = {\n maxItems: Math.max(1, Math.floor(limits.maxItems / 2)),\n maxStringLength: Math.max(25, Math.floor(limits.maxStringLength / 2)),\n maxDepth: Math.max(2, limits.maxDepth - 1)\n };\n }\n return JSON.stringify(prune(value, 0, limits)) ?? \"null\";\n}\n","/**\n * Minimal typings for the WebMCP browser API.\n *\n * The standard exposes `document.modelContext` (Chrome 149+ origin trial;\n * `navigator.modelContext` was the pre-Chrome-150 spelling and is deprecated).\n * Browsers without the API can get it from a polyfill such as `@mcp-b/global`.\n * Only the surface this library uses is typed.\n */\n\nexport interface ToolTextContent {\n type: \"text\";\n text: string;\n}\n\nexport type ToolContent = ToolTextContent;\n\nexport interface ToolResult {\n content: ToolContent[];\n isError?: boolean;\n}\n\nexport interface ToolAnnotations {\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n untrustedContentHint?: boolean;\n}\n\nexport interface JsonSchemaObject {\n type: \"object\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n [key: string]: unknown;\n}\n\nexport interface ToolDefinition {\n name: string;\n description: string;\n inputSchema?: JsonSchemaObject;\n annotations?: ToolAnnotations;\n execute: (args: Record<string, unknown>) => Promise<ToolResult> | ToolResult;\n}\n\nexport interface RegisterToolOptions {\n /** Aborting this signal unregisters the tool. */\n signal?: AbortSignal;\n /** Origins allowed to see this tool when the page is framed. */\n exposedTo?: string[];\n}\n\nexport interface ModelContext {\n registerTool: (\n tool: ToolDefinition,\n options?: RegisterToolOptions\n ) => Promise<void> | void;\n getTools?: () => Promise<ToolDefinition[]>;\n addEventListener?: EventTarget[\"addEventListener\"];\n}\n\ndeclare global {\n interface Document {\n modelContext?: ModelContext;\n }\n}\n\n/** True when this browser can accept WebMCP tool registrations. */\nexport function webmcpSupported(): boolean {\n return (\n typeof document !== \"undefined\" &&\n typeof document.modelContext?.registerTool === \"function\"\n );\n}\n\n/** Canonical text result — identical shape across agents. */\nexport function textResult(text: string, isError = false): ToolResult {\n return isError\n ? { content: [{ type: \"text\", text }], isError: true }\n : { content: [{ type: \"text\", text }] };\n}\n","/**\n * Schema-gated actions. Every call is validated before your handler runs;\n * invalid input gets a structured refusal naming each violated field, so an\n * agent can fix its call instead of corrupting your state. The gate is\n * deterministic — the same input always gets the same verdict.\n */\nimport { useContext, useEffect, useRef, useState } from \"react\";\nimport { z } from \"zod\";\nimport { BoundaryContext } from \"./boundary\";\nimport {\n textResult,\n webmcpSupported,\n type JsonSchemaObject,\n type ToolResult\n} from \"./types\";\n\nexport interface AgentActionConfig<Schema extends z.ZodType = z.ZodType> {\n /** What this action does, written for the agent deciding whether to call it. */\n description: string;\n /** Input contract. Omit for zero-argument actions. */\n input?: Schema;\n /** True when the action changes nothing — lets agents call it freely. */\n readOnly?: boolean;\n /** True when the action destroys something a person would miss. */\n destructive?: boolean;\n /**\n * Reserved: price per call (e.g. \"$0.001\"). Inert in v1 — declared here so\n * adding x402 settlement later is not a breaking change.\n */\n price?: string;\n /** Runs only after input passes the schema gate. */\n execute: (input: z.infer<Schema>) => Promise<unknown> | unknown;\n}\n\nexport interface AgentActionStatus {\n /** Whether this browser accepts WebMCP registrations. */\n supported: boolean;\n /** The name the tool was published under (boundary prefixes applied). */\n name: string;\n}\n\nfunction formatRefusal(toolName: string, error: z.ZodError): ToolResult {\n const violations = error.issues.map((issue) => {\n const path = issue.path.length > 0 ? issue.path.join(\".\") : \"input\";\n return `- ${path}: ${issue.message}`;\n });\n return textResult(\n `REFUSED: invalid input for \"${toolName}\".\\n` +\n `Violations (${violations.length}):\\n${violations.join(\"\\n\")}\\n\\n` +\n `Fix the specific violations above and call the tool again. ` +\n `Validation is deterministic — the same input always gets the same verdict.`,\n true\n );\n}\n\nfunction toInputSchema(schema: z.ZodType | undefined): JsonSchemaObject {\n if (!schema) return { type: \"object\", properties: {}, additionalProperties: false };\n const { $schema: _discard, ...rest } = z.toJSONSchema(schema) as Record<string, unknown>;\n return rest as JsonSchemaObject;\n}\n\n/**\n * Publish an action as a WebMCP tool for the lifetime of the component.\n * Inside an `<AgentBoundary name=\"cart\">`, `name` becomes `cart_name`.\n * The handler and description are read at call time through a ref, so\n * re-renders never re-register the tool.\n */\nexport function useAgentAction<Schema extends z.ZodType>(\n name: string,\n config: AgentActionConfig<Schema>\n): AgentActionStatus {\n const scope = useContext(BoundaryContext);\n const fullName = scope ? `${scope.replace(/\\./g, \"_\")}_${name}` : name;\n\n const configRef = useRef(config);\n configRef.current = config;\n\n const [supported, setSupported] = useState(false);\n\n useEffect(() => {\n if (!webmcpSupported()) return;\n const controller = new AbortController();\n const registeredWith = configRef.current;\n\n Promise.resolve(\n document.modelContext!.registerTool(\n {\n name: fullName,\n description: registeredWith.description,\n inputSchema: toInputSchema(registeredWith.input),\n annotations: {\n readOnlyHint: registeredWith.readOnly === true,\n ...(registeredWith.destructive !== undefined && {\n destructiveHint: registeredWith.destructive\n })\n },\n execute: async (args) => {\n const current = configRef.current;\n let input: unknown = args;\n if (current.input) {\n const parsed = current.input.safeParse(args);\n if (!parsed.success) return formatRefusal(fullName, parsed.error);\n input = parsed.data;\n }\n try {\n const out = await current.execute(input as z.infer<Schema>);\n if (out === undefined) return textResult(\"Done.\");\n return textResult(typeof out === \"string\" ? out : JSON.stringify(out));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return textResult(`Error in \"${fullName}\": ${message}`, true);\n }\n }\n },\n { signal: controller.signal }\n )\n )\n .then(() => {\n if (!controller.signal.aborted) setSupported(true);\n })\n .catch(() => {\n /* registration failed — tool stays unpublished; page works for humans */\n });\n\n return () => controller.abort();\n }, [fullName]);\n\n return { supported, name: fullName };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKA,mBAA0D;AAgBjD;AAdF,IAAM,sBAAkB,4BAA6B,IAAI;AAEzD,SAAS,UAAU,OAAsB,KAAa,WAA8B;AACzF,SAAO,QAAQ,GAAG,KAAK,GAAG,SAAS,GAAG,GAAG,KAAK;AAChD;AAOO,SAAS,cAAc,EAAE,MAAM,SAAS,GAAuB;AACpE,QAAM,aAAS,yBAAW,eAAe;AACzC,QAAM,QAAQ,SAAS,GAAG,MAAM,IAAI,IAAI,KAAK;AAC7C,SAAO,4CAAC,gBAAgB,UAAhB,EAAyB,OAAO,OAAQ,UAAS;AAC3D;;;ACZA,IAAAA,gBAA8C;;;ACF9C,IAAM,WAAW;AAG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AQ,KAAwB;AAC1D,kBAAI,QAAQ,OAAW,QAAO,WAAW,OAAO;AAChD,qBAAO,WAAW,OAAO,QAAQ,WAAW,MAAM,KAAK,UAAU,GAAG,CAAC;AAAA,YACvE,SAAS,OAAO;AACd,oBAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,qBAAO,WAAW,aAAa,QAAQ,MAAM,OAAO,IAAI,IAAI;AAAA,YAC9D;AAAA,UACF;AAAA,QACF;AAAA,QACA,EAAE,QAAQ,WAAW,OAAO;AAAA,MAC9B;AAAA,IACF,EACG,KAAK,MAAM;AACV,UAAI,CAAC,WAAW,OAAO,QAAS,cAAa,IAAI;AAAA,IACnD,CAAC,EACA,MAAM,MAAM;AAAA,IAEb,CAAC;AAEH,WAAO,MAAM,WAAW,MAAM;AAAA,EAChC,GAAG,CAAC,QAAQ,CAAC;AAEb,SAAO,EAAE,WAAW,MAAM,SAAS;AACrC;","names":["import_react","import_react"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import * as react from 'react';
|
|
2
|
+
import { ReactNode } from 'react';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
|
|
5
|
+
interface AgentBoundaryProps {
|
|
6
|
+
name: string;
|
|
7
|
+
children: ReactNode;
|
|
8
|
+
}
|
|
9
|
+
declare function AgentBoundary({ name, children }: AgentBoundaryProps): react.JSX.Element;
|
|
10
|
+
|
|
11
|
+
declare const DEFAULT_STATE_BUDGET = 1000;
|
|
12
|
+
interface AgentStateOptions {
|
|
13
|
+
/** What this slice means, for future per-slice docs. */
|
|
14
|
+
description?: string;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Expose a slice of live app state to agents under `key`. The current value
|
|
18
|
+
* is captured on every render; agents always read the latest through
|
|
19
|
+
* `get_page_state`. Inside an `<AgentBoundary name="cart">`, `key` becomes
|
|
20
|
+
* `cart.key`.
|
|
21
|
+
*/
|
|
22
|
+
declare function useAgentState<T>(key: string, value: T, options?: AgentStateOptions): void;
|
|
23
|
+
/** Set the total token budget for the `get_page_state` snapshot. */
|
|
24
|
+
declare function setAgentStateBudget(tokens: number): void;
|
|
25
|
+
|
|
26
|
+
interface AgentActionConfig<Schema extends z.ZodType = z.ZodType> {
|
|
27
|
+
/** What this action does, written for the agent deciding whether to call it. */
|
|
28
|
+
description: string;
|
|
29
|
+
/** Input contract. Omit for zero-argument actions. */
|
|
30
|
+
input?: Schema;
|
|
31
|
+
/** True when the action changes nothing — lets agents call it freely. */
|
|
32
|
+
readOnly?: boolean;
|
|
33
|
+
/** True when the action destroys something a person would miss. */
|
|
34
|
+
destructive?: boolean;
|
|
35
|
+
/**
|
|
36
|
+
* Reserved: price per call (e.g. "$0.001"). Inert in v1 — declared here so
|
|
37
|
+
* adding x402 settlement later is not a breaking change.
|
|
38
|
+
*/
|
|
39
|
+
price?: string;
|
|
40
|
+
/** Runs only after input passes the schema gate. */
|
|
41
|
+
execute: (input: z.infer<Schema>) => Promise<unknown> | unknown;
|
|
42
|
+
}
|
|
43
|
+
interface AgentActionStatus {
|
|
44
|
+
/** Whether this browser accepts WebMCP registrations. */
|
|
45
|
+
supported: boolean;
|
|
46
|
+
/** The name the tool was published under (boundary prefixes applied). */
|
|
47
|
+
name: string;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Publish an action as a WebMCP tool for the lifetime of the component.
|
|
51
|
+
* Inside an `<AgentBoundary name="cart">`, `name` becomes `cart_name`.
|
|
52
|
+
* The handler and description are read at call time through a ref, so
|
|
53
|
+
* re-renders never re-register the tool.
|
|
54
|
+
*/
|
|
55
|
+
declare function useAgentAction<Schema extends z.ZodType>(name: string, config: AgentActionConfig<Schema>): AgentActionStatus;
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Token-budgeted serialization. Agents pay per token to read state, so the
|
|
59
|
+
* snapshot an agent sees is pruned — long strings truncated, long arrays
|
|
60
|
+
* elided with an explicit marker, depth capped — until it fits the budget.
|
|
61
|
+
* Pruning is deterministic: the same value and budget always produce the
|
|
62
|
+
* same snapshot.
|
|
63
|
+
*/
|
|
64
|
+
/** Rough token estimate (~4 characters per token). */
|
|
65
|
+
declare function estimateTokens(text: string): number;
|
|
66
|
+
/**
|
|
67
|
+
* Serialize `value` as compact JSON within roughly `budget` tokens.
|
|
68
|
+
* Tightens limits in deterministic steps until the snapshot fits (or the
|
|
69
|
+
* limits bottom out — a pathological value can still exceed a tiny budget).
|
|
70
|
+
*/
|
|
71
|
+
declare function serializeBudgeted(value: unknown, budget: number): string;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Minimal typings for the WebMCP browser API.
|
|
75
|
+
*
|
|
76
|
+
* The standard exposes `document.modelContext` (Chrome 149+ origin trial;
|
|
77
|
+
* `navigator.modelContext` was the pre-Chrome-150 spelling and is deprecated).
|
|
78
|
+
* Browsers without the API can get it from a polyfill such as `@mcp-b/global`.
|
|
79
|
+
* Only the surface this library uses is typed.
|
|
80
|
+
*/
|
|
81
|
+
interface ToolTextContent {
|
|
82
|
+
type: "text";
|
|
83
|
+
text: string;
|
|
84
|
+
}
|
|
85
|
+
type ToolContent = ToolTextContent;
|
|
86
|
+
interface ToolResult {
|
|
87
|
+
content: ToolContent[];
|
|
88
|
+
isError?: boolean;
|
|
89
|
+
}
|
|
90
|
+
interface ToolAnnotations {
|
|
91
|
+
readOnlyHint?: boolean;
|
|
92
|
+
destructiveHint?: boolean;
|
|
93
|
+
idempotentHint?: boolean;
|
|
94
|
+
untrustedContentHint?: boolean;
|
|
95
|
+
}
|
|
96
|
+
interface JsonSchemaObject {
|
|
97
|
+
type: "object";
|
|
98
|
+
properties?: Record<string, unknown>;
|
|
99
|
+
required?: string[];
|
|
100
|
+
additionalProperties?: boolean;
|
|
101
|
+
[key: string]: unknown;
|
|
102
|
+
}
|
|
103
|
+
interface ToolDefinition {
|
|
104
|
+
name: string;
|
|
105
|
+
description: string;
|
|
106
|
+
inputSchema?: JsonSchemaObject;
|
|
107
|
+
annotations?: ToolAnnotations;
|
|
108
|
+
execute: (args: Record<string, unknown>) => Promise<ToolResult> | ToolResult;
|
|
109
|
+
}
|
|
110
|
+
interface RegisterToolOptions {
|
|
111
|
+
/** Aborting this signal unregisters the tool. */
|
|
112
|
+
signal?: AbortSignal;
|
|
113
|
+
/** Origins allowed to see this tool when the page is framed. */
|
|
114
|
+
exposedTo?: string[];
|
|
115
|
+
}
|
|
116
|
+
interface ModelContext {
|
|
117
|
+
registerTool: (tool: ToolDefinition, options?: RegisterToolOptions) => Promise<void> | void;
|
|
118
|
+
getTools?: () => Promise<ToolDefinition[]>;
|
|
119
|
+
addEventListener?: EventTarget["addEventListener"];
|
|
120
|
+
}
|
|
121
|
+
declare global {
|
|
122
|
+
interface Document {
|
|
123
|
+
modelContext?: ModelContext;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
/** True when this browser can accept WebMCP tool registrations. */
|
|
127
|
+
declare function webmcpSupported(): boolean;
|
|
128
|
+
/** Canonical text result — identical shape across agents. */
|
|
129
|
+
declare function textResult(text: string, isError?: boolean): ToolResult;
|
|
130
|
+
|
|
131
|
+
export { type AgentActionConfig, type AgentActionStatus, AgentBoundary, type AgentBoundaryProps, type AgentStateOptions, DEFAULT_STATE_BUDGET, type ModelContext, type ToolAnnotations, type ToolDefinition, type ToolResult, estimateTokens, serializeBudgeted, setAgentStateBudget, textResult, useAgentAction, useAgentState, webmcpSupported };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import * as react from 'react';
|
|
2
|
+
import { ReactNode } from 'react';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
|
|
5
|
+
interface AgentBoundaryProps {
|
|
6
|
+
name: string;
|
|
7
|
+
children: ReactNode;
|
|
8
|
+
}
|
|
9
|
+
declare function AgentBoundary({ name, children }: AgentBoundaryProps): react.JSX.Element;
|
|
10
|
+
|
|
11
|
+
declare const DEFAULT_STATE_BUDGET = 1000;
|
|
12
|
+
interface AgentStateOptions {
|
|
13
|
+
/** What this slice means, for future per-slice docs. */
|
|
14
|
+
description?: string;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Expose a slice of live app state to agents under `key`. The current value
|
|
18
|
+
* is captured on every render; agents always read the latest through
|
|
19
|
+
* `get_page_state`. Inside an `<AgentBoundary name="cart">`, `key` becomes
|
|
20
|
+
* `cart.key`.
|
|
21
|
+
*/
|
|
22
|
+
declare function useAgentState<T>(key: string, value: T, options?: AgentStateOptions): void;
|
|
23
|
+
/** Set the total token budget for the `get_page_state` snapshot. */
|
|
24
|
+
declare function setAgentStateBudget(tokens: number): void;
|
|
25
|
+
|
|
26
|
+
interface AgentActionConfig<Schema extends z.ZodType = z.ZodType> {
|
|
27
|
+
/** What this action does, written for the agent deciding whether to call it. */
|
|
28
|
+
description: string;
|
|
29
|
+
/** Input contract. Omit for zero-argument actions. */
|
|
30
|
+
input?: Schema;
|
|
31
|
+
/** True when the action changes nothing — lets agents call it freely. */
|
|
32
|
+
readOnly?: boolean;
|
|
33
|
+
/** True when the action destroys something a person would miss. */
|
|
34
|
+
destructive?: boolean;
|
|
35
|
+
/**
|
|
36
|
+
* Reserved: price per call (e.g. "$0.001"). Inert in v1 — declared here so
|
|
37
|
+
* adding x402 settlement later is not a breaking change.
|
|
38
|
+
*/
|
|
39
|
+
price?: string;
|
|
40
|
+
/** Runs only after input passes the schema gate. */
|
|
41
|
+
execute: (input: z.infer<Schema>) => Promise<unknown> | unknown;
|
|
42
|
+
}
|
|
43
|
+
interface AgentActionStatus {
|
|
44
|
+
/** Whether this browser accepts WebMCP registrations. */
|
|
45
|
+
supported: boolean;
|
|
46
|
+
/** The name the tool was published under (boundary prefixes applied). */
|
|
47
|
+
name: string;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Publish an action as a WebMCP tool for the lifetime of the component.
|
|
51
|
+
* Inside an `<AgentBoundary name="cart">`, `name` becomes `cart_name`.
|
|
52
|
+
* The handler and description are read at call time through a ref, so
|
|
53
|
+
* re-renders never re-register the tool.
|
|
54
|
+
*/
|
|
55
|
+
declare function useAgentAction<Schema extends z.ZodType>(name: string, config: AgentActionConfig<Schema>): AgentActionStatus;
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Token-budgeted serialization. Agents pay per token to read state, so the
|
|
59
|
+
* snapshot an agent sees is pruned — long strings truncated, long arrays
|
|
60
|
+
* elided with an explicit marker, depth capped — until it fits the budget.
|
|
61
|
+
* Pruning is deterministic: the same value and budget always produce the
|
|
62
|
+
* same snapshot.
|
|
63
|
+
*/
|
|
64
|
+
/** Rough token estimate (~4 characters per token). */
|
|
65
|
+
declare function estimateTokens(text: string): number;
|
|
66
|
+
/**
|
|
67
|
+
* Serialize `value` as compact JSON within roughly `budget` tokens.
|
|
68
|
+
* Tightens limits in deterministic steps until the snapshot fits (or the
|
|
69
|
+
* limits bottom out — a pathological value can still exceed a tiny budget).
|
|
70
|
+
*/
|
|
71
|
+
declare function serializeBudgeted(value: unknown, budget: number): string;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Minimal typings for the WebMCP browser API.
|
|
75
|
+
*
|
|
76
|
+
* The standard exposes `document.modelContext` (Chrome 149+ origin trial;
|
|
77
|
+
* `navigator.modelContext` was the pre-Chrome-150 spelling and is deprecated).
|
|
78
|
+
* Browsers without the API can get it from a polyfill such as `@mcp-b/global`.
|
|
79
|
+
* Only the surface this library uses is typed.
|
|
80
|
+
*/
|
|
81
|
+
interface ToolTextContent {
|
|
82
|
+
type: "text";
|
|
83
|
+
text: string;
|
|
84
|
+
}
|
|
85
|
+
type ToolContent = ToolTextContent;
|
|
86
|
+
interface ToolResult {
|
|
87
|
+
content: ToolContent[];
|
|
88
|
+
isError?: boolean;
|
|
89
|
+
}
|
|
90
|
+
interface ToolAnnotations {
|
|
91
|
+
readOnlyHint?: boolean;
|
|
92
|
+
destructiveHint?: boolean;
|
|
93
|
+
idempotentHint?: boolean;
|
|
94
|
+
untrustedContentHint?: boolean;
|
|
95
|
+
}
|
|
96
|
+
interface JsonSchemaObject {
|
|
97
|
+
type: "object";
|
|
98
|
+
properties?: Record<string, unknown>;
|
|
99
|
+
required?: string[];
|
|
100
|
+
additionalProperties?: boolean;
|
|
101
|
+
[key: string]: unknown;
|
|
102
|
+
}
|
|
103
|
+
interface ToolDefinition {
|
|
104
|
+
name: string;
|
|
105
|
+
description: string;
|
|
106
|
+
inputSchema?: JsonSchemaObject;
|
|
107
|
+
annotations?: ToolAnnotations;
|
|
108
|
+
execute: (args: Record<string, unknown>) => Promise<ToolResult> | ToolResult;
|
|
109
|
+
}
|
|
110
|
+
interface RegisterToolOptions {
|
|
111
|
+
/** Aborting this signal unregisters the tool. */
|
|
112
|
+
signal?: AbortSignal;
|
|
113
|
+
/** Origins allowed to see this tool when the page is framed. */
|
|
114
|
+
exposedTo?: string[];
|
|
115
|
+
}
|
|
116
|
+
interface ModelContext {
|
|
117
|
+
registerTool: (tool: ToolDefinition, options?: RegisterToolOptions) => Promise<void> | void;
|
|
118
|
+
getTools?: () => Promise<ToolDefinition[]>;
|
|
119
|
+
addEventListener?: EventTarget["addEventListener"];
|
|
120
|
+
}
|
|
121
|
+
declare global {
|
|
122
|
+
interface Document {
|
|
123
|
+
modelContext?: ModelContext;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
/** True when this browser can accept WebMCP tool registrations. */
|
|
127
|
+
declare function webmcpSupported(): boolean;
|
|
128
|
+
/** Canonical text result — identical shape across agents. */
|
|
129
|
+
declare function textResult(text: string, isError?: boolean): ToolResult;
|
|
130
|
+
|
|
131
|
+
export { type AgentActionConfig, type AgentActionStatus, AgentBoundary, type AgentBoundaryProps, type AgentStateOptions, DEFAULT_STATE_BUDGET, type ModelContext, type ToolAnnotations, type ToolDefinition, type ToolResult, estimateTokens, serializeBudgeted, setAgentStateBudget, textResult, useAgentAction, useAgentState, webmcpSupported };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
// src/boundary.tsx
|
|
2
|
+
import { createContext, useContext } from "react";
|
|
3
|
+
import { jsx } from "react/jsx-runtime";
|
|
4
|
+
var BoundaryContext = createContext(null);
|
|
5
|
+
function scopedKey(scope, key, separator) {
|
|
6
|
+
return scope ? `${scope}${separator}${key}` : key;
|
|
7
|
+
}
|
|
8
|
+
function AgentBoundary({ name, children }) {
|
|
9
|
+
const parent = useContext(BoundaryContext);
|
|
10
|
+
const scope = parent ? `${parent}.${name}` : name;
|
|
11
|
+
return /* @__PURE__ */ jsx(BoundaryContext.Provider, { value: scope, children });
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// src/state.ts
|
|
15
|
+
import { useContext as useContext2, useEffect, useRef } from "react";
|
|
16
|
+
|
|
17
|
+
// src/serialize.ts
|
|
18
|
+
var ELLIPSIS = "\u2026";
|
|
19
|
+
function estimateTokens(text) {
|
|
20
|
+
return Math.ceil(text.length / 4);
|
|
21
|
+
}
|
|
22
|
+
function prune(value, depth, limits) {
|
|
23
|
+
if (value === null || typeof value !== "object") {
|
|
24
|
+
if (typeof value === "string" && value.length > limits.maxStringLength) {
|
|
25
|
+
return value.slice(0, limits.maxStringLength) + ELLIPSIS;
|
|
26
|
+
}
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
if (depth >= limits.maxDepth) return ELLIPSIS;
|
|
30
|
+
if (Array.isArray(value)) {
|
|
31
|
+
const kept = value.slice(0, limits.maxItems).map((item) => prune(item, depth + 1, limits));
|
|
32
|
+
if (value.length > limits.maxItems) {
|
|
33
|
+
kept.push(`${ELLIPSIS} +${value.length - limits.maxItems} more`);
|
|
34
|
+
}
|
|
35
|
+
return kept;
|
|
36
|
+
}
|
|
37
|
+
const out = {};
|
|
38
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
39
|
+
if (entry === void 0 || typeof entry === "function") continue;
|
|
40
|
+
out[key] = prune(entry, depth + 1, limits);
|
|
41
|
+
}
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
function serializeBudgeted(value, budget) {
|
|
45
|
+
let limits = { maxItems: 20, maxStringLength: 200, maxDepth: 6 };
|
|
46
|
+
for (let pass = 0; pass < 6; pass++) {
|
|
47
|
+
const text = JSON.stringify(prune(value, 0, limits)) ?? "null";
|
|
48
|
+
if (estimateTokens(text) <= budget || limits.maxItems === 1 && limits.maxStringLength <= 25) {
|
|
49
|
+
return text;
|
|
50
|
+
}
|
|
51
|
+
limits = {
|
|
52
|
+
maxItems: Math.max(1, Math.floor(limits.maxItems / 2)),
|
|
53
|
+
maxStringLength: Math.max(25, Math.floor(limits.maxStringLength / 2)),
|
|
54
|
+
maxDepth: Math.max(2, limits.maxDepth - 1)
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
return JSON.stringify(prune(value, 0, limits)) ?? "null";
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// src/types.ts
|
|
61
|
+
function webmcpSupported() {
|
|
62
|
+
return typeof document !== "undefined" && typeof document.modelContext?.registerTool === "function";
|
|
63
|
+
}
|
|
64
|
+
function textResult(text, isError = false) {
|
|
65
|
+
return isError ? { content: [{ type: "text", text }], isError: true } : { content: [{ type: "text", text }] };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// src/state.ts
|
|
69
|
+
var DEFAULT_STATE_BUDGET = 1e3;
|
|
70
|
+
var PageStateStore = class {
|
|
71
|
+
entries = /* @__PURE__ */ new Map();
|
|
72
|
+
controller = null;
|
|
73
|
+
budget = DEFAULT_STATE_BUDGET;
|
|
74
|
+
add(key, entry) {
|
|
75
|
+
this.entries.set(key, entry);
|
|
76
|
+
this.ensureRegistered();
|
|
77
|
+
}
|
|
78
|
+
remove(key) {
|
|
79
|
+
this.entries.delete(key);
|
|
80
|
+
if (this.entries.size === 0 && this.controller) {
|
|
81
|
+
this.controller.abort();
|
|
82
|
+
this.controller = null;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
snapshot() {
|
|
86
|
+
const out = {};
|
|
87
|
+
for (const [key, entry] of this.entries) out[key] = entry.get();
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
ensureRegistered() {
|
|
91
|
+
if (this.controller || !webmcpSupported()) return;
|
|
92
|
+
const controller = new AbortController();
|
|
93
|
+
this.controller = controller;
|
|
94
|
+
Promise.resolve(
|
|
95
|
+
document.modelContext.registerTool(
|
|
96
|
+
{
|
|
97
|
+
name: "get_page_state",
|
|
98
|
+
description: "Read a live snapshot of this page's application state, as compact JSON. Call this before acting so you work from what the page actually shows, not from a guess. Long values are pruned to stay small; a trailing '\u2026 +N more' marker means an array was elided.",
|
|
99
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
|
100
|
+
annotations: { readOnlyHint: true },
|
|
101
|
+
execute: () => textResult(serializeBudgeted(this.snapshot(), this.budget))
|
|
102
|
+
},
|
|
103
|
+
{ signal: controller.signal }
|
|
104
|
+
)
|
|
105
|
+
).catch(() => {
|
|
106
|
+
if (this.controller === controller) this.controller = null;
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
/** Test-only: forget all slices and drop the registration. */
|
|
110
|
+
resetForTests() {
|
|
111
|
+
this.controller?.abort();
|
|
112
|
+
this.controller = null;
|
|
113
|
+
this.entries.clear();
|
|
114
|
+
this.budget = DEFAULT_STATE_BUDGET;
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
var pageStateStore = new PageStateStore();
|
|
118
|
+
function useAgentState(key, value, options) {
|
|
119
|
+
const scope = useContext2(BoundaryContext);
|
|
120
|
+
const fullKey = scopedKey(scope, key, ".");
|
|
121
|
+
const valueRef = useRef(value);
|
|
122
|
+
valueRef.current = value;
|
|
123
|
+
const descriptionRef = useRef(options?.description);
|
|
124
|
+
descriptionRef.current = options?.description;
|
|
125
|
+
useEffect(() => {
|
|
126
|
+
pageStateStore.add(fullKey, {
|
|
127
|
+
get: () => valueRef.current,
|
|
128
|
+
description: descriptionRef.current
|
|
129
|
+
});
|
|
130
|
+
return () => pageStateStore.remove(fullKey);
|
|
131
|
+
}, [fullKey]);
|
|
132
|
+
}
|
|
133
|
+
function setAgentStateBudget(tokens) {
|
|
134
|
+
pageStateStore.budget = tokens;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// src/action.ts
|
|
138
|
+
import { useContext as useContext3, useEffect as useEffect2, useRef as useRef2, useState } from "react";
|
|
139
|
+
import { z } from "zod";
|
|
140
|
+
function formatRefusal(toolName, error) {
|
|
141
|
+
const violations = error.issues.map((issue) => {
|
|
142
|
+
const path = issue.path.length > 0 ? issue.path.join(".") : "input";
|
|
143
|
+
return `- ${path}: ${issue.message}`;
|
|
144
|
+
});
|
|
145
|
+
return textResult(
|
|
146
|
+
`REFUSED: invalid input for "${toolName}".
|
|
147
|
+
Violations (${violations.length}):
|
|
148
|
+
${violations.join("\n")}
|
|
149
|
+
|
|
150
|
+
Fix the specific violations above and call the tool again. Validation is deterministic \u2014 the same input always gets the same verdict.`,
|
|
151
|
+
true
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
function toInputSchema(schema) {
|
|
155
|
+
if (!schema) return { type: "object", properties: {}, additionalProperties: false };
|
|
156
|
+
const { $schema: _discard, ...rest } = z.toJSONSchema(schema);
|
|
157
|
+
return rest;
|
|
158
|
+
}
|
|
159
|
+
function useAgentAction(name, config) {
|
|
160
|
+
const scope = useContext3(BoundaryContext);
|
|
161
|
+
const fullName = scope ? `${scope.replace(/\./g, "_")}_${name}` : name;
|
|
162
|
+
const configRef = useRef2(config);
|
|
163
|
+
configRef.current = config;
|
|
164
|
+
const [supported, setSupported] = useState(false);
|
|
165
|
+
useEffect2(() => {
|
|
166
|
+
if (!webmcpSupported()) return;
|
|
167
|
+
const controller = new AbortController();
|
|
168
|
+
const registeredWith = configRef.current;
|
|
169
|
+
Promise.resolve(
|
|
170
|
+
document.modelContext.registerTool(
|
|
171
|
+
{
|
|
172
|
+
name: fullName,
|
|
173
|
+
description: registeredWith.description,
|
|
174
|
+
inputSchema: toInputSchema(registeredWith.input),
|
|
175
|
+
annotations: {
|
|
176
|
+
readOnlyHint: registeredWith.readOnly === true,
|
|
177
|
+
...registeredWith.destructive !== void 0 && {
|
|
178
|
+
destructiveHint: registeredWith.destructive
|
|
179
|
+
}
|
|
180
|
+
},
|
|
181
|
+
execute: async (args) => {
|
|
182
|
+
const current = configRef.current;
|
|
183
|
+
let input = args;
|
|
184
|
+
if (current.input) {
|
|
185
|
+
const parsed = current.input.safeParse(args);
|
|
186
|
+
if (!parsed.success) return formatRefusal(fullName, parsed.error);
|
|
187
|
+
input = parsed.data;
|
|
188
|
+
}
|
|
189
|
+
try {
|
|
190
|
+
const out = await current.execute(input);
|
|
191
|
+
if (out === void 0) return textResult("Done.");
|
|
192
|
+
return textResult(typeof out === "string" ? out : JSON.stringify(out));
|
|
193
|
+
} catch (error) {
|
|
194
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
195
|
+
return textResult(`Error in "${fullName}": ${message}`, true);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
},
|
|
199
|
+
{ signal: controller.signal }
|
|
200
|
+
)
|
|
201
|
+
).then(() => {
|
|
202
|
+
if (!controller.signal.aborted) setSupported(true);
|
|
203
|
+
}).catch(() => {
|
|
204
|
+
});
|
|
205
|
+
return () => controller.abort();
|
|
206
|
+
}, [fullName]);
|
|
207
|
+
return { supported, name: fullName };
|
|
208
|
+
}
|
|
209
|
+
export {
|
|
210
|
+
AgentBoundary,
|
|
211
|
+
DEFAULT_STATE_BUDGET,
|
|
212
|
+
estimateTokens,
|
|
213
|
+
serializeBudgeted,
|
|
214
|
+
setAgentStateBudget,
|
|
215
|
+
textResult,
|
|
216
|
+
useAgentAction,
|
|
217
|
+
useAgentState,
|
|
218
|
+
webmcpSupported
|
|
219
|
+
};
|
|
220
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/boundary.tsx","../src/state.ts","../src/serialize.ts","../src/types.ts","../src/action.ts"],"sourcesContent":["/**\n * Scopes the agent surface the way a component tree scopes the human one.\n * State keys inside a boundary are prefixed `name.key`; action names are\n * prefixed `name_action`. Boundaries nest.\n */\nimport { createContext, useContext, type ReactNode } from \"react\";\n\nexport const BoundaryContext = createContext<string | null>(null);\n\nexport function scopedKey(scope: string | null, key: string, separator: \".\" | \"_\"): string {\n return scope ? `${scope}${separator}${key}` : key;\n}\n\nexport interface AgentBoundaryProps {\n name: string;\n children: ReactNode;\n}\n\nexport function AgentBoundary({ name, children }: AgentBoundaryProps) {\n const parent = useContext(BoundaryContext);\n const scope = parent ? `${parent}.${name}` : name;\n return <BoundaryContext.Provider value={scope}>{children}</BoundaryContext.Provider>;\n}\n","/**\n * Live page state exposed to agents through one `get_page_state` tool.\n *\n * Components declare slices with `useAgentState(key, value)`. The store keeps\n * a getter per key — values are resolved at call time, never at registration\n * time, so re-renders never tear down and re-register the tool. The tool is\n * registered when the first slice mounts and unregistered (via its\n * AbortController) when the last one unmounts, which fires the browser's\n * `toolchange` event so an idle agent learns the surface moved.\n */\nimport { useContext, useEffect, useRef } from \"react\";\nimport { BoundaryContext, scopedKey } from \"./boundary\";\nimport { serializeBudgeted } from \"./serialize\";\nimport { textResult, webmcpSupported } from \"./types\";\n\nexport const DEFAULT_STATE_BUDGET = 1000;\n\ninterface StateEntry {\n description?: string;\n get: () => unknown;\n}\n\nclass PageStateStore {\n private entries = new Map<string, StateEntry>();\n private controller: AbortController | null = null;\n budget = DEFAULT_STATE_BUDGET;\n\n add(key: string, entry: StateEntry): void {\n this.entries.set(key, entry);\n this.ensureRegistered();\n }\n\n remove(key: string): void {\n this.entries.delete(key);\n if (this.entries.size === 0 && this.controller) {\n this.controller.abort();\n this.controller = null;\n }\n }\n\n snapshot(): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of this.entries) out[key] = entry.get();\n return out;\n }\n\n private ensureRegistered(): void {\n if (this.controller || !webmcpSupported()) return;\n const controller = new AbortController();\n this.controller = controller;\n Promise.resolve(\n document.modelContext!.registerTool(\n {\n name: \"get_page_state\",\n description:\n \"Read a live snapshot of this page's application state, as compact JSON. \" +\n \"Call this before acting so you work from what the page actually shows, \" +\n \"not from a guess. Long values are pruned to stay small; a trailing \" +\n \"'… +N more' marker means an array was elided.\",\n inputSchema: { type: \"object\", properties: {}, additionalProperties: false },\n annotations: { readOnlyHint: true },\n execute: () => textResult(serializeBudgeted(this.snapshot(), this.budget))\n },\n { signal: controller.signal }\n )\n ).catch(() => {\n if (this.controller === controller) this.controller = null;\n });\n }\n\n /** Test-only: forget all slices and drop the registration. */\n resetForTests(): void {\n this.controller?.abort();\n this.controller = null;\n this.entries.clear();\n this.budget = DEFAULT_STATE_BUDGET;\n }\n}\n\nexport const pageStateStore = new PageStateStore();\n\nexport interface AgentStateOptions {\n /** What this slice means, for future per-slice docs. */\n description?: string;\n}\n\n/**\n * Expose a slice of live app state to agents under `key`. The current value\n * is captured on every render; agents always read the latest through\n * `get_page_state`. Inside an `<AgentBoundary name=\"cart\">`, `key` becomes\n * `cart.key`.\n */\nexport function useAgentState<T>(key: string, value: T, options?: AgentStateOptions): void {\n const scope = useContext(BoundaryContext);\n const fullKey = scopedKey(scope, key, \".\");\n const valueRef = useRef<T>(value);\n valueRef.current = value;\n const descriptionRef = useRef(options?.description);\n descriptionRef.current = options?.description;\n\n useEffect(() => {\n pageStateStore.add(fullKey, {\n get: () => valueRef.current,\n description: descriptionRef.current\n });\n return () => pageStateStore.remove(fullKey);\n }, [fullKey]);\n}\n\n/** Set the total token budget for the `get_page_state` snapshot. */\nexport function setAgentStateBudget(tokens: number): void {\n pageStateStore.budget = tokens;\n}\n","/**\n * Token-budgeted serialization. Agents pay per token to read state, so the\n * snapshot an agent sees is pruned — long strings truncated, long arrays\n * elided with an explicit marker, depth capped — until it fits the budget.\n * Pruning is deterministic: the same value and budget always produce the\n * same snapshot.\n */\n\nconst ELLIPSIS = \"…\";\n\n/** Rough token estimate (~4 characters per token). */\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\ninterface PruneLimits {\n maxItems: number;\n maxStringLength: number;\n maxDepth: number;\n}\n\nfunction prune(value: unknown, depth: number, limits: PruneLimits): unknown {\n if (value === null || typeof value !== \"object\") {\n if (typeof value === \"string\" && value.length > limits.maxStringLength) {\n return value.slice(0, limits.maxStringLength) + ELLIPSIS;\n }\n return value;\n }\n if (depth >= limits.maxDepth) return ELLIPSIS;\n if (Array.isArray(value)) {\n const kept = value\n .slice(0, limits.maxItems)\n .map((item) => prune(item, depth + 1, limits));\n if (value.length > limits.maxItems) {\n kept.push(`${ELLIPSIS} +${value.length - limits.maxItems} more`);\n }\n return kept;\n }\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n if (entry === undefined || typeof entry === \"function\") continue;\n out[key] = prune(entry, depth + 1, limits);\n }\n return out;\n}\n\n/**\n * Serialize `value` as compact JSON within roughly `budget` tokens.\n * Tightens limits in deterministic steps until the snapshot fits (or the\n * limits bottom out — a pathological value can still exceed a tiny budget).\n */\nexport function serializeBudgeted(value: unknown, budget: number): string {\n let limits: PruneLimits = { maxItems: 20, maxStringLength: 200, maxDepth: 6 };\n for (let pass = 0; pass < 6; pass++) {\n const text = JSON.stringify(prune(value, 0, limits)) ?? \"null\";\n if (estimateTokens(text) <= budget || (limits.maxItems === 1 && limits.maxStringLength <= 25)) {\n return text;\n }\n limits = {\n maxItems: Math.max(1, Math.floor(limits.maxItems / 2)),\n maxStringLength: Math.max(25, Math.floor(limits.maxStringLength / 2)),\n maxDepth: Math.max(2, limits.maxDepth - 1)\n };\n }\n return JSON.stringify(prune(value, 0, limits)) ?? \"null\";\n}\n","/**\n * Minimal typings for the WebMCP browser API.\n *\n * The standard exposes `document.modelContext` (Chrome 149+ origin trial;\n * `navigator.modelContext` was the pre-Chrome-150 spelling and is deprecated).\n * Browsers without the API can get it from a polyfill such as `@mcp-b/global`.\n * Only the surface this library uses is typed.\n */\n\nexport interface ToolTextContent {\n type: \"text\";\n text: string;\n}\n\nexport type ToolContent = ToolTextContent;\n\nexport interface ToolResult {\n content: ToolContent[];\n isError?: boolean;\n}\n\nexport interface ToolAnnotations {\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n untrustedContentHint?: boolean;\n}\n\nexport interface JsonSchemaObject {\n type: \"object\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n [key: string]: unknown;\n}\n\nexport interface ToolDefinition {\n name: string;\n description: string;\n inputSchema?: JsonSchemaObject;\n annotations?: ToolAnnotations;\n execute: (args: Record<string, unknown>) => Promise<ToolResult> | ToolResult;\n}\n\nexport interface RegisterToolOptions {\n /** Aborting this signal unregisters the tool. */\n signal?: AbortSignal;\n /** Origins allowed to see this tool when the page is framed. */\n exposedTo?: string[];\n}\n\nexport interface ModelContext {\n registerTool: (\n tool: ToolDefinition,\n options?: RegisterToolOptions\n ) => Promise<void> | void;\n getTools?: () => Promise<ToolDefinition[]>;\n addEventListener?: EventTarget[\"addEventListener\"];\n}\n\ndeclare global {\n interface Document {\n modelContext?: ModelContext;\n }\n}\n\n/** True when this browser can accept WebMCP tool registrations. */\nexport function webmcpSupported(): boolean {\n return (\n typeof document !== \"undefined\" &&\n typeof document.modelContext?.registerTool === \"function\"\n );\n}\n\n/** Canonical text result — identical shape across agents. */\nexport function textResult(text: string, isError = false): ToolResult {\n return isError\n ? { content: [{ type: \"text\", text }], isError: true }\n : { content: [{ type: \"text\", text }] };\n}\n","/**\n * Schema-gated actions. Every call is validated before your handler runs;\n * invalid input gets a structured refusal naming each violated field, so an\n * agent can fix its call instead of corrupting your state. The gate is\n * deterministic — the same input always gets the same verdict.\n */\nimport { useContext, useEffect, useRef, useState } from \"react\";\nimport { z } from \"zod\";\nimport { BoundaryContext } from \"./boundary\";\nimport {\n textResult,\n webmcpSupported,\n type JsonSchemaObject,\n type ToolResult\n} from \"./types\";\n\nexport interface AgentActionConfig<Schema extends z.ZodType = z.ZodType> {\n /** What this action does, written for the agent deciding whether to call it. */\n description: string;\n /** Input contract. Omit for zero-argument actions. */\n input?: Schema;\n /** True when the action changes nothing — lets agents call it freely. */\n readOnly?: boolean;\n /** True when the action destroys something a person would miss. */\n destructive?: boolean;\n /**\n * Reserved: price per call (e.g. \"$0.001\"). Inert in v1 — declared here so\n * adding x402 settlement later is not a breaking change.\n */\n price?: string;\n /** Runs only after input passes the schema gate. */\n execute: (input: z.infer<Schema>) => Promise<unknown> | unknown;\n}\n\nexport interface AgentActionStatus {\n /** Whether this browser accepts WebMCP registrations. */\n supported: boolean;\n /** The name the tool was published under (boundary prefixes applied). */\n name: string;\n}\n\nfunction formatRefusal(toolName: string, error: z.ZodError): ToolResult {\n const violations = error.issues.map((issue) => {\n const path = issue.path.length > 0 ? issue.path.join(\".\") : \"input\";\n return `- ${path}: ${issue.message}`;\n });\n return textResult(\n `REFUSED: invalid input for \"${toolName}\".\\n` +\n `Violations (${violations.length}):\\n${violations.join(\"\\n\")}\\n\\n` +\n `Fix the specific violations above and call the tool again. ` +\n `Validation is deterministic — the same input always gets the same verdict.`,\n true\n );\n}\n\nfunction toInputSchema(schema: z.ZodType | undefined): JsonSchemaObject {\n if (!schema) return { type: \"object\", properties: {}, additionalProperties: false };\n const { $schema: _discard, ...rest } = z.toJSONSchema(schema) as Record<string, unknown>;\n return rest as JsonSchemaObject;\n}\n\n/**\n * Publish an action as a WebMCP tool for the lifetime of the component.\n * Inside an `<AgentBoundary name=\"cart\">`, `name` becomes `cart_name`.\n * The handler and description are read at call time through a ref, so\n * re-renders never re-register the tool.\n */\nexport function useAgentAction<Schema extends z.ZodType>(\n name: string,\n config: AgentActionConfig<Schema>\n): AgentActionStatus {\n const scope = useContext(BoundaryContext);\n const fullName = scope ? `${scope.replace(/\\./g, \"_\")}_${name}` : name;\n\n const configRef = useRef(config);\n configRef.current = config;\n\n const [supported, setSupported] = useState(false);\n\n useEffect(() => {\n if (!webmcpSupported()) return;\n const controller = new AbortController();\n const registeredWith = configRef.current;\n\n Promise.resolve(\n document.modelContext!.registerTool(\n {\n name: fullName,\n description: registeredWith.description,\n inputSchema: toInputSchema(registeredWith.input),\n annotations: {\n readOnlyHint: registeredWith.readOnly === true,\n ...(registeredWith.destructive !== undefined && {\n destructiveHint: registeredWith.destructive\n })\n },\n execute: async (args) => {\n const current = configRef.current;\n let input: unknown = args;\n if (current.input) {\n const parsed = current.input.safeParse(args);\n if (!parsed.success) return formatRefusal(fullName, parsed.error);\n input = parsed.data;\n }\n try {\n const out = await current.execute(input as z.infer<Schema>);\n if (out === undefined) return textResult(\"Done.\");\n return textResult(typeof out === \"string\" ? out : JSON.stringify(out));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return textResult(`Error in \"${fullName}\": ${message}`, true);\n }\n }\n },\n { signal: controller.signal }\n )\n )\n .then(() => {\n if (!controller.signal.aborted) setSupported(true);\n })\n .catch(() => {\n /* registration failed — tool stays unpublished; page works for humans */\n });\n\n return () => controller.abort();\n }, [fullName]);\n\n return { supported, name: fullName };\n}\n"],"mappings":";AAKA,SAAS,eAAe,kBAAkC;AAgBjD;AAdF,IAAM,kBAAkB,cAA6B,IAAI;AAEzD,SAAS,UAAU,OAAsB,KAAa,WAA8B;AACzF,SAAO,QAAQ,GAAG,KAAK,GAAG,SAAS,GAAG,GAAG,KAAK;AAChD;AAOO,SAAS,cAAc,EAAE,MAAM,SAAS,GAAuB;AACpE,QAAM,SAAS,WAAW,eAAe;AACzC,QAAM,QAAQ,SAAS,GAAG,MAAM,IAAI,IAAI,KAAK;AAC7C,SAAO,oBAAC,gBAAgB,UAAhB,EAAyB,OAAO,OAAQ,UAAS;AAC3D;;;ACZA,SAAS,cAAAA,aAAY,WAAW,cAAc;;;ACF9C,IAAM,WAAW;AAGV,SAAS,eAAe,MAAsB;AACnD,SAAO,KAAK,KAAK,KAAK,SAAS,CAAC;AAClC;AAQA,SAAS,MAAM,OAAgB,OAAe,QAA8B;AAC1E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AW,OAAO,QAAQ,WAAW,MAAM,KAAK,UAAU,GAAG,CAAC;AAAA,YACvE,SAAS,OAAO;AACd,oBAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,qBAAO,WAAW,aAAa,QAAQ,MAAM,OAAO,IAAI,IAAI;AAAA,YAC9D;AAAA,UACF;AAAA,QACF;AAAA,QACA,EAAE,QAAQ,WAAW,OAAO;AAAA,MAC9B;AAAA,IACF,EACG,KAAK,MAAM;AACV,UAAI,CAAC,WAAW,OAAO,QAAS,cAAa,IAAI;AAAA,IACnD,CAAC,EACA,MAAM,MAAM;AAAA,IAEb,CAAC;AAEH,WAAO,MAAM,WAAW,MAAM;AAAA,EAChC,GAAG,CAAC,QAAQ,CAAC;AAEb,SAAO,EAAE,WAAW,MAAM,SAAS;AACrC;","names":["useContext","useContext","useContext","useEffect","useRef","useContext","useRef","useEffect"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@agentperf/react",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Give your React app a fast lane for AI agents: token-budgeted state snapshots and schema-gated actions on the WebMCP standard (document.modelContext).",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/N-45div/AgentPerf.git",
|
|
9
|
+
"directory": "packages/react"
|
|
10
|
+
},
|
|
11
|
+
"keywords": [
|
|
12
|
+
"webmcp",
|
|
13
|
+
"mcp",
|
|
14
|
+
"agents",
|
|
15
|
+
"react",
|
|
16
|
+
"modelcontext",
|
|
17
|
+
"agentperf"
|
|
18
|
+
],
|
|
19
|
+
"type": "module",
|
|
20
|
+
"main": "./dist/index.cjs",
|
|
21
|
+
"module": "./dist/index.js",
|
|
22
|
+
"types": "./dist/index.d.ts",
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"import": "./dist/index.js",
|
|
27
|
+
"require": "./dist/index.cjs"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"dist",
|
|
32
|
+
"README.md"
|
|
33
|
+
],
|
|
34
|
+
"sideEffects": false,
|
|
35
|
+
"peerDependencies": {
|
|
36
|
+
"react": ">=18",
|
|
37
|
+
"zod": "^4.0.0"
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@testing-library/dom": "^10.4.0",
|
|
41
|
+
"@testing-library/react": "^16.1.0",
|
|
42
|
+
"@types/react": "^19.0.0",
|
|
43
|
+
"jsdom": "^25.0.0",
|
|
44
|
+
"react": "^19.0.0",
|
|
45
|
+
"react-dom": "^19.0.0",
|
|
46
|
+
"tsup": "^8.3.0",
|
|
47
|
+
"typescript": "^5.7.0",
|
|
48
|
+
"vitest": "^3.0.0",
|
|
49
|
+
"zod": "^4.0.0"
|
|
50
|
+
},
|
|
51
|
+
"scripts": {
|
|
52
|
+
"build": "tsup src/index.ts --format esm,cjs --dts --sourcemap --clean",
|
|
53
|
+
"test": "vitest run",
|
|
54
|
+
"typecheck": "tsc -p tsconfig.json"
|
|
55
|
+
}
|
|
56
|
+
}
|