@parcha/agentrun-serve 0.1.0-beta.39 → 0.1.0-beta.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +51 -1
  3. package/dist/console/assets/index-B8Zn1Iqn.css +1 -0
  4. package/dist/console/assets/index-Jbxjcmdp.js +705 -0
  5. package/dist/console/index.html +2 -2
  6. package/dist/email/account.d.ts +0 -1
  7. package/dist/email/account.js +3 -3
  8. package/dist/email/answer.d.ts +5 -0
  9. package/dist/email/answer.js +35 -0
  10. package/dist/email/mail.js +19 -26
  11. package/dist/email/names.d.ts +30 -0
  12. package/dist/email/names.js +34 -0
  13. package/dist/email/routes.d.ts +1 -0
  14. package/dist/email/routes.js +1 -1
  15. package/dist/email/tools.d.ts +11 -4
  16. package/dist/email/tools.js +91 -46
  17. package/dist/eval-mailbox.d.ts +1 -1
  18. package/dist/eval-mailbox.js +3 -3
  19. package/dist/learn/compile.d.ts +3 -2
  20. package/dist/learn/compile.js +6 -5
  21. package/dist/learn/promote.d.ts +25 -14
  22. package/dist/learn/promote.js +32 -14
  23. package/dist/learning-cost.d.ts +17 -8
  24. package/dist/learning-cost.js +12 -4
  25. package/dist/local-models.d.ts +7 -1
  26. package/dist/local-models.js +11 -5
  27. package/dist/openapi.d.ts +1 -1
  28. package/dist/openapi.js +17 -15
  29. package/dist/port-models.d.ts +4 -1
  30. package/dist/port-models.js +1 -0
  31. package/dist/refusal-words.d.ts +3 -0
  32. package/dist/refusal-words.js +3 -0
  33. package/dist/run-launch.d.ts +2 -0
  34. package/dist/run-launch.js +2 -0
  35. package/dist/run-view.d.ts +3 -4
  36. package/dist/run-view.js +26 -24
  37. package/dist/runner/adapter-loop.d.ts +6 -2
  38. package/dist/runner/adapter-loop.js +45 -12
  39. package/dist/runner/adapter-run-spec.d.ts +1 -0
  40. package/dist/runner/adapter-run-spec.js +37 -1
  41. package/dist/runner/cli-run-spec.js +1 -0
  42. package/dist/runner/journal-kinds.d.ts +22 -0
  43. package/dist/runner/journal-kinds.js +39 -0
  44. package/dist/runner/model-route.d.ts +3 -1
  45. package/dist/runner/model-route.js +18 -3
  46. package/dist/runner/promotion.d.ts +8 -8
  47. package/dist/runner/promotion.js +135 -54
  48. package/dist/server.js +15 -8
  49. package/dist/store/dialect.d.ts +3 -0
  50. package/dist/store/dialect.js +1 -0
  51. package/dist/store/postgres/connection.d.ts +11 -5
  52. package/dist/store/postgres/connection.js +44 -17
  53. package/dist/store/postgres/dialect.js +5 -0
  54. package/dist/store/postgres/store.d.ts +7 -3
  55. package/dist/store/postgres/store.js +1 -0
  56. package/dist/store/sqlite/connection.js +72 -8
  57. package/dist/store/sqlite/run-launch.d.ts +11 -0
  58. package/dist/store/sqlite/run-launch.js +8 -0
  59. package/dist/store/sqlite/store.js +37 -16
  60. package/dist/store/sqlite/worker.d.ts +2 -0
  61. package/dist/store/sqlite/worker.js +13 -10
  62. package/dist/store/store.d.ts +15 -0
  63. package/dist/store-reads/learning.d.ts +30 -13
  64. package/dist/store-reads/learning.js +125 -51
  65. package/dist/template-eval.js +1 -1
  66. package/dist/templates.d.ts +14 -1
  67. package/dist/templates.js +67 -17
  68. package/dist/tool-gate.d.ts +5 -3
  69. package/dist/tool-gate.js +5 -2
  70. package/dist/tools.d.ts +13 -0
  71. package/dist/tools.js +15 -10
  72. package/dist/trigger-adapter.d.ts +3 -32
  73. package/dist/trigger-email.js +30 -77
  74. package/dist/triggers.d.ts +26 -14
  75. package/dist/triggers.js +99 -76
  76. package/dist/workflow/decision-recovery.js +5 -2
  77. package/dist/workflow/decisions.d.ts +7 -0
  78. package/package.json +9 -9
  79. package/templates/README.md +2 -2
  80. package/dist/console/assets/index-BNhZs-jp.css +0 -1
  81. package/dist/console/assets/index-BQv5aOGB.js +0 -700
@@ -141,7 +141,8 @@ export type PendingApproval = {
141
141
  /** The call's arguments as text, at most ARGS_PREVIEW_BYTES. */
142
142
  args_preview: string;
143
143
  /** What the call does in words, where its tool says (email_send: "Send email to <to>, cc <cc>: <subject>" and the
144
- * text's first 300 characters), redacted as its arguments are. */
144
+ * text's first 300 characters), then why it asks when its setting allows it (ToolEntry.asks), redacted as its
145
+ * arguments are. */
145
146
  summary?: string;
146
147
  requested_at: string;
147
148
  price?: ApprovalPrice;
@@ -149,8 +150,9 @@ export type PendingApproval = {
149
150
  destructive?: true;
150
151
  };
151
152
  export { type DenyFrom, deniedText, denyPlace, NOT_RUN, RAN_UNKNOWN, refusedText, type SettingFrom } from "./refusal-words.js";
152
- /** The refusal of an ask where no one can approve it: a server with accounts off, whose answer route takes no token. */
153
- export declare const noApproverText: (tool: string, ran?: "no" | "unknown") => string;
153
+ /** The refusal of an ask where no one can approve it: a server with accounts off, whose answer route takes no token.
154
+ * `because`: the tool's own reason (ToolEntry.asks) for a call its setting allows, which no setting lifts. */
155
+ export declare const noApproverText: (tool: string, ran?: "no" | "unknown", because?: string) => string;
154
156
  /** The Timeline row of a call that waits for an approval. */
155
157
  export declare const APPROVAL_ROW: "tool_approval_requested";
156
158
  /** A call's arguments shown on its approval, at most this many bytes. */
package/dist/tool-gate.js CHANGED
@@ -329,8 +329,11 @@ export const permissionOf = (name, server, agent = {}, approvals = "ask", effect
329
329
  // The refusal words (SettingFrom, DenyFrom, NOT_RUN, RAN_UNKNOWN, denyPlace, deniedText, refusedText) live in
330
330
  // refusal-words.ts, shared with the runner's loops.
331
331
  export { deniedText, denyPlace, NOT_RUN, RAN_UNKNOWN, refusedText } from "./refusal-words.js";
332
- /** The refusal of an ask where no one can approve it: a server with accounts off, whose answer route takes no token. */
333
- export const noApproverText = (tool, ran = "no") => `${DENIED_OPENING}${tool} needs the owner's approval, and this server has accounts off (AGENTRUN_ACCOUNTS=0), so no one can give it: set the tool to allow or deny in the agent's Tools. ${ran === "no" ? NOT_RUN : RAN_UNKNOWN}`;
332
+ /** The refusal of an ask where no one can approve it: a server with accounts off, whose answer route takes no token.
333
+ * `because`: the tool's own reason (ToolEntry.asks) for a call its setting allows, which no setting lifts. */
334
+ export const noApproverText = (tool, ran = "no", because) => because === undefined
335
+ ? `${DENIED_OPENING}${tool} needs the owner's approval, and this server has accounts off (AGENTRUN_ACCOUNTS=0), so no one can give it: set the tool to allow or deny in the agent's Tools. ${ran === "no" ? NOT_RUN : RAN_UNKNOWN}`
336
+ : `${DENIED_OPENING}${tool} needs the owner's approval for this call (${because}), and this server has accounts off (AGENTRUN_ACCOUNTS=0), so no one can give it. ${ran === "no" ? NOT_RUN : RAN_UNKNOWN}`;
334
337
  /** The Timeline row of a call that waits for an approval. */
335
338
  export const APPROVAL_ROW = "tool_approval_requested";
336
339
  /** A call's arguments shown on its approval, at most this many bytes. */
package/dist/tools.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import "./email/labels.js";
1
2
  import type { TSchema } from "typebox";
2
3
  import { type Extension, type Harness, type ToolRegistration, type Tx } from "@earendil-works/pi-durable";
3
4
  import type { Revision } from "./agent-rows.js";
@@ -158,6 +159,12 @@ export type EffectRun = {
158
159
  ledger?: Ledger;
159
160
  search?: SearchOn;
160
161
  };
162
+ /** What a tool's own ask (ToolEntry.asks) reads: the run's host, and how many calls of a tool the run has run to a good
163
+ * end, from the run's record (its journal), so a pause and a new host count them all. */
164
+ export type AskContext = {
165
+ readonly host: ToolHost;
166
+ ran(tool: string): Promise<number>;
167
+ };
161
168
  export type ToolEntry = {
162
169
  /** One line, for capabilities. */
163
170
  summary: string;
@@ -177,6 +184,12 @@ export type ToolEntry = {
177
184
  /** No agent whose place is a sandbox may name it: it writes the run's work/ from this machine by paths a box's command
178
185
  * could turn through a link (runnable.ts). */
179
186
  runnerOnly?: true;
187
+ /** On the runner, before the intent of a call its setting allows: why this call asks a person anyway, in words (shown
188
+ * on its approval), or nothing. No setting lifts it; where no one can approve, the call is refused in those words. */
189
+ asks?(args: Record<string, unknown>, ctx: AskContext): Promise<string | undefined>;
190
+ /** What a call waiting on approval does, in a person's words (run-view.ts, the pending approval's `summary`): email_send's
191
+ * to whom and what. Undefined where its arguments do not say. */
192
+ approvalSummary?(args: unknown): string | undefined;
180
193
  };
181
194
  /** Where the browser files what it reads: the run's `evidence/`, through its Workspace, so the run's files show it and
182
195
  * the agent can read it back. A text body follows one line of the read's facts; a capture's bytes go beside its facts.
package/dist/tools.js CHANGED
@@ -5,7 +5,9 @@
5
5
  // run's folder or its computer. `bash` and the background tools may be named only by an agent whose place is a box
6
6
  // (runnable.ts).
7
7
  import { blurbOf, isHostTool } from "./tool-list.js";
8
- import { EMAIL_DRAFT, EMAIL_FILE, EMAIL_READ, EMAIL_SEARCH, EMAIL_SEND } from "./email/names.js";
8
+ import { EMAIL_DESCRIPTIONS, EMAIL_DRAFT, EMAIL_FILE, EMAIL_READ, EMAIL_SEARCH, EMAIL_SEND, fileSummary, sendSummary } from "./email/names.js";
9
+ // The email tools' timeline lines (registerLabel), registered as this module loads.
10
+ import "./email/labels.js";
9
11
  import { mcpNameOf } from "./tool-names.js";
10
12
  import { appendFileSync } from "node:fs";
11
13
  import { pathToFileURL } from "node:url";
@@ -82,12 +84,15 @@ const callOnly = (summary, effect) => ({
82
84
  summary, needs: [], nodes: false, callOnly: true, effect,
83
85
  bind: async () => { throw new Error("a call-only tool binds no agent tool"); },
84
86
  });
85
- /** An email tool (email/tools.ts emailEntry), its binding loaded at its first bind. */
86
- const emailTool = (name, summary) => ({
87
- summary,
87
+ /** An email tool, its summary its description (email/names.ts), its binding (email/tools.ts bindEmail) and email_send's
88
+ * own ask (sendAsks) loaded at first use, the mail libraries with them. */
89
+ const emailTool = (name) => ({
90
+ summary: EMAIL_DESCRIPTIONS[name],
88
91
  needs: [],
89
92
  nodes: false,
90
- bind: async (host) => (await import("./email/tools.js")).emailEntry(name, summary).bind(host),
93
+ bind: async (host) => (await import("./email/tools.js")).bindEmail(name, host),
94
+ ...(name === EMAIL_SEND ? { approvalSummary: sendSummary, asks: async (args, ctx) => (await import("./email/tools.js")).sendAsks(args, ctx) } : {}),
95
+ ...(name === EMAIL_FILE ? { approvalSummary: fileSummary } : {}),
91
96
  });
92
97
  /** web_fetch, bound under `name`. */
93
98
  const webFetchEntry = (name) => ({
@@ -594,11 +599,11 @@ export const TOOLS = Object.freeze({
594
599
  },
595
600
  // The email tools (email/tools.ts) on the server's one email account (Settings → Email), every harness's as web_fetch is;
596
601
  // the mail libraries load at the first bind.
597
- [EMAIL_SEARCH]: emailTool(EMAIL_SEARCH, "Search the server's email account: { from?, to?, subject?, text?, since?, unread?, mailbox?: \"INBOX\", limit?: 20 (max 50) } -> { messages: [{ message_id, from, to, subject, date, snippet, unread, attachments }] }, newest first. On a run an email started, its thread alone unless the agent's setting says scope: \"mailbox\"."),
598
- [EMAIL_READ]: emailTool(EMAIL_READ, "Read an email of the server's account by message_id, or its whole thread (thread: true, by References and In-Reply-To, oldest first): { message_id, thread? } -> { messages: [{ from, from_name, to, cc, subject, date, message_id, in_reply_to, text, attachments, references }] }. Reads leave mail unread."),
599
- [EMAIL_DRAFT]: emailTool(EMAIL_DRAFT, "Save an email to the account's Drafts, sending nothing: { to, cc?, subject, text, in_reply_to? } -> { saved: true, mailbox, message_id }; in_reply_to threads it as a reply."),
600
- [EMAIL_SEND]: emailTool(EMAIL_SEND, "Send an email from the server's account over SMTP: { to, cc?, subject, text, in_reply_to? } -> { sent: true, message_id }; in_reply_to threads it as a reply, and a copy is filed in Sent. Asks the person first by default."),
601
- [EMAIL_FILE]: emailTool(EMAIL_FILE, "File an email of the server's account by message_id under to: { message_id, to, archive? } -> { filed: true, message_id, to, archived, subject, note? }. On Gmail it adds the label and the message stays in the inbox (archive: true takes it out too); elsewhere it moves the message out of the inbox to the folder, its note saying \"moved out of the inbox to <to>\" (an explicit archive: false is refused). Folders and labels are made if missing; the trash and junk folders are refused: it never deletes mail. On a run an email started, its thread alone unless the agent's setting says scope: \"mailbox\"."),
602
+ [EMAIL_SEARCH]: emailTool(EMAIL_SEARCH),
603
+ [EMAIL_READ]: emailTool(EMAIL_READ),
604
+ [EMAIL_DRAFT]: emailTool(EMAIL_DRAFT),
605
+ [EMAIL_SEND]: emailTool(EMAIL_SEND),
606
+ [EMAIL_FILE]: emailTool(EMAIL_FILE),
602
607
  browser: browserTool,
603
608
  // A pi run's subagent (runner/subagent.ts): a native tool of the run's root agent, bound by the runner's pi spec
604
609
  // (adapter-run-spec.ts), never by this table; not a host tool (tool-list.ts `replay`), so another harness refuses it.
@@ -79,43 +79,14 @@ export type TriggerAdapter = {
79
79
  /** For a clock source that polls (the email trigger): what it finds when its time comes, read from outside the server.
80
80
  * The engine fires each event it returns through the path a pushed event takes (`takes`, `concurrent`,
81
81
  * max_active_runs, the day-kept keys, a run per event), records no `missed` row for a time it was not there for, and
82
- * keeps the poll's cursor once its firings are recorded. */
82
+ * keeps the poll's cursor once its firings are recorded. A poll with no cursor is where its trigger starts watching:
83
+ * the engine polls at once when the trigger is made, turned on again (its cursor and last check forgotten first) or its
84
+ * source edited (its cursor kept: a poll whose cursor was read elsewhere starts over itself). */
83
85
  poll?(source: Source, ctx: PollContext): Promise<PollResult>;
84
- /** For a source that polls: where its trigger starts watching, taken when the trigger is made, when an edit changes one
85
- * of its source's `on` fields and when it is turned on again; never at its first poll. An edit of any other field keeps
86
- * the cursor. A start not taken (the source unreachable, or slower than the engine waits) leaves no cursor: the first
87
- * poll that reads the source takes it, and says so. */
88
- start?: Start;
89
86
  /** A run's title after its trigger's name, from what its source says of the firing (its attrs): an email's sender and
90
87
  * subject. Default: the event and action the attrs name. */
91
88
  title?(attrs: Record<string, string>): string | undefined;
92
89
  };
93
- /** Why a start is taken: the trigger was made, an edit changed where it reads, or it was turned on again. */
94
- export type StartWhy = "created" | "edited" | "enabled";
95
- /** What a start is given: its trigger, why, and the source's credentials, read now (as a poll's). */
96
- export type StartContext = {
97
- trigger: string;
98
- why: StartWhy;
99
- credentials(): Promise<unknown>;
100
- };
101
- /** What a start found: `check`, said on the trigger as its last check (a refusal here never counts toward turning it
102
- * off); `note`, the history line it writes; `cursor`, the settings it starts from, none when it could not read the
103
- * source. */
104
- export type StartResult = {
105
- check: {
106
- ok: boolean;
107
- message: string;
108
- };
109
- note: string;
110
- cursor?: Record<string, string>;
111
- };
112
- export type Start = {
113
- /** The source's fields an edit of which takes a new start. */
114
- on: readonly string[];
115
- take(source: Source, ctx: StartContext): Promise<StartResult>;
116
- /** The words of a start the engine stopped waiting for. */
117
- unchecked(source: Source, why: StartWhy): string;
118
- };
119
90
  /** What a poll is given: its trigger's own settings (its cursor, public, as the adapter's `settings` names them) and the
120
91
  * source's credentials, read now (TriggerDeps.credentials: the email account, opened). */
121
92
  export type PollContext = {
@@ -3,16 +3,18 @@
3
3
  // came since its cursor is one firing through the path a pushed event takes (triggers.ts): its accept filter, a run per
4
4
  // message, max_active_runs, its key kept for its day. The cursor is the account it was read on (its user, IMAP host and
5
5
  // port: nothing secret), the mailbox, its UIDVALIDITY and the last UID read, in the trigger's own settings, kept only once
6
- // the poll's firings are recorded, so a restart goes on from it. Its start
7
- // (the engine's start hook) is taken when the trigger is made, when an edit changes its mailbox or account, and when it
8
- // is turned on again: mail from before then starts no run, and that is said; any other edit keeps the cursor. A start
9
- // that can't sign in is taken at the first poll that does, and said; a UIDVALIDITY the server changed the same, and so
10
- // another account saved in its place (PUT /v2/settings/email). A message's key is its Message-ID (else UIDVALIDITY:UID), so
6
+ // the poll's firings are recorded, so a restart goes on from it. A poll with no cursor, or one read on another mailbox
7
+ // or account, starts watching: the mailbox's end now, mail from before it starting no run, and that is said. The engine
8
+ // polls at once when the trigger is made, turned on again (its cursor forgotten) or edited (its cursor kept), so it
9
+ // watches from then; one that couldn't check until a later poll says so then. A UIDVALIDITY the server changed starts
10
+ // over the same, as does another account saved in its place (PUT /v2/settings/email). A message's key is its Message-ID (else UIDVALIDITY:UID), so
11
11
  // one seen twice fires once; its attrs say where it was found (mailbox, UIDVALIDITY, UID), which a run's thread is read
12
12
  // from (email/tools.ts). At most POLL_TAKES messages a poll, oldest first. A
13
13
  // message this server sent (X-AgentRun-Sent, email/tools.ts email_send) is left, and said. An unreachable server is said
14
14
  // on the trigger and tried at the next time; a refused sign-in counts (the engine turns the trigger off at the third).
15
15
  import { DEFAULT_ACCOUNT, NO_ACCOUNT } from "./email/account.js";
16
+ import { fittedPayload } from "./email/answer.js";
17
+ import { messages } from "./email/names.js";
16
18
  import { ACCEPT_SCHEMA, acceptOf, acceptRefusal } from "./trigger-accept.js";
17
19
  import { closedSchema, PAYLOAD_KEPT_BYTES, unknownSourceFields } from "./trigger-adapter.js";
18
20
  import { MAX_EVERY_S, MIN_EVERY_S } from "./trigger-schedule.js";
@@ -20,8 +22,9 @@ import { MAX_EVERY_S, MIN_EVERY_S } from "./trigger-schedule.js";
20
22
  export const POLL_TAKES = 20;
21
23
  /** The one event an email trigger's accept names. */
22
24
  const EVENT = "message";
23
- /** The trigger's own settings: its cursor and its last check, no secret (public). */
25
+ /** The trigger's own settings: its cursor and its last check (the engine's), no secret (public). */
24
26
  const CURSOR = "cursor";
27
+ const LAST_CHECK = "last_check";
25
28
  /** Which account a cursor was read on: its user, IMAP host and port, nothing secret (the cursor is a public setting). */
26
29
  const accountKey = (account) => `${account.user.trim().toLowerCase()}@${account.imap.host.toLowerCase()}:${account.imap.port}`;
27
30
  /** The source's own fields, checked: each issue through `bad`. Undefined when one does not read. */
@@ -61,45 +64,10 @@ function cursorOf(text) {
61
64
  }
62
65
  }
63
66
  const kept = (cursor) => ({ [CURSOR]: JSON.stringify(cursor) });
64
- /** Whether `payload`'s JSON is within the engine's bound, measured as the engine does: bytes of UTF-8, escapes counted. */
65
- const fits = (payload) => Buffer.byteLength(JSON.stringify(payload), "utf8") <= PAYLOAD_KEPT_BYTES;
66
- /** The first `n` characters (code points) of `text`, ending in `…` when cut. */
67
- const clipped = (text, n) => (typeof text === "string" && [...text].length > n ? `${[...text].slice(0, n).join("")}…` : text);
68
- /** A message's payload whole, its JSON within PAYLOAD_KEPT_BYTES, so the engine never cuts it mid-string. When it is over,
69
- * the text is cut, the longest prefix that fits found by halving (a character's start, escapes counted), said in it and
70
- * marked `text_truncated: true`; when its other fields alone are over, the subject, the names and the lists are cut too,
71
- * shorter until it fits. */
72
- function fittedPayload(whole) {
73
- if (fits(whole))
74
- return whole;
75
- const text = typeof whole.text === "string" ? whole.text : "";
76
- // No more characters than the bound has bytes can fit: the halving reads at most that many.
77
- const chars = [...text.slice(0, 2 * PAYLOAD_KEPT_BYTES)].slice(0, PAYLOAD_KEPT_BYTES);
78
- const said = `\n[cut: the message's text was ${Buffer.byteLength(text, "utf8")} bytes]`;
79
- let rest = whole;
80
- const withText = (n) => ({ ...rest, text: `${chars.slice(0, n).join("")}${said}`, text_truncated: true });
81
- for (let room = 1000; !fits(withText(0)); room = Math.floor(room / 2)) {
82
- const list = (value) => (Array.isArray(value) ? value.slice(0, Math.max(1, Math.floor(room / 20))).map((one) => (typeof one === "string" ? clipped(one, Math.min(320, room)) : one)) : value);
83
- const attachments = Array.isArray(whole.attachments) ? whole.attachments.slice(0, Math.max(0, Math.floor(room / 20))).map((a) => ({ ...a, name: clipped(a?.name, Math.min(200, room)) })) : whole.attachments;
84
- rest = { ...whole, from: clipped(whole.from, Math.min(998, room)), message_id: clipped(whole.message_id, Math.min(998, room)), in_reply_to: clipped(whole.in_reply_to, Math.min(998, room)), subject: clipped(whole.subject, room), from_name: clipped(whole.from_name, Math.min(320, room)), to: list(whole.to), cc: list(whole.cc), attachments };
85
- if (room === 0)
86
- break;
87
- }
88
- let lo = 0;
89
- let hi = chars.length;
90
- while (lo < hi) {
91
- const mid = Math.ceil((lo + hi) / 2);
92
- if (fits(withText(mid)))
93
- lo = mid;
94
- else
95
- hi = mid - 1;
96
- }
97
- return withText(lo);
98
- }
99
67
  /** A message as the event its trigger fires: its payload (JSON, untrusted, whole within the engine's bound), its attrs
100
68
  * (who, what, and where it was found: the run's thread is read from there), keyed by its Message-ID. */
101
69
  function eventOf(m, cursor, payloadOf) {
102
- const payload = fittedPayload(payloadOf(m));
70
+ const payload = fittedPayload(payloadOf(m), PAYLOAD_KEPT_BYTES);
103
71
  return {
104
72
  key: m.message_id ?? `${cursor.uidvalidity}:${m.uid}`,
105
73
  text: JSON.stringify(payload),
@@ -110,8 +78,6 @@ function eventOf(m, cursor, payloadOf) {
110
78
  ...(m.sent_here !== undefined ? { left: "Left: this server sent that message (it carries X-AgentRun-Sent), so it starts no run." } : {}),
111
79
  };
112
80
  }
113
- /** `n` messages, in words. */
114
- const messages = (n) => `${n} message${n === 1 ? "" : "s"}`;
115
81
  /** The cursor at the end of `source`'s mailbox on `account` as it is now, and how many messages it holds: where watching
116
82
  * starts. */
117
83
  async function endOf(session, source, account) {
@@ -121,33 +87,30 @@ async function endOf(session, source, account) {
121
87
  const uid = box.uidNext > 0 ? box.uidNext - 1 : Math.max(0, ...(await session.uids({ all: true })));
122
88
  return { cursor: { account: accountKey(account), mailbox: path, uidvalidity: box.uidValidity, uid }, exists: box.exists };
123
89
  }
124
- /** The history line of a start taken for `why`, with `exists` messages left. */
125
- const watching = (source, exists, why) => why === "enabled"
126
- ? `Watching ${source.mailbox} from now, on again: the ${messages(exists)} already there, any that came while it was off among them, won't start runs.`
90
+ /** The history line of a start, with `exists` messages left: said once, by the poll that starts watching, which says so
91
+ * when the checks before it failed (`failedBefore`). */
92
+ const watching = (source, exists, failedBefore) => failedBefore
93
+ ? `Couldn't check ${source.mailbox} until now; watching from now: the ${messages(exists)} there won't start runs.`
127
94
  : `Watching ${source.mailbox} from now: the ${messages(exists)} already there won't start runs.`;
128
- /** The history line of a start that could not read the mailbox. */
129
- const unchecked = (source, why) => `Couldn't check ${String(source.mailbox ?? "INBOX")} when it was ${why === "created" ? "created" : why === "edited" ? "changed" : "turned on again"}; watching from the first check that signs in.`;
130
- /** `source`'s start, on `account`: the cursor at its mailbox's end now. */
131
- async function start(source, account, why) {
132
- const { MailError, withImap } = await import("./email/mail.js");
133
- return withImap(account, async (session) => {
134
- const end = await endOf(session, source, account);
135
- return { check: { ok: true, message: `Watching ${source.mailbox}.` }, note: watching(source, end.exists, why), cursor: kept(end.cursor) };
136
- }).catch((error) => {
137
- const failure = error instanceof MailError ? error : new MailError("failed", String(error?.message ?? error));
138
- return { check: { ok: false, message: failure.message }, note: unchecked(source, why) };
139
- });
140
- }
141
- /** One poll of `source`'s mailbox from `cursor`, on `account`. The mail libraries load at the first poll, never with the
142
- * registry (every process that reads the sources). */
143
- async function poll(source, account, cursor) {
95
+ /** Whether the trigger's last check (the engine's last_check setting) failed. */
96
+ const lastFailed = (text) => {
97
+ try {
98
+ return text !== undefined && JSON.parse(text).ok === false;
99
+ }
100
+ catch {
101
+ return false;
102
+ }
103
+ };
104
+ /** One poll of `source`'s mailbox from `cursor`, on `account`; `failedBefore`, its last check failed. The mail libraries
105
+ * load at the first poll, never with the registry (every process that reads the sources). */
106
+ async function poll(source, account, cursor, failedBefore) {
144
107
  const { MailError, payloadOf, READ_BYTES, withImap } = await import("./email/mail.js");
145
108
  return withImap(account, async (session) => {
146
109
  const end = await endOf(session, source, account);
147
110
  const path = end.cursor.mailbox;
148
- // No start yet (one that could not sign in, or a cursor kept before starts were taken): this check takes it.
111
+ // No cursor (made, turned on again, or no check signed in yet), or one on another mailbox (an edit): it starts here.
149
112
  if (!cursor || cursor.mailbox !== path)
150
- return { check: { ok: true, message: `Watching ${source.mailbox}.` }, note: watching(source, end.exists, "created"), cursor: kept(end.cursor) };
113
+ return { check: { ok: true, message: `Watching ${source.mailbox}.` }, note: watching(source, end.exists, failedBefore), cursor: kept(end.cursor) };
151
114
  // Another account saved in its place (or a cursor that names none): its UIDs are another mailbox's, so it starts over.
152
115
  if (cursor.account !== end.cursor.account) {
153
116
  return { check: { ok: true, message: `Watching ${source.mailbox} again: the email account changed.` }, note: `The email account changed: watching ${source.mailbox} from now; the ${messages(end.exists)} there won't start runs.`, cursor: kept(end.cursor) };
@@ -177,7 +140,7 @@ export const email = {
177
140
  owner: false,
178
141
  // Each message is its sender's: one run's answer (to alice) is never handed to the next (bob's).
179
142
  previousResult: false,
180
- settings: { scope: "trigger", fields: { [CURSOR]: { public: true }, last_check: { public: true } } },
143
+ settings: { scope: "trigger", fields: { [CURSOR]: { public: true }, [LAST_CHECK]: { public: true } } },
181
144
  describe: `{kind: "email", account?: "${DEFAULT_ACCOUNT}", mailbox?: "INBOX", every_s?: ${MIN_EVERY_S}, accept?: [{event: "${EVENT}", where?}]}`,
182
145
  fires: "each new message in the server's email account's mailbox (`email`), read every every_s seconds, that its `accept` takes",
183
146
  firedBy: "`email`: a message found in the email account's mailbox, its key from the trigger and the message's Message-ID (else its UIDVALIDITY and UID).",
@@ -212,17 +175,7 @@ export const email = {
212
175
  const account = (await ctx.credentials());
213
176
  if (!account)
214
177
  return { check: { ok: false, message: NO_ACCOUNT } };
215
- return poll(source, account, cursorOf(ctx.setting(CURSOR)));
216
- },
217
- start: {
218
- on: ["account", "mailbox"],
219
- async take(source, ctx) {
220
- const account = (await ctx.credentials());
221
- if (!account)
222
- return { check: { ok: false, message: NO_ACCOUNT }, note: unchecked(source, ctx.why) };
223
- return start(source, account, ctx.why);
224
- },
225
- unchecked,
178
+ return poll(source, account, cursorOf(ctx.setting(CURSOR)), lastFailed(ctx.setting(LAST_CHECK)));
226
179
  },
227
180
  title: (attrs) => `${attrs.from ?? ""} — ${attrs.subject ?? ""}`,
228
181
  };
@@ -1,7 +1,7 @@
1
1
  import { type MessageOrigin } from "./timeline/index.js";
2
2
  import { ApiError, type InputIssue } from "./errors.js";
3
3
  import { type FiringRow, type Store } from "./store/index.js";
4
- import { PAYLOAD_KEPT_BYTES, type Source, type TriggerAdapter } from "./trigger-adapter.js";
4
+ import { type Source, type TriggerAdapter } from "./trigger-adapter.js";
5
5
  import { type Json } from "./validate.js";
6
6
  export { MAX_EVERY_S, MIN_EVERY_S } from "./trigger-schedule.js";
7
7
  /** The firings each trigger keeps in its history, newest first; a firing still due is never dropped, nor a failure whose
@@ -15,7 +15,6 @@ export declare const SOURCE_KINDS: readonly string[];
15
15
  export declare const TARGET_KINDS: readonly ["start_run", "message_run"];
16
16
  export declare const FIRING_STATUSES: readonly ["due", "started", "sent", "skipped", "failed", "missed"];
17
17
  /** The most of a webhook's payload a firing passes on: the rest is cut, at a character's start (trigger-adapter.ts). */
18
- export { PAYLOAD_KEPT_BYTES };
19
18
  /** How late a missed time may be and still fire once, by default: an hour. */
20
19
  export declare const CATCHUP_WINDOW_S = 3600;
21
20
  /** The failed tries in a row that turn a trigger off. */
@@ -34,9 +33,9 @@ export declare const MAX_ACTIVE_RUNS = 100;
34
33
  export declare const LAST_CHECK = "last_check";
35
34
  /** The sign-ins a polled source's server refuses in a row that turn its trigger off. */
36
35
  export declare const REFUSALS_TO_STOP = 3;
37
- /** How long a trigger's create, edit or turn-on waits for its source's start (trigger-adapter.ts `start`): one not taken
38
- * by then is taken at its first check. */
39
- export declare const START_WAIT_MS = 10000;
36
+ /** How long a create or a turn-on of a polled source waits for its first poll (where it starts watching) before it
37
+ * answers: past it, the answer goes out and the poll carries on. */
38
+ export declare const FIRST_POLL_WAIT_MS = 10000;
40
39
  /** What a source's sender keeps of a trigger, set up from here (composio-triggers.ts: Composio's trigger instance): made
41
40
  * before the trigger is kept and undone when it is not, kept in step as the owner turns the trigger on and off (and as
42
41
  * the server turns it off itself: offThere), removed after it. What it could not do there is answered beside the change (`said`, by its source's name: `{composio: {done:
@@ -181,10 +180,17 @@ export declare class Triggers {
181
180
  private waiting;
182
181
  /** The triggers whose day-kept keys are at their cap, said once until they are under it again. */
183
182
  private readonly seenFull;
184
- /** The polled triggers whose poll is running: one at a time each. */
183
+ /** The polled triggers whose poll is running, one at a time each: true when it is a kick's (kick), which a time come
184
+ * meanwhile waits for (the first poll, the watching start, is never the reason a time is lost); false for a time's own,
185
+ * which a time come meanwhile skips (a server slower than every_s is never polled back to back). */
185
186
  private readonly polling;
186
- /** Each polled trigger's count of starts taken (takeStart): a poll or a start that sees it changed keeps nothing. */
187
- private readonly starts;
187
+ /** The polled triggers kicked (kick), or whose time came during a kick's poll, while their poll ran: polled again once
188
+ * it is done, as a kick's poll (true) when a kick asked for it, else as a time's. */
189
+ private readonly pollAgain;
190
+ /** Who waits on the poll after the one running (a kick made while it ran): told when that one is done. */
191
+ private readonly pollWaiters;
192
+ /** Each polled trigger's count of turn-ons: a poll that sees it changed keeps nothing, its cursor read before. */
193
+ private readonly restarts;
188
194
  private closed;
189
195
  constructor(deps: TriggerDeps);
190
196
  /** At the server's start: every enabled trigger whose source no longer reads turned off, each failure's trigger.failed
@@ -433,10 +439,6 @@ export declare class Triggers {
433
439
  } | null | undefined;
434
440
  hook_url?: string | undefined;
435
441
  }>;
436
- /** Trigger `trigger`'s polled source started from now (its adapter's start, waited on at most START_WAIT_MS): its old
437
- * cursor and last check forgotten, the start's cursor and check kept (no refusal counted), its note a skipped history
438
- * line. A start not taken leaves no cursor, so its first poll takes it. Never throws: the create or edit stands. */
439
- private takeStart;
440
442
  /** The trigger deleted, and what its sender keeps of it removed after (said, when it could not be: the delete holds). */
441
443
  remove(id: string): Promise<Json | undefined>;
442
444
  /** Run now: one firing per Idempotency-Key, driven before the answer. `created` false: the key's firing, as it stands. */
@@ -458,13 +460,23 @@ export declare class Triggers {
458
460
  * turned off. */
459
461
  private advance;
460
462
  /** A polled source's time come: its next time moved on from the latest that has come (a time it was not there for is no
461
- * `missed` row: what came meanwhile is still there to read), then its poll, after none still running for it, off the
462
- * timer, so a slow server never holds the other triggers. */
463
+ * `missed` row: what came meanwhile is still there to read), then its poll, off the timer, so a slow server never
464
+ * holds the other triggers. With one still running for it: once that one is done when it is a kick's (pollDone),
465
+ * else skipped. */
463
466
  private pollDue;
467
+ /** A poll of `trigger` now, answered once the poll that answers it is done: its own, or, when an edit of its source
468
+ * drops its result (polled), the one after it, which it asks for at once; when one is running, the one after that. */
469
+ private kick;
470
+ /** `trigger`'s first poll (made, or turned on again) kicked and waited on, FIRST_POLL_WAIT_MS at most. */
471
+ private firstPoll;
472
+ /** `id`'s poll done: a kick, or a time come during a kick's poll, polls now, once however many came, the trigger read
473
+ * again (on, and as it is now). A time come during this one skips, as during a time's own. */
474
+ private pollDone;
464
475
  /** One poll of `trigger`'s source for its time `nominalAt`: each event it found recorded in order (its note a skipped
465
476
  * history line; one it leaves, skipped and said; one its accept does not take, an ignored row kept for its day; any
466
477
  * other due, and driven), its cursor kept once they are, then its last check, and at the REFUSALS_TO_STOPth refused
467
478
  * sign-in in a row the trigger turned off. A poll that throws is a failed check. */
479
+ /** False when an edit of its source while it polled dropped what it found (the edit's poll comes after it); else true. */
468
480
  private polled;
469
481
  /** A firing taken from due to its end: skipped when its trigger's last run is active, else its run started (or its
470
482
  * message sent). A failed try keeps it due under the backoff table, or ends it failed. Each step reads the trigger and