@g9tm/aiassistant 0.0.0-stage → 1.0.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/dist/text.js ADDED
@@ -0,0 +1,115 @@
1
+ /**
2
+ * The model's text, safely (rules 7 and 8): never HTML. A small Markdown subset becomes tokens a renderer draws
3
+ * as plain text nodes: paragraphs, bullet and numbered lists, bold, inline code and links. A link is clickable only when
4
+ * it is https on one of the host's link hosts; remote images are never loaded (they stay text).
5
+ */
6
+ /** Whether a link may be opened: https only, and only to the host's allowed hosts. */
7
+ export function safeHref(href, linkHosts) {
8
+ const url = href.trim();
9
+ if (!url.toLowerCase().startsWith("https://") || /[\s<>"'\\]/u.test(url))
10
+ return null;
11
+ const rest = url.slice(8);
12
+ if ((rest.split(/[/?#]/u)[0] ?? "").includes("@"))
13
+ return null; // user info: https://allowed:443@evil.com opens evil.com
14
+ let end = rest.length;
15
+ for (const stop of ["/", "?", "#", ":"]) {
16
+ const at = rest.indexOf(stop);
17
+ if (at >= 0 && at < end)
18
+ end = at;
19
+ }
20
+ const host = rest.slice(0, end).toLowerCase();
21
+ if (host.length === 0 || !/^[a-z0-9.-]+$/u.test(host))
22
+ return null;
23
+ return linkHosts.some((h) => host === h.toLowerCase() || host.endsWith("." + h.toLowerCase())) ? url : null;
24
+ }
25
+ /** Inline tokens of one line: **bold**, `code` and [text](link); anything else is plain text (no HTML is ever read). */
26
+ export function inlines(line, linkHosts) {
27
+ const out = [];
28
+ let plain = "";
29
+ const flush = () => {
30
+ if (plain.length > 0)
31
+ out.push({ kind: "text", text: plain });
32
+ plain = "";
33
+ };
34
+ for (let i = 0; i < line.length;) {
35
+ const rest = line.slice(i);
36
+ const bold = /^\*\*([^*]+)\*\*/u.exec(rest);
37
+ const code = /^`([^`]+)`/u.exec(rest);
38
+ const link = /^\[([^\]]+)\]\(([^)\s]+)\)/u.exec(rest);
39
+ const image = /^!\[([^\]]*)\]\(([^)\s]+)\)/u.exec(rest);
40
+ if (image) {
41
+ flush();
42
+ out.push({ kind: "text", text: image[1] ?? "" }); // a remote image is never loaded
43
+ i += image[0].length;
44
+ }
45
+ else if (bold) {
46
+ flush();
47
+ out.push({ kind: "bold", text: bold[1] ?? "" });
48
+ i += bold[0].length;
49
+ }
50
+ else if (code) {
51
+ flush();
52
+ out.push({ kind: "code", text: code[1] ?? "" });
53
+ i += code[0].length;
54
+ }
55
+ else if (link) {
56
+ flush();
57
+ out.push({ kind: "link", text: link[1] ?? "", href: safeHref(link[2] ?? "", linkHosts) });
58
+ i += link[0].length;
59
+ }
60
+ else {
61
+ plain += line.charAt(i);
62
+ i++;
63
+ }
64
+ }
65
+ flush();
66
+ return out;
67
+ }
68
+ /** The model's text as paragraphs and lists (a blank line ends a paragraph). */
69
+ export function parseText(text, linkHosts = []) {
70
+ if (typeof text !== "string" || text.length === 0)
71
+ return [];
72
+ const blocks = [];
73
+ let paragraph = [];
74
+ let list = null;
75
+ const endParagraph = () => {
76
+ if (paragraph.length > 0)
77
+ blocks.push({ kind: "paragraph", inlines: inlines(paragraph.join("\n"), linkHosts) });
78
+ paragraph = [];
79
+ };
80
+ const endList = () => {
81
+ if (list)
82
+ blocks.push({ kind: "list", ordered: list.ordered, items: list.items });
83
+ list = null;
84
+ };
85
+ for (const raw of text.replace(/\r\n?/gu, "\n").split("\n")) {
86
+ const line = raw.trimEnd();
87
+ const bullet = /^\s*[-*•]\s+(.*)$/u.exec(line);
88
+ const numbered = /^\s*[0-9۰-۹]+[.)]\s+(.*)$/u.exec(line);
89
+ if (bullet || numbered) {
90
+ endParagraph();
91
+ const ordered = numbered !== null;
92
+ if (list === null || list.ordered !== ordered) {
93
+ endList();
94
+ list = { ordered, items: [] };
95
+ }
96
+ list.items.push(inlines((bullet ?? numbered)?.[1] ?? "", linkHosts));
97
+ }
98
+ else if (line.trim().length === 0) {
99
+ endParagraph();
100
+ endList();
101
+ }
102
+ else {
103
+ endList();
104
+ paragraph.push(line);
105
+ }
106
+ }
107
+ endParagraph();
108
+ endList();
109
+ return blocks;
110
+ }
111
+ /** Plain text of tokens (for copying and for screen readers). */
112
+ export function plainText(blocks) {
113
+ const line = (xs) => xs.map((x) => x.text).join("");
114
+ return blocks.map((b) => (b.kind === "paragraph" ? line(b.inlines) : b.items.map((it, n) => (b.ordered ? String(n + 1) + ". " : "• ") + line(it)).join("\n"))).join("\n\n");
115
+ }
@@ -0,0 +1,4 @@
1
+ /** The conversation as plain text for "copy all": questions and answers, tables with tabs, blocks as text. */
2
+ import type { MessageView } from "./conversation.js";
3
+ import type { Texts } from "./i18n.js";
4
+ export declare function transcript(messages: readonly MessageView[], texts: Texts): string;
@@ -0,0 +1,26 @@
1
+ /** The conversation as plain text for "copy all": questions and answers, tables with tabs, blocks as text. */
2
+ import { blockView } from "./blocks.js";
3
+ export function transcript(messages, texts) {
4
+ const out = [];
5
+ for (const m of messages) {
6
+ if (m.pending || m.card !== null || (m.kind !== "text" && m.kind !== "block"))
7
+ continue;
8
+ const lines = [(m.role === "user" ? texts.t("transcript.you") : texts.t("transcript.assistant")) + ":"];
9
+ if (m.text.length > 0)
10
+ lines.push(m.text);
11
+ for (const raw of m.blocks) {
12
+ const b = blockView(raw, texts.locale);
13
+ if (b.type === "table") {
14
+ if (b.title)
15
+ lines.push(b.title);
16
+ lines.push(b.columns.map((c) => c.label).join("\t"));
17
+ for (const r of b.rows)
18
+ lines.push(r.join("\t"));
19
+ }
20
+ else if (b.fallbackText.length > 0)
21
+ lines.push(b.fallbackText);
22
+ }
23
+ out.push(lines.join("\n"));
24
+ }
25
+ return out.join("\n\n");
26
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Three transports, one interface: server-sent events (with a short-lived stream ticket), long polling, and the
3
+ * synchronous mode. Each hands the same events to the run, so the renderer never knows which is in use. Two stream
4
+ * failures in a row fall back to polling for the rest of the session; polling pauses while the app is in the background.
5
+ */
6
+ import type { AssistantApi } from "./api.js";
7
+ import type { AssistantHost } from "./host.js";
8
+ import type { RawEvent } from "./run.js";
9
+ export interface TransportHandlers {
10
+ onEvent(e: RawEvent): void;
11
+ /** The run finished, or the transport stopped for good (with the reason). */
12
+ onEnd(reason: "finished" | "stopped" | "failed"): void;
13
+ }
14
+ export interface Transport {
15
+ readonly kind: "sse" | "poll" | "sync";
16
+ /** Follows a run from a cursor; returns a function that stops following. */
17
+ follow(runId: string, after: number, handlers: TransportHandlers): () => void;
18
+ }
19
+ /** Long polling: waits up to 25 s on the server; between empty answers 1.2 s, then 3 s after 30 s, 6 s after 2 minutes. */
20
+ export declare class PollTransport implements Transport {
21
+ private readonly api;
22
+ private readonly host;
23
+ private readonly wait;
24
+ readonly kind: "poll";
25
+ private hidden;
26
+ constructor(api: AssistantApi, host: AssistantHost, wait?: number);
27
+ static gap(sinceStartMs: number): number;
28
+ follow(runId: string, after: number, h: TransportHandlers): () => void;
29
+ }
30
+ /** The synchronous mode (the migration period): one request that waits up to 50 s, then polling. */
31
+ export declare class SyncTransport implements Transport {
32
+ readonly kind: "sync";
33
+ private readonly poll;
34
+ constructor(api: AssistantApi, host: AssistantHost);
35
+ follow(runId: string, after: number, h: TransportHandlers): () => void;
36
+ }
37
+ /** Server-sent events through the host's EventSource, with a stream ticket (EventSource sends no headers). */
38
+ export declare class SseTransport implements Transport {
39
+ private readonly api;
40
+ private readonly host;
41
+ private readonly fallback;
42
+ readonly kind: "sse";
43
+ failures: number;
44
+ constructor(api: AssistantApi, host: AssistantHost, fallback: PollTransport);
45
+ follow(runId: string, after: number, h: TransportHandlers): () => void;
46
+ }
47
+ /** The transport to use: streaming when the host can and it has not failed here; else polling; sync when asked. */
48
+ export declare function pickTransport(api: AssistantApi, host: AssistantHost, options?: {
49
+ sse?: boolean;
50
+ sync?: boolean;
51
+ }): Transport;
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Three transports, one interface: server-sent events (with a short-lived stream ticket), long polling, and the
3
+ * synchronous mode. Each hands the same events to the run, so the renderer never knows which is in use. Two stream
4
+ * failures in a row fall back to polling for the rest of the session; polling pauses while the app is in the background.
5
+ */
6
+ import { toRawEvent } from "./api.js";
7
+ import { timer } from "./host.js";
8
+ const EVENT_TYPES = ["run.started", "stage", "tier", "progress", "tool", "text.delta", "message", "card", "waiting", "round", "guard", "result", "reconnect", "run.finished"];
9
+ /** Long polling: waits up to 25 s on the server; between empty answers 1.2 s, then 3 s after 30 s, 6 s after 2 minutes. */
10
+ export class PollTransport {
11
+ constructor(api, host, wait = 25) {
12
+ this.api = api;
13
+ this.host = host;
14
+ this.wait = wait;
15
+ this.kind = "poll";
16
+ this.hidden = false;
17
+ host.onBackground?.((h) => { this.hidden = h; });
18
+ }
19
+ static gap(sinceStartMs) {
20
+ return sinceStartMs < 30000 ? 1200 : sinceStartMs < 120000 ? 3000 : 6000;
21
+ }
22
+ follow(runId, after, h) {
23
+ const t = timer(this.host);
24
+ const started = t.now();
25
+ let stopped = false;
26
+ let cursor = after;
27
+ let handle;
28
+ const tick = async () => {
29
+ if (stopped)
30
+ return;
31
+ if (this.hidden) {
32
+ handle = t.set(() => void tick(), 1000);
33
+ return;
34
+ } // paused in the background
35
+ try {
36
+ const page = await this.api.events(runId, cursor, this.wait);
37
+ if (stopped)
38
+ return;
39
+ for (const e of page.events) {
40
+ cursor = Math.max(cursor, e.seq);
41
+ h.onEvent(e);
42
+ }
43
+ cursor = Math.max(cursor, page.last);
44
+ if (page.finished) {
45
+ h.onEnd("finished");
46
+ return;
47
+ }
48
+ handle = t.set(() => void tick(), page.events.length > 0 ? 0 : PollTransport.gap(t.now() - started));
49
+ }
50
+ catch {
51
+ if (!stopped)
52
+ handle = t.set(() => void tick(), 3000);
53
+ }
54
+ };
55
+ void tick();
56
+ return () => { stopped = true; t.clear(handle); h.onEnd("stopped"); };
57
+ }
58
+ }
59
+ /** The synchronous mode (the migration period): one request that waits up to 50 s, then polling. */
60
+ export class SyncTransport {
61
+ constructor(api, host) {
62
+ this.kind = "sync";
63
+ this.poll = new PollTransport(api, host, 50);
64
+ }
65
+ follow(runId, after, h) {
66
+ return this.poll.follow(runId, after, h);
67
+ }
68
+ }
69
+ /** Server-sent events through the host's EventSource, with a stream ticket (EventSource sends no headers). */
70
+ export class SseTransport {
71
+ constructor(api, host, fallback) {
72
+ this.api = api;
73
+ this.host = host;
74
+ this.fallback = fallback;
75
+ this.kind = "sse";
76
+ this.failures = 0;
77
+ }
78
+ follow(runId, after, h) {
79
+ let stopped = false;
80
+ let cursor = after;
81
+ let close = () => { };
82
+ let polling = false;
83
+ const open = async () => {
84
+ if (stopped)
85
+ return;
86
+ if (this.failures >= 2 || !this.host.eventSource) {
87
+ polling = true;
88
+ close = this.fallback.follow(runId, cursor, h);
89
+ return;
90
+ }
91
+ try {
92
+ const ticket = await this.api.ticket(runId);
93
+ if (stopped)
94
+ return;
95
+ const source = this.host.eventSource(this.api.streamUrl(runId, cursor, ticket));
96
+ let ended = false;
97
+ close = () => source.close();
98
+ for (const type of EVENT_TYPES) {
99
+ source.addEventListener(type, (m) => {
100
+ let e;
101
+ try {
102
+ e = toRawEvent(JSON.parse(m.data));
103
+ }
104
+ catch {
105
+ return;
106
+ }
107
+ cursor = Math.max(cursor, e.seq);
108
+ this.failures = 0;
109
+ if (e.type === "reconnect") {
110
+ source.close();
111
+ void open();
112
+ return;
113
+ } // the server ended the stream: continue from the cursor
114
+ h.onEvent(e);
115
+ if (e.type === "run.finished") {
116
+ ended = true;
117
+ source.close();
118
+ h.onEnd("finished");
119
+ }
120
+ });
121
+ }
122
+ source.onerror = () => {
123
+ if (ended || stopped)
124
+ return;
125
+ source.close();
126
+ this.failures++;
127
+ void open(); // two failures in a row: polling for the rest of the session
128
+ };
129
+ }
130
+ catch {
131
+ this.failures++;
132
+ if (!stopped)
133
+ void open();
134
+ }
135
+ };
136
+ void open();
137
+ return () => {
138
+ stopped = true;
139
+ close();
140
+ if (!polling)
141
+ h.onEnd("stopped"); // polling ends the run itself when it stops
142
+ };
143
+ }
144
+ }
145
+ /** The transport to use: streaming when the host can and it has not failed here; else polling; sync when asked. */
146
+ export function pickTransport(api, host, options = {}) {
147
+ const poll = new PollTransport(api, host);
148
+ if (options.sync)
149
+ return new SyncTransport(api, host);
150
+ if (options.sse !== false && host.eventSource)
151
+ return new SseTransport(api, host, poll);
152
+ return poll;
153
+ }
@@ -0,0 +1,22 @@
1
+ /** Small shared types of the client core. */
2
+ export type Provenance = "rule" | "learned" | "model" | "fallback" | "cached";
3
+ /** The layouts of the ready-made components (layer 1). */
4
+ export type Layout = "sheet" | "side" | "fullscreen" | "inline" | "card" | "compact" | "auto";
5
+ /** Container widths at which "auto" picks a layout (by the container, not the window). */
6
+ export interface LayoutThresholds {
7
+ compact: number;
8
+ sheet: number;
9
+ }
10
+ export declare const DEFAULT_THRESHOLDS: LayoutThresholds;
11
+ /** The layout "auto" picks for a container width. */
12
+ export declare function pickLayout(layout: Layout, containerWidth: number, thresholds?: LayoutThresholds): Exclude<Layout, "auto">;
13
+ /** The stable part names hosts style and replace (layer 3): part of the public, versioned contract. */
14
+ export declare const PARTS: readonly ["panel", "panel.header", "panel.body", "panel.footer", "hero", "bar-button", "ask-about", "chat", "messages", "message", "message.user", "message.assistant", "message.text", "message.provenance", "message.feedback", "composer", "composer.input", "composer.attach", "composer.mic", "composer.send", "composer.stop", "file-chips", "file-chip", "work", "work.stage", "work.progress", "work.tool", "work.elapsed", "card.approval", "card.approval.step", "card.approval.fact", "card.approval.code", "card.approval.confirm", "card.approval.refuse", "card.undo", "card.ask", "card.choice", "secret-field", "block", "block.text", "block.callout", "block.table", "block.table.card", "block.chart", "block.chart.bar", "block.chart.line", "block.kpi", "block.steps", "block.actions", "block.action", "block.flow", "block.image", "block.open", "block.fallback", "mode-banner", "usage-chip", "thinking-orb", "stages-thinking", "reveal-text"];
15
+ export type PartName = (typeof PARTS)[number];
16
+ /** Per-part classes and styles from the host (layer 3). */
17
+ export interface PartStyles {
18
+ classes?: Partial<Record<PartName, string>>;
19
+ styles?: Partial<Record<PartName, string>>;
20
+ }
21
+ /** The class of a part: the library's stable class plus the host's. */
22
+ export declare function partClass(part: PartName, styles: PartStyles | undefined, unstyled?: boolean): string;
package/dist/types.js ADDED
@@ -0,0 +1,28 @@
1
+ /** Small shared types of the client core. */
2
+ export const DEFAULT_THRESHOLDS = { compact: 360, sheet: 720 };
3
+ /** The layout "auto" picks for a container width. */
4
+ export function pickLayout(layout, containerWidth, thresholds = DEFAULT_THRESHOLDS) {
5
+ if (layout !== "auto")
6
+ return layout;
7
+ if (containerWidth < thresholds.compact)
8
+ return "compact";
9
+ return containerWidth < thresholds.sheet ? "sheet" : "side";
10
+ }
11
+ /** The stable part names hosts style and replace (layer 3): part of the public, versioned contract. */
12
+ export const PARTS = [
13
+ "panel", "panel.header", "panel.body", "panel.footer", "hero", "bar-button", "ask-about", "chat",
14
+ "messages", "message", "message.user", "message.assistant", "message.text", "message.provenance", "message.feedback",
15
+ "composer", "composer.input", "composer.attach", "composer.mic", "composer.send", "composer.stop", "file-chips", "file-chip",
16
+ "work", "work.stage", "work.progress", "work.tool", "work.elapsed",
17
+ "card.approval", "card.approval.step", "card.approval.fact", "card.approval.code", "card.approval.confirm", "card.approval.refuse",
18
+ "card.undo", "card.ask", "card.choice", "secret-field",
19
+ "block", "block.text", "block.callout", "block.table", "block.table.card", "block.chart", "block.chart.bar", "block.chart.line",
20
+ "block.kpi", "block.steps", "block.actions", "block.action", "block.flow", "block.image", "block.open", "block.fallback",
21
+ "mode-banner", "usage-chip", "thinking-orb", "stages-thinking", "reveal-text",
22
+ ];
23
+ /** The class of a part: the library's stable class plus the host's. */
24
+ export function partClass(part, styles, unstyled = false) {
25
+ const own = styles?.classes ? new Map(Object.entries(styles.classes)).get(part) : undefined;
26
+ const base = "g9a-" + part.replace(/\./gu, "__");
27
+ return [unstyled ? base + " g9a-unstyled" : base, own].filter((x) => typeof x === "string" && x.length > 0).join(" ");
28
+ }
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@g9tm/aiassistant",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0",
4
+ "description": "Headless client of the G9 AI assistant: API client, run state, transports, block view models, safe text and Persian helpers. No DOM, no framework.",
5
+ "license": "MIT",
6
+ "author": {
7
+ "name": "Iman Kari",
8
+ "url": "G9TM"
9
+ },
10
+ "type": "module",
11
+ "sideEffects": false,
12
+ "main": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js"
18
+ },
19
+ "./admin": {
20
+ "types": "./dist/admin.d.ts",
21
+ "import": "./dist/admin.js"
22
+ }
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "README.md"
27
+ ],
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "dependencies": {
32
+ "@g9tm/aiassistant-contracts": "1.0.0"
33
+ },
34
+ "scripts": {
35
+ "build": "tsc -p tsconfig.json",
36
+ "typecheck": "tsc -p tsconfig.json --noEmit"
37
+ }
6
38
  }