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

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 (199) hide show
  1. package/CHANGELOG.md +130 -0
  2. package/NOTICE +2 -0
  3. package/README.md +149 -21
  4. package/dist/agent-rows.d.ts +1 -1
  5. package/dist/agents-store.js +3 -1
  6. package/dist/api-only.d.ts +3 -1
  7. package/dist/api-only.js +4 -2
  8. package/dist/api-token.d.ts +30 -0
  9. package/dist/api-token.js +89 -0
  10. package/dist/calendar/address.d.ts +49 -0
  11. package/dist/calendar/address.js +153 -0
  12. package/dist/calendar/fetch.d.ts +24 -0
  13. package/dist/calendar/fetch.js +146 -0
  14. package/dist/calendar/ics-faux.d.ts +39 -0
  15. package/dist/calendar/ics-faux.js +236 -0
  16. package/dist/calendar/labels.d.ts +3 -0
  17. package/dist/calendar/labels.js +61 -0
  18. package/dist/calendar/names.d.ts +52 -0
  19. package/dist/calendar/names.js +54 -0
  20. package/dist/calendar/parse.d.ts +108 -0
  21. package/dist/calendar/parse.js +625 -0
  22. package/dist/calendar/routes.d.ts +17 -0
  23. package/dist/calendar/routes.js +81 -0
  24. package/dist/calendar/tools.d.ts +23 -0
  25. package/dist/calendar/tools.js +124 -0
  26. package/dist/cli.js +22 -6
  27. package/dist/composio-made.d.ts +54 -0
  28. package/dist/composio-made.js +83 -0
  29. package/dist/composio-preset.d.ts +16 -8
  30. package/dist/composio-preset.js +106 -43
  31. package/dist/composio-triggers.d.ts +7 -2
  32. package/dist/composio-triggers.js +13 -7
  33. package/dist/computer-attach.d.ts +29 -11
  34. package/dist/computer-attach.js +141 -47
  35. package/dist/computer-keys.d.ts +4 -0
  36. package/dist/computer-keys.js +5 -0
  37. package/dist/computer-record.d.ts +55 -0
  38. package/dist/computer-record.js +315 -0
  39. package/dist/computer-setting.d.ts +1 -0
  40. package/dist/computer-setting.js +15 -2
  41. package/dist/computers.d.ts +11 -1
  42. package/dist/computers.js +23 -26
  43. package/dist/console/assets/{index-B8Zn1Iqn.css → index-C3gNPz58.css} +1 -1
  44. package/dist/console/assets/index-DYJ_wj27.js +711 -0
  45. package/dist/console/index.html +2 -2
  46. package/dist/decisions.js +9 -2
  47. package/dist/eval-feed.d.ts +26 -0
  48. package/dist/eval-feed.js +72 -0
  49. package/dist/eval-mailbox.d.ts +4 -1
  50. package/dist/eval-mailbox.js +11 -3
  51. package/dist/exa-keyless.d.ts +1 -1
  52. package/dist/exa-keyless.js +1 -1
  53. package/dist/feed/feed-faux.d.ts +62 -0
  54. package/dist/feed/feed-faux.js +123 -0
  55. package/dist/feed/fetch.d.ts +41 -0
  56. package/dist/feed/fetch.js +128 -0
  57. package/dist/feed/parse.d.ts +42 -0
  58. package/dist/feed/parse.js +291 -0
  59. package/dist/feed/pointer.d.ts +2 -0
  60. package/dist/feed/pointer.js +17 -0
  61. package/dist/file-types.js +1 -0
  62. package/dist/host-command.d.ts +3 -0
  63. package/dist/host-command.js +18 -0
  64. package/dist/host.d.ts +3 -0
  65. package/dist/host.js +3 -0
  66. package/dist/learn/check.d.ts +17 -1
  67. package/dist/learn/check.js +240 -5
  68. package/dist/learn/compile.d.ts +48 -27
  69. package/dist/learn/compile.js +134 -101
  70. package/dist/learn/promote.d.ts +61 -5
  71. package/dist/learn/promote.js +12 -2
  72. package/dist/learned-nodes.d.ts +21 -4
  73. package/dist/learned-nodes.js +21 -8
  74. package/dist/learned-workflow.d.ts +3 -3
  75. package/dist/learned-workflow.js +14 -5
  76. package/dist/learning-setting.d.ts +23 -0
  77. package/dist/learning-setting.js +51 -0
  78. package/dist/learning-words.d.ts +3 -0
  79. package/dist/learning-words.js +3 -0
  80. package/dist/learning.d.ts +3 -2
  81. package/dist/learning.js +5 -3
  82. package/dist/mcp-oauth.d.ts +23 -1
  83. package/dist/mcp-oauth.js +46 -5
  84. package/dist/mcp-pin-first.d.ts +4 -2
  85. package/dist/mcp-pin-first.js +4 -3
  86. package/dist/mcp-private-hosts.d.ts +13 -0
  87. package/dist/mcp-private-hosts.js +16 -0
  88. package/dist/mcp-servers-store.d.ts +58 -5
  89. package/dist/mcp-servers-store.js +136 -17
  90. package/dist/mcp.d.ts +2 -2
  91. package/dist/mcp.js +2 -2
  92. package/dist/observation/http.d.ts +4 -1
  93. package/dist/observation/http.js +5 -4
  94. package/dist/openapi.d.ts +1 -0
  95. package/dist/openapi.js +151 -21
  96. package/dist/print.d.ts +6 -3
  97. package/dist/print.js +4 -2
  98. package/dist/run-files.d.ts +6 -2
  99. package/dist/run-files.js +29 -7
  100. package/dist/run-labels.d.ts +23 -0
  101. package/dist/run-labels.js +79 -0
  102. package/dist/run-learning-served.d.ts +1 -1
  103. package/dist/run-reads-over-store.d.ts +5 -1
  104. package/dist/run-reads-over-store.js +8 -4
  105. package/dist/run-recordings.d.ts +20 -0
  106. package/dist/run-recordings.js +133 -0
  107. package/dist/run-secrets.js +12 -4
  108. package/dist/runner/adapter-loop.d.ts +1 -1
  109. package/dist/runner/adapter-loop.js +94 -16
  110. package/dist/runner/adapter-run-spec.d.ts +19 -0
  111. package/dist/runner/adapter-run-spec.js +57 -36
  112. package/dist/runner/beside.d.ts +6 -3
  113. package/dist/runner/beside.js +9 -7
  114. package/dist/runner/cli-run-spec.js +41 -32
  115. package/dist/runner/conformance/harness.js +69 -14
  116. package/dist/runner/conformance/subject.d.ts +4 -1
  117. package/dist/runner/feedback-round.d.ts +9 -25
  118. package/dist/runner/feedback-round.js +22 -40
  119. package/dist/runner/learning-end.d.ts +17 -7
  120. package/dist/runner/learning-end.js +79 -53
  121. package/dist/runner/main.d.ts +12 -1
  122. package/dist/runner/main.js +31 -4
  123. package/dist/runner/mcp-claim.d.ts +3 -0
  124. package/dist/runner/mcp-claim.js +1 -1
  125. package/dist/runner/mcp-run.d.ts +6 -2
  126. package/dist/runner/mcp-run.js +5 -3
  127. package/dist/runner/model-route.d.ts +4 -2
  128. package/dist/runner/model-route.js +8 -8
  129. package/dist/runner/promotion.d.ts +44 -4
  130. package/dist/runner/promotion.js +323 -21
  131. package/dist/runner/reflect-hook.d.ts +5 -0
  132. package/dist/runner/reflect-hook.js +22 -14
  133. package/dist/runner/store-secrets.js +3 -1
  134. package/dist/runner/workflow-first.d.ts +6 -11
  135. package/dist/runner/workflow-first.js +16 -20
  136. package/dist/runs-over-store.d.ts +1 -1
  137. package/dist/runs-over-store.js +5 -2
  138. package/dist/sdk/runs.d.ts +7 -1
  139. package/dist/sdk/runs.js +21 -7
  140. package/dist/secret-cut.js +3 -1
  141. package/dist/secrets.js +5 -3
  142. package/dist/server.d.ts +31 -5
  143. package/dist/server.js +240 -61
  144. package/dist/store/agent-body.d.ts +5 -3
  145. package/dist/store/agent-body.js +14 -10
  146. package/dist/store/dialect.d.ts +3 -0
  147. package/dist/store/dialect.js +1 -0
  148. package/dist/store/index.d.ts +1 -1
  149. package/dist/store/postgres/dialect.js +1 -0
  150. package/dist/store/postgres/migrations/0015_run_labels.sql +5 -0
  151. package/dist/store/postgres/migrations/0016_minted_tokens.sql +21 -0
  152. package/dist/store/schema.d.ts +9 -0
  153. package/dist/store/schema.js +26 -2
  154. package/dist/store/sqlite/connection.js +11 -3
  155. package/dist/store/sqlite/run-patch.d.ts +2 -1
  156. package/dist/store/sqlite/run-patch.js +3 -2
  157. package/dist/store/sqlite/store.js +64 -10
  158. package/dist/store/store.d.ts +38 -1
  159. package/dist/store-reads/journal.js +2 -1
  160. package/dist/store-reads/learning.d.ts +1 -1
  161. package/dist/store-reads/learning.js +6 -1
  162. package/dist/store-reads/loop.d.ts +1 -0
  163. package/dist/store-reads/loop.js +14 -4
  164. package/dist/store-reads/runs.d.ts +4 -3
  165. package/dist/store-reads/runs.js +3 -2
  166. package/dist/store-view.d.ts +5 -0
  167. package/dist/store-view.js +8 -2
  168. package/dist/template-eval.d.ts +11 -0
  169. package/dist/template-eval.js +177 -52
  170. package/dist/templates.d.ts +13 -1
  171. package/dist/templates.js +89 -18
  172. package/dist/timeline/computer.js +2 -1
  173. package/dist/timeline/origin.d.ts +1 -1
  174. package/dist/timeline/origin.js +2 -2
  175. package/dist/tool-list.js +1 -0
  176. package/dist/tools.d.ts +7 -0
  177. package/dist/tools.js +11 -0
  178. package/dist/trigger-adapter.d.ts +9 -4
  179. package/dist/trigger-adapters.js +2 -1
  180. package/dist/trigger-feed.d.ts +12 -0
  181. package/dist/trigger-feed.js +420 -0
  182. package/dist/triggers.d.ts +2 -1
  183. package/dist/triggers.js +23 -5
  184. package/dist/validate.js +7 -2
  185. package/dist/webhooks.js +9 -5
  186. package/dist/workspace/computer-deps.d.ts +5 -1
  187. package/dist/workspace/computer-deps.js +2 -2
  188. package/dist/workspace/computer-for-claim.d.ts +7 -0
  189. package/dist/workspace/computer-for-claim.js +12 -2
  190. package/dist/workspace/index.d.ts +1 -0
  191. package/dist/workspace/index.js +2 -0
  192. package/dist/workspace/paths.d.ts +4 -0
  193. package/dist/workspace/paths.js +9 -0
  194. package/dist/workspace/resolve-computer.d.ts +35 -4
  195. package/dist/workspace/resolve-computer.js +47 -9
  196. package/launcher/agentrun-serve +34 -22
  197. package/package.json +11 -9
  198. package/templates/README.md +38 -4
  199. package/dist/console/assets/index-Jbxjcmdp.js +0 -705
package/dist/api-only.js CHANGED
@@ -2,9 +2,11 @@
2
2
  export const API_ONLY_ENV = "AGENTRUN_API_ONLY";
3
3
  /** The routes (server.ts ROUTES, by name) an API-only server serves: a run's launch, read, list, timeline, messages,
4
4
  * stop, cancel, cap raise and grade; its files and the uploads a launch names; an agent's Archil disk, read and removed (the
5
- * agent layer of a run's disk, archil-routes.ts); capabilities, health and usage. */
5
+ * agent layer of a run's disk, archil-routes.ts); capabilities, health and usage; and a run's hosted machine that dials
6
+ * fetching this server's computerd with its own token (computer-attach.ts), as it dials the attach socket, which the
7
+ * upgrade takes for such a machine alone (a paired computer is the console's). */
6
8
  export const API_ONLY_ROUTES = new Set([
7
- "createRun", "createInlineRun",
9
+ "createRun", "createInlineRun", "getComputerDaemon",
8
10
  "getAgentArchil", "deleteAgentArchil",
9
11
  "getRun", "listRuns", "listAllRuns", "getTimeline",
10
12
  "sendMessage", "stopRun", "cancelRun", "raiseRunCap", "gradeRun",
@@ -0,0 +1,30 @@
1
+ /** The variable that holds the token list. A secret, as AGENTRUN_TOKEN is. */
2
+ export declare const TOKENS_ENV = "AGENTRUN_TOKENS";
3
+ /** The id of the token AGENTRUN_TOKEN (or DIR/.token) gives. */
4
+ export declare const DEFAULT_TOKEN_ID = "default";
5
+ /** One API token: `id` names it in log lines and the banner; `token` is the secret a caller sends as its Bearer. */
6
+ export type ApiToken = {
7
+ readonly id: string;
8
+ readonly token: string;
9
+ };
10
+ /** Why `token` (from `name`) is no API token, in words; undefined when it is one: 32 characters or more, no whitespace. */
11
+ export declare function tokenProblem(token: string, name?: string): string | undefined;
12
+ /** AGENTRUN_TOKENS read: entries `id:secret`, separated by commas, whitespace or newlines; the first `:` ends the id.
13
+ * An empty or blank value, or one of separators alone, is no list (undefined), as an empty AGENTRUN_TOKEN is no token. Throws, in words that never
14
+ * hold a secret, on an entry with no `:`, an id outside ID, a secret that breaks the token's rules or holds a comma
15
+ * (the separator), or an id used twice. */
16
+ export declare function parseTokens(text: string | undefined): ApiToken[] | undefined;
17
+ /** The tokens a server takes, in order: AGENTRUN_TOKEN's (or DIR/.token's) as `default` when there is one, then the
18
+ * list's. The first is the server's token: the one the console's session header stands for. Throws when there is none,
19
+ * when an id is used twice (a log line could not say which token was used) or when one secret is given twice. */
20
+ export declare function acceptedTokens(token: string | undefined, list: readonly ApiToken[] | undefined): readonly ApiToken[];
21
+ /** The values a redaction cuts for the variable `name` holding `value`: the value whole, and for AGENTRUN_TOKENS each
22
+ * entry's secret too, so a listed token met alone (pasted into a session, a file) is cut as AGENTRUN_TOKEN's would be.
23
+ * Read leniently: an entry that is not id:secret is cut whole, never skipped, and nothing here throws. */
24
+ export declare function secretValues(name: string, value: string): string[];
25
+ /** A test of an Authorization header: the id of the token when it is exactly `Bearer <that token's secret>`, else
26
+ * undefined. The header and each token's `Bearer ` line are hashed first, so every comparison is of two 32-byte digests
27
+ * whatever was sent, and `equal` (node:crypto's timingSafeEqual) compares them in constant time. Every token is
28
+ * compared on every call, with no early return on a match, so the time taken says neither whether a token matched nor
29
+ * which. */
30
+ export declare function bearerCheck(tokens: readonly ApiToken[], equal?: (a: Buffer, b: Buffer) => boolean): (header: string | undefined) => string | undefined;
@@ -0,0 +1,89 @@
1
+ // The server's API tokens: a list of named tokens, any of which opens every route the token opens. AGENTRUN_TOKENS holds
2
+ // the list as `id:secret` entries; AGENTRUN_TOKEN (else the one DIR/.token keeps) is the entry named `default`. A
3
+ // rotation never refuses a caller: add the new token as an entry, move every caller to it, then remove the old entry.
4
+ // Every check of a presented token goes through bearerCheck here, against every entry, in constant time, and answers
5
+ // which entry matched (its id, never its secret) for the request's log line.
6
+ import { createHash, timingSafeEqual } from "node:crypto";
7
+ /** The variable that holds the token list. A secret, as AGENTRUN_TOKEN is. */
8
+ export const TOKENS_ENV = "AGENTRUN_TOKENS";
9
+ /** The id of the token AGENTRUN_TOKEN (or DIR/.token) gives. */
10
+ export const DEFAULT_TOKEN_ID = "default";
11
+ /** A token's id: a letter or digit, then up to 31 letters, digits, `.`, `_` or `-`. Never a secret, so a log may hold it. */
12
+ const ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$/;
13
+ /** Why `token` (from `name`) is no API token, in words; undefined when it is one: 32 characters or more, no whitespace. */
14
+ export function tokenProblem(token, name = "the token") {
15
+ return token.length < 32 || /\s/.test(token) ? `${name} must be 32 characters or more, with no whitespace` : undefined;
16
+ }
17
+ /** AGENTRUN_TOKENS read: entries `id:secret`, separated by commas, whitespace or newlines; the first `:` ends the id.
18
+ * An empty or blank value, or one of separators alone, is no list (undefined), as an empty AGENTRUN_TOKEN is no token. Throws, in words that never
19
+ * hold a secret, on an entry with no `:`, an id outside ID, a secret that breaks the token's rules or holds a comma
20
+ * (the separator), or an id used twice. */
21
+ export function parseTokens(text) {
22
+ if (text === undefined || text.trim() === "")
23
+ return undefined;
24
+ const entries = text.split(/[\s,]+/).filter((entry) => entry !== "");
25
+ // Separators alone hold no entry: no list, so the start and its banner agree (DIR/.token's is the token, and printed).
26
+ if (entries.length === 0)
27
+ return undefined;
28
+ return entries.map((entry, index) => {
29
+ const colon = entry.indexOf(":");
30
+ if (colon < 0)
31
+ throw new Error(`${TOKENS_ENV} entry ${index + 1} is not id:secret`);
32
+ const id = entry.slice(0, colon);
33
+ const token = entry.slice(colon + 1);
34
+ if (!ID.test(id))
35
+ throw new Error(`${TOKENS_ENV} entry ${index + 1}'s id must be a letter or digit, then up to 31 letters, digits, ".", "_" or "-"`);
36
+ const problem = tokenProblem(token, `${TOKENS_ENV} entry ${id}'s secret`);
37
+ if (problem)
38
+ throw new Error(problem);
39
+ return { id, token };
40
+ });
41
+ }
42
+ /** The tokens a server takes, in order: AGENTRUN_TOKEN's (or DIR/.token's) as `default` when there is one, then the
43
+ * list's. The first is the server's token: the one the console's session header stands for. Throws when there is none,
44
+ * when an id is used twice (a log line could not say which token was used) or when one secret is given twice. */
45
+ export function acceptedTokens(token, list) {
46
+ const all = [...(token === undefined ? [] : [{ id: DEFAULT_TOKEN_ID, token }]), ...(list ?? [])];
47
+ if (all.length === 0)
48
+ throw new TypeError("a server takes at least one token");
49
+ const ids = new Set();
50
+ const secrets = new Set();
51
+ for (const entry of all) {
52
+ if (ids.has(entry.id))
53
+ throw new Error(`the API token id ${entry.id} is used twice${entry.id === DEFAULT_TOKEN_ID ? ` (AGENTRUN_TOKEN is ${DEFAULT_TOKEN_ID})` : ""}`);
54
+ if (secrets.has(entry.token))
55
+ throw new Error(`the API token ${entry.id} has the same secret as another token`);
56
+ ids.add(entry.id);
57
+ secrets.add(entry.token);
58
+ }
59
+ return all;
60
+ }
61
+ /** The values a redaction cuts for the variable `name` holding `value`: the value whole, and for AGENTRUN_TOKENS each
62
+ * entry's secret too, so a listed token met alone (pasted into a session, a file) is cut as AGENTRUN_TOKEN's would be.
63
+ * Read leniently: an entry that is not id:secret is cut whole, never skipped, and nothing here throws. */
64
+ export function secretValues(name, value) {
65
+ if (name !== TOKENS_ENV)
66
+ return [value];
67
+ const entries = value.split(/[\s,]+/).filter((entry) => entry !== "");
68
+ return [value, ...entries, ...entries.map((entry) => entry.slice(entry.indexOf(":") + 1))];
69
+ }
70
+ const digest = (text) => createHash("sha256").update(text).digest();
71
+ /** A test of an Authorization header: the id of the token when it is exactly `Bearer <that token's secret>`, else
72
+ * undefined. The header and each token's `Bearer ` line are hashed first, so every comparison is of two 32-byte digests
73
+ * whatever was sent, and `equal` (node:crypto's timingSafeEqual) compares them in constant time. Every token is
74
+ * compared on every call, with no early return on a match, so the time taken says neither whether a token matched nor
75
+ * which. */
76
+ export function bearerCheck(tokens, equal = timingSafeEqual) {
77
+ if (tokens.length === 0)
78
+ throw new TypeError("a server takes at least one token");
79
+ const expected = tokens.map((entry) => digest(`Bearer ${entry.token}`));
80
+ return (header) => {
81
+ const given = digest(String(header ?? ""));
82
+ let found = -1;
83
+ for (let i = 0; i < expected.length; i++) {
84
+ const hit = equal(given, expected[i]);
85
+ found = hit ? i : found;
86
+ }
87
+ return found < 0 ? undefined : tokens[found].id;
88
+ };
89
+ }
@@ -0,0 +1,49 @@
1
+ import { ApiError } from "../errors.js";
2
+ import type { SealedKeys } from "../store/index.js";
3
+ export type CalendarStore = {
4
+ sealedKeys: Pick<SealedKeys, "get" | "put" | "remove">;
5
+ flush?(): Promise<void>;
6
+ };
7
+ /** The calendar as the server keeps it: its address (https, or http to a loopback fake), and its own name
8
+ * (X-WR-CALNAME) and time zone as the save read them, null when that read failed. */
9
+ export type SavedCalendar = {
10
+ url: string;
11
+ name: string | null;
12
+ time_zone: string | null;
13
+ };
14
+ /** A loopback hostname as written: only there is plain http taken, for the fakes. */
15
+ export declare const LOOPBACK_NAME: RegExp;
16
+ /** The address a body gives, as it is kept: `webcal://` (and `webcals://`) read as https, any other scheme but https
17
+ * refused, and plain http taken to a loopback address alone. 422 by `field`, in words, never echoing the address. */
18
+ export declare function addressOf(value: unknown, field?: string): string;
19
+ /** Every form of `url` that text may carry it in, longest first: as kept, as webcal, decoded, its path with its query
20
+ * (where a provider keeps the secret part) when that is long enough to be one, and each path segment and query value
21
+ * that is a token on its own (tokenLike), so text that holds the address cut short holds none of its secret. What the
22
+ * redactors hold. */
23
+ export declare function addressForms(url: string): string[];
24
+ /** Each form of `url` cut from `text` (a fetch error, a calendar's own text): the address is never said. `url` may be the
25
+ * saved address and each address a read was redirected to (fetch.ts ReadCalendar followed), every one a secret: their
26
+ * forms are cut together, longest first. */
27
+ export declare function scrubAddress(text: string, url: string | readonly string[] | undefined): string;
28
+ /** The address of an opened calendar row, in each of its forms (runner/store-secrets.ts: the one redactor holds them, not
29
+ * the row's JSON). */
30
+ export declare const calendarRowSecrets: (plain: string) => string[];
31
+ /** The calendar kept now, opened with `sealKey`; undefined when none is kept, or its row does not open (sealed under
32
+ * another key) or read. */
33
+ export declare function openCalendar(store: CalendarStore, sealKey: Buffer): Promise<SavedCalendar | undefined>;
34
+ /** The calendar's view (GET /settings/calendar): whether one is kept, the host it is read from, and its own name and time
35
+ * zone. Never its address. */
36
+ export declare function calendarView(store: CalendarStore, sealKey: Buffer): Promise<{
37
+ configured: boolean;
38
+ host: string | null;
39
+ name: string | null;
40
+ time_zone: string | null;
41
+ }>;
42
+ /** The calendar saved whole, in one write. */
43
+ export declare function saveCalendar(store: CalendarStore, sealKey: Buffer, calendar: SavedCalendar): Promise<void>;
44
+ /** The calendar forgotten: its one row, in one write. */
45
+ export declare function removeCalendar(store: CalendarStore): Promise<void>;
46
+ /** A PUT's or a test's body, `{url}`, read: its address, or 422 in words. */
47
+ export declare function bodyAddress(body: unknown): string;
48
+ /** The refusal for a test of the saved calendar when none is kept. */
49
+ export declare const noCalendar: () => ApiError;
@@ -0,0 +1,153 @@
1
+ // The server's one calendar (saved with PUT /v2/settings/calendar, routes.ts): its iCal address, which is a credential (anyone
2
+ // who has it reads the calendar), kept in ONE row of the one store's sealed keys (CALENDAR_ROW, beside the tool keys and
3
+ // the email account) with the calendar's own name and time zone as the save last read them. Opened only with the seal
4
+ // key: by the server for the settings view and the test, and by a runner for a run whose revision names calendar_events
5
+ // (tools.ts). No answer, event, log line or run input holds the address: the runner's one redactor holds each of its
6
+ // forms (addressForms), read out of this row (runner/store-secrets.ts), and the server's list holds the ones saved since
7
+ // it started (server.ts).
8
+ import { ApiError, invalid } from "../errors.js";
9
+ import { getSealedKey, putSealedKey, removeSealedKey } from "../server-keys.js";
10
+ import { isObject, unknownFields } from "../validate.js";
11
+ import { ADDRESS_MAX, CALENDAR_ROW, NO_CALENDAR } from "./names.js";
12
+ /** A loopback hostname as written: only there is plain http taken, for the fakes. */
13
+ export const LOOPBACK_NAME = /^(?:localhost|\[::1\]|127(?:[.]\d{1,3}){3})$/; // key-gate: loopback-rule only a loopback fake calendar is read over plain http
14
+ const CONTROL = /[\u0000- \u007f-\u009f]/;
15
+ /** The address a body gives, as it is kept: `webcal://` (and `webcals://`) read as https, any other scheme but https
16
+ * refused, and plain http taken to a loopback address alone. 422 by `field`, in words, never echoing the address. */
17
+ export function addressOf(value, field = "url") {
18
+ const bad = (message) => invalid([{ field, reason: "invalid", message }]);
19
+ if (typeof value !== "string")
20
+ throw invalid([{ field, reason: value === undefined ? "missing" : "wrong_type", message: `${field} is the calendar's iCal address, as text (https://… or webcal://…).` }]);
21
+ const given = value.trim();
22
+ if (!given || given.length > ADDRESS_MAX)
23
+ throw bad(`${field} is 1 to ${ADDRESS_MAX} characters.`);
24
+ if (CONTROL.test(given))
25
+ throw bad(`${field} holds a space or a control character: paste the address whole, on one line.`);
26
+ const swapped = given.replace(/^webcals?:\/\//i, "https://");
27
+ const url = URL.parse(swapped);
28
+ if (!url)
29
+ throw bad(`${field} is not an address: paste the calendar's iCal address (https://… or webcal://…).`);
30
+ if (url.username || url.password)
31
+ throw bad(`${field} carries a user and password: use the calendar's secret iCal address, which needs none.`);
32
+ if (url.protocol === "http:" && !LOOPBACK_NAME.test(url.hostname))
33
+ throw bad(`${field} is http: a calendar is read over https only (webcal:// is read as https://).`);
34
+ if (url.protocol !== "https:" && url.protocol !== "http:")
35
+ throw bad(`${field} is ${url.protocol.replace(/:$/, "")}: a calendar is read over https only (webcal:// is read as https://).`);
36
+ url.hash = "";
37
+ return url.href;
38
+ }
39
+ /** A part of an address that reads as its secret on its own: decoded, no "@" (an owner's email in the path is said in the
40
+ * calendar's events as its organizer's), and a run of at least 16 letters, digits, "-" and "_" with a letter and a digit
41
+ * in it: Google's private-<hex>, iCloud's and Outlook's long ids, a feed's ?token=. */
42
+ function tokenLike(part) {
43
+ if (part.includes("@"))
44
+ return false;
45
+ const longest = (part.match(/[A-Za-z0-9_-]+/g) ?? []).reduce((a, b) => (b.length > a.length ? b : a), "");
46
+ return longest.length >= 16 && /[A-Za-z]/.test(longest) && /[0-9]/.test(longest);
47
+ }
48
+ /** Every form of `url` that text may carry it in, longest first: as kept, as webcal, decoded, its path with its query
49
+ * (where a provider keeps the secret part) when that is long enough to be one, and each path segment and query value
50
+ * that is a token on its own (tokenLike), so text that holds the address cut short holds none of its secret. What the
51
+ * redactors hold. */
52
+ export function addressForms(url) {
53
+ const forms = new Set([url]);
54
+ const parsed = URL.parse(url);
55
+ if (parsed) {
56
+ forms.add(parsed.href);
57
+ if (parsed.protocol === "https:")
58
+ forms.add(`webcal://${parsed.href.slice("https://".length)}`);
59
+ const secret = `${parsed.pathname}${parsed.search}`;
60
+ if (secret.length >= 16)
61
+ forms.add(secret);
62
+ const decode = (part) => {
63
+ try {
64
+ return decodeURIComponent(part);
65
+ }
66
+ catch {
67
+ return part;
68
+ }
69
+ };
70
+ for (const part of [...parsed.pathname.split("/"), ...[...parsed.searchParams.values()]]) {
71
+ for (const one of new Set([part, decode(part)]))
72
+ if (tokenLike(decode(one)))
73
+ forms.add(one);
74
+ }
75
+ for (const one of [...forms]) {
76
+ try {
77
+ forms.add(decodeURIComponent(one));
78
+ }
79
+ catch { }
80
+ }
81
+ }
82
+ return [...forms].filter((one) => one.length >= 8).sort((a, b) => b.length - a.length);
83
+ }
84
+ /** Each form of `url` cut from `text` (a fetch error, a calendar's own text): the address is never said. `url` may be the
85
+ * saved address and each address a read was redirected to (fetch.ts ReadCalendar followed), every one a secret: their
86
+ * forms are cut together, longest first. */
87
+ export function scrubAddress(text, url) {
88
+ const urls = (typeof url === "string" ? [url] : (url ?? [])).filter((one) => one);
89
+ if (urls.length === 0)
90
+ return text;
91
+ const forms = urls.length === 1 ? addressForms(urls[0]) : [...new Set(urls.flatMap((one) => addressForms(one)))].sort((a, b) => b.length - a.length);
92
+ let out = text;
93
+ for (const form of forms)
94
+ out = out.split(form).join("[the calendar's address]");
95
+ return out;
96
+ }
97
+ /** An opened row read: the calendar, or undefined when it is not the shape a save writes. */
98
+ function keptOf(plain) {
99
+ let value;
100
+ try {
101
+ value = plain === undefined ? undefined : JSON.parse(plain);
102
+ }
103
+ catch {
104
+ return undefined;
105
+ }
106
+ if (!isObject(value) || value.v !== 1 || typeof value.url !== "string")
107
+ return undefined;
108
+ const text = (one) => (typeof one === "string" ? one : null);
109
+ return { url: value.url, name: text(value.name), time_zone: text(value.time_zone) };
110
+ }
111
+ /** The address of an opened calendar row, in each of its forms (runner/store-secrets.ts: the one redactor holds them, not
112
+ * the row's JSON). */
113
+ export const calendarRowSecrets = (plain) => {
114
+ const url = keptOf(plain)?.url;
115
+ return url ? addressForms(url) : [];
116
+ };
117
+ /** The calendar kept now, opened with `sealKey`; undefined when none is kept, or its row does not open (sealed under
118
+ * another key) or read. */
119
+ export async function openCalendar(store, sealKey) {
120
+ if ((await store.sealedKeys.get(CALENDAR_ROW)) === undefined)
121
+ return undefined;
122
+ return keptOf(await getSealedKey(store, sealKey, CALENDAR_ROW));
123
+ }
124
+ /** The calendar's view (GET /settings/calendar): whether one is kept, the host it is read from, and its own name and time
125
+ * zone. Never its address. */
126
+ export async function calendarView(store, sealKey) {
127
+ const kept = await openCalendar(store, sealKey);
128
+ if (!kept)
129
+ return { configured: false, host: null, name: null, time_zone: null };
130
+ // A name saved before saves scrubbed it is scrubbed here too.
131
+ return { configured: true, host: URL.parse(kept.url)?.host ?? null, name: kept.name === null ? null : scrubAddress(kept.name, kept.url), time_zone: kept.time_zone };
132
+ }
133
+ /** The calendar saved whole, in one write. */
134
+ export async function saveCalendar(store, sealKey, calendar) {
135
+ await putSealedKey(store, sealKey, CALENDAR_ROW, JSON.stringify({ v: 1, url: calendar.url, name: calendar.name, time_zone: calendar.time_zone }));
136
+ await store.flush?.();
137
+ }
138
+ /** The calendar forgotten: its one row, in one write. */
139
+ export async function removeCalendar(store) {
140
+ await removeSealedKey(store, CALENDAR_ROW);
141
+ await store.flush?.();
142
+ }
143
+ /** A PUT's or a test's body, `{url}`, read: its address, or 422 in words. */
144
+ export function bodyAddress(body) {
145
+ if (!isObject(body))
146
+ throw invalid([{ field: "", reason: "wrong_type", message: "The body is {url}: the calendar's iCal address." }]);
147
+ const unknown = unknownFields(body, ["url"]);
148
+ if (unknown.length)
149
+ throw invalid(unknown);
150
+ return addressOf(body.url);
151
+ }
152
+ /** The refusal for a test of the saved calendar when none is kept. */
153
+ export const noCalendar = () => new ApiError("input_invalid", NO_CALENDAR, { fields: [{ field: "url", reason: "not_set", message: NO_CALENDAR }] });
@@ -0,0 +1,24 @@
1
+ import type { OAuthNetwork, Reach } from "../mcp-oauth.js";
2
+ import { type ParsedCalendar } from "./parse.js";
3
+ /** A read that failed, in words that never hold the address. */
4
+ export declare class CalendarError extends Error {
5
+ }
6
+ /** Where a read may go beyond public hosts (mcp-oauth.ts Reach): `loopback`, a local install's (its fakes); `allowed`, the
7
+ * private-network hosts the owner allows (Settings → MCP servers); `own`, this server's own origins, never dialled on
8
+ * loopback. */
9
+ export type CalendarReach = Reach;
10
+ /** The network a read resolves and dials through (mcp-oauth.ts OAuthNetwork), for a test. Default the system's. */
11
+ export type CalendarNetwork = OAuthNetwork;
12
+ /** A calendar read: parsed, with `followed`, every address a redirect took the read to (the saved one's host may send it
13
+ * to another secret address), each scrubbed from what the calendar says as the saved one is (address.ts scrubAddress). */
14
+ export type ReadCalendar = ParsedCalendar & {
15
+ followed: readonly string[];
16
+ };
17
+ /** Every kept read made stale, its parsed copy and validators kept: the next read of each revalidates (a test's, standing in
18
+ * for five minutes passing). */
19
+ export declare function staleCalendarsForTests(): void;
20
+ /** Every kept read forgotten (a test's). */
21
+ export declare function forgetCalendarsForTests(): void;
22
+ /** The calendar at `url`, parsed: the kept copy while it is fresh, else fetched (a 304 keeps the kept copy, the addresses
23
+ * this read was redirected to added to its own). */
24
+ export declare function readCalendar(url: string, reach?: CalendarReach, network?: CalendarNetwork, signal?: AbortSignal): Promise<ReadCalendar>;
@@ -0,0 +1,146 @@
1
+ import { scrubAddress } from "./address.js";
2
+ import { BODY_MAX_BYTES, CALENDAR_SETTING, FETCH_TIMEOUT_MS, FRESH_MS, REDIRECTS_MAX } from "./names.js";
3
+ import { parseCalendar } from "./parse.js";
4
+ /** A read that failed, in words that never hold the address. */
5
+ export class CalendarError extends Error {
6
+ }
7
+ /** Each address's last read, by address: at most KEPT_MAX, the oldest read dropped first. */
8
+ const kept = new Map();
9
+ const KEPT_MAX = 16;
10
+ /** Every kept read made stale, its parsed copy and validators kept: the next read of each revalidates (a test's, standing in
11
+ * for five minutes passing). */
12
+ export function staleCalendarsForTests() {
13
+ for (const one of kept.values())
14
+ one.at = 0;
15
+ }
16
+ /** Every kept read forgotten (a test's). */
17
+ export function forgetCalendarsForTests() {
18
+ kept.clear();
19
+ }
20
+ /** The calendar at `url`, parsed: the kept copy while it is fresh, else fetched (a 304 keeps the kept copy, the addresses
21
+ * this read was redirected to added to its own). */
22
+ export async function readCalendar(url, reach = {}, network, signal) {
23
+ const held = kept.get(url);
24
+ if (held && Date.now() - held.at < FRESH_MS)
25
+ return held.calendar;
26
+ const followed = [];
27
+ try {
28
+ const answer = await fetchCalendar(url, reach, network, held, signal, followed);
29
+ // A 304 only answers a read that sent the kept copy's validators (fetchCalendar), so `held` is there.
30
+ if (answer.status === 304) {
31
+ if (!held)
32
+ throw new CalendarError(`${hostOf(url)} answered 304.`);
33
+ held.at = Date.now();
34
+ for (const one of followed)
35
+ if (!held.followed.includes(one))
36
+ held.followed.push(one);
37
+ return held.calendar;
38
+ }
39
+ const calendar = { ...parseCalendar(answer.body ?? "", hostOf(url)), followed };
40
+ kept.delete(url);
41
+ kept.set(url, { at: Date.now(), from: answer.from, ...(answer.etag ? { etag: answer.etag } : {}), ...(answer.modified ? { modified: answer.modified } : {}), calendar, followed });
42
+ while (kept.size > KEPT_MAX)
43
+ kept.delete(kept.keys().next().value);
44
+ return calendar;
45
+ }
46
+ catch (error) {
47
+ // Words of the server's own, or the parser's, the address cut from them whatever they say.
48
+ const said = error instanceof CalendarError ? error.message : `${hostOf(url)}'s calendar couldn't be read (${error?.message ?? String(error)})`;
49
+ throw new CalendarError(scrubAddress(said, [url, ...followed]));
50
+ }
51
+ }
52
+ const hostOf = (url) => (typeof url === "string" ? (URL.parse(url)?.host ?? "the calendar's host") : url.host);
53
+ /** `refused` (mcp-oauth.ts checked's words, which name the host alone) as a sentence. */
54
+ const refusal = (at) => {
55
+ const said = `${at.refused.charAt(0).toUpperCase()}${at.refused.slice(1)}`;
56
+ return at.unresolved ? `${said}: check the address saved with ${CALENDAR_SETTING}.` : `${said}.`;
57
+ };
58
+ /** An error's code (ECONNREFUSED, ENOTFOUND, CERT_HAS_EXPIRED), from it or its cause: never its message, which may name
59
+ * what was asked for. */
60
+ function codeOf(error) {
61
+ for (let at = error, depth = 0; at && depth < 4; at = at.cause, depth += 1) {
62
+ const code = at.code;
63
+ if (typeof code === "string" && /^[A-Z][A-Z0-9_]{1,40}$/.test(code))
64
+ return code;
65
+ }
66
+ return undefined;
67
+ }
68
+ /** One fetch of `url`, following at most REDIRECTS_MAX redirects, each hop checked and its address added to `followed`;
69
+ * conditional on `held`'s validators at the address its body came from alone, so a redirect that now goes elsewhere is
70
+ * read in full there (another server's ETag may match by chance), and a 304 counts only from that address. */
71
+ async function fetchCalendar(url, reach, given, held, stop, followed) {
72
+ const signal = AbortSignal.any([AbortSignal.timeout(FETCH_TIMEOUT_MS), ...(stop ? [stop] : [])]);
73
+ const { calendarAt, dialAt, systemNetwork } = await import("../mcp-oauth.js");
74
+ const network = given ?? systemNetwork;
75
+ let target = new URL(url);
76
+ try {
77
+ for (let hop = 0;; hop += 1) {
78
+ // Each hop under the one rule, dialled at the address it checked (undefined: loopback as written, a local install's).
79
+ const at = await calendarAt(target, signal, network, reach);
80
+ if ("refused" in at)
81
+ throw new CalendarError(refusal(at));
82
+ let res;
83
+ try {
84
+ const headers = { accept: "text/calendar, text/plain;q=0.5, */*;q=0.1", "user-agent": "AgentRun-calendar/1" };
85
+ const asking = held !== undefined && target.href === held.from;
86
+ if (asking && held.etag)
87
+ headers["if-none-match"] = held.etag;
88
+ if (asking && held.modified)
89
+ headers["if-modified-since"] = held.modified;
90
+ res = await dialAt(network, at.address)(target.href, { redirect: "manual", signal, headers });
91
+ const location = res.headers.get("location");
92
+ if (res.status >= 300 && res.status < 400 && res.status !== 304 && location) {
93
+ if (hop >= REDIRECTS_MAX)
94
+ throw new CalendarError(`${hostOf(url)}'s calendar redirected more than ${REDIRECTS_MAX} times: check the address saved with ${CALENDAR_SETTING}.`);
95
+ const next = URL.parse(location, target);
96
+ if (!next)
97
+ throw new CalendarError(`${target.host} redirected the calendar to an address that isn't one.`);
98
+ target = next;
99
+ if (target.href !== url && !followed.includes(target.href))
100
+ followed.push(target.href);
101
+ continue;
102
+ }
103
+ const validators = { ...(res.headers.get("etag") ? { etag: res.headers.get("etag") } : {}), ...(res.headers.get("last-modified") ? { modified: res.headers.get("last-modified") } : {}) };
104
+ if (res.status === 304 && asking)
105
+ return { status: 304, etag: validators.etag ?? held.etag, modified: validators.modified ?? held.modified };
106
+ if (res.status === 401 || res.status === 403 || res.status === 404 || res.status === 410)
107
+ throw new CalendarError(`${target.host} answered ${res.status}: the address may be old or wrong; copy it again and save it with ${CALENDAR_SETTING}.`);
108
+ if (res.status < 200 || res.status >= 300)
109
+ throw new CalendarError(`${target.host} answered ${res.status}.`);
110
+ return { status: 200, body: await bodyOf(res, target), from: target.href, ...validators };
111
+ }
112
+ finally {
113
+ await res?.body?.cancel().catch(() => undefined);
114
+ }
115
+ }
116
+ }
117
+ catch (error) {
118
+ if (error instanceof CalendarError)
119
+ throw error;
120
+ if (signal.aborted && !stop?.aborted)
121
+ throw new CalendarError(`${target.host} didn't answer within ${FETCH_TIMEOUT_MS / 1000} s.`);
122
+ if (stop?.aborted)
123
+ throw new CalendarError("The read was stopped.");
124
+ throw new CalendarError(`${target.host} couldn't be reached (${codeOf(error) ?? "the connection failed"}).`);
125
+ }
126
+ }
127
+ /** A 2xx answer's body, as text, at most BODY_MAX_BYTES. */
128
+ async function bodyOf(res, target) {
129
+ const stream = res.body;
130
+ if (!stream)
131
+ return "";
132
+ const chunks = [];
133
+ let size = 0;
134
+ for (const reader = stream.getReader();;) {
135
+ const { done, value } = await reader.read();
136
+ if (done)
137
+ break;
138
+ size += value.length;
139
+ if (size > BODY_MAX_BYTES) {
140
+ await reader.cancel().catch(() => undefined);
141
+ throw new CalendarError(`${target.host}'s calendar is over ${BODY_MAX_BYTES / 1024 / 1024} MB: too big to read.`);
142
+ }
143
+ chunks.push(value);
144
+ }
145
+ return Buffer.concat(chunks).toString("utf8");
146
+ }
@@ -0,0 +1,39 @@
1
+ /** Lines as iCalendar writes them: CRLF, each line at most 75 octets, a longer one folded onto lines that start with a
2
+ * space (RFC 5545 3.1). */
3
+ export declare function icsLines(lines: readonly string[]): string;
4
+ /** The standup's description: over 500 characters, so an answer's is cut. */
5
+ export declare const LONG_DESCRIPTION: string;
6
+ /** The fake's own calendar (see the head of this file). */
7
+ export declare const FAUX_CALENDAR: string;
8
+ /** A calendar of `name` whose one series runs every hour from Nov 1 2026, with no end: more events than any answer holds. */
9
+ export declare const hourlyCalendar: (name?: string) => string;
10
+ /** One request the fake answered. */
11
+ export type IcsRequest = {
12
+ path: string;
13
+ status: number;
14
+ ifNoneMatch?: string;
15
+ ifModifiedSince?: string;
16
+ };
17
+ export type IcsFaux = {
18
+ /** Where it listens: on loopback, at the port it was given (else one free). */
19
+ readonly origin: string;
20
+ /** Its own calendar's address: a secret-looking path, as a provider's private address is. */
21
+ readonly address: string;
22
+ /** The address of `path` on it. */
23
+ at(path: string): string;
24
+ /** Serves `text` at `path` (its own calendar's, by default) from now on, under a new ETag and Last-Modified. */
25
+ serve(text: string, path?: string): void;
26
+ /** `path` answers 302 to `to`: a path on it, or a whole address elsewhere (a redirect off it). */
27
+ move(path: string, to: string): void;
28
+ /** Every request answers `status` (its body naming the address asked for), or, with undefined, as before. */
29
+ failing(status: number | undefined): void;
30
+ /** The requests it answered, oldest first. */
31
+ requests(): IcsRequest[];
32
+ close(): Promise<void>;
33
+ };
34
+ /** Starts the fake on loopback (an ephemeral port unless `port`), its own calendar served at `address`, or `text` there in
35
+ * its place. */
36
+ export declare function startIcsFaux(options?: {
37
+ port?: number;
38
+ text?: string;
39
+ }): Promise<IcsFaux>;