Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"check": "pnpm typecheck && pnpm test && pnpm test:go && pnpm build && pnpm pack:packages && pnpm smoke:consumer && pnpm smoke:cloudflare",
"clean": "pnpm -r clean",
"pack:packages": "mkdir -p .packs && pnpm -r --filter './packages/*' pack --pack-destination ./.packs",
"publish:packages": "pnpm --filter @better-matrix-js/cloudflare publish --access public --no-git-checks && pnpm --filter better-matrix-js publish --access public --no-git-checks && pnpm --filter @better-matrix-js/chat-adapter publish --access public --no-git-checks",
"publish:packages": "pnpm --filter @better-matrix-js/cloudflare publish --access public --no-git-checks && pnpm --filter better-matrix-js publish --access public --no-git-checks && pnpm --filter @better-matrix-js/chat-adapter publish --access public --no-git-checks && pnpm --filter @better-matrix-js/ai-sdk publish --access public --no-git-checks",
"smoke:cloudflare": "node scripts/smoke-cloudflare-worker.mjs",
"smoke:consumer": "node scripts/package-consumer-smoke.mjs",
"smoke:package-consumer": "node scripts/package-consumer-smoke.mjs",
Expand Down
21 changes: 21 additions & 0 deletions packages/ai-sdk/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
5 changes: 5 additions & 0 deletions packages/ai-sdk/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# @better-matrix-js/ai-sdk

AI SDK stream adapters for `better-matrix-js`.

This package is separate from `@better-matrix-js/chat-adapter` so Matrix and Chat SDK users do not need the AI SDK integration unless they want it.
59 changes: 59 additions & 0 deletions packages/ai-sdk/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
{
"name": "@better-matrix-js/ai-sdk",
"version": "0.1.0",
"description": "AI SDK stream adapters for better-matrix-js",
"type": "module",
"homepage": "https://github.com/batuhan/better-matrix-js#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/batuhan/better-matrix-js.git",
"directory": "packages/ai-sdk"
},
"bugs": {
"url": "https://github.com/batuhan/better-matrix-js/issues"
},
"main": "./dist/index.js",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"files": [
"dist",
"README.md",
"LICENSE"
],
"publishConfig": {
"access": "public"
},
"scripts": {
"build": "tsup",
"clean": "rm -rf dist",
"prepublishOnly": "node ../../scripts/guard-pnpm-publish.mjs",
"test": "vitest run --coverage",
"typecheck": "tsc --noEmit"
},
"peerDependencies": {
"@better-matrix-js/chat-adapter": "^0.1.0"
},
"devDependencies": {
"@better-matrix-js/chat-adapter": "workspace:*",
"@types/node": "^25.3.2",
"tsup": "^8.3.5",
"typescript": "^5.7.2",
"vitest": "^4.0.18"
},
"keywords": [
"matrix",
"ai-sdk",
"streaming",
"beeper"
],
"engines": {
"node": ">=20"
},
"license": "MIT"
}
55 changes: 55 additions & 0 deletions packages/ai-sdk/src/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { describe, expect, it } from "vitest";
import { fromAIStreamResult, fromAIUIMessageStream, isAIUIMessageStreamResult } from "./index";

async function collect<T>(iterable: AsyncIterable<T>): Promise<T[]> {
const values: T[] = [];
for await (const value of iterable) {
values.push(value);
}
return values;
}

describe("AI SDK stream adapters", () => {
it("passes async iterable UI message chunks through structurally", async () => {
async function* chunks() {
yield { delta: "hello", id: "text-1", type: "text-delta" };
}

await expect(collect(fromAIUIMessageStream(chunks()))).resolves.toEqual([
{ delta: "hello", id: "text-1", type: "text-delta" },
]);
});

it("converts ReadableStream UI message chunks to async iterable Matrix streams", async () => {
const stream = new ReadableStream({
start(controller) {
controller.enqueue({ id: "reasoning-1", type: "reasoning-start" });
controller.enqueue({ delta: "thinking", id: "reasoning-1", type: "reasoning-delta" });
controller.close();
},
});

await expect(collect(fromAIUIMessageStream(stream))).resolves.toEqual([
{ id: "reasoning-1", type: "reasoning-start" },
{ delta: "thinking", id: "reasoning-1", type: "reasoning-delta" },
]);
});

it("accepts streamText-like results with toUIMessageStream", async () => {
const result = {
toUIMessageStream() {
return new ReadableStream({
start(controller) {
controller.enqueue({ finishReason: "stop", type: "finish" });
controller.close();
},
});
},
};

expect(isAIUIMessageStreamResult(result)).toBe(true);
await expect(collect(fromAIStreamResult(result))).resolves.toEqual([
{ finishReason: "stop", type: "finish" },
]);
});
});
52 changes: 52 additions & 0 deletions packages/ai-sdk/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import type { MatrixStream } from "@better-matrix-js/chat-adapter";

export type AIUIMessageChunk = {
type: string;
[key: string]: unknown;
};

export type AIUIMessageChunkStream =
| AsyncIterable<AIUIMessageChunk>
| ReadableStream<AIUIMessageChunk>;

export interface AIUIMessageStreamResult {
toUIMessageStream(): AIUIMessageChunkStream;
}

export function fromAIUIMessageStream(stream: AIUIMessageChunkStream): MatrixStream {
if (isAsyncIterable(stream)) {
return stream;
}
return readableStreamToAsyncIterable(stream);
}

export function fromAIStreamResult(result: AIUIMessageStreamResult): MatrixStream {
return fromAIUIMessageStream(result.toUIMessageStream());
}

export function isAIUIMessageStreamResult(value: unknown): value is AIUIMessageStreamResult {
return (
typeof value === "object" &&
value !== null &&
typeof (value as { toUIMessageStream?: unknown }).toUIMessageStream === "function"
);
}

async function* readableStreamToAsyncIterable(stream: ReadableStream<AIUIMessageChunk>): AsyncIterable<AIUIMessageChunk> {
const reader = stream.getReader();
try {
while (true) {
const result = await reader.read();
if (result.done) {
return;
}
yield result.value;
}
} finally {
reader.releaseLock();
}
}

function isAsyncIterable(value: AIUIMessageChunkStream): value is AsyncIterable<AIUIMessageChunk> {
return Symbol.asyncIterator in value;
}
8 changes: 8 additions & 0 deletions packages/ai-sdk/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./dist"
},
"include": ["src/**/*"],
"exclude": ["dist", "node_modules", "**/*.test.ts"]
}
10 changes: 10 additions & 0 deletions packages/ai-sdk/tsup.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { defineConfig } from "tsup";

export default defineConfig({
entry: ["src/index.ts"],
format: ["esm"],
dts: true,
clean: true,
sourcemap: false,
external: ["@better-matrix-js/chat-adapter", "ai"],
});
11 changes: 11 additions & 0 deletions packages/ai-sdk/vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { defineConfig } from "vitest/config";

export default defineConfig({
test: {
environment: "node",
coverage: {
provider: "v8",
reporter: ["text", "json-summary"],
},
},
});
Loading
Loading