@tangle-network/agent-app 0.45.20 → 0.45.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/dist/DesignCanvas-ZG7DJS7C.js +10 -0
  2. package/dist/DesignCanvasEditor-SLFMHOII.js +13 -0
  3. package/dist/app-auth/index.js +2 -2
  4. package/dist/assistant/index.d.ts +1 -1
  5. package/dist/assistant/index.js +5 -5
  6. package/dist/{attachment-validation-CsmUzuI3.d.ts → attachment-validation-BfJDBU1g.d.ts} +41 -5
  7. package/dist/{auth-DJjJBtYw.d.ts → auth-BYtiazA4.d.ts} +1 -1
  8. package/dist/chat-react/index.js +2 -2
  9. package/dist/chat-routes/index.d.ts +8 -4
  10. package/dist/chat-routes/index.js +22 -5
  11. package/dist/chat-routes/index.js.map +1 -1
  12. package/dist/{chunk-KPRBFNGT.js → chunk-3IHYJIDJ.js} +3 -3
  13. package/dist/{chunk-MYS7DHMM.js → chunk-4QVG4WJQ.js} +2 -2
  14. package/dist/{chunk-RMHZKMQ4.js → chunk-73CQJOIU.js} +5 -5
  15. package/dist/{chunk-PAB253MA.js → chunk-7V2I3JGZ.js} +19 -3
  16. package/dist/chunk-7V2I3JGZ.js.map +1 -0
  17. package/dist/chunk-CCVG2TL6.js +327 -0
  18. package/dist/chunk-CCVG2TL6.js.map +1 -0
  19. package/dist/{chunk-U4BXAZCN.js → chunk-DRB77FYL.js} +2 -2
  20. package/dist/{chunk-6MUJROBT.js → chunk-E4DHYENH.js} +2 -2
  21. package/dist/chunk-F7VH4G5C.js +283 -0
  22. package/dist/chunk-F7VH4G5C.js.map +1 -0
  23. package/dist/chunk-I24YIKHO.js +183 -0
  24. package/dist/chunk-I24YIKHO.js.map +1 -0
  25. package/dist/{chunk-AH3IOSWF.js → chunk-NZVBJM73.js} +1432 -187
  26. package/dist/chunk-NZVBJM73.js.map +1 -0
  27. package/dist/{chunk-OO4DROKM.js → chunk-OASVAPRL.js} +3 -3
  28. package/dist/{chunk-ZSGTG6PK.js → chunk-P5PIAQVS.js} +2 -2
  29. package/dist/chunk-PC2WYTK7.js +405 -0
  30. package/dist/chunk-PC2WYTK7.js.map +1 -0
  31. package/dist/{chunk-YEFFHORB.js → chunk-TX6S7XXU.js} +8 -2
  32. package/dist/chunk-TX6S7XXU.js.map +1 -0
  33. package/dist/chunk-UGWQLQDS.js +35 -0
  34. package/dist/chunk-UGWQLQDS.js.map +1 -0
  35. package/dist/{chunk-O22STZ3P.js → chunk-X5DQ5QOP.js} +2 -2
  36. package/dist/{chunk-PCJHEZA7.js → chunk-YABHE2QY.js} +2 -2
  37. package/dist/design-canvas/index.d.ts +3 -3
  38. package/dist/design-canvas/index.js +2 -2
  39. package/dist/design-canvas-react/engine.js +4 -4
  40. package/dist/design-canvas-react/index.js +7 -7
  41. package/dist/design-canvas-react/lazy.js +1 -1
  42. package/dist/documents/index.d.ts +233 -0
  43. package/dist/documents/index.js +495 -0
  44. package/dist/documents/index.js.map +1 -0
  45. package/dist/documents/pdf-inspector.d.ts +60 -0
  46. package/dist/documents/pdf-inspector.js +100 -0
  47. package/dist/documents/pdf-inspector.js.map +1 -0
  48. package/dist/eval/index.d.ts +1 -1
  49. package/dist/fold-DACU7gtf.d.ts +320 -0
  50. package/dist/{mcp-BiKqnsJV.d.ts → mcp-xxoZZfor.d.ts} +2 -2
  51. package/dist/openui/index.d.ts +208 -0
  52. package/dist/openui/index.js +350 -0
  53. package/dist/openui/index.js.map +1 -0
  54. package/dist/openui-react/index.d.ts +119 -0
  55. package/dist/openui-react/index.js +149 -0
  56. package/dist/openui-react/index.js.map +1 -0
  57. package/dist/platform/index.js +2 -2
  58. package/dist/preset-cloudflare/index.d.ts +2 -2
  59. package/dist/rate-limit-BOVmJRXZ.d.ts +35 -0
  60. package/dist/record/drizzle.d.ts +682 -0
  61. package/dist/record/drizzle.js +579 -0
  62. package/dist/record/drizzle.js.map +1 -0
  63. package/dist/record/index.d.ts +16 -0
  64. package/dist/record/index.js +35 -0
  65. package/dist/record/index.js.map +1 -0
  66. package/dist/runtime/index.d.ts +3 -3
  67. package/dist/sandbox/index.d.ts +13 -4
  68. package/dist/sandbox/index.js +6 -3
  69. package/dist/sequences/index.d.ts +3 -3
  70. package/dist/sequences/index.js +1 -1
  71. package/dist/session-shell/index.d.ts +173 -1
  72. package/dist/session-shell/index.js +13 -1
  73. package/dist/teams/index.js +9 -9
  74. package/dist/teams/invitations-api.js +3 -3
  75. package/dist/tools/index.d.ts +5 -5
  76. package/dist/tools/index.js +3 -2
  77. package/dist/{types-DbU-oO5h.d.ts → types-B25Mib1r.d.ts} +11 -0
  78. package/dist/types-DrBidf3O.d.ts +123 -0
  79. package/dist/values-C7RidJuI.d.ts +156 -0
  80. package/dist/web/index.d.ts +197 -31
  81. package/dist/web/index.js +15 -3
  82. package/dist/web-react/async/index.d.ts +309 -0
  83. package/dist/web-react/async/index.js +327 -0
  84. package/dist/web-react/async/index.js.map +1 -0
  85. package/dist/web-react/index.d.ts +338 -2
  86. package/dist/web-react/index.js +52 -6
  87. package/dist/work-product/index.d.ts +1 -1
  88. package/dist/work-product/index.js +2 -1
  89. package/dist/work-product/index.js.map +1 -1
  90. package/dist/workspace-react/index.js +1 -1
  91. package/package.json +43 -3
  92. package/dist/DesignCanvas-NEIW3AER.js +0 -10
  93. package/dist/DesignCanvasEditor-QD33OI2W.js +0 -13
  94. package/dist/chunk-AH3IOSWF.js.map +0 -1
  95. package/dist/chunk-GINKOZFD.js +0 -214
  96. package/dist/chunk-GINKOZFD.js.map +0 -1
  97. package/dist/chunk-J25RST7G.js +0 -126
  98. package/dist/chunk-J25RST7G.js.map +0 -1
  99. package/dist/chunk-PAB253MA.js.map +0 -1
  100. package/dist/chunk-WBHPN5DY.js +0 -158
  101. package/dist/chunk-WBHPN5DY.js.map +0 -1
  102. package/dist/chunk-YEFFHORB.js.map +0 -1
  103. /package/dist/{DesignCanvas-NEIW3AER.js.map → DesignCanvas-ZG7DJS7C.js.map} +0 -0
  104. /package/dist/{DesignCanvasEditor-QD33OI2W.js.map → DesignCanvasEditor-SLFMHOII.js.map} +0 -0
  105. /package/dist/{chunk-KPRBFNGT.js.map → chunk-3IHYJIDJ.js.map} +0 -0
  106. /package/dist/{chunk-MYS7DHMM.js.map → chunk-4QVG4WJQ.js.map} +0 -0
  107. /package/dist/{chunk-RMHZKMQ4.js.map → chunk-73CQJOIU.js.map} +0 -0
  108. /package/dist/{chunk-U4BXAZCN.js.map → chunk-DRB77FYL.js.map} +0 -0
  109. /package/dist/{chunk-6MUJROBT.js.map → chunk-E4DHYENH.js.map} +0 -0
  110. /package/dist/{chunk-OO4DROKM.js.map → chunk-OASVAPRL.js.map} +0 -0
  111. /package/dist/{chunk-ZSGTG6PK.js.map → chunk-P5PIAQVS.js.map} +0 -0
  112. /package/dist/{chunk-O22STZ3P.js.map → chunk-X5DQ5QOP.js.map} +0 -0
  113. /package/dist/{chunk-PCJHEZA7.js.map → chunk-YABHE2QY.js.map} +0 -0
@@ -0,0 +1,350 @@
1
+ import {
2
+ OPENUI_INPUT_KINDS,
3
+ OPENUI_INTERACTIVE_AUTHORING_GUIDE
4
+ } from "../chunk-UGWQLQDS.js";
5
+
6
+ // src/openui/segments.ts
7
+ var FENCE = /```openui\s*\n([\s\S]*?)```/g;
8
+ function isNodeLike(value) {
9
+ return typeof value === "object" && value !== null && !Array.isArray(value) && typeof value.type === "string";
10
+ }
11
+ function nodesFrom(parsed) {
12
+ const candidates = Array.isArray(parsed) ? parsed : [parsed];
13
+ return candidates.filter(isNodeLike);
14
+ }
15
+ function pushText(segments, text) {
16
+ const trimmed = text.trim();
17
+ if (trimmed) segments.push({ type: "markdown", text: trimmed });
18
+ }
19
+ function parseOpenUISegments(content) {
20
+ const segments = [];
21
+ let lastIndex = 0;
22
+ FENCE.lastIndex = 0;
23
+ let match;
24
+ while ((match = FENCE.exec(content)) !== null) {
25
+ if (match.index > lastIndex) pushText(segments, content.slice(lastIndex, match.index));
26
+ const body = match[1] ?? "";
27
+ let nodes = [];
28
+ try {
29
+ nodes = nodesFrom(JSON.parse(body));
30
+ } catch {
31
+ nodes = [];
32
+ }
33
+ if (nodes.length > 0) segments.push({ type: "openui", nodes });
34
+ else pushText(segments, `\`\`\`json
35
+ ${body}\`\`\``);
36
+ lastIndex = match.index + match[0].length;
37
+ }
38
+ if (lastIndex < content.length) pushText(segments, content.slice(lastIndex));
39
+ if (segments.length === 0 && content.trim()) segments.push({ type: "markdown", text: content });
40
+ return segments;
41
+ }
42
+ function hasOpenUISegment(content) {
43
+ return parseOpenUISegments(content).some((segment) => segment.type === "openui");
44
+ }
45
+ function parseOpenUIArtifact(content) {
46
+ let parsed;
47
+ try {
48
+ parsed = JSON.parse(content);
49
+ } catch {
50
+ return { succeeded: false, error: { code: "artifact_not_json", message: "Stored page is not JSON." } };
51
+ }
52
+ const envelope = parsed && typeof parsed === "object" && !Array.isArray(parsed) && "schema" in parsed ? parsed : null;
53
+ const nodes = nodesFrom(envelope ? envelope.schema : parsed);
54
+ if (nodes.length === 0) {
55
+ return { succeeded: false, error: { code: "artifact_no_nodes", message: "Stored page carries no nodes." } };
56
+ }
57
+ const title = envelope && typeof envelope.title === "string" ? envelope.title : void 0;
58
+ return { succeeded: true, value: { nodes, ...title ? { title } : {} } };
59
+ }
60
+
61
+ // src/openui/values.ts
62
+ function isSafeOpenUIFieldId(id) {
63
+ return /^[A-Za-z0-9_-]+$/.test(id) && id !== "__proto__" && id !== "constructor" && id !== "prototype";
64
+ }
65
+ var FIELD_KINDS = /* @__PURE__ */ new Set([
66
+ "text",
67
+ "number",
68
+ "currency",
69
+ "select",
70
+ "checkbox",
71
+ "slider"
72
+ ]);
73
+ function isOpenUIFieldKind(kind) {
74
+ return FIELD_KINDS.has(kind);
75
+ }
76
+ function issue(fieldId, code, message) {
77
+ return { fieldId, code, message };
78
+ }
79
+ var STEP_EPSILON = 1e-9;
80
+ function checkNumeric(field, value) {
81
+ if (!Number.isFinite(value)) return issue(field.id, "type", `${field.id} must be a finite number`);
82
+ if (field.min !== void 0 && value < field.min) {
83
+ return issue(field.id, "range", `${field.id} must be at least ${field.min}`);
84
+ }
85
+ if (field.max !== void 0 && value > field.max) {
86
+ return issue(field.id, "range", `${field.id} must be at most ${field.max}`);
87
+ }
88
+ if (field.step !== void 0 && field.step > 0) {
89
+ const offset = (value - (field.min ?? 0)) / field.step;
90
+ if (Math.abs(offset - Math.round(offset)) > STEP_EPSILON) {
91
+ return issue(field.id, "step", `${field.id} must move in steps of ${field.step}`);
92
+ }
93
+ }
94
+ return null;
95
+ }
96
+ function isEmpty(value) {
97
+ if (typeof value === "string") return value.trim() === "";
98
+ if (Array.isArray(value)) return value.length === 0;
99
+ return false;
100
+ }
101
+ function checkField(field, value) {
102
+ if (value === void 0 || isEmpty(value)) {
103
+ if (field.required) return issue(field.id, "required", `${field.id} is required`);
104
+ return null;
105
+ }
106
+ switch (field.kind) {
107
+ case "text": {
108
+ if (typeof value !== "string") return issue(field.id, "type", `${field.id} must be text`);
109
+ if (field.maxLength !== void 0 && value.length > field.maxLength) {
110
+ return issue(field.id, "length", `${field.id} must be at most ${field.maxLength} characters`);
111
+ }
112
+ return null;
113
+ }
114
+ case "number":
115
+ case "currency":
116
+ case "slider": {
117
+ if (typeof value !== "number") return issue(field.id, "type", `${field.id} must be a number`);
118
+ return checkNumeric(field, value);
119
+ }
120
+ case "checkbox": {
121
+ if (typeof value !== "boolean") return issue(field.id, "type", `${field.id} must be true or false`);
122
+ return null;
123
+ }
124
+ case "select": {
125
+ const allowed = field.options ? new Set(field.options.map((option) => option.value)) : null;
126
+ if (field.multiple) {
127
+ if (!Array.isArray(value)) return issue(field.id, "type", `${field.id} must be a list of choices`);
128
+ if (allowed) {
129
+ const rejected = value.find((entry) => !allowed.has(entry));
130
+ if (rejected !== void 0) {
131
+ return issue(field.id, "option", `${field.id} does not offer "${rejected}"`);
132
+ }
133
+ }
134
+ return null;
135
+ }
136
+ if (typeof value !== "string") return issue(field.id, "type", `${field.id} must be a single choice`);
137
+ if (allowed && !allowed.has(value)) return issue(field.id, "option", `${field.id} does not offer "${value}"`);
138
+ return null;
139
+ }
140
+ }
141
+ }
142
+ function validateOpenUIFormValues(spec, values) {
143
+ const issues = [];
144
+ const seen = /* @__PURE__ */ new Set();
145
+ for (const field of spec.fields) {
146
+ if (!isSafeOpenUIFieldId(field.id)) {
147
+ issues.push(issue(field.id, "unsafe_field_id", `${field.id} is not a usable field id`));
148
+ continue;
149
+ }
150
+ if (seen.has(field.id)) {
151
+ issues.push(issue(field.id, "duplicate_field", `${field.id} is declared more than once`));
152
+ continue;
153
+ }
154
+ seen.add(field.id);
155
+ }
156
+ for (const key of Object.keys(values)) {
157
+ if (!seen.has(key)) issues.push(issue(key, "unknown_field", `${key} is not a field on this form`));
158
+ }
159
+ const accepted = {};
160
+ for (const field of spec.fields) {
161
+ if (!seen.has(field.id)) continue;
162
+ const value = Object.prototype.hasOwnProperty.call(values, field.id) ? values[field.id] : void 0;
163
+ const problem = checkField(field, value);
164
+ if (problem) {
165
+ issues.push(problem);
166
+ continue;
167
+ }
168
+ if (value !== void 0) accepted[field.id] = value;
169
+ }
170
+ if (issues.length > 0) return { ok: false, issues };
171
+ return { ok: true, values: accepted };
172
+ }
173
+
174
+ // src/openui/action.ts
175
+ function isSafeOpenUIActionId(id) {
176
+ return isSafeOpenUIFieldId(id);
177
+ }
178
+ function isOpenUIValue(value) {
179
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || Array.isArray(value) && value.every((entry) => typeof entry === "string");
180
+ }
181
+ function optionalId(value, code, label) {
182
+ if (value === void 0 || value === null) return { ok: true, value: void 0 };
183
+ if (typeof value !== "string" || !isSafeOpenUIActionId(value)) {
184
+ return { ok: false, code, error: `Invalid ${label}: letters, numbers, underscores, and hyphens only` };
185
+ }
186
+ return { ok: true, value };
187
+ }
188
+ function isSafeArtifactPath(path) {
189
+ return path.length > 0 && path.length <= 512 && !path.includes("..") && !path.startsWith("/");
190
+ }
191
+ function validateOpenUIActionBody(body) {
192
+ const actionId = body.actionId;
193
+ if (typeof actionId !== "string" || actionId.trim() === "") {
194
+ return { ok: false, code: "OPENUI_ACTION_ID_MISSING", error: "Missing actionId" };
195
+ }
196
+ if (!isSafeOpenUIActionId(actionId)) {
197
+ return {
198
+ ok: false,
199
+ code: "OPENUI_ACTION_ID_INVALID",
200
+ error: "Invalid actionId: letters, numbers, underscores, and hyphens only"
201
+ };
202
+ }
203
+ const formId = optionalId(body.formId, "OPENUI_FORM_ID_INVALID", "formId");
204
+ if (!formId.ok) return formId;
205
+ const nodeId = optionalId(body.nodeId, "OPENUI_NODE_ID_INVALID", "nodeId");
206
+ if (!nodeId.ok) return nodeId;
207
+ let artifactPath;
208
+ if (body.artifactPath !== void 0 && body.artifactPath !== null) {
209
+ if (typeof body.artifactPath !== "string" || !isSafeArtifactPath(body.artifactPath)) {
210
+ return { ok: false, code: "OPENUI_ARTIFACT_PATH_INVALID", error: "Invalid artifactPath" };
211
+ }
212
+ artifactPath = body.artifactPath;
213
+ }
214
+ const values = {};
215
+ if (body.values !== void 0 && body.values !== null) {
216
+ if (typeof body.values !== "object" || Array.isArray(body.values)) {
217
+ return { ok: false, code: "OPENUI_VALUES_INVALID", error: "Invalid values: expected an object of field values" };
218
+ }
219
+ for (const [key, value] of Object.entries(body.values)) {
220
+ if (!isSafeOpenUIFieldId(key)) {
221
+ return {
222
+ ok: false,
223
+ code: "OPENUI_FIELD_ID_INVALID",
224
+ error: "Invalid values: field names must contain only letters, numbers, underscores, or hyphens"
225
+ };
226
+ }
227
+ if (!isOpenUIValue(value)) {
228
+ return {
229
+ ok: false,
230
+ code: "OPENUI_FIELD_VALUE_INVALID",
231
+ error: "Invalid values: field values must be strings, numbers, booleans, or string arrays"
232
+ };
233
+ }
234
+ values[key] = value;
235
+ }
236
+ }
237
+ return {
238
+ ok: true,
239
+ submission: {
240
+ actionId,
241
+ values,
242
+ ...formId.value ? { formId: formId.value } : {},
243
+ ...nodeId.value ? { nodeId: nodeId.value } : {},
244
+ ...artifactPath ? { artifactPath } : {}
245
+ }
246
+ };
247
+ }
248
+ function describeValue(value) {
249
+ if (Array.isArray(value)) return value.join(", ");
250
+ return String(value);
251
+ }
252
+ function describeOpenUIAction(submission) {
253
+ const entries = Object.entries(submission.values);
254
+ const where = submission.formId ? ` on form "${submission.formId}"` : "";
255
+ if (entries.length === 0) return `User pressed "${submission.actionId}"${where}.`;
256
+ const pairs = entries.map(([key, value]) => `${key}=${describeValue(value)}`).join(", ");
257
+ return `User pressed "${submission.actionId}"${where} with ${pairs}.`;
258
+ }
259
+
260
+ // src/openui/route.ts
261
+ function failure(code, error, status, extra) {
262
+ return Response.json({ ok: false, code, error, ...extra ?? {} }, { status });
263
+ }
264
+ function createOpenUIActionRoute(options) {
265
+ const logger = options.logger ?? console;
266
+ async function handle(request) {
267
+ if (request.method !== "POST") return failure("OPENUI_METHOD_NOT_ALLOWED", "Method not allowed", 405);
268
+ const body = await request.json().catch(() => null);
269
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
270
+ return failure("OPENUI_BODY_INVALID", "Invalid JSON body", 400);
271
+ }
272
+ const parsed = validateOpenUIActionBody(body);
273
+ if (!parsed.ok) return failure(parsed.code, parsed.error, 400);
274
+ const submission = parsed.submission;
275
+ const handler = Object.prototype.hasOwnProperty.call(options.actions, submission.actionId) ? options.actions[submission.actionId] : void 0;
276
+ if (!handler) {
277
+ return failure(
278
+ "OPENUI_ACTION_UNKNOWN",
279
+ `No handler is registered for "${submission.actionId}".`,
280
+ 404,
281
+ { actionId: submission.actionId }
282
+ );
283
+ }
284
+ const resolution = await options.resolve({ request, submission });
285
+ if (!resolution.ok) return resolution.response;
286
+ const spec = submission.formId && options.forms ? Object.prototype.hasOwnProperty.call(options.forms, submission.formId) ? options.forms[submission.formId] : void 0 : void 0;
287
+ let values = submission.values;
288
+ if (spec) {
289
+ const checked = validateOpenUIFormValues(spec, submission.values);
290
+ if (!checked.ok) {
291
+ return failure("OPENUI_VALUES_REJECTED", "Some fields need fixing before this can run.", 422, {
292
+ issues: checked.issues
293
+ });
294
+ }
295
+ values = checked.values;
296
+ }
297
+ const checkedSubmission = { ...submission, values };
298
+ let result;
299
+ try {
300
+ result = await handler({ request, submission: checkedSubmission, context: resolution.context });
301
+ } catch (error) {
302
+ logger.error("[openui] action handler failed:", error);
303
+ return failure("OPENUI_ACTION_FAILED", "That action could not be completed. Try again.", 500, {
304
+ actionId: submission.actionId
305
+ });
306
+ }
307
+ if (!result.ok) {
308
+ return failure(result.code, result.message, result.status ?? 400, {
309
+ actionId: submission.actionId,
310
+ ...result.issues ? { issues: result.issues } : {}
311
+ });
312
+ }
313
+ if (options.recordForAgent) {
314
+ try {
315
+ await options.recordForAgent({
316
+ request,
317
+ submission: checkedSubmission,
318
+ context: resolution.context,
319
+ note: describeOpenUIAction(checkedSubmission)
320
+ });
321
+ } catch (error) {
322
+ logger.warn("[openui] recordForAgent failed:", error);
323
+ }
324
+ }
325
+ return Response.json({
326
+ ok: true,
327
+ actionId: submission.actionId,
328
+ ...result.message ? { message: result.message } : {},
329
+ ...result.values ? { values: result.values } : {},
330
+ ...result.schema ? { schema: result.schema } : {},
331
+ ...result.data ? { data: result.data } : {}
332
+ });
333
+ }
334
+ return { handle };
335
+ }
336
+ export {
337
+ OPENUI_INPUT_KINDS,
338
+ OPENUI_INTERACTIVE_AUTHORING_GUIDE,
339
+ createOpenUIActionRoute,
340
+ describeOpenUIAction,
341
+ hasOpenUISegment,
342
+ isOpenUIFieldKind,
343
+ isSafeOpenUIActionId,
344
+ isSafeOpenUIFieldId,
345
+ parseOpenUIArtifact,
346
+ parseOpenUISegments,
347
+ validateOpenUIActionBody,
348
+ validateOpenUIFormValues
349
+ };
350
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/openui/segments.ts","../../src/openui/values.ts","../../src/openui/action.ts","../../src/openui/route.ts"],"sourcesContent":["/**\n * Splitting an assistant message into prose and agent-authored UI.\n *\n * An agent emits a page by fencing it as ```` ```openui ```` in its reply (the\n * inline path) or by calling `render_ui` (the persisted-artifact path). Every\n * product that renders the inline path had forked the same scanner into its own\n * chat-message body; this is that scanner, once, with no React and no renderer\n * import — the node union stays owned by `@tangle-network/ui`'s `./openui`.\n */\n\n/**\n * The narrowest thing a host can assert about a parsed node: it names a type.\n * A renderer's node union satisfies this, so\n * `parseOpenUISegments<OpenUIComponentNode>(text)` hands typed nodes straight\n * to the renderer with no cast at the call site.\n */\nexport interface OpenUINode {\n type: string\n id?: string\n}\n\n/** One piece of an assistant message: prose, or a page to render. */\nexport type OpenUISegment<TNode extends OpenUINode = OpenUINode> =\n | { type: 'markdown'; text: string }\n | { type: 'openui'; nodes: TNode[] }\n\nconst FENCE = /```openui\\s*\\n([\\s\\S]*?)```/g\n\nfunction isNodeLike(value: unknown): boolean {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as { type?: unknown }).type === 'string'\n )\n}\n\n/** Every array entry (or the single object) that names a node type. */\nfunction nodesFrom(parsed: unknown): unknown[] {\n const candidates = Array.isArray(parsed) ? parsed : [parsed]\n return candidates.filter(isNodeLike)\n}\n\nfunction pushText<TNode extends OpenUINode>(segments: Array<OpenUISegment<TNode>>, text: string): void {\n const trimmed = text.trim()\n if (trimmed) segments.push({ type: 'markdown', text: trimmed })\n}\n\n/**\n * Split message content into markdown and OpenUI segments, in source order.\n *\n * A fence whose body is not JSON, or whose JSON carries no node at all, is\n * returned as a fenced `json` markdown segment rather than an empty page: the\n * content is still streaming, or the agent wrote something malformed, and both\n * cases are better shown than swallowed into a blank card.\n *\n * The type argument is the caller's assertion about the node union it will\n * render; this function checks only that each node names a `type`, and the\n * renderer rejects types it does not know.\n */\nexport function parseOpenUISegments<TNode extends OpenUINode = OpenUINode>(\n content: string,\n): Array<OpenUISegment<TNode>> {\n const segments: Array<OpenUISegment<TNode>> = []\n let lastIndex = 0\n\n // `FENCE` carries the `g` flag and therefore `lastIndex` state; reset it so\n // concurrent/repeat calls cannot resume mid-string from a previous scan.\n FENCE.lastIndex = 0\n let match: RegExpExecArray | null\n while ((match = FENCE.exec(content)) !== null) {\n if (match.index > lastIndex) pushText(segments, content.slice(lastIndex, match.index))\n const body = match[1] ?? ''\n let nodes: unknown[] = []\n try {\n nodes = nodesFrom(JSON.parse(body) as unknown)\n } catch {\n nodes = []\n }\n if (nodes.length > 0) segments.push({ type: 'openui', nodes: nodes as TNode[] })\n else pushText(segments, `\\`\\`\\`json\\n${body}\\`\\`\\``)\n lastIndex = match.index + match[0].length\n }\n\n if (lastIndex < content.length) pushText(segments, content.slice(lastIndex))\n if (segments.length === 0 && content.trim()) segments.push({ type: 'markdown', text: content })\n return segments\n}\n\n/** Whether a message carries any agent-authored page at all. */\nexport function hasOpenUISegment(content: string): boolean {\n return parseOpenUISegments(content).some((segment) => segment.type === 'openui')\n}\n\n/** A page read back out of the vault, and its title when one was stored. */\nexport interface OpenUIArtifact<TNode extends OpenUINode = OpenUINode> {\n title?: string\n nodes: TNode[]\n}\n\n/** Why a stored page could not be read. */\nexport interface OpenUIArtifactError {\n code: 'artifact_not_json' | 'artifact_no_nodes'\n message: string\n}\n\n/** Reading a stored page either produces nodes or says why it did not. */\nexport type OpenUIArtifactResult<TNode extends OpenUINode = OpenUINode> =\n | { succeeded: true; value: OpenUIArtifact<TNode> }\n | { succeeded: false; error: OpenUIArtifactError }\n\n/**\n * Read a `render_ui` artifact back out of the vault.\n *\n * Two shapes are in the wild and a product cannot tell them apart from the\n * path: the bare node tree that `preset-cloudflare`'s handler writes\n * (`JSON.stringify(args.schema)`), and the `{ title, schema }` envelope some\n * products write themselves. Reading only one of them renders an empty panel\n * for the other, with nothing on screen to say why — so this reads both and\n * fails loud when it is neither.\n */\nexport function parseOpenUIArtifact<TNode extends OpenUINode = OpenUINode>(\n content: string,\n): OpenUIArtifactResult<TNode> {\n let parsed: unknown\n try {\n parsed = JSON.parse(content) as unknown\n } catch {\n return { succeeded: false, error: { code: 'artifact_not_json', message: 'Stored page is not JSON.' } }\n }\n\n const envelope =\n parsed && typeof parsed === 'object' && !Array.isArray(parsed) && 'schema' in parsed\n ? (parsed as { schema: unknown; title?: unknown })\n : null\n const nodes = nodesFrom(envelope ? envelope.schema : parsed)\n if (nodes.length === 0) {\n return { succeeded: false, error: { code: 'artifact_no_nodes', message: 'Stored page carries no nodes.' } }\n }\n const title = envelope && typeof envelope.title === 'string' ? envelope.title : undefined\n return { succeeded: true, value: { nodes: nodes as TNode[], ...(title ? { title } : {}) } }\n}\n","/**\n * The value half of an interactive OpenUI page: what a field holds, and whether\n * a submitted set of field values matches the form the agent authored.\n *\n * The NODE vocabulary (which fields exist, how they render) has one owner —\n * `@tangle-network/ui`'s `./openui` entry. This module does not restate it. It\n * declares the narrowest STRUCTURAL port a host needs to check a submission:\n * the field's id, its kind, and the constraints that make a value legal. A\n * renderer's richer node type satisfies this port by assignment, so the two\n * packages stay in step without either importing the other.\n */\n\n/** A value one OpenUI field can hold. `string[]` is a multi-select. */\nexport type OpenUIValue = string | number | boolean | string[]\n\n/** Submitted field values, keyed by field id. */\nexport type OpenUIFormValues = Record<string, OpenUIValue>\n\n/**\n * Field ids the host will accept: identifier-safe, and never a key that would\n * reach `Object.prototype`. A submission arrives from a browser and is used to\n * index an object, so this is a boundary check, not a style rule.\n */\nexport function isSafeOpenUIFieldId(id: string): boolean {\n return /^[A-Za-z0-9_-]+$/.test(id) && id !== '__proto__' && id !== 'constructor' && id !== 'prototype'\n}\n\n/** The input kinds a form field can be. */\nexport type OpenUIFieldKind = 'text' | 'number' | 'currency' | 'select' | 'checkbox' | 'slider'\n\nconst FIELD_KINDS: ReadonlySet<string> = new Set<OpenUIFieldKind>([\n 'text',\n 'number',\n 'currency',\n 'select',\n 'checkbox',\n 'slider',\n])\n\n/** Whether a string names an input kind this contract knows. */\nexport function isOpenUIFieldKind(kind: string): kind is OpenUIFieldKind {\n return FIELD_KINDS.has(kind)\n}\n\n/**\n * One field, reduced to what a value check needs. A renderer node carrying\n * labels, placeholders, and layout is assignable to this — the extra\n * presentation properties are simply not read here.\n */\nexport interface OpenUIFieldSpec {\n id: string\n kind: OpenUIFieldKind\n required?: boolean\n /** `number` / `currency` / `slider` bounds, inclusive. */\n min?: number\n max?: number\n /** Increment `number` / `currency` / `slider` values must land on, measured from `min ?? 0`. */\n step?: number\n /** Longest accepted `text` value. */\n maxLength?: number\n /** Accepted `select` values. */\n options?: ReadonlyArray<{ value: string }>\n /** A `select` that accepts more than one option; its value is a `string[]`. */\n multiple?: boolean\n}\n\n/** A form the host can check a submission against. */\nexport interface OpenUIFormSpec {\n id: string\n fields: readonly OpenUIFieldSpec[]\n}\n\n/** Why one field's value was rejected. */\nexport type OpenUIFieldIssueCode =\n | 'required'\n | 'type'\n | 'range'\n | 'step'\n | 'option'\n | 'length'\n | 'unknown_field'\n | 'duplicate_field'\n | 'unsafe_field_id'\n\n/** One rejected field, named so a card can mark exactly that input. */\nexport interface OpenUIFieldIssue {\n fieldId: string\n code: OpenUIFieldIssueCode\n message: string\n}\n\n/** The outcome of checking a submission against a form. */\nexport type OpenUIFormValidation =\n | { ok: true; values: OpenUIFormValues }\n | { ok: false; issues: OpenUIFieldIssue[] }\n\nfunction issue(fieldId: string, code: OpenUIFieldIssueCode, message: string): OpenUIFieldIssue {\n return { fieldId, code, message }\n}\n\n/** Floating-point step arithmetic: 0.1 increments must not reject 0.3. */\nconst STEP_EPSILON = 1e-9\n\nfunction checkNumeric(field: OpenUIFieldSpec, value: number): OpenUIFieldIssue | null {\n if (!Number.isFinite(value)) return issue(field.id, 'type', `${field.id} must be a finite number`)\n if (field.min !== undefined && value < field.min) {\n return issue(field.id, 'range', `${field.id} must be at least ${field.min}`)\n }\n if (field.max !== undefined && value > field.max) {\n return issue(field.id, 'range', `${field.id} must be at most ${field.max}`)\n }\n if (field.step !== undefined && field.step > 0) {\n const offset = (value - (field.min ?? 0)) / field.step\n if (Math.abs(offset - Math.round(offset)) > STEP_EPSILON) {\n return issue(field.id, 'step', `${field.id} must move in steps of ${field.step}`)\n }\n }\n return null\n}\n\nfunction isEmpty(value: OpenUIValue): boolean {\n if (typeof value === 'string') return value.trim() === ''\n if (Array.isArray(value)) return value.length === 0\n return false\n}\n\nfunction checkField(field: OpenUIFieldSpec, value: OpenUIValue | undefined): OpenUIFieldIssue | null {\n if (value === undefined || isEmpty(value)) {\n // A checkbox is never \"empty\" — `false` is an answer — so only a genuinely\n // absent value can fail the required check for one.\n if (field.required) return issue(field.id, 'required', `${field.id} is required`)\n return null\n }\n\n switch (field.kind) {\n case 'text': {\n if (typeof value !== 'string') return issue(field.id, 'type', `${field.id} must be text`)\n if (field.maxLength !== undefined && value.length > field.maxLength) {\n return issue(field.id, 'length', `${field.id} must be at most ${field.maxLength} characters`)\n }\n return null\n }\n case 'number':\n case 'currency':\n case 'slider': {\n if (typeof value !== 'number') return issue(field.id, 'type', `${field.id} must be a number`)\n return checkNumeric(field, value)\n }\n case 'checkbox': {\n if (typeof value !== 'boolean') return issue(field.id, 'type', `${field.id} must be true or false`)\n return null\n }\n case 'select': {\n const allowed = field.options ? new Set(field.options.map((option) => option.value)) : null\n if (field.multiple) {\n if (!Array.isArray(value)) return issue(field.id, 'type', `${field.id} must be a list of choices`)\n if (allowed) {\n const rejected = value.find((entry) => !allowed.has(entry))\n if (rejected !== undefined) {\n return issue(field.id, 'option', `${field.id} does not offer \"${rejected}\"`)\n }\n }\n return null\n }\n if (typeof value !== 'string') return issue(field.id, 'type', `${field.id} must be a single choice`)\n if (allowed && !allowed.has(value)) return issue(field.id, 'option', `${field.id} does not offer \"${value}\"`)\n return null\n }\n }\n}\n\n/**\n * Check submitted values against the form the agent authored.\n *\n * Fails loud on both sides of the shape: a value the form never declared is an\n * error (`unknown_field`), not a silently ignored extra, because a host that\n * drops it would act on a form different from the one the user filled in. A\n * `required` field with no value is an error even when the caller simply never\n * sent the key.\n *\n * On success the returned `values` contain only declared fields, in the form's\n * own field order — the object a handler should act on.\n */\nexport function validateOpenUIFormValues(spec: OpenUIFormSpec, values: OpenUIFormValues): OpenUIFormValidation {\n const issues: OpenUIFieldIssue[] = []\n const seen = new Set<string>()\n for (const field of spec.fields) {\n if (!isSafeOpenUIFieldId(field.id)) {\n issues.push(issue(field.id, 'unsafe_field_id', `${field.id} is not a usable field id`))\n continue\n }\n if (seen.has(field.id)) {\n issues.push(issue(field.id, 'duplicate_field', `${field.id} is declared more than once`))\n continue\n }\n seen.add(field.id)\n }\n\n for (const key of Object.keys(values)) {\n if (!seen.has(key)) issues.push(issue(key, 'unknown_field', `${key} is not a field on this form`))\n }\n\n const accepted: OpenUIFormValues = {}\n for (const field of spec.fields) {\n if (!seen.has(field.id)) continue\n const value = Object.prototype.hasOwnProperty.call(values, field.id) ? values[field.id] : undefined\n const problem = checkField(field, value)\n if (problem) {\n issues.push(problem)\n continue\n }\n if (value !== undefined) accepted[field.id] = value\n }\n\n if (issues.length > 0) return { ok: false, issues }\n return { ok: true, values: accepted }\n}\n","/**\n * What travels when a user presses a button on a page the agent authored.\n *\n * The submission is a plain REST body, not a chat turn. That is the entire\n * point of this module: pressing \"Recalculate\" on an agent-authored form must\n * cost the same as pressing a button on a hand-built screen — one product route\n * call, no model tokens, no sandbox wake-up. The wire shape here is therefore\n * deliberately small and self-contained: an action id, the form it belongs to,\n * that form's current values, and enough addressing for the product to find the\n * page. Nothing in it references a session, a turn, or a run.\n */\n\nimport { isSafeOpenUIFieldId, type OpenUIFormValues, type OpenUIValue } from './values'\n\n/** What the browser POSTs when an action fires. */\nexport interface OpenUIActionSubmission {\n /** The action's stable id, as authored on the page. */\n actionId: string\n /** The form whose values are attached, when the action sits in one. */\n formId?: string\n /** Current values of that form, keyed by field id. Empty for a bare action. */\n values: OpenUIFormValues\n /** The node the action was rendered on, when the page carries several. */\n nodeId?: string\n /** Vault path of the persisted `render_ui` artifact this page came from. */\n artifactPath?: string\n}\n\n/** Parsed submission, or the reason the body was refused. */\nexport type OpenUIActionBodyValidation =\n | { ok: true; submission: OpenUIActionSubmission }\n | { ok: false; code: OpenUIActionBodyErrorCode; error: string }\n\n/** Why a submission body was refused before any handler ran. */\nexport type OpenUIActionBodyErrorCode =\n | 'OPENUI_ACTION_ID_MISSING'\n | 'OPENUI_ACTION_ID_INVALID'\n | 'OPENUI_FORM_ID_INVALID'\n | 'OPENUI_NODE_ID_INVALID'\n | 'OPENUI_ARTIFACT_PATH_INVALID'\n | 'OPENUI_VALUES_INVALID'\n | 'OPENUI_FIELD_ID_INVALID'\n | 'OPENUI_FIELD_VALUE_INVALID'\n\n/** Ids the host accepts on the wire: identifier-safe, same rule as field ids. */\nexport function isSafeOpenUIActionId(id: string): boolean {\n return isSafeOpenUIFieldId(id)\n}\n\nfunction isOpenUIValue(value: unknown): value is OpenUIValue {\n return (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n (Array.isArray(value) && value.every((entry) => typeof entry === 'string'))\n )\n}\n\nfunction optionalId(\n value: unknown,\n code: OpenUIActionBodyErrorCode,\n label: string,\n): { ok: true; value: string | undefined } | { ok: false; code: OpenUIActionBodyErrorCode; error: string } {\n if (value === undefined || value === null) return { ok: true, value: undefined }\n if (typeof value !== 'string' || !isSafeOpenUIActionId(value)) {\n return { ok: false, code, error: `Invalid ${label}: letters, numbers, underscores, and hyphens only` }\n }\n return { ok: true, value }\n}\n\n/** A vault path is a product-addressed string, not an identifier — bound its\n * length and reject traversal rather than the character class. */\nfunction isSafeArtifactPath(path: string): boolean {\n return path.length > 0 && path.length <= 512 && !path.includes('..') && !path.startsWith('/')\n}\n\n/**\n * Validate a raw JSON body into a submission. Every rejection names a code so\n * the browser can tell \"the page sent something malformed\" from \"the product\n * refused the action\".\n */\nexport function validateOpenUIActionBody(body: Record<string, unknown>): OpenUIActionBodyValidation {\n const actionId = body.actionId\n if (typeof actionId !== 'string' || actionId.trim() === '') {\n return { ok: false, code: 'OPENUI_ACTION_ID_MISSING', error: 'Missing actionId' }\n }\n if (!isSafeOpenUIActionId(actionId)) {\n return {\n ok: false,\n code: 'OPENUI_ACTION_ID_INVALID',\n error: 'Invalid actionId: letters, numbers, underscores, and hyphens only',\n }\n }\n\n const formId = optionalId(body.formId, 'OPENUI_FORM_ID_INVALID', 'formId')\n if (!formId.ok) return formId\n const nodeId = optionalId(body.nodeId, 'OPENUI_NODE_ID_INVALID', 'nodeId')\n if (!nodeId.ok) return nodeId\n\n let artifactPath: string | undefined\n if (body.artifactPath !== undefined && body.artifactPath !== null) {\n if (typeof body.artifactPath !== 'string' || !isSafeArtifactPath(body.artifactPath)) {\n return { ok: false, code: 'OPENUI_ARTIFACT_PATH_INVALID', error: 'Invalid artifactPath' }\n }\n artifactPath = body.artifactPath\n }\n\n const values: OpenUIFormValues = {}\n if (body.values !== undefined && body.values !== null) {\n if (typeof body.values !== 'object' || Array.isArray(body.values)) {\n return { ok: false, code: 'OPENUI_VALUES_INVALID', error: 'Invalid values: expected an object of field values' }\n }\n for (const [key, value] of Object.entries(body.values as Record<string, unknown>)) {\n if (!isSafeOpenUIFieldId(key)) {\n return {\n ok: false,\n code: 'OPENUI_FIELD_ID_INVALID',\n error: 'Invalid values: field names must contain only letters, numbers, underscores, or hyphens',\n }\n }\n if (!isOpenUIValue(value)) {\n return {\n ok: false,\n code: 'OPENUI_FIELD_VALUE_INVALID',\n error: 'Invalid values: field values must be strings, numbers, booleans, or string arrays',\n }\n }\n values[key] = value\n }\n }\n\n return {\n ok: true,\n submission: {\n actionId,\n values,\n ...(formId.value ? { formId: formId.value } : {}),\n ...(nodeId.value ? { nodeId: nodeId.value } : {}),\n ...(artifactPath ? { artifactPath } : {}),\n },\n }\n}\n\nfunction describeValue(value: OpenUIValue): string {\n if (Array.isArray(value)) return value.join(', ')\n return String(value)\n}\n\n/**\n * One plain line recording what the user did, for the product to carry into the\n * NEXT turn's context.\n *\n * The action itself spends no model tokens; without a record of it the agent\n * would later reason about a page the user has already changed. Appending this\n * to the thread (as a note, a system line, or a stored part) is how the agent\n * catches up on the next turn the user actually pays for.\n */\nexport function describeOpenUIAction(submission: OpenUIActionSubmission): string {\n const entries = Object.entries(submission.values)\n const where = submission.formId ? ` on form \"${submission.formId}\"` : ''\n if (entries.length === 0) return `User pressed \"${submission.actionId}\"${where}.`\n const pairs = entries.map(([key, value]) => `${key}=${describeValue(value)}`).join(', ')\n return `User pressed \"${submission.actionId}\"${where} with ${pairs}.`\n}\n","/**\n * The host half of an interactive OpenUI page: one POST endpoint that turns a\n * button press into a product function call.\n *\n * THE SEAM THAT KEEPS IT FREE. This factory has no agent connection, no session\n * id, no sandbox, and no turn — look at {@link OpenUIActionRouteOptions}: the\n * only things a product supplies are an authorizer and a map of plain handlers.\n * There is no seam here through which a model call could be made, which is what\n * makes \"manipulating agent-authored UI costs nothing\" a structural property\n * rather than a promise. Compare `./interactions`, whose answer route exists\n * precisely to unblock a running turn: that one resolves a sidecar connection,\n * and this one cannot.\n *\n * A handler returns data, a replacement page, or a typed failure. If it wants\n * the agent to know what happened, the product records\n * {@link describeOpenUIAction} into the thread — read on the NEXT turn the user\n * chooses to spend, never as a side effect of the click.\n *\n * Handlers return web-standard `Response`s (Workers, Node 18+, Deno).\n */\n\nimport {\n describeOpenUIAction,\n validateOpenUIActionBody,\n type OpenUIActionSubmission,\n} from './action'\nimport type { OpenUINode } from './segments'\nimport {\n validateOpenUIFormValues,\n type OpenUIFieldIssue,\n type OpenUIFormSpec,\n type OpenUIFormValues,\n} from './values'\n\n/** Logging surface the route uses; `console` by default. */\nexport type OpenUIActionLogger = Pick<Console, 'warn' | 'error'>\n\n/** The product's verdict on who is calling. `response` short-circuits with a\n * product-authored Response (401/403/404/429…). */\nexport type OpenUIActionResolution<TContext> =\n | { ok: true; context: TContext }\n | { ok: false; response: Response }\n\n/** What a handler is given: the caller's request, the parsed submission, and\n * whatever the product's authorizer resolved. */\nexport interface OpenUIActionHandlerArgs<TContext> {\n request: Request\n submission: OpenUIActionSubmission\n context: TContext\n}\n\n/** What a handler returns. A replacement `schema` re-renders the page in place;\n * `values` writes corrected/derived values back into the form. */\nexport type OpenUIActionResult<TNode extends OpenUINode = OpenUINode> =\n | {\n ok: true\n /** Short confirmation for the card, in the user's language. */\n message?: string\n /** Values to write back into the form (server-corrected or derived). */\n values?: OpenUIFormValues\n /** A page to render in place of the current one. */\n schema?: TNode | TNode[]\n /** Anything else the client should read (totals, ids, links). */\n data?: Record<string, unknown>\n }\n | {\n ok: false\n /** Machine-readable reason, surfaced to the client verbatim. */\n code: string\n /** One sentence the user can act on. */\n message: string\n /** HTTP status; defaults to 400. */\n status?: number\n /** Field-level rejections, so the card can mark the offending inputs. */\n issues?: OpenUIFieldIssue[]\n }\n\n/** One product action, keyed in {@link OpenUIActionRouteOptions.actions} by the\n * `action.id` the agent authored on the page. */\nexport type OpenUIActionHandler<TContext, TNode extends OpenUINode = OpenUINode> = (\n args: OpenUIActionHandlerArgs<TContext>,\n) => OpenUIActionResult<TNode> | Promise<OpenUIActionResult<TNode>>\n\n/** How the route is wired. Note what is absent: nothing here can reach a model. */\nexport interface OpenUIActionRouteOptions<TContext, TNode extends OpenUINode = OpenUINode> {\n /**\n * Authenticate and authorize the caller, and resolve whatever the handlers\n * need (db handle, workspace, user). The only product-supplied gate.\n */\n resolve: (args: {\n request: Request\n submission: OpenUIActionSubmission\n }) => OpenUIActionResolution<TContext> | Promise<OpenUIActionResolution<TContext>>\n /** Handlers by action id. An id with no handler is a 404, never a no-op. */\n actions: Record<string, OpenUIActionHandler<TContext, TNode>>\n /**\n * Form specs by form id. When the submission names a form listed here, its\n * values are checked against the spec before the handler runs, and rejections\n * come back as field issues. Omit a form to leave checking to its handler.\n */\n forms?: Record<string, OpenUIFormSpec>\n /**\n * Called after a successful handler with the line the agent should read on\n * its next turn. Persist it against the thread; do NOT start a turn from it.\n */\n recordForAgent?: (args: {\n request: Request\n submission: OpenUIActionSubmission\n context: TContext\n note: string\n }) => void | Promise<void>\n logger?: OpenUIActionLogger\n}\n\n/** The endpoint a product mounts. */\nexport interface OpenUIActionRoute {\n /** POST `{ actionId, formId?, values?, nodeId?, artifactPath? }`. */\n handle: (request: Request) => Promise<Response>\n}\n\nfunction failure(code: string, error: string, status: number, extra?: Record<string, unknown>): Response {\n return Response.json({ ok: false, code, error, ...(extra ?? {}) }, { status })\n}\n\n/**\n * Build the action endpoint for agent-authored pages.\n *\n * ```ts\n * const route = createOpenUIActionRoute({\n * resolve: async ({ request }) => {\n * const session = await auth(request)\n * if (!session) return { ok: false, response: new Response('Unauthorized', { status: 401 }) }\n * return { ok: true, context: { db, workspaceId: session.workspaceId } }\n * },\n * forms: { deduction_form: DEDUCTION_FORM },\n * actions: {\n * recalculate: async ({ submission, context }) => {\n * const totals = recompute(context.db, submission.values)\n * return { ok: true, data: totals, schema: totalsPage(totals) }\n * },\n * },\n * })\n * export const action = ({ request }: ActionFunctionArgs) => route.handle(request)\n * ```\n */\nexport function createOpenUIActionRoute<TContext, TNode extends OpenUINode = OpenUINode>(\n options: OpenUIActionRouteOptions<TContext, TNode>,\n): OpenUIActionRoute {\n const logger = options.logger ?? console\n\n async function handle(request: Request): Promise<Response> {\n if (request.method !== 'POST') return failure('OPENUI_METHOD_NOT_ALLOWED', 'Method not allowed', 405)\n\n const body = (await request.json().catch(() => null)) as Record<string, unknown> | null\n if (!body || typeof body !== 'object' || Array.isArray(body)) {\n return failure('OPENUI_BODY_INVALID', 'Invalid JSON body', 400)\n }\n\n const parsed = validateOpenUIActionBody(body)\n if (!parsed.ok) return failure(parsed.code, parsed.error, 400)\n const submission = parsed.submission\n\n // Unknown ids are refused before the authorizer runs: a page that names an\n // action the product never registered is a broken page, and answering it\n // 404 is what makes that visible instead of a button that does nothing.\n const handler = Object.prototype.hasOwnProperty.call(options.actions, submission.actionId)\n ? options.actions[submission.actionId]\n : undefined\n if (!handler) {\n return failure(\n 'OPENUI_ACTION_UNKNOWN',\n `No handler is registered for \"${submission.actionId}\".`,\n 404,\n { actionId: submission.actionId },\n )\n }\n\n const resolution = await options.resolve({ request, submission })\n if (!resolution.ok) return resolution.response\n\n const spec =\n submission.formId && options.forms\n ? Object.prototype.hasOwnProperty.call(options.forms, submission.formId)\n ? options.forms[submission.formId]\n : undefined\n : undefined\n let values = submission.values\n if (spec) {\n const checked = validateOpenUIFormValues(spec, submission.values)\n if (!checked.ok) {\n return failure('OPENUI_VALUES_REJECTED', 'Some fields need fixing before this can run.', 422, {\n issues: checked.issues,\n })\n }\n values = checked.values\n }\n\n const checkedSubmission: OpenUIActionSubmission = { ...submission, values }\n\n let result: OpenUIActionResult<TNode>\n try {\n result = await handler({ request, submission: checkedSubmission, context: resolution.context })\n } catch (error) {\n logger.error('[openui] action handler failed:', error)\n return failure('OPENUI_ACTION_FAILED', 'That action could not be completed. Try again.', 500, {\n actionId: submission.actionId,\n })\n }\n\n if (!result.ok) {\n return failure(result.code, result.message, result.status ?? 400, {\n actionId: submission.actionId,\n ...(result.issues ? { issues: result.issues } : {}),\n })\n }\n\n if (options.recordForAgent) {\n try {\n await options.recordForAgent({\n request,\n submission: checkedSubmission,\n context: resolution.context,\n note: describeOpenUIAction(checkedSubmission),\n })\n } catch (error) {\n // The user's action already succeeded. Losing the agent-facing note\n // degrades the next turn's context; it must not fail the click.\n logger.warn('[openui] recordForAgent failed:', error)\n }\n }\n\n return Response.json({\n ok: true,\n actionId: submission.actionId,\n ...(result.message ? { message: result.message } : {}),\n ...(result.values ? { values: result.values } : {}),\n ...(result.schema ? { schema: result.schema } : {}),\n ...(result.data ? { data: result.data } : {}),\n })\n }\n\n return { handle }\n}\n"],"mappings":";;;;;;AA0BA,IAAM,QAAQ;AAEd,SAAS,WAAW,OAAyB;AAC3C,SACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,KAAK,KACpB,OAAQ,MAA6B,SAAS;AAElD;AAGA,SAAS,UAAU,QAA4B;AAC7C,QAAM,aAAa,MAAM,QAAQ,MAAM,IAAI,SAAS,CAAC,MAAM;AAC3D,SAAO,WAAW,OAAO,UAAU;AACrC;AAEA,SAAS,SAAmC,UAAuC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AAI;AACd,aAAO,QAAQ,OAAO,MAAM,OAAO,SAAS,OAAO,UAAU,KAAK;AAAA,QAChE,UAAU,WAAW;AAAA,QACrB,GAAI,OAAO,SAAS,EAAE,QAAQ,OAAO,OAAO,IAAI,CAAC;AAAA,MACnD,CAAC;AAAA,IACH;AAEA,QAAI,QAAQ,gBAAgB;AAC1B,UAAI;AACF,cAAM,QAAQ,eAAe;AAAA,UAC3B;AAAA,UACA,YAAY;AAAA,UACZ,SAAS,WAAW;AAAA,UACpB,MAAM,qBAAqB,iBAAiB;AAAA,QAC9C,CAAC;AAAA,MACH,SAAS,OAAO;AAGd,eAAO,KAAK,mCAAmC,KAAK;AAAA,MACtD;AAAA,IACF;AAEA,WAAO,SAAS,KAAK;AAAA,MACnB,IAAI;AAAA,MACJ,UAAU,WAAW;AAAA,MACrB,GAAI,OAAO,UAAU,EAAE,SAAS,OAAO,QAAQ,IAAI,CAAC;AAAA,MACpD,GAAI,OAAO,SAAS,EAAE,QAAQ,OAAO,OAAO,IAAI,CAAC;AAAA,MACjD,GAAI,OAAO,SAAS,EAAE,QAAQ,OAAO,OAAO,IAAI,CAAC;AAAA,MACjD,GAAI,OAAO,OAAO,EAAE,MAAM,OAAO,KAAK,IAAI,CAAC;AAAA,IAC7C,CAAC;AAAA,EACH;AAEA,SAAO,EAAE,OAAO;AAClB;","names":[]}
@@ -0,0 +1,119 @@
1
+ import { O as OpenUIFormValues, a as OpenUIFieldIssue, b as OpenUINode, c as OpenUIValue } from '../values-C7RidJuI.js';
2
+
3
+ /**
4
+ * `@tangle-network/agent-app/openui-react` — the missing `onAction`.
5
+ *
6
+ * The OpenUI renderer takes an `onAction` handler and does nothing when the
7
+ * host omits it, which is what left every button on an agent-authored page
8
+ * inert. This hook is the handler: it holds the page's field values, posts a
9
+ * pressed action to ONE product REST endpoint, and hands back the reply —
10
+ * a message, corrected values, a replacement page.
11
+ *
12
+ * It reaches the product route and nothing else. There is no chat stream here,
13
+ * no turn start, no sandbox: a user dragging a slider on a page the agent wrote
14
+ * costs exactly one product request, the same as a hand-built screen. Tests
15
+ * enforce that by walking this module's imports.
16
+ */
17
+
18
+ /** A successful action reply, as the route sends it. */
19
+ interface OpenUIActionResponse<TNode extends OpenUINode = OpenUINode> {
20
+ ok: true;
21
+ actionId: string;
22
+ message?: string;
23
+ values?: OpenUIFormValues;
24
+ schema?: TNode | TNode[];
25
+ data?: Record<string, unknown>;
26
+ }
27
+ /** A refused action, as the route sends it. */
28
+ interface OpenUIActionFailure {
29
+ code: string;
30
+ error: string;
31
+ actionId?: string;
32
+ issues?: OpenUIFieldIssue[];
33
+ }
34
+ /** The boundary outcome: the reply, or the reason there is none. */
35
+ type OpenUIActionOutcome<TNode extends OpenUINode = OpenUINode> = {
36
+ succeeded: true;
37
+ value: OpenUIActionResponse<TNode>;
38
+ } | {
39
+ succeeded: false;
40
+ error: OpenUIActionFailure;
41
+ };
42
+ /** Where on the page an action fired, and what the form held at that moment.
43
+ * A renderer that owns form state passes `values`; otherwise the hook's own
44
+ * `values` are sent. */
45
+ interface OpenUIActionContext {
46
+ formId?: string;
47
+ nodeId?: string;
48
+ values?: OpenUIFormValues;
49
+ }
50
+ /** How the hook talks to the product route. */
51
+ interface UseOpenUIActionsOptions<TNode extends OpenUINode = OpenUINode> {
52
+ /** The product's action endpoint — a plain REST route, never a chat route. */
53
+ endpoint: string;
54
+ /** Extra routing fields merged into every POST body (workspaceId, threadId).
55
+ * Reserved keys (`actionId`, `formId`, `values`, `nodeId`, `artifactPath`)
56
+ * always win. */
57
+ body?: Record<string, string | number | boolean>;
58
+ /** Vault path of the persisted page, when the product renders one. */
59
+ artifactPath?: string;
60
+ /** Seed values, e.g. the `value` each field was authored with. */
61
+ initialValues?: OpenUIFormValues;
62
+ headers?: Record<string, string>;
63
+ /** Injection seam for tests; defaults to global `fetch`. */
64
+ fetchImpl?: typeof fetch;
65
+ /** Called with every settled outcome, success or failure. */
66
+ onResult?: (outcome: OpenUIActionOutcome<TNode>) => void;
67
+ }
68
+ /** What the hook returns. `onAction` is the renderer prop; the rest is state a
69
+ * card renders around it. */
70
+ interface OpenUIActionsController<TNode extends OpenUINode = OpenUINode> {
71
+ /** Current field values. */
72
+ values: OpenUIFormValues;
73
+ /** Set one field. */
74
+ setValue: (fieldId: string, value: OpenUIValue) => void;
75
+ /** Replace all fields. */
76
+ setValues: (next: OpenUIFormValues) => void;
77
+ /** Back to `initialValues`. */
78
+ resetValues: () => void;
79
+ /**
80
+ * Pass straight to the renderer's `onAction`. Fire-and-forget; read the
81
+ * result from this controller's state or from `onResult`.
82
+ */
83
+ onAction: (action: {
84
+ id: string;
85
+ }, context?: OpenUIActionContext) => void;
86
+ /** The awaitable form of `onAction`, for a product's own buttons. */
87
+ submit: (action: {
88
+ id: string;
89
+ }, context?: OpenUIActionContext) => Promise<OpenUIActionOutcome<TNode>>;
90
+ /** The action currently in flight, if any. */
91
+ pendingActionId: string | null;
92
+ /** The last failure, cleared when the next action starts. */
93
+ error: OpenUIActionFailure | null;
94
+ /** The last success message, cleared when the next action starts. */
95
+ message: string | null;
96
+ /** A replacement page from the last success, to render instead of the original. */
97
+ schema: TNode[] | null;
98
+ /** Free-form payload from the last success. */
99
+ data: Record<string, unknown> | null;
100
+ }
101
+ /**
102
+ * Make an agent-authored page interactive.
103
+ *
104
+ * ```tsx
105
+ * const ui = useOpenUIActions({ endpoint: '/api/openui/action', body: { workspaceId } })
106
+ * <OpenUIArtifactRenderer schema={ui.schema ?? nodes} onAction={ui.onAction} />
107
+ * {ui.error && <p role="alert">{ui.error.error}</p>}
108
+ * ```
109
+ *
110
+ * One action runs at a time: pressing a second button while the first is in
111
+ * flight is refused with `OPENUI_ACTION_BUSY` rather than racing two writes
112
+ * against the same form.
113
+ */
114
+ declare function useOpenUIActions<TNode extends OpenUINode = OpenUINode>(options: UseOpenUIActionsOptions<TNode>): OpenUIActionsController<TNode>;
115
+ /** The body keys the hook owns; a product's extra `body` fields cannot shadow
116
+ * them. Exported so a route's own tests can assert the same list. */
117
+ declare const OPENUI_RESERVED_BODY_KEYS: readonly string[];
118
+
119
+ export { OPENUI_RESERVED_BODY_KEYS, type OpenUIActionContext, type OpenUIActionFailure, type OpenUIActionOutcome, type OpenUIActionResponse, type OpenUIActionsController, type UseOpenUIActionsOptions, useOpenUIActions };