@kana-ai/edgar-ext-uptimerobot 0.0.0-stage → 0.1.1

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 ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Kana.ai
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/README.md CHANGED
@@ -1,3 +1,85 @@
1
- # Temporary Holding Version
1
+ # @kana-ai/edgar-ext-uptimerobot
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The UptimeRobot extension of EDGAR. UptimeRobot checks a service from the outside, so it sees
4
+ what a customer sees, including the minutes when the service is too busy to log anything about
5
+ itself. The extension's service files UptimeRobot's incidents as cards, and its tools read
6
+ incidents and response times. It reads only; a read-only key is enough.
7
+
8
+ ## Feed
9
+
10
+ With `[extensions.uptimerobot.feed]` set, the service reads the incidents that started since its
11
+ last sweep, every `every_seconds`, and files one card per incident in `card_column`.
12
+
13
+ - **Degraded performance** is always filed. Nothing errors and nothing is logged while a monitor
14
+ answers slowly, so the card carries the response-time series from 30 minutes before the
15
+ incident to 15 minutes after it, and the monitor's own threshold. A `*` marks each bucket at or
16
+ above the threshold. The series is in five-minute averaged buckets, so the check that fired the
17
+ alert is averaged away inside its bucket, and the card says so. UptimeRobot does not publish
18
+ the measured value.
19
+ - **Down** is filed once the outage has lasted `down_after_seconds` (180 by default). A shorter
20
+ one is usually in the service's own logs with more detail. The cursor never moves past an
21
+ outage that is still going and too young to file, so an outage that goes on is filed on a later
22
+ sweep.
23
+ - **One card per incident.** The fingerprint is the incident's id, so two incidents on one monitor
24
+ are two cards, each judged on its own evidence, and a second reading of one incident is the same
25
+ card. A down incident is `critical` and a degraded one `medium`.
26
+ - **Where to look next.** The card's `window` is the incident from 5 minutes before its start to 5
27
+ minutes after its end (`<since>/<until>`), and the description repeats it. The project's skills
28
+ say which logs to read for that window.
29
+ - **Service.** `services` maps the host a monitor checks to a project service, and any other host
30
+ goes to `default_service`. With neither, the card names no service.
31
+ - **Pace.** A sweep opens at most `max_per_run` cards and keeps the rest for the next sweep, up to
32
+ 200 waiting.
33
+ - **Failures.** A refused key ends the service, which opens its breaker, since a person must act.
34
+ Any other failure is logged and the next sweep reads again from the same cursor. A card that the
35
+ tracker cannot open for a while (a 503, a rate limit) stays first in line for the next sweep; one
36
+ that the tracker refuses is logged and dropped. A series that
37
+ cannot be read is written as such on the card and does not stop it.
38
+ - **Restart.** The cursor lives in memory, so a restart reads back one day, and EDGAR answers each
39
+ repeated fingerprint with the card it has.
40
+
41
+ ## Tools
42
+
43
+ | Tool | Input | Output | Notes |
44
+ | ----------------------------- | ------------------------------------------ | -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
45
+ | `uptimerobot__incidents` | optional `since` (24 hours ago), `monitor` | `incidents`, `complete` | Each incident has `id`, `monitor_id`, `monitor`, `url`, `kind` (`down` or `degraded`), `reason`, `started_at`, `resolved_at` and `duration_seconds`. Reads at most 5 pages; `complete` is false when more were left. |
46
+ | `uptimerobot__response_times` | `monitor`, `since`; optional `until` (now) | `threshold_ms`, `min_ms`, `avg_ms`, `max_ms`, `points`, `note` | Five-minute averaged buckets with the monitor's threshold, flat or the lowest per region. |
47
+
48
+ Both tools read only, and never ask a person.
49
+
50
+ ## Configuration
51
+
52
+ ```toml
53
+ [extensions]
54
+ enabled = ["uptimerobot"]
55
+
56
+ [extensions.uptimerobot.feed]
57
+ card_column = "intake"
58
+ services = { "example.com" = "web" }
59
+ default_service = "web"
60
+ environment = "prod"
61
+ down_after_seconds = 180
62
+ every_seconds = 300
63
+ max_per_run = 5
64
+
65
+ [secrets]
66
+ UPTIMEROBOT_API_KEY = { env = "UPTIMEROBOT_API_KEY" }
67
+ ```
68
+
69
+ Every key of the feed table has a default, except `default_service` and `environment`, which a
70
+ card leaves out when they are absent. Without the `feed` table the service only waits, and the
71
+ tools still work.
72
+
73
+ `UPTIMEROBOT_API_KEY` is a read-only v3 key. It is sent only to `api.uptimerobot.com`. Run
74
+ `edgar extensions approve uptimerobot` after each build: the approval covers
75
+ `network:api.uptimerobot.com`.
76
+
77
+ ## Build and test
78
+
79
+ ```sh
80
+ pnpm --filter @kana-ai/edgar-ext-uptimerobot run build
81
+ pnpm --filter @kana-ai/edgar-ext-uptimerobot run test
82
+ ```
83
+
84
+ The tests answer every request from a recorded reply in the shape of UptimeRobot's published v3
85
+ schema, with no network.
@@ -0,0 +1,17 @@
1
+ import { type Ctx, type Failure, type Result } from "@kana-ai/edgar-sdk";
2
+ import type { z } from "zod";
3
+ /** The secret that holds a read-only v3 API key. */
4
+ export declare const KEY = "UPTIMEROBOT_API_KEY";
5
+ /** The API host; the key is sent nowhere else. */
6
+ export declare const HOST: "api.uptimerobot.com";
7
+ /** The secret and the capability of each tool and of the service. */
8
+ export declare const apiAccess: {
9
+ readonly secrets: readonly ["UPTIMEROBOT_API_KEY"];
10
+ readonly capabilities: readonly ["network:api.uptimerobot.com"];
11
+ };
12
+ /** A context that holds the key. */
13
+ export type UptimeCtx = Ctx<typeof KEY>;
14
+ /** The answer of one call: the parsed body, or the failure it maps to. */
15
+ export type Reply<T> = Result<T, Failure>;
16
+ /** Reads one v3 path with the parameters that have a value, and parses the answer with `schema`. */
17
+ export declare function uptimerobot<T>(ctx: UptimeCtx, path: string, params: Readonly<Record<string, string | undefined>>, schema: z.ZodType<T>, now?: number): Promise<Reply<T>>;
@@ -0,0 +1,32 @@
1
+ import { attemptAsync, err, failure, fetchFailure, ok, unwrapOr, } from "@kana-ai/edgar-sdk";
2
+ import { limits, mapFailure } from "#api/failures";
3
+ /** The secret that holds a read-only v3 API key. */
4
+ export const KEY = "UPTIMEROBOT_API_KEY";
5
+ /** The API host; the key is sent nowhere else. */
6
+ export const HOST = limits.source;
7
+ /** The secret and the capability of each tool and of the service. */
8
+ export const apiAccess = { secrets: [KEY], capabilities: [`network:${HOST}`] };
9
+ /** Reads one v3 path with the parameters that have a value, and parses the answer with `schema`. */
10
+ export async function uptimerobot(ctx, path, params, schema, now = Date.now()) {
11
+ const url = new URL(`https://${HOST}/v3${path}`);
12
+ for (const [k, v] of Object.entries(params)) {
13
+ if (v !== undefined && v !== "")
14
+ url.searchParams.set(k, v);
15
+ }
16
+ const context = `uptimerobot GET ${path}`;
17
+ const sent = await attemptAsync(async () => await fetch(url, {
18
+ signal: ctx.signal,
19
+ headers: { authorization: `Bearer ${ctx.secrets.get(KEY)}`, accept: "application/json" },
20
+ }), (caught) => fetchFailure(caught, ctx.signal, context));
21
+ if (!sent.ok)
22
+ return sent;
23
+ const response = sent.value;
24
+ if (!response.ok)
25
+ return err(mapFailure(response.status, response.headers, context, now));
26
+ const json = unwrapOr(await attemptAsync(async () => await response.json(), () => null), null);
27
+ const read = schema.safeParse(json);
28
+ if (read.success)
29
+ return ok(read.data);
30
+ const fields = read.error.issues.map((i) => i.path.join(".") || "(root)").join(", ");
31
+ return err(failure("tool_error", `${context}: unexpected answer`, { cause: `fields: ${fields}` }));
32
+ }
@@ -0,0 +1,8 @@
1
+ import { type Failure } from "@kana-ai/edgar-sdk";
2
+ /** UptimeRobot reports a rate limit as 429 with `Retry-After`. */
3
+ export declare const limits: {
4
+ readonly scheme: "retry_after";
5
+ readonly source: "api.uptimerobot.com";
6
+ };
7
+ /** Maps an error answer of the API to a failure: a refused key is permanent, 5xx is temporary, and `cause` holds the status. */
8
+ export declare function mapFailure(status: number, headers: Headers, context: string, now?: number): Failure;
@@ -0,0 +1,19 @@
1
+ import { vendorFailure } from "@kana-ai/edgar-sdk";
2
+ /** UptimeRobot reports a rate limit as 429 with `Retry-After`. */
3
+ export const limits = {
4
+ scheme: "retry_after",
5
+ source: "api.uptimerobot.com",
6
+ };
7
+ const statusKinds = new Map([
8
+ [400, "invalid"],
9
+ [401, "unauthenticated"],
10
+ [403, "forbidden"],
11
+ [404, "not_found"],
12
+ [422, "invalid"],
13
+ [429, "rate_limited"],
14
+ ]);
15
+ /** Maps an error answer of the API to a failure: a refused key is permanent, 5xx is temporary, and `cause` holds the status. */
16
+ export function mapFailure(status, headers, context, now = Date.now()) {
17
+ const kind = status >= 500 ? "provider_unavailable" : (statusKinds.get(status) ?? "tool_error");
18
+ return vendorFailure(kind, context, `status:${String(status)}`, headers, limits, now);
19
+ }
@@ -0,0 +1,23 @@
1
+ import type { z } from "zod";
2
+ import { type Reply, type UptimeCtx } from "#api/client";
3
+ import type { incidentFacts } from "#schemas/tools";
4
+ import { type Incident, type Monitor, type ResponseTimes } from "#schemas/uptimerobot";
5
+ /** The incidents that started after `since`, oldest page first; `complete` is false when pages were left. */
6
+ export declare function incidentsSince(ctx: UptimeCtx, since: string, now?: number): Promise<Reply<{
7
+ readonly incidents: Incident[];
8
+ readonly complete: boolean;
9
+ }>>;
10
+ /** Every monitor by its id, from the first page of 50. */
11
+ export declare function monitorsById(ctx: UptimeCtx, now?: number): Promise<Reply<ReadonlyMap<string, Monitor>>>;
12
+ /** A monitor's response-time series between two times. */
13
+ export declare function seriesBetween(ctx: UptimeCtx, monitor: string, from: string, to: string, now?: number): Promise<Reply<ResponseTimes>>;
14
+ /** The line the alert fires on: the flat threshold, which live accounts fill, else the lowest per-region one. */
15
+ export declare function thresholdOf(m: Monitor | undefined): number | undefined;
16
+ /** Whether an incident is about response time, read from UptimeRobot's own words; anything else counts as down, which files late rather than never. */
17
+ export declare const isDegraded: (inc: Incident) => boolean;
18
+ /** An ISO time of `value`, or `undefined` when it names none. */
19
+ export declare const isoOf: (value: unknown) => string | undefined;
20
+ /** Where the incident's monitor points. */
21
+ export declare function urlOf(inc: Incident, known: ReadonlyMap<string, Monitor>): string | undefined;
22
+ /** An incident as the tools answer it; `undefined` when it names no start. */
23
+ export declare function factsOf(inc: Incident, known: ReadonlyMap<string, Monitor>): z.infer<typeof incidentFacts> | undefined;
@@ -0,0 +1,77 @@
1
+ import { ok } from "@kana-ai/edgar-sdk";
2
+ import { uptimerobot } from "#api/client";
3
+ import { incidents, monitors, regionThreshold, responseTimes, } from "#schemas/uptimerobot";
4
+ /** Pages of incidents one read follows. */
5
+ const MAX_PAGES = 5;
6
+ /** The incidents that started after `since`, oldest page first; `complete` is false when pages were left. */
7
+ export async function incidentsSince(ctx, since, now = Date.now()) {
8
+ const all = [];
9
+ let page;
10
+ for (let n = 0; n < MAX_PAGES; n += 1) {
11
+ const params = { started_after: since, cursor: page };
12
+ const read = await uptimerobot(ctx, "/incidents", params, incidents, now);
13
+ if (!read.ok)
14
+ return read;
15
+ all.push(...read.value.data);
16
+ const link = read.value.nextLink ?? "";
17
+ page = URL.canParse(link) ? (new URL(link).searchParams.get("cursor") ?? undefined) : undefined;
18
+ if (page === undefined || read.value.data.length === 0)
19
+ return ok({ incidents: all, complete: true });
20
+ }
21
+ return ok({ incidents: all, complete: false });
22
+ }
23
+ /** Every monitor by its id, from the first page of 50. */
24
+ export async function monitorsById(ctx, now = Date.now()) {
25
+ const listed = await uptimerobot(ctx, "/monitors", { limit: "50" }, monitors, now);
26
+ if (!listed.ok)
27
+ return listed;
28
+ return ok(new Map(listed.value.data.map((m) => [String(m.id), m])));
29
+ }
30
+ /** A monitor's response-time series between two times. */
31
+ export async function seriesBetween(ctx, monitor, from, to, now = Date.now()) {
32
+ const path = `/monitors/${monitor}/stats/response-time`;
33
+ const params = { from, to, includeTimeSeries: "true", region: "all" };
34
+ return await uptimerobot(ctx, path, params, responseTimes, now);
35
+ }
36
+ /** The line the alert fires on: the flat threshold, which live accounts fill, else the lowest per-region one. */
37
+ export function thresholdOf(m) {
38
+ const flat = m?.responseTimeThreshold ?? 0;
39
+ if (flat > 0)
40
+ return flat;
41
+ const values = Object.values(m?.regionData ?? {}).flatMap((v) => {
42
+ const r = regionThreshold.safeParse(v);
43
+ const n = r.success ? (r.data.THRESHOLD ?? r.data.threshold ?? 0) : 0;
44
+ return n > 0 ? [n] : [];
45
+ });
46
+ return values.length > 0 ? Math.min(...values) : undefined;
47
+ }
48
+ /** Whether an incident is about response time, read from UptimeRobot's own words; anything else counts as down, which files late rather than never. */
49
+ export const isDegraded = (inc) => /degrad|response ?time|slow|latency/i.test([inc.reason, inc.type, inc.status].map(String).join(" "));
50
+ /** An ISO time of `value`, or `undefined` when it names none. */
51
+ export const isoOf = (value) => {
52
+ const at = typeof value === "number" ? value : Date.parse(String(value ?? ""));
53
+ return Number.isFinite(at) ? new Date(at).toISOString() : undefined;
54
+ };
55
+ /** Where the incident's monitor points. */
56
+ export function urlOf(inc, known) {
57
+ const url = inc.rootCause?.url ?? known.get(String(inc.monitor?.id))?.url ?? "";
58
+ return URL.canParse(url) ? url : undefined;
59
+ }
60
+ /** An incident as the tools answer it; `undefined` when it names no start. */
61
+ export function factsOf(inc, known) {
62
+ const started = isoOf(inc.startedAt);
63
+ if (started === undefined)
64
+ return undefined;
65
+ const monitorId = inc.monitor?.id;
66
+ return {
67
+ id: String(inc.id ?? ""),
68
+ monitor_id: monitorId === null || monitorId === undefined ? null : String(monitorId),
69
+ monitor: inc.monitor?.friendlyName ?? null,
70
+ url: urlOf(inc, known) ?? null,
71
+ kind: isDegraded(inc) ? "degraded" : "down",
72
+ reason: inc.reason ?? inc.type ?? null,
73
+ started_at: started,
74
+ resolved_at: isoOf(inc.resolvedAt) ?? null,
75
+ duration_seconds: inc.duration ?? null,
76
+ };
77
+ }
@@ -0,0 +1,23 @@
1
+ import type { CardSpec } from "@kana-ai/edgar-contracts/rpc";
2
+ import type { ResponseTimes } from "#schemas/uptimerobot";
3
+ import type { z } from "zod";
4
+ import type { incidentFacts } from "#schemas/tools";
5
+ type Facts = z.infer<typeof incidentFacts>;
6
+ /** The 16 hex characters of a card's fingerprint. */
7
+ export declare const fingerprintOf: (identity: string) => string;
8
+ /** The window a card asks a stage to read other evidence in: 5 minutes before the start to 5 minutes after the end, or 10 minutes after a start still open. */
9
+ export declare function windowOf(f: Facts): {
10
+ readonly since: string;
11
+ readonly until: string;
12
+ };
13
+ /** The series around an incident, written for a person: the buckets are five-minute averages, so the check that fired is averaged away, and the card says so. */
14
+ export declare function seriesText(series: ResponseTimes, from: string, to: string, threshold: number | undefined): string;
15
+ /** Where a card goes and what it names besides the incident. */
16
+ export interface Home {
17
+ readonly column: string;
18
+ readonly service: string | undefined;
19
+ readonly environment: string | undefined;
20
+ }
21
+ /** The card of one incident, with its own fingerprint, so each is judged on its evidence and a second reading is the same card. `series` is set for a degraded spell. */
22
+ export declare function incidentCard(f: Facts, home: Home, threshold: number | undefined, series: string | undefined): CardSpec;
23
+ export {};
@@ -0,0 +1,71 @@
1
+ import { createHash } from "node:crypto";
2
+ const MINUTE = 60_000;
3
+ /** The 16 hex characters of a card's fingerprint. */
4
+ export const fingerprintOf = (identity) => createHash("sha256").update(identity).digest("hex").slice(0, 16);
5
+ const clip = (text, most) => text.length > most ? `${text.slice(0, most - 1)}…` : text;
6
+ /** The window a card asks a stage to read other evidence in: 5 minutes before the start to 5 minutes after the end, or 10 minutes after a start still open. */
7
+ export function windowOf(f) {
8
+ const started = Date.parse(f.started_at);
9
+ const ended = f.resolved_at === null ? started + 10 * MINUTE : Date.parse(f.resolved_at);
10
+ return {
11
+ since: new Date(started - 5 * MINUTE).toISOString(),
12
+ until: new Date(ended + 5 * MINUTE).toISOString(),
13
+ };
14
+ }
15
+ /** The series around an incident, written for a person: the buckets are five-minute averages, so the check that fired is averaged away, and the card says so. */
16
+ export function seriesText(series, from, to, threshold) {
17
+ const sum = series.summary;
18
+ const points = series.time_series ?? [];
19
+ const shown = points.length > 90 ? [...points.slice(0, 45), undefined, ...points.slice(-45)] : points;
20
+ const ms = (n) => n === null || n === undefined ? "?" : String(Math.round(n));
21
+ return [
22
+ `Response time from UptimeRobot, ${from} to ${to}${threshold === undefined ? "" : ` (the monitor fires above ${String(threshold)}ms; * marks a bucket at or above it)`}`,
23
+ "These are five-minute buckets, averaged. The check that triggered the alert is inside one",
24
+ "of them and is averaged away; UptimeRobot does not publish the measured value.",
25
+ `min ${ms(sum?.min)}ms · avg ${ms(sum?.avg)}ms · max ${ms(sum?.max)}ms over ${String(series.data_points ?? points.length)} buckets`,
26
+ "",
27
+ ...shown.map((p) => p === undefined
28
+ ? " … middle of the window left out …"
29
+ : `${p.timestamp.slice(11, 16)} ${String(Math.round(p.value))}ms${threshold !== undefined && p.value >= threshold ? " *" : ""}`),
30
+ ].join("\n");
31
+ }
32
+ /** The card of one incident, with its own fingerprint, so each is judged on its evidence and a second reading is the same card. `series` is set for a degraded spell. */
33
+ export function incidentCard(f, home, threshold, series) {
34
+ const name = f.monitor ?? (f.url === null ? `monitor ${String(f.monitor_id)}` : new URL(f.url).host);
35
+ const when = `${f.started_at.slice(0, 16).replace("T", " ")} UTC`;
36
+ const titleKey = `${f.kind === "degraded" ? "degraded performance on " : "down: "}${name}, ${when}`;
37
+ const identity = f.id === "" ? `monitor ${String(f.monitor_id ?? name)} at ${f.started_at}` : `incident ${f.id}`;
38
+ const window = windowOf(f);
39
+ const record = [
40
+ `Monitor: ${name}${f.url === null ? "" : ` (${f.url})`}`,
41
+ `Reason: ${f.reason ?? "unknown"}`,
42
+ `Started: ${f.started_at}`,
43
+ f.resolved_at === null ? "Still open when this was read" : `Resolved: ${f.resolved_at}`,
44
+ f.duration_seconds === null ? "" : `Lasted: ${String(Math.round(f.duration_seconds))}s`,
45
+ threshold === undefined ? "" : `Response-time threshold: ${String(threshold)}ms`,
46
+ `Incident id: ${f.id}`,
47
+ `Read the service's own evidence from ${window.since} to ${window.until}.`,
48
+ ].filter((line) => line !== "");
49
+ return {
50
+ title: `uptime: ${clip(titleKey, 110)}`,
51
+ description: [
52
+ record.join("\n"),
53
+ series === undefined ? "" : `\`\`\`\n${clip(series, 7000)}\n\`\`\``,
54
+ ]
55
+ .filter((part) => part !== "")
56
+ .join("\n\n"),
57
+ column: home.column,
58
+ labels: ["uptime"],
59
+ block: {
60
+ kind: "defect",
61
+ ...(home.service === undefined ? {} : { service: home.service }),
62
+ ...(home.environment === undefined ? {} : { environment: home.environment }),
63
+ fingerprint: fingerprintOf(`uptimerobot ${identity}`),
64
+ first_seen: f.started_at,
65
+ last_seen: f.resolved_at ?? f.started_at,
66
+ occurrences: 1,
67
+ severity: f.kind === "degraded" ? "medium" : "critical",
68
+ window: `${window.since}/${window.until}`,
69
+ },
70
+ };
71
+ }
@@ -0,0 +1,23 @@
1
+ import type { CardSpec } from "@kana-ai/edgar-contracts/rpc";
2
+ import { type Outcome } from "@kana-ai/edgar-sdk";
3
+ import type { Reply, UptimeCtx } from "#api/client";
4
+ import { type Feed } from "#schemas/config";
5
+ /** What one sweep filed, and the start time the next one reads after. */
6
+ export interface Swept {
7
+ readonly cards: readonly CardSpec[];
8
+ readonly cursor: string;
9
+ }
10
+ /**
11
+ * One sweep of the incidents that started after `from`, or in the last day. A degraded spell is filed with its response-time series;
12
+ * an outage only once it has lasted `down_after_seconds`, since a short one is usually in the service's own logs with more detail.
13
+ * The cursor is the newest start less a second, and never passes an outage still going that was too young to file.
14
+ */
15
+ export declare function sweep(ctx: UptimeCtx, feed: Feed, from: string | undefined, now?: number): Promise<Reply<Swept>>;
16
+ /** Opens at most `most` of the waiting cards, the oldest first. A card that the tracker could not open for a while goes back to the head; one that it refused is dropped with a log line. */
17
+ export declare function file(ctx: UptimeCtx, waiting: CardSpec[], most: number): Promise<void>;
18
+ /**
19
+ * The service: with `[extensions.uptimerobot.feed]` set, a sweep every `every_seconds` that opens at most `max_per_run` cards and keeps the rest, up to 200, for the next sweep; without it, it only waits.
20
+ * A refused key ends it with its permanent failure, which opens its breaker; any other failure waits for the next sweep from the same cursor, and a card that the tracker could not open for a while waits for the next sweep too.
21
+ * shortcut: the cursor and the waiting cards live in memory, so a restart reads back one day and EDGAR answers each repeated fingerprint with the card it has; upgrade when a service can keep state.
22
+ */
23
+ export declare function watch(ctx: UptimeCtx): Promise<Outcome>;