@segmentstream/ontology 0.102.0 → 0.105.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,47 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.105.0
4
+
5
+ The console can draw each workflow as a map. `ontologyWorkflows()` now reads every workflow's
6
+ code when the ontology builds: the steps its `"use workflow"` function calls in order, its waits
7
+ (`sleep`, hooks, webhooks), `agentTask`, branches (`if`, `switch`, early `return` and `throw`),
8
+ loops (including `do…while`), `Promise.all` groups and `try`/`catch`, following helpers the
9
+ project declares. For each step it keeps the comment above the function as its description and
10
+ the entity actions, record operations and connection requests its code calls. The service serves
11
+ it at `GET /api/ontology/workflows/:workflow/structure` to callers that may read the workflow's
12
+ runs. The reading never runs the code, never fails the build, and marks what it could not follow.
13
+
14
+ Write a comment above each `"use step"` function and above the statements of the workflow body
15
+ that need explaining: the console shows them on the map. The SDK now depends on `typescript` to
16
+ read the code at build time.
17
+
18
+ ## 0.104.0
19
+
20
+ The agent answers a website's visitors. `signUp` takes the channel `web` with `origins`, the
21
+ websites by exact origin: a browser on one of them signs its visitor up at
22
+ `POST /api/ontology/agent/visitors`, which creates a user holding the roles `signUp` gives `web`
23
+ and answers an agent token with a refresh token. The refresh token renews the agent token at the
24
+ ontology's OAuth token endpoint as client `agent-web`, which the service serves for visitors even
25
+ with `mcp: false`. A visitor's `onSignUp` that fails runs again before their next turn, as it does
26
+ on a messenger, and so does that of anyone sign-up created who talks to the agent from the app. Any other origin is refused with
27
+ `origin_not_allowed`; one network address may start 10 visitors an hour, and the workspace's cap on
28
+ new users and the agent's turn limits apply as to everyone `signUp` created. `check` refuses `web`
29
+ without origins, and an origin with a path, a wildcard, or `http` beyond `localhost`.
30
+
31
+ The agent's web channel answers browsers on any origin, since every request carries an agent token
32
+ as its bearer, never a cookie.
33
+
34
+ `useAgent({ app })` in `@segmentstream/app/agent` talks to the agent of the workspace app at `app`
35
+ from another website, as its visitor: it signs them up with their first message and keeps their
36
+ refresh token in the browser, so they stay the same user. `visitorToken(app)` gets the token
37
+ outside React and `forgetVisitorTokens()` starts over as a new visitor.
38
+
39
+ ## 0.103.0
40
+
41
+ The agent's temporary attachments accept `whatsapp` as a source, so files members send the agent
42
+ in WhatsApp are stored as Telegram's and Slack's are. The next `segmentstream-ontology migrate`
43
+ (every deploy runs it) widens the attachment table's source check; no data changes.
44
+
3
45
  ## 0.102.0
4
46
 
5
47
  The agent's limits for people who signed up now apply to the web. Each message a member sends from
package/README.md CHANGED
@@ -410,9 +410,14 @@ export default defineOntology({
410
410
  affected member has linked email before restoring an email-only deployment. `User.sendSignInLink`
411
411
  preserves Neon links in compatibility and dual mode; sole SegmentStream uses interactive central
412
412
  sign-in, preserving templates, reply routing and the requested landing path.
413
- - `signUp: { channels, roles, byChannel? }` opens sign-up to strangers on each listed channel:
414
- `email` (signing in to the app by email code), `telegram` (a first private message to the bot,
415
- or opening the Mini App) and `whatsapp` (a first message to the number). The new user holds
413
+ - `signUp: { channels, roles, byChannel?, origins? }` opens sign-up to strangers on each listed
414
+ channel: `email` (signing in to the app by email code), `telegram` (a first private message to
415
+ the bot, or opening the Mini App), `whatsapp` (a first message to the number) and `web` (a
416
+ visitor of a website `origins` lists, by exact origin, who writes to the agent there; `http` only
417
+ for `localhost` and `127.0.0.1`). `web` signs a visitor up at
418
+ `POST /api/ontology/agent/visitors`, which answers only browsers on those origins, at most 10 new
419
+ visitors per network address an hour, with an agent token and a refresh token that renews it at
420
+ the OAuth token endpoint as client `agent-web`. The new user holds
416
421
  exactly `roles`, declared roles passed as role objects or names, or the channel's own list in
417
422
  `byChannel`; `[]` grants nothing beyond what is later granted or shared. Sign-up writes them as
418
423
  ordinary role assignments in its own transaction, so one person's roles can be revoked or added
@@ -429,9 +434,9 @@ export default defineOntology({
429
434
  commits: before the first agent turn or Mini App session, and before an email user's first
430
435
  request. Every channel's roles must be able to run it, it cannot grant roles, and a failure
431
436
  leaves it pending for the next contact. Promote a person with an ordinary action that calls
432
- `User.grantRoles`. The manifest carries `sign_in.sign_up` (each channel's role wire names) and
433
- `sign_in.on_sign_up` only when declared; `signUpRolesOf(manifest, channel)` reads them and
434
- keeps unknown or malformed channels closed.
437
+ `User.grantRoles`. The manifest carries `sign_in.sign_up` (each channel's role wire names, and `origins` with
438
+ `web`) and `sign_in.on_sign_up` only when declared; `signUpRolesOf(manifest, channel)` and
439
+ `signUpOriginsOf(manifest)` read them and keep unknown or malformed channels closed.
435
440
  - `signIn: { policy }` decides who may become a member by signing in. `invited`, the
436
441
  default, admits only people whose email a member already has, from an invitation or a
437
442
  role grant; anyone else is answered 403 `not_invited`. `open` makes anyone who signs in a
package/dist/analyze.js CHANGED
@@ -11,7 +11,7 @@ import { REFERENCE_ANNOTATION, propertyDefinition, propertyOptionNames, unknownP
11
11
  import { EXPLICIT_GRANT_ENTITIES, generatedActionPermissions, grants, isAllowed, normalizePermission, parsePermission, parseWorkflowPermission, permissionOf, READ_VERB, rolesGranting, USER_IDENTITY_VERBS, USER_MEMBER_VERBS, WILDCARD, wildcardEntityCovers, WORKSPACE_SOURCE, WORKSPACE_SOURCE_PERMISSION, } from "./permissions.js";
12
12
  import { ON_DELETE, isRelationship } from "./relationship.js";
13
13
  import { isRole, member, role } from "./role.js";
14
- import { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, SIGN_UP_CHANNELS, SIGN_UP_CHAT_CHANNELS, isSignInPolicy, isSignUpChannel, } from "./sign-in.js";
14
+ import { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, SIGN_UP_CHANNELS, SIGN_UP_CHAT_CHANNELS, isSignInPolicy, isSignUpChannel, signUpOrigin, } from "./sign-in.js";
15
15
  import { emailOptions } from "./emails.js";
16
16
  import { AgentChat } from "./agent-chat.js";
17
17
  import { AgentReview } from "./agent-review.js";
@@ -1288,11 +1288,11 @@ function signUpOptions(config, signIn, declaredRoles, report) {
1288
1288
  return result;
1289
1289
  }
1290
1290
  if (!isPlainObject(options)) {
1291
- report("invalid-sign-in", "signUp", 'signUp takes { channels: ["telegram", "whatsapp", "email"], roles: [...] }.');
1291
+ report("invalid-sign-in", "signUp", 'signUp takes { channels: ["telegram", "whatsapp", "email", "web"], roles: [...] }.');
1292
1292
  return result;
1293
1293
  }
1294
1294
  for (const key of Object.keys(options)) {
1295
- if (!["channels", "roles", "byChannel"].includes(key)) {
1295
+ if (!["channels", "roles", "byChannel", "origins"].includes(key)) {
1296
1296
  report("invalid-sign-in", `signUp.${key}`, `Unknown signUp key: ${key}.`);
1297
1297
  }
1298
1298
  }
@@ -1376,9 +1376,40 @@ function signUpOptions(config, signIn, declaredRoles, report) {
1376
1376
  }
1377
1377
  }
1378
1378
  }
1379
+ const origins = [];
1380
+ if (options.origins !== undefined) {
1381
+ if (!channels.includes("web")) {
1382
+ report("invalid-sign-in", "signUp.origins", "origins are the websites of web; list web.");
1383
+ }
1384
+ else if (!Array.isArray(options.origins)) {
1385
+ report("invalid-sign-in", "signUp.origins", "List the websites' origins, such as https://www.example.com.");
1386
+ }
1387
+ else {
1388
+ options.origins.forEach((candidate, index) => {
1389
+ const origin = signUpOrigin(candidate);
1390
+ const path = `signUp.origins[${index}]`;
1391
+ if (origin === undefined) {
1392
+ report("invalid-sign-in", path, "Use an exact origin alone, such as https://www.example.com; http only for localhost.");
1393
+ }
1394
+ else if (origins.includes(origin)) {
1395
+ report("invalid-sign-in", path, `${origin} is listed twice.`);
1396
+ }
1397
+ else {
1398
+ origins.push(origin);
1399
+ }
1400
+ });
1401
+ }
1402
+ }
1403
+ if (channels.includes("web") &&
1404
+ origins.length === 0 &&
1405
+ (options.origins === undefined ||
1406
+ (Array.isArray(options.origins) && options.origins.length === 0))) {
1407
+ report("invalid-sign-in", "signUp.origins", "Signing up on web needs the websites' origins in signUp.origins.");
1408
+ }
1379
1409
  if (channels.length > 0 && roles !== undefined) {
1380
1410
  result.signUp = {
1381
1411
  channels: Object.fromEntries(channels.map((channel) => [channel, byChannel[channel] ?? roles])),
1412
+ ...(origins.length === 0 ? {} : { origins }),
1382
1413
  };
1383
1414
  }
1384
1415
  return result;
package/dist/index.d.ts CHANGED
@@ -24,7 +24,7 @@ export type { ActionsBuilder, AnyEntity, ActionHandle, ActionInvoker, MetricQuer
24
24
  export { ActionRejected, BatchErrorDetails, Conflict, DeploymentInterrupted, DeploymentSwitching, LimitErrorDetails, NotFound, PermissionDenied, ScopeViolated, } from "./errors.js";
25
25
  export type { ActionError } from "./errors.js";
26
26
  export { browserAuthenticationCompatible } from "./manifest-compatibility.js";
27
- export { ActionManifest, actionConnectionKeys, canonicalJson, ConnectionManifest, EntityManifest, EntityPermissionsManifest, decodeManifestDocument, encodeManifest, formatManifest, IndexManifest, isValueMatched, MANIFEST_VERSION, manifestHash, ModelMetricManifest, OntologyManifest, OntologyManifestWire, PropertyManifest, RelationshipManifest, RoleManifest, ActionTriggerManifest, ScopeManifest, CronTriggerManifest, isActionTrigger, isCronTrigger, isWebhookTrigger, OtherTriggerManifest, WebhookTriggerManifest, WorkflowManifest, WorkflowTriggerManifest, SelectOptionManifest, SignInManifest, signInPolicyOf, channelPolicyOf, signUpRolesOf, } from "./manifest.js";
27
+ export { ActionManifest, actionConnectionKeys, canonicalJson, ConnectionManifest, EntityManifest, EntityPermissionsManifest, decodeManifestDocument, encodeManifest, formatManifest, IndexManifest, isValueMatched, MANIFEST_VERSION, manifestHash, ModelMetricManifest, OntologyManifest, OntologyManifestWire, PropertyManifest, RelationshipManifest, RoleManifest, ActionTriggerManifest, ScopeManifest, CronTriggerManifest, isActionTrigger, isCronTrigger, isWebhookTrigger, OtherTriggerManifest, WebhookTriggerManifest, WorkflowManifest, WorkflowTriggerManifest, SelectOptionManifest, SignInManifest, signInPolicyOf, channelPolicyOf, signUpOriginsOf, signUpRolesOf, } from "./manifest.js";
28
28
  export { SYSTEM_PROPERTIES } from "./names.js";
29
29
  export type { SystemProperty } from "./names.js";
30
30
  export { isMe, isMeMarker, MAX_ME_HOPS, me, ME_KEY, MeMarker, mePathOf, meToWire, MeTypeId, } from "./me.js";
@@ -48,7 +48,7 @@ export { after, changed, cron, cronNeverFires, cronProblem, isWorkflow, isWorkfl
48
48
  export { MAX_WEBHOOK_BODY_BYTES, MAX_META_WEBHOOK_BODY_BYTES, MAX_WEBHOOK_HEADERS, MAX_WEBHOOKS, WEBHOOK_BASE_PATH, WEBHOOK_SIGNATURE_SCHEMES, webhookDelivery, webhookHeaderProblem, webhookPath, } from "./webhooks.js";
49
49
  export type { WebhookDelivery, WebhookSignatureScheme } from "./webhooks.js";
50
50
  export type { ActionEvent, ActionTrigger, AfterOptions, AnyActionHandle, AnyWorkflow, ChangedBounds, CronOptions, CronProblem, CronTrigger, TriggerFunction, TriggerRecord, WebhookOptions, WebhookSignature, WebhookVerification, WebhookTrigger, Workflow, WorkflowFunction, WorkflowOptions, WorkflowRunContext, WorkflowTrigger, } from "./workflow.js";
51
- export { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, SIGN_IN_METHODS, SIGN_IN_POLICIES, SIGN_UP_CHANNELS, } from "./sign-in.js";
51
+ export { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, SIGN_IN_METHODS, SIGN_IN_POLICIES, SIGN_UP_CHANNELS, signUpOrigin, } from "./sign-in.js";
52
52
  export type { ChannelProvider, ResolvedSignInOptions, ResolvedSignUp, SignInCheck, SignInMethod, SignInOptions, SignInPolicy, SignUpChannel, SignUpOptions, } from "./sign-in.js";
53
53
  export type { EmailTemplate } from "./emails.js";
54
54
  export { OntologyActions, OntologyReads, OntologyRuntime, OntologyWrites } from "./runtime.js";
@@ -86,9 +86,9 @@ export { configFromEnv, ENVIRONMENT_VARIABLES, NEON_AUTH_ENVIRONMENT_VARIABLES,
86
86
  export type { ActionCommitted, AfterCommitHook, NeonAuthEnvironment, OntologyEnvironment, OntologyServiceConfig, } from "./service/config.js";
87
87
  export type { Decide, DecisionRequest } from "./service/decisions.js";
88
88
  export { IdentityInUse, NotInvited, OntologyBackend } from "./service/runtime-contract.js";
89
- export type { AgentIdentity, AgentMember, AgentLimits, AgentLimitScope, ChannelSignInInput, AgentResolution, ResolveIdentityInput, AgentPairing, AgentStore, AgentWebStore, WebTurnLimit, SeenChat, HeldReplyInput, HeldReview, GeneratedActionsProvider, IdentityProvider, OAuthClient, OAuthClientAuthMethod, OAuthGrant, OAuthDevice, DevicePoll, OAuthRequest, OAuthStore, OAuthToken, OAuthTokenKind, OntologyServiceRuntime, RunActionInput, SignInIdentity, UsedOAuthToken, } from "./service/runtime-contract.js";
89
+ export type { AgentIdentity, AgentMember, AgentLimits, AgentLimitScope, ChannelSignInInput, AgentResolution, ResolveIdentityInput, AgentPairing, AgentStore, AgentWebStore, VisitorSignUp, WebTurnLimit, SeenChat, HeldReplyInput, HeldReview, GeneratedActionsProvider, IdentityProvider, OAuthClient, OAuthClientAuthMethod, OAuthGrant, OAuthDevice, DevicePoll, OAuthRequest, OAuthStore, OAuthToken, OAuthTokenKind, OntologyServiceRuntime, RunActionInput, SignInIdentity, UsedOAuthToken, } from "./service/runtime-contract.js";
90
90
  export { createOntologyService, ONTOLOGY_HASH_HEADER, REQUEST_ID_HEADER, } from "./service/service.js";
91
- export { AGENT_PATH, AGENT_TOKEN_INTROSPECTION_PATH, AGENT_TOKENS_PATH, } from "./service/agent/server.js";
91
+ export { AGENT_PATH, AGENT_TOKEN_INTROSPECTION_PATH, AGENT_TOKENS_PATH, AGENT_VISITORS_PATH, } from "./service/agent/server.js";
92
92
  export { AGENT_TASK_PATH, AGENT_TASK_RESULT_PATH } from "./service/agent/tasks.js";
93
93
  export { WORKSPACE_SOURCE_PATH } from "./service/agent/source.js";
94
94
  export { AGENT_WEB_CLIENT_ID, agentResource } from "./service/agent/web-tokens.js";
package/dist/index.js CHANGED
@@ -13,7 +13,7 @@ export { entity, isEntity } from "./entity.js";
13
13
  export { isToolset, MCP_TOOL_NAME, TOOLSET_LOCK_VERSION, toolset, ToolsetLock, ToolsetLockTool, } from "./toolset.js";
14
14
  export { ActionRejected, BatchErrorDetails, Conflict, DeploymentInterrupted, DeploymentSwitching, LimitErrorDetails, NotFound, PermissionDenied, ScopeViolated, } from "./errors.js";
15
15
  export { browserAuthenticationCompatible } from "./manifest-compatibility.js";
16
- export { ActionManifest, actionConnectionKeys, canonicalJson, ConnectionManifest, EntityManifest, EntityPermissionsManifest, decodeManifestDocument, encodeManifest, formatManifest, IndexManifest, isValueMatched, MANIFEST_VERSION, manifestHash, ModelMetricManifest, OntologyManifest, OntologyManifestWire, PropertyManifest, RelationshipManifest, RoleManifest, ActionTriggerManifest, ScopeManifest, CronTriggerManifest, isActionTrigger, isCronTrigger, isWebhookTrigger, OtherTriggerManifest, WebhookTriggerManifest, WorkflowManifest, WorkflowTriggerManifest, SelectOptionManifest, SignInManifest, signInPolicyOf, channelPolicyOf, signUpRolesOf, } from "./manifest.js";
16
+ export { ActionManifest, actionConnectionKeys, canonicalJson, ConnectionManifest, EntityManifest, EntityPermissionsManifest, decodeManifestDocument, encodeManifest, formatManifest, IndexManifest, isValueMatched, MANIFEST_VERSION, manifestHash, ModelMetricManifest, OntologyManifest, OntologyManifestWire, PropertyManifest, RelationshipManifest, RoleManifest, ActionTriggerManifest, ScopeManifest, CronTriggerManifest, isActionTrigger, isCronTrigger, isWebhookTrigger, OtherTriggerManifest, WebhookTriggerManifest, WorkflowManifest, WorkflowTriggerManifest, SelectOptionManifest, SignInManifest, signInPolicyOf, channelPolicyOf, signUpOriginsOf, signUpRolesOf, } from "./manifest.js";
17
17
  export { SYSTEM_PROPERTIES } from "./names.js";
18
18
  export { isMe, isMeMarker, MAX_ME_HOPS, me, ME_KEY, MeMarker, mePathOf, meToWire, MeTypeId, } from "./me.js";
19
19
  export { check, defineOntology } from "./ontology.js";
@@ -26,7 +26,7 @@ export { renderCatalog } from "./render.js";
26
26
  export { member, role, roleEntries, rolePermissions } from "./role.js";
27
27
  export { after, changed, cron, cronNeverFires, cronProblem, isWorkflow, isWorkflowTrigger, MAX_ACTION_TRIGGERS, MAX_WORKFLOWS, nextCronTime, webhook, workflow, } from "./workflow.js";
28
28
  export { MAX_WEBHOOK_BODY_BYTES, MAX_META_WEBHOOK_BODY_BYTES, MAX_WEBHOOK_HEADERS, MAX_WEBHOOKS, WEBHOOK_BASE_PATH, WEBHOOK_SIGNATURE_SCHEMES, webhookDelivery, webhookHeaderProblem, webhookPath, } from "./webhooks.js";
29
- export { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, SIGN_IN_METHODS, SIGN_IN_POLICIES, SIGN_UP_CHANNELS, } from "./sign-in.js";
29
+ export { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, SIGN_IN_METHODS, SIGN_IN_POLICIES, SIGN_UP_CHANNELS, signUpOrigin, } from "./sign-in.js";
30
30
  export { OntologyActions, OntologyReads, OntologyRuntime, OntologyWrites } from "./runtime.js";
31
31
  export { User } from "./user.js";
32
32
  export { AgentChat } from "./agent-chat.js";
@@ -54,7 +54,7 @@ export { IdentityInUse, NotInvited, OntologyBackend } from "./service/runtime-co
54
54
  export { createOntologyService, ONTOLOGY_HASH_HEADER, REQUEST_ID_HEADER, } from "./service/service.js";
55
55
  // The app's own agent: pairing channel accounts with members, and acting as them, or as a
56
56
  // workflow's user in the tasks workflows hand it.
57
- export { AGENT_PATH, AGENT_TOKEN_INTROSPECTION_PATH, AGENT_TOKENS_PATH, } from "./service/agent/server.js";
57
+ export { AGENT_PATH, AGENT_TOKEN_INTROSPECTION_PATH, AGENT_TOKENS_PATH, AGENT_VISITORS_PATH, } from "./service/agent/server.js";
58
58
  export { AGENT_TASK_PATH, AGENT_TASK_RESULT_PATH } from "./service/agent/tasks.js";
59
59
  export { WORKSPACE_SOURCE_PATH } from "./service/agent/source.js";
60
60
  // Agent tokens: access tokens of a member's grant to the agent, which a browser shows the agent.
@@ -60,6 +60,9 @@ import { type ResolvedSignInOptions, type SignInPolicy } from "./sign-in.js";
60
60
  * Within version 15, `signIn` may carry `signUp`, the wire names of the roles each channel open to
61
61
  * sign-up grants, and `onSignUp`, written only when declared. Older readers ignore them and keep
62
62
  * every channel closed to sign-up.
63
+ * Within version 15, `signUp` may carry `web` among its channels and `origins`, the websites whose
64
+ * visitors sign up on it, written only when declared. Older readers ignore both and keep `web`
65
+ * closed.
63
66
  */
64
67
  export declare const MANIFEST_VERSION = 15;
65
68
  /** The phrase used for a direction the author did not phrase. */
@@ -608,9 +611,13 @@ export declare const BrowserSignInManifest: Schema.encodeKeys<Schema.Struct<{
608
611
  }>, {
609
612
  readonly autoRedirect: "auto_redirect";
610
613
  }>;
611
- /** Sign-up: the wire names of the roles each open channel grants. Unknown channels stay closed. */
614
+ /**
615
+ * Sign-up: the wire names of the roles each open channel grants, and the websites whose visitors
616
+ * may sign up on `web`. Unknown channels stay closed.
617
+ */
612
618
  export declare const SignUpManifest: Schema.Struct<{
613
619
  readonly channels: Schema.$Record<Schema.String, Schema.Unknown>;
620
+ readonly origins: Schema.optionalKey<Schema.$Array<Schema.String>>;
614
621
  }>;
615
622
  export declare const SignInManifest: Schema.encodeKeys<Schema.Struct<{
616
623
  readonly browser: Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
@@ -629,6 +636,7 @@ export declare const SignInManifest: Schema.encodeKeys<Schema.Struct<{
629
636
  readonly codeLink: Schema.optionalKey<Schema.Boolean>;
630
637
  readonly signUp: Schema.optionalKey<Schema.Struct<{
631
638
  readonly channels: Schema.$Record<Schema.String, Schema.Unknown>;
639
+ readonly origins: Schema.optionalKey<Schema.$Array<Schema.String>>;
632
640
  }>>;
633
641
  readonly onSignUp: Schema.optionalKey<Schema.String>;
634
642
  }>, {
@@ -909,6 +917,7 @@ export declare const OntologyManifestWire: Schema.encodeKeys<Schema.Struct<{
909
917
  readonly codeLink: Schema.optionalKey<Schema.Boolean>;
910
918
  readonly signUp: Schema.optionalKey<Schema.Struct<{
911
919
  readonly channels: Schema.$Record<Schema.String, Schema.Unknown>;
920
+ readonly origins: Schema.optionalKey<Schema.$Array<Schema.String>>;
912
921
  }>>;
913
922
  readonly onSignUp: Schema.optionalKey<Schema.String>;
914
923
  }>, {
@@ -1292,6 +1301,7 @@ export declare const OntologyManifest: Schema.declareConstructor<{
1292
1301
  readonly channels: {
1293
1302
  readonly [x: string]: unknown;
1294
1303
  };
1304
+ readonly origins?: readonly string[] | undefined;
1295
1305
  } | undefined;
1296
1306
  readonly onSignUp?: string | undefined;
1297
1307
  } | undefined;
@@ -1560,6 +1570,7 @@ export declare const OntologyManifest: Schema.declareConstructor<{
1560
1570
  readonly channels: {
1561
1571
  readonly [x: string]: unknown;
1562
1572
  };
1573
+ readonly origins?: readonly string[] | undefined;
1563
1574
  } | undefined;
1564
1575
  readonly onSignUp?: string | undefined;
1565
1576
  } | undefined;
@@ -1879,6 +1890,7 @@ export declare const OntologyManifest: Schema.declareConstructor<{
1879
1890
  readonly channels: {
1880
1891
  readonly [x: string]: unknown;
1881
1892
  };
1893
+ readonly origins?: readonly string[] | undefined;
1882
1894
  } | undefined;
1883
1895
  readonly on_sign_up?: string | undefined;
1884
1896
  } | undefined;
@@ -2096,6 +2108,7 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2096
2108
  readonly channels: {
2097
2109
  readonly [x: string]: unknown;
2098
2110
  };
2111
+ readonly origins?: readonly string[] | undefined;
2099
2112
  } | undefined;
2100
2113
  readonly on_sign_up?: string | undefined;
2101
2114
  } | undefined;
@@ -2348,6 +2361,7 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2348
2361
  readonly codeLink: Schema.optionalKey<Schema.Boolean>;
2349
2362
  readonly signUp: Schema.optionalKey<Schema.Struct<{
2350
2363
  readonly channels: Schema.$Record<Schema.String, Schema.Unknown>;
2364
+ readonly origins: Schema.optionalKey<Schema.$Array<Schema.String>>;
2351
2365
  }>>;
2352
2366
  readonly onSignUp: Schema.optionalKey<Schema.String>;
2353
2367
  }>, {
@@ -2702,6 +2716,7 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2702
2716
  readonly codeLink: Schema.optionalKey<Schema.Boolean>;
2703
2717
  readonly signUp: Schema.optionalKey<Schema.Struct<{
2704
2718
  readonly channels: Schema.$Record<Schema.String, Schema.Unknown>;
2719
+ readonly origins: Schema.optionalKey<Schema.$Array<Schema.String>>;
2705
2720
  }>>;
2706
2721
  readonly onSignUp: Schema.optionalKey<Schema.String>;
2707
2722
  }>, {
@@ -3077,6 +3092,7 @@ export declare const OntologyManifest: Schema.declareConstructor<{
3077
3092
  readonly channels: {
3078
3093
  readonly [x: string]: unknown;
3079
3094
  };
3095
+ readonly origins?: readonly string[] | undefined;
3080
3096
  } | undefined;
3081
3097
  readonly onSignUp?: string | undefined;
3082
3098
  } | undefined;
@@ -3345,6 +3361,7 @@ export declare const OntologyManifest: Schema.declareConstructor<{
3345
3361
  readonly channels: {
3346
3362
  readonly [x: string]: unknown;
3347
3363
  };
3364
+ readonly origins?: readonly string[] | undefined;
3348
3365
  } | undefined;
3349
3366
  readonly onSignUp?: string | undefined;
3350
3367
  } | undefined;
@@ -3619,6 +3636,7 @@ export declare const decodeManifestDocument: (value: unknown) => Effect.Effect<{
3619
3636
  readonly channels: {
3620
3637
  readonly [x: string]: unknown;
3621
3638
  };
3639
+ readonly origins?: readonly string[] | undefined;
3622
3640
  } | undefined;
3623
3641
  readonly onSignUp?: string | undefined;
3624
3642
  } | undefined;
@@ -3887,6 +3905,7 @@ export declare const decodeManifestDocument: (value: unknown) => Effect.Effect<{
3887
3905
  readonly channels: {
3888
3906
  readonly [x: string]: unknown;
3889
3907
  };
3908
+ readonly origins?: readonly string[] | undefined;
3890
3909
  } | undefined;
3891
3910
  readonly onSignUp?: string | undefined;
3892
3911
  } | undefined;
@@ -3954,6 +3973,11 @@ export declare function signInPolicyOf(manifest: Pick<OntologyManifest, "signIn"
3954
3973
  * the channel is closed to sign-up: not a channel this reader knows, or no well-formed entry.
3955
3974
  */
3956
3975
  export declare function signUpRolesOf(manifest: Pick<OntologyManifest, "signIn">, channel: string): ReadonlyArray<string> | undefined;
3976
+ /**
3977
+ * The websites whose visitors may sign up on `web`, by origin: empty while `web` is closed to
3978
+ * sign-up. Entries that are not an origin `signUp.origins` accepts are left out.
3979
+ */
3980
+ export declare function signUpOriginsOf(manifest: Pick<OntologyManifest, "signIn">): ReadonlyArray<string>;
3957
3981
  /** Unsupported providers and missing or unknown channel policies require invitation. */
3958
3982
  export declare function channelPolicyOf(manifest: Pick<OntologyManifest, "signIn">, provider: string): SignInPolicy;
3959
3983
  /** JSON with object keys sorted at every level and no whitespace: the input of the manifest hash. */
package/dist/manifest.js CHANGED
@@ -4,7 +4,7 @@ import { acceptingEarlierManifestNames, withEarlierManifestNames } from "./legac
4
4
  import { humanize, MEMBER_ROLE, FEEDBACK_REPORTER_ROLE } from "./names.js";
5
5
  import { PROPERTY_TYPES } from "./property.js";
6
6
  import { ON_DELETE } from "./relationship.js";
7
- import { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, isSignInPolicy, isSignUpChannel, } from "./sign-in.js";
7
+ import { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, isSignInPolicy, isSignUpChannel, signUpOrigin, } from "./sign-in.js";
8
8
  /**
9
9
  * The manifest format this SDK writes. Readers accept any version and ignore unknown fields. Version
10
10
  * 2 replaced the actions' `allow` with `permission`, and added the roles' `permissions` and the
@@ -60,6 +60,9 @@ import { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, isSignInPolicy, isSignUpChan
60
60
  * Within version 15, `signIn` may carry `signUp`, the wire names of the roles each channel open to
61
61
  * sign-up grants, and `onSignUp`, written only when declared. Older readers ignore them and keep
62
62
  * every channel closed to sign-up.
63
+ * Within version 15, `signUp` may carry `web` among its channels and `origins`, the websites whose
64
+ * visitors sign up on it, written only when declared. Older readers ignore both and keep `web`
65
+ * closed.
63
66
  */
64
67
  export const MANIFEST_VERSION = 15;
65
68
  /** The first version whose documents use snake_case names on the wire. */
@@ -386,9 +389,13 @@ export const BrowserSignInManifest = Schema.Struct({
386
389
  autoRedirect: Schema.Boolean,
387
390
  local: Schema.optionalKey(Schema.Struct({ port: Schema.Int })),
388
391
  }).pipe(Schema.encodeKeys({ autoRedirect: "auto_redirect" }));
389
- /** Sign-up: the wire names of the roles each open channel grants. Unknown channels stay closed. */
392
+ /**
393
+ * Sign-up: the wire names of the roles each open channel grants, and the websites whose visitors
394
+ * may sign up on `web`. Unknown channels stay closed.
395
+ */
390
396
  export const SignUpManifest = Schema.Struct({
391
397
  channels: Schema.Record(Schema.String, Schema.Unknown),
398
+ origins: Schema.optionalKey(Schema.Array(Schema.String)),
392
399
  });
393
400
  export const SignInManifest = Schema.Struct({
394
401
  browser: Schema.optionalKey(BrowserSignInManifest),
@@ -552,6 +559,22 @@ export function signUpRolesOf(manifest, channel) {
552
559
  ? roles
553
560
  : undefined;
554
561
  }
562
+ /**
563
+ * The websites whose visitors may sign up on `web`, by origin: empty while `web` is closed to
564
+ * sign-up. Entries that are not an origin `signUp.origins` accepts are left out.
565
+ */
566
+ export function signUpOriginsOf(manifest) {
567
+ if (signUpRolesOf(manifest, "web") === undefined) {
568
+ return [];
569
+ }
570
+ const origins = manifest.signIn?.signUp?.origins;
571
+ return Array.isArray(origins)
572
+ ? origins.flatMap((candidate) => {
573
+ const origin = signUpOrigin(candidate);
574
+ return origin === undefined ? [] : [origin];
575
+ })
576
+ : [];
577
+ }
555
578
  // @legacy ontology.legacy-channel-admission
556
579
  /** Unsupported providers and missing or unknown channel policies require invitation. */
557
580
  export function channelPolicyOf(manifest, provider) {
@@ -800,6 +823,9 @@ export function buildManifest(input) {
800
823
  channel,
801
824
  [...(roles ?? [])],
802
825
  ])),
826
+ ...(input.signIn.signUp.origins === undefined
827
+ ? {}
828
+ : { origins: [...input.signIn.signUp.origins] }),
803
829
  },
804
830
  }),
805
831
  ...(input.signIn.onSignUp === undefined ? {} : { onSignUp: input.signIn.onSignUp }),
@@ -495,6 +495,7 @@ export declare const MigrationPlan: Schema.Struct<{
495
495
  readonly channels: {
496
496
  readonly [x: string]: unknown;
497
497
  };
498
+ readonly origins?: readonly string[] | undefined;
498
499
  } | undefined;
499
500
  readonly onSignUp?: string | undefined;
500
501
  } | undefined;
@@ -763,6 +764,7 @@ export declare const MigrationPlan: Schema.Struct<{
763
764
  readonly channels: {
764
765
  readonly [x: string]: unknown;
765
766
  };
767
+ readonly origins?: readonly string[] | undefined;
766
768
  } | undefined;
767
769
  readonly onSignUp?: string | undefined;
768
770
  } | undefined;
@@ -1082,6 +1084,7 @@ export declare const MigrationPlan: Schema.Struct<{
1082
1084
  readonly channels: {
1083
1085
  readonly [x: string]: unknown;
1084
1086
  };
1087
+ readonly origins?: readonly string[] | undefined;
1085
1088
  } | undefined;
1086
1089
  readonly on_sign_up?: string | undefined;
1087
1090
  } | undefined;
@@ -1299,6 +1302,7 @@ export declare const MigrationPlan: Schema.Struct<{
1299
1302
  readonly channels: {
1300
1303
  readonly [x: string]: unknown;
1301
1304
  };
1305
+ readonly origins?: readonly string[] | undefined;
1302
1306
  } | undefined;
1303
1307
  readonly on_sign_up?: string | undefined;
1304
1308
  } | undefined;
@@ -1507,6 +1511,7 @@ export declare const MigrationPlan: Schema.Struct<{
1507
1511
  readonly codeLink: Schema.optionalKey<Schema.Boolean>;
1508
1512
  readonly signUp: Schema.optionalKey<Schema.Struct<{
1509
1513
  readonly channels: Schema.$Record<Schema.String, Schema.Unknown>;
1514
+ readonly origins: Schema.optionalKey<Schema.$Array<Schema.String>>;
1510
1515
  }>>;
1511
1516
  readonly onSignUp: Schema.optionalKey<Schema.String>;
1512
1517
  }>, {
@@ -1766,6 +1771,7 @@ export declare const MigrationPlan: Schema.Struct<{
1766
1771
  readonly codeLink: Schema.optionalKey<Schema.Boolean>;
1767
1772
  readonly signUp: Schema.optionalKey<Schema.Struct<{
1768
1773
  readonly channels: Schema.$Record<Schema.String, Schema.Unknown>;
1774
+ readonly origins: Schema.optionalKey<Schema.$Array<Schema.String>>;
1769
1775
  }>>;
1770
1776
  readonly onSignUp: Schema.optionalKey<Schema.String>;
1771
1777
  }>, {
@@ -2098,6 +2104,7 @@ export declare const MigrationPlan: Schema.Struct<{
2098
2104
  readonly channels: {
2099
2105
  readonly [x: string]: unknown;
2100
2106
  };
2107
+ readonly origins?: readonly string[] | undefined;
2101
2108
  } | undefined;
2102
2109
  readonly onSignUp?: string | undefined;
2103
2110
  } | undefined;
@@ -2366,6 +2373,7 @@ export declare const MigrationPlan: Schema.Struct<{
2366
2373
  readonly channels: {
2367
2374
  readonly [x: string]: unknown;
2368
2375
  };
2376
+ readonly origins?: readonly string[] | undefined;
2369
2377
  } | undefined;
2370
2378
  readonly onSignUp?: string | undefined;
2371
2379
  } | undefined;
@@ -1,5 +1,6 @@
1
1
  import { BaseBuilder } from "@workflow/builders";
2
2
  import type { Nitro } from "nitro/types";
3
+ import type { WorkflowStructures } from "./workflow-structure.js";
3
4
  /**
4
5
  * The build side of `ontologyWorkflows()` (see `./nitro.ts`), loaded only while Nitro builds.
5
6
  */
@@ -84,6 +85,19 @@ export declare class OntologyWorkflowBuilder extends BaseBuilder {
84
85
  get platformWorkflowFile(): string | undefined;
85
86
  build(): Promise<void>;
86
87
  }
88
+ /** The module the build writes with the workflows' structures, which the service registers. */
89
+ export declare const STRUCTURES_FILE = "structures.mjs";
90
+ /** The structures module: one default export, the structures by workflow id. */
91
+ export declare function structuresModuleSource(structures: WorkflowStructures): string;
92
+ /**
93
+ * The Nitro plugin that registers the workflows' structures with the service at startup, from the
94
+ * module the build wrote.
95
+ */
96
+ export declare function structuresPluginSource(input: {
97
+ readonly file: string;
98
+ /** The module that exports `registerWorkflowStructures`: the `server` entry. */
99
+ readonly server?: string;
100
+ }): string;
87
101
  /** Where the generated handler takes its runtime from; tests point them elsewhere. */
88
102
  export interface CallbackImports {
89
103
  /** The module that exports `serveWorkflowCallback`. */
@@ -1,5 +1,5 @@
1
1
  import { mkdir, readFile, writeFile } from "node:fs/promises";
2
- import { join } from "node:path";
2
+ import { join, resolve } from "node:path";
3
3
  import { pathToFileURL } from "node:url";
4
4
  import { BaseBuilder, createBaseBuilderConfig } from "@workflow/builders";
5
5
  import { workflowTransformPlugin } from "@workflow/rollup";
@@ -123,12 +123,67 @@ export class OntologyWorkflowBuilder extends BaseBuilder {
123
123
  "the ontology's queue namespace cannot be set.");
124
124
  }
125
125
  await writeFile(flowFile, flow.replace(ENTRYPOINT_CALL, `workflowEntrypoint(workflowCode, { namespace: ${JSON.stringify(this.#namespace)},`));
126
- await this.createManifest({
126
+ const manifest = await this.createManifest({
127
127
  workflowBundlePath: flowFile,
128
128
  manifestDir: this.#outDir,
129
129
  manifest: built.manifest,
130
130
  });
131
+ await writeFile(join(this.#outDir, STRUCTURES_FILE), structuresModuleSource(await this.#structures(manifest === undefined ? undefined : JSON.parse(manifest))));
131
132
  }
133
+ /**
134
+ * What each workspace workflow does, read from its source for the console's map. A reading that
135
+ * fails leaves the workflows without a map and never fails the build.
136
+ */
137
+ async #structures(manifest) {
138
+ if (manifest === undefined) {
139
+ return {};
140
+ }
141
+ try {
142
+ const { readWorkflowStructures } = await import("./workflow-structure-extract.js");
143
+ const imported = (await import("typescript"));
144
+ const platform = this.#platform === undefined ? undefined : this.#platform.dir;
145
+ return readWorkflowStructures({
146
+ ts: imported.default ?? imported,
147
+ root: this.config.workingDir,
148
+ manifest,
149
+ skip: (file) => platform !== undefined && resolve(this.config.workingDir, file).startsWith(platform),
150
+ onError: (workflowId, error) => {
151
+ console.warn(`The ontology could not read the structure of ${workflowId}:`, error);
152
+ },
153
+ });
154
+ }
155
+ catch (error) {
156
+ console.warn("The ontology could not read its workflows' structures:", error);
157
+ return {};
158
+ }
159
+ }
160
+ }
161
+ /** The module the build writes with the workflows' structures, which the service registers. */
162
+ export const STRUCTURES_FILE = "structures.mjs";
163
+ /** The structures module: one default export, the structures by workflow id. */
164
+ export function structuresModuleSource(structures) {
165
+ return [
166
+ "// Written by @segmentstream/ontology's ontologyWorkflows() on every build: what each",
167
+ "// workflow does, read from its code, for the console's map.",
168
+ `export default ${JSON.stringify(structures)};`,
169
+ "",
170
+ ].join("\n");
171
+ }
172
+ /**
173
+ * The Nitro plugin that registers the workflows' structures with the service at startup, from the
174
+ * module the build wrote.
175
+ */
176
+ export function structuresPluginSource(input) {
177
+ const server = input.server ?? "@segmentstream/ontology/server";
178
+ return [
179
+ `import { registerWorkflowStructures } from ${JSON.stringify(server)};`,
180
+ `import structures from ${JSON.stringify(pathToFileURL(input.file).href)};`,
181
+ "",
182
+ "export default function registerOntologyWorkflowStructures() {",
183
+ " registerWorkflowStructures(structures);",
184
+ "}",
185
+ "",
186
+ ].join("\n");
132
187
  }
133
188
  /** See `addNodeRequireBanner` in `workflow/nitro`: undici loads `node:http2` with `require`. */
134
189
  const REQUIRE_BANNER = "import { createRequire as __wkfCreateRequire } from 'node:module'; " +
@@ -256,12 +311,17 @@ export async function setupOntologyWorkflows(nitro, settings) {
256
311
  }
257
312
  const id = "#segmentstream-ontology/workflow-flow";
258
313
  const platformPlugin = "#segmentstream-ontology/platform-workflows";
314
+ const structuresPlugin = "#segmentstream-ontology/workflow-structures";
259
315
  // At startup, before any request: the service refuses an action whose triggers may fire until
260
316
  // the platform's recovery workflow is registered.
261
317
  (nitro.options.plugins ??= []).push(platformPlugin);
262
318
  nitro.options.virtual[platformPlugin] = platformPluginSource({
263
319
  file: join(platformDir, PLATFORM_WORKFLOW_FILE),
264
320
  });
321
+ nitro.options.plugins.push(structuresPlugin);
322
+ nitro.options.virtual[structuresPlugin] = structuresPluginSource({
323
+ file: join(outDir, STRUCTURES_FILE),
324
+ });
265
325
  nitro.options.handlers.push({ route: settings.route, handler: id, lazy: true });
266
326
  nitro.options.virtual[id] = callbackHandlerSource({
267
327
  file: join(outDir, "workflows.mjs"),
@@ -1,9 +1,16 @@
1
+ import { Effect } from "effect";
1
2
  import type { SqlClient } from "effect/unstable/sql";
2
3
  import type { Ontology } from "../ontology.js";
3
- import type { AgentWebStore } from "../service/runtime-contract.js";
4
+ import type { AgentResolution, AgentWebStore } from "../service/runtime-contract.js";
4
5
  /**
5
6
  * Agent tokens in the ontology's OAuth tables, as channel sessions are: one standing grant per
6
7
  * member and resource for the first-party client `agent-web`, and a new access token on each
7
8
  * request. Blocking or deactivating the member revokes the grant with every other one of theirs.
8
9
  */
9
- export declare function sqlAgentWebStore(ontology: Ontology, sql: SqlClient.SqlClient): AgentWebStore;
10
+ /** How many new website visitors one network address may start an hour. */
11
+ export declare const VISITORS_PER_CLIENT_PER_HOUR = 10;
12
+ export interface AgentWebAdmission {
13
+ /** Admits a new visitor on `web` as `signUp` admits a channel account: their user, or why not. */
14
+ readonly signUp: (visitorId: string) => Effect.Effect<AgentResolution>;
15
+ }
16
+ export declare function sqlAgentWebStore(ontology: Ontology, sql: SqlClient.SqlClient, admission: AgentWebAdmission): AgentWebStore;