apps 1.0.0-beta.4 → 2.0.0-next.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 (90) hide show
  1. package/README.md +10 -48
  2. package/check-publish.mjs +7 -0
  3. package/package.json +27 -56
  4. package/src/Access.ts +37 -0
  5. package/src/Accounts.ts +468 -0
  6. package/src/App.ts +11 -0
  7. package/src/Ask.ts +156 -0
  8. package/src/Changes.ts +13 -0
  9. package/src/Http.ts +30 -0
  10. package/src/Provider.ts +146 -0
  11. package/src/Session.ts +52 -0
  12. package/src/Settings.ts +164 -0
  13. package/src/contract.ts +852 -0
  14. package/src/css-modules.d.ts +2 -0
  15. package/src/desktop/Desktop.ts +192 -0
  16. package/src/desktop/bridge.ts +62 -0
  17. package/src/desktop/errors.ts +88 -0
  18. package/src/desktop/index.ts +15 -0
  19. package/src/entry.ts +48 -0
  20. package/src/index.ts +16 -4
  21. package/src/internal/defects.ts +62 -0
  22. package/src/internal/files.ts +369 -0
  23. package/src/internal/host.ts +17 -0
  24. package/src/internal/query.ts +114 -0
  25. package/src/internal/records.ts +838 -0
  26. package/src/internal/retention.ts +87 -0
  27. package/src/internal/retries.ts +185 -0
  28. package/src/internal/telemetry.ts +167 -0
  29. package/src/migrations.ts +110 -0
  30. package/src/page/Accounts.ts +27 -0
  31. package/src/page/Changes.ts +126 -0
  32. package/src/page/Session.ts +46 -0
  33. package/src/page/client.ts +107 -0
  34. package/src/page/errors.ts +15 -0
  35. package/src/page/http.ts +21 -0
  36. package/src/page/index.ts +18 -0
  37. package/src/page/paths.ts +22 -0
  38. package/src/providers/anthropic.ts +26 -0
  39. package/src/providers/github.ts +49 -0
  40. package/src/providers/google.ts +67 -0
  41. package/src/providers/openai.ts +62 -0
  42. package/src/providers/slack.ts +81 -0
  43. package/src/runtime.ts +1540 -0
  44. package/src/testing.ts +660 -0
  45. package/src/text-modules.d.ts +5 -0
  46. package/src/theme.css +50 -0
  47. package/dist/authoring/index.d.ts +0 -422
  48. package/dist/authoring/index.js +0 -36
  49. package/dist/chunk-2DVKSPQH.js +0 -312
  50. package/dist/chunk-4OZFMCTT.js +0 -17
  51. package/dist/chunk-535V5K64.js +0 -155
  52. package/dist/chunk-B7NEUIJL.js +0 -14
  53. package/dist/chunk-DP6UJCMX.js +0 -27
  54. package/dist/chunk-QA72XJZU.js +0 -41
  55. package/dist/chunk-S5KFP4JQ.js +0 -20
  56. package/dist/chunk-XYT6GZ7M.js +0 -99
  57. package/dist/http/index.d.ts +0 -9
  58. package/dist/http/index.js +0 -6
  59. package/dist/index.d.ts +0 -4
  60. package/dist/index.js +0 -48
  61. package/dist/manifest/contract.d.ts +0 -63
  62. package/dist/manifest/contract.js +0 -8
  63. package/dist/manifest/index.d.ts +0 -20
  64. package/dist/manifest/index.js +0 -16
  65. package/dist/mcp/client.d.ts +0 -9
  66. package/dist/mcp/index.d.ts +0 -11
  67. package/dist/mcp/index.js +0 -7
  68. package/dist/openapi/index.d.ts +0 -14
  69. package/dist/openapi/index.js +0 -7
  70. package/dist/openapi/mapper.d.ts +0 -7
  71. package/dist/runner/index.d.ts +0 -4
  72. package/dist/runner/index.js +0 -66
  73. package/dist/runner/protocol.d.ts +0 -33
  74. package/dist/runner/protocol.js +0 -8
  75. package/dist/runtime/index.d.ts +0 -83
  76. package/dist/runtime/index.js +0 -12
  77. package/dist/workerd/index.d.ts +0 -7
  78. package/dist/workerd/index.js +0 -10
  79. package/src/authoring/index.ts +0 -686
  80. package/src/http/index.ts +0 -26
  81. package/src/manifest/contract.ts +0 -64
  82. package/src/manifest/index.ts +0 -156
  83. package/src/mcp/client.ts +0 -59
  84. package/src/mcp/index.ts +0 -42
  85. package/src/openapi/index.ts +0 -70
  86. package/src/openapi/mapper.ts +0 -25
  87. package/src/runner/index.ts +0 -80
  88. package/src/runner/protocol.ts +0 -54
  89. package/src/runtime/index.ts +0 -554
  90. package/src/workerd/index.ts +0 -17
@@ -0,0 +1,852 @@
1
+ /**
2
+ * The contract between Executor's app host and an app built with `apps`.
3
+ *
4
+ * Plain TypeScript only: no Effect type crosses it, because the app and the
5
+ * platform each run their own copy of Effect. Values that cross are structured
6
+ * clone data, `Request`/`Response`/`ReadableStream`, or RPC stubs.
7
+ *
8
+ * How an app is loaded:
9
+ *
10
+ * - The app's bundle is loaded with Worker Loader. Its main module exports a
11
+ * Durable Object class named {@link APP_CLASS} (see {@link AppObject}), and
12
+ * a default `WorkerEntrypoint` ({@link AppEntrypoint}) for what needs no
13
+ * database: `describe()`.
14
+ * - The host runs that class as a facet of its own Durable Object, so the app
15
+ * owns the facet's SQLite database directly. SQL is not in this contract.
16
+ * - The Worker Loader `env` carries {@link AppEnv}: the capability object
17
+ * ({@link HostCapabilities}, usually an RPC stub) and a few plain values.
18
+ * - Facets cannot set alarms (workerd: "Facets currently cannot set alarms"),
19
+ * so the host's object holds the alarm. The app says when it next wants
20
+ * {@link AppObject.wake} through {@link HostClock.setWake}, and `wake()`
21
+ * returns the same time.
22
+ * - The host decides when the app goes idle. After any call into the app it
23
+ * asks {@link AppObject.status}; when nothing is in flight, no call is open
24
+ * and `next` is more than about 2 s away, it arms its alarm for `next` and
25
+ * aborts the facet (`ctx.facets.abort`). The app keeps nothing in memory
26
+ * that it needs later, and starts again from its database at any moment.
27
+ */
28
+
29
+ /** Bumped on any incompatible change. An app reports the version it was built with. */
30
+ export const CONTRACT_VERSION = 1 as const;
31
+ export type ContractVersion = typeof CONTRACT_VERSION;
32
+
33
+ /** The export name of the app's Durable Object class in its main module. */
34
+ export const APP_CLASS = "App" as const;
35
+
36
+ /**
37
+ * The request header that carries the caller's identity, as JSON
38
+ * ({@link CallerIdentity}). The host sets it on requests it forwards and
39
+ * removes it from every request that arrives from outside.
40
+ */
41
+ export const IDENTITY_HEADER = "x-executor-identity" as const;
42
+
43
+ /**
44
+ * The request header that says how a call reached the app, as JSON
45
+ * ({@link CallContext}). Like {@link IDENTITY_HEADER}, only the host writes
46
+ * it, at the one place it calls into the app, after deleting any header of
47
+ * that name from the incoming request. The host also writes a W3C
48
+ * `traceparent` there, so the app's spans join the trace of the host's record
49
+ * of the call; Effect's HTTP server continues it with no app code.
50
+ */
51
+ export const CALL_HEADER = "x-executor-call" as const;
52
+
53
+ export interface CallContext {
54
+ /** The host's id for this call: the key of its record. */
55
+ readonly invocation: string;
56
+ /**
57
+ * How the call came: `call` or `execute` (an agent through the gateway's tool of that name), `agent`
58
+ * (the gateway, by another way), `request` (a signed-in caller at the app's address), `public`,
59
+ * `internal` (Executor itself, such as listing tools at deploy).
60
+ */
61
+ readonly via: string;
62
+ /** The gateway's reference for the call (`call_…`), where it has one. */
63
+ readonly reference: string | null;
64
+ /**
65
+ * What the call is, decided by the host from who made it, never from the request's own headers:
66
+ * from the gateway, `tool` or `mcp` (its own MCP client wrote the routing headers) or `internal`;
67
+ * from the app's address, always `request`.
68
+ */
69
+ readonly kind: "tool" | "mcp" | "request" | "internal";
70
+ /** The tool's name, the MCP method, or the request's method and path. */
71
+ readonly name: string;
72
+ /** The approval request (`apr_…`) a tool call runs under, when a person approved it first. */
73
+ readonly approval?: string | null | undefined;
74
+ }
75
+
76
+ export interface AppObject {
77
+ /**
78
+ * Every HTTP request for the app: `/mcp`, its routes, the page's API.
79
+ * Streams both ways. The caller, if any, is in {@link IDENTITY_HEADER}.
80
+ */
81
+ fetch(request: Request): Promise<Response>;
82
+ /**
83
+ * Background work is due (the host's alarm fired). Runs everything due now,
84
+ * then returns its status and what it recorded. The host sets its next alarm
85
+ * from `status.next`.
86
+ */
87
+ wake(): Promise<Settled>;
88
+ /**
89
+ * {@link status}, together with everything the app has recorded since it
90
+ * was last asked: spans, logs, run updates and step attempts. The host calls
91
+ * it wherever it decides whether to let the app go, and stores the batch
92
+ * before it aborts the app, so the last batch is never lost to an abort.
93
+ */
94
+ settle(): Promise<Settled>;
95
+ /**
96
+ * The platform's own cleanup and nothing else: removes ended runs past their retention from
97
+ * the app's database, as {@link wake} does, but starts none of the app's code and runs no due
98
+ * work, so it adds no data. It keeps removing until nothing is left to remove or a few seconds
99
+ * have passed. The host calls it while the app's database is full, and reads
100
+ * `status.databaseBytes` to see whether the app is back under its limit.
101
+ */
102
+ cleanup(): Promise<Settled>;
103
+ /**
104
+ * Whether anything is in flight and when the next work is due. Cheap: no
105
+ * start-up, no I/O beyond the app's own database. The host asks after every
106
+ * call to decide whether to let the app go.
107
+ */
108
+ status(): Promise<AppStatus>;
109
+ /** Run the app's `migrations/`. Called at deploy, after `describe()`, before the version takes traffic. */
110
+ migrate(): Promise<MigrateResult>;
111
+ /**
112
+ * An account was linked, or is about to be unlinked. Runs the app's hooks. For a `linked` event
113
+ * the app first reads the account's profile (see `checkAccount`), gives the hook the external id
114
+ * it found, and returns the profile with the result.
115
+ */
116
+ accountEvent(event: AccountEvent): Promise<AccountEventResult>;
117
+ /**
118
+ * Read one linked account's profile, inside the app: a GET of the provider's declared
119
+ * `profile.url` with the account's token, the declared fields picked from the JSON reply. The
120
+ * host stores the answer as display text and never makes this request itself. A refusal here
121
+ * (401, 403) is reported as `failed`; it does not report the token as rejected.
122
+ */
123
+ checkAccount(account: AccountRef): Promise<Result<AccountProfile>>;
124
+ /** Run the app's own check of a setting it declared with a check. */
125
+ check(input: { readonly setting: string }): Promise<Result<CheckResult>>;
126
+ /**
127
+ * Cancel a run: a workflow is interrupted (Effect's `WorkflowEngine.interrupt`);
128
+ * a scheduled job's slot is forgotten, so it stops retrying. Optional until the
129
+ * runtime implements it; the host treats a missing method as `Unsupported`.
130
+ */
131
+ cancelRun?(run: RunRef): Promise<Result<RunControlResult>>;
132
+ /**
133
+ * Run again from the start. A workflow is forgotten by the engine and executed
134
+ * afresh with the payload it was first started with, so steps that had
135
+ * succeeded run again. A scheduled job runs now (see {@link runJob}).
136
+ */
137
+ rerunRun?(run: RunRef): Promise<Result<RunControlResult>>;
138
+ /** Run a scheduled job now, outside its schedule. Its schedule is unchanged. */
139
+ runJob?(job: { readonly name: string }): Promise<Result<RunControlResult>>;
140
+ /**
141
+ * A read-only query over the app's own database, inside a transaction that is
142
+ * always rolled back, bounded by the request's limits.
143
+ */
144
+ query?(request: QueryRequest): Promise<Result<QueryResult>>;
145
+ }
146
+
147
+ /** One run: a workflow execution, or one slot of a scheduled job. */
148
+ export type RunRef =
149
+ | { readonly kind: "workflow"; readonly workflow: string; readonly executionId: string }
150
+ /** `slot` is the slot's time as an ISO string, as the job's runs carry it. */
151
+ | { readonly kind: "scheduled"; readonly job: string; readonly slot: string };
152
+
153
+ export interface RunControlResult {
154
+ /** The run that now stands for the request: for `runJob`, the new slot. */
155
+ readonly run: RunRef;
156
+ /** What the app did: `cancelled`, `restarted`, `started`. */
157
+ readonly action: "cancelled" | "restarted" | "started";
158
+ }
159
+
160
+ export interface QueryRequest {
161
+ /** One SQL statement. Writes are rolled back; a second statement is refused. */
162
+ readonly sql: string;
163
+ readonly params?: ReadonlyArray<string | number | null> | undefined;
164
+ /** Stop after this many rows. */
165
+ readonly maxRows: number;
166
+ /** Stop once the rows read so far encode to more than this many bytes of JSON. */
167
+ readonly maxBytes: number;
168
+ /** Cut any one string value to this many characters. */
169
+ readonly maxCellChars: number;
170
+ }
171
+
172
+ export interface QueryResult {
173
+ readonly columns: ReadonlyArray<string>;
174
+ readonly rows: ReadonlyArray<ReadonlyArray<unknown>>;
175
+ /** A limit stopped the read before the last row. */
176
+ readonly truncated: boolean;
177
+ /** As SQLite counted them, for the rows read before stopping. */
178
+ readonly rowsRead: number;
179
+ }
180
+
181
+ /** The bundle's default export, a `WorkerEntrypoint`: what needs no object and no database. */
182
+ export interface AppEntrypoint {
183
+ /**
184
+ * What the app declares in code. Called at deploy, before `migrate()`.
185
+ * Needs no settings, no accounts and no database.
186
+ */
187
+ describe(): Promise<AppDescription>;
188
+ }
189
+
190
+ export interface AppStatus {
191
+ /**
192
+ * Background work is executing or about to: a workflow body or scheduled
193
+ * run in progress, start-up still writing its first schedule, or a write to
194
+ * the job tables in the last moments. Open calls are not included: the host
195
+ * counts its own calls (a streaming response until its body ends), and
196
+ * `openCalls` says how many the app has. The host must not abort the app
197
+ * while this is true or a call is open. A host instance that did not open
198
+ * those calls (a fresh instance after the old one was replaced) learns them
199
+ * only from `openCalls`: it must not let the copy go while `openCalls > 0`.
200
+ */
201
+ readonly inFlight: boolean;
202
+ /**
203
+ * Calls into the app's `fetch` that have not ended: a streamed response until
204
+ * its body has been sent or the client went away. The host's own calls
205
+ * (`wake`, `settle`, `migrate`, ...) are not counted. While it is above 0,
206
+ * `askAgainAt` is set, so the host asks again without polling.
207
+ */
208
+ readonly openCalls: number;
209
+ /** Why, for logs: `workflow`, `due`, `starting`, `writing`, `scheduling`, `needs-setup`, `failed`. */
210
+ readonly reasons: ReadonlyArray<string>;
211
+ /** Epoch milliseconds of the next due work, or `null` when nothing is scheduled. */
212
+ readonly next: number | null;
213
+ /**
214
+ * While `inFlight` or calls are open, when the host should ask again (epoch milliseconds), so
215
+ * it need not poll: soon for work that settles in moments (start-up, a job
216
+ * storing its next run), later for a workflow body or a run in progress. The
217
+ * app also calls `clock.setWake(now)` the moment busy work settles, so the
218
+ * host can decide then. `null` when not in flight and no call is open.
219
+ */
220
+ readonly askAgainAt: number | null;
221
+ /**
222
+ * Set when the app's code could not start (its Layer failed to build) on the
223
+ * last attempt. While set, `inFlight` is false and `next` is null: nothing
224
+ * runs until the cause is fixed, so the host lets the app go and does not
225
+ * retry it in a loop. The next call into the app tries again (after a
226
+ * missing setting has been set, say) and clears it on success.
227
+ */
228
+ readonly failure: StartFailure | null;
229
+ /**
230
+ * Stored runs for code this version does not have (a workflow or scheduled
231
+ * job removed, or rolled back past), by workflow or job: kept, not due, and
232
+ * not woken for. A later version that registers that code again picks them
233
+ * up. Empty when there are none.
234
+ */
235
+ readonly parked: ReadonlyArray<ParkedRuns>;
236
+ /**
237
+ * The size of the app's own database, in bytes (SQLite's page count times its page size: no
238
+ * table is read). On a host where the app's database shares a storage limit with the host's
239
+ * own object, the host stops the app before the shared limit is reached. `null` where the
240
+ * runtime cannot read it.
241
+ */
242
+ readonly databaseBytes: number | null;
243
+ /**
244
+ * An id the runtime makes once per isolate (on its first answer). The host compares it with
245
+ * the last answer for the same loaded build: a change means the platform gave the app a fresh
246
+ * isolate (on Cloudflare, silently, after it ran out of memory).
247
+ */
248
+ readonly isolate: string;
249
+ }
250
+
251
+ /** Runs of one workflow or scheduled job that this version does not have. */
252
+ export interface ParkedRuns {
253
+ /** `entity`: an entity type that is neither (an app's own `Entity`). */
254
+ readonly kind: "workflow" | "scheduled-job" | "entity";
255
+ /** The workflow's name, the job's name, or the entity type. */
256
+ readonly name: string;
257
+ /** Workflow executions, scheduled slots, or entities waiting. */
258
+ readonly runs: number;
259
+ }
260
+
261
+ /** Why the app could not start. */
262
+ export interface StartFailure {
263
+ /**
264
+ * - `missing-setting`: the app read a setting or secret that has no value
265
+ * (`settings` names it). Not a crash: the app is waiting for setup.
266
+ * - `invalid-setting`: a setting has a value the app could not read.
267
+ * - `start-failed`: anything else; `message` has the app's own error.
268
+ */
269
+ readonly reason: "missing-setting" | "invalid-setting" | "start-failed";
270
+ /** The failure's text, for a person or an agent to act on. */
271
+ readonly message: string;
272
+ /** The settings involved, by name, for `missing-setting` and `invalid-setting`. */
273
+ readonly settings: ReadonlyArray<string>;
274
+ /** Epoch milliseconds of the attempt. */
275
+ readonly at: number;
276
+ }
277
+
278
+ /**
279
+ * The header on the app's 503 reply when it cannot start; its value is the
280
+ * `StartFailure.reason`. The body is JSON: {@link StartFailureBody}.
281
+ */
282
+ export const START_FAILURE_HEADER = "x-executor-start-failure" as const;
283
+
284
+ export interface StartFailureBody {
285
+ readonly error: "app_not_started";
286
+ readonly failure: StartFailure;
287
+ /** One sentence on what would fix it. */
288
+ readonly hint: string;
289
+ }
290
+
291
+ /** What `wake()` and `settle()` return: the status, and the drained batch (`null` when nothing was recorded). */
292
+ export interface Settled {
293
+ readonly status: AppStatus;
294
+ readonly batch: TelemetryBatch | null;
295
+ /**
296
+ * The app as it started, with its real settings: the scheduled jobs and workflows that
297
+ * actually registered, its public paths, accounts, settings and MCP server. Sent once, in the
298
+ * first `settle()` or `wake()` answer after each start (a settings change restarts the app).
299
+ * The host replaces what `describe()` said at deploy, which ran with no settings, with it.
300
+ */
301
+ readonly description?: AppDescription | undefined;
302
+ }
303
+
304
+ export interface MigrateResult {
305
+ /** Migrations applied by this call, in order, as `[id, name]`. Empty when already current. */
306
+ readonly applied: ReadonlyArray<readonly [id: number, name: string]>;
307
+ /**
308
+ * Migrations the app's database has run that this version's source doesn't have, as
309
+ * `[id, name]`: the database keeps their schema, so code written before them may fail.
310
+ * Empty when none.
311
+ */
312
+ readonly unknown: ReadonlyArray<readonly [id: number, name: string]>;
313
+ }
314
+
315
+ export interface AppDescription {
316
+ readonly contractVersion: ContractVersion;
317
+ /** The version of `apps` the app was built with. */
318
+ readonly appsVersion: string;
319
+ /** The version of `effect` bundled with the app. */
320
+ readonly effectVersion: string;
321
+ /**
322
+ * The app's MCP server, `null` when it mounts none. `"unknown"` when the
323
+ * app's Layer could not be built without a database or settings (see
324
+ * `unknownReason`): it is known after the first start.
325
+ */
326
+ readonly mcp: McpDescription | null | "unknown";
327
+ readonly accounts: ReadonlyArray<AccountDeclaration>;
328
+ readonly settings: ReadonlyArray<SettingDeclaration>;
329
+ /** `"unknown"` under the same condition as `mcp`. */
330
+ readonly scheduledJobs: ReadonlyArray<ScheduledJobDescription> | "unknown";
331
+ /** Why `mcp` and `scheduledJobs` are unknown, or `null`. */
332
+ readonly unknownReason: string | null;
333
+ /**
334
+ * The same cause, classified, when the app's Layer could not be built with no
335
+ * settings: a deploy can show "needs setup: STRIPE_SECRET" before it starts.
336
+ */
337
+ readonly startFailure: StartFailure | null;
338
+ /** Path patterns the app marks public (no sign-in). */
339
+ readonly publicPaths: ReadonlyArray<string>;
340
+ /**
341
+ * How many hooks the app registered to run when an account is linked and before one is
342
+ * unlinked (`Accounts.hooks`). Absent in a description from before this field existed.
343
+ */
344
+ readonly hooks?: { readonly onLink: number; readonly onUnlink: number } | undefined;
345
+ /** The app's HTTP limits (`Http.declare`). `firstResponseMs: null` takes the host's default. */
346
+ readonly http: { readonly firstResponseMs: number | null };
347
+ /**
348
+ * The names of the workflows the app registers. `"unknown"` under the same
349
+ * condition as `mcp`. Optional until the runtime reports it.
350
+ */
351
+ readonly workflows?: ReadonlyArray<string> | "unknown" | undefined;
352
+ }
353
+
354
+ export interface McpDescription {
355
+ readonly path: string;
356
+ readonly name: string;
357
+ readonly version: string;
358
+ readonly instructions: string | null;
359
+ }
360
+
361
+ export interface ScheduledJobDescription {
362
+ readonly name: string;
363
+ /** The cron expression's fields as given to `Cron` (seconds first when present). */
364
+ readonly cron: string;
365
+ readonly timeZone: string | null;
366
+ /** Epoch milliseconds of the next slot after now. */
367
+ readonly next: number | null;
368
+ /**
369
+ * `ClusterCron`'s own flag. When `false` (Effect's default) each slot is its
370
+ * own run, and a run that outlasts its interval overlaps the next one
371
+ * whenever the runner starts while it is due or running: Effect's start-up
372
+ * singleton schedules the slot after "now" beside the run. On Executor every
373
+ * wake from idle is a runner start, so this happens with no crash or kill.
374
+ * When `true`, runs never overlap and missed slots are caught up in order.
375
+ * Either is a valid choice; reported for the host to show, not to refuse.
376
+ */
377
+ readonly calculateNextRunFromPrevious: boolean;
378
+ /** How old a missed slot may be and still run, in milliseconds. */
379
+ readonly skipIfOlderThanMs: number;
380
+ }
381
+
382
+ export interface AccountDeclaration {
383
+ readonly name: string;
384
+ /** `user`: each member links their own. `app`: an admin links one for the app. */
385
+ readonly owner: "user" | "app";
386
+ readonly provider: ProviderDescription;
387
+ }
388
+
389
+ /**
390
+ * A linkable service, as data. `auth` uses the same shape as today's provider
391
+ * declarations, so a provider declared the same way gets the same identity and
392
+ * the accounts people already linked are offered for it.
393
+ */
394
+ export interface ProviderDescription {
395
+ /** Shown to people: "GitHub". */
396
+ readonly name: string;
397
+ /** Sign-in methods by name, e.g. `{ oauth: { type: "oauth2", ... } }` or `{ key: { type: "secrets", ... } }`. */
398
+ readonly auth: Readonly<Record<string, ProviderAuthMethod>>;
399
+ /**
400
+ * Hosts the credential is meant for. `account.http` attaches the token only to these unless the
401
+ * author asks otherwise; the profile address must be on one of them.
402
+ */
403
+ readonly hosts?: ReadonlyArray<string> | undefined;
404
+ /** How Executor reads who an account is, and checks that it still works. */
405
+ readonly profile?: ProviderProfile | undefined;
406
+ }
407
+
408
+ export type ProviderAuthMethod = OAuth2Method | SecretsMethod;
409
+
410
+ export interface OAuth2Method {
411
+ readonly type: "oauth2";
412
+ /** An issuer to discover endpoints from (RFC 8414), or the endpoints themselves. */
413
+ readonly discover?: string | undefined;
414
+ readonly authorizationUrl?: string | undefined;
415
+ readonly tokenUrl?: string | undefined;
416
+ readonly revocationUrl?: string | undefined;
417
+ readonly scopes?: ReadonlyArray<string> | undefined;
418
+ readonly authorizationParams?: Readonly<Record<string, string>> | undefined;
419
+ readonly pkce?: false | undefined;
420
+ /** JSON Schema of the token response's fields the app reads. */
421
+ readonly response: Readonly<Record<string, unknown>>;
422
+ readonly [option: string]: unknown;
423
+ }
424
+
425
+ export interface SecretsMethod {
426
+ readonly type: "secrets";
427
+ /** Shown to people: "API key". */
428
+ readonly label: string;
429
+ /** Markdown shown above the fields. */
430
+ readonly guide?: string | undefined;
431
+ /** JSON Schema (draft 2020-12) of the fields a person enters. */
432
+ readonly fields: Readonly<Record<string, unknown>>;
433
+ /** Fields that are not secret, so forms show them. */
434
+ readonly plain?: ReadonlyArray<string> | undefined;
435
+ readonly [option: string]: unknown;
436
+ }
437
+
438
+ /**
439
+ * A request Executor makes with the account's token to learn who it is (the
440
+ * health check). Only a request and a mapping: anything that needs code is the
441
+ * app's own `check`.
442
+ */
443
+ export interface ProviderProfile {
444
+ readonly url: string;
445
+ /** Where the token goes. Default: `authorization: Bearer <token>`. */
446
+ readonly header?: { readonly name: string; readonly scheme: string | null } | undefined;
447
+ /** Dot paths into the JSON reply. */
448
+ readonly map: {
449
+ readonly externalId?: string | undefined;
450
+ readonly displayName?: string | undefined;
451
+ readonly username?: string | undefined;
452
+ readonly email?: string | undefined;
453
+ readonly avatarUrl?: string | undefined;
454
+ readonly profileUrl?: string | undefined;
455
+ };
456
+ }
457
+
458
+ export interface SettingDeclaration {
459
+ readonly name: string;
460
+ /** `text`: a person types it. `secret`: a person pastes it, and it is never shown again. `generated`: Executor makes a random value once. */
461
+ readonly kind: "text" | "secret" | "generated";
462
+ readonly label: string | null;
463
+ readonly description: string | null;
464
+ readonly default: string | null;
465
+ /** The app answers `check({ setting })` for it. */
466
+ readonly checked: boolean;
467
+ }
468
+
469
+ export interface AccountEvent {
470
+ /** Stable for one link or unlink: a repeated delivery carries the same id. */
471
+ readonly id: string;
472
+ /** `linked`: after the link is saved. `unlinking`: before it is removed, while the token still works. */
473
+ readonly kind: "linked" | "unlinking";
474
+ /**
475
+ * Why it fired. `link` and `unlink`: a person linked or unlinked the account (or replaced it with
476
+ * another). `deploy`: a new version was activated, and every account already linked is offered
477
+ * to the link hook again, so a hook added in a later version also runs for accounts linked
478
+ * before it existed. `removed`: the account, or the app itself, is being
479
+ * removed from Executor.
480
+ */
481
+ readonly cause: "link" | "deploy" | "unlink" | "removed";
482
+ readonly account: LinkedAccount;
483
+ /**
484
+ * The trace the host recorded this delivery under: the app runs the hook in a span whose parent
485
+ * is `spanId` in `traceId`, so the hook's spans are reachable from the delivery's record.
486
+ */
487
+ readonly trace?: { readonly traceId: string; readonly spanId: string } | undefined;
488
+ }
489
+
490
+ export interface LinkedAccount extends AccountRef {
491
+ /** The account's name in Executor, e.g. "Work". */
492
+ readonly label: string;
493
+ /** The account's id at the provider, when its profile says. */
494
+ readonly externalId: string | null;
495
+ }
496
+
497
+ export type AccountEventResult =
498
+ | { readonly ok: true; readonly profile?: AccountProfile | undefined }
499
+ | {
500
+ readonly ok: false;
501
+ readonly error: ContractError;
502
+ readonly profile?: AccountProfile | undefined;
503
+ };
504
+
505
+ /**
506
+ * What an account's profile said, read by the app. `unchecked`: the provider declares no profile.
507
+ * `info` holds the declared fields (`externalId`, `displayName`, `username`, `email`, `avatarUrl`,
508
+ * `profileUrl`) as text; the host treats every value as untrusted display text.
509
+ */
510
+ export type AccountProfile =
511
+ | { readonly status: "ok"; readonly info: Readonly<Record<string, string>> }
512
+ | { readonly status: "failed"; readonly message: string }
513
+ | { readonly status: "unchecked" };
514
+
515
+ export interface CheckResult {
516
+ readonly status: "ok" | "failed";
517
+ readonly message: string | null;
518
+ }
519
+
520
+ /** The JSON value of {@link IDENTITY_HEADER}. */
521
+ export interface CallerIdentity {
522
+ readonly user: {
523
+ readonly id: string;
524
+ readonly name?: string | undefined;
525
+ readonly email?: string | undefined;
526
+ };
527
+ /** The organization the app is installed in. Local Executor, with one operator, sends `local`. */
528
+ readonly organization: { readonly id: string };
529
+ /**
530
+ * The caller's role in the organization, where the host knows one (hosted).
531
+ * Absent on local Executor.
532
+ */
533
+ readonly role?: "owner" | "admin" | "member" | undefined;
534
+ }
535
+
536
+ /** The Worker Loader `env` the host gives the app's worker. */
537
+ export interface AppEnv {
538
+ readonly EXECUTOR: HostCapabilities;
539
+ /** The installed app's id. */
540
+ readonly EXECUTOR_APP_ID: string;
541
+ /** The app's own public address, e.g. `https://my-app.example.com`. */
542
+ readonly EXECUTOR_APP_URL: string;
543
+ /** The contract version the host speaks. */
544
+ readonly EXECUTOR_CONTRACT_VERSION: number;
545
+ }
546
+
547
+ /**
548
+ * One capability object per loaded app. Every method returns plain data. A
549
+ * failure the app should handle comes back as `{ ok: false, error }`, never as
550
+ * a thrown error, so it keeps its shape across RPC.
551
+ */
552
+ export interface HostCapabilities {
553
+ readonly accounts: HostAccounts;
554
+ readonly settings: HostSettings;
555
+ readonly files: HostFiles;
556
+ readonly clock: HostClock;
557
+ readonly telemetry: HostTelemetry;
558
+ /** Present only where there is a shell. */
559
+ readonly process?: HostProcess | undefined;
560
+ /** Open pages of the app; absent on a host without pages. */
561
+ readonly pages?: HostPages | undefined;
562
+ }
563
+
564
+ export interface ContractError {
565
+ /** A stable machine-readable reason, e.g. `NotLinked`, `NotFound`. */
566
+ readonly reason: string;
567
+ readonly message: string;
568
+ /** Where a person can fix it, e.g. the page that links the account. */
569
+ readonly url?: string | undefined;
570
+ }
571
+
572
+ export type Result<A> =
573
+ | { readonly ok: true; readonly value: A }
574
+ | { readonly ok: false; readonly error: ContractError };
575
+
576
+ export type AccountOwner =
577
+ | { readonly kind: "user"; readonly userId: string }
578
+ | { readonly kind: "app" };
579
+
580
+ export interface AccountRef {
581
+ /** The name the app declared the account under. */
582
+ readonly name: string;
583
+ readonly owner: AccountOwner;
584
+ /**
585
+ * Executor's id for one linked account. Set on the account a hook receives,
586
+ * so its token is that account's even while another account replaces it.
587
+ */
588
+ readonly accountId?: string | undefined;
589
+ }
590
+
591
+ /**
592
+ * A fresh, real credential. `token` is what goes in `authorization: Bearer`:
593
+ * the OAuth access token, or the one secret of an API-key method. `fields` are
594
+ * every value the account holds (several for a method with more than one field).
595
+ */
596
+ export interface AccountCredential {
597
+ readonly token: string;
598
+ readonly fields: Readonly<Record<string, string>>;
599
+ /** Epoch milliseconds, when known. */
600
+ readonly expiresAt: number | null;
601
+ readonly scopes: ReadonlyArray<string>;
602
+ }
603
+
604
+ export interface AccountOwnerEntry {
605
+ readonly owner: AccountOwner;
606
+ /** The account's name in Executor, e.g. "Work". */
607
+ readonly label: string;
608
+ }
609
+
610
+ /**
611
+ * Error reasons: `NotLinked` (with `url`, the page to link it), `NeedsReconnection`
612
+ * (with `url`), `NotDeclared`, `Unavailable`.
613
+ */
614
+ export interface HostAccounts {
615
+ /**
616
+ * A fresh, real credential for the named account and owner. `caller` is the
617
+ * user the app is acting for, when there is one; Executor records each use.
618
+ */
619
+ token(
620
+ account: AccountRef,
621
+ use: {
622
+ /** The member the app says it acts for. */
623
+ readonly caller: string | null;
624
+ /**
625
+ * The host's id for the call the token is used in (`invocation` of the request's
626
+ * `CALL_HEADER`), so Executor records the caller it put on that call beside the claimed one.
627
+ */
628
+ readonly invocation?: string | null | undefined;
629
+ },
630
+ ): Promise<Result<AccountCredential>>;
631
+ /** Every owner who has linked the named account, for `.all`. */
632
+ owners(name: string): Promise<Result<ReadonlyArray<AccountOwnerEntry>>>;
633
+ /**
634
+ * The provider rejected `token`. Executor renews it (`renewed: true`: ask for
635
+ * a token again) or, when a renewed token is rejected too or the account
636
+ * cannot be renewed, marks it as needing reconnection.
637
+ */
638
+ rejected(account: AccountRef, token: string): Promise<Result<{ readonly renewed: boolean }>>;
639
+ }
640
+
641
+ export interface HostSettings {
642
+ /**
643
+ * The app's settings and secrets, by name, read into Effect's `Config`. A
644
+ * setting nobody has filled in and with no default is absent. `version`
645
+ * changes whenever a value does; the host restarts the app when it changes.
646
+ */
647
+ read(): Promise<
648
+ Result<{
649
+ readonly values: Readonly<Record<string, string>>;
650
+ readonly version: string;
651
+ /**
652
+ * The page where a person fills in the app's settings, named in the error for a missing one;
653
+ * null where this Executor has no settings page for the app.
654
+ */
655
+ readonly url: string | null;
656
+ }>
657
+ >;
658
+ }
659
+
660
+ export interface FileInfo {
661
+ readonly type: "File" | "Directory";
662
+ readonly size: number;
663
+ /** Epoch milliseconds. */
664
+ readonly mtime: number | null;
665
+ }
666
+
667
+ /**
668
+ * The operations behind `FileSystem`. Paths are absolute within the app's own
669
+ * storage (`/` is its root). Reasons: `NotFound`, `AlreadyExists`, `BadResource`,
670
+ * `TooLarge`, `Unsupported`.
671
+ */
672
+ export interface HostFiles {
673
+ read(path: string): Promise<Result<Uint8Array>>;
674
+ /** Streams the file's bytes. */
675
+ stream(
676
+ path: string,
677
+ options?: { readonly offset?: number; readonly length?: number },
678
+ ): Promise<Result<ReadableStream<Uint8Array>>>;
679
+ write(
680
+ path: string,
681
+ data: Uint8Array | ReadableStream<Uint8Array>,
682
+ options?: { readonly append?: boolean; readonly exclusive?: boolean },
683
+ ): Promise<Result<null>>;
684
+ stat(path: string): Promise<Result<FileInfo>>;
685
+ /** Names of the entries directly inside `path`. */
686
+ list(path: string): Promise<Result<ReadonlyArray<string>>>;
687
+ makeDirectory(path: string, options?: { readonly recursive?: boolean }): Promise<Result<null>>;
688
+ copy(from: string, to: string, options?: { readonly overwrite?: boolean }): Promise<Result<null>>;
689
+ rename(from: string, to: string): Promise<Result<null>>;
690
+ remove(path: string, options?: { readonly recursive?: boolean }): Promise<Result<null>>;
691
+ }
692
+
693
+ export interface HostClock {
694
+ /**
695
+ * When the app next wants `wake()`, in epoch milliseconds; `null` for never.
696
+ * Replaces the previous value. The host keeps it in its alarm.
697
+ */
698
+ setWake(at: number | null): Promise<void>;
699
+ }
700
+
701
+ export interface SpanRecord {
702
+ readonly traceId: string;
703
+ readonly spanId: string;
704
+ readonly parentSpanId: string | null;
705
+ readonly name: string;
706
+ readonly kind: "internal" | "server" | "client" | "producer" | "consumer";
707
+ /** Epoch nanoseconds, as decimal strings (bigint does not survive JSON). */
708
+ readonly startTime: string;
709
+ readonly endTime: string;
710
+ /** `interrupted`: ended by an interruption only (a cancel, a workflow suspending, the app being stopped). */
711
+ readonly status: "ok" | "error" | "interrupted";
712
+ readonly attributes: Readonly<Record<string, unknown>>;
713
+ readonly events: ReadonlyArray<{
714
+ readonly name: string;
715
+ readonly time: string;
716
+ readonly attributes: Readonly<Record<string, unknown>>;
717
+ }>;
718
+ }
719
+
720
+ export interface LogRecord {
721
+ /** Epoch milliseconds. */
722
+ readonly time: number;
723
+ readonly level: "Trace" | "Debug" | "Info" | "Warn" | "Error" | "Fatal";
724
+ readonly message: ReadonlyArray<unknown>;
725
+ readonly annotations: Readonly<Record<string, unknown>>;
726
+ readonly traceId: string | null;
727
+ readonly spanId: string | null;
728
+ }
729
+
730
+ export interface TelemetryBatch {
731
+ readonly spans: ReadonlyArray<SpanRecord>;
732
+ readonly logs: ReadonlyArray<LogRecord>;
733
+ /** Changes to runs, in the order they happened. */
734
+ readonly runs?: ReadonlyArray<RunUpdate> | undefined;
735
+ /** Attempts of workflow steps (activities), in the order they ended. */
736
+ readonly steps?: ReadonlyArray<StepAttempt> | undefined;
737
+ /** Spans, logs, runs and steps the app dropped because its buffer was full. */
738
+ readonly dropped?: number | undefined;
739
+ }
740
+
741
+ /** A typed error or defect, made plain. */
742
+ export interface RecordedError {
743
+ /** The error's `_tag`, or its class name, or `null`. */
744
+ readonly tag: string | null;
745
+ /** At most 1,000 characters. */
746
+ readonly message: string;
747
+ /** The error's own fields as JSON, at most 1,000 characters encoded; `null` when it has none. */
748
+ readonly detail: unknown;
749
+ }
750
+
751
+ /**
752
+ * - `running`: a workflow body or a scheduled run is executing.
753
+ * - `sleeping`: a workflow waits on a durable clock until `wakeAt`.
754
+ * - `waiting`: a workflow waits on something else (a deferred, a child).
755
+ * - `suspended`: a workflow with `Workflow.SuspendOnFailure` failed and waits for `resume` or a cancel.
756
+ * - `cancelling`: a cancel was sent; the run's final status follows from the result Effect stores.
757
+ * - `parked`: stored for a workflow or job this version does not register; it waits, untouched,
758
+ * for a version that registers it again. The error names what it waits for.
759
+ * - `retrying`: a scheduled run failed; Effect delivers the slot again until it is a day old.
760
+ * - `skipped`: a scheduled slot older than the job's `skipIfOlderThan` was dropped.
761
+ * - `failed`, `completed`, `cancelled`: ended.
762
+ */
763
+ export type RunStatus =
764
+ | "running"
765
+ | "sleeping"
766
+ | "waiting"
767
+ | "suspended"
768
+ | "cancelling"
769
+ | "parked"
770
+ | "retrying"
771
+ | "skipped"
772
+ | "failed"
773
+ | "completed"
774
+ | "cancelled";
775
+
776
+ export interface RunUpdate {
777
+ readonly run: RunRef;
778
+ readonly status: RunStatus;
779
+ /** Epoch milliseconds. */
780
+ readonly time: number;
781
+ /**
782
+ * The payload a workflow was started with, sent once with its first
783
+ * `running`. At most 4,096 bytes of JSON; a larger payload is replaced by
784
+ * `{ "truncated": true, "bytes": n }` (the app keeps the whole payload).
785
+ */
786
+ readonly payload?: unknown;
787
+ readonly error?: RecordedError | null | undefined;
788
+ /** Epoch milliseconds a sleeping workflow wakes at. */
789
+ readonly wakeAt?: number | null | undefined;
790
+ /** The trace that started the run, or the trace of this attempt. */
791
+ readonly traceId?: string | null | undefined;
792
+ /**
793
+ * The app removed this ended run's state from its database (its retention). The run's record
794
+ * stays, but the run can no longer be run again. The host reads only this flag and the time;
795
+ * `status` is not applied.
796
+ */
797
+ readonly stateCleared?: true | undefined;
798
+ }
799
+
800
+ export interface StepAttempt {
801
+ readonly run: { readonly workflow: string; readonly executionId: string };
802
+ /** The activity's name. */
803
+ readonly step: string;
804
+ /** Effect's attempt number for the activity, from 1. */
805
+ readonly attempt: number;
806
+ readonly status: "ok" | "error" | "suspended";
807
+ /**
808
+ * The engine returned a stored result without running the activity: a
809
+ * workflow body re-executing after a sleep or a `resume`. Not a new attempt.
810
+ */
811
+ readonly replayed: boolean;
812
+ readonly error: RecordedError | null;
813
+ /** Epoch milliseconds. */
814
+ readonly startTime: number;
815
+ readonly durationMs: number;
816
+ readonly traceId: string | null;
817
+ }
818
+
819
+ export interface HostTelemetry {
820
+ export(batch: TelemetryBatch): Promise<void>;
821
+ }
822
+
823
+ export interface HostPages {
824
+ /**
825
+ * The app's own data changed (a write to one of its tables, or the author's
826
+ * `Changes.notify`). The host tells every open page, which fetches again.
827
+ * Says nothing about what changed. The app calls it at most every few
828
+ * milliseconds; the host may coalesce.
829
+ */
830
+ changed(): Promise<void>;
831
+ }
832
+
833
+ export interface ProcessRequest {
834
+ readonly command: string;
835
+ readonly args: ReadonlyArray<string>;
836
+ readonly cwd?: string | undefined;
837
+ readonly env?: Readonly<Record<string, string>> | undefined;
838
+ readonly stdin?: ReadableStream<Uint8Array> | undefined;
839
+ }
840
+
841
+ export interface ProcessHandle {
842
+ readonly pid: number;
843
+ readonly stdout: ReadableStream<Uint8Array>;
844
+ readonly stderr: ReadableStream<Uint8Array>;
845
+ /** Resolves with the exit code once the process ends. */
846
+ exitCode(): Promise<number>;
847
+ kill(signal?: string): Promise<void>;
848
+ }
849
+
850
+ export interface HostProcess {
851
+ spawn(request: ProcessRequest): Promise<Result<ProcessHandle>>;
852
+ }