@noodleseed/agent-kit 0.8.1 → 0.10.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.
@@ -3,35 +3,206 @@
3
3
  ## Contents
4
4
 
5
5
  - Tools and views
6
- - React authoring
7
- - CSP and permissions
8
- - Host bridge
6
+ - React hook surface
7
+ - Worked widget recipe
8
+ - ChatGPT App = this widget + a domain
9
+ - Knowledge/source apps (search + fetch)
10
+ - Permissions and host bridge
9
11
  - Readiness and boundaries
10
12
 
11
13
  ## Tools and views
12
14
 
13
- Use `toolWithWidget(name, { description, input, output, fulfil, view })` for a model-visible tool that renders a widget, and `toolForWidget(name, { ... })` for a widget-only helper hidden from the model. A `view` is `{ component: "name", entry: "./views/name.tsx" }`.
15
+ Use `toolWithWidget(name, { description, input, output, fulfil, view })` for a model-visible tool that renders a widget, and `toolForWidget(name, { ... })` for a widget-only helper hidden from the model. A `view` is `{ component: "name", entry: "./views/name.tsx" }` — a React component the compiler bundles at validate/deploy time.
14
16
 
15
- ## React authoring
17
+ ## React hook surface
16
18
 
17
- Author views as React components. Get typed helpers from `@noodleseed/one/react`:
19
+ Author views as React components. `generateHelpers<ServerDefinition>()` (from `@noodleseed/one/react`) returns the typed host hooks:
18
20
 
19
- ```ts
21
+ | Hook | Use for |
22
+ | :-- | :-- |
23
+ | `useToolInfo` | Read the invoking tool result; `structuredContent` is the widget’s typed data payload. |
24
+ | `useCallTool` | Call a tool from the widget — returns `{ status, callTool, callToolAsync, data, structuredContent, error, reset }`; target a model-visible tool or a hidden `toolForWidget` helper. |
25
+ | `useViewState` | Persist per-widget UI state across re-renders and restores: `const [value, setValue] = useViewState("key", initial)`. |
26
+ | `useLayout` | Read host layout: `{ theme, displayMode, locale? }` (`theme` is `"light"`/`"dark"`, `displayMode` is `"inline"`/`"fullscreen"`) — adapt styling to the host theme and mode. |
27
+ | `useOpenExternal` | Open an external link through the host (never `window.open`); the target origin must be listed in the server-level `handoff.allowedDomains`. |
28
+ | `useSendFollowUpMessage` | Send a follow-up prompt to the model from a user interaction: `send({ prompt })` — trigger only from an explicit user action. |
29
+ | `useAppFlow` | Manage named widget views with persisted params and back-stack state: `const flow = useAppFlow({ initialView, views })`. |
30
+ | `useHandoff` | Open server-created HTTP(S) handoff URLs through the host with status/error state; domain policy still comes from `handoff.allowedDomains`. |
31
+
32
+ Bind interactive elements to tools (`useCallTool("place_order")`), drive named views with `useAppFlow(...)`, open server-created handoffs with `useHandoff()`, and annotate model-facing context with `data-llm`. Use `createViewStore("key", initial)` for multi-component widget state such as carts, filters, or drafts. Use the domain-neutral React components from `@noodleseed/one/react` (`AppShell`, `ShellNav`, `ViewStack`, `AsyncBoundary`, `ActionBar`, `Field`, `QuantityStepper`, `ChoiceGroup`, `HandoffButton`, and related state components) for rich apps before inventing local shell/control scaffolding. Adapt to the host with `useLayout()` — style for both `theme` values, and keep the inline `displayMode` compact (content fits the space; no internal scrolling). Trigger `useOpenExternal()`, `useHandoff()`, and `useSendFollowUpMessage()` only from explicit user actions. A raw `html` escape hatch exists for self-contained widgets (declarative `data-bind`/`data-action`; no inline `<script>`).
33
+
34
+ ## Worked widget recipe
35
+
36
+ Minimal, complete, and compile-verified — `noodle validate` bundles the view and `noodle check --target chatgpt` audits it. Author two files: the view (`src/views/order-status.tsx`) and the tool declaration (`src/server.ts`).
37
+
38
+ ### 1. The view component
39
+
40
+ Author React. `generateHelpers<ServerDefinition>()` (from `@noodleseed/one/react`) returns the typed host hooks: read the tool result with `useToolInfo`, call a widget-only helper with `useCallTool`, keep local UI state that survives re-render with `useViewState`, open an allowlisted link with `useOpenExternal`, and mirror model-facing context back to the model as text with `data-llm`.
41
+
42
+ ```tsx
43
+ import type { ServerDefinition } from '@noodleseed/one';
20
44
  import { generateHelpers } from '@noodleseed/one/react';
21
- const { useCallTool, useLayout, useToolInfo, useViewState } = generateHelpers<AppType>();
45
+
46
+ // One call wires the typed host bridge; destructure only the hooks this view uses.
47
+ const { useToolInfo, useCallTool, useViewState, useOpenExternal } =
48
+ generateHelpers<ServerDefinition>();
49
+
50
+ type OrderResult = {
51
+ readonly customer?: string;
52
+ readonly item?: string;
53
+ readonly total?: number;
54
+ readonly checkoutUrl?: string;
55
+ };
56
+
57
+ export default function OrderStatus() {
58
+ const shown = useToolInfo('show_order').structuredContent as OrderResult | undefined;
59
+ const placeOrder = useCallTool('place_order'); // calls the widget-only helper tool
60
+ const openExternal = useOpenExternal();
61
+ const [item, setItem] = useViewState('item', shown?.item ?? 'falafel_wrap'); // survives re-render
62
+ const confirmed = placeOrder.data?.structuredContent as { readonly status?: string } | undefined;
63
+ const total = shown?.total ?? 0;
64
+ const checkoutUrl = shown?.checkoutUrl ?? '';
65
+
66
+ return (
67
+ // data-llm mirrors the visible state back to the model as text context.
68
+ <main data-llm={`Pickup order for ${shown?.customer ?? 'Guest'}: ${item}, total ${total}`}>
69
+ <h1>Pickup order</h1>
70
+ <label>
71
+ Item
72
+ <select value={item} onChange={(event) => setItem(event.currentTarget.value)}>
73
+ <option value="falafel_wrap">Falafel Wrap</option>
74
+ <option value="lentil_soup">Lentil Soup</option>
75
+ <option value="mint_lemonade">Mint Lemonade</option>
76
+ </select>
77
+ </label>
78
+ <button
79
+ type="button"
80
+ disabled={placeOrder.isPending}
81
+ onClick={() => placeOrder.callTool({ customer: shown?.customer ?? 'Guest', item })}
82
+ >
83
+ {placeOrder.isPending ? 'Placing…' : 'Place order'}
84
+ </button>
85
+ <p>{confirmed?.status ?? `Total: $${total}`}</p>
86
+ <button type="button" onClick={() => openExternal(checkoutUrl)}>
87
+ Continue checkout
88
+ </button>
89
+ </main>
90
+ );
91
+ }
22
92
  ```
23
93
 
24
- Bind interactive elements to tools (`useCallTool("place_order")`) and annotate model-facing context with `data-llm`. A raw `html` escape hatch exists for self-contained widgets (declarative `data-bind`/`data-action`; no inline `<script>`).
94
+ ### 2. The tool declaration
95
+
96
+ `toolWithWidget` is the model-visible tool that renders the view; pair it with `toolForWidget` helpers the view calls (hidden from the model). Wire `view: { component, entry }`, `csp`, a widget `domain`, and a real `output` schema so non-Apps hosts still receive structured data. Inside `fulfil`, `input` is a symbolic ref recorded into a flow — reference it in output/template strings, but never use it as an object key or `if` condition.
97
+
98
+ ```ts
99
+ import { annotations, server, toolForWidget, toolWithWidget, z } from '@noodleseed/one';
25
100
 
26
- ## CSP, domain, and permissions
101
+ const item = z.enum(['falafel_wrap', 'lentil_soup', 'mint_lemonade']).default('falafel_wrap');
102
+ const checkoutUrl = (customer: string) =>
103
+ `https://orders.example.com/pickup?customer=${customer}`;
27
104
 
28
- Declare network/host needs explicitly: `csp: { connectDomains, resourceDomains, frameDomains }` and `permissions` (e.g. `clipboardWrite`). Secrets are never injected into widgets; tool output is redacted before widget delivery.
105
+ export default server(
106
+ 'pickup',
107
+ {
108
+ title: 'Pickup',
109
+ version: '1.0.0',
110
+ // External-link targets the widget opens; the compiler derives ChatGPT redirect_domains from this.
111
+ handoff: { allowedDomains: ['https://orders.example.com'] },
112
+ },
113
+ [
114
+ toolWithWidget('show_order', {
115
+ description: 'Show the pickup order and render the ordering widget.',
116
+ // Declare tool annotations — a ChatGPT-submission requirement. A read → `readOnly()`.
117
+ annotations: annotations.readOnly(),
118
+ input: z.object({ customer: z.string().default('Guest') }),
119
+ output: z.object({
120
+ customer: z.string(),
121
+ item: z.string(),
122
+ total: z.number(),
123
+ checkoutUrl: z.string(),
124
+ }),
125
+ fulfil: ({ input }) => ({
126
+ customer: input.customer,
127
+ item: 'falafel_wrap',
128
+ total: 12,
129
+ checkoutUrl: checkoutUrl(input.customer),
130
+ }),
131
+ widgetTitle: 'Pickup order',
132
+ widgetDescription: 'Pick an item and place a pickup order.',
133
+ // A ChatGPT App is this widget + a domain: one https origin per app.
134
+ domain: 'https://pickup.example.com',
135
+ view: { component: 'order-status', entry: './views/order-status.tsx' },
136
+ csp: {
137
+ connectDomains: ['https://orders.example.com'],
138
+ resourceDomains: ['https://example.com'],
139
+ // Keep CSP origins exact and minimal. Add `frameDomains` ONLY if the widget embeds an
140
+ // iframe — it relaxes subframe rendering and triggers stricter ChatGPT review.
141
+ },
142
+ }),
143
+ // Widget-only helper the view calls with useCallTool('place_order'); hidden from the model.
144
+ toolForWidget('place_order', {
145
+ description: 'Place a pickup order from the widget.',
146
+ // A write that reaches the outside world → `action()` (not read-only, not destructive).
147
+ annotations: annotations.action(),
148
+ input: z.object({ customer: z.string().default('Guest'), item }),
149
+ output: z.object({ status: z.string(), item: z.string(), checkoutUrl: z.string() }),
150
+ fulfil: ({ input }) => ({
151
+ status: `Order placed for ${input.customer}.`,
152
+ item: input.item,
153
+ checkoutUrl: checkoutUrl(input.customer),
154
+ }),
155
+ }),
156
+ ],
157
+ );
158
+ ```
159
+
160
+ ## ChatGPT App = this widget + a domain
161
+
162
+ A "ChatGPT App" is not a separate authoring surface — it is exactly this MCP Apps widget rendered by the ChatGPT host. From the same declaration you author three things:
163
+
164
+ - `domain` on the widget — one https origin per app (required for app-store submission, optional for dev-mode testing).
165
+ - `csp: { connectDomains, resourceDomains }` — the exact network/resource origins the widget may reach; keep them minimal. Add `frameDomains` only if the widget embeds an iframe (it relaxes subframe rendering and draws stricter review).
166
+ - server `handoff.allowedDomains` — the external-link targets `useOpenExternal()` opens.
167
+
168
+ The compiler emits the rest automatically: the `openai/*` metadata (`openai/outputTemplate`, `openai/widgetCSP`, `openai/widgetDescription`) and ChatGPT’s `redirect_domains` (derived from `handoff.allowedDomains`). `window.openai` and Claude’s ext-apps bridge are auto-detected at startup, so the same widget renders in both Claude and ChatGPT with no host-specific code.
169
+
170
+ Verify it in the loop: `noodle check --target chatgpt --json` returning `ok:true` means the widget is **metadata-ready** for ChatGPT’s checks (`domain`, `openai/outputTemplate`, CSP present) — it does NOT prove host rendering, conversation UX, or submission acceptance. Fix any `severity:"error"` finding by its `fix`, then re-check. Validate real rendering in ChatGPT Developer Mode / MCP Inspector as a higher level before submitting.
171
+
172
+ **Every tool needs annotations** (`annotations.readOnly()` / `.action()` / `.openAction()`) — missing or wrong `readOnlyHint`/`openWorldHint`/`destructiveHint` is a common submission rejection. **App-store submission is more than building**: a public https endpoint, exact CSP, org verification, app info, screenshots, and test prompts are required — follow OpenAI’s Apps submission guidelines; `noodle check --target chatgpt` covers only the metadata prerequisites.
173
+
174
+ ## Knowledge/source apps (ChatGPT): search + fetch
175
+
176
+ If the app is a read-only knowledge/source connector (docs, wiki, CRM lookups) meant for ChatGPT company-knowledge, implement exactly two tools — `search` and `fetch`, both read-only. ChatGPT only surfaces knowledge apps that match these signatures:
177
+
178
+ ```ts
179
+ import { annotations, server, tool, z } from '@noodleseed/one';
180
+
181
+ export default server('kb', { title: 'Knowledge base', version: '1.0.0' }, [
182
+ tool('search', {
183
+ description: 'Search the knowledge base; return citable results.',
184
+ annotations: annotations.readOnly(),
185
+ input: z.object({ query: z.string() }),
186
+ output: z.object({
187
+ results: z.array(z.object({ id: z.string(), title: z.string(), url: z.string() })),
188
+ }),
189
+ fulfil: ({ input }) => ({ results: [{ id: 'doc-1', title: `Match: ${input.query}`, url: 'https://example.com/doc-1' }] }),
190
+ }),
191
+ tool('fetch', {
192
+ description: 'Fetch one document by id for citation.',
193
+ annotations: annotations.readOnly(),
194
+ input: z.object({ id: z.string() }),
195
+ output: z.object({ id: z.string(), title: z.string(), text: z.string(), url: z.string() }),
196
+ fulfil: ({ input }) => ({ id: input.id, title: 'Doc', text: 'Full document text…', url: 'https://example.com/doc-1' }),
197
+ }),
198
+ ]);
199
+ ```
29
200
 
30
- For ChatGPT: set `domain` on each widget (one https origin per app; required for app-store submission, optional for dev-mode testing), and declare external-link targets in the server-level `handoff.allowedDomains` the compiler derives ChatGPT’s `redirect_domains` from it so `useOpenExternal()` links open without the safe-link warning. `noodle check --target chatgpt` verifies all of this.
201
+ `search` `{ results: [{ id, title, url }] }`; `fetch` `{ id, title, text, url, metadata? }`. `url` must be an absolute, user-openable https link for citation.
31
202
 
32
- ## Host bridge
203
+ ## Permissions and host bridge
33
204
 
34
- One runtime targets both Claude’s ext-apps bridge and ChatGPT’s `window.openai`, detected at startup. Tool results still carry useful `content`/`structuredContent` so non-Apps hosts degrade gracefully.
205
+ Declare extra host capabilities with `permissions` (e.g. `permissions: { clipboardWrite: {} }`). Secrets are never injected into widgets and tool output is redacted before widget delivery. Tool results still carry useful `content`/`structuredContent`, so non-Apps hosts degrade gracefully.
35
206
 
36
207
  ## Readiness and boundaries
37
208