@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/plan.d.ts ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The approval card's state (ApprovalCard): step ticks with their dependants, the method, tries left,
3
+ * and "answered once". The confirmation is always bound to the plan's hash from the server; a host's own card cannot
4
+ * send one without it (A_host_override_cannot_bypass_core_safety).
5
+ */
6
+ export interface PlanStepView {
7
+ index: number;
8
+ text: string;
9
+ tool: string;
10
+ undoable: boolean;
11
+ facts: {
12
+ key: string;
13
+ args: Record<string, string>;
14
+ }[];
15
+ diff: {
16
+ name: string;
17
+ args: Record<string, string>;
18
+ before: string | null;
19
+ after: string | null;
20
+ }[];
21
+ dependsOn: number[];
22
+ ticked: boolean;
23
+ }
24
+ export interface PlanView {
25
+ id: string;
26
+ hash: string;
27
+ title: string;
28
+ /** How the person confirms: the server's names (a click, their PIN, a code, a TOTP code, signing in again, on another device). */
29
+ method: "click" | "pin" | "code" | "totp" | "step_up" | "remote";
30
+ warning: string | null;
31
+ steps: PlanStepView[];
32
+ readOnly: boolean;
33
+ expiresAt: string | null;
34
+ answered: "confirmed" | "refused" | null;
35
+ triesLeft: number | null;
36
+ failCode: string | null;
37
+ }
38
+ /** The card's view model from the server's card body. */
39
+ export declare function planView(card: unknown): PlanView;
40
+ /** Ticks or unticks a step; unticking a step unticks every step that uses what it makes. */
41
+ export declare function toggle(plan: PlanView, index: number): PlanView;
42
+ /** Whether a method needs a code typed on the card (a click does not; neither does an approval on another device). */
43
+ export declare function needsCode(method: PlanView["method"]): boolean;
44
+ /** What the confirmation sends: the server's hash, the code, the unticked steps; null when nothing is left or it was answered. */
45
+ export declare function confirmation(plan: PlanView, code: string | null): {
46
+ planId: string;
47
+ hash: string;
48
+ code: string | null;
49
+ skip: number[];
50
+ } | null;
51
+ /** The server's answer that an approval (the person's phone, a second person) has not come yet: not an error, not done. */
52
+ export declare const WAITING = "confirm.waiting";
53
+ /** The card after the server's answer to a confirmation. */
54
+ export declare function afterConfirm(plan: PlanView, ok: boolean, body: unknown): PlanView;
55
+ /** Cards that take one answer (ask, learn, routine): the first answer stays; a second is ignored. */
56
+ export declare class AnsweredCards {
57
+ private readonly answers;
58
+ answer(cardId: string, value: string): boolean;
59
+ of(cardId: string): string | undefined;
60
+ }
package/dist/plan.js ADDED
@@ -0,0 +1,117 @@
1
+ /**
2
+ * The approval card's state (ApprovalCard): step ticks with their dependants, the method, tries left,
3
+ * and "answered once". The confirmation is always bound to the plan's hash from the server; a host's own card cannot
4
+ * send one without it (A_host_override_cannot_bypass_core_safety).
5
+ */
6
+ import { arr, num, obj, str } from "./api.js";
7
+ function refs(input) {
8
+ const found = new Set();
9
+ const walk = (v) => {
10
+ if (typeof v === "string")
11
+ for (const m of v.matchAll(/\$(\d+)\./gu))
12
+ found.add(Number(m[1]));
13
+ else if (Array.isArray(v))
14
+ v.forEach(walk);
15
+ else if (v !== null && typeof v === "object")
16
+ Object.values(v).forEach(walk);
17
+ };
18
+ walk(input);
19
+ return [...found].sort((a, b) => a - b);
20
+ }
21
+ /** The text arguments of a text line (anything that is not text is dropped). */
22
+ function texts(args) {
23
+ return Object.fromEntries(Object.entries(obj(args)).filter((e) => typeof e[1] === "string"));
24
+ }
25
+ /** The card's view model from the server's card body. */
26
+ export function planView(card) {
27
+ const b = obj(card);
28
+ const methods = new Set(["click", "pin", "code", "totp", "step_up", "remote"]);
29
+ const steps = arr(b["steps"]).map(obj).map((s, i) => ({
30
+ index: num(s["index"], i + 1),
31
+ text: str(s["text"], str(s["tool"])),
32
+ tool: str(s["tool"]),
33
+ undoable: s["undoable"] !== false,
34
+ facts: arr(s["facts"]).map(obj).map((f) => ({ key: str(f["key"]), args: texts(f["args"]) })),
35
+ diff: arr(s["diff"]).map(obj).map((d) => ({ name: str(obj(d["name"])["key"], str(d["name"])), args: texts(obj(d["name"])["args"]), before: typeof d["before"] === "string" ? d["before"] : null, after: typeof d["after"] === "string" ? d["after"] : null })),
36
+ dependsOn: refs(s["input"]),
37
+ ticked: true,
38
+ }));
39
+ const warning = obj(b["warning"]);
40
+ return {
41
+ id: str(b["id"]),
42
+ hash: str(b["hash"]),
43
+ title: str(b["title"]),
44
+ // A method this client does not know is never taken for a click: it asks for a code, and the server decides.
45
+ method: (methods.has(str(b["method"])) ? str(b["method"]) : str(b["method"]).length > 0 ? "code" : "click"),
46
+ warning: typeof warning["key"] === "string" ? warning["key"] : null,
47
+ steps,
48
+ readOnly: b["readOnly"] === true,
49
+ expiresAt: typeof b["expiresAt"] === "string" ? b["expiresAt"] : null,
50
+ answered: null,
51
+ triesLeft: null,
52
+ failCode: null,
53
+ };
54
+ }
55
+ /** Ticks or unticks a step; unticking a step unticks every step that uses what it makes. */
56
+ export function toggle(plan, index) {
57
+ const step = plan.steps.find((s) => s.index === index);
58
+ if (!step || plan.answered)
59
+ return plan;
60
+ const ticked = !step.ticked;
61
+ const off = new Set();
62
+ if (!ticked) {
63
+ off.add(index);
64
+ let grew = true;
65
+ while (grew) {
66
+ grew = false;
67
+ for (const s of plan.steps)
68
+ if (!off.has(s.index) && s.dependsOn.some((d) => off.has(d))) {
69
+ off.add(s.index);
70
+ grew = true;
71
+ }
72
+ }
73
+ }
74
+ return { ...plan, steps: plan.steps.map((s) => (off.has(s.index) ? { ...s, ticked: false } : s.index === index ? { ...s, ticked } : s)) };
75
+ }
76
+ /** Whether a method needs a code typed on the card (a click does not; neither does an approval on another device). */
77
+ export function needsCode(method) {
78
+ return method !== "click" && method !== "remote";
79
+ }
80
+ /** What the confirmation sends: the server's hash, the code, the unticked steps; null when nothing is left or it was answered. */
81
+ export function confirmation(plan, code) {
82
+ if (plan.answered || plan.hash.length === 0)
83
+ return null;
84
+ const skip = plan.steps.filter((s) => !s.ticked).map((s) => s.index);
85
+ if (skip.length === plan.steps.length)
86
+ return null;
87
+ if (needsCode(plan.method) && (code === null || code.trim().length === 0))
88
+ return null;
89
+ return { planId: plan.id, hash: plan.hash, code: needsCode(plan.method) ? code : null, skip };
90
+ }
91
+ /** The server's answer that an approval (the person's phone, a second person) has not come yet: not an error, not done. */
92
+ export const WAITING = "confirm.waiting";
93
+ /** The card after the server's answer to a confirmation. */
94
+ export function afterConfirm(plan, ok, body) {
95
+ const b = obj(body);
96
+ if (ok && b["ok"] === false)
97
+ return { ...plan, failCode: WAITING }; // 202: it waits for an approval
98
+ if (ok)
99
+ return { ...plan, answered: "confirmed", failCode: null };
100
+ const e = b["error"];
101
+ return { ...plan, failCode: typeof e === "string" ? e : str(obj(e)["code"], "error"), triesLeft: typeof b["triesLeft"] === "number" ? b["triesLeft"] : plan.triesLeft };
102
+ }
103
+ /** Cards that take one answer (ask, learn, routine): the first answer stays; a second is ignored. */
104
+ export class AnsweredCards {
105
+ constructor() {
106
+ this.answers = new Map();
107
+ }
108
+ answer(cardId, value) {
109
+ if (this.answers.has(cardId))
110
+ return false;
111
+ this.answers.set(cardId, value);
112
+ return true;
113
+ }
114
+ of(cardId) {
115
+ return this.answers.get(cardId);
116
+ }
117
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Progressive reveal without a DOM: only an answer that arrived in front of the person is
3
+ * revealed, over about 1.5 seconds, in batches no faster than one render per 80 ms; a history message, or any message
4
+ * with reduced motion, shows whole at once.
5
+ */
6
+ export declare const REVEAL_MS = 1500;
7
+ export declare const FRAME_MS = 80;
8
+ /** How much of a text is visible at a moment of its reveal. */
9
+ export declare function visibleLength(textLength: number, elapsedMs: number, reducedMotion: boolean, durationMs?: number): number;
10
+ /** The visible part, never cutting inside a word when it can help it (a cut word reads as a typo). */
11
+ export declare function visibleText(text: string, elapsedMs: number, reducedMotion: boolean, durationMs?: number): string;
12
+ /** Which messages may be revealed: those not yet watched. A message is watched once it has been shown. */
13
+ export declare class Watched {
14
+ private readonly seen;
15
+ /** Marks the messages of a loaded history as watched (they never animate). */
16
+ history(ids: Iterable<string>): void;
17
+ /** Whether a message should be revealed now; the first time only. */
18
+ reveal(id: string): boolean;
19
+ has(id: string): boolean;
20
+ }
package/dist/reveal.js ADDED
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Progressive reveal without a DOM: only an answer that arrived in front of the person is
3
+ * revealed, over about 1.5 seconds, in batches no faster than one render per 80 ms; a history message, or any message
4
+ * with reduced motion, shows whole at once.
5
+ */
6
+ export const REVEAL_MS = 1500;
7
+ export const FRAME_MS = 80;
8
+ /** How much of a text is visible at a moment of its reveal. */
9
+ export function visibleLength(textLength, elapsedMs, reducedMotion, durationMs = REVEAL_MS) {
10
+ if (reducedMotion || textLength === 0 || elapsedMs >= durationMs)
11
+ return textLength;
12
+ if (elapsedMs <= 0)
13
+ return 0;
14
+ const frames = Math.floor(elapsedMs / FRAME_MS); // batched: one step per frame
15
+ const total = Math.max(1, Math.ceil(durationMs / FRAME_MS));
16
+ return Math.min(textLength, Math.ceil((textLength * frames) / total));
17
+ }
18
+ /** The visible part, never cutting inside a word when it can help it (a cut word reads as a typo). */
19
+ export function visibleText(text, elapsedMs, reducedMotion, durationMs = REVEAL_MS) {
20
+ const n = visibleLength(text.length, elapsedMs, reducedMotion, durationMs);
21
+ if (n >= text.length)
22
+ return text;
23
+ const space = text.lastIndexOf(" ", n);
24
+ return text.slice(0, space > n * 0.6 ? space : n);
25
+ }
26
+ /** Which messages may be revealed: those not yet watched. A message is watched once it has been shown. */
27
+ export class Watched {
28
+ constructor() {
29
+ this.seen = new Set();
30
+ }
31
+ /** Marks the messages of a loaded history as watched (they never animate). */
32
+ history(ids) {
33
+ for (const id of ids)
34
+ this.seen.add(id);
35
+ }
36
+ /** Whether a message should be revealed now; the first time only. */
37
+ reveal(id) {
38
+ if (this.seen.has(id))
39
+ return false;
40
+ this.seen.add(id);
41
+ return true;
42
+ }
43
+ has(id) {
44
+ return this.seen.has(id);
45
+ }
46
+ }
package/dist/run.d.ts ADDED
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The run as the client sees it: one reducer over the run's events builds the RunView. Every transport feeds
3
+ * the same events in the same order, so streaming, long polling and the synchronous mode build the same view.
4
+ */
5
+ export interface RawEvent {
6
+ seq: number;
7
+ type: string;
8
+ at: string;
9
+ body: Record<string, unknown>;
10
+ }
11
+ export interface TextLine {
12
+ key: string;
13
+ args?: Record<string, string>;
14
+ }
15
+ export type StageId = "routing" | "reading" | "thinking" | "tooling" | "checking" | "waiting" | "running" | "role";
16
+ export interface RunView {
17
+ runId: string;
18
+ state: "queued" | "working" | "waiting-confirm" | "waiting-answer" | "done" | "failed" | "cancelled";
19
+ stages: {
20
+ id: StageId;
21
+ role?: string;
22
+ state: "idle" | "on" | "done";
23
+ }[];
24
+ progress?: TextLine;
25
+ tools: {
26
+ name: string;
27
+ title: TextLine;
28
+ state: "start" | "ok" | "fail";
29
+ }[];
30
+ streamingText?: string;
31
+ provenance?: "rule" | "learned" | "model" | "fallback" | "cached";
32
+ tier?: string;
33
+ elapsedMs: number;
34
+ longRunning: boolean;
35
+ seq: number;
36
+ code?: string;
37
+ /** Messages and cards the run wrote (in order). */
38
+ messages: Record<string, unknown>[];
39
+ cards: {
40
+ kind: string;
41
+ id: string;
42
+ body: Record<string, unknown>;
43
+ }[];
44
+ /** The structured output of a non-conversation capability. */
45
+ result?: {
46
+ used: boolean;
47
+ provenance: string;
48
+ output: unknown;
49
+ code?: string;
50
+ };
51
+ startedAt?: number;
52
+ }
53
+ /** After this long a run is shown as "still working". */
54
+ export declare const LONG_RUNNING_MS = 40000;
55
+ export declare function emptyRun(runId: string): RunView;
56
+ /** One event applied to a view (an event already seen, by its seq, changes nothing). */
57
+ export declare function reduceRun(view: RunView, e: RawEvent, now?: number): RunView;
58
+ export declare function finished(v: RunView): boolean;
59
+ /** A whole tape of events applied in order. */
60
+ export declare function replay(runId: string, events: readonly RawEvent[]): RunView;
61
+ /** The view's tools and stages without timing, for comparing two renderers or two transports. */
62
+ export declare function comparable(v: RunView): Omit<RunView, "elapsedMs" | "longRunning" | "startedAt">;
63
+ export declare function messagesOf(v: unknown): Record<string, unknown>[];
64
+ export declare function seqOf(v: unknown): number;
package/dist/run.js ADDED
@@ -0,0 +1,126 @@
1
+ /**
2
+ * The run as the client sees it: one reducer over the run's events builds the RunView. Every transport feeds
3
+ * the same events in the same order, so streaming, long polling and the synchronous mode build the same view.
4
+ */
5
+ import { arr, num, obj, str } from "./api.js";
6
+ /** After this long a run is shown as "still working". */
7
+ export const LONG_RUNNING_MS = 40000;
8
+ export function emptyRun(runId) {
9
+ return { runId, state: "queued", stages: [], tools: [], elapsedMs: 0, longRunning: false, seq: 0, messages: [], cards: [] };
10
+ }
11
+ const PROVENANCES = new Set(["rule", "learned", "model", "fallback", "cached"]);
12
+ function textLine(v) {
13
+ const o = obj(v);
14
+ const args = Object.fromEntries(Object.entries(obj(o["args"])).filter((e) => typeof e[1] === "string"));
15
+ return Object.keys(args).length > 0 ? { key: str(o["key"]), args } : { key: str(o["key"]) };
16
+ }
17
+ /** One event applied to a view (an event already seen, by its seq, changes nothing). */
18
+ export function reduceRun(view, e, now) {
19
+ if (e.seq > 0 && e.seq <= view.seq)
20
+ return view; // a replayed event (reconnect, a second transport)
21
+ const v = { ...view, seq: e.seq > 0 ? e.seq : view.seq };
22
+ const at = Date.parse(e.at);
23
+ if (Number.isFinite(at)) {
24
+ v.startedAt ?? (v.startedAt = at);
25
+ v.elapsedMs = Math.max(v.elapsedMs, at - v.startedAt);
26
+ }
27
+ if (now !== undefined && v.startedAt !== undefined)
28
+ v.elapsedMs = Math.max(v.elapsedMs, now - v.startedAt);
29
+ v.longRunning = v.elapsedMs >= LONG_RUNNING_MS && !finished(v);
30
+ const b = e.body;
31
+ switch (e.type) {
32
+ case "run.started":
33
+ if (v.state === "queued")
34
+ v.state = "working";
35
+ break;
36
+ case "stage": {
37
+ const id = str(b["id"]);
38
+ const role = typeof b["role"] === "string" ? b["role"] : undefined;
39
+ const on = b["state"] === "on";
40
+ const stages = v.stages.map((s) => (s.id === id && s.role === role ? { ...s, state: on ? "on" : "done" } : s));
41
+ if (!stages.some((s) => s.id === id && s.role === role))
42
+ stages.push(role === undefined ? { id, state: on ? "on" : "done" } : { id, role, state: on ? "on" : "done" });
43
+ v.stages = stages;
44
+ if (on && v.state === "queued")
45
+ v.state = "working";
46
+ if (!on && id === "waiting" && (v.state === "waiting-confirm" || v.state === "waiting-answer"))
47
+ v.state = "working";
48
+ break;
49
+ }
50
+ case "progress":
51
+ v.progress = textLine(b);
52
+ break;
53
+ case "tool": {
54
+ const name = str(b["name"]);
55
+ const state = b["state"] === "ok" ? "ok" : b["state"] === "fail" ? "fail" : "start";
56
+ const tools = v.tools.filter((t) => !(t.name === name && t.state === "start"));
57
+ tools.push({ name, title: textLine(b["title"]), state });
58
+ v.tools = tools;
59
+ break;
60
+ }
61
+ case "tier":
62
+ v.tier = str(b["tier"]);
63
+ break;
64
+ case "text.delta":
65
+ v.streamingText = (v.streamingText ?? "") + str(b["text"]);
66
+ break;
67
+ case "message": {
68
+ const m = obj(b["message"]);
69
+ v.messages = [...v.messages, m];
70
+ if (m["role"] === "assistant")
71
+ delete v.streamingText; // the whole message replaces the stream
72
+ if (typeof m["provenance"] === "string" && PROVENANCES.has(m["provenance"]))
73
+ v.provenance = m["provenance"];
74
+ break;
75
+ }
76
+ case "card":
77
+ v.cards = [...v.cards, { kind: str(b["kind"]), id: str(b["id"]), body: obj(b["body"]) }];
78
+ break;
79
+ case "waiting":
80
+ v.state = b["for"] === "answer" ? "waiting-answer" : "waiting-confirm";
81
+ break;
82
+ case "result": {
83
+ const result = { used: b["used"] === true, provenance: str(b["provenance"]), output: b["output"] ?? null };
84
+ if (typeof b["code"] === "string")
85
+ result.code = b["code"];
86
+ v.result = result;
87
+ break;
88
+ }
89
+ case "run.finished": {
90
+ v.state = b["outcome"] === "done" ? "done" : b["outcome"] === "cancelled" ? "cancelled" : "failed";
91
+ if (typeof b["code"] === "string")
92
+ v.code = b["code"];
93
+ if (typeof b["provenance"] === "string" && PROVENANCES.has(b["provenance"]) && v.provenance === undefined)
94
+ v.provenance = b["provenance"];
95
+ v.stages = v.stages.map((s) => (s.state === "on" ? { ...s, state: "done" } : s));
96
+ v.longRunning = false;
97
+ break;
98
+ }
99
+ default:
100
+ break; // round, guard, reconnect and unknown types leave the view as it is
101
+ }
102
+ if (v.streamingText === undefined)
103
+ delete v.streamingText;
104
+ return v;
105
+ }
106
+ export function finished(v) {
107
+ return v.state === "done" || v.state === "failed" || v.state === "cancelled";
108
+ }
109
+ /** A whole tape of events applied in order. */
110
+ export function replay(runId, events) {
111
+ return events.reduce((v, e) => reduceRun(v, e), emptyRun(runId));
112
+ }
113
+ /** The view's tools and stages without timing, for comparing two renderers or two transports. */
114
+ export function comparable(v) {
115
+ const rest = { ...v };
116
+ delete rest.elapsedMs;
117
+ delete rest.longRunning;
118
+ delete rest.startedAt;
119
+ return rest;
120
+ }
121
+ export function messagesOf(v) {
122
+ return arr(obj(v)["messages"]).map(obj);
123
+ }
124
+ export function seqOf(v) {
125
+ return num(obj(v)["seq"]);
126
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The assistant's state for the page (state.ts and budget.ts): its mode (on, offline with why and until when,
3
+ * off), cards waiting, and the usage windows, read again every so often and paused in the background.
4
+ */
5
+ import type { AssistantApi } from "./api.js";
6
+ import type { AssistantHost } from "./host.js";
7
+ export interface UsageWindow {
8
+ name: string;
9
+ used: number;
10
+ limit: number;
11
+ resetsAt: string | null;
12
+ }
13
+ export interface AssistantState {
14
+ mode: "on" | "offline" | "off";
15
+ reason: string | null;
16
+ until: string | null;
17
+ waiting: number;
18
+ usage: UsageWindow[];
19
+ /** A speech service is ready on the server (the microphone shows only then, or when the device dictates). */
20
+ voice: boolean;
21
+ }
22
+ export declare const OFF: AssistantState;
23
+ export declare function readState(raw: unknown): AssistantState;
24
+ /** A usage window for display: the share left (0..1) and the time to its reset. */
25
+ export declare function windowView(w: UsageWindow, nowMs: number): {
26
+ left: number;
27
+ resetInMs: number | null;
28
+ };
29
+ /** Reads the state every interval (60 s by default) while the page is in front, and tells its listeners. */
30
+ export declare class StateWatch {
31
+ private readonly api;
32
+ private readonly host;
33
+ private readonly intervalMs;
34
+ private current;
35
+ private readonly listeners;
36
+ private handle;
37
+ private hidden;
38
+ private stopped;
39
+ constructor(api: AssistantApi, host: AssistantHost, intervalMs?: number);
40
+ get state(): AssistantState;
41
+ subscribe(listener: (s: AssistantState) => void): () => void;
42
+ start(): void;
43
+ stop(): void;
44
+ refresh(): Promise<AssistantState>;
45
+ }
package/dist/state.js ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The assistant's state for the page (state.ts and budget.ts): its mode (on, offline with why and until when,
3
+ * off), cards waiting, and the usage windows, read again every so often and paused in the background.
4
+ */
5
+ import { arr, num, obj, str } from "./api.js";
6
+ import { timer } from "./host.js";
7
+ export const OFF = { mode: "off", reason: null, until: null, waiting: 0, usage: [], voice: false };
8
+ export function readState(raw) {
9
+ const s = obj(raw);
10
+ const mode = s["mode"] === "on" ? "on" : s["mode"] === "offline" ? "offline" : "off";
11
+ return {
12
+ mode,
13
+ reason: typeof s["reason"] === "string" ? s["reason"] : null,
14
+ until: typeof s["until"] === "string" ? s["until"] : null,
15
+ waiting: num(s["waiting"]),
16
+ // Only this capability's model backend; the share used is a percent of the window.
17
+ voice: s["voice"] === true,
18
+ usage: arr(obj(s["usage"])["windows"]).map(obj).map((u) => ({ name: str(u["name"]), used: num(u["usedPercent"]), limit: 100, resetsAt: typeof u["resetsAt"] === "string" ? u["resetsAt"] : null })),
19
+ };
20
+ }
21
+ /** A usage window for display: the share left (0..1) and the time to its reset. */
22
+ export function windowView(w, nowMs) {
23
+ const left = w.limit > 0 ? Math.max(0, Math.min(1, 1 - w.used / w.limit)) : 1;
24
+ const reset = w.resetsAt === null ? null : Date.parse(w.resetsAt);
25
+ return { left, resetInMs: reset === null || !Number.isFinite(reset) ? null : Math.max(0, reset - nowMs) };
26
+ }
27
+ /** Reads the state every interval (60 s by default) while the page is in front, and tells its listeners. */
28
+ export class StateWatch {
29
+ constructor(api, host, intervalMs = 60000) {
30
+ this.api = api;
31
+ this.host = host;
32
+ this.intervalMs = intervalMs;
33
+ this.current = OFF;
34
+ this.listeners = new Set();
35
+ this.hidden = false;
36
+ this.stopped = true;
37
+ host.onBackground?.((h) => {
38
+ this.hidden = h;
39
+ if (!h && !this.stopped)
40
+ void this.refresh();
41
+ });
42
+ }
43
+ get state() {
44
+ return this.current;
45
+ }
46
+ subscribe(listener) {
47
+ this.listeners.add(listener);
48
+ listener(this.current);
49
+ return () => this.listeners.delete(listener);
50
+ }
51
+ start() {
52
+ if (!this.stopped)
53
+ return;
54
+ this.stopped = false;
55
+ void this.refresh();
56
+ }
57
+ stop() {
58
+ this.stopped = true;
59
+ timer(this.host).clear(this.handle);
60
+ }
61
+ async refresh() {
62
+ const t = timer(this.host);
63
+ t.clear(this.handle);
64
+ try {
65
+ this.current = readState(await this.api.state());
66
+ }
67
+ catch {
68
+ // keep the last state; the next read tries again
69
+ }
70
+ for (const l of this.listeners)
71
+ l(this.current);
72
+ // Hidden: no read (the page coming back reads at once and starts the interval again).
73
+ if (!this.stopped)
74
+ this.handle = t.set(() => { if (!this.hidden)
75
+ void this.refresh(); }, this.intervalMs);
76
+ return this.current;
77
+ }
78
+ }
package/dist/text.d.ts ADDED
@@ -0,0 +1,35 @@
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
+ export type Inline = {
7
+ kind: "text";
8
+ text: string;
9
+ } | {
10
+ kind: "bold";
11
+ text: string;
12
+ } | {
13
+ kind: "code";
14
+ text: string;
15
+ } | {
16
+ kind: "link";
17
+ text: string;
18
+ href: string | null;
19
+ };
20
+ export type TextBlock = {
21
+ kind: "paragraph";
22
+ inlines: Inline[];
23
+ } | {
24
+ kind: "list";
25
+ ordered: boolean;
26
+ items: Inline[][];
27
+ };
28
+ /** Whether a link may be opened: https only, and only to the host's allowed hosts. */
29
+ export declare function safeHref(href: string, linkHosts: readonly string[]): string | null;
30
+ /** Inline tokens of one line: **bold**, `code` and [text](link); anything else is plain text (no HTML is ever read). */
31
+ export declare function inlines(line: string, linkHosts: readonly string[]): Inline[];
32
+ /** The model's text as paragraphs and lists (a blank line ends a paragraph). */
33
+ export declare function parseText(text: string | null | undefined, linkHosts?: readonly string[]): TextBlock[];
34
+ /** Plain text of tokens (for copying and for screen readers). */
35
+ export declare function plainText(blocks: readonly TextBlock[]): string;