@open-qa/qa-stage 0.0.0-stage → 0.1.0-alpha.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.
Files changed (113) hide show
  1. package/LICENSE +204 -0
  2. package/NOTICE +7 -0
  3. package/THIRD_PARTY.md +13 -0
  4. package/THIRD_PARTY_NOTICES.md +11 -0
  5. package/package.json +68 -4
  6. package/scripts/bundle.d.ts +7 -0
  7. package/scripts/bundle.js +78 -0
  8. package/src/auth.d.ts +10 -0
  9. package/src/auth.js +26 -0
  10. package/src/blackboard-tools.d.ts +2 -0
  11. package/src/blackboard-tools.js +46 -0
  12. package/src/config.d.ts +61 -0
  13. package/src/config.js +64 -0
  14. package/src/discord-api.d.ts +47 -0
  15. package/src/discord-api.js +151 -0
  16. package/src/discord-surface.d.ts +4 -0
  17. package/src/discord-surface.js +218 -0
  18. package/src/drivers.d.ts +21 -0
  19. package/src/drivers.js +12 -0
  20. package/src/email-message.d.ts +22 -0
  21. package/src/email-message.js +114 -0
  22. package/src/email-surface.d.ts +4 -0
  23. package/src/email-surface.js +140 -0
  24. package/src/event-log.d.ts +18 -0
  25. package/src/event-log.js +46 -0
  26. package/src/expect-engine.d.ts +15 -0
  27. package/src/expect-engine.js +114 -0
  28. package/src/expect-evidence.d.ts +7 -0
  29. package/src/expect-evidence.js +68 -0
  30. package/src/flow-tools.d.ts +2 -0
  31. package/src/flow-tools.js +26 -0
  32. package/src/http-expect.d.ts +4 -0
  33. package/src/http-expect.js +68 -0
  34. package/src/index.d.ts +13 -0
  35. package/src/index.js +37 -0
  36. package/src/main.d.ts +1 -0
  37. package/src/main.js +51 -0
  38. package/src/mcp.d.ts +14 -0
  39. package/src/mcp.js +23 -0
  40. package/src/observation-tools.d.ts +3 -0
  41. package/src/observation-tools.js +39 -0
  42. package/src/page-diagnostics.d.ts +19 -0
  43. package/src/page-diagnostics.js +53 -0
  44. package/src/page-pixels.d.ts +35 -0
  45. package/src/page-pixels.js +73 -0
  46. package/src/page-policy.d.ts +48 -0
  47. package/src/page-policy.js +125 -0
  48. package/src/page-recording.d.ts +39 -0
  49. package/src/page-recording.js +532 -0
  50. package/src/page-replay.d.ts +7 -0
  51. package/src/page-replay.js +69 -0
  52. package/src/page-views.d.ts +85 -0
  53. package/src/page-views.js +338 -0
  54. package/src/rendered.d.ts +6 -0
  55. package/src/rendered.js +135 -0
  56. package/src/replay-artifacts.d.ts +2 -0
  57. package/src/replay-artifacts.js +100 -0
  58. package/src/replay-assets.d.ts +21 -0
  59. package/src/replay-assets.js +106 -0
  60. package/src/replay-budget.d.ts +22 -0
  61. package/src/replay-budget.js +47 -0
  62. package/src/replay-files.d.ts +3 -0
  63. package/src/replay-files.js +18 -0
  64. package/src/replay-privacy.d.ts +10 -0
  65. package/src/replay-privacy.js +48 -0
  66. package/src/replay-script.d.ts +2 -0
  67. package/src/replay-script.js +65 -0
  68. package/src/replay-warnings.d.ts +6 -0
  69. package/src/replay-warnings.js +16 -0
  70. package/src/replay-writer.d.ts +24 -0
  71. package/src/replay-writer.js +92 -0
  72. package/src/screen-tools.d.ts +5 -0
  73. package/src/screen-tools.js +168 -0
  74. package/src/server.d.ts +50 -0
  75. package/src/server.js +537 -0
  76. package/src/signed-artifacts.d.ts +21 -0
  77. package/src/signed-artifacts.js +127 -0
  78. package/src/sqlite-parser.d.ts +3 -0
  79. package/src/stage-clock.d.ts +2 -0
  80. package/src/stage-clock.js +7 -0
  81. package/src/surface-adapter.d.ts +65 -0
  82. package/src/surface-adapter.js +0 -0
  83. package/src/system-common.d.ts +34 -0
  84. package/src/system-common.js +123 -0
  85. package/src/system-db.d.ts +9 -0
  86. package/src/system-db.js +143 -0
  87. package/src/system-github.d.ts +6 -0
  88. package/src/system-github.js +73 -0
  89. package/src/system-http.d.ts +4 -0
  90. package/src/system-http.js +86 -0
  91. package/src/system-logs.d.ts +6 -0
  92. package/src/system-logs.js +78 -0
  93. package/src/telegram-api.d.ts +162 -0
  94. package/src/telegram-api.js +170 -0
  95. package/src/telegram-markup.d.ts +4 -0
  96. package/src/telegram-markup.js +129 -0
  97. package/src/telegram-surface.d.ts +39 -0
  98. package/src/telegram-surface.js +448 -0
  99. package/src/tool-gateway.d.ts +41 -0
  100. package/src/tool-gateway.js +696 -0
  101. package/src/tool-limits.d.ts +12 -0
  102. package/src/tool-limits.js +41 -0
  103. package/src/tool-secrets.d.ts +8 -0
  104. package/src/tool-secrets.js +38 -0
  105. package/src/vendor/gmail.d.ts +45 -0
  106. package/src/vendor/gmail.js +193 -0
  107. package/src/watch.d.ts +11 -0
  108. package/src/watch.js +30 -0
  109. package/src/web-expect.d.ts +5 -0
  110. package/src/web-expect.js +130 -0
  111. package/src/web-tools.d.ts +15 -0
  112. package/src/web-tools.js +340 -0
  113. package/README.md +0 -3
@@ -0,0 +1,86 @@
1
+ import { z } from "zod";
2
+ import { assertPageUrl } from "./page-policy.js";
3
+ import { httpExpect } from "./http-expect.js";
4
+ import {
5
+ checked,
6
+ conditionContext,
7
+ equal,
8
+ invalidSystemExpectation,
9
+ readBody,
10
+ parseJsonBody,
11
+ SystemReadError,
12
+ requestSignal,
13
+ systemOutput
14
+ } from "./system-common.js";
15
+ const input = z.strictObject({
16
+ url: z.url(),
17
+ method: z.enum(["GET", "HEAD"]).default("GET"),
18
+ headers: z.record(z.string(), z.string()).optional()
19
+ });
20
+ function httpSurface(config, fetcher = fetch) {
21
+ const read = async (raw, signal) => {
22
+ const args = input.parse(raw);
23
+ let url = args.url;
24
+ const deadline = requestSignal(signal);
25
+ for (let redirects = 0; redirects <= 5; redirects++) {
26
+ try {
27
+ assertPageUrl(url, config);
28
+ } catch {
29
+ throw new SystemReadError("url_forbidden");
30
+ }
31
+ const headers = new Headers(args.headers);
32
+ if (headers.has("host") || headers.has("cf-access-client-id") || headers.has("cf-access-client-secret"))
33
+ throw new Error("HTTP header is not allowed");
34
+ if (config.access && new URL(url).origin === config.access.origin) {
35
+ headers.set("cf-access-client-id", config.access.clientId);
36
+ headers.set("cf-access-client-secret", config.access.clientSecret);
37
+ }
38
+ const response = await fetcher(url, {
39
+ method: args.method,
40
+ redirect: "manual",
41
+ headers,
42
+ signal: deadline
43
+ });
44
+ const location = response.headers.get("location");
45
+ if (location && [301, 302, 303, 307, 308].includes(response.status)) {
46
+ await response.body?.cancel();
47
+ const next = new URL(location, url);
48
+ if (next.origin !== new URL(url).origin)
49
+ throw new Error("Cross-origin HTTP redirect is blocked");
50
+ url = next.href;
51
+ continue;
52
+ }
53
+ return { status: response.status, body: await readBody(response) };
54
+ }
55
+ throw new Error("HTTP redirect limit exceeded");
56
+ };
57
+ return {
58
+ name: "http",
59
+ expectPollIntervalMs: 5e3,
60
+ tools: [
61
+ {
62
+ name: "http_request",
63
+ description: "Read an allowlisted HTTP URL using GET or HEAD",
64
+ scope: "actor",
65
+ inputSchema: input,
66
+ execute: async (args, context) => systemOutput(await read(args, context.signal))
67
+ }
68
+ ],
69
+ expect: async (request, context) => {
70
+ if (request.condition.type === "http.status")
71
+ return httpExpect(config, fetcher)(request, context);
72
+ const parsed = z.strictObject({
73
+ ...conditionContext,
74
+ type: z.literal("http.json"),
75
+ url: z.url(),
76
+ equals: z.json()
77
+ }).safeParse(request.condition);
78
+ if (!parsed.success) return invalidSystemExpectation();
79
+ const data = await read({ url: parsed.data.url }, context.signal);
80
+ return checked(equal(parseJsonBody(data.body), parsed.data.equals), data);
81
+ }
82
+ };
83
+ }
84
+ export {
85
+ httpSurface
86
+ };
@@ -0,0 +1,6 @@
1
+ import type { SurfaceAdapter } from "./surface-adapter.js";
2
+ import { type Fetcher } from "./system-common.js";
3
+ export declare function logsSurface(config: {
4
+ project: string;
5
+ accessToken: string;
6
+ }, fetcher?: Fetcher): SurfaceAdapter;
@@ -0,0 +1,78 @@
1
+ import { z } from "zod";
2
+ import {
3
+ checked,
4
+ conditionContext,
5
+ invalidSystemExpectation,
6
+ readJson,
7
+ requestSignal,
8
+ systemOutput,
9
+ fullEvidence
10
+ } from "./system-common.js";
11
+ const input = z.strictObject({ filter: z.string().min(1).max(16e3) });
12
+ function logsSurface(config, fetcher = fetch) {
13
+ const read = async (filter, signal) => {
14
+ input.parse({ filter });
15
+ const raw = await readJson(
16
+ await fetcher("https://logging.googleapis.com/v2/entries:list", {
17
+ method: "POST",
18
+ redirect: "error",
19
+ signal: requestSignal(signal),
20
+ headers: {
21
+ authorization: `Bearer ${config.accessToken}`,
22
+ "content-type": "application/json"
23
+ },
24
+ body: JSON.stringify({
25
+ resourceNames: [`projects/${config.project}`],
26
+ filter,
27
+ pageSize: 100,
28
+ orderBy: "timestamp desc"
29
+ })
30
+ })
31
+ );
32
+ const data = z.object({
33
+ entries: z.array(z.record(z.string(), z.json())).default([]),
34
+ nextPageToken: z.string().optional()
35
+ }).parse(raw);
36
+ if (data.entries.some(
37
+ (entry) => typeof entry.logName === "string" && !entry.logName.startsWith(`projects/${config.project}/`)
38
+ ))
39
+ throw new Error("Log entry is outside the QA project");
40
+ return fullEvidence(
41
+ { entries: data.entries, total: data.entries.length, hasMore: !!data.nextPageToken },
42
+ [config.accessToken]
43
+ );
44
+ };
45
+ return {
46
+ name: "logs",
47
+ expectPollIntervalMs: 5e3,
48
+ tools: [
49
+ {
50
+ name: "logs_query",
51
+ description: "Read Cloud Logging entries in the testapp QA project",
52
+ scope: "actor",
53
+ inputSchema: input,
54
+ execute: async ({ filter }, context) => systemOutput(await read(String(filter), context.signal))
55
+ }
56
+ ],
57
+ expect: async (request, context) => {
58
+ const parsed = z.strictObject({
59
+ ...conditionContext,
60
+ type: z.enum(["logs.entry", "logs.contains"]),
61
+ filter: input.shape.filter,
62
+ contains: z.string().optional()
63
+ }).safeParse(request.condition);
64
+ if (!parsed.success) return invalidSystemExpectation();
65
+ const data = await read(parsed.data.filter, context.signal);
66
+ const entries = data.entries;
67
+ return checked(
68
+ entries.some(
69
+ (entry) => !parsed.data.contains || JSON.stringify(entry).includes(parsed.data.contains)
70
+ ),
71
+ data
72
+ );
73
+ }
74
+ };
75
+ }
76
+ export {
77
+ logsSurface
78
+ };
@@ -0,0 +1,162 @@
1
+ import { z } from "zod";
2
+ export declare const telegramMessageSchema: z.ZodObject<{
3
+ message_id: z.ZodNumber;
4
+ date: z.ZodNumber;
5
+ edit_date: z.ZodOptional<z.ZodNumber>;
6
+ chat: z.ZodObject<{
7
+ id: z.ZodNumber;
8
+ type: z.ZodString;
9
+ }, z.core.$strip>;
10
+ from: z.ZodOptional<z.ZodObject<{
11
+ id: z.ZodNumber;
12
+ is_bot: z.ZodOptional<z.ZodBoolean>;
13
+ username: z.ZodOptional<z.ZodString>;
14
+ first_name: z.ZodOptional<z.ZodString>;
15
+ }, z.core.$strip>>;
16
+ text: z.ZodOptional<z.ZodString>;
17
+ caption: z.ZodOptional<z.ZodString>;
18
+ entities: z.ZodOptional<z.ZodArray<z.ZodObject<{
19
+ type: z.ZodString;
20
+ offset: z.ZodNumber;
21
+ length: z.ZodNumber;
22
+ url: z.ZodOptional<z.ZodString>;
23
+ }, z.core.$strip>>>;
24
+ caption_entities: z.ZodOptional<z.ZodArray<z.ZodObject<{
25
+ type: z.ZodString;
26
+ offset: z.ZodNumber;
27
+ length: z.ZodNumber;
28
+ url: z.ZodOptional<z.ZodString>;
29
+ }, z.core.$strip>>>;
30
+ rich_message: z.ZodOptional<z.ZodObject<{
31
+ blocks: z.ZodArray<z.ZodRecord<z.ZodString, z.ZodJSONSchema>>;
32
+ }, z.core.$strip>>;
33
+ reply_to_message: z.ZodOptional<z.ZodObject<{
34
+ message_id: z.ZodNumber;
35
+ }, z.core.$strip>>;
36
+ reply_markup: z.ZodOptional<z.ZodObject<{
37
+ inline_keyboard: z.ZodArray<z.ZodArray<z.ZodObject<{
38
+ text: z.ZodString;
39
+ url: z.ZodOptional<z.ZodString>;
40
+ callback_data: z.ZodOptional<z.ZodString>;
41
+ }, z.core.$strip>>>;
42
+ }, z.core.$strip>>;
43
+ }, z.core.$strip>;
44
+ export type TelegramMessage = z.infer<typeof telegramMessageSchema>;
45
+ export interface TelegramApiOptions {
46
+ fetch?: typeof fetch;
47
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
48
+ retry?: (method: string, seconds: number) => void;
49
+ }
50
+ type TelegramFailure = "unauthorized" | "conflict_webhook_or_poller" | "chat_not_found" | "timeout" | "bad_response" | "request_failed";
51
+ export declare class TelegramApiError extends Error {
52
+ readonly reason: TelegramFailure;
53
+ readonly code?: number | undefined;
54
+ constructor(reason?: TelegramFailure, code?: number | undefined);
55
+ }
56
+ export declare class TelegramApi {
57
+ private readonly token;
58
+ private readonly options;
59
+ private offset;
60
+ private readonly request;
61
+ private readonly sleep;
62
+ constructor(token: string, options?: TelegramApiOptions);
63
+ call(method: "sendMessage" | "getUpdates" | "getMe" | "getChat", params: Record<string, unknown>, signal?: AbortSignal): Promise<unknown>;
64
+ private parse;
65
+ me(signal?: AbortSignal): Promise<{
66
+ id: number;
67
+ username: string;
68
+ }>;
69
+ chat(username: string, signal?: AbortSignal): Promise<{
70
+ id: number;
71
+ }>;
72
+ send(chatId: number | string, text: string, replyTo?: number, signal?: AbortSignal): Promise<TelegramMessage>;
73
+ updates(signal?: AbortSignal): Promise<{
74
+ update_id: number;
75
+ message?: {
76
+ message_id: number;
77
+ date: number;
78
+ chat: {
79
+ id: number;
80
+ type: string;
81
+ };
82
+ edit_date?: number | undefined;
83
+ from?: {
84
+ id: number;
85
+ is_bot?: boolean | undefined;
86
+ username?: string | undefined;
87
+ first_name?: string | undefined;
88
+ } | undefined;
89
+ text?: string | undefined;
90
+ caption?: string | undefined;
91
+ entities?: {
92
+ type: string;
93
+ offset: number;
94
+ length: number;
95
+ url?: string | undefined;
96
+ }[] | undefined;
97
+ caption_entities?: {
98
+ type: string;
99
+ offset: number;
100
+ length: number;
101
+ url?: string | undefined;
102
+ }[] | undefined;
103
+ rich_message?: {
104
+ blocks: Record<string, z.core.util.JSONType>[];
105
+ } | undefined;
106
+ reply_to_message?: {
107
+ message_id: number;
108
+ } | undefined;
109
+ reply_markup?: {
110
+ inline_keyboard: {
111
+ text: string;
112
+ url?: string | undefined;
113
+ callback_data?: string | undefined;
114
+ }[][];
115
+ } | undefined;
116
+ } | undefined;
117
+ edited_message?: {
118
+ message_id: number;
119
+ date: number;
120
+ chat: {
121
+ id: number;
122
+ type: string;
123
+ };
124
+ edit_date?: number | undefined;
125
+ from?: {
126
+ id: number;
127
+ is_bot?: boolean | undefined;
128
+ username?: string | undefined;
129
+ first_name?: string | undefined;
130
+ } | undefined;
131
+ text?: string | undefined;
132
+ caption?: string | undefined;
133
+ entities?: {
134
+ type: string;
135
+ offset: number;
136
+ length: number;
137
+ url?: string | undefined;
138
+ }[] | undefined;
139
+ caption_entities?: {
140
+ type: string;
141
+ offset: number;
142
+ length: number;
143
+ url?: string | undefined;
144
+ }[] | undefined;
145
+ rich_message?: {
146
+ blocks: Record<string, z.core.util.JSONType>[];
147
+ } | undefined;
148
+ reply_to_message?: {
149
+ message_id: number;
150
+ } | undefined;
151
+ reply_markup?: {
152
+ inline_keyboard: {
153
+ text: string;
154
+ url?: string | undefined;
155
+ callback_data?: string | undefined;
156
+ }[][];
157
+ } | undefined;
158
+ } | undefined;
159
+ }[]>;
160
+ drain(signal?: AbortSignal): Promise<void>;
161
+ }
162
+ export {};
@@ -0,0 +1,170 @@
1
+ import { setTimeout as delay } from "node:timers/promises";
2
+ import { z } from "zod";
3
+ import { jsonObjectSchema } from "@open-qa/qa-engine/protocol";
4
+ const telegramMessageSchema = z.object({
5
+ message_id: z.number().int(),
6
+ date: z.number(),
7
+ edit_date: z.number().optional(),
8
+ chat: z.object({ id: z.number().int(), type: z.string() }),
9
+ from: z.object({
10
+ id: z.number().int(),
11
+ is_bot: z.boolean().optional(),
12
+ username: z.string().optional(),
13
+ first_name: z.string().optional()
14
+ }).optional(),
15
+ text: z.string().optional(),
16
+ caption: z.string().optional(),
17
+ entities: z.array(
18
+ z.object({
19
+ type: z.string(),
20
+ offset: z.number().int().nonnegative(),
21
+ length: z.number().int().nonnegative(),
22
+ url: z.string().optional()
23
+ })
24
+ ).optional(),
25
+ caption_entities: z.array(
26
+ z.object({
27
+ type: z.string(),
28
+ offset: z.number().int().nonnegative(),
29
+ length: z.number().int().nonnegative(),
30
+ url: z.string().optional()
31
+ })
32
+ ).optional(),
33
+ rich_message: z.object({ blocks: z.array(jsonObjectSchema).max(200) }).optional(),
34
+ reply_to_message: z.object({ message_id: z.number().int() }).optional(),
35
+ reply_markup: z.object({
36
+ inline_keyboard: z.array(
37
+ z.array(
38
+ z.object({
39
+ text: z.string(),
40
+ url: z.string().optional(),
41
+ callback_data: z.string().optional()
42
+ })
43
+ )
44
+ )
45
+ }).optional()
46
+ });
47
+ const updateSchema = z.object({
48
+ update_id: z.number().int().nonnegative(),
49
+ message: telegramMessageSchema.optional(),
50
+ edited_message: telegramMessageSchema.optional()
51
+ });
52
+ const envelopeSchema = z.object({
53
+ ok: z.boolean(),
54
+ result: z.unknown().optional(),
55
+ error_code: z.number().optional(),
56
+ description: z.string().optional(),
57
+ parameters: z.object({ retry_after: z.number().int().positive().max(86400).optional() }).optional()
58
+ });
59
+ class TelegramApiError extends Error {
60
+ constructor(reason = "request_failed", code) {
61
+ super(`env: Telegram ${reason}${code === void 0 ? "" : ` (${code})`}`);
62
+ this.reason = reason;
63
+ this.code = code;
64
+ }
65
+ reason;
66
+ code;
67
+ }
68
+ class TelegramApi {
69
+ constructor(token, options = {}) {
70
+ this.token = token;
71
+ this.options = options;
72
+ this.request = options.fetch ?? fetch;
73
+ this.sleep = options.sleep ?? (async (ms, signal) => {
74
+ await delay(ms, void 0, { signal });
75
+ });
76
+ }
77
+ token;
78
+ options;
79
+ offset = 0;
80
+ request;
81
+ sleep;
82
+ async call(method, params, signal) {
83
+ const bounded = AbortSignal.any([...signal ? [signal] : [], AbortSignal.timeout(12e4)]);
84
+ try {
85
+ for (; ; ) {
86
+ bounded.throwIfAborted();
87
+ const response = await this.request(`https://api.telegram.org/bot${this.token}/${method}`, {
88
+ method: "POST",
89
+ redirect: "error",
90
+ headers: { "content-type": "application/json" },
91
+ body: JSON.stringify(params),
92
+ signal: bounded
93
+ });
94
+ const body = envelopeSchema.parse(await response.json());
95
+ if (body.error_code === 429 && body.parameters?.retry_after) {
96
+ this.options.retry?.(method, body.parameters.retry_after);
97
+ await this.sleep(body.parameters.retry_after * 1e3, bounded);
98
+ continue;
99
+ }
100
+ if (!response.ok || !body.ok) {
101
+ const code = body.error_code ?? response.status;
102
+ const reason = code === 401 ? "unauthorized" : code === 409 ? "conflict_webhook_or_poller" : code === 400 && body.description?.toLowerCase().includes("chat not found") ? "chat_not_found" : "request_failed";
103
+ throw new TelegramApiError(reason, code);
104
+ }
105
+ return body.result;
106
+ }
107
+ } catch (error) {
108
+ if (error instanceof TelegramApiError) throw error;
109
+ if (bounded.aborted) throw new TelegramApiError("timeout");
110
+ if (error instanceof z.ZodError || error instanceof SyntaxError)
111
+ throw new TelegramApiError("bad_response");
112
+ throw new TelegramApiError();
113
+ }
114
+ }
115
+ parse(schema, value) {
116
+ const result = schema.safeParse(value);
117
+ if (!result.success) throw new TelegramApiError("bad_response");
118
+ return result.data;
119
+ }
120
+ async me(signal) {
121
+ return this.parse(
122
+ z.object({ id: z.number().int(), username: z.string() }),
123
+ await this.call("getMe", {}, signal)
124
+ );
125
+ }
126
+ async chat(username, signal) {
127
+ return this.parse(
128
+ z.object({ id: z.number().int() }),
129
+ await this.call("getChat", { chat_id: username }, signal)
130
+ );
131
+ }
132
+ async send(chatId, text, replyTo, signal) {
133
+ return this.parse(
134
+ telegramMessageSchema,
135
+ await this.call(
136
+ "sendMessage",
137
+ {
138
+ chat_id: chatId,
139
+ text,
140
+ ...replyTo === void 0 ? {} : { reply_parameters: { message_id: replyTo } }
141
+ },
142
+ signal
143
+ )
144
+ );
145
+ }
146
+ async updates(signal) {
147
+ const updates = this.parse(
148
+ z.array(updateSchema).max(100),
149
+ await this.call(
150
+ "getUpdates",
151
+ { offset: this.offset, timeout: 0, allowed_updates: ["message", "edited_message"] },
152
+ signal
153
+ )
154
+ );
155
+ for (const update of updates) this.offset = Math.max(this.offset, update.update_id + 1);
156
+ return updates;
157
+ }
158
+ async drain(signal) {
159
+ for (let i = 0; i < 100; i++) {
160
+ if ((await this.updates(signal)).length === 0) return;
161
+ signal?.throwIfAborted();
162
+ }
163
+ throw new TelegramApiError();
164
+ }
165
+ }
166
+ export {
167
+ TelegramApi,
168
+ TelegramApiError,
169
+ telegramMessageSchema
170
+ };
@@ -0,0 +1,4 @@
1
+ import type { TelegramMessage } from "./telegram-api.js";
2
+ export declare function messageHtml(m: TelegramMessage): string;
3
+ export declare function messagePlain(m: TelegramMessage): string;
4
+ export declare const esc: (s: string) => string;
@@ -0,0 +1,129 @@
1
+ function messageHtml(m) {
2
+ if (m.rich_message) return blocksHtml(m.rich_message.blocks);
3
+ const text = m.text ?? m.caption ?? "";
4
+ const entities = m.entities ?? m.caption_entities ?? [];
5
+ if (text) return `<p>${entitiesHtml(text, entities)}</p>`;
6
+ const kind = "unsupported message";
7
+ return unrendered(kind);
8
+ }
9
+ function messagePlain(m) {
10
+ if (m.rich_message) return blocksPlain(m.rich_message.blocks);
11
+ return m.text ?? m.caption ?? "";
12
+ }
13
+ const href = (url) => esc(/^https?:\/\//i.test(url) ? url : "#");
14
+ const esc = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
15
+ const unrendered = (what) => `<aside>unrendered: ${esc(what)}</aside>`;
16
+ const WRAP = {
17
+ bold: ["<b>", "</b>"],
18
+ italic: ["<i>", "</i>"],
19
+ underline: ["<u>", "</u>"],
20
+ strikethrough: ["<s>", "</s>"],
21
+ spoiler: ['<span class="spoiler">', "</span>"],
22
+ code: ["<code>", "</code>"],
23
+ pre: ["<pre>", "</pre>"],
24
+ blockquote: ["<blockquote>", "</blockquote>"],
25
+ expandable_blockquote: ["<blockquote>", "</blockquote>"]
26
+ };
27
+ function entitiesHtml(text, entities) {
28
+ const opens = /* @__PURE__ */ new Map();
29
+ const closes = /* @__PURE__ */ new Map();
30
+ const sorted = [...entities].sort((a, b) => a.offset - b.offset || b.length - a.length);
31
+ for (const e of sorted) {
32
+ if (!e.length || e.offset + e.length > text.length) continue;
33
+ const slice = text.slice(e.offset, e.offset + e.length);
34
+ let pair = WRAP[e.type];
35
+ if (e.type === "text_link") pair = [`<a href="${href(e.url ?? "")}">`, "</a>"];
36
+ if (e.type === "url") pair = [`<a href="${href(slice)}">`, "</a>"];
37
+ if (e.type === "mention" || e.type === "bot_command" || e.type === "hashtag")
38
+ pair = ['<span class="link">', "</span>"];
39
+ if (!pair) pair = ["<aside>", "</aside>"];
40
+ (opens.get(e.offset) ?? opens.set(e.offset, []).get(e.offset)).push(pair[0]);
41
+ (closes.get(e.offset + e.length) ?? closes.set(e.offset + e.length, []).get(e.offset + e.length)).unshift(pair[1]);
42
+ }
43
+ let out = "";
44
+ for (let i = 0; i <= text.length; i++) {
45
+ out += (closes.get(i) ?? []).join("") + (opens.get(i) ?? []).join("");
46
+ if (i < text.length) out += text[i] === "\n" ? "<br>" : esc(text[i]);
47
+ }
48
+ return out;
49
+ }
50
+ function object(value) {
51
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
52
+ }
53
+ function array(value) {
54
+ return Array.isArray(value) ? value.slice(0, 200) : [];
55
+ }
56
+ function inlineHtml(value, depth = 0) {
57
+ if (depth > 20) return unrendered("nested content");
58
+ if (typeof value === "string") return esc(value).replace(/\n/g, "<br>");
59
+ if (Array.isArray(value))
60
+ return array(value).map((item) => inlineHtml(item, depth + 1)).join("");
61
+ if (value == null) return "";
62
+ const node = object(value), type = String(node.type ?? "unknown"), inner = inlineHtml(node.text, depth + 1);
63
+ if (type === "url" || type === "text_link")
64
+ return `<a href="${href(String(node.url ?? ""))}">${inner}</a>`;
65
+ const pair = WRAP[type];
66
+ return pair ? pair[0] + inner + pair[1] : unrendered(`inline ${type}`) + inner;
67
+ }
68
+ function inlinePlain(value, depth = 0) {
69
+ if (depth > 20) return "[unrendered]";
70
+ if (typeof value === "string") return value;
71
+ if (Array.isArray(value))
72
+ return array(value).map((item) => inlinePlain(item, depth + 1)).join("");
73
+ return value == null ? "" : inlinePlain(object(value).text, depth + 1);
74
+ }
75
+ function blocksHtml(value, depth = 0) {
76
+ if (depth > 20) return unrendered("nested blocks");
77
+ return array(value).map((value2) => {
78
+ const b = object(value2), text = inlineHtml(b.text), type = String(b.type ?? "unknown");
79
+ switch (type) {
80
+ case "paragraph":
81
+ return `<p>${text}</p>`;
82
+ case "heading":
83
+ return `<h4>${text}</h4>`;
84
+ case "pre":
85
+ return `<pre>${esc(String(b.text ?? ""))}</pre>`;
86
+ case "blockquote":
87
+ return `<blockquote>${blocksHtml(b.blocks, depth + 1)}</blockquote>`;
88
+ case "divider":
89
+ return "<hr>";
90
+ case "list":
91
+ return `<ul>${array(b.items).map((value3) => {
92
+ const item = object(value3);
93
+ return `<li>${esc(String(item.label ?? ""))}${blocksHtml(item.blocks, depth + 1)}</li>`;
94
+ }).join("")}</ul>`;
95
+ case "table":
96
+ return `<table>${array(b.cells).map(
97
+ (row) => `<tr>${array(row).map((value3) => {
98
+ const cell = object(value3), tag = cell.is_header ? "th" : "td";
99
+ return `<${tag}>${inlineHtml(cell.text)}</${tag}>`;
100
+ }).join("")}</tr>`
101
+ ).join("")}</table>`;
102
+ default:
103
+ return unrendered(`block ${type}`);
104
+ }
105
+ }).join("");
106
+ }
107
+ function blocksPlain(value, depth = 0) {
108
+ if (depth > 20) return "[unrendered]";
109
+ return array(value).map((value2) => {
110
+ const b = object(value2);
111
+ if (b.type === "list")
112
+ return array(b.items).map((value3) => {
113
+ const item = object(value3);
114
+ return `${String(item.label ?? "")} ${blocksPlain(item.blocks, depth + 1)}`;
115
+ }).join("\n");
116
+ if (b.type === "blockquote") return blocksPlain(b.blocks, depth + 1);
117
+ if (b.type === "table")
118
+ return array(b.cells).map(
119
+ (row) => array(row).map((value3) => inlinePlain(object(value3).text)).join(" | ")
120
+ ).join("\n");
121
+ if (b.type === "divider") return "---";
122
+ return inlinePlain(b.text);
123
+ }).join("\n");
124
+ }
125
+ export {
126
+ esc,
127
+ messageHtml,
128
+ messagePlain
129
+ };
@@ -0,0 +1,39 @@
1
+ import type { OpenViewRequest, OpenViewResponse } from "@open-qa/qa-engine/protocol";
2
+ import type { DriverContext, StageDrivers } from "./drivers.js";
3
+ import type { SurfaceAdapter, ToolContext, ViewDriver } from "./surface-adapter.js";
4
+ import { type TelegramApiOptions } from "./telegram-api.js";
5
+ export declare class TelegramSurface {
6
+ private readonly pages;
7
+ private readonly render;
8
+ private readonly openPage;
9
+ private readonly options;
10
+ private readonly conversations;
11
+ private readonly tokens;
12
+ private readonly opening;
13
+ private readonly sends;
14
+ private readonly sendQueues;
15
+ readonly surface: SurfaceAdapter;
16
+ readonly views: ViewDriver;
17
+ constructor(pages: ViewDriver, render: StageDrivers["renderView"], openPage: StageDrivers["openView"], options: TelegramApiOptions & {
18
+ now?: () => number;
19
+ closeView: StageDrivers["closeView"];
20
+ navigate: (view: string, url: string, context: ToolContext) => Promise<void>;
21
+ });
22
+ owns(view: string): boolean;
23
+ forget(view: string): void;
24
+ open(request: Extract<OpenViewRequest, {
25
+ type: "rendered";
26
+ }>, context: DriverContext): Promise<OpenViewResponse>;
27
+ private sleep;
28
+ private now;
29
+ private conversation;
30
+ private safe;
31
+ private paint;
32
+ private driver;
33
+ private refresh;
34
+ private remember;
35
+ private matching;
36
+ private summary;
37
+ private tools;
38
+ readonly expect: StageDrivers["expect"];
39
+ }