@cheerlyai/agentlib-protocol 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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Cheerly AI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,77 @@
1
+ # @cheerlyai/agentlib-protocol
2
+
3
+ Parsers for the conventions agentlib layers on top of the Vercel AI SDK
4
+ stream. Zero dependencies, no DOM — usable from React, Vue, Svelte, a Node
5
+ service rendering a transcript, or a test.
6
+
7
+ ```bash
8
+ npm install @cheerlyai/agentlib-protocol
9
+ ```
10
+
11
+ ## Why it exists
12
+
13
+ The stream is standard: text deltas, tool parts, reasoning, step markers. But
14
+ two things an agent can produce travel *inside* the assistant's text rather
15
+ than as protocol parts, because that is what makes them degrade gracefully — a
16
+ client that knows nothing about them still shows a readable reply instead of a
17
+ hole.
18
+
19
+ A chatbox that doesn't handle them looks broken: **raw JSON** where a chart
20
+ should be, a **dangling heading** where citations should be.
21
+
22
+ ## Charts
23
+
24
+ Agents with charts enabled are instructed to write a ```chart fenced block of
25
+ JSON on a fixed schema. Parse it inside your markdown renderer's code-block
26
+ handler:
27
+
28
+ ```ts
29
+ import { parseChartSpec, CHART_LANGUAGE } from "@cheerlyai/agentlib-protocol";
30
+
31
+ const spec = parseChartSpec(fenceContents);
32
+ // null => not a drawable chart. Render the code block instead: a
33
+ // half-streamed or malformed one is still readable as JSON.
34
+ ```
35
+
36
+ `ChartSpec` is `{ type, title?, unit?, x, series }`, where `type` is one of
37
+ `bar`, `line`, `area`, `stacked_bar`. Validation is strict about the things
38
+ that would make a chart lie — a series whose values don't line up with the
39
+ axis is rejected outright — and caps at 8 series, past which hue stops
40
+ identifying anything.
41
+
42
+ ## Sources
43
+
44
+ Agents with a knowledge base are instructed to end a reply with a `Sources:`
45
+ section. Split it off so it renders as citations rather than trailing prose:
46
+
47
+ ```ts
48
+ import { splitReply } from "@cheerlyai/agentlib-protocol";
49
+
50
+ const { body, sources } = splitReply(text);
51
+ ```
52
+
53
+ `sources` is null when there is none — and also while a heading has arrived
54
+ but its list has not, so a "Sources" label never flashes above an empty box
55
+ mid-stream. Recognises `Sources:`, `**Sources**`, `## Sources` and friends,
56
+ because a model asked for a section in prose writes it differently every few
57
+ runs.
58
+
59
+ ## Parts
60
+
61
+ ```ts
62
+ import { isToolPart, toolPartName, OUTPUT_TOOL_PART, RUN_INFO_PART } from "@cheerlyai/agentlib-protocol";
63
+ ```
64
+
65
+ `isToolPart` covers both shapes the protocol uses (`tool-<name>` and
66
+ `dynamic-tool`). `OUTPUT_TOOL_PART` is the part carrying the reply of an agent
67
+ with output fields — it arrives as tool activity, so a renderer that files it
68
+ under "tools" hides the answer. `RUN_INFO_PART` is agentlib's trailer: read it
69
+ via `useChat`'s `onData` and skip it when rendering.
70
+
71
+ Anything you don't recognise must fall through to nothing rendered.
72
+
73
+ ## Already handled for you
74
+
75
+ [`@cheerlyai/agentlib-react`](../react) and the script widget do all of this. Reach for
76
+ this package when you are building the UI yourself, or on a stack they don't
77
+ cover.
package/dist/index.cjs ADDED
@@ -0,0 +1,85 @@
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 src_exports = {};
22
+ __export(src_exports, {
23
+ CHART_LANGUAGE: () => CHART_LANGUAGE,
24
+ OUTPUT_TOOL_PART: () => OUTPUT_TOOL_PART,
25
+ RUN_INFO_PART: () => RUN_INFO_PART,
26
+ isToolPart: () => isToolPart,
27
+ parseChartSpec: () => parseChartSpec,
28
+ splitReply: () => splitReply,
29
+ toolPartName: () => toolPartName
30
+ });
31
+ module.exports = __toCommonJS(src_exports);
32
+ var CHART_LANGUAGE = "chart";
33
+ var CHART_TYPES = ["bar", "line", "area", "stacked_bar"];
34
+ var MAX_SERIES = 8;
35
+ function parseChartSpec(raw) {
36
+ let value;
37
+ try {
38
+ value = JSON.parse(raw);
39
+ } catch {
40
+ return null;
41
+ }
42
+ if (typeof value !== "object" || value === null) return null;
43
+ const spec = value;
44
+ if (typeof spec.type !== "string" || !CHART_TYPES.includes(spec.type)) return null;
45
+ if (!Array.isArray(spec.x) || spec.x.length === 0) return null;
46
+ if (!Array.isArray(spec.series) || spec.series.length === 0) return null;
47
+ const x = spec.x.map(String);
48
+ const series = [];
49
+ for (const entry of spec.series.slice(0, MAX_SERIES)) {
50
+ if (typeof entry !== "object" || entry === null) return null;
51
+ const s = entry;
52
+ if (!Array.isArray(s.values)) return null;
53
+ const values = s.values.map(
54
+ (v) => typeof v === "number" && Number.isFinite(v) ? v : NaN
55
+ );
56
+ if (values.length !== x.length || values.some(Number.isNaN)) return null;
57
+ series.push({ label: typeof s.label === "string" ? s.label : "", values });
58
+ }
59
+ if (series.length === 0) return null;
60
+ return {
61
+ type: spec.type,
62
+ title: typeof spec.title === "string" ? spec.title : void 0,
63
+ unit: typeof spec.unit === "string" ? spec.unit : void 0,
64
+ x,
65
+ series
66
+ };
67
+ }
68
+ var SOURCES_HEADING = /(?:^|\n)\s{0,3}(?:#{1,6}\s*)?(?:\*\*)?Sources\s*:?(?:\*\*)?\s*:?\s*(?:\n|$)/gi;
69
+ function splitReply(text) {
70
+ const re = new RegExp(SOURCES_HEADING.source, SOURCES_HEADING.flags);
71
+ let last = null;
72
+ for (let m; m = re.exec(text); ) last = m;
73
+ if (!last) return { body: text, sources: null };
74
+ const sources = text.slice(last.index + last[0].length).trim();
75
+ if (!sources) return { body: text, sources: null };
76
+ return { body: text.slice(0, last.index).trimEnd(), sources };
77
+ }
78
+ function isToolPart(type) {
79
+ return type.startsWith("tool-") || type === "dynamic-tool";
80
+ }
81
+ function toolPartName(part) {
82
+ return part.type === "dynamic-tool" ? part.toolName ?? "tool" : part.type.slice("tool-".length);
83
+ }
84
+ var OUTPUT_TOOL_PART = "tool-answer";
85
+ var RUN_INFO_PART = "data-run-info";
@@ -0,0 +1,86 @@
1
+ /** The conventions agentlib layers on top of the Vercel AI SDK stream.
2
+ *
3
+ * The stream itself is standard: text deltas, tool parts, reasoning, step
4
+ * markers. But two things an agent can produce travel *inside* the assistant's
5
+ * text rather than as protocol parts, because that is what makes them
6
+ * degrade gracefully — a client that knows nothing about them still shows a
7
+ * readable reply instead of a hole:
8
+ *
9
+ * - **Charts** arrive as a ```chart fenced block of JSON on a fixed schema.
10
+ * - **Sources** arrive as a trailing `Sources:` section.
11
+ *
12
+ * Both are written by the model because its instructions ask it to, which
13
+ * means neither is guaranteed to be well-formed. Every function here is
14
+ * tolerant: it returns null (or leaves the text alone) rather than throwing,
15
+ * so a half-streamed block or a hallucinated field costs you a chart, never
16
+ * the reply around it.
17
+ *
18
+ * Zero dependencies and no DOM, so the same parsing runs in a React app, a
19
+ * Vue one, a Node service rendering a transcript, or a test.
20
+ */
21
+ /** A chart an agent asked for, validated. */
22
+ type ChartSpec = {
23
+ type: "bar" | "line" | "area" | "stacked_bar";
24
+ title?: string;
25
+ unit?: string;
26
+ x: string[];
27
+ series: {
28
+ label: string;
29
+ values: number[];
30
+ }[];
31
+ };
32
+ /** The language tag on the fenced block agents use for charts. */
33
+ declare const CHART_LANGUAGE = "chart";
34
+ /** Parse a ```chart block's contents.
35
+ *
36
+ * Returns null for anything that isn't a chart that can be drawn honestly — a
37
+ * half-streamed block, a hallucinated field, a series whose values do not line
38
+ * up with the axis. Render the block as code when this returns null: JSON is
39
+ * readable, a thrown exception is not.
40
+ */
41
+ declare function parseChartSpec(raw: string): ChartSpec | null;
42
+ /** An assistant reply split into its prose and its citations. */
43
+ type SplitReply = {
44
+ /** The answer, with the sources section removed. */
45
+ body: string;
46
+ /** The markdown of the sources section, or null when there is none. */
47
+ sources: string | null;
48
+ };
49
+ /** Split a reply's trailing `Sources:` section off from its prose.
50
+ *
51
+ * Safe to call on every render, including mid-stream: while the heading has
52
+ * arrived but its list has not, the text is returned untouched, so a
53
+ * "Sources" label never flashes above an empty box.
54
+ *
55
+ * The *last* heading wins — an answer that discusses the word "sources"
56
+ * earlier should not have its body truncated at that mention.
57
+ */
58
+ declare function splitReply(text: string): SplitReply;
59
+ /** Whether a stream part is tool activity, under either of the protocol's two
60
+ * shapes: `tool-<name>` for a declared tool, `dynamic-tool` for one resolved
61
+ * at run time (an MCP server's, say). */
62
+ declare function isToolPart(type: string): boolean;
63
+ /** The tool's name, for a part `isToolPart` accepts. */
64
+ declare function toolPartName(part: {
65
+ type: string;
66
+ toolName?: string;
67
+ }): string;
68
+ /** The part carrying the reply of an agent configured with `output_fields`.
69
+ *
70
+ * Such an agent answers by calling its output tool, so its reply arrives as
71
+ * tool activity rather than as text. A client that files it under "tools"
72
+ * renders a collapsed "Used answer" — the answer itself, hidden — and one
73
+ * that ignores tool parts shows an empty bubble. Treat this part as the
74
+ * reply. (The embed API refuses these agents outright for that reason; on
75
+ * `/v1/agents/{id}/chat` they are yours to render.)
76
+ */
77
+ declare const OUTPUT_TOOL_PART = "tool-answer";
78
+ /** agentlib's trailing data part: run config, usage, and the conversation id.
79
+ *
80
+ * It rides in `message.parts` like anything else, so a renderer with no
81
+ * default case will show it as an unknown blob. Read it via `useChat`'s
82
+ * `onData` and skip it when rendering.
83
+ */
84
+ declare const RUN_INFO_PART = "data-run-info";
85
+
86
+ export { CHART_LANGUAGE, type ChartSpec, OUTPUT_TOOL_PART, RUN_INFO_PART, type SplitReply, isToolPart, parseChartSpec, splitReply, toolPartName };
@@ -0,0 +1,86 @@
1
+ /** The conventions agentlib layers on top of the Vercel AI SDK stream.
2
+ *
3
+ * The stream itself is standard: text deltas, tool parts, reasoning, step
4
+ * markers. But two things an agent can produce travel *inside* the assistant's
5
+ * text rather than as protocol parts, because that is what makes them
6
+ * degrade gracefully — a client that knows nothing about them still shows a
7
+ * readable reply instead of a hole:
8
+ *
9
+ * - **Charts** arrive as a ```chart fenced block of JSON on a fixed schema.
10
+ * - **Sources** arrive as a trailing `Sources:` section.
11
+ *
12
+ * Both are written by the model because its instructions ask it to, which
13
+ * means neither is guaranteed to be well-formed. Every function here is
14
+ * tolerant: it returns null (or leaves the text alone) rather than throwing,
15
+ * so a half-streamed block or a hallucinated field costs you a chart, never
16
+ * the reply around it.
17
+ *
18
+ * Zero dependencies and no DOM, so the same parsing runs in a React app, a
19
+ * Vue one, a Node service rendering a transcript, or a test.
20
+ */
21
+ /** A chart an agent asked for, validated. */
22
+ type ChartSpec = {
23
+ type: "bar" | "line" | "area" | "stacked_bar";
24
+ title?: string;
25
+ unit?: string;
26
+ x: string[];
27
+ series: {
28
+ label: string;
29
+ values: number[];
30
+ }[];
31
+ };
32
+ /** The language tag on the fenced block agents use for charts. */
33
+ declare const CHART_LANGUAGE = "chart";
34
+ /** Parse a ```chart block's contents.
35
+ *
36
+ * Returns null for anything that isn't a chart that can be drawn honestly — a
37
+ * half-streamed block, a hallucinated field, a series whose values do not line
38
+ * up with the axis. Render the block as code when this returns null: JSON is
39
+ * readable, a thrown exception is not.
40
+ */
41
+ declare function parseChartSpec(raw: string): ChartSpec | null;
42
+ /** An assistant reply split into its prose and its citations. */
43
+ type SplitReply = {
44
+ /** The answer, with the sources section removed. */
45
+ body: string;
46
+ /** The markdown of the sources section, or null when there is none. */
47
+ sources: string | null;
48
+ };
49
+ /** Split a reply's trailing `Sources:` section off from its prose.
50
+ *
51
+ * Safe to call on every render, including mid-stream: while the heading has
52
+ * arrived but its list has not, the text is returned untouched, so a
53
+ * "Sources" label never flashes above an empty box.
54
+ *
55
+ * The *last* heading wins — an answer that discusses the word "sources"
56
+ * earlier should not have its body truncated at that mention.
57
+ */
58
+ declare function splitReply(text: string): SplitReply;
59
+ /** Whether a stream part is tool activity, under either of the protocol's two
60
+ * shapes: `tool-<name>` for a declared tool, `dynamic-tool` for one resolved
61
+ * at run time (an MCP server's, say). */
62
+ declare function isToolPart(type: string): boolean;
63
+ /** The tool's name, for a part `isToolPart` accepts. */
64
+ declare function toolPartName(part: {
65
+ type: string;
66
+ toolName?: string;
67
+ }): string;
68
+ /** The part carrying the reply of an agent configured with `output_fields`.
69
+ *
70
+ * Such an agent answers by calling its output tool, so its reply arrives as
71
+ * tool activity rather than as text. A client that files it under "tools"
72
+ * renders a collapsed "Used answer" — the answer itself, hidden — and one
73
+ * that ignores tool parts shows an empty bubble. Treat this part as the
74
+ * reply. (The embed API refuses these agents outright for that reason; on
75
+ * `/v1/agents/{id}/chat` they are yours to render.)
76
+ */
77
+ declare const OUTPUT_TOOL_PART = "tool-answer";
78
+ /** agentlib's trailing data part: run config, usage, and the conversation id.
79
+ *
80
+ * It rides in `message.parts` like anything else, so a renderer with no
81
+ * default case will show it as an unknown blob. Read it via `useChat`'s
82
+ * `onData` and skip it when rendering.
83
+ */
84
+ declare const RUN_INFO_PART = "data-run-info";
85
+
86
+ export { CHART_LANGUAGE, type ChartSpec, OUTPUT_TOOL_PART, RUN_INFO_PART, type SplitReply, isToolPart, parseChartSpec, splitReply, toolPartName };
package/dist/index.js ADDED
@@ -0,0 +1,64 @@
1
+ // src/index.ts
2
+ var CHART_LANGUAGE = "chart";
3
+ var CHART_TYPES = ["bar", "line", "area", "stacked_bar"];
4
+ var MAX_SERIES = 8;
5
+ function parseChartSpec(raw) {
6
+ let value;
7
+ try {
8
+ value = JSON.parse(raw);
9
+ } catch {
10
+ return null;
11
+ }
12
+ if (typeof value !== "object" || value === null) return null;
13
+ const spec = value;
14
+ if (typeof spec.type !== "string" || !CHART_TYPES.includes(spec.type)) return null;
15
+ if (!Array.isArray(spec.x) || spec.x.length === 0) return null;
16
+ if (!Array.isArray(spec.series) || spec.series.length === 0) return null;
17
+ const x = spec.x.map(String);
18
+ const series = [];
19
+ for (const entry of spec.series.slice(0, MAX_SERIES)) {
20
+ if (typeof entry !== "object" || entry === null) return null;
21
+ const s = entry;
22
+ if (!Array.isArray(s.values)) return null;
23
+ const values = s.values.map(
24
+ (v) => typeof v === "number" && Number.isFinite(v) ? v : NaN
25
+ );
26
+ if (values.length !== x.length || values.some(Number.isNaN)) return null;
27
+ series.push({ label: typeof s.label === "string" ? s.label : "", values });
28
+ }
29
+ if (series.length === 0) return null;
30
+ return {
31
+ type: spec.type,
32
+ title: typeof spec.title === "string" ? spec.title : void 0,
33
+ unit: typeof spec.unit === "string" ? spec.unit : void 0,
34
+ x,
35
+ series
36
+ };
37
+ }
38
+ var SOURCES_HEADING = /(?:^|\n)\s{0,3}(?:#{1,6}\s*)?(?:\*\*)?Sources\s*:?(?:\*\*)?\s*:?\s*(?:\n|$)/gi;
39
+ function splitReply(text) {
40
+ const re = new RegExp(SOURCES_HEADING.source, SOURCES_HEADING.flags);
41
+ let last = null;
42
+ for (let m; m = re.exec(text); ) last = m;
43
+ if (!last) return { body: text, sources: null };
44
+ const sources = text.slice(last.index + last[0].length).trim();
45
+ if (!sources) return { body: text, sources: null };
46
+ return { body: text.slice(0, last.index).trimEnd(), sources };
47
+ }
48
+ function isToolPart(type) {
49
+ return type.startsWith("tool-") || type === "dynamic-tool";
50
+ }
51
+ function toolPartName(part) {
52
+ return part.type === "dynamic-tool" ? part.toolName ?? "tool" : part.type.slice("tool-".length);
53
+ }
54
+ var OUTPUT_TOOL_PART = "tool-answer";
55
+ var RUN_INFO_PART = "data-run-info";
56
+ export {
57
+ CHART_LANGUAGE,
58
+ OUTPUT_TOOL_PART,
59
+ RUN_INFO_PART,
60
+ isToolPart,
61
+ parseChartSpec,
62
+ splitReply,
63
+ toolPartName
64
+ };
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@cheerlyai/agentlib-protocol",
3
+ "version": "0.1.0",
4
+ "description": "Parsers for the conventions agentlib layers on the Vercel AI SDK stream — chart blocks and source sections. Framework-agnostic, zero dependencies.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.cjs",
8
+ "module": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js",
14
+ "require": "./dist/index.cjs"
15
+ }
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "sideEffects": false,
24
+ "scripts": {
25
+ "build": "tsup",
26
+ "lint": "tsc --noEmit"
27
+ },
28
+ "devDependencies": {
29
+ "tsup": "^8.5.0",
30
+ "typescript": "^5.9.3"
31
+ }
32
+ }