@intentic/extension-manifest 1.431.0 → 1.433.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.
Files changed (68) hide show
  1. package/README.md +48 -2
  2. package/dist/manifest.d.ts +296 -0
  3. package/dist/manifest.d.ts.map +1 -1
  4. package/dist/manifest.js +105 -1
  5. package/dist/manifest.js.map +1 -1
  6. package/dist/permissions.d.ts +27 -0
  7. package/dist/permissions.d.ts.map +1 -1
  8. package/dist/permissions.js +32 -1
  9. package/dist/permissions.js.map +1 -1
  10. package/dist/points/automation-templates.d.ts +68 -0
  11. package/dist/points/automation-templates.d.ts.map +1 -1
  12. package/dist/points/automation-templates.js +29 -1
  13. package/dist/points/automation-templates.js.map +1 -1
  14. package/dist/points/capabilities.d.ts +357 -50
  15. package/dist/points/capabilities.d.ts.map +1 -1
  16. package/dist/points/capabilities.js +22 -51
  17. package/dist/points/capabilities.js.map +1 -1
  18. package/dist/points/capability-broker.d.ts +110 -0
  19. package/dist/points/capability-broker.d.ts.map +1 -0
  20. package/dist/points/capability-broker.js +125 -0
  21. package/dist/points/capability-broker.js.map +1 -0
  22. package/dist/points/channel-facts.d.ts +46 -0
  23. package/dist/points/channel-facts.d.ts.map +1 -0
  24. package/dist/points/channel-facts.js +80 -0
  25. package/dist/points/channel-facts.js.map +1 -0
  26. package/dist/points/index.d.ts +587 -0
  27. package/dist/points/index.d.ts.map +1 -1
  28. package/dist/points/index.js +12 -0
  29. package/dist/points/index.js.map +1 -1
  30. package/dist/points/listener.d.ts +12 -0
  31. package/dist/points/listener.d.ts.map +1 -1
  32. package/dist/points/listener.js +6 -0
  33. package/dist/points/listener.js.map +1 -1
  34. package/dist/points/model-roles.d.ts +31 -0
  35. package/dist/points/model-roles.d.ts.map +1 -0
  36. package/dist/points/model-roles.js +27 -0
  37. package/dist/points/model-roles.js.map +1 -0
  38. package/dist/points/public-routes.d.ts +91 -0
  39. package/dist/points/public-routes.d.ts.map +1 -0
  40. package/dist/points/public-routes.js +140 -0
  41. package/dist/points/public-routes.js.map +1 -0
  42. package/dist/points/sleep-watch.d.ts +15 -0
  43. package/dist/points/sleep-watch.d.ts.map +1 -0
  44. package/dist/points/sleep-watch.js +30 -0
  45. package/dist/points/sleep-watch.js.map +1 -0
  46. package/dist/points/watch-kinds.d.ts +102 -0
  47. package/dist/points/watch-kinds.d.ts.map +1 -0
  48. package/dist/points/watch-kinds.js +118 -0
  49. package/dist/points/watch-kinds.js.map +1 -0
  50. package/intentic-extension.schema.json +1398 -34
  51. package/package.json +2 -2
  52. package/src/manifest.ts +145 -1
  53. package/src/permissions.test.ts +48 -1
  54. package/src/permissions.ts +99 -4
  55. package/src/points/automation-templates.ts +43 -5
  56. package/src/points/capabilities.ts +37 -80
  57. package/src/points/capability-broker.ts +203 -0
  58. package/src/points/channel-facts.test.ts +38 -0
  59. package/src/points/channel-facts.ts +119 -0
  60. package/src/points/index.ts +12 -0
  61. package/src/points/listener.ts +16 -0
  62. package/src/points/model-roles.ts +44 -0
  63. package/src/points/public-routes.test.ts +132 -0
  64. package/src/points/public-routes.ts +198 -0
  65. package/src/points/sleep-watch.ts +54 -0
  66. package/src/points/watch-kinds.test.ts +73 -0
  67. package/src/points/watch-kinds.ts +172 -0
  68. package/src/powers.test.ts +116 -8
@@ -0,0 +1,198 @@
1
+ import { z } from "zod";
2
+ import type { ContributionPoint } from "../contribution-point.js";
3
+
4
+ // (2026-11-26) A PUBLIC DOOR INTO AN EXTENSION'S BACKEND: a route anyone on the internet may call, with no sign-in, served
5
+ // by the daemon at /door/<id>/<path> and handed to the backend's `api.publicRoutes.serve` handler only once the daemon's
6
+ // own protections passed it: the body's size, the per-minute window and the day's ceiling, the caller's Origin against an
7
+ // automation's allowlist (or that automation's door key in its place), a solved proof-of-work challenge, a Cloudflare
8
+ // Turnstile token (2026-11-26) and a provider's signature over the body, each checked against a sandbox secret the
9
+ // extension never sees, a redelivery of a call already taken answered without reaching it. Every request through `/x/<id>` stays behind sign-in.
10
+
11
+ // What the daemon accepts at most, and what a route that names no ceiling of its own gets.
12
+ export const PUBLIC_ROUTE_BODY_MAX = 1024 * 1024;
13
+ export const PUBLIC_ROUTE_BODY_DEFAULT = 64 * 1024;
14
+ export const PUBLIC_ROUTE_RATE_DEFAULT = 30;
15
+ export const PUBLIC_ROUTE_RATE_MAX = 600;
16
+ export const PUBLIC_ROUTE_DAILY_DEFAULT = 1_000;
17
+ export const PUBLIC_ROUTE_DAILY_MAX = 100_000;
18
+ // (2026-11-26) A GET-only route's declaration that it counts no day at all.
19
+ export const PUBLIC_ROUTE_NO_DAILY_MAX = "none";
20
+
21
+ export const PUBLIC_ROUTE_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"] as const;
22
+ export type PublicRouteMethod = (typeof PUBLIC_ROUTE_METHODS)[number];
23
+
24
+ // The signing schemes the daemon checks itself, each as its provider signs (the automations wire's own list, which the
25
+ // daemon's verifier is typed by, so a scheme here it cannot check fails its typecheck).
26
+ export const PUBLIC_ROUTE_SIGNATURE_SCHEMES = ["github", "linear", "sentry", "stripe", "standard-webhooks"] as const;
27
+
28
+ // (2026-11-26) The header a caller sends a Cloudflare Turnstile token in, for a route declaring `turnstile`: the core's own
29
+ // Visitor chat's check, verified by the daemon with a secret the extension never sees.
30
+ export const PUBLIC_ROUTE_TURNSTILE_HEADER = "x-intentic-turnstile";
31
+
32
+ // A segment of a public route's path: a lowercase word (dots allowed, never leading, so no `.` or `..`), or a lone `*`
33
+ // standing for any one segment.
34
+ const SEGMENT = /^(?:\*|[a-z0-9][a-z0-9._-]{0,63})$/u;
35
+ const SEGMENTS_MAX = 8;
36
+
37
+ // Why a declared path is not one, or undefined when it is.
38
+ export const publicRoutePathProblem = (path: string): string | undefined => {
39
+ const segments = path.split("/");
40
+ if (path === "" || segments.length > SEGMENTS_MAX) {
41
+ return `a public route's path is 1 to ${SEGMENTS_MAX} segments joined by "/", with no leading slash`;
42
+ }
43
+ const bad = segments.find((segment) => !SEGMENT.test(segment));
44
+ return bad === undefined ? undefined : `"${bad}" is not a segment: a lowercase word (letters, digits, ".", "_", "-"), or a lone "*" for any one segment`;
45
+ };
46
+
47
+ export const PublicRouteContributionSchema = z
48
+ .object({
49
+ path: z
50
+ .string()
51
+ .superRefine((path, ctx) => {
52
+ const problem = publicRoutePathProblem(path);
53
+ if (problem !== undefined) {
54
+ ctx.addIssue({ code: "custom", message: problem });
55
+ }
56
+ })
57
+ .describe('Where it answers, under /door/<id>/: segments joined by "/", each a lowercase word or a lone `*` for any one segment, e.g. "hook", "*/report".'),
58
+ methods: z.array(z.enum(PUBLIC_ROUTE_METHODS)).min(1).describe("The methods it answers; anything else is refused before your backend hears of it."),
59
+ automation: z
60
+ .literal(true)
61
+ .optional()
62
+ .describe(
63
+ "The path's first `*` names an automation listening on this extension's own listener provider: one that is not there answers 404 and one switched off 409, its `allowedOrigins` are the list `origins` checks, its door key is what `key` admits, and the day's ceiling is counted per automation.",
64
+ ),
65
+ origins: z
66
+ .enum(["listed", "any"])
67
+ .optional()
68
+ .describe(
69
+ "`listed`: a browser's Origin must be on the automation's allowed origins, or the call is refused (403); needs `automation`. `any` or absent: no Origin is checked, as for a provider's webhook.",
70
+ ),
71
+ key: z
72
+ .literal(true)
73
+ .optional()
74
+ .describe(
75
+ "A caller with no Origin to check (an app, a server) may present the automation's door key instead, as `?key=` or `Authorization: Bearer`; needs `automation` and `origins: \"listed\"`. The key itself never reaches your backend.",
76
+ ),
77
+ keyFromBrowsers: z
78
+ .literal(true)
79
+ .optional()
80
+ .describe(
81
+ "(2026-11-26) An automation that opts in (its trigger's `keyFromBrowsers`) lets its door key admit a browser whose Origin is not on its list too; needs `key`. The owner opts each automation in, off by default, since a key in a public page is anyone's to copy: the minute's window and the day's ceiling are then what bound it.",
82
+ ),
83
+ signature: z
84
+ .object({
85
+ scheme: z.enum(PUBLIC_ROUTE_SIGNATURE_SCHEMES).describe("Which provider's signing scheme the sender uses."),
86
+ secret: z
87
+ .string()
88
+ .regex(/^[A-Za-z_][A-Za-z0-9_]{0,127}$/)
89
+ .describe("The name of the sandbox secret holding the signing secret, which the owner sets; its value never reaches your backend."),
90
+ })
91
+ .optional()
92
+ .describe(
93
+ "Refuse anything not signed by the sender with the named secret (and, for a timestamped scheme, sent within five minutes); a redelivery of a call already taken is answered without reaching your backend.",
94
+ ),
95
+ turnstile: z
96
+ .object({
97
+ secret: z
98
+ .string()
99
+ .regex(/^[A-Za-z_][A-Za-z0-9_]{0,127}$/)
100
+ .describe("The name of the sandbox secret holding the Cloudflare Turnstile secret key, which the owner sets; its value never reaches your backend."),
101
+ })
102
+ .optional()
103
+ .describe(
104
+ `Refuse a call without a Cloudflare Turnstile token the sandbox verifies with Cloudflare under the named secret: the page renders the widget with its site key (public, yours to serve) and sends the token it gets as \`${PUBLIC_ROUTE_TURNSTILE_HEADER}\`. A token is good once.`,
105
+ ),
106
+ proofOfWork: z
107
+ .literal(true)
108
+ .optional()
109
+ .describe(
110
+ "Refuse a call without a solved challenge: the caller fetches one at GET /door/<id>/~challenge?caller=<its id> and sends `x-intentic-pow: <salt>:<nonce>` and `x-intentic-pow-caller: <its id>`.",
111
+ ),
112
+ rate: z
113
+ .number()
114
+ .int()
115
+ .min(1)
116
+ .max(PUBLIC_ROUTE_RATE_MAX)
117
+ .optional()
118
+ .describe(`Calls a minute one caller (by address) may make before 429; ${PUBLIC_ROUTE_RATE_DEFAULT} when absent.`),
119
+ dailyMax: z
120
+ .union([z.number().int().min(1).max(PUBLIC_ROUTE_DAILY_MAX), z.literal(PUBLIC_ROUTE_NO_DAILY_MAX)])
121
+ .optional()
122
+ .describe(
123
+ `Calls a day it takes in all (per automation, for an automation's route) before 429; ${PUBLIC_ROUTE_DAILY_DEFAULT} when absent. \`"none"\` (2026-11-26) counts no day at all, for a route that only serves what a page loads (a script, its settings), so a busy site's page views cannot shut it; only a GET-only route may say it, and its minute's window and size still hold.`,
124
+ ),
125
+ bodyMax: z
126
+ .number()
127
+ .int()
128
+ .min(0)
129
+ .max(PUBLIC_ROUTE_BODY_MAX)
130
+ .optional()
131
+ .describe(`The largest body it takes, in bytes; ${PUBLIC_ROUTE_BODY_DEFAULT} when absent, at most ${PUBLIC_ROUTE_BODY_MAX}.`),
132
+ wakes: z
133
+ .literal(true)
134
+ .meta({ power: { key: "wakes:${path}", sentence: "a call to /${path} wakes the sandbox while it sleeps, which spends its awake hours" } })
135
+ .optional()
136
+ .describe(
137
+ "(2026-11-27) A call here may wake a sandbox the platform hosts while it sleeps, when it reaches the route at the URL `api.sleep.wakeUrl(path, { automationId })` hands out (a wake secret rides in its query) and an automation on this extension's listener provider is switched on (the one the path names, for an automation's route). The sender is answered 503 with `Retry-After` while the machine boots, so it must retry; one that never retries loses what it sent. Its only `*` is the automation's.",
138
+ ),
139
+ })
140
+ .superRefine((route, ctx) => {
141
+ if (route.origins === "listed" && route.automation !== true) {
142
+ ctx.addIssue({ code: "custom", path: ["origins"], message: "`origins: \"listed\"` checks an automation's allowed origins, so it needs `automation: true`" });
143
+ }
144
+ if (route.key === true && route.origins !== "listed") {
145
+ ctx.addIssue({ code: "custom", path: ["key"], message: "`key` admits a caller in place of a listed Origin, so it needs `origins: \"listed\"`" });
146
+ }
147
+ if (route.keyFromBrowsers === true && route.key !== true) {
148
+ ctx.addIssue({ code: "custom", path: ["keyFromBrowsers"], message: "`keyFromBrowsers` lets the key stand in for an unlisted browser, so it needs `key: true`" });
149
+ }
150
+ if (route.dailyMax === PUBLIC_ROUTE_NO_DAILY_MAX && route.methods.some((method) => method !== "GET")) {
151
+ ctx.addIssue({ code: "custom", path: ["dailyMax"], message: '`dailyMax: "none"` is for a route that only serves what a page loads, so its methods must be GET alone' });
152
+ }
153
+ if (route.automation === true && !route.path.split("/").includes("*")) {
154
+ ctx.addIssue({ code: "custom", path: ["automation"], message: "`automation` reads the automation's id from the path's first `*`, which this path has none of" });
155
+ }
156
+ // A wake URL names one path, so nothing in it may be left to the caller but the automation the route is for.
157
+ if (route.wakes === true && route.path.split("/").filter((segment) => segment === "*").length > (route.automation === true ? 1 : 0)) {
158
+ ctx.addIssue({ code: "custom", path: ["wakes"], message: "a route that wakes the sandbox names one path: its only `*` is an automation's, with `automation: true`" });
159
+ }
160
+ })
161
+ .meta({
162
+ power: {
163
+ key: "public:${path}",
164
+ sentence: "anyone on the internet can call its backend at ${methods|, } /${path}${signature? when signed with your secret ${signature.secret}:}",
165
+ },
166
+ });
167
+ export type PublicRouteContribution = z.infer<typeof PublicRouteContributionSchema>;
168
+
169
+ /** The declared route `method` and the path's `segments` (under /door/<id>/) land on, the first that matches; undefined for none. */
170
+ export const publicRouteFor = <Route extends Pick<PublicRouteContribution, "path" | "methods">>(
171
+ routes: readonly Route[],
172
+ method: string,
173
+ segments: readonly string[],
174
+ ): Route | undefined =>
175
+ routes.find((route) => {
176
+ const declared = route.path.split("/");
177
+ return (
178
+ route.methods.some((each) => each === method.toUpperCase()) &&
179
+ declared.length === segments.length &&
180
+ declared.every((glob, index) => {
181
+ const segment = segments[index] ?? "";
182
+ return glob === "*" ? segment !== "" && segment !== "." && segment !== ".." && !segment.includes("\\") : glob === segment;
183
+ })
184
+ );
185
+ });
186
+
187
+ /** The segment of `segments` an automation-scoped route reads the automation's id from: the one under its first `*`. */
188
+ export const publicRouteAutomationOf = (route: Pick<PublicRouteContribution, "path" | "automation">, segments: readonly string[]): string | undefined =>
189
+ route.automation === true ? segments[route.path.split("/").indexOf("*")] : undefined;
190
+
191
+ export const publicRoutesPoint = {
192
+ name: "publicRoutes",
193
+ description:
194
+ "Routes anyone on the internet may call without signing in, served at /door/<id>/<path> and handed to your backend's `api.publicRoutes.serve` handler only after the sandbox's own protections passed the call: its size, a per-minute window and a daily ceiling, an automation's allowed origins or its door key, a proof-of-work challenge, a Cloudflare Turnstile token, a provider's signature, the last two checked against secrets you never see. Each is a power the owner approves.",
195
+ schema: z
196
+ .array(PublicRouteContributionSchema)
197
+ .refine((routes) => new Set(routes.map((route) => route.path)).size === routes.length, { message: "public route paths must be unique" }),
198
+ } as const satisfies ContributionPoint;
@@ -0,0 +1,54 @@
1
+ import { z } from "zod";
2
+ import type { CapabilityField } from "./capabilities.js";
3
+
4
+ /* (2026-11-27) WHAT INTENTIC'S SERVERS MAY HOLD FOR A CARD WHILE A HOSTED SANDBOX SLEEPS. Credentials stay in the sandbox,
5
+ * with one exception: a service that delivers only over a live connection (Discord's gateway) can be heard while the
6
+ * machine sleeps only by something outside it holding that connection. A cli card declares which of its fields holds
7
+ * the credential and which switch is the owner's yes for one connection; the daemon hands the credential to the
8
+ * platform right before a sleep only for a connection whose switch is on, on a hosted sandbox, while an automation
9
+ * listens on the card's provider, and the platform deletes it when the sandbox wakes. The services the platform speaks
10
+ * are a closed list: a declaration naming another would hand a credential to nothing. */
11
+
12
+ // The connections the platform's sleep watcher can hold: `discord`, a bot's gateway connection.
13
+ export const SLEEP_WATCH_SERVICES = ["discord"] as const;
14
+ export type SleepWatchService = (typeof SLEEP_WATCH_SERVICES)[number];
15
+
16
+ export const SleepWatchSchema = z
17
+ .object({
18
+ service: z
19
+ .enum(SLEEP_WATCH_SERVICES)
20
+ .describe("The connection Intentic's servers hold for it while the sandbox sleeps: `discord`, the bot's gateway connection, the only one they speak."),
21
+ credential: z.string().describe("The secret field holding the credential they hold (a bot token)."),
22
+ consent: z
23
+ .string()
24
+ .describe(
25
+ "The switch (`boolean: true`, `hosted: true`, off by default) that is the owner's yes for one connection. Off, or on a sandbox on the owner's own computer, nothing leaves the sandbox. Its label or hint must say exactly what happens.",
26
+ ),
27
+ })
28
+ .describe(
29
+ "Lets Intentic's servers hold this card's credential while a hosted sandbox sleeps, to notice what the service delivers only over a live connection and wake the sandbox for it: only for a connection whose owner turned the `consent` switch on, only while an automation listens on this card's provider, and only until the sandbox wakes, when it is deleted. The one exception to credentials staying in the sandbox.",
30
+ );
31
+ export type SleepWatch = z.infer<typeof SleepWatchSchema>;
32
+
33
+ // Why a card's declaration cannot stand against its own fields: a credential that is not a secret field, or a consent
34
+ // that is not an off-by-default, hosted-only switch.
35
+ export const sleepWatchProblems = (watch: SleepWatch, fields: readonly CapabilityField[]): string[] => {
36
+ const declared = new Map(fields.map((field) => [field.key, field]));
37
+ const problems: string[] = [];
38
+ if (declared.get(watch.credential)?.secret !== true) {
39
+ problems.push(`sleepWatch.credential "${watch.credential}" must name a secret field`);
40
+ }
41
+ const consent = declared.get(watch.consent);
42
+ if (consent?.boolean !== true || consent.hosted !== true || (consent.default ?? "off") !== "off") {
43
+ problems.push(
44
+ `sleepWatch.consent "${watch.consent}" must name a switch (\`boolean: true\`) drawn only on hosted sandboxes (\`hosted: true\`) and off by default`,
45
+ );
46
+ }
47
+ return problems;
48
+ };
49
+
50
+ // Whether a stored connection's answer to the consent switch is yes: the form stores a switch as "on"/"off".
51
+ export const sleepWatchConsented = (watch: SleepWatch, config: Readonly<Record<string, string | number | boolean | undefined>>): boolean => {
52
+ const answer = config[watch.consent];
53
+ return answer === "on" || answer === true;
54
+ };
@@ -0,0 +1,73 @@
1
+ import { ExtensionManifestSchema } from "../manifest.js";
2
+ import { WatchKindContributionSchema, watchParamsProblem, watchSentence } from "./watch-kinds.js";
3
+
4
+ // A watch kind's declaration: what it may say, the sentence a source of it reads as, and the rule its parameters are
5
+ // held to, which the daemon, the Automations view and the approval card all read through these two functions.
6
+
7
+ const RELEASES = {
8
+ id: "github-release",
9
+ label: "GitHub release",
10
+ description: "The newest release of a repository.",
11
+ sentence: "GitHub releases of {repo}[ (prereleases too){prereleases}]",
12
+ fields: [
13
+ { key: "repo", label: "Repository", required: true, pattern: "^[\\w.-]+/[\\w.-]+$", patternHint: "owner/name" },
14
+ { key: "prereleases", label: "Prereleases too", type: "switch" },
15
+ ],
16
+ };
17
+
18
+ const manifestWith = (fields: object) => ({ publisher: "acme", name: "forge", version: "1.0.0", engines: { intentic: "^2.51.0" }, ...fields });
19
+
20
+ test("a sentence fills its parameters and drops a segment whose parameter is absent or off", () => {
21
+ const kind = WatchKindContributionSchema.parse(RELEASES);
22
+ expect(watchSentence(kind, { kind: "github-release", repo: "oven-sh/bun" })).toBe("GitHub releases of oven-sh/bun");
23
+ expect(watchSentence(kind, { kind: "github-release", repo: "oven-sh/bun", prereleases: false })).toBe("GitHub releases of oven-sh/bun");
24
+ expect(watchSentence(kind, { kind: "github-release", repo: "oven-sh/bun", prereleases: true })).toBe("GitHub releases of oven-sh/bun (prereleases too)");
25
+ // Undeclared: the id and what it holds, so a source whose extension is gone still says what it watched.
26
+ expect(watchSentence(undefined, { kind: "pypi", package: "httpx", pre: true, off: false })).toBe("pypi package=httpx pre");
27
+ });
28
+
29
+ test("parameters are held to the declared fields: required, pattern, type, and nothing undeclared", () => {
30
+ const kind = WatchKindContributionSchema.parse(RELEASES);
31
+ expect(watchParamsProblem(kind, { kind: "github-release", repo: "oven-sh/bun", prereleases: true })).toBeUndefined();
32
+ expect(watchParamsProblem(kind, { kind: "github-release" })).toBe("Repository is required");
33
+ expect(watchParamsProblem(kind, { kind: "github-release", repo: "bun" })).toBe("Repository must look like owner/name");
34
+ expect(watchParamsProblem(kind, { kind: "github-release", repo: " " })).toBe("Repository is empty");
35
+ expect(watchParamsProblem(kind, { kind: "github-release", repo: "a/b", prereleases: "yes" })).toBe("Prereleases too is on or off");
36
+ expect(watchParamsProblem(kind, { kind: "github-release", repo: "a/b", tag: "x" })).toBe("a github-release watch has no tag: it takes repo, prereleases");
37
+ });
38
+
39
+ test("a declaration names only its own fields, never `url` or `kind`, and a switch carries no text rules", () => {
40
+ const issues = (declared: object): string[] => WatchKindContributionSchema.safeParse(declared).error?.issues.map((issue) => issue.message) ?? [];
41
+ expect(issues({ ...RELEASES, id: "url" })[0]).toContain("not `url`, the sandbox's own");
42
+ expect(issues({ ...RELEASES, sentence: "{nope}" })).toEqual(['the sentence names "{nope}", which is none of the kind\'s fields']);
43
+ expect(issues({ ...RELEASES, fields: [...RELEASES.fields, { key: "kind", label: "Kind" }] })[0]).toContain("not `kind`");
44
+ expect(issues({ ...RELEASES, sentence: "Watching[ (on){on}]", fields: [{ key: "on", label: "On", type: "switch", required: true }] })).toEqual(["a switch is never required and has no pattern or length"]);
45
+ expect(issues({ ...RELEASES, sentence: "{repo}", fields: [{ key: "repo", label: "A", pattern: "(" }] })).toEqual(["the pattern does not compile as a regular expression"]);
46
+ });
47
+
48
+ test("a manifest's watch kinds need a backend to answer them, and reach only its own cards", () => {
49
+ const parsed = (fields: object): string[] => ExtensionManifestSchema.safeParse(manifestWith(fields)).error?.issues.map((issue) => issue.message) ?? [];
50
+ expect(parsed({ server: "dist/server.js", contributes: { watchKinds: [RELEASES] } })).toEqual([]);
51
+ expect(parsed({ contributes: { watchKinds: [RELEASES] } })).toEqual(["watch kinds need a `server` bundle to answer their checks"]);
52
+ expect(parsed({ server: "dist/server.js", contributes: { watchKinds: [{ ...RELEASES, capabilities: ["github"] }] } })).toEqual([
53
+ '"github" is not one of this extension\'s own capability cards',
54
+ ]);
55
+ expect(parsed({ server: "dist/server.js", contributes: { watchKinds: [RELEASES, RELEASES] } })).toEqual(['the watch kind "github-release" is declared twice']);
56
+ });
57
+
58
+ test("a template takes every field the daemon's own carry, a watch's included", () => {
59
+ const template = {
60
+ id: "releases",
61
+ title: "Releases",
62
+ trigger: { kind: "schedule" as const, cron: "41 */6 * * *", tz: "Europe/Warsaw", afterSessions: 3 },
63
+ source: { kind: "github-release", repo: "oven-sh/bun", prereleases: true },
64
+ fireOn: "change" as const,
65
+ until: "first-fire" as const,
66
+ target: { kind: "extension" as const, extension: "acme.forge", handler: "sweep" },
67
+ prompt: "Read it.",
68
+ };
69
+ const hook = { id: "hook", title: "Hook", trigger: { kind: "event" as const, dailyMax: 5, signature: { scheme: "github", secret: "S" } }, prompt: "Go." };
70
+ const once = { id: "once", title: "Once", trigger: { kind: "once" as const, at: 1 }, prompt: "Go." };
71
+ const parsed = ExtensionManifestSchema.parse(manifestWith({ contributes: { automationTemplates: [template, hook, once] } }));
72
+ expect(parsed.contributes?.automationTemplates).toEqual([template, hook, once]);
73
+ });
@@ -0,0 +1,172 @@
1
+ import { z } from "zod";
2
+ import type { ContributionPoint } from "../contribution-point.js";
3
+
4
+ // (2026-11-26) A WATCH KIND: a ready-made check an automation can name instead of a guard command, which this extension's
5
+ // backend answers (`api.checks.serve(kind, handler)`) and the daemon calls through the backend host's door, under the
6
+ // scheduler, with no shell and no model. The daemon keeps one kind of its own, `url` (a page's text); every other kind is
7
+ // declared here, so the composer, the `automations` command and an automation's approval card draw it from this
8
+ // declaration rather than from a list in the core. An automation stores its source as `{ kind: <id>, ...parameters }`,
9
+ // each parameter one of `fields`, and saving checks it against them. Before this the daemon held the npm and GitHub
10
+ // release clients itself and the five places that named a kind each listed them.
11
+
12
+ // A kind's id, as an automation names it: a lowercase word. `url` is the daemon's own.
13
+ export const WATCH_KIND_ID = /^(?!url$)[a-z][a-z0-9-]{0,63}$/u;
14
+ // A parameter's name, as an automation stores it beside `kind`.
15
+ export const WATCH_PARAM_KEY = /^(?!kind$)[a-z][a-zA-Z0-9]{0,39}$/u;
16
+ // What a parameter holds: a line of text, or a switch that is on.
17
+ export type WatchParamValue = string | boolean;
18
+ export type WatchParams = Readonly<Record<string, WatchParamValue | undefined>>;
19
+
20
+ // The longest a text parameter may be when its field names no bound of its own.
21
+ const TEXT_MAX = 2000;
22
+
23
+ const compiles = (pattern: string): boolean => {
24
+ try {
25
+ void new RegExp(pattern, "u");
26
+ return true;
27
+ } catch {
28
+ // allow(silent-catch): not compiling is the answer this asks for
29
+ return false;
30
+ }
31
+ };
32
+
33
+ export const WatchKindFieldSchema = z.object({
34
+ key: z
35
+ .string()
36
+ .regex(WATCH_PARAM_KEY, "a parameter's key is a camelCase word, and not `kind`")
37
+ .describe("The parameter's name as the automation stores it, beside `kind`: what `--with <key>=<value>` sets on the command line."),
38
+ label: z.string().min(1).max(80).describe("The box's label in the composer."),
39
+ type: z
40
+ .enum(["text", "switch"])
41
+ .optional()
42
+ .describe("`text` (the default): a line of text, stored as typed. `switch`: on or off, stored as `true` only when on."),
43
+ required: z.boolean().optional().describe("Whether a source of this kind must carry it. A switch is never required."),
44
+ placeholder: z.string().min(1).max(200).optional().describe("An example value, shown in the empty box."),
45
+ hint: z.string().min(1).max(300).optional().describe("One sentence on what it changes, behind the field's (i)."),
46
+ pattern: z
47
+ .string()
48
+ .min(1)
49
+ .max(300)
50
+ .refine(compiles, "the pattern does not compile as a regular expression")
51
+ .optional()
52
+ .describe("A regular expression a text value must match, checked when the automation is saved, in the composer and by the command."),
53
+ patternHint: z.string().min(1).max(120).optional().describe("What a value that matches looks like, said when one does not: `owner/name`."),
54
+ maxLength: z.number().int().positive().max(TEXT_MAX).optional().describe(`The longest a text value may be. Absent means ${TEXT_MAX} characters.`),
55
+ });
56
+ export type WatchKindField = z.infer<typeof WatchKindFieldSchema>;
57
+
58
+ // `{key}` names a parameter; a `[…]` segment is left out when a parameter it names is absent or off.
59
+ const PLACEHOLDER = /\{([a-zA-Z0-9]+)\}/gu;
60
+ const SEGMENT = /\[([^[\]]*)\]/gu;
61
+
62
+ /** The parameters a sentence names, outside and inside its optional segments. */
63
+ export const sentenceKeys = (sentence: string): string[] => [...sentence.matchAll(PLACEHOLDER)].map((match) => match[1] ?? "");
64
+
65
+ // The declaration's fields, before the rules across them: what the catalogue's shape (the contract's WatchKindSchema)
66
+ // is made from, since a refined schema cannot be narrowed.
67
+ export const WatchKindDeclarationSchema = z.object({
68
+ id: z
69
+ .string()
70
+ .regex(WATCH_KIND_ID, "a watch kind's id is a lowercase word: letters, digits and dashes, and not `url`, the sandbox's own")
71
+ .describe("The kind's id, which an automation's source names as `kind`. Keep it once shipped: a stored automation names it."),
72
+ label: z.string().min(1).max(40).describe("What the composer's chip says: a few words, like `npm package`."),
73
+ icon: z.string().min(1).optional().describe("A name from the host's icon set for the chip."),
74
+ logo: z.string().min(1).optional().describe("A simple-icons slug, drawn where a logo fits better than an icon."),
75
+ description: z.string().min(1).max(300).describe("One sentence under the chips on what the check looks at and when it passes."),
76
+ sentence: z
77
+ .string()
78
+ .min(1)
79
+ .max(200)
80
+ .describe(
81
+ "What one source of this kind watches, in a few words, for the automation's row, its approval card and the wake: `{key}` puts a parameter in, and a `[…]` segment is left out when a parameter it names is absent or off, like `GitHub releases of {repo}[ (prereleases too){prereleases}]`. A switch puts nothing in: it only keeps its segment.",
82
+ ),
83
+ fields: z.array(WatchKindFieldSchema).max(12).describe("Its parameters, in the order the composer draws them."),
84
+ capabilities: z
85
+ .array(z.string().min(1))
86
+ .optional()
87
+ .describe(
88
+ "Ids of this extension's own capability cards whose credential-gateway addresses each check is handed, as the automation's role reaches them: a GitHub card for a private repository's releases. Never a credential itself.",
89
+ ),
90
+ });
91
+
92
+ export const WatchKindContributionSchema = WatchKindDeclarationSchema
93
+ .superRefine((kind, ctx) => {
94
+ const keys = kind.fields.map((field) => field.key);
95
+ const doubled = keys.find((key, index) => keys.indexOf(key) !== index);
96
+ if (doubled !== undefined) {
97
+ ctx.addIssue({ code: "custom", path: ["fields"], message: `the field "${doubled}" is declared twice` });
98
+ }
99
+ const unknown = sentenceKeys(kind.sentence).find((key) => !keys.includes(key));
100
+ if (unknown !== undefined) {
101
+ ctx.addIssue({ code: "custom", path: ["sentence"], message: `the sentence names "{${unknown}}", which is none of the kind's fields` });
102
+ }
103
+ for (const [index, field] of kind.fields.entries()) {
104
+ if (field.type === "switch" && (field.required === true || field.pattern !== undefined || field.maxLength !== undefined)) {
105
+ ctx.addIssue({ code: "custom", path: ["fields", index], message: `a switch is never required and has no pattern or length` });
106
+ }
107
+ }
108
+ })
109
+ .meta({ power: { key: "watch-kind:${id}", sentence: 'its backend checks "${label}" watches for the sandbox\'s automations' } });
110
+ export type WatchKindContribution = z.infer<typeof WatchKindContributionSchema>;
111
+
112
+ // What renders a sentence or checks parameters: the declaration, with or without the parts only its manifest carries.
113
+ export type DeclaredWatchKind = Pick<WatchKindContribution, "id" | "sentence" | "fields">;
114
+
115
+ const present = (value: WatchParamValue | undefined): boolean => value !== undefined && value !== false && value !== "";
116
+ // A text parameter's words; a switch, on or off, puts none in.
117
+ const wordsOf = (value: WatchParamValue | undefined): string => (value === undefined || value === true || value === false ? "" : value);
118
+
119
+ /**
120
+ * One source's sentence, as its kind declares it: `npm bun@>=1.4.3`, `GitHub releases of oven-sh/bun`. A kind nobody
121
+ * declares here reads as its id and its parameters, so a source whose extension is off still says what it was.
122
+ */
123
+ export const watchSentence = (kind: DeclaredWatchKind | undefined, params: WatchParams & { readonly kind: string }): string => {
124
+ if (kind === undefined) {
125
+ const named = Object.entries(params).filter(([key, value]) => key !== "kind" && present(value));
126
+ return named.length === 0 ? params.kind : `${params.kind} ${named.map(([key, value]) => (value === true ? key : `${key}=${wordsOf(value)}`)).join(" ")}`;
127
+ }
128
+ const fill = (text: string): string => text.replace(PLACEHOLDER, (_whole, key: string) => wordsOf(params[key]));
129
+ return fill(kind.sentence.replace(SEGMENT, (_whole, inner: string) => (sentenceKeys(inner).every((key) => present(params[key])) ? inner : ""))).trim();
130
+ };
131
+
132
+ // One field's value as saving accepts it, each refusal naming the field.
133
+ const fieldSchema = (field: WatchKindField): z.ZodType => {
134
+ if (field.type === "switch") {
135
+ return z.boolean({ error: `${field.label} is on or off` }).optional();
136
+ }
137
+ const max = field.maxLength ?? TEXT_MAX;
138
+ let text = z
139
+ .string({ error: `${field.label} ${field.required === true ? "is required" : "takes text"}` })
140
+ .refine((value) => value.trim() !== "", `${field.label} is empty`)
141
+ .refine((value) => value.length <= max, `${field.label} is longer than ${max} characters`);
142
+ if (field.pattern !== undefined && compiles(field.pattern)) {
143
+ const pattern = new RegExp(field.pattern, "u");
144
+ text = text.refine((value) => pattern.test(value), field.patternHint === undefined ? `${field.label} does not look right` : `${field.label} must look like ${field.patternHint}`);
145
+ }
146
+ return field.required === true ? text : text.optional();
147
+ };
148
+
149
+ /** The parameters a kind takes, as one schema: its fields, and nothing it does not declare. */
150
+ export const watchParamsSchema = (kind: DeclaredWatchKind): z.ZodType<Readonly<Record<string, WatchParamValue | undefined>>> => {
151
+ const takes = kind.fields.map((field) => field.key).join(", ");
152
+ // SAFETY: every field's schema above answers a string, a boolean or nothing, so the object answers that record.
153
+ return z.strictObject(Object.fromEntries(kind.fields.map((field) => [field.key, fieldSchema(field)])), {
154
+ error: (issue) => (issue.code === "unrecognized_keys" ? `a ${kind.id} watch has no ${issue.keys.join(", ")}${takes === "" ? "" : `: it takes ${takes}`}` : undefined),
155
+ }) as z.ZodType<Readonly<Record<string, WatchParamValue | undefined>>>;
156
+ };
157
+
158
+ /**
159
+ * Why a source's parameters do not fit its kind's fields, in a sentence naming the field, or undefined when they do:
160
+ * what saving refuses, the composer says at the box and the command says before it asks.
161
+ */
162
+ export const watchParamsProblem = (kind: DeclaredWatchKind, params: WatchParams): string | undefined => {
163
+ const { kind: _kind, ...rest } = params;
164
+ return watchParamsSchema(kind).safeParse(rest).error?.issues[0]?.message;
165
+ };
166
+
167
+ export const watchKindsPoint = {
168
+ name: "watchKinds",
169
+ description:
170
+ "Ready-made checks an automation can name instead of a guard command: a package's version, a service's newest release. Your backend answers each check (`api.checks.serve(id, handler)`), and the sandbox runs it on the automation's schedule with no shell and no model, firing only when it passes or when what it saw changed. The composer, the `automations` command and the approval card draw each kind from this declaration. Needs a `server` bundle.",
171
+ schema: z.array(WatchKindContributionSchema),
172
+ } as const satisfies ContributionPoint;