@segmentstream/ontology 0.104.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,20 @@
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
+
3
18
  ## 0.104.0
4
19
 
5
20
  The agent answers a website's visitors. `signUp` takes the channel `web` with `origins`, the
@@ -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"),
package/dist/server.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type PlatformWorkflows } from "./workflow-runtime.js";
2
+ import type { WorkflowStructures } from "./workflow-structure.js";
2
3
  /**
3
4
  * Prepares the process for serving the ontology's runs; the starter's `server/plugin.ts` calls it
4
5
  * at startup. Until the flow handler loads, which sets the Workflow SDK's base path itself from the
@@ -21,3 +22,9 @@ export declare function installWorkflowRuntime(): void;
21
22
  * since the service could not arm the recovery run that guarantees its starts.
22
23
  */
23
24
  export declare function registerPlatformWorkflows(workflows: PlatformWorkflows): void;
25
+ /**
26
+ * Registers what the build read of each workflow's code, by workflow id: the plugin
27
+ * `ontologyWorkflows()` generates calls it at startup, and the service serves each declared
28
+ * workflow's structure beside its runs. Without it, the service answers that it has none.
29
+ */
30
+ export declare function registerWorkflowStructures(structures: WorkflowStructures): void;
package/dist/server.js CHANGED
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import { setWorkflowBasePath } from "@workflow/utils";
7
7
  import { deploymentFromEnv, requireDeploymentCapability } from "./deployment.js";
8
- import { setPlatformWorkflows, setWorkflowSdk, } from "./workflow-runtime.js";
8
+ import { setPlatformWorkflows, setWorkflowSdk, setWorkflowStructures, } from "./workflow-runtime.js";
9
9
  import { ONTOLOGY_QUEUE_NAMESPACE, WORKFLOW_BASE_PATH } from "./workflow-topics.js";
10
10
  import { installWorkflowArgumentCodecs } from "./service/workflow-argument-serialization.js";
11
11
  import { installWorkflowLogging } from "./service/workflow-logging.js";
@@ -105,3 +105,11 @@ export function installWorkflowRuntime() {
105
105
  export function registerPlatformWorkflows(workflows) {
106
106
  setPlatformWorkflows(workflows);
107
107
  }
108
+ /**
109
+ * Registers what the build read of each workflow's code, by workflow id: the plugin
110
+ * `ontologyWorkflows()` generates calls it at startup, and the service serves each declared
111
+ * workflow's structure beside its runs. Without it, the service answers that it has none.
112
+ */
113
+ export function registerWorkflowStructures(structures) {
114
+ setWorkflowStructures(structures);
115
+ }
@@ -189,6 +189,8 @@ export declare const SWEEP_PATH = "/api/ontology/workflows/sweep";
189
189
  * `workflow:<workflow>:start`, or for the platform;
190
190
  * - `GET /api/ontology/workflows`, `…/:workflow/runs` and `…/runs/:runId` read the declarations
191
191
  * and the SDK's run records for callers holding `workflow:<workflow>:read` and the platform;
192
+ * - `GET /api/ontology/workflows/:workflow/structure`, for the same callers, serves what the build
193
+ * read of the workflow's code (`../workflow-structure.ts`), `null` when it has none;
192
194
  * - `GET /api/ontology/workflows/:workflow/starts` lists the starts its action triggers decided,
193
195
  * pending and started, for the same callers;
194
196
  * - `GET` and `POST /api/ontology/workflows/sweep`, verified with the cron secret, start the
@@ -25,7 +25,7 @@ import { validate } from "../runtime/validation.js";
25
25
  import { triggerContext, WorkflowStartFailed, } from "../runtime/workflow-starts.js";
26
26
  import { RECOVERY_CONFIRM_MS, RECOVERY_COVERAGE_MARGIN_MS, RECOVERY_FIRST_SWEEP_MS, } from "../start-recovery-contract.js";
27
27
  import { nextCronTime, } from "../workflow.js";
28
- import { platformWorkflows, setWorkflowBinding, WORKFLOW_BASE_PATH, workflowSdk, } from "../workflow-runtime.js";
28
+ import { platformWorkflows, setWorkflowBinding, WORKFLOW_BASE_PATH, workflowSdk, workflowStructures, } from "../workflow-runtime.js";
29
29
  import { callbackIdentityToken } from "./workflow-callback.js";
30
30
  import { expireAgentTask, startAgentTask, } from "./agent/task-start.js";
31
31
  import { CurrentPrincipal, WORKLOAD_TOKEN_TYPE, withPrincipal, workloadKind, } from "./authentication.js";
@@ -565,6 +565,8 @@ function expected(effect, tags) {
565
565
  * `workflow:<workflow>:start`, or for the platform;
566
566
  * - `GET /api/ontology/workflows`, `…/:workflow/runs` and `…/runs/:runId` read the declarations
567
567
  * and the SDK's run records for callers holding `workflow:<workflow>:read` and the platform;
568
+ * - `GET /api/ontology/workflows/:workflow/structure`, for the same callers, serves what the build
569
+ * read of the workflow's code (`../workflow-structure.ts`), `null` when it has none;
568
570
  * - `GET /api/ontology/workflows/:workflow/starts` lists the starts its action triggers decided,
569
571
  * pending and started, for the same callers;
570
572
  * - `GET` and `POST /api/ontology/workflows/sweep`, verified with the cron secret, start the
@@ -1486,6 +1488,17 @@ export function workflowsLayer(options) {
1486
1488
  nextCursor: page.value.hasMore ? page.value.cursor : null,
1487
1489
  });
1488
1490
  })));
1491
+ // What the build read of the workflow's code: its steps, waits, branches and loops.
1492
+ yield* router.add("GET", `${WORKFLOW_BASE_PATH}/workflows/:workflow/structure`, authorized((caller) => Effect.gen(function* () {
1493
+ const params = yield* HttpRouter.params;
1494
+ const found = yield* readable(caller, params.workflow);
1495
+ if (!found.ok) {
1496
+ return found.refused;
1497
+ }
1498
+ const workflowId = compiledWorkflowId(found.workflow.declaration.run);
1499
+ const structure = workflowId === undefined ? undefined : workflowStructures()?.[workflowId];
1500
+ return json({ structure: structure ?? null });
1501
+ })));
1489
1502
  yield* router.add("GET", `${WORKFLOW_BASE_PATH}/workflows/:workflow/runs/:runId`, authorized((caller, request) => Effect.gen(function* () {
1490
1503
  const requestId = yield* RequestId;
1491
1504
  const params = yield* HttpRouter.params;
@@ -5,6 +5,7 @@ import type { Files } from "./files.js";
5
5
  import type { OntologyActions, OntologyReads, OntologyWrites } from "./runtime.js";
6
6
  import type { StartRecoveryInput, StartRecoveryOutcome } from "./start-recovery-contract.js";
7
7
  import type { WorkflowReservation } from "./runtime/workflow-admission.js";
8
+ import type { WorkflowStructures } from "./workflow-structure.js";
8
9
  /**
9
10
  * The ontology service's workflow runtime, shared through `globalThis` so that every copy of this
10
11
  * module a bundler makes sees the same one. This module imports none of the Workflow SDK: the
@@ -87,6 +88,10 @@ export declare function workflowBinding(): WorkflowBinding | undefined;
87
88
  export declare function setPlatformWorkflows(workflows: PlatformWorkflows | undefined): void;
88
89
  /** The platform's workflow functions as the generated plugin registered them; `undefined` before. */
89
90
  export declare function platformWorkflows(): PlatformWorkflows | undefined;
91
+ /** Registers what the build read of each workflow's code; the latest registration wins. */
92
+ export declare function setWorkflowStructures(structures: WorkflowStructures | undefined): void;
93
+ /** The build's workflow structures by workflow id, as the generated plugin registered them. */
94
+ export declare function workflowStructures(): WorkflowStructures | undefined;
90
95
  /** The Workflow SDK as `installWorkflowRuntime()` registered it; `undefined` before. */
91
96
  export declare function workflowSdk(): WorkflowSdk | undefined;
92
97
  /** `run` was called where no step runs: in a `"use workflow"` body or outside any workflow. */
@@ -17,6 +17,7 @@ export const WORKFLOW_ROUTE_BASE = "/.well-known/workflow/v1";
17
17
  const BINDING = Symbol.for("@segmentstream/ontology/workflow-binding");
18
18
  const SDK = Symbol.for("@segmentstream/ontology/workflow-sdk");
19
19
  const PLATFORM = Symbol.for("@segmentstream/ontology/platform-workflows");
20
+ const STRUCTURES = Symbol.for("@segmentstream/ontology/workflow-structures");
20
21
  const globals = globalThis;
21
22
  /** Registers the Workflow SDK for the service's workflow routes; the first registration stays. */
22
23
  export function setWorkflowSdk(sdk) {
@@ -37,6 +38,14 @@ export function setPlatformWorkflows(workflows) {
37
38
  export function platformWorkflows() {
38
39
  return globals[PLATFORM];
39
40
  }
41
+ /** Registers what the build read of each workflow's code; the latest registration wins. */
42
+ export function setWorkflowStructures(structures) {
43
+ globals[STRUCTURES] = structures;
44
+ }
45
+ /** The build's workflow structures by workflow id, as the generated plugin registered them. */
46
+ export function workflowStructures() {
47
+ return globals[STRUCTURES];
48
+ }
40
49
  /** The Workflow SDK as `installWorkflowRuntime()` registered it; `undefined` before. */
41
50
  export function workflowSdk() {
42
51
  return globals[SDK];
@@ -0,0 +1,52 @@
1
+ import type * as TS from "typescript";
2
+ import { type WorkflowStructure, type WorkflowStructures } from "./workflow-structure.js";
3
+ /**
4
+ * Reads what each workflow does from its source, at build time: see `./workflow-structure.ts` for
5
+ * the shape. The Workflow SDK's builder finds the workflow and step functions and gives them ids;
6
+ * this reading walks each workflow function's body in TypeScript's syntax tree and follows the
7
+ * calls it can resolve: steps, the SDK's waits, `agentTask`, and helpers declared in the project.
8
+ * It never runs the code. What it cannot resolve becomes an `unknown` node and clears `complete`.
9
+ */
10
+ /** The parts of the Workflow SDK's build manifest the reading uses, by file relative to the root. */
11
+ export interface WorkflowBuildManifest {
12
+ readonly steps?: Readonly<Record<string, Readonly<Record<string, {
13
+ readonly stepId: string;
14
+ }>>>>;
15
+ readonly workflows?: Readonly<Record<string, Readonly<Record<string, {
16
+ readonly workflowId: string;
17
+ }>>>>;
18
+ }
19
+ /** Reads a file's text, or `undefined` when it cannot be read. */
20
+ export type SourceReader = (path: string) => string | undefined;
21
+ /**
22
+ * The comment directly above a node, without its markers: the last group of comments not
23
+ * separated from the node, or from each other, by a blank line. JSDoc tags are left out.
24
+ */
25
+ export declare function leadingComment(ts: typeof TS, node: TS.Node, source: TS.SourceFile): string | undefined;
26
+ /**
27
+ * The structure of one workflow function, `name` in `file`. `stepKey` names a step function the
28
+ * way the runs record it; `agentSteps` are the step keys of `agentTask`.
29
+ */
30
+ export declare function readWorkflowStructure(input: {
31
+ readonly ts: typeof TS;
32
+ readonly root: string;
33
+ readonly file: string;
34
+ readonly name: string;
35
+ readonly stepKey: (file: string, name: string) => string;
36
+ readonly agentSteps?: ReadonlyArray<string>;
37
+ readonly read?: SourceReader;
38
+ }): WorkflowStructure;
39
+ /**
40
+ * The structures of every workflow in a build's manifest, by workflow id, read from the sources
41
+ * under `root`. The step keys come from the manifest; a step it does not list is keyed as the SDK
42
+ * names a project's own steps. A workflow whose reading throws is left out.
43
+ */
44
+ export declare function readWorkflowStructures(input: {
45
+ readonly ts: typeof TS;
46
+ readonly root: string;
47
+ readonly manifest: WorkflowBuildManifest;
48
+ /** Files of the build that are not the workspace's: the platform's own workflows. */
49
+ readonly skip?: (file: string) => boolean;
50
+ readonly read?: SourceReader;
51
+ readonly onError?: (workflowId: string, error: unknown) => void;
52
+ }): WorkflowStructures;