@tjakoen/grain 0.1.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/PLAN.md +27 -0
- package/README.md +243 -0
- package/ai/accepts.test.ts +69 -0
- package/ai/accepts.ts +57 -0
- package/ai/ai.css +127 -0
- package/ai/client-door.test.ts +70 -0
- package/ai/client-door.ts +56 -0
- package/ai/contract.test.ts +158 -0
- package/ai/contract.ts +285 -0
- package/ai/interaction-layer.test.ts +270 -0
- package/ai/interaction-layer.ts +138 -0
- package/ai/manifest-dom.test.ts +176 -0
- package/ai/manifest-dom.ts +187 -0
- package/ai/manifest.test.ts +71 -0
- package/ai/manifest.ts +57 -0
- package/ai/markdown.test.ts +68 -0
- package/ai/markdown.ts +74 -0
- package/ai/model-chat.test.ts +131 -0
- package/ai/model-chat.ts +151 -0
- package/ai/model-reasoner.test.ts +152 -0
- package/ai/model-reasoner.ts +146 -0
- package/ai/model.test.ts +148 -0
- package/ai/model.ts +200 -0
- package/ai/reasoner-kit.test.ts +142 -0
- package/ai/reasoner-kit.ts +159 -0
- package/ai/reasoner.test.ts +227 -0
- package/ai/reasoner.ts +446 -0
- package/ai/timeline-log.test.ts +55 -0
- package/ai/timeline-log.ts +50 -0
- package/ai/vocab-reference.test.ts +43 -0
- package/ai/vocab-reference.ts +107 -0
- package/ai/webllm.test.ts +79 -0
- package/ai/webllm.ts +125 -0
- package/assets/figure-sample.svg +14 -0
- package/assets/sprite.svg +22 -0
- package/catalog/catalog.test.ts +37 -0
- package/catalog/catalog.ts +424 -0
- package/components/atoms/action-badge/action-badge.css +17 -0
- package/components/atoms/action-badge/action-badge.html +6 -0
- package/components/atoms/action-badge/action-badge.md +23 -0
- package/components/atoms/b-badge/b-badge.css +15 -0
- package/components/atoms/b-badge/b-badge.html +2 -0
- package/components/atoms/b-badge/b-badge.md +16 -0
- package/components/atoms/b-button/b-button.ai.md +22 -0
- package/components/atoms/b-button/b-button.css +87 -0
- package/components/atoms/b-button/b-button.html +5 -0
- package/components/atoms/b-button/b-button.md +77 -0
- package/components/atoms/b-icon/b-icon.css +10 -0
- package/components/atoms/b-icon/b-icon.html +5 -0
- package/components/atoms/b-icon/b-icon.md +36 -0
- package/components/atoms/b-icon-button/b-icon-button.ai.md +11 -0
- package/components/atoms/b-icon-button/b-icon-button.css +43 -0
- package/components/atoms/b-icon-button/b-icon-button.html +8 -0
- package/components/atoms/b-icon-button/b-icon-button.md +33 -0
- package/components/atoms/b-input/b-input.css +36 -0
- package/components/atoms/b-input/b-input.html +8 -0
- package/components/atoms/b-input/b-input.md +59 -0
- package/components/atoms/b-kbd/b-kbd.css +11 -0
- package/components/atoms/b-kbd/b-kbd.html +3 -0
- package/components/atoms/b-kbd/b-kbd.md +13 -0
- package/components/atoms/b-list/b-list.css +21 -0
- package/components/atoms/b-list/b-list.html +6 -0
- package/components/atoms/b-list/b-list.md +24 -0
- package/components/atoms/b-meter/b-meter.css +39 -0
- package/components/atoms/b-meter/b-meter.md +44 -0
- package/components/atoms/b-select/b-select.css +35 -0
- package/components/atoms/b-select/b-select.md +75 -0
- package/components/atoms/b-switch/b-switch.css +61 -0
- package/components/atoms/b-switch/b-switch.html +6 -0
- package/components/atoms/b-switch/b-switch.md +40 -0
- package/components/atoms/b-text/b-text.ai.md +29 -0
- package/components/atoms/b-text/b-text.css +2 -0
- package/components/atoms/b-text/b-text.html +3 -0
- package/components/atoms/b-text/b-text.md +23 -0
- package/components/atoms/code-block/code-block.css +42 -0
- package/components/atoms/code-block/code-block.md +23 -0
- package/components/examples.test.ts +23 -0
- package/components/molecules/callout/callout.css +19 -0
- package/components/molecules/callout/callout.md +15 -0
- package/components/molecules/card/card.css +28 -0
- package/components/molecules/card/card.md +30 -0
- package/components/molecules/chat-message/chat-message.css +83 -0
- package/components/molecules/chat-message/chat-message.md +52 -0
- package/components/molecules/chip-group/chip-group.css +35 -0
- package/components/molecules/chip-group/chip-group.md +42 -0
- package/components/molecules/content-index/content-index.css +87 -0
- package/components/molecules/content-index/content-index.md +27 -0
- package/components/molecules/content-source/content-source.css +6 -0
- package/components/molecules/content-source/content-source.md +13 -0
- package/components/molecules/figure/figure.css +19 -0
- package/components/molecules/figure/figure.md +20 -0
- package/components/molecules/lede/lede.css +17 -0
- package/components/molecules/lede/lede.md +17 -0
- package/components/molecules/made-with/made-with.css +25 -0
- package/components/molecules/made-with/made-with.md +35 -0
- package/components/molecules/nav-item/nav-item.css +19 -0
- package/components/molecules/nav-item/nav-item.md +21 -0
- package/components/molecules/stat-tile/stat-tile.css +34 -0
- package/components/molecules/stat-tile/stat-tile.md +50 -0
- package/components/molecules/status-list/status-list.css +47 -0
- package/components/molecules/status-list/status-list.md +62 -0
- package/components/molecules/tab/tab.css +32 -0
- package/components/molecules/tab/tab.md +27 -0
- package/components/molecules/table/table.css +23 -0
- package/components/molecules/table/table.md +18 -0
- package/components/organisms/activity-bar/activity-bar.css +36 -0
- package/components/organisms/activity-bar/activity-bar.md +43 -0
- package/components/organisms/app-shell/app-shell.css +193 -0
- package/components/organisms/app-shell/app-shell.md +58 -0
- package/components/organisms/app-shell/app-shell.test.ts +74 -0
- package/components/organisms/app-window/app-window.css +111 -0
- package/components/organisms/app-window/app-window.md +53 -0
- package/components/organisms/chat-log/chat-log.css +5 -0
- package/components/organisms/chat-log/chat-log.md +14 -0
- package/components/organisms/code-editor/code-editor.ai.md +31 -0
- package/components/organisms/code-editor/code-editor.css +111 -0
- package/components/organisms/code-editor/code-editor.md +122 -0
- package/components/organisms/console/console.css +112 -0
- package/components/organisms/console/console.md +66 -0
- package/components/organisms/file-tree/file-tree.css +85 -0
- package/components/organisms/file-tree/file-tree.md +49 -0
- package/components/organisms/note/note.css +19 -0
- package/components/organisms/note/note.md +20 -0
- package/components/organisms/notepad/notepad.css +60 -0
- package/components/organisms/notepad/notepad.md +40 -0
- package/components/organisms/side-rail/side-rail.css +55 -0
- package/components/organisms/side-rail/side-rail.md +24 -0
- package/components/organisms/sidebar-panel/sidebar-panel.css +69 -0
- package/components/organisms/sidebar-panel/sidebar-panel.md +47 -0
- package/components/organisms/status-bar/status-bar.css +33 -0
- package/components/organisms/status-bar/status-bar.md +28 -0
- package/components/organisms/tab-bar/tab-bar.css +48 -0
- package/components/organisms/tab-bar/tab-bar.md +26 -0
- package/components/organisms/timeline/timeline.css +51 -0
- package/components/organisms/timeline/timeline.md +42 -0
- package/components/organisms/topbar/topbar.css +8 -0
- package/components/organisms/topbar/topbar.md +26 -0
- package/components/responsive-polish.test.ts +43 -0
- package/components/tokens.test.ts +39 -0
- package/fonts/redaction-35-400.woff2 +0 -0
- package/fonts/redaction-400.woff2 +0 -0
- package/fonts/redaction-50-400.woff2 +0 -0
- package/fonts/redaction-70-400.woff2 +0 -0
- package/package.json +46 -0
- package/scripts/ai-dispatch.js +583 -0
- package/scripts/ai-dispatch.test.ts +85 -0
- package/scripts/ai-spotlight.d.ts +23 -0
- package/scripts/ai-spotlight.js +139 -0
- package/scripts/ai-spotlight.test.ts +31 -0
- package/scripts/catalog-peek.js +156 -0
- package/scripts/catalog-peek.test.ts +31 -0
- package/scripts/cmdk.js +159 -0
- package/scripts/demo-box.js +53 -0
- package/scripts/handoff.js +64 -0
- package/scripts/handoff.test.ts +36 -0
- package/scripts/lightbox.js +144 -0
- package/scripts/lightbox.test.ts +23 -0
- package/scripts/made-with.d.ts +2 -0
- package/scripts/made-with.js +22 -0
- package/scripts/made-with.test.ts +25 -0
- package/scripts/notepad.js +100 -0
- package/scripts/shell.js +204 -0
- package/scripts/shell.test.ts +50 -0
- package/scripts/tabs.js +127 -0
- package/scripts/tabs.test.ts +40 -0
- package/scripts/terminal.js +271 -0
- package/scripts/terminal.test.ts +36 -0
- package/scripts/theme-boot.js +15 -0
- package/scripts/theme.js +87 -0
- package/scripts/type-effect.js +25 -0
- package/scripts/xray.js +79 -0
- package/scripts/xray.test.ts +43 -0
- package/styles/cmdk.css +65 -0
- package/styles/global.css +80 -0
- package/styles/grain.css +47 -0
- package/styles/lightbox.css +78 -0
- package/styles/themes/_template.css +48 -0
- package/styles/themes/baguette.css +30 -0
- package/styles/themes/brioche.css +30 -0
- package/styles/variables.css +217 -0
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// grain/ai/markdown.test.ts — the settle-time sanitizing markdown renderer. Pins the allowlist
|
|
2
|
+
// (emphasis/code/links/lists/paragraphs) AND the security properties that make it safe to feed
|
|
3
|
+
// unsanitized AI/user text through: raw HTML is always inert, an unsafe href never becomes a link.
|
|
4
|
+
import { test, expect } from "bun:test";
|
|
5
|
+
import { renderMarkdown } from "./markdown.ts";
|
|
6
|
+
|
|
7
|
+
test("strong and em render", () => {
|
|
8
|
+
expect(renderMarkdown("hello **world**")).toContain("<strong>world</strong>");
|
|
9
|
+
expect(renderMarkdown("hello *world*")).toContain("<em>world</em>");
|
|
10
|
+
expect(renderMarkdown("hello _world_")).toContain("<em>world</em>");
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
test("inline code renders", () => {
|
|
14
|
+
expect(renderMarkdown("run `bun test`")).toContain("<code>bun test</code>");
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
test("a same-origin relative link renders as an anchor", () => {
|
|
18
|
+
const html = renderMarkdown("see [the docs](/grain/docs/ai-interface)");
|
|
19
|
+
expect(html).toContain('<a href="/grain/docs/ai-interface">the docs</a>');
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
test("an unsafe href (javascript:) does NOT become an anchor — text survives, href is dropped", () => {
|
|
23
|
+
const html = renderMarkdown("click [here](javascript:alert(1))");
|
|
24
|
+
expect(html).not.toContain("<a ");
|
|
25
|
+
expect(html).not.toContain("javascript:");
|
|
26
|
+
expect(html).toContain("here");
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test("an external href does NOT become an anchor", () => {
|
|
30
|
+
const html = renderMarkdown("go [away](https://evil.example/steal)");
|
|
31
|
+
expect(html).not.toContain("<a ");
|
|
32
|
+
expect(html).not.toContain("evil.example");
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test("a protocol-relative href does NOT become an anchor", () => {
|
|
36
|
+
const html = renderMarkdown("[x](//evil.example)");
|
|
37
|
+
expect(html).not.toContain("<a ");
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test("raw <script>/HTML in the source text is INERT — escaped, never re-parsed as markup", () => {
|
|
41
|
+
const html = renderMarkdown('<script>alert(1)</script> and <img src=x onerror=alert(1)>');
|
|
42
|
+
expect(html).not.toContain("<script>");
|
|
43
|
+
expect(html).not.toContain("<img");
|
|
44
|
+
expect(html).toContain("<script>");
|
|
45
|
+
expect(html).toContain("<img");
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test("a simple list renders as <ul><li>", () => {
|
|
49
|
+
const html = renderMarkdown("- one\n- two\n- three");
|
|
50
|
+
expect(html).toBe("<ul><li>one</li><li>two</li><li>three</li></ul>");
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test("a bare paragraph wraps in <p>, multiple paragraphs are separate blocks", () => {
|
|
54
|
+
const html = renderMarkdown("first paragraph\n\nsecond paragraph");
|
|
55
|
+
expect(html).toBe("<p>first paragraph</p><p>second paragraph</p>");
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test("single newlines within a paragraph become <br>, not separate paragraphs", () => {
|
|
59
|
+
expect(renderMarkdown("line one\nline two")).toBe("<p>line one<br>line two</p>");
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test("code spans are not further mangled by em/strong inside them", () => {
|
|
63
|
+
expect(renderMarkdown("`*not em*`")).toBe("<p><code>*not em*</code></p>");
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
test("empty input renders nothing", () => {
|
|
67
|
+
expect(renderMarkdown("")).toBe("");
|
|
68
|
+
});
|
package/ai/markdown.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// grain/ai/markdown.ts — a SMALL, SELF-CONTAINED, sanitizing markdown renderer for AI chat text.
|
|
2
|
+
//
|
|
3
|
+
// The dispatcher streams assistant text as `textContent` while it's in flight (safe by
|
|
4
|
+
// construction — no HTML can be injected mid-stream, scripts/ai-dispatch.js's `applyType`). Once a
|
|
5
|
+
// message SETTLES, the dispatcher re-renders that same accumulated plain text through THIS
|
|
6
|
+
// renderer so `**bold**`, `` `code` ``, and links read as formatting instead of literal asterisks —
|
|
7
|
+
// without ever setting innerHTML from unsanitized text. It works by escaping every character
|
|
8
|
+
// FIRST, then building ONLY the tags on its allowlist around the escaped text — so raw
|
|
9
|
+
// `<script>` or any other HTML present in the source text is always inert: the only markup that
|
|
10
|
+
// can ever appear in the output is markup THIS function wrote.
|
|
11
|
+
//
|
|
12
|
+
// Allowlist: *em*/_em_, **strong**, `code`, [text](/relative-path) (same-origin only — the exact
|
|
13
|
+
// `isSafeNavigateHref` rule contract.ts's `navigate` op uses; an unsafe href renders as plain
|
|
14
|
+
// text, never becomes a link), simple "- "/"* " lists, and paragraphs. Nothing else. No external
|
|
15
|
+
// dependency — grain ships no runtime deps (CLAUDE.md).
|
|
16
|
+
//
|
|
17
|
+
// scripts/ai-dispatch.js carries an INTENTIONAL, near-identical copy of this renderer (browser-
|
|
18
|
+
// native, no cross-module import of ai/*.ts into the "ONE accepted bit of client JS" — see that
|
|
19
|
+
// file's header) — markdown.test.ts drift-guards the two copies' regex rules against each other so
|
|
20
|
+
// they can't silently diverge (CLAUDE.md lesson #5). This module is the canonical, unit-tested,
|
|
21
|
+
// importable-by-any-consumer form — "exposed from the kit" via reasoner-kit.ts's re-export.
|
|
22
|
+
|
|
23
|
+
import { isSafeNavigateHref } from "./contract.ts";
|
|
24
|
+
|
|
25
|
+
const esc = (s: string): string =>
|
|
26
|
+
s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
27
|
+
|
|
28
|
+
// Inline rules, applied IN ORDER to an already-escaped line: code spans first (so em/strong never
|
|
29
|
+
// look inside a code span), then links, then strong (**) before em (*) so "**x**" isn't read as
|
|
30
|
+
// two adjacent em's.
|
|
31
|
+
const CODE_RE = /`([^`]+)`/g;
|
|
32
|
+
const LINK_RE = /\[([^\]]+)\]\(([^)]+)\)/g;
|
|
33
|
+
const STRONG_RE = /\*\*([^*]+)\*\*/g;
|
|
34
|
+
const EM_RE = /(?:\*([^*]+)\*|_([^_]+)_)/g;
|
|
35
|
+
const LIST_ITEM_RE = /^[-*]\s+/;
|
|
36
|
+
const BLOCK_SPLIT_RE = /\n{2,}/;
|
|
37
|
+
// Placeholder delimiter for pulled-out code spans (below) — \x00 can't occur in real chat text
|
|
38
|
+
// (it was already esc()'d as ordinary text upstream), so it never collides.
|
|
39
|
+
const CODE_PLACEHOLDER_RE = /\x00(\d+)\x00/g;
|
|
40
|
+
|
|
41
|
+
function inline(escaped: string): string {
|
|
42
|
+
// Code spans are pulled OUT first and swapped for a \x00-delimited placeholder, so their literal
|
|
43
|
+
// contents (which may themselves contain *, _, [, ], (, )) can never be re-interpreted by the
|
|
44
|
+
// rules below — they're spliced back in verbatim at the very end, untouched by strong/em/links.
|
|
45
|
+
const codeSpans: string[] = [];
|
|
46
|
+
let out = escaped.replace(CODE_RE, (_m, code) => {
|
|
47
|
+
codeSpans.push(`<code>${code}</code>`);
|
|
48
|
+
return `\x00${codeSpans.length - 1}\x00`;
|
|
49
|
+
});
|
|
50
|
+
out = out.replace(LINK_RE, (_m, text, href) => (isSafeNavigateHref(href) ? `<a href="${href}">${text}</a>` : text));
|
|
51
|
+
out = out.replace(STRONG_RE, (_m, t) => `<strong>${t}</strong>`);
|
|
52
|
+
out = out.replace(EM_RE, (_m, a, b) => `<em>${a ?? b}</em>`);
|
|
53
|
+
out = out.replace(CODE_PLACEHOLDER_RE, (_m, i) => codeSpans[Number(i)]);
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Render plain assistant text as sanitized HTML: paragraphs + simple "- "/"* " lists, with
|
|
58
|
+
* inline emphasis/code/links inside each line. Deterministic, pure, no DOM — the caller (the
|
|
59
|
+
* dispatcher) owns writing the result into the page. */
|
|
60
|
+
export function renderMarkdown(text: string): string {
|
|
61
|
+
const blocks = text.split(BLOCK_SPLIT_RE);
|
|
62
|
+
const out: string[] = [];
|
|
63
|
+
for (const block of blocks) {
|
|
64
|
+
const lines = block.split("\n").filter((l) => l.length > 0);
|
|
65
|
+
if (!lines.length) continue;
|
|
66
|
+
if (lines.every((l) => LIST_ITEM_RE.test(l))) {
|
|
67
|
+
const items = lines.map((l) => `<li>${inline(esc(l.replace(LIST_ITEM_RE, "")))}</li>`).join("");
|
|
68
|
+
out.push(`<ul>${items}</ul>`);
|
|
69
|
+
} else {
|
|
70
|
+
out.push(`<p>${lines.map((l) => inline(esc(l))).join("<br>")}</p>`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return out.join("");
|
|
74
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// grain/ai/model-chat.test.ts — UNIT: the OpenAI-chat engine adapter (the WebLLM transport), with a
|
|
2
|
+
// FAKE engine. No SDK, no WebGPU, no download: a structural fake records the request it receives and
|
|
3
|
+
// returns canned content, proving the adapter builds a correct chat request + returns the raw text the
|
|
4
|
+
// reasoner core parses.
|
|
5
|
+
import { test, expect } from "bun:test";
|
|
6
|
+
import {
|
|
7
|
+
makeChatModel, splitPrompt, streamChat,
|
|
8
|
+
type ChatEngine, type ChatCompletionRequest,
|
|
9
|
+
type StreamingChatEngine, type ChatStreamRequest, type ChatStreamChunk,
|
|
10
|
+
} from "./model-chat.ts";
|
|
11
|
+
import { buildReasonerPrompt, SYSTEM_PREAMBLE } from "./model.ts";
|
|
12
|
+
|
|
13
|
+
// A structural fake: captures the last request, returns a fixed completion.
|
|
14
|
+
function fakeEngine(content: string | null) {
|
|
15
|
+
let last: ChatCompletionRequest | null = null;
|
|
16
|
+
const engine: ChatEngine = {
|
|
17
|
+
chat: { completions: { create: async (req) => { last = req; return { choices: [{ message: { content } }] }; } } },
|
|
18
|
+
};
|
|
19
|
+
return { engine, req: () => last };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
test("makeChatModel: returns the assistant content verbatim for the core to parse", async () => {
|
|
23
|
+
const { engine } = fakeEngine('{"action":null,"reply":"hi"}');
|
|
24
|
+
const model = makeChatModel(engine);
|
|
25
|
+
expect(await model.complete("some prompt")).toBe('{"action":null,"reply":"hi"}');
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test("makeChatModel: null content degrades to empty string (no crash)", async () => {
|
|
29
|
+
const { engine } = fakeEngine(null);
|
|
30
|
+
expect(await makeChatModel(engine).complete("p")).toBe("");
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test("makeChatModel: requests JSON mode + low temperature by default", async () => {
|
|
34
|
+
const { engine, req } = fakeEngine("{}");
|
|
35
|
+
await makeChatModel(engine).complete("p");
|
|
36
|
+
expect(req()!.response_format).toEqual({ type: "json_object" });
|
|
37
|
+
expect(req()!.temperature).toBe(0.2);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test("makeChatModel: jsonMode:false omits response_format (for engines that reject it)", async () => {
|
|
41
|
+
const { engine, req } = fakeEngine("{}");
|
|
42
|
+
await makeChatModel(engine, { jsonMode: false, temperature: 0 }).complete("p");
|
|
43
|
+
expect(req()!.response_format).toBeUndefined();
|
|
44
|
+
expect(req()!.temperature).toBe(0);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test("makeChatModel: a real composed prompt is split into system + user messages", async () => {
|
|
48
|
+
const { engine, req } = fakeEngine("{}");
|
|
49
|
+
const prompt = buildReasonerPrompt("MANIFEST-TEXT", "note the milk");
|
|
50
|
+
await makeChatModel(engine).complete(prompt);
|
|
51
|
+
const msgs = req()!.messages;
|
|
52
|
+
expect(msgs).toHaveLength(2);
|
|
53
|
+
expect(msgs[0].role).toBe("system");
|
|
54
|
+
expect(msgs[0].content).toBe(SYSTEM_PREAMBLE); // the one-door rules land in system
|
|
55
|
+
expect(msgs[1].role).toBe("user");
|
|
56
|
+
expect(msgs[1].content).toContain("MANIFEST-TEXT"); // the manifest + message + contract in user
|
|
57
|
+
expect(msgs[1].content).toContain("note the milk");
|
|
58
|
+
expect(msgs[1].content).not.toContain(SYSTEM_PREAMBLE); // not duplicated
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
test("splitPrompt: an unknown prompt shape falls back to a single user message", () => {
|
|
62
|
+
const msgs = splitPrompt("no preamble here");
|
|
63
|
+
expect(msgs).toEqual([{ role: "user", content: "no preamble here" }]);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
test("splitPrompt: leads with the preamble → clean system/user split", () => {
|
|
67
|
+
const msgs = splitPrompt(SYSTEM_PREAMBLE + "\n\nrest of the prompt");
|
|
68
|
+
expect(msgs[0]).toEqual({ role: "system", content: SYSTEM_PREAMBLE });
|
|
69
|
+
expect(msgs[1]).toEqual({ role: "user", content: "rest of the prompt" });
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
// ── the streaming transport (streamChat) ──────────────────────────────────────────────────────────
|
|
73
|
+
// A structural fake STREAMING engine: yields the given content deltas as chunks (interleaving an empty
|
|
74
|
+
// delta to prove they're skipped), records the request it got, and counts interrupt calls.
|
|
75
|
+
function fakeStreamEngine(deltas: string[]) {
|
|
76
|
+
let last: ChatStreamRequest | null = null;
|
|
77
|
+
let interrupts = 0;
|
|
78
|
+
let drained = false; // did the consumer read every chunk?
|
|
79
|
+
const engine: StreamingChatEngine = {
|
|
80
|
+
chat: { completions: { create: async (req) => {
|
|
81
|
+
last = req;
|
|
82
|
+
async function* gen(): AsyncIterable<ChatStreamChunk> {
|
|
83
|
+
for (const d of deltas) {
|
|
84
|
+
yield { choices: [{ delta: { content: "" } }] }; // empty → must be skipped
|
|
85
|
+
yield { choices: [{ delta: { content: d } }] };
|
|
86
|
+
}
|
|
87
|
+
drained = true;
|
|
88
|
+
}
|
|
89
|
+
return gen();
|
|
90
|
+
} } },
|
|
91
|
+
interruptGenerate() { interrupts++; },
|
|
92
|
+
};
|
|
93
|
+
return { engine, req: () => last, interrupts: () => interrupts, drained: () => drained };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
test("streamChat: yields content deltas in order and skips empty ones", async () => {
|
|
97
|
+
const { engine } = fakeStreamEngine(["Hel", "lo", " world"]);
|
|
98
|
+
const out: string[] = [];
|
|
99
|
+
for await (const d of streamChat(engine, [{ role: "user", content: "hi" }])) out.push(d);
|
|
100
|
+
expect(out).toEqual(["Hel", "lo", " world"]);
|
|
101
|
+
expect(out.join("")).toBe("Hello world");
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test("streamChat: a natural finish does NOT interrupt the engine", async () => {
|
|
105
|
+
const { engine, interrupts } = fakeStreamEngine(["a", "b"]);
|
|
106
|
+
for await (const _ of streamChat(engine, [{ role: "user", content: "hi" }])) { /* drain */ }
|
|
107
|
+
expect(interrupts()).toBe(0);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test("streamChat: breaking early interrupts generation (finally → interruptGenerate)", async () => {
|
|
111
|
+
const { engine, interrupts, drained } = fakeStreamEngine(["one", "two", "three", "four"]);
|
|
112
|
+
const out: string[] = [];
|
|
113
|
+
for await (const d of streamChat(engine, [{ role: "user", content: "hi" }])) {
|
|
114
|
+
out.push(d);
|
|
115
|
+
if (out.length === 2) break; // a stop button / loop-guard
|
|
116
|
+
}
|
|
117
|
+
expect(out).toEqual(["one", "two"]);
|
|
118
|
+
expect(interrupts()).toBe(1); // stopped mid-stream
|
|
119
|
+
expect(drained()).toBe(false); // and never read to the end
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
test("streamChat: maps grain-cased opts to the engine's snake_case request", async () => {
|
|
123
|
+
const { engine, req } = fakeStreamEngine(["x"]);
|
|
124
|
+
for await (const _ of streamChat(engine, [{ role: "user", content: "hi" }], {
|
|
125
|
+
maxTokens: 220, temperature: 0.5, topP: 0.9, frequencyPenalty: 0.6, presencePenalty: 0.4,
|
|
126
|
+
})) { /* drain */ }
|
|
127
|
+
expect(req()).toMatchObject({
|
|
128
|
+
stream: true, max_tokens: 220, temperature: 0.5, top_p: 0.9,
|
|
129
|
+
frequency_penalty: 0.6, presence_penalty: 0.4,
|
|
130
|
+
});
|
|
131
|
+
});
|
package/ai/model-chat.ts
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// grain/ai/model-chat.ts — a `Model` adapter for any OpenAI-CHAT-SHAPED engine (the WebLLM transport).
|
|
2
|
+
//
|
|
3
|
+
// makeModelReasoner (model-reasoner.ts) talks to a `Model` PORT (model.ts): one method, `complete`.
|
|
4
|
+
// The real transport the human chose is WebLLM — an in-browser model over WebGPU — whose engine
|
|
5
|
+
// (`@mlc-ai/web-llm`'s MLCEngine) exposes an OpenAI-compatible `chat.completions.create`. Rather than
|
|
6
|
+
// depend on that heavy, browser-specific SDK, grain adapts a MINIMAL STRUCTURAL slice of it (ChatEngine
|
|
7
|
+
// below): the COMPOSITION ROOT installs `@mlc-ai/web-llm`, builds the engine, and hands it in — grain
|
|
8
|
+
// stays lean + dependency-light, and the SAME adapter serves any OpenAI-chat-shaped engine (a hosted
|
|
9
|
+
// API, a proxy, a test fake), not only WebLLM. That's the flexibility the whole seam is for: one
|
|
10
|
+
// reasoning core, one port, many engines; the transport is the root's choice (§19.3, like OpenChannel).
|
|
11
|
+
//
|
|
12
|
+
// CLIENT-SAFE (§19.2): pure, relative imports only, no SDK import, no DOM, no secrets. Unit-tested with
|
|
13
|
+
// a fake engine — no browser, no WebGPU, no model download.
|
|
14
|
+
|
|
15
|
+
import { SYSTEM_PREAMBLE } from "./model.ts";
|
|
16
|
+
import type { Model } from "./model.ts";
|
|
17
|
+
|
|
18
|
+
// ── the sliver of an OpenAI-chat engine this adapter touches (structural, not the SDK) ────────────
|
|
19
|
+
export interface ChatMessage { role: "system" | "user" | "assistant"; content: string }
|
|
20
|
+
export interface ChatCompletionRequest {
|
|
21
|
+
messages: ChatMessage[];
|
|
22
|
+
temperature?: number;
|
|
23
|
+
/** Ask the engine to constrain output to a JSON object — WebLLM + OpenAI both honour this, and it
|
|
24
|
+
* sharply raises the odds `parseModelMove` gets clean JSON (fewer prose wrappers to strip). */
|
|
25
|
+
response_format?: { type: "json_object" };
|
|
26
|
+
}
|
|
27
|
+
export interface ChatCompletion { choices: { message: { content: string | null } }[] }
|
|
28
|
+
export interface ChatEngine {
|
|
29
|
+
chat: { completions: { create(req: ChatCompletionRequest): Promise<ChatCompletion> } };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface ChatModelOptions {
|
|
33
|
+
/** Low by default: choosing a move from a fixed vocabulary wants determinism, not creativity. */
|
|
34
|
+
temperature?: number;
|
|
35
|
+
/** Request JSON-object output (default true). Set false only for an engine that rejects the flag. */
|
|
36
|
+
jsonMode?: boolean;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Adapt an OpenAI-chat-shaped `engine` into grain's `Model` port. The reasoner core hands `complete`
|
|
40
|
+
* one composed prompt (buildReasonerPrompt: preamble + manifest + message + output contract); this
|
|
41
|
+
* splits the leading system preamble into a `system` message (where a chat model expects its
|
|
42
|
+
* instructions) and sends the rest as the `user` turn, then returns the assistant's raw text for the
|
|
43
|
+
* core to parse + validate. The split is best-effort: if the marker isn't found the whole prompt goes
|
|
44
|
+
* as the user turn — correctness never depends on the split, only prompt hygiene. */
|
|
45
|
+
export function makeChatModel(engine: ChatEngine, opts: ChatModelOptions = {}): Model {
|
|
46
|
+
const temperature = opts.temperature ?? 0.2;
|
|
47
|
+
const jsonMode = opts.jsonMode ?? true;
|
|
48
|
+
|
|
49
|
+
return {
|
|
50
|
+
async complete(prompt: string): Promise<string> {
|
|
51
|
+
const messages = splitPrompt(prompt);
|
|
52
|
+
const req: ChatCompletionRequest = { messages, temperature };
|
|
53
|
+
if (jsonMode) req.response_format = { type: "json_object" };
|
|
54
|
+
const res = await engine.chat.completions.create(req);
|
|
55
|
+
return res.choices[0]?.message?.content ?? "";
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Split a composed reasoner prompt into system + user messages. The preamble (the one-door rules)
|
|
61
|
+
* belongs in the `system` role; everything after it (the manifest, the human's message, the output
|
|
62
|
+
* contract) is the `user` turn. Falls back to one user message if the prompt doesn't lead with the
|
|
63
|
+
* known preamble, so an evolving prompt format can never break the adapter — correctness depends only
|
|
64
|
+
* on the full prompt reaching the model, never on the split succeeding. */
|
|
65
|
+
export function splitPrompt(prompt: string): ChatMessage[] {
|
|
66
|
+
if (!prompt.startsWith(SYSTEM_PREAMBLE)) return [{ role: "user", content: prompt }];
|
|
67
|
+
const user = prompt.slice(SYSTEM_PREAMBLE.length).trim();
|
|
68
|
+
return [{ role: "system", content: SYSTEM_PREAMBLE }, { role: "user", content: user }];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// ── the STREAMING variant of the chat transport ───────────────────────────────────────────────────
|
|
72
|
+
// makeChatModel above is the REASONER's transport: one composed prompt, one whole-text completion, then
|
|
73
|
+
// parse + validate — streaming buys the strict-JSON core nothing. A conversational surface (the
|
|
74
|
+
// portfolio's "desk") is the opposite: it streams the human-facing reply token by token and must be
|
|
75
|
+
// able to STOP mid-generation (the visitor hits stop; a weak model spins into a repetition loop). That
|
|
76
|
+
// lives HERE, beside the non-streaming adapter, because it is the SAME OpenAI-chat engine — only the
|
|
77
|
+
// `create` shape (stream:true → an async-iterable of deltas) and an `interruptGenerate` differ. Grain
|
|
78
|
+
// owns the plumbing; the loop-guard / accumulation / UI stay in the composing reasoner. This is NOT the
|
|
79
|
+
// `Model` port — a streamed chat reply is the composing reasoner's concern, never the validated-move
|
|
80
|
+
// core's (see model.ts, the port's doc comment).
|
|
81
|
+
|
|
82
|
+
/** One streamed chunk — the sliver of an OpenAI stream delta we consume (content only). */
|
|
83
|
+
export interface ChatStreamChunk { choices?: Array<{ delta?: { content?: string } }> }
|
|
84
|
+
|
|
85
|
+
/** Sampling knobs for a streamed completion (all optional — the composing reasoner tunes them; a weak
|
|
86
|
+
* model in particular wants penalties or it loops). Grain-cased; mapped to the engine's snake_case in
|
|
87
|
+
* the request below so callers never touch the wire shape. */
|
|
88
|
+
export interface ChatStreamOptions {
|
|
89
|
+
maxTokens?: number;
|
|
90
|
+
temperature?: number;
|
|
91
|
+
topP?: number;
|
|
92
|
+
frequencyPenalty?: number;
|
|
93
|
+
presencePenalty?: number;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The streaming `create` request, in the engine's own (OpenAI) shape. Built by `streamChat`, not by
|
|
97
|
+
* callers — kept exported only so a fake engine in a test can type the request it captures. */
|
|
98
|
+
export interface ChatStreamRequest {
|
|
99
|
+
messages: ChatMessage[];
|
|
100
|
+
stream: true;
|
|
101
|
+
max_tokens?: number;
|
|
102
|
+
temperature?: number;
|
|
103
|
+
top_p?: number;
|
|
104
|
+
frequency_penalty?: number;
|
|
105
|
+
presence_penalty?: number;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** A STREAMING OpenAI-chat engine: `create` resolves to an async-iterable of content deltas, and
|
|
109
|
+
* generation can be interrupted early. WebLLM's MLCEngine satisfies this exactly (`interruptGenerate`);
|
|
110
|
+
* a hosted API would map `interruptGenerate` to aborting the underlying fetch. Structural, like
|
|
111
|
+
* `ChatEngine` — grain depends on the SHAPE, never the SDK (§19.2/§19.3). */
|
|
112
|
+
export interface StreamingChatEngine {
|
|
113
|
+
chat: { completions: { create(req: ChatStreamRequest): Promise<AsyncIterable<ChatStreamChunk>> } };
|
|
114
|
+
interruptGenerate(): void;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Stream a chat completion as CONTENT-only token deltas. The caller drives the async-iterable and
|
|
118
|
+
* decides when to stop: BREAKING the `for await` early (a stop button, a loop-guard) unwinds this
|
|
119
|
+
* generator's `finally`, which calls `interruptGenerate` — so the caller never touches the engine to
|
|
120
|
+
* halt it, it just stops iterating. Empty deltas are skipped, so a consumer only ever sees real text.
|
|
121
|
+
* Pure plumbing: accumulation, the repetition loop-guard, and the UI belong to the composing reasoner,
|
|
122
|
+
* not here. */
|
|
123
|
+
export async function* streamChat(
|
|
124
|
+
engine: StreamingChatEngine,
|
|
125
|
+
messages: ChatMessage[],
|
|
126
|
+
opts: ChatStreamOptions = {},
|
|
127
|
+
): AsyncIterable<string> {
|
|
128
|
+
const stream = await engine.chat.completions.create({
|
|
129
|
+
messages,
|
|
130
|
+
stream: true,
|
|
131
|
+
max_tokens: opts.maxTokens,
|
|
132
|
+
temperature: opts.temperature,
|
|
133
|
+
top_p: opts.topP,
|
|
134
|
+
frequency_penalty: opts.frequencyPenalty,
|
|
135
|
+
presence_penalty: opts.presencePenalty,
|
|
136
|
+
});
|
|
137
|
+
let finished = false;
|
|
138
|
+
try {
|
|
139
|
+
for await (const chunk of stream) {
|
|
140
|
+
const delta = chunk.choices?.[0]?.delta?.content;
|
|
141
|
+
if (delta) yield delta;
|
|
142
|
+
}
|
|
143
|
+
finished = true;
|
|
144
|
+
} finally {
|
|
145
|
+
// Only interrupt on an EARLY exit (a break/throw before the stream ran dry). Interrupting after a
|
|
146
|
+
// natural finish is a harmless no-op on WebLLM, but a hosted transport might treat a late abort as
|
|
147
|
+
// an error, so we stay precise. `try/catch` because interruptGenerate can throw if the engine has
|
|
148
|
+
// already torn the generation down.
|
|
149
|
+
if (!finished) { try { engine.interruptGenerate(); } catch { /* already stopped */ } }
|
|
150
|
+
}
|
|
151
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// grain/ai/model-reasoner.test.ts — UNIT: the real reasoner, driven by a FAKE model + recording tools.
|
|
2
|
+
// No browser, no network: a fake `Model` returns canned JSON, a recording `ReasonTools` captures every
|
|
3
|
+
// emitted op, and we assert the reasoner turns a natural-language turn into the right validated ops —
|
|
4
|
+
// and rejects illegal model output cleanly. This is the M★ seam proven end-to-end minus the transport.
|
|
5
|
+
import { test, expect } from "bun:test";
|
|
6
|
+
import { makeModelReasoner } from "./model-reasoner.ts";
|
|
7
|
+
import type { Model } from "./model.ts";
|
|
8
|
+
import { buildManifest, type Manifest, type ManifestTarget } from "./manifest.ts";
|
|
9
|
+
import type { ReasonTools } from "./reasoner.ts";
|
|
10
|
+
import type { Intent, RenderOp } from "./contract.ts";
|
|
11
|
+
|
|
12
|
+
const targets: ManifestTarget[] = [
|
|
13
|
+
{ id: "notepad", kind: "notepad", accepts: ["note.append", "note.replace"] },
|
|
14
|
+
{ id: "chat-log", kind: "chat-log", accepts: ["chat.send"] },
|
|
15
|
+
{ id: "item:ITM-1", kind: "item", accepts: ["item.archive"] },
|
|
16
|
+
];
|
|
17
|
+
const manifest = (): Manifest => buildManifest("loop", targets, { surfaces: targets.map((t) => t.id), readable: [] });
|
|
18
|
+
|
|
19
|
+
// A recording tools double: captures emitted ops + records archive calls; delay/cancel are inert.
|
|
20
|
+
function recordingTools() {
|
|
21
|
+
const ops: RenderOp[] = [];
|
|
22
|
+
const archived: string[] = [];
|
|
23
|
+
const tools: ReasonTools = {
|
|
24
|
+
emit: (op) => { ops.push(op); },
|
|
25
|
+
archiveItem: async (id) => { archived.push(id); },
|
|
26
|
+
renderSurface: async (s) => `<clean surface="${s}"/>`,
|
|
27
|
+
cancelled: () => false,
|
|
28
|
+
delay: async () => {},
|
|
29
|
+
};
|
|
30
|
+
return { tools, ops, archived };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const model = (raw: string): Model => ({ complete: async () => raw });
|
|
34
|
+
const intent = (over: Partial<Intent>): Intent =>
|
|
35
|
+
({ source: "user", session: "s1", screen: "loop", surface: "chat-log", action: "chat.send", payload: {}, ...over });
|
|
36
|
+
|
|
37
|
+
const kinds = (ops: RenderOp[]) => ops.map((o) => o.op);
|
|
38
|
+
const targetsOf = (ops: RenderOp[]) => ops.map((o) => o.target);
|
|
39
|
+
|
|
40
|
+
test("chat.send → model picks note.append: user bubble + AI bubble + the note op + streamed reply", async () => {
|
|
41
|
+
const r = makeModelReasoner({ model: model('{"action":"note.append","target":"notepad","payload":{"text":"buy milk"},"reply":"Added that."}'), manifest });
|
|
42
|
+
const { tools, ops } = recordingTools();
|
|
43
|
+
const d = await r.decide(intent({ action: "chat.send", surface: "chat-log", payload: { text: "note: buy milk" } }), tools);
|
|
44
|
+
|
|
45
|
+
expect(d.ok).toBe(true);
|
|
46
|
+
// 1) the human's message bubble, 2) an empty AI bubble, 3) the note.append op, then the streamed reply
|
|
47
|
+
expect(kinds(ops).slice(0, 2)).toEqual(["append", "append"]); // user + AI bubbles
|
|
48
|
+
const note = ops.find((o) => o.target === "notepad-body");
|
|
49
|
+
expect(note).toMatchObject({ op: "append", provenance: "ai", commit: "committed" });
|
|
50
|
+
// the reply streamed into the AI bubble, then settled
|
|
51
|
+
const typed = ops.filter((o) => o.op === "type" && o.text).map((o) => o.text).join("");
|
|
52
|
+
expect(typed).toBe("Added that.");
|
|
53
|
+
expect(ops.some((o) => o.op === "type" && o.done)).toBe(true); // settled clean
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
test("chat.send → reply-only move (action null): no structural op, just the streamed reply", async () => {
|
|
57
|
+
const r = makeModelReasoner({ model: model('{"action":null,"reply":"I am here — what would you like to plan?"}'), manifest });
|
|
58
|
+
const { tools, ops } = recordingTools();
|
|
59
|
+
const d = await r.decide(intent({ payload: { text: "hi" } }), tools);
|
|
60
|
+
|
|
61
|
+
expect(d.ok).toBe(true);
|
|
62
|
+
expect(ops.some((o) => o.target === "notepad-body")).toBe(false); // no structural effect
|
|
63
|
+
const typed = ops.filter((o) => o.op === "type" && o.text).map((o) => o.text).join("");
|
|
64
|
+
expect(typed).toBe("I am here — what would you like to plan?");
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test("chat.send → item.archive: performs the scoped write + emits the committed fragment", async () => {
|
|
68
|
+
const r = makeModelReasoner({ model: model('{"action":"item.archive","target":"item:ITM-1","reply":"Archived."}'), manifest });
|
|
69
|
+
const { tools, ops, archived } = recordingTools();
|
|
70
|
+
const d = await r.decide(intent({ payload: { text: "archive ITM-1" } }), tools);
|
|
71
|
+
|
|
72
|
+
expect(d.ok).toBe(true);
|
|
73
|
+
expect(archived).toEqual(["ITM-1"]); // the real write happened through the tool
|
|
74
|
+
expect(ops.some((o) => o.target === "item:ITM-1" && o.op === "replace" && o.commit === "committed")).toBe(true);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
test("chat.send → navigate is emitted LAST (terminal), after the reply", async () => {
|
|
78
|
+
// navigate applies to a "screen" surface — the manifest must advertise one.
|
|
79
|
+
const navTargets: ManifestTarget[] = [...targets, { id: "screen", kind: "screen", accepts: ["navigate"] }];
|
|
80
|
+
const navManifest = (): Manifest => buildManifest("loop", navTargets, { surfaces: [], readable: [] });
|
|
81
|
+
const r = makeModelReasoner({ model: model('{"action":"navigate","target":"screen","payload":{"href":"/notes"},"reply":"Taking you there."}'), manifest: navManifest });
|
|
82
|
+
const { tools, ops } = recordingTools();
|
|
83
|
+
await r.decide(intent({ payload: { text: "go to notes" } }), tools);
|
|
84
|
+
|
|
85
|
+
const navIdx = ops.findIndex((o) => o.op === "navigate");
|
|
86
|
+
const lastType = ops.map((o) => o.op).lastIndexOf("type");
|
|
87
|
+
expect(navIdx).toBeGreaterThan(-1);
|
|
88
|
+
expect(navIdx).toBeGreaterThan(lastType); // reply streamed before we leave the page
|
|
89
|
+
expect(ops[navIdx]).toMatchObject({ href: "/notes" });
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test("hallucinated verb → the opened AI bubble is replaced with an error, not left blank", async () => {
|
|
93
|
+
const r = makeModelReasoner({ model: model('{"action":"task.nuke","target":"notepad"}'), manifest });
|
|
94
|
+
const { tools, ops } = recordingTools();
|
|
95
|
+
const d = await r.decide(intent({ payload: { text: "nuke it" } }), tools);
|
|
96
|
+
|
|
97
|
+
expect(d.ok).toBe(false);
|
|
98
|
+
expect(d.reason).toContain("unknown verb");
|
|
99
|
+
// an AI bubble WAS opened (emitted), and the failure replaces its body (returned in decision.ops,
|
|
100
|
+
// which the door pushes) — so no dangling empty bubble is left on screen.
|
|
101
|
+
expect(ops.some((o) => o.op === "append" && o.provenance === "ai")).toBe(true); // the bubble opened
|
|
102
|
+
expect(d.ops.some((o) => o.op === "replace" && o.commit === "committed")).toBe(true); // then got filled
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
test("unafforded target → rejected, reason echoes the valid targets (self-correction)", async () => {
|
|
106
|
+
const r = makeModelReasoner({ model: model('{"action":"chat.send","target":"notepad","payload":{"text":"x"}}'), manifest });
|
|
107
|
+
const { tools } = recordingTools();
|
|
108
|
+
const d = await r.decide(intent({ payload: { text: "say hi in the notepad" } }), tools);
|
|
109
|
+
expect(d.ok).toBe(false);
|
|
110
|
+
expect(d.reason).toContain("does not accept chat.send");
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test("malformed model output → clean rejection, no throw", async () => {
|
|
114
|
+
const r = makeModelReasoner({ model: model("I refuse"), manifest });
|
|
115
|
+
const { tools } = recordingTools();
|
|
116
|
+
const d = await r.decide(intent({ payload: { text: "do a thing" } }), tools);
|
|
117
|
+
expect(d.ok).toBe(false);
|
|
118
|
+
expect(d.reason).toContain("no JSON");
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
test("model.complete throwing → graceful failure, not a crash", async () => {
|
|
122
|
+
const boom: Model = { complete: async () => { throw new Error("network down"); } };
|
|
123
|
+
const r = makeModelReasoner({ model: boom, manifest });
|
|
124
|
+
const { tools } = recordingTools();
|
|
125
|
+
const d = await r.decide(intent({ payload: { text: "hello" } }), tools);
|
|
126
|
+
expect(d.ok).toBe(false);
|
|
127
|
+
expect(d.reason).toContain("network down");
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
test("say.set → the reply streams straight into the reflection surface (no chat bubble)", async () => {
|
|
131
|
+
const reflTargets: ManifestTarget[] = [{ id: "reflection", kind: "reflection", accepts: ["say.set"] }];
|
|
132
|
+
const reflManifest = (): Manifest => buildManifest("loop", reflTargets, { surfaces: ["reflection"], readable: [] });
|
|
133
|
+
const r = makeModelReasoner({ model: model('{"action":"say.set","target":"reflection","payload":{"text":"noted"},"reply":"Noted: clear Thursday."}'), manifest: reflManifest });
|
|
134
|
+
const { tools, ops } = recordingTools();
|
|
135
|
+
const d = await r.decide(intent({ action: "say.set", surface: "reflection", payload: { text: "clear thursday" } }), tools);
|
|
136
|
+
|
|
137
|
+
expect(d.ok).toBe(true);
|
|
138
|
+
expect(targetsOf(ops.filter((o) => o.op === "type"))).toEqual(new Array([...("Noted: clear Thursday.")].length + 1).fill("reflection"));
|
|
139
|
+
expect(ops.every((o) => o.target === "reflection")).toBe(true); // no chat-log bubble machinery
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
test("direct verb (control click, no message) → executed without consulting the model", async () => {
|
|
143
|
+
let called = false;
|
|
144
|
+
const spy: Model = { complete: async () => { called = true; return "{}"; } };
|
|
145
|
+
const r = makeModelReasoner({ model: spy, manifest });
|
|
146
|
+
const { tools, archived } = recordingTools();
|
|
147
|
+
const d = await r.decide(intent({ action: "item.archive", surface: "item:ITM-1", payload: {} }), tools);
|
|
148
|
+
|
|
149
|
+
expect(d.ok).toBe(true);
|
|
150
|
+
expect(called).toBe(false); // the human already decided — no model turn
|
|
151
|
+
expect(archived).toEqual(["ITM-1"]);
|
|
152
|
+
});
|