@kana-ai/edgar-ext-email 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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,96 @@
1
- # Temporary Holding Version
1
+ # @kana-ai/edgar-ext-email
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 email extension of EDGAR, over SMTP. It sends a plain-text mail when EDGAR starts, stops, pauses, or needs a look, a daily report of the runs of the day before, and a line when a stage runs out of tokens. It can also mail the end of each run. Stages call its tool as `email__send`.
4
+
5
+ [`@kana-ai/edgar-ext-resend`](/packages/extensions/ext-resend/README.md) has the same tool, hooks, service and table, and sends through the Resend API. To change from one to the other, change the name in `[extensions] enabled`, rename the table, and rename `email__send` to `resend__send` in a stage that calls it.
6
+
7
+ ## Parts
8
+
9
+ | Part | What it does |
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. |
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
+ | 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
+ | 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
+
16
+ What each topic means:
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. |
27
+
28
+ ## Configuration
29
+
30
+ ```toml
31
+ [extensions]
32
+ enabled = ["email"]
33
+
34
+ [extensions.email]
35
+ # the host of EMAIL_SMTP_URL, unless it is 127.0.0.1
36
+ hosts = ["smtp.example.com"]
37
+ from = "EDGAR <edgar@example.com>" # required: an address, or Name <address>
38
+ to = ["ops@example.com"] # required: 1 to 50 readers
39
+ reply_to = "ops@example.com" # optional
40
+ on = [
41
+ "unhealthy",
42
+ "paused",
43
+ "started",
44
+ "stopped",
45
+ "daily",
46
+ "budget",
47
+ ] # the default; add "end" for a mail at each run's end
48
+ api_port = 7400 # the default: the port of [api] bind
49
+ console_url = "https://edgar.example.com" # no default: when set, the end note links the run's page, <console_url>/runs/<id>; use an address the readers can open
50
+ every_seconds = 60 # the default, 10 to 3600: how often the service reads the engine API
51
+ ```
52
+
53
+ ## The secret
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.
56
+
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
+ - The user and the password sign in with `AUTH PLAIN`. The password never enters a message, a log line or an outcome.
59
+ - The body is UTF-8 in base64. A subject or a sender name that is not ASCII is an RFC 2047 word.
60
+
61
+ ## Failures
62
+
63
+ | SMTP answer | Outcome |
64
+ | ---------------------------------- | ------------------------------------------------------------------------------------------------ |
65
+ | 4xx | `temporary_failure`, `provider_unavailable`, `cause` `smtp:<code>` |
66
+ | 530, 534, 535 | `permanent_failure`, `unauthenticated`, with "check the user and the password of EMAIL_SMTP_URL" |
67
+ | Any other 5xx | `permanent_failure`, `refused` |
68
+ | No connection, a reset, 30 s quiet | `temporary_failure`, `network` |
69
+ | A URL that is not SMTP | `permanent_failure`, `invalid` |
70
+
71
+ A tool call or a hook answers the failure, so the engine tries the event again. In the service, a failed mail goes to the log and the next read goes on. A `started` mail that fails for good, such as a refused sign-in, ends the service with that failure, so its breaker opens and the console shows why.
72
+
73
+ ## Build and test
74
+
75
+ ```sh
76
+ pnpm build # writes edgar-extension.json and schemas/
77
+ pnpm test # unit tests against an SMTP server on loopback in the test process and a mock engine API, no network
78
+ ```
79
+
80
+ ## Validation
81
+
82
+ Run on 2026-11-12 from the repository root. No SMTP account was used. The tests run a fake SMTP server on `127.0.0.1` in the test process, which reads each command and decodes each mail.
83
+
84
+ | Command | Exit code |
85
+ | --------------------------------------------------------- | ----------------- |
86
+ | `pnpm --filter @kana-ai/edgar-ext-email run check-types` | 0 |
87
+ | `pnpm --filter @kana-ai/edgar-ext-email run lint` | 0 |
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 |
90
+ | `pnpm --filter @kana-ai/edgar-ext-email run build`, twice | 0, the same bytes |
91
+
92
+ ## Shortcuts
93
+
94
+ - shortcut: SMTP has no idempotency key, so a send that the engine tries again after a lost answer can mail twice.
95
+ - shortcut: the budget mail's once-an-hour bound and the service's last state live in the process, so a restart can send one more.
96
+ - shortcut: the daily report pages `GET /api/runs` newest first, and stops after 20 pages of 200 or at a page whose runs were all created a week before the day. Upgrade when the API filters by `finished_at`.
@@ -0,0 +1,13 @@
1
+ import { sendMail } from "#smtp/client";
2
+ /** The email extension over SMTP: the server, its user and its password are the one secret `EMAIL_SMTP_URL`. */
3
+ export declare const spec: {
4
+ name: string;
5
+ secret: "EMAIL_SMTP_URL";
6
+ help: string;
7
+ hosts: never[];
8
+ capabilities: never[];
9
+ from: undefined;
10
+ transport: typeof sendMail;
11
+ };
12
+ declare const _default: import("@kana-ai/edgar-sdk").Extension;
13
+ export default _default;
@@ -0,0 +1,13 @@
1
+ import { defineMail } from "#mail/define";
2
+ import { sendMail } from "#smtp/client";
3
+ /** The email extension over SMTP: the server, its user and its password are the one secret `EMAIL_SMTP_URL`. */
4
+ export const spec = {
5
+ name: "email",
6
+ secret: "EMAIL_SMTP_URL",
7
+ help: "Set EMAIL_SMTP_URL to smtps://<user>:<password>@<host>:465, or smtp://<user>:<password>@<host>:587 for a server with STARTTLS. Write the user and the password URL-encoded.",
8
+ hosts: [],
9
+ capabilities: [],
10
+ from: undefined,
11
+ transport: sendMail,
12
+ };
13
+ export default defineMail(spec);
@@ -0,0 +1,52 @@
1
+ import { type Capability, type Failure, type Result } from "@kana-ai/edgar-sdk";
2
+ import type { Mail } from "#smtp/message";
3
+ export { type Mail, addressOf } from "#smtp/message";
4
+ /** Sends one mail with the secret's value and answers the vendor's id; `key` makes a retry of the same mail send it once where the vendor takes an idempotency key. */
5
+ export type Transport = (secret: string, mail: Mail, signal: AbortSignal, key: string | undefined) => Promise<Result<string, Failure>>;
6
+ /** What one mail extension differs in: its name, its secret, the hosts and capabilities its transport needs, the default sender, and the transport. */
7
+ export interface MailSpec<S extends string> {
8
+ readonly name: string;
9
+ readonly secret: S;
10
+ readonly help: string;
11
+ readonly hosts: readonly string[];
12
+ readonly capabilities: readonly Capability[];
13
+ readonly from: string | undefined;
14
+ readonly transport: Transport;
15
+ }
16
+ /** The parts of a mail extension: the tool `send`, the hook `end_note` on each run's end, the hook `budget` on a stage out of tokens, and the service that mails on start, stop, a hold, a problem and each day. */
17
+ export declare function mailParts<const S extends string>(spec: MailSpec<S>): {
18
+ schema: import("zod").ZodObject<{
19
+ from: import("zod").ZodDefault<import("zod").ZodUnion<readonly [import("zod").ZodEmail, import("zod").ZodString]>> | import("zod").ZodUnion<readonly [import("zod").ZodEmail, import("zod").ZodString]>;
20
+ reply_to: import("zod").ZodOptional<import("zod").ZodUnion<readonly [import("zod").ZodEmail, import("zod").ZodString]>>;
21
+ to: import("zod").ZodArray<import("zod").ZodEmail>;
22
+ on: import("zod").ZodDefault<import("zod").ZodArray<import("zod").ZodEnum<{
23
+ budget: "budget";
24
+ daily: "daily";
25
+ end: "end";
26
+ paused: "paused";
27
+ started: "started";
28
+ stopped: "stopped";
29
+ unhealthy: "unhealthy";
30
+ }>>>;
31
+ api_port: import("zod").ZodDefault<import("zod").ZodNumber>;
32
+ console_url: import("zod").ZodOptional<import("zod").ZodURL>;
33
+ every_seconds: import("zod").ZodDefault<import("zod").ZodNumber>;
34
+ }, import("zod/v4/core").$strict>;
35
+ tools: {
36
+ send: import("@kana-ai/edgar-sdk").Tool<{
37
+ to?: string[];
38
+ subject: string;
39
+ text: string;
40
+ }, {
41
+ id: string;
42
+ to: string[];
43
+ }, S>;
44
+ };
45
+ hooks: {
46
+ end_note: import("@kana-ai/edgar-sdk").EventHook;
47
+ budget: import("@kana-ai/edgar-sdk").EventHook;
48
+ };
49
+ service: import("@kana-ai/edgar-sdk").Service;
50
+ };
51
+ /** A mail extension. Each one has the shape of `mailParts`, so a project swaps one for another in `[extensions] enabled` and its table. */
52
+ export declare function defineMail<const S extends string>(spec: MailSpec<S>): import("@kana-ai/edgar-sdk").Extension;
@@ -0,0 +1,114 @@
1
+ import { defineEventHook, defineExtension, defineService, defineTool, done, } from "@kana-ai/edgar-sdk";
2
+ import { configOf, settingsOf } from "#schemas/config";
3
+ import { sendTool } from "#schemas/tools";
4
+ export { addressOf } from "#smtp/message";
5
+ import { BUDGET_EVERY_MS, budgetNoteOf, endNoteOf } from "#mail/notes";
6
+ import { watch } from "#watch/service";
7
+ /** The engine API on loopback, which the service reads. */
8
+ const API_HOST = "127.0.0.1";
9
+ const API = `network:${API_HOST}`;
10
+ /** The parts of a mail extension: the tool `send`, the hook `end_note` on each run's end, the hook `budget` on a stage out of tokens, and the service that mails on start, stop, a hold, a problem and each day. */
11
+ export function mailParts(spec) {
12
+ const schema = configOf(spec.from);
13
+ const access = { secrets: [spec.secret], capabilities: [...spec.capabilities] };
14
+ const sender = (ctx, settings) => async (note, signal, key) => await spec.transport(ctx.secrets.get(spec.secret), {
15
+ from: settings.from,
16
+ replyTo: settings.reply_to,
17
+ to: note.to ?? settings.to,
18
+ subject: note.subject,
19
+ body: note.body,
20
+ }, signal, key);
21
+ let budgetSent = Number.NEGATIVE_INFINITY;
22
+ return {
23
+ schema,
24
+ tools: {
25
+ send: defineTool({
26
+ description: "Send a plain-text mail, to the table's `to` unless the call names readers",
27
+ input: sendTool.input,
28
+ output: sendTool.output,
29
+ ...access,
30
+ side_effect: true,
31
+ undo: "none",
32
+ undo_reason: "a mail cannot be taken back once it is sent",
33
+ execute: async (input, ctx) => {
34
+ const settings = settingsOf(schema, spec.name, ctx.config);
35
+ if (!settings.ok)
36
+ return settings.error;
37
+ const to = input.to ?? settings.value.to;
38
+ const note = {
39
+ topic: "end",
40
+ subject: input.subject,
41
+ body: input.text,
42
+ to,
43
+ };
44
+ const sent = await sender(ctx, settings.value)(note, ctx.signal, ctx.operation_id);
45
+ return sent.ok ? done({ id: sent.value, to: [...to] }) : sent.error;
46
+ },
47
+ }),
48
+ },
49
+ hooks: {
50
+ end_note: defineEventHook({
51
+ events: ["run_outcome"],
52
+ ...access,
53
+ deliver: async (event, ctx) => {
54
+ const settings = settingsOf(schema, spec.name, ctx.config);
55
+ if (!settings.ok)
56
+ return settings.error;
57
+ if (!settings.value.on.includes("end"))
58
+ return done({});
59
+ const note = endNoteOf(event, settings.value.console_url);
60
+ if (note === undefined)
61
+ return done({});
62
+ const key = `edgar-end-${event.run}-${String(event.id)}`;
63
+ const sent = await sender(ctx, settings.value)(note, ctx.signal, key);
64
+ return sent.ok ? done({}) : sent.error;
65
+ },
66
+ }),
67
+ budget: defineEventHook({
68
+ events: ["attempt_outcome"],
69
+ ...access,
70
+ deliver: async (event, ctx) => {
71
+ const settings = settingsOf(schema, spec.name, ctx.config);
72
+ if (!settings.ok)
73
+ return settings.error;
74
+ const note = budgetNoteOf(event);
75
+ const now = Date.now();
76
+ if (!settings.value.on.includes("budget") || note === undefined)
77
+ return done({});
78
+ if (now - budgetSent < BUDGET_EVERY_MS)
79
+ return done({});
80
+ const key = `edgar-budget-${event.run}-${String(event.id)}`;
81
+ const sent = await sender(ctx, settings.value)(note, ctx.signal, key);
82
+ if (!sent.ok)
83
+ return sent.error;
84
+ budgetSent = now;
85
+ return done({});
86
+ },
87
+ }),
88
+ },
89
+ service: defineService({
90
+ secrets: [spec.secret],
91
+ capabilities: [...spec.capabilities, API],
92
+ run: async (ctx) => {
93
+ const settings = settingsOf(schema, spec.name, ctx.config);
94
+ if (!settings.ok)
95
+ return settings.error;
96
+ const send = async (note, signal) => await sender(ctx, settings.value)(note, signal);
97
+ return await watch(ctx, settings.value, send);
98
+ },
99
+ }),
100
+ };
101
+ }
102
+ /** A mail extension. Each one has the shape of `mailParts`, so a project swaps one for another in `[extensions] enabled` and its table. */
103
+ export function defineMail(spec) {
104
+ const { schema, tools, hooks, service } = mailParts(spec);
105
+ return defineExtension({
106
+ name: spec.name,
107
+ config: schema,
108
+ secrets: { [spec.secret]: { hosts: [...spec.hosts, API_HOST], help: spec.help } },
109
+ capabilities: [...spec.capabilities, API],
110
+ tools,
111
+ hooks,
112
+ service,
113
+ });
114
+ }
@@ -0,0 +1,7 @@
1
+ import { type RunEvent } from "@kana-ai/edgar-sdk";
2
+ import type { Note } from "#watch/status";
3
+ export declare const BUDGET_EVERY_MS = 3600000;
4
+ /** The end note of a `run_outcome`: the subject says what happened and names the card, or the run when it has no card; the body is the note of `endNote`, with the run's page when `consoleUrl` is set. An event that `endNote` cannot read gives a note that says only that the run is over. No note for a run with no card that ends done, and none for a failed run of a schedule whose run just before it failed the same way. */
5
+ export declare function endNoteOf(event: RunEvent, consoleUrl: string | undefined): Note | undefined;
6
+ /** The budget line of an `attempt_outcome` whose stage spent its `max_tokens`; none for any other outcome. */
7
+ export declare function budgetNoteOf(event: RunEvent): Note | undefined;
@@ -0,0 +1,51 @@
1
+ import { endNote } from "@kana-ai/edgar-sdk";
2
+ import { attemptOutcome } from "#schemas/engine";
3
+ export const BUDGET_EVERY_MS = 3_600_000;
4
+ /** The most characters of a card's id and title in a subject: a mail line holds 998, and a long title in an encoded word passes that. */
5
+ const SUBJECT_CHARS = 120;
6
+ /** How a plain-text mail writes an end note: a link as its label with the address in brackets, and each text as it is. */
7
+ const style = { link: (url, label) => `${label} (${url})`, text: (text) => text };
8
+ /** The start of an end note's subject, by the one thing the reader must know. */
9
+ const subjects = {
10
+ opened: "EDGAR opened a pull request",
11
+ merged: "The pull request is merged",
12
+ approved: "The pull request is approved",
13
+ changes: "A reviewer asked for changes",
14
+ closed: "The pull request was closed with no merge",
15
+ decision: "EDGAR needs your decision",
16
+ waits: "EDGAR is waiting",
17
+ failed: "EDGAR could not finish",
18
+ stopped: "A person stopped the run",
19
+ done: "EDGAR finished",
20
+ recovered: "EDGAR works again",
21
+ };
22
+ /** The end note of a `run_outcome`: the subject says what happened and names the card, or the run when it has no card; the body is the note of `endNote`, with the run's page when `consoleUrl` is set. An event that `endNote` cannot read gives a note that says only that the run is over. No note for a run with no card that ends done, and none for a failed run of a schedule whose run just before it failed the same way. */
23
+ export function endNoteOf(event, consoleUrl) {
24
+ const note = endNote(event, style, consoleUrl);
25
+ if (note === undefined)
26
+ return {
27
+ topic: "end",
28
+ subject: `EDGAR: run ${event.run} is over`,
29
+ body: `Run ${event.run} is over.`,
30
+ };
31
+ const { card } = note;
32
+ if (note.repeat || (card === undefined && note.what === "done"))
33
+ return undefined;
34
+ const named = Array.from(card?.id === undefined ? (card?.title ?? "") : `${card.id} ${card.title}`);
35
+ const about = card === undefined
36
+ ? ` (run ${event.run})`
37
+ : `: ${named.slice(0, SUBJECT_CHARS).join("")}${named.length > SUBJECT_CHARS ? "…" : ""}`;
38
+ return { topic: "end", subject: `${subjects[note.what]}${about}`, body: note.lines.join("\n") };
39
+ }
40
+ /** The budget line of an `attempt_outcome` whose stage spent its `max_tokens`; none for any other outcome. */
41
+ export function budgetNoteOf(event) {
42
+ const record = attemptOutcome.safeParse(event.payload);
43
+ if (record.data?.outcome.kind !== "token_budget")
44
+ return undefined;
45
+ const stage = event.stage ?? "a stage";
46
+ return {
47
+ topic: "budget",
48
+ subject: `EDGAR: a stage ran out of tokens (run ${event.run})`,
49
+ body: `The stage ${stage} of run ${event.run} spent its max_tokens, so it stopped. Raise the role's limits.max_tokens, or split the stage. EDGAR sends this mail at most once an hour.`,
50
+ };
51
+ }
@@ -0,0 +1,30 @@
1
+ import { type Failure, type Result } from "@kana-ai/edgar-sdk";
2
+ import { z } from "zod";
3
+ /** What a mail is about. The first six are on by default; `end`, a mail at the end of each run, is not. */
4
+ export declare const topics: readonly ["unhealthy", "paused", "started", "stopped", "daily", "budget", "end"];
5
+ export type Topic = (typeof topics)[number];
6
+ /** An address, or `Name <address>`. */
7
+ export declare const sender: z.ZodUnion<readonly [z.ZodEmail, z.ZodString]>;
8
+ /** 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. */
9
+ export declare function configOf(from: string | undefined): z.ZodObject<{
10
+ from: z.ZodDefault<z.ZodUnion<readonly [z.ZodEmail, z.ZodString]>> | z.ZodUnion<readonly [z.ZodEmail, z.ZodString]>;
11
+ reply_to: z.ZodOptional<z.ZodUnion<readonly [z.ZodEmail, z.ZodString]>>;
12
+ to: z.ZodArray<z.ZodEmail>;
13
+ on: z.ZodDefault<z.ZodArray<z.ZodEnum<{
14
+ budget: "budget";
15
+ daily: "daily";
16
+ end: "end";
17
+ paused: "paused";
18
+ started: "started";
19
+ stopped: "stopped";
20
+ unhealthy: "unhealthy";
21
+ }>>>;
22
+ api_port: z.ZodDefault<z.ZodNumber>;
23
+ console_url: z.ZodOptional<z.ZodURL>;
24
+ every_seconds: z.ZodDefault<z.ZodNumber>;
25
+ }, z.core.$strict>;
26
+ export type Config = z.infer<ReturnType<typeof configOf>>;
27
+ /** The table of a call, with its defaults; one that does not match is a permanent `invalid` that names `name`'s table. */
28
+ export declare function settingsOf(schema: ReturnType<typeof configOf>, name: string, value: unknown): Result<Config, Failure>;
29
+ /** `EMAIL_SMTP_URL`: `smtps://` is TLS from the first byte, `smtp://` upgrades with STARTTLS; the user and the password, when given, sign in with `AUTH PLAIN`. */
30
+ export declare const smtpUrl: z.ZodPipe<z.ZodURL, z.ZodTransform<import("url").URL, string>>;
@@ -0,0 +1,41 @@
1
+ import { err, ok, permanentFailure } from "@kana-ai/edgar-sdk";
2
+ import { z } from "zod";
3
+ /** What a mail is about. The first six are on by default; `end`, a mail at the end of each run, is not. */
4
+ export const topics = [
5
+ "unhealthy",
6
+ "paused",
7
+ "started",
8
+ "stopped",
9
+ "daily",
10
+ "budget",
11
+ "end",
12
+ ];
13
+ /** An address, or `Name <address>`. */
14
+ export const sender = z.union([
15
+ z.email(),
16
+ z.string().regex(/^[^<>\r\n]+<[^<>\s@]+@[^<>\s@]+\.[^<>\s@]+>$/),
17
+ ]);
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
+ export function configOf(from) {
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),
28
+ });
29
+ }
30
+ /** The table of a call, with its defaults; one that does not match is a permanent `invalid` that names `name`'s table. */
31
+ export function settingsOf(schema, name, value) {
32
+ const parsed = schema.safeParse(value ?? {});
33
+ return parsed.success
34
+ ? ok(parsed.data)
35
+ : err(permanentFailure("invalid", `the [extensions.${name}] table does not match its schema`));
36
+ }
37
+ /** `EMAIL_SMTP_URL`: `smtps://` is TLS from the first byte, `smtp://` upgrades with STARTTLS; the user and the password, when given, sign in with `AUTH PLAIN`. */
38
+ export const smtpUrl = z
39
+ .url({ protocol: /^smtps?$/ })
40
+ .transform((text) => new URL(text))
41
+ .refine((url) => url.hostname.length > 0);