@kana-ai/edgar-ext-email 0.1.2 → 0.1.4

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/README.md CHANGED
@@ -8,22 +8,22 @@ The email extension of EDGAR, over SMTP. It sends a plain-text mail when EDGAR s
8
8
 
9
9
  | Part | What it does |
10
10
  | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
11
- | The service | Sends `started` once it runs. Every `every_seconds` it reads `GET /api/status` on `127.0.0.1:<api_port>` and sends `unhealthy` for each new problem, `paused` when a hold begins and when it ends. At the first read of a new UTC day it sends `daily`. It sends `stopped` when EDGAR stops. A mail that fails for a while (a server that is down, a rate limit) is sent again at the next read; one that the server refuses for good is logged and not sent again. |
11
+ | The service | Sends `started` once it runs, after its first read of `GET /api/status`: "EDGAR has started after a crash" when the worker before did not stop cleanly. Every `every_seconds` it reads `GET /api/status` on `127.0.0.1:<api_port>` and sends `unhealthy` for each new problem, `paused` when a hold begins and when it ends. At the first read of a new UTC day it sends `daily`, which also reads `GET /api/usage`. It sends `stopped` when EDGAR stops. A mail that fails for a while (a server that is down, a rate limit) is sent again at the next read; one that the server refuses for good is logged and not sent again. |
12
12
  | The tool `send` | Sends a mail with `subject` and `text`, to `to` of the call or of the table. Answers the Message-ID as `id`, and `to`. Side effect with no undo: a mail cannot be taken back. |
13
13
  | The hook `end_note` | On each `run_outcome`, when `on` names `end`: the end note that `endNote` of `@kana-ai/edgar-sdk` writes, the same lines as the Slack note. No mail for a run with no card that ends done, and none for a failed run of a schedule whose run just before it failed with the same failure kind. The first run of that schedule that works again sends "EDGAR works again". The subject says what happened and names the card, such as "EDGAR opened a pull request: ENG-12 Search fails", "EDGAR needs your decision: …", "EDGAR could not finish: …", "A person stopped the run: …" or "EDGAR finished: …". A run with no card has "(run 7)" in place of the card. A subject holds at most 120 characters of the card's id and title. For an event that `endNote` cannot read, the mail says only that the run is over. The body names the assignee, the card with its link, each pull request, the stage that failed, and the run with its time, tokens and cost. |
14
14
  | The hook `budget` | On an `attempt_outcome` of kind `token_budget`: "EDGAR: a stage ran out of tokens (run 7)", at most once an hour. |
15
15
 
16
16
  What each topic means:
17
17
 
18
- | Topic | When |
19
- | ----------- | ---------------------------------------------------------------------------------------------------------------------------- |
20
- | `unhealthy` | A problem that the last read did not have: the database is stale, no worker answers, or a breaker is open or half open. |
21
- | `paused` | The engine state turns `hold` ("EDGAR has paused", with the reason and who), or back from `hold` ("EDGAR is working again"). |
22
- | `started` | The service starts, which is each `edgar start`, and each restart of the service after it stopped by itself. |
23
- | `stopped` | The service's signal aborts, which is each `edgar stop`. That mail has 10 seconds. |
24
- | `daily` | The runs that ended on the UTC day before: how many are done, failed and cancelled, and how many things wait for a person. |
25
- | `budget` | A stage spent its `limits.max_tokens`. |
26
- | `end` | A run ended. Off by default, since it is one mail for each run. |
18
+ | Topic | When |
19
+ | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
20
+ | `unhealthy` | A problem that the last read did not have: the database is stale, no worker answers, a breaker is open or half open, or a new open alert of the engine (`alerts` of the status: the alerts of the last 24 hours), named by its first line. An alert mails once while it stays open. |
21
+ | `paused` | The engine state turns `hold` ("EDGAR has paused", with the reason and who), or back from `hold` ("EDGAR is working again"). |
22
+ | `started` | The service starts, which is each `edgar start`, and each restart of the service after it stopped by itself. The mail says when the last stop was not clean (`last_start.clean` of the status is false), and when the service could not read the status. |
23
+ | `stopped` | The service's signal aborts, which is each `edgar stop`. That mail has 10 seconds. |
24
+ | `daily` | The runs that ended on the UTC day before: how many are done, failed and cancelled, and how many things wait for a person. What the model calls of that day used, from `GET /api/usage`, by provider and by the role that ran the stage: the cost, or the tokens alone with "no cost" for a provider that reports none and has no price set. And how the last backup ended, from `last_backup` of the status. |
25
+ | `budget` | A stage spent its `limits.max_tokens`. |
26
+ | `end` | A run ended. Off by default, since it is one mail for each run. |
27
27
 
28
28
  ## Configuration
29
29
 
@@ -52,7 +52,7 @@ every_seconds = 60 # the default, 10 to 3600: how often the service reads the en
52
52
 
53
53
  ## The secret
54
54
 
55
- `EMAIL_SMTP_URL` names the server, the user and the password: `smtps://<user>:<password>@<host>:465` for TLS from the first byte, or `smtp://<user>:<password>@<host>:587` for a server with STARTTLS. Write the user and the password URL-encoded, such as `p%40ss` for `p@ss`. SMTP goes over `node:net` and `node:tls`, which the runtime holds to the call's `network:<host>` capabilities, and the manifest cannot name the SMTP host of each project. Name it in `[extensions.email] hosts`, with no port: EDGAR adds it to every call and to the hosts of `EMAIL_SMTP_URL`, and `edgar extensions approve email` prints it and binds it to the approval. With no entry, the extension reaches only an SMTP server on `127.0.0.1`. The manifest lists `127.0.0.1` in the secret's hosts, because the service reads the engine's status there and the engine gives a call that holds a secret only the hosts of that secret. The secret is not sent to that host. EDGAR gives the API token, as `EDGAR_API_TOKEN`, only to an extension whose manifest lists `network:127.0.0.1`, and the service sends it on each read of the status.
55
+ `EMAIL_SMTP_URL` names the server, the user and the password: `smtps://<user>:<password>@<host>:465` for TLS from the first byte, or `smtp://<user>:<password>@<host>:587` for a server with STARTTLS. Write the user and the password URL-encoded, such as `p%40ss` for `p@ss`. SMTP goes over `node:net` and `node:tls`, which the runtime holds to the call's `network:<host>` capabilities, and the manifest cannot name the SMTP host of each project. Name it in `[extensions.email] hosts`, with no port: EDGAR adds it to every call and to the hosts of `EMAIL_SMTP_URL`, and `edgar extensions approve email` prints it and binds it to the approval. With no entry, the extension reaches only an SMTP server on `127.0.0.1`. The manifest lists `127.0.0.1` in the secret's hosts, because the service reads the engine's status there and the engine gives a call that holds a secret only the hosts of that secret. The secret is not sent to that host. EDGAR gives a token that may only read, as `EDGAR_API_TOKEN`, only to an extension whose manifest lists `network:127.0.0.1`, and the service sends it on each read of the status, the runs and the spend.
56
56
 
57
57
  - On `smtp://`, EDGAR sends `STARTTLS` when the server offers it. A server that does not offer it gets no password, and the mail ends `refused`, unless the host is `127.0.0.1`, `localhost` or `[::1]`, a relay on the same machine.
58
58
  - The user and the password sign in with `AUTH PLAIN`. The password never enters a message, a log line or an outcome.
@@ -86,7 +86,7 @@ Run on 2026-11-12 from the repository root. No SMTP account was used. The tests
86
86
  | `pnpm --filter @kana-ai/edgar-ext-email run check-types` | 0 |
87
87
  | `pnpm --filter @kana-ai/edgar-ext-email run lint` | 0 |
88
88
  | `pnpm --filter @kana-ai/edgar-ext-email run format:check` | 0 |
89
- | `pnpm --filter @kana-ai/edgar-ext-email run test` | 0, 13 tests pass |
89
+ | `pnpm --filter @kana-ai/edgar-ext-email run test` | 0, 18 tests pass |
90
90
  | `pnpm --filter @kana-ai/edgar-ext-email run build`, twice | 0, the same bytes |
91
91
 
92
92
  ## Shortcuts
@@ -23,6 +23,7 @@ export function mailParts(spec) {
23
23
  schema,
24
24
  tools: {
25
25
  send: defineTool({
26
+ publishes: true,
26
27
  description: "Send a plain-text mail, to the table's `to` unless the call names readers",
27
28
  input: sendTool.input,
28
29
  output: sendTool.output,
@@ -18,13 +18,37 @@ export const sender = z.union([
18
18
  /** The table both mail extensions take: who sends and who reads, the topics that send a mail, the engine API on loopback, the console at an address the readers can open, and how often the service reads the API. `from` has a default only where the vendor gives one. */
19
19
  export function configOf(from) {
20
20
  return z.strictObject({
21
- from: from === undefined ? sender : sender.default(from),
22
- reply_to: sender.optional(),
23
- to: z.array(z.email()).min(1).max(50),
24
- on: z.array(z.enum(topics)).default(topics.filter((topic) => topic !== "end")),
25
- api_port: z.number().int().min(1).max(65_535).default(7400),
26
- console_url: z.url({ protocol: /^https?$/ }).optional(),
27
- every_seconds: z.number().int().min(10).max(3600).default(60),
21
+ from: (from === undefined ? sender : sender.default(from)).describe(`Who sends each mail, as an address or Name <address>.${from === undefined ? "" : ` Default ${from}.`}`),
22
+ reply_to: sender
23
+ .optional()
24
+ .describe("Where replies go, as an address or Name <address>. With none, replies go to the sender."),
25
+ to: z
26
+ .array(z.email())
27
+ .min(1)
28
+ .max(50)
29
+ .describe("The addresses each mail goes to, 1 to 50. A send call can name its own."),
30
+ on: z
31
+ .array(z.enum(topics))
32
+ .default(topics.filter((topic) => topic !== "end"))
33
+ .describe("The topics that send a mail. Default every topic but end, which sends one mail at the end of each run."),
34
+ api_port: z
35
+ .number()
36
+ .int()
37
+ .min(1)
38
+ .max(65_535)
39
+ .default(7400)
40
+ .describe("The port of the engine API on 127.0.0.1, as in [api] bind. Default 7400."),
41
+ console_url: z
42
+ .url({ protocol: /^https?$/ })
43
+ .optional()
44
+ .describe("The console's address as the readers open it. When set, the end-of-run mail links the run's page."),
45
+ every_seconds: z
46
+ .number()
47
+ .int()
48
+ .min(10)
49
+ .max(3600)
50
+ .default(60)
51
+ .describe("How often the service reads the engine API, in seconds. Default 60."),
28
52
  });
29
53
  }
30
54
  /** The table of a call, with its defaults; one that does not match is a permanent `invalid` that names `name`'s table. */
@@ -35,6 +35,18 @@ export declare const status: z.ZodObject<{
35
35
  outbox_count: z.ZodNumber;
36
36
  approvals_count: z.ZodNumber;
37
37
  }, z.core.$loose>;
38
+ last_start: z.ZodNullable<z.ZodObject<{
39
+ at: z.ZodNumber;
40
+ clean: z.ZodBoolean;
41
+ }, z.core.$loose>>;
42
+ alerts: z.ZodArray<z.ZodObject<{
43
+ at: z.ZodNumber;
44
+ message: z.ZodString;
45
+ }, z.core.$loose>>;
46
+ last_backup: z.ZodNullable<z.ZodObject<{
47
+ at: z.ZodNumber;
48
+ failure: z.ZodNullable<z.ZodString>;
49
+ }, z.core.$loose>>;
38
50
  }, z.core.$loose>;
39
51
  export type Status = z.infer<typeof status>;
40
52
  /** One page of `GET /api/runs`, newest first. */
@@ -48,6 +60,21 @@ export declare const runPage: z.ZodObject<{
48
60
  next: z.ZodNullable<z.ZodString>;
49
61
  }, z.core.$loose>;
50
62
  export type RunPage = z.infer<typeof runPage>;
63
+ /** The part of `GET /api/usage` the daily report reads: the model calls by UTC hour, provider and role. `cost_micros` is in millionths of a USD and counts only the calls that have a cost; `unpriced_tokens` are the tokens of the calls that have none. */
64
+ export declare const usage: z.ZodObject<{
65
+ rows: z.ZodArray<z.ZodObject<{
66
+ hour: z.ZodNumber;
67
+ provider: z.ZodString;
68
+ role: z.ZodOptional<z.ZodString>;
69
+ calls: z.ZodNumber;
70
+ input_tokens: z.ZodNumber;
71
+ output_tokens: z.ZodNumber;
72
+ cost_micros: z.ZodNumber;
73
+ priced_calls: z.ZodNumber;
74
+ unpriced_tokens: z.ZodNumber;
75
+ }, z.core.$loose>>;
76
+ }, z.core.$loose>;
77
+ export type Usage = z.infer<typeof usage>;
51
78
  /** The part of an `attempt_outcome` payload the budget line reads. */
52
79
  export declare const attemptOutcome: z.ZodObject<{
53
80
  outcome: z.ZodObject<{
@@ -17,6 +17,9 @@ export const status = z.looseObject({
17
17
  outbox_count: z.number(),
18
18
  approvals_count: z.number(),
19
19
  }),
20
+ last_start: z.looseObject({ at: z.number(), clean: z.boolean() }).nullable(),
21
+ alerts: z.array(z.looseObject({ at: z.number(), message: z.string() })),
22
+ last_backup: z.looseObject({ at: z.number(), failure: z.string().nullable() }).nullable(),
20
23
  });
21
24
  /** One page of `GET /api/runs`, newest first. */
22
25
  export const runPage = z.looseObject({
@@ -28,6 +31,20 @@ export const runPage = z.looseObject({
28
31
  })),
29
32
  next: z.string().nullable(),
30
33
  });
34
+ /** The part of `GET /api/usage` the daily report reads: the model calls by UTC hour, provider and role. `cost_micros` is in millionths of a USD and counts only the calls that have a cost; `unpriced_tokens` are the tokens of the calls that have none. */
35
+ export const usage = z.looseObject({
36
+ rows: z.array(z.looseObject({
37
+ hour: z.number(),
38
+ provider: z.string(),
39
+ role: z.string().optional(),
40
+ calls: z.number(),
41
+ input_tokens: z.number(),
42
+ output_tokens: z.number(),
43
+ cost_micros: z.number(),
44
+ priced_calls: z.number(),
45
+ unpriced_tokens: z.number(),
46
+ })),
47
+ });
31
48
  /** The part of an `attempt_outcome` payload the budget line reads. */
32
49
  export const attemptOutcome = z.looseObject({
33
50
  outcome: z.looseObject({ kind: z.string().optional() }),
@@ -1,4 +1,5 @@
1
1
  import { type Failure, type Result } from "@kana-ai/edgar-sdk";
2
+ import { type Status } from "#schemas/engine";
2
3
  import { type Note } from "#watch/status";
3
4
  /** The UTC day of `ms`, as `YYYY-MM-DD`. */
4
5
  export declare function dayOf(ms: number): string;
@@ -14,5 +15,21 @@ export interface Ended {
14
15
  * shortcut: it stops at a page whose runs were all created a week before that day, or after 20 pages; upgrade when the API filters by `finished_at`.
15
16
  */
16
17
  export declare function yesterday(port: number, now: number, signal: AbortSignal): Promise<Result<Ended, Failure>>;
17
- /** The daily report: how the runs of the day ended, and what waits for a person now. */
18
- export declare function dailyNote(ended: Ended, waiting: number | undefined): Note;
18
+ /** What the model calls of one provider or one role used: the tokens and calls of all, and the cost of those that have one. */
19
+ export interface Spent {
20
+ readonly name: string;
21
+ readonly calls: number;
22
+ readonly tokens: number;
23
+ readonly costMicros: number;
24
+ readonly pricedCalls: number;
25
+ readonly unpricedTokens: number;
26
+ }
27
+ /** What the model calls that ended on one UTC day used, by provider and by role, each largest cost first, then most tokens. */
28
+ export interface Spend {
29
+ readonly byProvider: readonly Spent[];
30
+ readonly byRole: readonly Spent[];
31
+ }
32
+ /** What the model calls that ended on the UTC day before `now` used, from `GET /api/usage`, by provider and by the role that ran the stage. */
33
+ export declare function spendOf(port: number, now: number, signal: AbortSignal): Promise<Result<Spend, Failure>>;
34
+ /** The daily report: how the runs of the day ended, what waits for a person now, what the model calls of the day used, and how the last backup ended. */
35
+ export declare function dailyNote(ended: Ended, waiting: number | undefined, spend: Spend | undefined, backup: Status["last_backup"] | undefined): Note;
@@ -1,5 +1,5 @@
1
1
  import { ok } from "@kana-ai/edgar-sdk";
2
- import { runPage } from "#schemas/engine";
2
+ import { runPage, usage } from "#schemas/engine";
3
3
  import { readApi } from "#watch/status";
4
4
  const DAY_MS = 86_400_000;
5
5
  /** At most this many pages of 200 runs are read for one report. */
@@ -8,13 +8,17 @@ const PAGES = 20;
8
8
  export function dayOf(ms) {
9
9
  return new Date(ms).toISOString().slice(0, 10);
10
10
  }
11
+ /** The first millisecond of the UTC day before the one of `now`, and of the day of `now`. */
12
+ function dayBefore(now) {
13
+ const end = Date.parse(`${dayOf(now)}T00:00:00Z`);
14
+ return { start: end - DAY_MS, end };
15
+ }
11
16
  /**
12
17
  * Counts the runs that ended on the UTC day before `now`, newest first.
13
18
  * shortcut: it stops at a page whose runs were all created a week before that day, or after 20 pages; upgrade when the API filters by `finished_at`.
14
19
  */
15
20
  export async function yesterday(port, now, signal) {
16
- const end = Date.parse(`${dayOf(now)}T00:00:00Z`);
17
- const start = end - DAY_MS;
21
+ const { start, end } = dayBefore(now);
18
22
  const counts = { day: dayOf(start), done: 0, failed: 0, cancelled: 0 };
19
23
  let after = null;
20
24
  for (let page = 0; page < PAGES; page += 1) {
@@ -39,8 +43,71 @@ export async function yesterday(port, now, signal) {
39
43
  }
40
44
  return ok(counts);
41
45
  }
42
- /** The daily report: how the runs of the day ended, and what waits for a person now. */
43
- export function dailyNote(ended, waiting) {
46
+ /** The rows summed by `key`, largest cost first, then most tokens. */
47
+ function sums(rows, key) {
48
+ const all = new Map();
49
+ for (const row of rows) {
50
+ const name = key(row);
51
+ const was = all.get(name);
52
+ all.set(name, {
53
+ name,
54
+ calls: (was?.calls ?? 0) + row.calls,
55
+ tokens: (was?.tokens ?? 0) + row.input_tokens + row.output_tokens,
56
+ costMicros: (was?.costMicros ?? 0) + row.cost_micros,
57
+ pricedCalls: (was?.pricedCalls ?? 0) + row.priced_calls,
58
+ unpricedTokens: (was?.unpricedTokens ?? 0) + row.unpriced_tokens,
59
+ });
60
+ }
61
+ return [...all.values()].toSorted((a, b) => b.costMicros - a.costMicros || b.tokens - a.tokens);
62
+ }
63
+ /** What the model calls that ended on the UTC day before `now` used, from `GET /api/usage`, by provider and by the role that ran the stage. */
64
+ export async function spendOf(port, now, signal) {
65
+ const { start, end } = dayBefore(now);
66
+ const read = await readApi(port, `/api/usage?from=${String(start)}`, usage, signal);
67
+ if (!read.ok)
68
+ return read;
69
+ const rows = read.value.rows.filter((row) => row.hour >= start && row.hour < end);
70
+ return ok({
71
+ byProvider: sums(rows, (row) => row.provider),
72
+ byRole: sums(rows, (row) => row.role ?? "a role EDGAR no longer keeps"),
73
+ });
74
+ }
75
+ const money = (micros) => `$${(micros / 1_000_000).toFixed(2)}`;
76
+ const count = (n) => n.toLocaleString("en-US");
77
+ /** One line of the spend: the cost, the tokens that have no cost, and the calls. A provider that reports no cost shows its tokens only, and says so. */
78
+ function spentLine(spent) {
79
+ const calls = spent.calls === 1 ? "1 call" : `${count(spent.calls)} calls`;
80
+ if (spent.pricedCalls === 0)
81
+ return `- ${spent.name}: ${count(spent.tokens)} tokens, ${calls}; no cost, as none was reported and no price is set`;
82
+ const unpriced = spent.unpricedTokens === 0 ? "" : `, and ${count(spent.unpricedTokens)} tokens with no cost`;
83
+ return `- ${spent.name}: ${money(spent.costMicros)}${unpriced}, ${calls}`;
84
+ }
85
+ /** The spend part of the daily report; `undefined` when EDGAR could not read it. */
86
+ function spendText(day, spend) {
87
+ if (spend === undefined)
88
+ return "EDGAR could not read what the model calls cost.";
89
+ if (spend.byProvider.length === 0)
90
+ return `No model call ended on ${day}.`;
91
+ return [
92
+ `What the model calls of ${day} used, by provider:`,
93
+ ...spend.byProvider.map(spentLine),
94
+ "By the role that ran the stage:",
95
+ ...spend.byRole.map(spentLine),
96
+ ].join("\n");
97
+ }
98
+ /** The backup part of the daily report, from `last_backup` of the status; `undefined` when EDGAR could not read the status. */
99
+ function backupText(backup) {
100
+ if (backup === undefined)
101
+ return "EDGAR could not read how the last backup ended.";
102
+ if (backup === null)
103
+ return "EDGAR has made no backup yet.";
104
+ const at = `${new Date(backup.at).toISOString().slice(0, 16).replace("T", " ")} UTC`;
105
+ return backup.failure === null
106
+ ? `The last backup, at ${at}, worked.`
107
+ : `The last backup, at ${at}, failed: ${backup.failure}`;
108
+ }
109
+ /** The daily report: how the runs of the day ended, what waits for a person now, what the model calls of the day used, and how the last backup ended. */
110
+ export function dailyNote(ended, waiting, spend, backup) {
44
111
  const total = ended.done + ended.failed + ended.cancelled;
45
112
  const runs = total === 1 ? "1 run" : `${String(total)} runs`;
46
113
  const wait = waiting === undefined
@@ -51,6 +118,12 @@ export function dailyNote(ended, waiting) {
51
118
  return {
52
119
  topic: "daily",
53
120
  subject: `EDGAR on ${ended.day}: ${runs} ended, ${String(ended.done)} done`,
54
- body: `On ${ended.day} (UTC), ${runs} ended: ${String(ended.done)} done, ${String(ended.failed)} failed, ${String(ended.cancelled)} cancelled. ${wait}`,
121
+ body: [
122
+ `On ${ended.day} (UTC), ${runs} ended: ${String(ended.done)} done, ${String(ended.failed)} failed, ${String(ended.cancelled)} cancelled. ${wait}`,
123
+ "",
124
+ spendText(ended.day, spend),
125
+ "",
126
+ backupText(backup),
127
+ ].join("\n"),
55
128
  };
56
129
  }
@@ -3,5 +3,5 @@ import type { Config } from "#schemas/config";
3
3
  import { type Note } from "#watch/status";
4
4
  /** Sends one note on the extension's transport. */
5
5
  export type Send = (note: Note, signal: AbortSignal) => Promise<Result<string, Failure>>;
6
- /** The service: a mail at start, one for each new problem, hold and release that `GET /api/status` shows, the daily report at the first read of a new UTC day, and a mail at stop. What was seen, and the day, move on only when each of their mails is settled. A start mail the vendor refuses for good ends the service, so its breaker shows the bad secret. */
6
+ /** The service: a mail at start, which says when the last stop was not clean, one for each new problem, hold and release that `GET /api/status` shows, the daily report at the first read of a new UTC day, with the runs, the spend and the last backup, and a mail at stop. What was seen, and the day, move on only when each of their mails is settled. A start mail the vendor refuses for good ends the service, so its breaker shows the bad secret. */
7
7
  export declare function watch(ctx: Ctx<string>, settings: Config, send: Send, now?: () => number): Promise<Outcome>;
@@ -1,7 +1,7 @@
1
1
  import { setTimeout as sleep } from "node:timers/promises";
2
2
  import { attemptAsync, done, } from "@kana-ai/edgar-sdk";
3
- import { dailyNote, dayOf, yesterday } from "#watch/daily";
4
- import { FIRST, notesOf, readStatus, waitingOf } from "#watch/status";
3
+ import { dailyNote, dayOf, spendOf, yesterday } from "#watch/daily";
4
+ import { FIRST, notesOf, readStatus, startNote, waitingOf } from "#watch/status";
5
5
  /** How long the mail at shutdown may take, since the service's own signal has aborted by then. */
6
6
  const STOP_MS = 10_000;
7
7
  /** Sends `note` when its topic is on; a failed send is logged and never stops the service, so one bad mail does not stop the next. */
@@ -16,15 +16,16 @@ async function mail(ctx, settings, send, note, signal) {
16
16
  }
17
17
  /** Whether a mail is settled: sent, or refused for good. One that failed for a while is sent again at the next read. */
18
18
  const settled = (sent) => sent.outcome !== "temporary_failure";
19
- /** The service: a mail at start, one for each new problem, hold and release that `GET /api/status` shows, the daily report at the first read of a new UTC day, and a mail at stop. What was seen, and the day, move on only when each of their mails is settled. A start mail the vendor refuses for good ends the service, so its breaker shows the bad secret. */
19
+ /** The service: a mail at start, which says when the last stop was not clean, one for each new problem, hold and release that `GET /api/status` shows, the daily report at the first read of a new UTC day, with the runs, the spend and the last backup, and a mail at stop. What was seen, and the day, move on only when each of their mails is settled. A start mail the vendor refuses for good ends the service, so its breaker shows the bad secret. */
20
20
  export async function watch(ctx, settings, send, now = Date.now) {
21
- const started = await mail(ctx, settings, send, { topic: "started", subject: "EDGAR has started", body: "EDGAR is running and takes work." }, ctx.signal);
21
+ let read = await readStatus(settings.api_port, ctx.signal);
22
+ const note = startNote(read.ok ? read.value : undefined);
23
+ const started = await mail(ctx, settings, send, note, ctx.signal);
22
24
  if (started.outcome === "permanent_failure" && started.kind !== "cancelled")
23
25
  return started;
24
26
  let seen = FIRST;
25
27
  let day = dayOf(now());
26
28
  while (!ctx.signal.aborted) {
27
- const read = await readStatus(settings.api_port, ctx.signal);
28
29
  if (read.ok) {
29
30
  const next = notesOf(seen, read.value);
30
31
  let all = true;
@@ -41,7 +42,10 @@ export async function watch(ctx, settings, send, now = Date.now) {
41
42
  if (!ended.ok)
42
43
  ctx.log(`daily report: ${ended.error.message}`);
43
44
  else {
44
- const note = dailyNote(ended.value, read.ok ? waitingOf(read.value) : undefined);
45
+ const spend = await spendOf(settings.api_port, now(), ctx.signal);
46
+ if (!spend.ok)
47
+ ctx.log(`daily report: ${spend.error.message}`);
48
+ const note = dailyNote(ended.value, read.ok ? waitingOf(read.value) : undefined, spend.ok ? spend.value : undefined, read.ok ? read.value.last_backup : undefined);
45
49
  if (settled(await mail(ctx, settings, send, note, ctx.signal)))
46
50
  day = today;
47
51
  }
@@ -49,6 +53,8 @@ export async function watch(ctx, settings, send, now = Date.now) {
49
53
  else
50
54
  day = today;
51
55
  await attemptAsync(async () => await sleep(settings.every_seconds * 1000, undefined, { signal: ctx.signal }), () => undefined);
56
+ if (!ctx.signal.aborted)
57
+ read = await readStatus(settings.api_port, ctx.signal);
52
58
  }
53
59
  await mail(ctx, settings, send, {
54
60
  topic: "stopped",
@@ -19,7 +19,9 @@ export declare const FIRST: Seen;
19
19
  export declare function readApi<T>(port: number, path: string, schema: z.ZodType<T>, signal: AbortSignal): Promise<Result<T, Failure>>;
20
20
  /** Reads `GET /api/status`. */
21
21
  export declare function readStatus(port: number, signal: AbortSignal): Promise<Result<Status, Failure>>;
22
- /** What needs a look now: a stale database, a stopped worker, and each breaker that is not closed. */
22
+ /** The mail at start, from the first read of `GET /api/status`: it says when the worker before did not stop cleanly, and when the read failed, that EDGAR could not tell. */
23
+ export declare function startNote(read: Status | undefined): Note;
24
+ /** What needs a look now: a stale database, a stopped worker, each breaker that is not closed, and the first line of each open alert, so an alert mails once while it is open. */
23
25
  export declare function problemsOf(read: Status): string[];
24
26
  /** The number of things that wait for a person now. */
25
27
  export declare function waitingOf(read: Status): number;
@@ -34,7 +34,24 @@ export async function readApi(port, path, schema, signal) {
34
34
  export async function readStatus(port, signal) {
35
35
  return await readApi(port, "/api/status", status, signal);
36
36
  }
37
- /** What needs a look now: a stale database, a stopped worker, and each breaker that is not closed. */
37
+ /** The mail at start, from the first read of `GET /api/status`: it says when the worker before did not stop cleanly, and when the read failed, that EDGAR could not tell. */
38
+ export function startNote(read) {
39
+ const running = "EDGAR is running and takes work.";
40
+ if (read?.last_start?.clean === false)
41
+ return {
42
+ topic: "started",
43
+ subject: "EDGAR has started after a crash",
44
+ body: `${running} The last time, it did not stop cleanly: it crashed or was killed. \`edgar logs\` shows how its last run ended.`,
45
+ };
46
+ return {
47
+ topic: "started",
48
+ subject: "EDGAR has started",
49
+ body: read === undefined
50
+ ? `${running} It could not read whether it stopped cleanly the last time.`
51
+ : running,
52
+ };
53
+ }
54
+ /** What needs a look now: a stale database, a stopped worker, each breaker that is not closed, and the first line of each open alert, so an alert mails once while it is open. */
38
55
  export function problemsOf(read) {
39
56
  const problems = [];
40
57
  if (read.engine.state === "stale_database")
@@ -43,6 +60,11 @@ export function problemsOf(read) {
43
60
  problems.push("no worker answers, so no run moves");
44
61
  for (const breaker of read.breakers)
45
62
  problems.push(`the breaker of ${breaker.name} is ${breaker.state.replace("_", " ")}`);
63
+ for (const alert of read.alerts) {
64
+ const problem = `alert: ${alert.message.split("\n", 1)[0] ?? ""}`;
65
+ if (!problems.includes(problem))
66
+ problems.push(problem);
67
+ }
46
68
  return problems;
47
69
  }
48
70
  /** The number of things that wait for a person now. */
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "contract": 1,
3
3
  "name": "email",
4
- "version": "0.1.2",
4
+ "version": "0.1.4",
5
5
  "config_schema": "schemas/config.json",
6
6
  "secrets": [
7
7
  {
@@ -20,6 +20,7 @@
20
20
  "secrets": ["EMAIL_SMTP_URL"],
21
21
  "capabilities": [],
22
22
  "side_effect": true,
23
+ "publishes": true,
23
24
  "undo": "none",
24
25
  "undo_reason": "a mail cannot be taken back once it is sent",
25
26
  "approval": "never",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kana-ai/edgar-ext-email",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "EDGAR extension for email: a mail over SMTP when EDGAR starts, stops, pauses or needs a look, a daily report, and a line when a stage runs out of tokens.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -22,11 +22,11 @@
22
22
  "./mail": "./dist/src/mail/define.js"
23
23
  },
24
24
  "dependencies": {
25
- "@kana-ai/edgar-sdk": "0.1.2",
25
+ "@kana-ai/edgar-sdk": "0.1.4",
26
26
  "zod": "4.6.7"
27
27
  },
28
28
  "devDependencies": {
29
- "@kana-ai/edgar-contracts": "0.1.2",
29
+ "@kana-ai/edgar-contracts": "0.1.4",
30
30
  "@types/node": "24.19.2",
31
31
  "oxfmt": "0.76.0",
32
32
  "oxlint": "1.91.0",
@@ -13,9 +13,11 @@
13
13
  "type": "string",
14
14
  "pattern": "^[^<>\\r\\n]+<[^<>\\s@]+@[^<>\\s@]+\\.[^<>\\s@]+>$"
15
15
  }
16
- ]
16
+ ],
17
+ "description": "Who sends each mail, as an address or Name <address>."
17
18
  },
18
19
  "reply_to": {
20
+ "description": "Where replies go, as an address or Name <address>. With none, replies go to the sender.",
19
21
  "anyOf": [
20
22
  {
21
23
  "type": "string",
@@ -36,10 +38,12 @@
36
38
  "type": "string",
37
39
  "format": "email",
38
40
  "pattern": "^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$"
39
- }
41
+ },
42
+ "description": "The addresses each mail goes to, 1 to 50. A send call can name its own."
40
43
  },
41
44
  "on": {
42
45
  "default": ["unhealthy", "paused", "started", "stopped", "daily", "budget"],
46
+ "description": "The topics that send a mail. Default every topic but end, which sends one mail at the end of each run.",
43
47
  "type": "array",
44
48
  "items": {
45
49
  "type": "string",
@@ -48,16 +52,19 @@
48
52
  },
49
53
  "api_port": {
50
54
  "default": 7400,
55
+ "description": "The port of the engine API on 127.0.0.1, as in [api] bind. Default 7400.",
51
56
  "type": "integer",
52
57
  "minimum": 1,
53
58
  "maximum": 65535
54
59
  },
55
60
  "console_url": {
61
+ "description": "The console's address as the readers open it. When set, the end-of-run mail links the run's page.",
56
62
  "type": "string",
57
63
  "format": "uri"
58
64
  },
59
65
  "every_seconds": {
60
66
  "default": 60,
67
+ "description": "How often the service reads the engine API, in seconds. Default 60.",
61
68
  "type": "integer",
62
69
  "minimum": 10,
63
70
  "maximum": 3600