Compare commits

...
26 changed files with 9306 additions and 3 deletions
+1
View File
@@ -60,6 +60,7 @@ sdk:
- "packages/client/**"
- "packages/highlight/**"
- "packages/protocol/**"
- "packages/workflows/**"
browser:
- "packages/server/src/server/agent/provider-snapshot-manager.ts"
+8
View File
@@ -127,6 +127,14 @@ jobs:
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
run: npm run test --workspace=@getpaseo/highlight
- name: Build workflows package
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
run: npm run build:workflows
- name: Run workflows tests
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
run: npm run test --workspace=@getpaseo/workflows
- name: Typecheck client examples
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
run: npm run typecheck:examples --workspace=@getpaseo/client
+11
View File
@@ -67,6 +67,17 @@
"entry": ["src/index.ts", "src/**/*.test.ts"],
"project": ["src/**/*.ts"]
},
"packages/workflows": {
"entry": [
"src/index.ts",
"src/ir.ts",
"src/dsl.ts",
"src/yaml.ts",
"src/testing.ts",
"test/**/*.test.ts"
],
"project": ["src/**/*.ts", "test/**/*.ts"]
},
"packages/expo-two-way-audio": {
"entry": ["src/index.ts"],
"project": ["src/**/*.ts"]
+20 -3
View File
@@ -16,6 +16,7 @@
"packages/highlight",
"packages/plugin",
"packages/protocol",
"packages/workflows",
"packages/client",
"packages/server",
"packages/app",
@@ -6709,6 +6710,10 @@
"resolved": "packages/website",
"link": true
},
"node_modules/@getpaseo/workflows": {
"resolved": "packages/workflows",
"link": true
},
"node_modules/@gorhom/bottom-sheet": {
"version": "5.2.14",
"resolved": "https://registry.npmjs.org/@gorhom/bottom-sheet/-/bottom-sheet-5.2.14.tgz",
@@ -14924,7 +14929,6 @@
"version": "8.11.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.11.0.tgz",
"integrity": "sha512-wGgprdCvMalC0BztXvitD2hC04YffAvtsUn93JbGXYLAtCUO4xd17mCCZQxUOItiBwZvJScWo8NIvQMQ71rdpg==",
"dev": true,
"license": "MIT",
"dependencies": {
"fast-deep-equal": "^3.1.1",
@@ -31398,7 +31402,6 @@
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
"integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
@@ -36228,7 +36231,6 @@
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
"integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",
"dev": true,
"license": "BSD-2-Clause",
"dependencies": {
"punycode": "^2.1.0"
@@ -43159,6 +43161,21 @@
}
}
},
"packages/workflows": {
"name": "@getpaseo/workflows",
"version": "0.1.0",
"license": "Apache-2.0",
"dependencies": {
"ajv": "^8.11.0",
"js-yaml": "^4.1.1",
"zod": "^4.4.3"
},
"devDependencies": {
"@types/node": "^20.9.0",
"typescript": "^5.9.3",
"vitest": "^4.1.6"
}
},
"plugins": {
"name": "@getpaseo/builtin-plugins",
"version": "0.18.1",
+3
View File
@@ -27,6 +27,7 @@
"packages/highlight",
"packages/plugin",
"packages/protocol",
"packages/workflows",
"packages/client",
"packages/server",
"packages/app",
@@ -60,6 +61,8 @@
"build:relay:clean": "npm run build:clean --workspace=@getpaseo/relay",
"build:protocol": "npm run build --workspace=@getpaseo/protocol",
"build:protocol:clean": "npm run build:clean --workspace=@getpaseo/protocol",
"build:workflows": "npm run build --workspace=@getpaseo/workflows",
"build:workflows:clean": "npm run build:clean --workspace=@getpaseo/workflows",
"build:client": "npm run build --workspace=@getpaseo/client",
"build:client:clean": "npm run build:protocol:clean && npm run build:clean --workspace=@getpaseo/client",
"build:server-deps": "npm run build:client && concurrently --kill-others-on-fail --names highlight,plugin,relay --prefix-colors yellow,green,blue \"npm run build:highlight\" \"npm run build:plugin\" \"npm run build:relay\"",
+211
View File
@@ -0,0 +1,211 @@
Copyright (c) 2025-present Mohamed Boudra
Portions of this software are licensed as follows:
* Third-party components incorporated into Paseo remain licensed under
the licenses provided by their respective copyright holders.
* Except for those third-party components, Paseo is licensed under the
Apache License, Version 2.0, reproduced below.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+60
View File
@@ -0,0 +1,60 @@
{
"name": "@getpaseo/workflows",
"version": "0.1.0",
"description": "Durable, subject-keyed workflow state machine, IR, DSL, and YAML compiler for Paseo",
"license": "Apache-2.0",
"files": [
"dist",
"!dist/**/*.map",
"LICENSE"
],
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"source": "./src/index.ts",
"default": "./dist/index.js"
},
"./ir": {
"types": "./dist/ir.d.ts",
"source": "./src/ir.ts",
"default": "./dist/ir.js"
},
"./dsl": {
"types": "./dist/dsl.d.ts",
"source": "./src/dsl.ts",
"default": "./dist/dsl.js"
},
"./yaml": {
"types": "./dist/yaml.d.ts",
"source": "./src/yaml.ts",
"default": "./dist/yaml.js"
},
"./testing": {
"types": "./dist/testing.d.ts",
"source": "./src/testing.ts",
"default": "./dist/testing.js"
}
},
"publishConfig": {
"access": "public"
},
"scripts": {
"clean": "node ../../scripts/clean-package-dist.mjs",
"build": "tsc -p tsconfig.json --incremental false",
"build:clean": "npm run clean && npm run build",
"prepack": "npm run build:clean",
"typecheck": "tsgo --noEmit && tsgo -p tsconfig.typecheck.json --noEmit",
"test": "vitest run"
},
"dependencies": {
"ajv": "^8.11.0",
"js-yaml": "^4.1.1",
"zod": "^4.4.3"
},
"devDependencies": {
"@types/node": "^20.9.0",
"typescript": "^5.9.3",
"vitest": "^4.1.6"
}
}
File diff suppressed because it is too large Load Diff
+549
View File
@@ -0,0 +1,549 @@
import type { z } from "zod";
import { createWorkflowEngineImpl } from "./internal/engine.js";
import type {
AgentSpecIR,
AgentTargetIR,
AllowOutputIR,
AuthGrantIR,
GateChoiceIR,
JsonObject,
JsonSchema,
JsonValue,
TerminalStatus,
WorkflowIR,
} from "./ir.js";
export type {
AgentSpecIR,
AgentTargetIR,
AllowOutputIR,
AuthGrantIR,
GateChoiceIR,
JsonObject,
JsonSchema,
JsonValue,
TerminalStatus,
WorkflowIR,
};
export { validateWorkflowIR, WorkflowValidationError } from "./ir.js";
export interface Clock {
now(): Date;
}
export interface EventActor {
readonly id: string;
readonly login?: string;
readonly isBot: boolean;
readonly isSelfApp: boolean;
}
export interface NormalizedIntegrationEvent {
readonly id: string;
readonly type: string;
readonly connection?: string;
readonly actor?: EventActor;
readonly subject?: {
readonly key?: string;
readonly data?: JsonObject;
};
readonly payload: JsonObject;
readonly prompt?: string;
readonly occurredAt: Date;
}
export interface IntegrationStorageEntry {
readonly key: string;
readonly value: JsonValue;
}
/**
* Narrow scoped key-value/document storage provided to integrations.
* Backed by one generic table or store in the host runtime — never a raw database handle.
*/
export interface IntegrationStorage {
get<T extends JsonValue = JsonValue>(key: string): Promise<T | undefined>;
set(key: string, value: JsonValue, options?: { readonly ttlMs?: number }): Promise<void>;
delete(key: string): Promise<void>;
list(prefix?: string): Promise<readonly IntegrationStorageEntry[]>;
withLock<T>(key: string, ttlMs: number, fn: () => Promise<T>): Promise<T>;
}
export interface IntegrationConnectionRecord {
readonly id: string;
readonly name: string;
readonly integration: string;
readonly config?: JsonObject;
readonly secret?: JsonObject;
}
export interface IntegrationConnections {
get(connectionNameOrId: string): Promise<IntegrationConnectionRecord | undefined>;
list(): Promise<readonly IntegrationConnectionRecord[]>;
}
export interface IntegrationLogger {
debug(message: string, meta?: JsonObject): void;
info(message: string, meta?: JsonObject): void;
warn(message: string, meta?: JsonObject): void;
error(message: string, meta?: JsonObject): void;
}
/**
* The ONLY host context passed into integration hooks (`triggers`, `steps`, `auth`, `tools`).
* Deliberately excludes database handles, SQL clients, and workflow engine internals.
*/
export interface IntegrationContext {
readonly scopeId: string;
readonly storage: IntegrationStorage;
readonly connections: IntegrationConnections;
readonly ingest: (event: NormalizedIntegrationEvent) => Promise<void>;
readonly fetch: typeof globalThis.fetch;
readonly log: IntegrationLogger;
readonly now: () => Date;
}
export interface IntegrationTriggerSpec {
readonly event: string;
readonly filterSchema?: z.ZodType;
readonly normalize?: (
raw: JsonObject,
ctx: IntegrationContext,
) => Promise<NormalizedIntegrationEvent> | NormalizedIntegrationEvent;
readonly matchFilters?: (event: NormalizedIntegrationEvent, filters: JsonObject) => boolean;
}
export type IntegrationStepExecuteResult =
| { readonly status: "completed"; readonly outcome: string; readonly output?: JsonObject }
| { readonly status: "suspended"; readonly waitKey: string; readonly timeoutMs?: number };
export type IntegrationStepEventResult =
| { readonly status: "completed"; readonly outcome: string; readonly output?: JsonObject }
| { readonly status: "still_waiting" };
/** Uniform contract covering both synchronous actions and suspended event waits. */
export interface IntegrationStepSpec {
readonly inputSchema: JsonSchema | z.ZodType;
readonly outputSchema?: JsonSchema | z.ZodType;
readonly outcomes: readonly string[];
execute(input: JsonObject, ctx: IntegrationContext): Promise<IntegrationStepExecuteResult>;
onEvent?(
event: NormalizedIntegrationEvent,
input: JsonObject,
ctx: IntegrationContext,
): Promise<IntegrationStepEventResult>;
}
export interface IntegrationAuthLease {
readonly leaseId: string;
readonly env: Readonly<Record<string, string>>;
readonly expiresAt?: Date;
}
export interface IntegrationAuthSlot {
mint(scope: AuthGrantIR, ctx: IntegrationContext): Promise<IntegrationAuthLease>;
revoke(leaseId: string, ctx: IntegrationContext): Promise<void>;
}
export interface IntegrationToolDefinition {
readonly name: string;
readonly description: string;
readonly inputSchema: JsonSchema;
}
export interface IntegrationToolsSlot {
readonly grantSchema: z.ZodType<JsonValue>;
readonly tools: readonly IntegrationToolDefinition[];
execute(
tool: string,
args: JsonObject,
grant: JsonValue,
ctx: IntegrationContext,
): Promise<JsonValue>;
}
/** 4-slot opt-in integration contract (triggers, steps, auth, tools). */
export interface WorkflowIntegration {
readonly id: string;
readonly triggers?: Readonly<Record<string, IntegrationTriggerSpec>>;
readonly steps?: Readonly<Record<string, IntegrationStepSpec>>;
readonly auth?: IntegrationAuthSlot;
readonly tools?: IntegrationToolsSlot;
}
export interface IntegrationRegistry {
get(id: string): WorkflowIntegration | undefined;
list(): readonly WorkflowIntegration[];
}
export function createIntegrationRegistry(
integrations: readonly WorkflowIntegration[],
): IntegrationRegistry {
const byId = new Map<string, WorkflowIntegration>();
for (const integration of integrations) {
if (byId.has(integration.id)) {
throw new Error(`duplicate workflow integration id "${integration.id}"`);
}
byId.set(integration.id, integration);
}
return {
get(id: string): WorkflowIntegration | undefined {
return byId.get(id);
},
list(): readonly WorkflowIntegration[] {
return [...byId.values()];
},
};
}
export interface ActiveAuthLease {
readonly integrationId: string;
readonly leaseId: string;
}
export type WorkflowRunStatus =
| "queued"
| "running"
| "waiting"
| "paused"
| "done"
| "failed"
| "cancelled";
export type StepAttemptStatus =
| "running"
| "waiting"
| "completed"
| "failed"
| "cancelled"
| "skipped";
export type StepWaitSpec =
| {
readonly kind: "integration";
readonly integrationId: string;
readonly stepName: string;
readonly waitKey: string;
readonly input: JsonObject;
readonly wakeAt?: Date;
}
| {
readonly kind: "wait_workflow";
readonly workflowId: string;
readonly outputKey: string;
readonly wakeAt?: Date;
}
| {
readonly kind: "gate";
readonly gateId: string;
readonly wakeAt?: Date;
}
| {
readonly kind: "sleep";
readonly wakeAt: Date;
};
export interface StepAttemptRecord {
readonly id: string;
readonly runId: string;
readonly stepId: string;
readonly attempt: number;
readonly executionId: string;
readonly status: StepAttemptStatus;
readonly outcome?: string;
readonly output?: JsonObject;
readonly error?: string;
readonly wait?: StepWaitSpec;
readonly activeLeases: readonly ActiveAuthLease[];
readonly startedAt: Date;
readonly finishedAt?: Date;
}
export interface WorkflowGateRecord {
readonly id: string;
readonly runId: string;
readonly workflowId: string;
readonly stepId: string;
readonly attemptId: string;
readonly title: string;
readonly summary?: string;
readonly recommended?: string;
readonly choices: readonly GateChoiceIR[];
readonly status: "open" | "resolved" | "expired" | "cancelled";
readonly openedAt: Date;
readonly expiresAt?: Date;
readonly resolution?: GateResolution;
}
export interface GateResolution {
readonly choice: string;
readonly note?: string;
readonly actor?: string;
readonly resolvedAt: Date;
}
export interface GateResolutionInput {
readonly choice: string;
readonly note?: string;
readonly actor?: string;
}
export interface PublishedWorkflowOutput {
readonly workflowId: string;
readonly outputKey: string;
readonly payload: JsonObject;
readonly publishedAt: Date;
}
export interface SuspendedWaitRecord {
readonly runId: string;
readonly attemptId: string;
readonly stepId: string;
readonly wait: StepWaitSpec;
}
export interface WorkflowRunSnapshot {
readonly id: string;
readonly workflowId: string;
readonly status: WorkflowRunStatus;
readonly pausedFromStatus?: "running" | "waiting";
readonly subjectKey?: string;
readonly subjectData: JsonObject;
readonly inputs: Readonly<Record<string, JsonValue>>;
readonly event?: NormalizedIntegrationEvent;
readonly currentState: string;
readonly loopCounts: Readonly<Record<string, number>>;
readonly attempts: readonly StepAttemptRecord[];
readonly lastGate?: {
readonly choice: string;
readonly note: string | null;
readonly actor: string | null;
};
readonly terminalReason?: string;
readonly terminalOutputs?: JsonObject;
readonly createdAt: Date;
readonly updatedAt: Date;
readonly completedAt?: Date;
}
export interface AcceptWorkflowRunInput {
readonly workflowId: string;
readonly initialState: string;
readonly subjectKey?: string;
readonly subjectData: JsonObject;
readonly onConflict?: "signal" | "queue" | "ignore" | "cancel_previous";
readonly inputs: Readonly<Record<string, JsonValue>>;
readonly event?: NormalizedIntegrationEvent;
readonly now: Date;
}
export type AcceptWorkflowRunResult =
| { readonly action: "started"; readonly run: WorkflowRunSnapshot }
| { readonly action: "queued"; readonly run: WorkflowRunSnapshot }
| { readonly action: "ignored"; readonly existingRun: WorkflowRunSnapshot }
| { readonly action: "signal"; readonly existingRun: WorkflowRunSnapshot }
| {
readonly action: "replaced";
readonly run: WorkflowRunSnapshot;
readonly cancelledRun: WorkflowRunSnapshot;
};
export interface BeginStepAttemptInput {
readonly runId: string;
readonly stepId: string;
readonly incrementLoop: boolean;
readonly now: Date;
}
export interface CompleteStepAttemptInput {
readonly runId: string;
readonly attemptId: string;
readonly status: "completed" | "failed" | "cancelled" | "skipped";
readonly outcome?: string;
readonly output?: JsonObject;
readonly error?: string;
readonly now: Date;
}
export interface TransitionRunInput {
readonly runId: string;
readonly status: WorkflowRunStatus;
readonly currentState?: string;
readonly pausedFromStatus?: "running" | "waiting";
readonly lastGate?: WorkflowRunSnapshot["lastGate"];
readonly terminalReason?: string;
readonly terminalOutputs?: JsonObject;
readonly now: Date;
}
export interface OpenGateInput {
readonly runId: string;
readonly workflowId: string;
readonly stepId: string;
readonly attemptId: string;
readonly title: string;
readonly summary?: string;
readonly recommended?: string;
readonly choices: readonly GateChoiceIR[];
readonly openedAt: Date;
readonly expiresAt?: Date;
}
export interface ListRunsFilter {
readonly workflowId?: string;
readonly subjectKey?: string;
readonly status?: WorkflowRunStatus | readonly WorkflowRunStatus[];
}
export interface ListOpenGatesFilter {
readonly workflowId?: string;
readonly runId?: string;
}
/** Persistence seam implemented by host storage backends (remote, embedded, or in-memory). */
export interface WorkflowStore {
acceptRun(input: AcceptWorkflowRunInput): Promise<AcceptWorkflowRunResult>;
loadRun(runId: string): Promise<WorkflowRunSnapshot | undefined>;
listRuns(filter?: ListRunsFilter): Promise<readonly WorkflowRunSnapshot[]>;
dequeueNextRun(
workflowId: string,
subjectKey: string,
now: Date,
): Promise<WorkflowRunSnapshot | undefined>;
beginStepAttempt(input: BeginStepAttemptInput): Promise<StepAttemptRecord>;
setAttemptLeases(attemptId: string, leases: readonly ActiveAuthLease[]): Promise<void>;
setAttemptExecutionId(attemptId: string, executionId: string): Promise<void>;
suspendStepAttempt(attemptId: string, wait: StepWaitSpec): Promise<void>;
completeStepAttempt(input: CompleteStepAttemptInput): Promise<WorkflowRunSnapshot>;
transitionRun(input: TransitionRunInput): Promise<WorkflowRunSnapshot>;
listSuspendedWaits(
kind?: StepWaitSpec["kind"],
options?: { readonly includePaused?: boolean },
): Promise<readonly SuspendedWaitRecord[]>;
findExpiredWaits(now: Date): Promise<readonly SuspendedWaitRecord[]>;
publishWorkflowOutput(input: PublishedWorkflowOutput): Promise<readonly SuspendedWaitRecord[]>;
findWorkflowOutput(
workflowId: string,
outputKey: string,
): Promise<PublishedWorkflowOutput | undefined>;
openGate(input: OpenGateInput): Promise<WorkflowGateRecord>;
getGate(gateId: string): Promise<WorkflowGateRecord | undefined>;
listOpenGates(filter?: ListOpenGatesFilter): Promise<readonly WorkflowGateRecord[]>;
resolveGate(gateId: string, resolution: GateResolution): Promise<WorkflowGateRecord | undefined>;
expireGate(gateId: string): Promise<WorkflowGateRecord | undefined>;
cancelRunGates(runId: string): Promise<readonly WorkflowGateRecord[]>;
}
export interface AgentStepRequest {
readonly runId: string;
readonly workflowId: string;
readonly stepId: string;
readonly attempt: number;
readonly executionId: string;
readonly prompt: string;
readonly title?: string;
readonly target?: AgentTargetIR;
readonly agent?: AgentSpecIR;
readonly continuation?: { readonly mode: string };
readonly env: Readonly<Record<string, string>>;
readonly outputSchema?: JsonSchema;
readonly tools?: Readonly<Record<string, JsonValue>>;
readonly allowOutputs?: Readonly<Record<string, AllowOutputIR>>;
readonly maxRuntimeMs?: number;
readonly idleTimeoutMs?: number;
readonly startupTimeoutMs?: number;
readonly autoArchive?: boolean;
readonly background?: boolean;
}
export type AgentStepStartResult =
| { readonly status: "completed"; readonly outcome?: string; readonly output?: JsonObject }
| { readonly status: "running"; readonly executionId?: string }
| { readonly status: "failed"; readonly error: string };
export interface AgentRunner {
start(request: AgentStepRequest): Promise<AgentStepStartResult>;
cancel(executionId: string, reason: string): Promise<void>;
inspect?(executionId: string): Promise<AgentStepStartResult>;
}
export interface GateSink {
onGateOpened(gate: WorkflowGateRecord): Promise<void>;
onGateResolved?(gate: WorkflowGateRecord): Promise<void>;
onGateExpired?(gate: WorkflowGateRecord): Promise<void>;
}
export interface StartWorkflowInput {
readonly workflowId: string;
readonly inputs?: Readonly<Record<string, JsonValue>>;
readonly event?: NormalizedIntegrationEvent;
readonly subjectKey?: string;
readonly subjectData?: JsonObject;
}
export interface CompleteAgentStepInput {
readonly runId: string;
readonly executionId: string;
readonly outcome?: string;
readonly output?: JsonObject;
readonly error?: string;
}
export interface PublishOutputInput {
readonly workflowId: string;
readonly outputKey: string;
readonly payload: JsonObject;
}
export interface PublishOutputResult {
readonly output: PublishedWorkflowOutput;
readonly resumedRuns: readonly WorkflowRunSnapshot[];
}
export interface IngestResult {
readonly matchedRuns: readonly WorkflowRunSnapshot[];
readonly resumedRuns: readonly WorkflowRunSnapshot[];
}
export interface TickResult {
readonly wokenRuns: readonly WorkflowRunSnapshot[];
}
export interface WorkflowEngineOptions {
readonly store: WorkflowStore;
readonly runner: AgentRunner;
readonly gates: GateSink;
readonly integrations: IntegrationRegistry | readonly WorkflowIntegration[];
readonly clock: Clock;
readonly workflows?: readonly WorkflowIR[];
readonly scopeId?: string;
readonly storage?: IntegrationStorage;
readonly connections?: IntegrationConnections;
readonly fetch?: typeof globalThis.fetch;
readonly log?: IntegrationLogger;
}
/** Opaque durable execution engine interface (storage- and runtime-agnostic). */
export interface WorkflowEngine {
registerWorkflow(workflow: WorkflowIR): void;
ingest(event: NormalizedIntegrationEvent): Promise<IngestResult>;
start(input: StartWorkflowInput): Promise<WorkflowRunSnapshot>;
completeAgentStep(input: CompleteAgentStepInput): Promise<WorkflowRunSnapshot>;
resolveGate(gateId: string, resolution: GateResolutionInput): Promise<WorkflowRunSnapshot>;
publishOutput(input: PublishOutputInput): Promise<PublishOutputResult>;
pause(runId: string): Promise<WorkflowRunSnapshot>;
resume(runId: string): Promise<WorkflowRunSnapshot>;
cancel(runId: string, reason?: string): Promise<WorkflowRunSnapshot>;
tick(): Promise<TickResult>;
getRun(runId: string): Promise<WorkflowRunSnapshot | undefined>;
listRuns(filter?: ListRunsFilter): Promise<readonly WorkflowRunSnapshot[]>;
listOpenGates(filter?: ListOpenGatesFilter): Promise<readonly WorkflowGateRecord[]>;
}
export function createWorkflowEngine(options: WorkflowEngineOptions): WorkflowEngine {
return createWorkflowEngineImpl(options);
}
@@ -0,0 +1,38 @@
const DURATION_PATTERN = /^([1-9][0-9]*)(ms|s|m|h|d)$/u;
const UNIT_MS: Readonly<Record<string, number>> = {
ms: 1,
s: 1_000,
m: 60_000,
h: 3_600_000,
d: 86_400_000,
};
export type DurationInput = number | string;
export function parseDurationMs(value: DurationInput, fieldName = "duration"): number {
if (typeof value === "number") {
if (!Number.isFinite(value) || value <= 0) {
throw new Error(`${fieldName} must be a positive finite number of milliseconds`);
}
return Math.trunc(value);
}
const trimmed = value.trim();
const match = DURATION_PATTERN.exec(trimmed);
if (match === null) {
throw new Error(
`${fieldName} must be a positive duration like "30s", "15m", "2h", or "14d" (got ${JSON.stringify(value)})`,
);
}
const amount = Number(match[1]);
const unit = match[2];
const multiplier = unit === undefined ? undefined : UNIT_MS[unit];
if (multiplier === undefined) {
throw new Error(`${fieldName} has unsupported unit in ${JSON.stringify(value)}`);
}
const total = amount * multiplier;
if (!Number.isSafeInteger(total) || total <= 0) {
throw new Error(`${fieldName} is out of range: ${JSON.stringify(value)}`);
}
return total;
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,745 @@
export type JsonPrimitive = string | number | boolean | null;
export type JsonValue =
| JsonPrimitive
| readonly JsonValue[]
| { readonly [key: string]: JsonValue };
export interface JsonObject {
readonly [key: string]: JsonValue;
}
export type JsonSchema = JsonObject;
export type ExprPath =
| { readonly namespace: "event"; readonly path: readonly string[] }
| { readonly namespace: "inputs"; readonly name: string }
| { readonly namespace: "subject"; readonly field: "key" }
| { readonly namespace: "subject"; readonly field: "data"; readonly path: readonly string[] }
| { readonly namespace: "steps"; readonly stepId: string; readonly field: "outcome" | "attempts" }
| {
readonly namespace: "steps";
readonly stepId: string;
readonly field: "outputs";
readonly path: readonly string[];
}
| { readonly namespace: "gate"; readonly field: "choice" | "note" | "actor" }
| { readonly namespace: "execution"; readonly field: "id" }
| { readonly namespace: "paseo"; readonly field: "prompt" }
| { readonly namespace: "values"; readonly name: string };
export type BinaryOperator = "==" | "!=" | "&&" | "||" | "??";
export type ExprNode =
| { readonly kind: "literal"; readonly value: JsonValue }
| { readonly kind: "path"; readonly path: ExprPath }
| { readonly kind: "not"; readonly value: ExprNode }
| {
readonly kind: "binary";
readonly operator: BinaryOperator;
readonly left: ExprNode;
readonly right: ExprNode;
}
| { readonly kind: "template"; readonly parts: readonly (string | ExprNode)[] };
export interface StepEvalState {
readonly outcome: string | null;
readonly outputs: JsonObject | null;
readonly attempts: number;
}
export interface GateEvalState {
readonly choice: string | null;
readonly note: string | null;
readonly actor: string | null;
}
export interface ExpressionContext {
readonly event: JsonValue;
readonly prompt: string;
readonly inputs: Readonly<Record<string, JsonValue>>;
readonly subject: {
readonly key: string | null;
readonly data: JsonObject;
};
readonly steps: Readonly<Record<string, StepEvalState>>;
readonly gate: GateEvalState;
readonly values: Readonly<Record<string, ExprNode>>;
readonly executionId: string | null;
}
export class ExpressionSyntaxError extends Error {
constructor(message: string) {
super(`invalid workflow expression: ${message}`);
this.name = "ExpressionSyntaxError";
}
}
export class ExpressionEvaluationError extends Error {
constructor(message: string) {
super(`workflow expression could not be evaluated: ${message}`);
this.name = "ExpressionEvaluationError";
}
}
type Operator = "!" | BinaryOperator;
type Token =
| { readonly kind: "literal"; readonly value: JsonValue }
| { readonly kind: "identifier"; readonly value: string }
| { readonly kind: "operator"; readonly value: Operator }
| { readonly kind: "dot" }
| { readonly kind: "left" }
| { readonly kind: "right" }
| { readonly kind: "array-left" }
| { readonly kind: "array-right" }
| { readonly kind: "object-left" }
| { readonly kind: "object-right" }
| { readonly kind: "comma" }
| { readonly kind: "colon" }
| { readonly kind: "end" };
const TOKEN_PATTERN =
/\s*(?:(true|false|null)\b|(-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)|("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')|([a-zA-Z_][a-zA-Z0-9_-]*)|(!=|==|&&|\|\||\?\?|!)|(\.)|(\()|(\))|(\[)|(\])|(\{)|(\})|(,)|(:)|(.))/gy;
export function isJsonValue(value: unknown): value is JsonValue {
if (value === null || typeof value === "string" || typeof value === "boolean") {
return true;
}
if (typeof value === "number") {
return Number.isFinite(value);
}
if (Array.isArray(value)) {
return value.every(isJsonValue);
}
if (typeof value === "object") {
return Object.values(value).every(isJsonValue);
}
return false;
}
export function isJsonObject(value: unknown): value is JsonObject {
return typeof value === "object" && value !== null && !Array.isArray(value) && isJsonValue(value);
}
export function parseExprPath(dotted: string): ExprPath {
const parts = dotted
.trim()
.split(".")
.map((segment) => segment.trim())
.filter((segment) => segment.length > 0);
if (parts.length === 0) {
throw new ExpressionSyntaxError("empty reference path");
}
return parsePathSegments(parts);
}
export function parseExpression(source: string): ExprNode {
const text = unwrapExpression(source);
const tokens = tokenize(text);
let index = 0;
const parse = (minimumPrecedence = 0): ExprNode => {
let left = parsePrefix();
while (true) {
const token = tokens[index];
if (token?.kind !== "operator" || token.value === "!") {
break;
}
const operator = token.value;
const precedence = operatorPrecedence(operator);
if (precedence < minimumPrecedence) {
break;
}
index += 1;
const right = parse(precedence + 1);
left = { kind: "binary", operator, left, right };
}
return left;
};
const parsePrefix = (): ExprNode => {
const token = tokens[index++];
if (token === undefined) {
throw new ExpressionSyntaxError("expression ended unexpectedly");
}
if (token.kind === "literal") {
return { kind: "literal", value: token.value };
}
if (token.kind === "operator" && token.value === "!") {
return { kind: "not", value: parsePrefix() };
}
if (token.kind === "left") {
const inner = parse();
if (tokens[index]?.kind !== "right") {
throw new ExpressionSyntaxError("missing ')'");
}
index += 1;
return inner;
}
if (token.kind === "array-left") {
return parseArrayLiteral();
}
if (token.kind === "object-left") {
return parseObjectLiteral();
}
if (token.kind !== "identifier") {
throw new ExpressionSyntaxError("expected a value");
}
return parsePath(token.value);
};
const result = parse();
if (tokens[index]?.kind !== "end") {
throw new ExpressionSyntaxError("unexpected trailing token");
}
return result;
function parsePath(first: string): ExprNode {
const parts = [first];
while (tokens[index]?.kind === "dot") {
index += 1;
const next = tokens[index++];
if (next?.kind !== "identifier") {
throw new ExpressionSyntaxError("expected path segment");
}
parts.push(next.value);
}
return { kind: "path", path: parsePathSegments(parts) };
}
function parseArrayLiteral(): ExprNode {
const values: JsonValue[] = [];
if (tokens[index]?.kind === "array-right") {
index += 1;
return { kind: "literal", value: values };
}
while (true) {
values.push(readJsonLiteral());
const separator = tokens[index++];
if (separator?.kind === "array-right") {
break;
}
if (separator?.kind !== "comma") {
throw new ExpressionSyntaxError("expected ',' or ']'");
}
if (tokens[index]?.kind === "array-right") {
throw new ExpressionSyntaxError("trailing comma in array literal");
}
}
return { kind: "literal", value: values };
}
function parseObjectLiteral(): ExprNode {
const value: Record<string, JsonValue> = {};
if (tokens[index]?.kind === "object-right") {
index += 1;
return { kind: "literal", value };
}
while (true) {
const key = tokens[index++];
if (key?.kind !== "literal" || typeof key.value !== "string") {
throw new ExpressionSyntaxError("object keys must be strings");
}
if (tokens[index++]?.kind !== "colon") {
throw new ExpressionSyntaxError("expected ':'");
}
value[key.value] = readJsonLiteral();
const separator = tokens[index++];
if (separator?.kind === "object-right") {
break;
}
if (separator?.kind !== "comma") {
throw new ExpressionSyntaxError("expected ',' or '}'");
}
if (tokens[index]?.kind === "object-right") {
throw new ExpressionSyntaxError("trailing comma in object literal");
}
}
return { kind: "literal", value };
}
function readJsonLiteral(): JsonValue {
const expression = parsePrefix();
if (expression.kind !== "literal") {
throw new ExpressionSyntaxError("JSON literals cannot contain paths or operators");
}
return expression.value;
}
}
/**
* Parse a string containing zero, one, or many `${{ ... }}` or `{{ ... }}` interpolations into
* a canonical `ExprNode`.
* - A plain string with no interpolations becomes `{ kind: "literal", value }`.
* - A string whose entire content is a single interpolation becomes that inner `ExprNode`
* (preserving typed non-string values such as numbers, booleans, arrays, or objects).
* - A mixed template becomes `{ kind: "template", parts }` with adjacent strings merged.
*/
export function parseTemplateExpression(template: string): ExprNode {
const parts: (string | ExprNode)[] = [];
let cursor = 0;
while (cursor < template.length) {
const next = findNextInterpolation(template, cursor);
if (next === undefined) {
parts.push(template.slice(cursor));
break;
}
if (next.start > cursor) {
parts.push(template.slice(cursor, next.start));
}
const end = template.indexOf("}}", next.exprStart);
if (end < 0) {
throw new ExpressionSyntaxError("unterminated template interpolation");
}
const exprText = template.slice(next.exprStart, end).trim();
if (exprText.length === 0) {
throw new ExpressionSyntaxError("empty template interpolation");
}
parts.push(parseExpression(exprText));
cursor = end + 2;
}
return normalizeTemplateParts(parts);
}
/** Build a canonical `ExprNode` from template literal segments and expressions. */
export function buildTemplateExpr(parts: readonly (string | ExprNode)[]): ExprNode {
return normalizeTemplateParts(parts);
}
function appendTemplatePart(merged: (string | ExprNode)[], part: string | ExprNode): void {
if (typeof part === "string") {
if (part.length === 0) {
return;
}
const prev = merged[merged.length - 1];
if (typeof prev === "string") {
merged[merged.length - 1] = prev + part;
} else {
merged.push(part);
}
return;
}
if (part.kind === "template") {
for (const nested of part.parts) {
appendTemplatePart(merged, nested);
}
return;
}
merged.push(part);
}
export function normalizeTemplateParts(rawParts: readonly (string | ExprNode)[]): ExprNode {
const merged: (string | ExprNode)[] = [];
for (const part of rawParts) {
appendTemplatePart(merged, part);
}
if (merged.length === 0) {
return { kind: "literal", value: "" };
}
if (merged.length === 1) {
const sole = merged[0]!;
return typeof sole === "string" ? { kind: "literal", value: sole } : sole;
}
return { kind: "template", parts: merged };
}
export function collectExprPaths(expression: ExprNode): ExprPath[] {
switch (expression.kind) {
case "literal":
return [];
case "path":
return [expression.path];
case "not":
return collectExprPaths(expression.value);
case "binary":
return [...collectExprPaths(expression.left), ...collectExprPaths(expression.right)];
case "template": {
const paths: ExprPath[] = [];
for (const part of expression.parts) {
if (typeof part !== "string") {
paths.push(...collectExprPaths(part));
}
}
return paths;
}
}
}
export function evaluateExpression(expression: ExprNode, context: ExpressionContext): JsonValue {
return evaluateInternal(expression, context, new Set());
}
export function evaluateStringExpression(expression: ExprNode, context: ExpressionContext): string {
const value = evaluateExpression(expression, context);
return formatInterpolatedValue(value);
}
function evaluateInternal(
expression: ExprNode,
context: ExpressionContext,
seenValues: Set<string>,
): JsonValue {
switch (expression.kind) {
case "literal":
return expression.value;
case "path":
return readPath(expression.path, context, seenValues);
case "not":
return !isTruthy(evaluateInternal(expression.value, context, seenValues));
case "binary": {
const left = evaluateInternal(expression.left, context, seenValues);
if (expression.operator === "&&") {
return isTruthy(left) ? evaluateInternal(expression.right, context, seenValues) : left;
}
if (expression.operator === "||") {
return isTruthy(left) ? left : evaluateInternal(expression.right, context, seenValues);
}
if (expression.operator === "??") {
return left === null ? evaluateInternal(expression.right, context, seenValues) : left;
}
const right = evaluateInternal(expression.right, context, seenValues);
if (expression.operator === "==") {
return sameJsonValue(left, right);
}
return !sameJsonValue(left, right);
}
case "template": {
let output = "";
for (const part of expression.parts) {
if (typeof part === "string") {
output += part;
} else {
output += formatInterpolatedValue(evaluateInternal(part, context, seenValues));
}
}
return output;
}
}
}
function readPath(path: ExprPath, context: ExpressionContext, seenValues: Set<string>): JsonValue {
switch (path.namespace) {
case "event":
return readNestedValue(context.event, path.path);
case "inputs":
return context.inputs[path.name] ?? null;
case "subject":
if (path.field === "key") {
return context.subject.key;
}
return readNestedValue(context.subject.data, path.path);
case "steps": {
const step = context.steps[path.stepId];
if (step === undefined) {
return path.field === "attempts" ? 0 : null;
}
if (path.field === "outputs") {
if (step.outputs === null) {
return null;
}
return readNestedValue(step.outputs, path.path);
}
if (path.field === "outcome") {
return step.outcome;
}
return step.attempts;
}
case "gate":
return context.gate[path.field];
case "execution":
return context.executionId;
case "paseo":
return context.prompt;
case "values": {
const valueExpr = context.values[path.name];
if (valueExpr === undefined) {
throw new ExpressionEvaluationError(`value ${path.name} is unavailable`);
}
if (seenValues.has(path.name)) {
throw new ExpressionEvaluationError(`cyclic value reference: ${path.name}`);
}
seenValues.add(path.name);
try {
return evaluateInternal(valueExpr, context, seenValues);
} finally {
seenValues.delete(path.name);
}
}
}
}
function readNestedValue(root: JsonValue, segments: readonly string[]): JsonValue {
let current: unknown = root;
for (const segment of segments) {
if (typeof current !== "object" || current === null || Array.isArray(current)) {
return null;
}
if (!Object.hasOwn(current, segment)) {
return null;
}
current = Reflect.get(current, segment);
}
if (current === undefined) {
return null;
}
if (!isJsonValue(current)) {
throw new ExpressionEvaluationError("path resolved to a non-JSON value");
}
return current;
}
function parseSubjectPath(parts: readonly string[]): ExprPath {
if (parts[1] === "key" && parts.length === 2) {
return { namespace: "subject", field: "key" };
}
if (parts[1] === "data" && parts.length >= 3) {
return { namespace: "subject", field: "data", path: parts.slice(2) };
}
throw new ExpressionSyntaxError(`unsupported path ${parts.join(".")}`);
}
function parseStepsPath(parts: readonly string[]): ExprPath {
if (parts.length < 3) {
throw new ExpressionSyntaxError(`unsupported path ${parts.join(".")}`);
}
const stepId = parts[1]!;
const field = parts[2];
if ((field === "outcome" || field === "attempts") && parts.length === 3) {
return { namespace: "steps", stepId, field };
}
if (field === "outputs" && parts.length >= 4) {
return { namespace: "steps", stepId, field: "outputs", path: parts.slice(3) };
}
throw new ExpressionSyntaxError(`unsupported path ${parts.join(".")}`);
}
function parsePaseoAliasPath(parts: readonly string[]): ExprPath {
if (parts[1] === "prompt" && parts.length === 2) {
return { namespace: "paseo", field: "prompt" };
}
if (parts[1] === "context") {
return { namespace: "event", path: parts.slice(2) };
}
if (parts[1] === "inputs" && parts.length === 3) {
return { namespace: "inputs", name: parts[2]! };
}
if (parts[1] === "execution" && parts[2] === "id" && parts.length === 3) {
return { namespace: "execution", field: "id" };
}
throw new ExpressionSyntaxError(`unsupported path ${parts.join(".")}`);
}
function parsePathSegments(parts: readonly string[]): ExprPath {
switch (parts[0]) {
case "event":
return { namespace: "event", path: parts.slice(1) };
case "inputs":
if (parts.length === 2) return { namespace: "inputs", name: parts[1]! };
break;
case "subject":
return parseSubjectPath(parts);
case "steps":
return parseStepsPath(parts);
case "gate":
if (
parts.length === 2 &&
(parts[1] === "choice" || parts[1] === "note" || parts[1] === "actor")
) {
return { namespace: "gate", field: parts[1] };
}
break;
case "execution":
if (parts.length === 2 && parts[1] === "id") return { namespace: "execution", field: "id" };
break;
case "values":
if (parts.length === 2) return { namespace: "values", name: parts[1]! };
break;
case "paseo":
return parsePaseoAliasPath(parts);
}
throw new ExpressionSyntaxError(`unsupported path ${parts.join(".")}`);
}
function findNextInterpolation(
template: string,
fromIndex: number,
): { readonly start: number; readonly exprStart: number } | undefined {
const dollarIdx = template.indexOf("${{", fromIndex);
const bareIdx = template.indexOf("{{", fromIndex);
if (dollarIdx < 0 && bareIdx < 0) {
return undefined;
}
if (dollarIdx >= 0 && (bareIdx < 0 || dollarIdx <= bareIdx)) {
return { start: dollarIdx, exprStart: dollarIdx + 3 };
}
// If bareIdx is immediately preceded by '$', it is actually a '${{' delimiter.
if (bareIdx > 0 && template[bareIdx - 1] === "$") {
return { start: bareIdx - 1, exprStart: bareIdx + 2 };
}
return { start: bareIdx, exprStart: bareIdx + 2 };
}
function tokenize(source: string): Token[] {
const tokens: Token[] = [];
TOKEN_PATTERN.lastIndex = 0;
while (TOKEN_PATTERN.lastIndex < source.length) {
const match = TOKEN_PATTERN.exec(source);
if (match === null) {
throw new ExpressionSyntaxError("unexpected character");
}
const token = tokenFromMatch(match);
if (token !== undefined) {
tokens.push(token);
}
}
tokens.push({ kind: "end" });
return tokens;
}
function tokenFromMatch(match: RegExpExecArray): Token | undefined {
const [
raw,
word,
numberLiteral,
stringLiteral,
identifier,
operator,
dot,
left,
right,
arrayLeft,
arrayRight,
objectLeft,
objectRight,
comma,
colon,
other,
] = match;
if (other !== undefined) {
throw new ExpressionSyntaxError(`unexpected token ${other}`);
}
if (word !== undefined) {
let value: JsonValue = null;
if (word === "true") {
value = true;
} else if (word === "false") {
value = false;
}
return { kind: "literal", value };
}
if (numberLiteral !== undefined) {
return { kind: "literal", value: Number(numberLiteral) };
}
if (stringLiteral !== undefined) {
return { kind: "literal", value: parseStringLiteral(stringLiteral) };
}
if (identifier !== undefined) {
return { kind: "identifier", value: identifier };
}
if (operator !== undefined && isOperator(operator)) {
return { kind: "operator", value: operator };
}
if (dot !== undefined) {
return { kind: "dot" };
}
if (left !== undefined) {
return { kind: "left" };
}
if (right !== undefined) {
return { kind: "right" };
}
if (arrayLeft !== undefined) {
return { kind: "array-left" };
}
if (arrayRight !== undefined) {
return { kind: "array-right" };
}
if (objectLeft !== undefined) {
return { kind: "object-left" };
}
if (objectRight !== undefined) {
return { kind: "object-right" };
}
if (comma !== undefined) {
return { kind: "comma" };
}
if (colon !== undefined) {
return { kind: "colon" };
}
if (raw.trim() === "") {
return undefined;
}
throw new ExpressionSyntaxError("unexpected token");
}
function parseStringLiteral(value: string): string {
if (value.startsWith('"')) {
const parsed: unknown = JSON.parse(value);
if (typeof parsed !== "string") {
throw new ExpressionSyntaxError("invalid string literal");
}
return parsed;
}
return value.slice(1, -1).replace(/\\([\\'])/gu, "$1");
}
function isOperator(value: string): value is Operator {
return (
value === "!" ||
value === "==" ||
value === "!=" ||
value === "&&" ||
value === "||" ||
value === "??"
);
}
function unwrapExpression(source: string): string {
const trimmed = source.trim();
if (trimmed.startsWith("${{")) {
if (!trimmed.endsWith("}}")) {
throw new ExpressionSyntaxError("unterminated expression");
}
return trimmed.slice(3, -2).trim();
}
if (trimmed.startsWith("{{")) {
if (!trimmed.endsWith("}}")) {
throw new ExpressionSyntaxError("unterminated expression");
}
return trimmed.slice(2, -2).trim();
}
return trimmed;
}
function operatorPrecedence(operator: BinaryOperator): number {
if (operator === "??") {
return 1;
}
if (operator === "||") {
return 2;
}
if (operator === "&&") {
return 3;
}
return 4;
}
function isTruthy(value: JsonValue): boolean {
return value !== false && value !== null && value !== 0 && value !== "";
}
function sameJsonValue(left: JsonValue, right: JsonValue): boolean {
if (typeof left !== typeof right) {
return false;
}
return JSON.stringify(left) === JSON.stringify(right);
}
function formatInterpolatedValue(value: JsonValue): string {
if (value === null) {
return "";
}
return typeof value === "string" ? value : JSON.stringify(value);
}
+13
View File
@@ -0,0 +1,13 @@
declare module "js-yaml" {
export interface LoadOptions {
readonly filename?: string;
readonly json?: boolean;
}
export function load(input: string, options?: LoadOptions): unknown;
const yaml: {
readonly load: typeof load;
};
export default yaml;
}
@@ -0,0 +1,187 @@
import AjvImport, { type ErrorObject, type ValidateFunction } from "ajv";
import { z } from "zod";
import { isJsonObject, isJsonValue, type JsonSchema, type JsonValue } from "./expression.js";
interface AjvInstance {
compile(schema: JsonSchema): ValidateFunction;
}
type AjvConstructor = new (options?: {
readonly allErrors?: boolean;
readonly strict?: boolean;
}) => AjvInstance;
function resolveAjvConstructor(): AjvConstructor {
const mod: unknown = AjvImport;
if (typeof mod === "function") {
return mod as unknown as AjvConstructor;
}
if (typeof mod === "object" && mod !== null && "default" in mod) {
const inner = (mod as { readonly default: unknown }).default;
if (typeof inner === "function") {
return inner as unknown as AjvConstructor;
}
}
throw new Error("unable to resolve Ajv constructor");
}
const AjvCtor = resolveAjvConstructor();
export interface CompiledJsonSchema {
readonly validate: ValidateFunction;
readonly schema: JsonSchema;
}
export function normalizeJsonSchema(schema: JsonSchema): JsonSchema {
const cloned = structuredClone(schema) as Record<string, unknown>;
delete cloned["$schema"];
if (!isJsonObject(cloned)) {
throw new Error("JSON Schema must be a plain JSON object");
}
return cloned;
}
export function zodToJsonSchema(schema: z.ZodType): JsonSchema {
const raw = z.toJSONSchema(schema, { target: "draft-7" }) as Record<string, unknown>;
delete raw["$schema"];
if (!isJsonObject(raw)) {
throw new Error("compiled Zod schema is not a plain JSON object");
}
return raw;
}
export function isZodSchema(value: unknown): value is z.ZodType {
return value instanceof z.ZodType;
}
export function compileJsonSchema(schema: JsonSchema): CompiledJsonSchema {
const normalized = normalizeJsonSchema(schema);
const ajv = new AjvCtor({ allErrors: true, strict: true });
return {
schema: normalized,
validate: ajv.compile(normalized),
};
}
export function validateAgainstSchema(
schema: JsonSchema | z.ZodType,
value: unknown,
prefix = "value",
): { readonly ok: true } | { readonly ok: false; readonly errors: readonly string[] } {
if (isZodSchema(schema)) {
const parsed = schema.safeParse(value);
if (parsed.success) {
return { ok: true };
}
return {
ok: false,
errors: parsed.error.issues.map((issue) => {
const path = issue.path.length === 0 ? prefix : `${prefix}.${issue.path.join(".")}`;
return `${path} ${issue.message}`;
}),
};
}
const compiled = compileJsonSchema(schema);
if (compiled.validate(value)) {
return { ok: true };
}
return {
ok: false,
errors: formatJsonSchemaErrors(compiled.validate.errors, prefix),
};
}
export function formatJsonSchemaErrors(
errors: readonly ErrorObject[] | null | undefined,
prefix = "output",
): string[] {
return (errors ?? []).map((error) => {
const path = error.instancePath === "" ? prefix : `${prefix}${error.instancePath}`;
return `${path} ${error.message ?? "is invalid"}`;
});
}
export function finiteSchemaChoices(
schema: JsonSchema,
path: readonly string[],
): readonly JsonValue[] | undefined {
const node = resolveSchemaAtPath(schema, path, schema, new Set());
if (node === undefined) {
return undefined;
}
return finiteChoices(node, schema, new Set());
}
function resolveSchemaAtPath(
schema: unknown,
path: readonly string[],
root: unknown,
seen: Set<unknown>,
): unknown {
const resolved = resolveSchema(schema, root, seen);
if (resolved === undefined) {
return undefined;
}
if (path.length === 0) {
return resolved;
}
if (!isRecord(resolved)) {
return undefined;
}
const properties = resolved["properties"];
if (!isRecord(properties)) {
return undefined;
}
return resolveSchemaAtPath(properties[path[0]!], path.slice(1), root, seen);
}
function finiteChoices(
schema: unknown,
root: unknown,
seen: Set<unknown>,
): readonly JsonValue[] | undefined {
const resolved = resolveSchema(schema, root, seen);
if (!isRecord(resolved)) {
return undefined;
}
if (Array.isArray(resolved["enum"]) && resolved["enum"].length > 0) {
return resolved["enum"].filter(isJsonValue);
}
if (isJsonValue(resolved["const"])) {
return [resolved["const"]];
}
return undefined;
}
function resolveSchema(schema: unknown, root: unknown, seen: Set<unknown>): unknown {
if (!isRecord(schema)) {
return undefined;
}
if (typeof schema["$ref"] !== "string") {
return schema;
}
if (seen.has(schema)) {
return undefined;
}
seen.add(schema);
const target = resolveLocalReference(root, schema["$ref"]);
return target === undefined ? undefined : resolveSchema(target, root, seen);
}
function resolveLocalReference(root: unknown, reference: string): unknown {
if (!reference.startsWith("#/")) {
return undefined;
}
let current: unknown = root;
for (const segment of reference.slice(2).split("/")) {
if (!isRecord(current)) {
return undefined;
}
current = current[segment.replaceAll("~1", "/").replaceAll("~0", "~")];
}
return current;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
+179
View File
@@ -0,0 +1,179 @@
import type { StepIR, TransitionTargetIR, WorkflowValidationIssue } from "../ir.js";
/**
* Validate transition targets and bounded-cycle safety:
* 1. Every `{ next }` target must refer to an existing state.
* 2. Every cycle in the state graph must contain at least one state that sets
* `maxLoops >= 1` AND declares `on.max_loops_exceeded`.
* (Graph-theoretically equivalent to: removing all loop-guarded states yields a DAG.)
* 3. A loop-guarded state's `max_loops_exceeded` transition cannot target itself.
*/
export function validateStateGraph(
states: Readonly<Record<string, StepIR>>,
): WorkflowValidationIssue[] {
const issues: WorkflowValidationIssue[] = [];
const stateIds = new Set(Object.keys(states));
for (const [stateId, step] of Object.entries(states)) {
for (const [outcome, target] of Object.entries(step.on)) {
if ("next" in target && !stateIds.has(target.next)) {
issues.push({
path: `states.${stateId}.on.${outcome}`,
message: `transition target "${target.next}" does not exist in states`,
});
}
}
const exceededTarget = step.on["max_loops_exceeded"];
if (
exceededTarget !== undefined &&
"next" in exceededTarget &&
exceededTarget.next === stateId
) {
issues.push({
path: `states.${stateId}.on.max_loops_exceeded`,
message: `max_loops_exceeded transition on "${stateId}" cannot target itself`,
});
}
}
// States that guard any cycle passing through them.
const guarded = new Set<string>();
for (const [stateId, step] of Object.entries(states)) {
if (
step.maxLoops !== undefined &&
step.maxLoops >= 1 &&
step.on["max_loops_exceeded"] !== undefined
) {
guarded.add(stateId);
}
}
// Check whether the subgraph induced by unguarded states contains any cycle.
const unguardedCycle = findCycle(states, stateIds, (id) => !guarded.has(id));
if (unguardedCycle !== undefined) {
issues.push({
path: `states.${unguardedCycle[0]}`,
message:
`unguarded cycle detected (${unguardedCycle.join(" -> ")}): ` +
"at least one state in every cycle must declare both maxLoops and on.max_loops_exceeded",
});
}
return issues;
}
export type TransitionResolution =
| { readonly kind: "next"; readonly stateId: string }
| {
readonly kind: "terminal";
readonly target: Extract<TransitionTargetIR, { readonly terminal: string }>;
}
| { readonly kind: "unhandled"; readonly outcome: string };
/**
* Pure transition resolver: given a completed step's outcome, look up `on[outcome] ?? on["*"]`.
* If the target state would exceed its `maxLoops` budget, route through `target.on.max_loops_exceeded`.
*/
export function resolveTransition(
states: Readonly<Record<string, StepIR>>,
currentStateId: string,
outcome: string,
loopCounts: Readonly<Record<string, number>>,
): TransitionResolution {
const currentStep = states[currentStateId];
if (currentStep === undefined) {
return { kind: "unhandled", outcome };
}
const target = currentStep.on[outcome] ?? currentStep.on["*"];
if (target === undefined) {
return { kind: "unhandled", outcome };
}
return followTarget(states, target, loopCounts, new Set());
}
function followTarget(
states: Readonly<Record<string, StepIR>>,
target: TransitionTargetIR,
loopCounts: Readonly<Record<string, number>>,
visited: Set<string>,
): TransitionResolution {
if ("terminal" in target) {
return { kind: "terminal", target };
}
const nextStep = states[target.next];
if (nextStep === undefined) {
return { kind: "unhandled", outcome: target.next };
}
const executedCount = loopCounts[nextStep.id] ?? 0;
if (nextStep.maxLoops !== undefined && executedCount >= nextStep.maxLoops) {
const exceededTarget = nextStep.on["max_loops_exceeded"];
if (exceededTarget === undefined || visited.has(nextStep.id)) {
return { kind: "unhandled", outcome: "max_loops_exceeded" };
}
visited.add(nextStep.id);
return followTarget(states, exceededTarget, loopCounts, visited);
}
return { kind: "next", stateId: nextStep.id };
}
function findCycle(
states: Readonly<Record<string, StepIR>>,
stateIds: ReadonlySet<string>,
include: (stateId: string) => boolean,
): string[] | undefined {
// 0 = unvisited, 1 = visiting (on stack), 2 = visited
const color = new Map<string, number>();
const stack: string[] = [];
const dfs = (nodeId: string): string[] | undefined => {
color.set(nodeId, 1);
stack.push(nodeId);
const step = states[nodeId];
if (step !== undefined) {
for (const target of Object.values(step.on)) {
if (!("next" in target)) {
continue;
}
const nextId = target.next;
if (!stateIds.has(nextId) || !include(nextId)) {
continue;
}
const nextColor = color.get(nextId) ?? 0;
if (nextColor === 1) {
const cycleStart = stack.indexOf(nextId);
return [...stack.slice(cycleStart), nextId];
}
if (nextColor === 0) {
const found = dfs(nextId);
if (found !== undefined) {
return found;
}
}
}
}
stack.pop();
color.set(nodeId, 2);
return undefined;
};
for (const stateId of Object.keys(states)) {
if (!include(stateId)) {
continue;
}
if ((color.get(stateId) ?? 0) === 0) {
const found = dfs(stateId);
if (found !== undefined) {
return found;
}
}
}
return undefined;
}
+691
View File
@@ -0,0 +1,691 @@
import { z } from "zod";
import { parseDurationMs, type DurationInput } from "./internal/duration.js";
import {
collectExprPaths,
isJsonObject,
isJsonValue,
type BinaryOperator,
type ExprNode,
type ExprPath,
type JsonObject,
type JsonPrimitive,
type JsonSchema,
type JsonValue,
} from "./internal/expression.js";
import { compileJsonSchema } from "./internal/json-schema.js";
import { validateStateGraph } from "./internal/machine.js";
export type {
BinaryOperator,
DurationInput,
ExprNode,
ExprPath,
JsonObject,
JsonPrimitive,
JsonSchema,
JsonValue,
};
export { parseDurationMs };
export type TerminalStatus = "done" | "failed" | "cancelled";
export type SubjectConflictPolicy = "signal" | "queue" | "ignore" | "cancel_previous";
export type TransitionTargetIR =
| { readonly next: string }
| {
readonly terminal: TerminalStatus;
readonly reason?: string;
readonly outputs?: Readonly<Record<string, ExprNode>>;
};
export interface TriggerRecurrenceIR {
readonly start: string;
readonly rule: string;
readonly timezone?: string;
}
export interface TriggerBindingIR {
readonly connection?: string;
readonly filters?: JsonObject;
readonly recurrence?: TriggerRecurrenceIR;
}
export interface InputSpecIR {
readonly type: "string" | "number" | "boolean";
readonly required?: boolean;
readonly default?: JsonPrimitive;
readonly choices?: readonly JsonPrimitive[];
}
export type WorktreeTargetIR =
| { readonly mode: "branch-off"; readonly newBranch: ExprNode; readonly base?: string }
| { readonly mode: "checkout-branch"; readonly branch: ExprNode }
| { readonly mode: "checkout-pr"; readonly prNumber: ExprNode };
export interface AgentTargetIR {
readonly daemon?: string;
readonly cwd?: string;
readonly environment?: string;
readonly worktree?: WorktreeTargetIR;
}
export interface AgentSpecIR {
readonly provider: string;
readonly model?: string;
readonly mode?: string;
readonly thinkingOptionId?: string;
readonly options?: JsonObject;
}
export interface ContinuationIR {
readonly mode: string;
}
export interface AuthGrantIR {
readonly connection?: string;
readonly [key: string]: JsonValue | undefined;
}
export interface AllowOutputIR {
readonly max?: number;
readonly required?: boolean;
}
export interface GateChoiceIR {
readonly id: string;
readonly label: string;
readonly description?: string;
}
export interface StepBaseIR {
readonly id: string;
readonly when?: ExprNode;
readonly maxLoops?: number;
readonly on: Readonly<Record<string, TransitionTargetIR>>;
}
export interface AgentStepIR extends StepBaseIR {
readonly kind: "agent";
readonly target?: AgentTargetIR;
readonly agent?: AgentSpecIR;
readonly continuation?: ContinuationIR;
readonly title?: ExprNode;
readonly prompt: ExprNode;
readonly maxRuntimeMs?: number;
readonly idleTimeoutMs?: number;
readonly startupTimeoutMs?: number;
readonly autoArchive?: boolean;
readonly background?: boolean;
readonly env?: Readonly<Record<string, ExprNode>>;
readonly auth?: Readonly<Record<string, AuthGrantIR>>;
readonly tools?: Readonly<Record<string, JsonValue>>;
readonly outputSchema?: JsonSchema;
readonly allowOutputs?: Readonly<Record<string, AllowOutputIR>>;
}
export interface IntegrationStepIR extends StepBaseIR {
readonly kind: "integration";
readonly integration: string;
readonly step: string;
readonly input: Readonly<Record<string, ExprNode>>;
readonly auth?: Readonly<Record<string, AuthGrantIR>>;
readonly timeoutMs?: number;
}
export interface WaitWorkflowStepIR extends StepBaseIR {
readonly kind: "wait_workflow";
readonly workflow: string;
readonly outputKey: ExprNode;
readonly dispatchIfMissing?: boolean;
readonly inputs?: Readonly<Record<string, ExprNode>>;
readonly timeoutMs?: number;
}
export interface GateStepIR extends StepBaseIR {
readonly kind: "gate";
readonly title: ExprNode;
readonly summary?: ExprNode;
readonly recommended?: string;
readonly choices: readonly GateChoiceIR[];
readonly timeoutMs?: number;
}
export interface SleepStepIR extends StepBaseIR {
readonly kind: "sleep";
readonly durationMs?: number;
readonly until?: ExprNode;
}
export type StepIR =
| AgentStepIR
| IntegrationStepIR
| WaitWorkflowStepIR
| GateStepIR
| SleepStepIR;
export interface WorkflowSubjectIR {
readonly key: ExprNode;
readonly onConflict: SubjectConflictPolicy;
}
export interface WorkflowPublishIR {
readonly key: ExprNode;
readonly schema?: JsonSchema;
readonly payload: Readonly<Record<string, ExprNode>> | ExprNode;
}
export interface WorkflowIR {
readonly version: 1;
readonly id: string;
readonly enabled: boolean;
readonly on: Readonly<Record<string, TriggerBindingIR>>;
readonly intake?: JsonObject;
readonly inputs?: Readonly<Record<string, InputSpecIR>>;
readonly values?: Readonly<Record<string, ExprNode>>;
readonly subject?: WorkflowSubjectIR;
readonly maxRuntimeMs?: number;
readonly initial: string;
readonly states: Readonly<Record<string, StepIR>>;
readonly publish?: WorkflowPublishIR;
}
export interface WorkflowValidationIssue {
readonly path: string;
readonly message: string;
}
export class WorkflowValidationError extends Error {
constructor(readonly issues: readonly WorkflowValidationIssue[]) {
super(
`Invalid workflow IR:\n${issues.map((issue) => `- ${issue.path}: ${issue.message}`).join("\n")}`,
);
this.name = "WorkflowValidationError";
}
}
const JsonValueSchema: z.ZodType<JsonValue> = z.custom<JsonValue>(isJsonValue, {
message: "expected a valid JSON value",
});
const JsonObjectSchema: z.ZodType<JsonObject> = z.custom<JsonObject>(isJsonObject, {
message: "expected a plain JSON object",
});
const ExprPathSchema: z.ZodType<ExprPath> = z.union([
z.object({ namespace: z.literal("event"), path: z.array(z.string().min(1)) }).strict(),
z.object({ namespace: z.literal("inputs"), name: z.string().min(1) }).strict(),
z.object({ namespace: z.literal("subject"), field: z.literal("key") }).strict(),
z
.object({
namespace: z.literal("subject"),
field: z.literal("data"),
path: z.array(z.string().min(1)).min(1),
})
.strict(),
z
.object({
namespace: z.literal("steps"),
stepId: z.string().min(1),
field: z.enum(["outcome", "attempts"]),
})
.strict(),
z
.object({
namespace: z.literal("steps"),
stepId: z.string().min(1),
field: z.literal("outputs"),
path: z.array(z.string().min(1)).min(1),
})
.strict(),
z
.object({
namespace: z.literal("gate"),
field: z.enum(["choice", "note", "actor"]),
})
.strict(),
z.object({ namespace: z.literal("execution"), field: z.literal("id") }).strict(),
z.object({ namespace: z.literal("paseo"), field: z.literal("prompt") }).strict(),
z.object({ namespace: z.literal("values"), name: z.string().min(1) }).strict(),
]);
export const ExprNodeSchema: z.ZodType<ExprNode> = z.lazy(() =>
z.union([
z.object({ kind: z.literal("literal"), value: JsonValueSchema }).strict(),
z.object({ kind: z.literal("path"), path: ExprPathSchema }).strict(),
z.object({ kind: z.literal("not"), value: ExprNodeSchema }).strict(),
z
.object({
kind: z.literal("binary"),
operator: z.enum(["==", "!=", "&&", "||", "??"]),
left: ExprNodeSchema,
right: ExprNodeSchema,
})
.strict(),
z
.object({
kind: z.literal("template"),
parts: z.array(z.union([z.string(), ExprNodeSchema])),
})
.strict(),
]),
);
const TransitionTargetSchema: z.ZodType<TransitionTargetIR> = z.union([
z.object({ next: z.string().min(1) }).strict(),
z
.object({
terminal: z.enum(["done", "failed", "cancelled"]),
reason: z.string().min(1).optional(),
outputs: z.record(z.string().min(1), ExprNodeSchema).optional(),
})
.strict(),
]);
const TriggerRecurrenceSchema = z
.object({
start: z.string().min(1),
rule: z.string().min(1),
timezone: z.string().min(1).optional(),
})
.strict();
const TriggerBindingSchema: z.ZodType<TriggerBindingIR> = z
.object({
connection: z.string().min(1).optional(),
filters: JsonObjectSchema.optional(),
recurrence: TriggerRecurrenceSchema.optional(),
})
.strict();
const InputValueSchema = z.union([z.string(), z.number().finite(), z.boolean(), z.null()]);
const InputSpecSchema: z.ZodType<InputSpecIR> = z
.object({
type: z.enum(["string", "number", "boolean"]),
required: z.boolean().optional(),
default: InputValueSchema.optional(),
choices: z.array(InputValueSchema).min(1).optional(),
})
.strict();
const WorktreeTargetSchema: z.ZodType<WorktreeTargetIR> = z.discriminatedUnion("mode", [
z
.object({
mode: z.literal("branch-off"),
newBranch: ExprNodeSchema,
base: z.string().min(1).optional(),
})
.strict(),
z.object({ mode: z.literal("checkout-branch"), branch: ExprNodeSchema }).strict(),
z.object({ mode: z.literal("checkout-pr"), prNumber: ExprNodeSchema }).strict(),
]);
const AgentTargetSchema: z.ZodType<AgentTargetIR> = z
.object({
daemon: z.string().min(1).optional(),
cwd: z.string().min(1).optional(),
environment: z.string().min(1).optional(),
worktree: WorktreeTargetSchema.optional(),
})
.strict();
const AgentSpecSchema: z.ZodType<AgentSpecIR> = z
.object({
provider: z.string().min(1),
model: z.string().min(1).optional(),
mode: z.string().min(1).optional(),
thinkingOptionId: z.string().min(1).optional(),
options: JsonObjectSchema.optional(),
})
.strict();
const ContinuationSchema: z.ZodType<ContinuationIR> = z
.object({ mode: z.string().min(1) })
.strict();
const AuthGrantSchema: z.ZodType<AuthGrantIR> = z.custom<AuthGrantIR>(
(value) => isJsonObject(value),
{ message: "auth grant must be a plain JSON object" },
);
const AllowOutputSchema: z.ZodType<AllowOutputIR> = z
.object({
max: z.number().int().positive().optional(),
required: z.boolean().optional(),
})
.strict();
const GateChoiceSchema: z.ZodType<GateChoiceIR> = z
.object({
id: z.string().min(1),
label: z.string().min(1),
description: z.string().optional(),
})
.strict();
const StepBaseFields = {
id: z.string().min(1),
when: ExprNodeSchema.optional(),
maxLoops: z.number().int().positive().optional(),
on: z.record(z.string().min(1), TransitionTargetSchema),
};
const AgentStepSchema = z
.object({
...StepBaseFields,
kind: z.literal("agent"),
target: AgentTargetSchema.optional(),
agent: AgentSpecSchema.optional(),
continuation: ContinuationSchema.optional(),
title: ExprNodeSchema.optional(),
prompt: ExprNodeSchema,
maxRuntimeMs: z.number().int().positive().optional(),
idleTimeoutMs: z.number().int().positive().optional(),
startupTimeoutMs: z.number().int().positive().optional(),
autoArchive: z.boolean().optional(),
background: z.boolean().optional(),
env: z.record(z.string().min(1), ExprNodeSchema).optional(),
auth: z.record(z.string().min(1), AuthGrantSchema).optional(),
tools: z.record(z.string().min(1), JsonValueSchema).optional(),
outputSchema: JsonObjectSchema.optional(),
allowOutputs: z.record(z.string().min(1), AllowOutputSchema).optional(),
})
.strict();
const IntegrationStepSchema = z
.object({
...StepBaseFields,
kind: z.literal("integration"),
integration: z.string().min(1),
step: z.string().min(1),
input: z.record(z.string().min(1), ExprNodeSchema),
auth: z.record(z.string().min(1), AuthGrantSchema).optional(),
timeoutMs: z.number().int().positive().optional(),
})
.strict();
const WaitWorkflowStepSchema = z
.object({
...StepBaseFields,
kind: z.literal("wait_workflow"),
workflow: z.string().min(1),
outputKey: ExprNodeSchema,
dispatchIfMissing: z.boolean().optional(),
inputs: z.record(z.string().min(1), ExprNodeSchema).optional(),
timeoutMs: z.number().int().positive().optional(),
})
.strict();
const GateStepSchema = z
.object({
...StepBaseFields,
kind: z.literal("gate"),
title: ExprNodeSchema,
summary: ExprNodeSchema.optional(),
recommended: z.string().min(1).optional(),
choices: z.array(GateChoiceSchema).min(1),
timeoutMs: z.number().int().positive().optional(),
})
.strict();
const SleepStepSchema = z
.object({
...StepBaseFields,
kind: z.literal("sleep"),
durationMs: z.number().int().positive().optional(),
until: ExprNodeSchema.optional(),
})
.strict();
const StepIRSchema: z.ZodType<StepIR> = z.discriminatedUnion("kind", [
AgentStepSchema,
IntegrationStepSchema,
WaitWorkflowStepSchema,
GateStepSchema,
SleepStepSchema,
]);
export const WorkflowIRSchema: z.ZodType<WorkflowIR> = z
.object({
version: z.literal(1),
id: z.string().min(1),
enabled: z.boolean(),
on: z.record(z.string().min(1), TriggerBindingSchema),
intake: JsonObjectSchema.optional(),
inputs: z.record(z.string().min(1), InputSpecSchema).optional(),
values: z.record(z.string().min(1), ExprNodeSchema).optional(),
subject: z
.object({
key: ExprNodeSchema,
onConflict: z.enum(["signal", "queue", "ignore", "cancel_previous"]),
})
.strict()
.optional(),
maxRuntimeMs: z.number().int().positive().optional(),
initial: z.string().min(1),
states: z.record(z.string().min(1), StepIRSchema),
publish: z
.object({
key: ExprNodeSchema,
schema: JsonObjectSchema.optional(),
payload: z.union([ExprNodeSchema, z.record(z.string().min(1), ExprNodeSchema)]),
})
.strict()
.optional(),
})
.strict();
/**
* Validate a `WorkflowIR` structurally and statically:
* - Schema shape (pure JSON, zero closures)
* - Initial state and all transition targets exist (or valid terminals)
* - Every cycle contains a state with `maxLoops` and an `on.max_loops_exceeded` transition
* - All `steps.<id>.*` expression references point to existing states
* - Gate choices are unique and `recommended` matches a declared choice
* - Sleep steps declare either `durationMs` or `until` (not neither, not both)
* - Output and publish JSON Schemas compile under strict AJV
*/
function validateStepDefinition(
key: string,
step: StepIR,
issues: WorkflowValidationIssue[],
): void {
if (step.id !== key) {
issues.push({
path: `states.${key}.id`,
message: `step id "${step.id}" must match state key "${key}"`,
});
}
if (step.kind === "gate") {
const seenChoiceIds = new Set<string>();
for (const choice of step.choices) {
if (seenChoiceIds.has(choice.id)) {
issues.push({
path: `states.${key}.choices`,
message: `duplicate gate choice id "${choice.id}"`,
});
}
seenChoiceIds.add(choice.id);
}
if (step.recommended !== undefined && !seenChoiceIds.has(step.recommended)) {
issues.push({
path: `states.${key}.recommended`,
message: `recommended choice "${step.recommended}" is not in choices`,
});
}
}
if (step.kind === "sleep" && (step.durationMs !== undefined) === (step.until !== undefined)) {
issues.push({
path: `states.${key}`,
message: "sleep step must specify exactly one of durationMs or until",
});
}
if (step.kind === "agent" && step.outputSchema !== undefined) {
try {
compileJsonSchema(step.outputSchema);
} catch (error) {
issues.push({
path: `states.${key}.outputSchema`,
message: error instanceof Error ? error.message : String(error),
});
}
}
}
export function validateWorkflowIR(input: unknown): WorkflowIR {
const parsed = WorkflowIRSchema.safeParse(input);
if (!parsed.success) {
throw new WorkflowValidationError(
parsed.error.issues.map((issue) => ({
path: issue.path.length === 0 ? "$" : issue.path.join("."),
message: issue.message,
})),
);
}
const ir = parsed.data;
const issues: WorkflowValidationIssue[] = [];
const stateIds = new Set(Object.keys(ir.states));
if (stateIds.size === 0) {
issues.push({ path: "states", message: "workflow must declare at least one state" });
}
if (!stateIds.has(ir.initial)) {
issues.push({
path: "initial",
message: `initial state "${ir.initial}" does not exist in states`,
});
}
for (const [key, step] of Object.entries(ir.states)) {
validateStepDefinition(key, step, issues);
}
if (ir.publish?.schema !== undefined) {
try {
compileJsonSchema(ir.publish.schema);
} catch (error) {
issues.push({
path: "publish.schema",
message: error instanceof Error ? error.message : String(error),
});
}
}
issues.push(...validateStateGraph(ir.states));
issues.push(...validateExpressionReferences(ir, stateIds));
if (issues.length > 0) {
throw new WorkflowValidationError(issues);
}
return ir;
}
function validateStepExpressionReferences(
prefix: string,
step: StepIR,
checkExpr: (expr: ExprNode | undefined, location: string) => void,
): void {
checkExpr(step.when, `${prefix}.when`);
for (const [outcome, target] of Object.entries(step.on)) {
if ("terminal" in target && target.outputs !== undefined) {
for (const [outKey, outExpr] of Object.entries(target.outputs)) {
checkExpr(outExpr, `${prefix}.on.${outcome}.outputs.${outKey}`);
}
}
}
switch (step.kind) {
case "agent":
checkExpr(step.title, `${prefix}.title`);
checkExpr(step.prompt, `${prefix}.prompt`);
if (step.target?.worktree !== undefined) {
const wt = step.target.worktree;
if (wt.mode === "branch-off") {
checkExpr(wt.newBranch, `${prefix}.target.worktree.newBranch`);
} else if (wt.mode === "checkout-branch") {
checkExpr(wt.branch, `${prefix}.target.worktree.branch`);
} else {
checkExpr(wt.prNumber, `${prefix}.target.worktree.prNumber`);
}
}
if (step.env !== undefined) {
for (const [envKey, envExpr] of Object.entries(step.env)) {
checkExpr(envExpr, `${prefix}.env.${envKey}`);
}
}
break;
case "integration":
for (const [inputKey, inputExpr] of Object.entries(step.input)) {
checkExpr(inputExpr, `${prefix}.input.${inputKey}`);
}
break;
case "wait_workflow":
checkExpr(step.outputKey, `${prefix}.outputKey`);
if (step.inputs !== undefined) {
for (const [inputKey, inputExpr] of Object.entries(step.inputs)) {
checkExpr(inputExpr, `${prefix}.inputs.${inputKey}`);
}
}
break;
case "gate":
checkExpr(step.title, `${prefix}.title`);
checkExpr(step.summary, `${prefix}.summary`);
break;
case "sleep":
checkExpr(step.until, `${prefix}.until`);
break;
}
}
function validateExpressionReferences(
ir: WorkflowIR,
stateIds: ReadonlySet<string>,
): WorkflowValidationIssue[] {
const issues: WorkflowValidationIssue[] = [];
const declaredValues = new Set(Object.keys(ir.values ?? {}));
const checkExpr = (expr: ExprNode | undefined, location: string): void => {
if (expr === undefined) {
return;
}
for (const refPath of collectExprPaths(expr)) {
if (refPath.namespace === "steps" && !stateIds.has(refPath.stepId)) {
issues.push({
path: location,
message: `expression references unknown step "${refPath.stepId}"`,
});
}
if (refPath.namespace === "values" && !declaredValues.has(refPath.name)) {
issues.push({
path: location,
message: `expression references undeclared value "${refPath.name}"`,
});
}
}
};
checkExpr(ir.subject?.key, "subject.key");
for (const [name, valueExpr] of Object.entries(ir.values ?? {})) {
checkExpr(valueExpr, `values.${name}`);
}
if (ir.publish !== undefined) {
checkExpr(ir.publish.key, "publish.key");
if ("kind" in ir.publish.payload) {
checkExpr(ir.publish.payload as ExprNode, "publish.payload");
} else {
for (const [field, fieldExpr] of Object.entries(ir.publish.payload)) {
checkExpr(fieldExpr, `publish.payload.${field}`);
}
}
}
for (const [stateId, step] of Object.entries(ir.states)) {
validateStepExpressionReferences(`states.${stateId}`, step, checkExpr);
}
return issues;
}
+713
View File
@@ -0,0 +1,713 @@
import type {
AcceptWorkflowRunInput,
AcceptWorkflowRunResult,
ActiveAuthLease,
AgentRunner,
AgentStepRequest,
AgentStepStartResult,
BeginStepAttemptInput,
Clock,
CompleteStepAttemptInput,
GateResolution,
GateSink,
IntegrationConnectionRecord,
IntegrationConnections,
IntegrationStorage,
IntegrationStorageEntry,
JsonValue,
ListOpenGatesFilter,
ListRunsFilter,
OpenGateInput,
PublishedWorkflowOutput,
StepAttemptRecord,
StepWaitSpec,
SuspendedWaitRecord,
TransitionRunInput,
WorkflowGateRecord,
WorkflowRunSnapshot,
WorkflowStore,
} from "./index.js";
export interface FakeClock extends Clock {
advance(ms: number): Date;
set(date: Date | string | number): Date;
}
/** Deterministic clock for tests and local simulation. */
export function createFakeClock(
initial: Date | string | number = "2026-01-01T00:00:00.000Z",
): FakeClock {
let currentMs = new Date(initial).getTime();
return {
now(): Date {
return new Date(currentMs);
},
advance(ms: number): Date {
if (!Number.isFinite(ms) || ms < 0) {
throw new Error("FakeClock.advance requires a non-negative finite ms value");
}
currentMs += ms;
return new Date(currentMs);
},
set(date: Date | string | number): Date {
currentMs = new Date(date).getTime();
return new Date(currentMs);
},
};
}
/** In-memory scoped `IntegrationStorage` with real TTL expiry and serialized locking. */
export function createMemoryIntegrationStorage(clock?: Clock): IntegrationStorage {
const nowMs = (): number => (clock === undefined ? Date.now() : clock.now().getTime());
const records = new Map<string, { value: JsonValue; expiresAt?: number }>();
const lockChains = new Map<string, Promise<void>>();
const isExpired = (entry: { expiresAt?: number }): boolean =>
entry.expiresAt !== undefined && nowMs() >= entry.expiresAt;
return {
async get<T extends JsonValue = JsonValue>(key: string): Promise<T | undefined> {
const entry = records.get(key);
if (entry === undefined || isExpired(entry)) {
records.delete(key);
return undefined;
}
return structuredClone(entry.value) as T;
},
async set(key: string, value: JsonValue, options?: { readonly ttlMs?: number }): Promise<void> {
const expiresAt = options?.ttlMs !== undefined ? nowMs() + options.ttlMs : undefined;
records.set(key, { value: structuredClone(value), expiresAt });
},
async delete(key: string): Promise<void> {
records.delete(key);
},
async list(prefix = ""): Promise<readonly IntegrationStorageEntry[]> {
const out: IntegrationStorageEntry[] = [];
for (const [key, entry] of records.entries()) {
if (isExpired(entry)) {
records.delete(key);
continue;
}
if (key.startsWith(prefix)) {
out.push({ key, value: structuredClone(entry.value) });
}
}
return out;
},
async withLock<T>(key: string, _ttlMs: number, fn: () => Promise<T>): Promise<T> {
const prior = lockChains.get(key) ?? Promise.resolve();
let release!: () => void;
const current = new Promise<void>((resolve) => {
release = resolve;
});
const tail = prior.then(() => current);
lockChains.set(key, tail);
await prior;
try {
return await fn();
} finally {
release();
if (lockChains.get(key) === tail) {
lockChains.delete(key);
}
}
},
};
}
/** In-memory `IntegrationConnections` registry for tests and local daemon runs. */
export function createMemoryIntegrationConnections(
initial: readonly IntegrationConnectionRecord[] = [],
): IntegrationConnections {
const list = initial.map((item) => structuredClone(item));
return {
async get(connectionNameOrId: string): Promise<IntegrationConnectionRecord | undefined> {
const found = list.find(
(item) => item.id === connectionNameOrId || item.name === connectionNameOrId,
);
return found === undefined ? undefined : structuredClone(found);
},
async list(): Promise<readonly IntegrationConnectionRecord[]> {
return list.map((item) => structuredClone(item));
},
};
}
export interface FakeGateSink extends GateSink {
readonly opened: WorkflowGateRecord[];
readonly resolved: WorkflowGateRecord[];
readonly expired: WorkflowGateRecord[];
}
/** Records all gate lifecycle notifications without mocks. */
export function createFakeGateSink(): FakeGateSink {
const opened: WorkflowGateRecord[] = [];
const resolved: WorkflowGateRecord[] = [];
const expired: WorkflowGateRecord[] = [];
return {
opened,
resolved,
expired,
async onGateOpened(gate: WorkflowGateRecord): Promise<void> {
opened.push(structuredClone(gate));
},
async onGateResolved(gate: WorkflowGateRecord): Promise<void> {
resolved.push(structuredClone(gate));
},
async onGateExpired(gate: WorkflowGateRecord): Promise<void> {
expired.push(structuredClone(gate));
},
};
}
export type FakeAgentHandler = (
request: AgentStepRequest,
) => Promise<AgentStepStartResult> | AgentStepStartResult;
export interface CancelledAgentRecord {
readonly executionId: string;
readonly reason: string;
}
export interface FakeAgentRunner extends AgentRunner {
readonly requests: AgentStepRequest[];
readonly cancelled: CancelledAgentRecord[];
setHandler(handler: FakeAgentHandler): void;
}
/** Programmable fake `AgentRunner` with full call recording and zero mocks. */
export function createFakeAgentRunner(initialHandler?: FakeAgentHandler): FakeAgentRunner {
const requests: AgentStepRequest[] = [];
const cancelled: CancelledAgentRecord[] = [];
let handler: FakeAgentHandler =
initialHandler ??
(() => ({
status: "completed",
outcome: "ok",
}));
return {
requests,
cancelled,
setHandler(next: FakeAgentHandler): void {
handler = next;
},
async start(request: AgentStepRequest): Promise<AgentStepStartResult> {
requests.push(structuredClone(request));
return handler(request);
},
async cancel(executionId: string, reason: string): Promise<void> {
cancelled.push({ executionId, reason });
},
};
}
interface MutableRun {
id: string;
workflowId: string;
status: WorkflowRunSnapshot["status"];
pausedFromStatus?: "running" | "waiting";
subjectKey?: string;
subjectData: WorkflowRunSnapshot["subjectData"];
inputs: Record<string, JsonValue>;
event?: WorkflowRunSnapshot["event"];
currentState: string;
loopCounts: Record<string, number>;
attempts: MutableAttempt[];
lastGate?: WorkflowRunSnapshot["lastGate"];
terminalReason?: string;
terminalOutputs?: WorkflowRunSnapshot["terminalOutputs"];
createdAt: Date;
updatedAt: Date;
completedAt?: Date;
}
interface MutableAttempt {
id: string;
runId: string;
stepId: string;
attempt: number;
executionId: string;
status: StepAttemptRecord["status"];
outcome?: string;
output?: StepAttemptRecord["output"];
error?: string;
wait?: StepWaitSpec;
activeLeases: ActiveAuthLease[];
startedAt: Date;
finishedAt?: Date;
}
interface MutableGate {
id: string;
runId: string;
workflowId: string;
stepId: string;
attemptId: string;
title: string;
summary?: string;
recommended?: string;
choices: WorkflowGateRecord["choices"];
status: WorkflowGateRecord["status"];
openedAt: Date;
expiresAt?: Date;
resolution?: GateResolution;
}
function isTerminalStatus(status: WorkflowRunSnapshot["status"]): boolean {
return status === "done" || status === "failed" || status === "cancelled";
}
function cloneRun(run: MutableRun): WorkflowRunSnapshot {
return structuredClone(run);
}
function cloneAttempt(attempt: MutableAttempt): StepAttemptRecord {
return structuredClone(attempt);
}
function cloneGate(gate: MutableGate): WorkflowGateRecord {
return structuredClone(gate);
}
/**
* Full in-memory implementation of `WorkflowStore`.
* Suitable both for zero-mock unit/contract tests and as the foundation for local daemon execution.
*/
export function createMemoryWorkflowStore(): WorkflowStore {
let runSeq = 0;
let attemptSeq = 0;
let gateSeq = 0;
const runs = new Map<string, MutableRun>();
const attemptsById = new Map<string, MutableAttempt>();
const gates = new Map<string, MutableGate>();
const outputs = new Map<string, PublishedWorkflowOutput>();
const outputMapKey = (workflowId: string, outputKey: string): string =>
`${workflowId}\0${outputKey}`;
const findActiveRunForSubject = (
workflowId: string,
subjectKey: string,
): MutableRun | undefined => {
for (const run of runs.values()) {
if (
run.workflowId === workflowId &&
run.subjectKey === subjectKey &&
!isTerminalStatus(run.status) &&
run.status !== "queued"
) {
return run;
}
}
return undefined;
};
return {
async acceptRun(input: AcceptWorkflowRunInput): Promise<AcceptWorkflowRunResult> {
const existing =
input.subjectKey === undefined
? undefined
: findActiveRunForSubject(input.workflowId, input.subjectKey);
if (existing !== undefined) {
const policy = input.onConflict ?? "ignore";
if (policy === "ignore") {
return { action: "ignored", existingRun: cloneRun(existing) };
}
if (policy === "signal") {
return { action: "signal", existingRun: cloneRun(existing) };
}
if (policy === "queue") {
const queuedId = `run_${++runSeq}`;
const queued: MutableRun = {
id: queuedId,
workflowId: input.workflowId,
status: "queued",
subjectKey: input.subjectKey,
subjectData: structuredClone(input.subjectData),
inputs: structuredClone(input.inputs) as Record<string, JsonValue>,
event: input.event === undefined ? undefined : structuredClone(input.event),
currentState: input.initialState,
loopCounts: {},
attempts: [],
createdAt: new Date(input.now.getTime()),
updatedAt: new Date(input.now.getTime()),
};
runs.set(queuedId, queued);
return { action: "queued", run: cloneRun(queued) };
}
if (policy === "cancel_previous") {
const cancelledSnapshot = cloneRun(existing);
existing.status = "cancelled";
existing.terminalReason = "superseded_by_new_run";
existing.updatedAt = new Date(input.now.getTime());
existing.completedAt = new Date(input.now.getTime());
for (const attempt of existing.attempts) {
if (attempt.status === "running" || attempt.status === "waiting") {
attempt.status = "cancelled";
attempt.wait = undefined;
attempt.finishedAt = new Date(input.now.getTime());
}
}
const nextId = `run_${++runSeq}`;
const nextRun: MutableRun = {
id: nextId,
workflowId: input.workflowId,
status: "running",
subjectKey: input.subjectKey,
subjectData: structuredClone(input.subjectData),
inputs: structuredClone(input.inputs) as Record<string, JsonValue>,
event: input.event === undefined ? undefined : structuredClone(input.event),
currentState: input.initialState,
loopCounts: {},
attempts: [],
createdAt: new Date(input.now.getTime()),
updatedAt: new Date(input.now.getTime()),
};
runs.set(nextId, nextRun);
return { action: "replaced", run: cloneRun(nextRun), cancelledRun: cancelledSnapshot };
}
}
const id = `run_${++runSeq}`;
const run: MutableRun = {
id,
workflowId: input.workflowId,
status: "running",
subjectKey: input.subjectKey,
subjectData: structuredClone(input.subjectData),
inputs: structuredClone(input.inputs) as Record<string, JsonValue>,
event: input.event === undefined ? undefined : structuredClone(input.event),
currentState: input.initialState,
loopCounts: {},
attempts: [],
createdAt: new Date(input.now.getTime()),
updatedAt: new Date(input.now.getTime()),
};
runs.set(id, run);
return { action: "started", run: cloneRun(run) };
},
async loadRun(runId: string): Promise<WorkflowRunSnapshot | undefined> {
const run = runs.get(runId);
return run === undefined ? undefined : cloneRun(run);
},
async listRuns(filter?: ListRunsFilter): Promise<readonly WorkflowRunSnapshot[]> {
let statuses: Set<WorkflowRunSnapshot["status"]> | undefined;
if (filter?.status !== undefined) {
statuses = Array.isArray(filter.status) ? new Set(filter.status) : new Set([filter.status]);
}
const result: WorkflowRunSnapshot[] = [];
for (const run of runs.values()) {
if (filter?.workflowId !== undefined && run.workflowId !== filter.workflowId) {
continue;
}
if (filter?.subjectKey !== undefined && run.subjectKey !== filter.subjectKey) {
continue;
}
if (statuses !== undefined && !statuses.has(run.status)) {
continue;
}
result.push(cloneRun(run));
}
return result;
},
async dequeueNextRun(
workflowId: string,
subjectKey: string,
now: Date,
): Promise<WorkflowRunSnapshot | undefined> {
if (findActiveRunForSubject(workflowId, subjectKey) !== undefined) {
return undefined;
}
for (const run of runs.values()) {
if (
run.workflowId === workflowId &&
run.subjectKey === subjectKey &&
run.status === "queued"
) {
run.status = "running";
run.updatedAt = new Date(now.getTime());
return cloneRun(run);
}
}
return undefined;
},
async beginStepAttempt(input: BeginStepAttemptInput): Promise<StepAttemptRecord> {
const run = runs.get(input.runId);
if (run === undefined) {
throw new Error(`run "${input.runId}" not found`);
}
const nextCount = (run.loopCounts[input.stepId] ?? 0) + (input.incrementLoop ? 1 : 0);
if (input.incrementLoop) {
run.loopCounts[input.stepId] = nextCount;
}
const attemptId = `att_${++attemptSeq}`;
const attempt: MutableAttempt = {
id: attemptId,
runId: input.runId,
stepId: input.stepId,
attempt: nextCount,
executionId: `exec_${attemptSeq}`,
status: "running",
activeLeases: [],
startedAt: new Date(input.now.getTime()),
};
run.attempts.push(attempt);
run.updatedAt = new Date(input.now.getTime());
attemptsById.set(attemptId, attempt);
return cloneAttempt(attempt);
},
async setAttemptLeases(attemptId: string, leases: readonly ActiveAuthLease[]): Promise<void> {
const attempt = attemptsById.get(attemptId);
if (attempt === undefined) {
return;
}
attempt.activeLeases = leases.map((lease) => ({ ...lease }));
},
async setAttemptExecutionId(attemptId: string, executionId: string): Promise<void> {
const attempt = attemptsById.get(attemptId);
if (attempt === undefined) {
return;
}
attempt.executionId = executionId;
},
async suspendStepAttempt(attemptId: string, wait: StepWaitSpec): Promise<void> {
const attempt = attemptsById.get(attemptId);
if (attempt === undefined) {
throw new Error(`attempt "${attemptId}" not found`);
}
attempt.status = "waiting";
attempt.wait = structuredClone(wait);
},
async completeStepAttempt(input: CompleteStepAttemptInput): Promise<WorkflowRunSnapshot> {
const run = runs.get(input.runId);
if (run === undefined) {
throw new Error(`run "${input.runId}" not found`);
}
const attempt = attemptsById.get(input.attemptId);
if (attempt === undefined) {
throw new Error(`attempt "${input.attemptId}" not found`);
}
attempt.status = input.status;
attempt.outcome = input.outcome;
attempt.output = input.output === undefined ? undefined : structuredClone(input.output);
attempt.error = input.error;
attempt.wait = undefined;
attempt.finishedAt = new Date(input.now.getTime());
run.updatedAt = new Date(input.now.getTime());
return cloneRun(run);
},
async transitionRun(input: TransitionRunInput): Promise<WorkflowRunSnapshot> {
const run = runs.get(input.runId);
if (run === undefined) {
throw new Error(`run "${input.runId}" not found`);
}
run.status = input.status;
if (input.status === "paused") {
run.pausedFromStatus = input.pausedFromStatus;
} else {
run.pausedFromStatus = undefined;
}
if (input.currentState !== undefined) {
run.currentState = input.currentState;
}
if (input.lastGate !== undefined) {
run.lastGate = { ...input.lastGate };
}
if (input.terminalReason !== undefined) {
run.terminalReason = input.terminalReason;
}
if (input.terminalOutputs !== undefined) {
run.terminalOutputs = structuredClone(input.terminalOutputs);
}
run.updatedAt = new Date(input.now.getTime());
if (isTerminalStatus(input.status)) {
run.completedAt = new Date(input.now.getTime());
}
return cloneRun(run);
},
async listSuspendedWaits(
kind?: StepWaitSpec["kind"],
options?: { readonly includePaused?: boolean },
): Promise<readonly SuspendedWaitRecord[]> {
const includePaused = options?.includePaused === true;
const result: SuspendedWaitRecord[] = [];
for (const attempt of attemptsById.values()) {
if (attempt.status !== "waiting" || attempt.wait === undefined) {
continue;
}
if (kind !== undefined && attempt.wait.kind !== kind) {
continue;
}
const run = runs.get(attempt.runId);
if (run === undefined) {
continue;
}
if (run.status !== "waiting" && !(includePaused && run.status === "paused")) {
continue;
}
result.push({
runId: attempt.runId,
attemptId: attempt.id,
stepId: attempt.stepId,
wait: structuredClone(attempt.wait),
});
}
return result;
},
async findExpiredWaits(now: Date): Promise<readonly SuspendedWaitRecord[]> {
const nowMs = now.getTime();
const result: SuspendedWaitRecord[] = [];
for (const attempt of attemptsById.values()) {
if (attempt.status !== "waiting" || attempt.wait === undefined) {
continue;
}
const run = runs.get(attempt.runId);
if (run === undefined || run.status !== "waiting") {
continue;
}
const wakeAt = attempt.wait.wakeAt;
if (wakeAt !== undefined && wakeAt.getTime() <= nowMs) {
result.push({
runId: attempt.runId,
attemptId: attempt.id,
stepId: attempt.stepId,
wait: structuredClone(attempt.wait),
});
}
}
return result;
},
async publishWorkflowOutput(
input: PublishedWorkflowOutput,
): Promise<readonly SuspendedWaitRecord[]> {
outputs.set(outputMapKey(input.workflowId, input.outputKey), structuredClone(input));
const matched: SuspendedWaitRecord[] = [];
for (const attempt of attemptsById.values()) {
if (attempt.status !== "waiting" || attempt.wait?.kind !== "wait_workflow") {
continue;
}
if (
attempt.wait.workflowId !== input.workflowId ||
attempt.wait.outputKey !== input.outputKey
) {
continue;
}
const run = runs.get(attempt.runId);
if (run === undefined || run.status !== "waiting") {
continue;
}
matched.push({
runId: attempt.runId,
attemptId: attempt.id,
stepId: attempt.stepId,
wait: structuredClone(attempt.wait),
});
}
return matched;
},
async findWorkflowOutput(
workflowId: string,
outputKey: string,
): Promise<PublishedWorkflowOutput | undefined> {
const found = outputs.get(outputMapKey(workflowId, outputKey));
return found === undefined ? undefined : structuredClone(found);
},
async openGate(input: OpenGateInput): Promise<WorkflowGateRecord> {
const id = `gate_${++gateSeq}`;
const gate: MutableGate = {
id,
runId: input.runId,
workflowId: input.workflowId,
stepId: input.stepId,
attemptId: input.attemptId,
title: input.title,
summary: input.summary,
recommended: input.recommended,
choices: structuredClone(input.choices),
status: "open",
openedAt: new Date(input.openedAt.getTime()),
expiresAt: input.expiresAt === undefined ? undefined : new Date(input.expiresAt.getTime()),
};
gates.set(id, gate);
return cloneGate(gate);
},
async getGate(gateId: string): Promise<WorkflowGateRecord | undefined> {
const gate = gates.get(gateId);
return gate === undefined ? undefined : cloneGate(gate);
},
async listOpenGates(filter?: ListOpenGatesFilter): Promise<readonly WorkflowGateRecord[]> {
const result: WorkflowGateRecord[] = [];
for (const gate of gates.values()) {
if (gate.status !== "open") {
continue;
}
if (filter?.workflowId !== undefined && gate.workflowId !== filter.workflowId) {
continue;
}
if (filter?.runId !== undefined && gate.runId !== filter.runId) {
continue;
}
result.push(cloneGate(gate));
}
return result;
},
async resolveGate(
gateId: string,
resolution: GateResolution,
): Promise<WorkflowGateRecord | undefined> {
const gate = gates.get(gateId);
if (gate === undefined || gate.status !== "open") {
return undefined;
}
gate.status = "resolved";
gate.resolution = {
choice: resolution.choice,
note: resolution.note,
actor: resolution.actor,
resolvedAt: new Date(resolution.resolvedAt.getTime()),
};
return cloneGate(gate);
},
async expireGate(gateId: string): Promise<WorkflowGateRecord | undefined> {
const gate = gates.get(gateId);
if (gate === undefined || gate.status !== "open") {
return undefined;
}
gate.status = "expired";
return cloneGate(gate);
},
async cancelRunGates(runId: string): Promise<readonly WorkflowGateRecord[]> {
const cancelled: WorkflowGateRecord[] = [];
for (const gate of gates.values()) {
if (gate.runId === runId && gate.status === "open") {
gate.status = "cancelled";
cancelled.push(cloneGate(gate));
}
}
return cancelled;
},
};
}
File diff suppressed because it is too large Load Diff
+220
View File
@@ -0,0 +1,220 @@
import { readdirSync, readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { defineWorkflow, step, terminal } from "../src/dsl.js";
import {
createWorkflowEngine,
type IntegrationContext,
type WorkflowIntegration,
type WorkflowIR,
} from "../src/index.js";
import {
createFakeAgentRunner,
createFakeClock,
createFakeGateSink,
createMemoryIntegrationConnections,
createMemoryIntegrationStorage,
createMemoryWorkflowStore,
} from "../src/testing.js";
const packageDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const srcDir = path.join(packageDir, "src");
function collectSourceFiles(dir: string): string[] {
const results: string[] = [];
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
results.push(...collectSourceFiles(fullPath));
} else if (entry.isFile() && /\.(?:ts|mts|js|mjs)$/u.test(entry.name)) {
results.push(fullPath);
}
}
return results.sort();
}
describe("hard mechanical boundaries", () => {
it("exports ONLY the 5 agreed entrypoints and allows ONLY pure runtime dependencies", () => {
const pkg = JSON.parse(readFileSync(path.join(packageDir, "package.json"), "utf8")) as {
readonly exports: Record<string, unknown>;
readonly dependencies?: Record<string, string>;
};
expect(Object.keys(pkg.exports).sort()).toEqual([".", "./dsl", "./ir", "./testing", "./yaml"]);
const allowedDeps = new Set(["zod", "ajv", "js-yaml"]);
const actualDeps = Object.keys(pkg.dependencies ?? {});
expect(actualDeps.length).toBeGreaterThan(0);
for (const dep of actualDeps) {
expect(allowedDeps.has(dep), `disallowed runtime dependency "${dep}"`).toBe(true);
}
const forbiddenDeps = ["pg", "drizzle-orm", "react", "@octokit/rest", "@octokit/core"];
for (const forbidden of forbiddenDeps) {
expect(actualDeps).not.toContain(forbidden);
}
});
it("contains zero Node builtin imports in src/ (including ./ir and ./dsl)", () => {
const files = collectSourceFiles(srcDir);
expect(files.length).toBeGreaterThan(0);
const nodeImportPattern =
/(?:from\s+["'](?:node:|fs|net|http|https|path|os|crypto|child_process|stream|worker_threads)["']|require\(["'](?:node:|fs|net|http|https|path|os|crypto|child_process)["']\))/gu;
for (const file of files) {
const content = readFileSync(file, "utf8");
const matches = content.match(nodeImportPattern);
expect(
matches,
`unexpected Node builtin import in ${path.relative(packageDir, file)}`,
).toBeNull();
}
});
it("contains zero hardcoded provider or database names anywhere in packages/workflows/src/", () => {
const files = collectSourceFiles(srcDir);
const forbiddenProviders = ["github", "slack", "discord", "linear", "notion", "postgres"];
for (const file of files) {
const content = readFileSync(file, "utf8");
for (const provider of forbiddenProviders) {
const pattern = new RegExp(`\\b${provider}\\b`, "i");
expect(
pattern.test(content),
`forbidden hardcoded provider "${provider}" found in ${path.relative(packageDir, file)}`,
).toBe(false);
}
}
});
it("passes ONLY the narrow IntegrationContext (zero Database/SQL/engine handles) to integration hooks", async () => {
// Compile-time type-level verification of exact IntegrationContext keys.
type ExpectedKeys = "scopeId" | "storage" | "connections" | "ingest" | "fetch" | "log" | "now";
type AssertExact<T, U> = [T] extends [U] ? ([U] extends [T] ? true : never) : never;
const _exactContextKeys: AssertExact<keyof IntegrationContext, ExpectedKeys> = true;
expect(_exactContextKeys).toBe(true);
const observedKeySets: string[][] = [];
const expectedSortedKeys = [
"connections",
"fetch",
"ingest",
"log",
"now",
"scopeId",
"storage",
];
const recordCtx = (ctx: IntegrationContext): void => {
observedKeySets.push(Object.keys(ctx).sort());
const asRecord = ctx as unknown as Record<string, unknown>;
expect(asRecord["db"]).toBeUndefined();
expect(asRecord["database"]).toBeUndefined();
expect(asRecord["sql"]).toBeUndefined();
expect(asRecord["drizzle"]).toBeUndefined();
expect(asRecord["store"]).toBeUndefined();
expect(asRecord["engine"]).toBeUndefined();
};
const acme: WorkflowIntegration = {
id: "acme",
auth: {
async mint(_scope, ctx) {
recordCtx(ctx);
return { leaseId: "lease_1", env: { ACME_TOKEN: "tok_1" } };
},
async revoke(_leaseId, ctx) {
recordCtx(ctx);
},
},
steps: {
check: {
inputSchema: z.object({ ticket: z.string() }),
outcomes: ["ok"],
async execute(input, ctx) {
recordCtx(ctx);
await ctx.storage.set("last_ticket", input["ticket"] as string, { ttlMs: 5_000 });
const stored = await ctx.storage.get<string>("last_ticket");
expect(stored).toBe("ACME-1");
const conn = await ctx.connections.get("acme-main");
expect(conn?.name).toBe("acme-main");
return { status: "completed", outcome: "ok", output: { seen: stored ?? "" } };
},
},
},
};
const ir = defineWorkflow({
id: "boundary-ctx-check",
on: { "acme.ping": {} },
initial: "run_check",
steps: {
run_check: step.integration("acme.check", {
auth: { acme: { connection: "acme-main" } },
input: { ticket: "ACME-1" },
on: { ok: terminal.done() },
}),
},
});
const roundTripped = JSON.parse(JSON.stringify(ir)) as WorkflowIR;
const clock = createFakeClock();
const engine = createWorkflowEngine({
store: createMemoryWorkflowStore(),
runner: createFakeAgentRunner(),
gates: createFakeGateSink(),
integrations: [acme],
clock,
scopeId: "tenant-a",
storage: createMemoryIntegrationStorage(clock),
connections: createMemoryIntegrationConnections([
{ id: "conn_1", name: "acme-main", integration: "acme" },
]),
workflows: [roundTripped],
});
const run = await engine.start({ workflowId: "boundary-ctx-check" });
expect(run.status).toBe("done");
expect(observedKeySets.length).toBe(3); // mint + execute + revoke
for (const keys of observedKeySets) {
expect(keys).toEqual(expectedSortedKeys);
}
});
it("enforces IntegrationStorage TTL expiry, listing, deletion, and lock serialization", async () => {
const clock = createFakeClock("2026-06-01T00:00:00.000Z");
const storage = createMemoryIntegrationStorage(clock);
await storage.set("cache:a", { count: 1 }, { ttlMs: 1_000 });
await storage.set("cache:b", { count: 2 });
await storage.set("other:c", "hello");
expect(await storage.get("cache:a")).toEqual({ count: 1 });
expect((await storage.list("cache:")).map((e) => e.key).sort()).toEqual(["cache:a", "cache:b"]);
clock.advance(1_000);
expect(await storage.get("cache:a")).toBeUndefined();
expect((await storage.list("cache:")).map((e) => e.key)).toEqual(["cache:b"]);
await storage.delete("cache:b");
expect(await storage.get("cache:b")).toBeUndefined();
const order: string[] = [];
const p1 = storage.withLock("lock-1", 5_000, async () => {
order.push("start-1");
await Promise.resolve();
order.push("end-1");
return "first";
});
const p2 = storage.withLock("lock-1", 5_000, async () => {
order.push("start-2");
order.push("end-2");
return "second";
});
expect(await Promise.all([p1, p2])).toEqual(["first", "second"]);
expect(order).toEqual(["start-1", "end-1", "start-2", "end-2"]);
});
});
+386
View File
@@ -0,0 +1,386 @@
import { existsSync, readdirSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { defineTrigger, defineWorkflow, expr, ref, step, terminal, tpl } from "../src/dsl.js";
import { validateWorkflowIR, type WorkflowIR } from "../src/ir.js";
import { compileWorkflowYaml } from "../src/yaml.js";
describe("DSL and YAML byte-identical IR compilation", () => {
it("compiles 1-state trigger shorthand identically from TS DSL and YAML", () => {
const yamlSource = `
name: acme-priority-review
enabled: true
on:
acme.pull_request_label_added:
connection: acme-main
filters:
repo: acme/widget
label: priority-review
max_runtime: 1h
run:
target:
daemon: factory
cwd: /srv/acme/widget
worktree:
mode: branch-off
base: origin/main
newBranch: priority-review-\${{ paseo.execution.id }}
agent:
provider: claude
model: claude-opus-5-5
mode: bypassPermissions
thinkingOptionId: medium
continuation:
mode: new
max_runtime: 30m
idle_timeout: 10m
auto_archive: true
background: true
acme:
connection: acme-main
repositories: [acme/widget]
permissions:
contents: read
pull_requests: write
prompt: "Review priority PR #\${{ paseo.context.acme.item.number }}."
outputs:
acme.reply:
max: 3
`;
const dslIR = defineTrigger({
name: "acme-priority-review",
enabled: true,
on: {
"acme.pull_request_label_added": {
connection: "acme-main",
filters: { repo: "acme/widget", label: "priority-review" },
},
},
maxRuntime: "1h",
run: {
target: {
daemon: "factory",
cwd: "/srv/acme/widget",
worktree: {
mode: "branch-off",
base: "origin/main",
newBranch: tpl`priority-review-${expr.executionId()}`,
},
},
agent: {
provider: "claude",
model: "claude-opus-5-5",
mode: "bypassPermissions",
thinkingOptionId: "medium",
},
continuation: { mode: "new" },
maxRuntime: "30m",
idleTimeout: "10m",
autoArchive: true,
background: true,
auth: {
acme: {
connection: "acme-main",
repositories: ["acme/widget"],
permissions: { contents: "read", pull_requests: "write" },
},
},
prompt: tpl`Review priority PR #${ref("event.acme.item.number")}.`,
outputs: {
"acme.reply": { max: 3 },
},
},
});
const yamlIR = compileWorkflowYaml(yamlSource);
expect(JSON.stringify(dslIR)).toBe(JSON.stringify(yamlIR));
expect(JSON.parse(JSON.stringify(yamlIR))).toEqual(yamlIR);
expect(yamlIR.initial).toBe("run");
expect(Object.keys(yamlIR.states)).toEqual(["run"]);
expect(yamlIR.states["run"]?.kind).toBe("agent");
});
it("compiles a full multi-step workflow with Zod schemas, integration waits, wait.workflow, gates, and sleep identically", () => {
const FixOutputSchema = z.object({
outcome: z.enum(["pr_ready", "needs_maintainer"]),
pr_number: z.number(),
head_sha: z.string(),
});
const dslIR = defineWorkflow({
id: "acme-issue-to-pr",
on: {
"acme.issue_created": {
connection: "acme-main",
filters: { repo: "acme/widget" },
},
},
subject: {
key: tpl`${ref("event.acme.repo")}#${ref("event.acme.issue_number")}`,
onConflict: "ignore",
},
initial: "fix",
steps: {
fix: step.agent({
maxLoops: 3,
prompt: tpl`Fix #${ref("event.acme.issue_number")}.`,
auth: { acme: { connection: "acme-main", scope: "write" } },
output: FixOutputSchema,
on: {
pr_ready: "wait_ci",
needs_maintainer: "maintainer_gate",
max_loops_exceeded: "maintainer_gate",
},
}),
wait_ci: step.integration("acme.wait_ci", {
input: {
repo: "acme/widget",
pr_number: ref("steps.fix.outputs.pr_number"),
head_sha: ref("steps.fix.outputs.head_sha"),
},
timeout: "90m",
on: {
green: "wait_review",
red: "fix",
timeout: "maintainer_gate",
},
}),
wait_review: step.waitWorkflow({
workflow: "acme-review",
outputKey: tpl`review:acme/widget#${ref("steps.fix.outputs.pr_number")}@${ref("steps.fix.outputs.head_sha")}`,
dispatchIfMissing: true,
inputs: {
pr_number: ref("steps.fix.outputs.pr_number"),
head_sha: ref("steps.fix.outputs.head_sha"),
},
timeout: "1h",
on: {
approved: "cooldown",
changes_requested: "fix",
timeout: "maintainer_gate",
},
}),
cooldown: step.sleep({
duration: "5m",
on: { done: "merge" },
}),
maintainer_gate: step.gate({
title: tpl`Decision needed on #${ref("event.acme.issue_number")}`,
summary: expr.coalesce(ref("steps.wait_review.outputs.reason"), "manual review"),
recommended: "rework",
choices: [
{ id: "merge_anyway", label: "Merge anyway" },
{ id: "rework", label: "Rework", description: "Try fix again" },
],
timeout: "14d",
onTimeout: terminal.cancelled("gate_expired"),
on: {
merge_anyway: "merge",
rework: "fix",
},
}),
merge: step.integration("acme.merge_pr", {
auth: { acme: { connection: "acme-main", scope: "write" } },
input: {
pr_number: ref("steps.fix.outputs.pr_number"),
note: expr.coalesce(ref("gate.note"), "auto-merged"),
},
on: {
merged: terminal.done(),
conflict: "fix",
},
}),
},
publish: {
key: tpl`issue:acme/widget#${ref("event.acme.issue_number")}`,
payload: {
pr_number: ref("steps.fix.outputs.pr_number"),
head_sha: ref("steps.fix.outputs.head_sha"),
},
},
});
const yamlSource = `
id: acme-issue-to-pr
on:
acme.issue_created:
connection: acme-main
filters:
repo: acme/widget
subject:
key: "{{ event.acme.repo }}#{{ event.acme.issue_number }}"
on_conflict: ignore
initial: fix
states:
fix:
kind: agent
max_loops: 3
prompt: "Fix #{{ event.acme.issue_number }}."
auth:
acme:
connection: acme-main
scope: write
output:
schema:
type: object
properties:
outcome:
type: string
enum: [pr_ready, needs_maintainer]
pr_number:
type: number
head_sha:
type: string
required: [outcome, pr_number, head_sha]
additionalProperties: false
on:
pr_ready: wait_ci
needs_maintainer: maintainer_gate
max_loops_exceeded: maintainer_gate
wait_ci:
kind: acme.wait_ci
input:
repo: acme/widget
pr_number: "{{ steps.fix.outputs.pr_number }}"
head_sha: "{{ steps.fix.outputs.head_sha }}"
timeout: 90m
on:
green: wait_review
red: fix
timeout: maintainer_gate
wait_review:
kind: wait.workflow
workflow: acme-review
output_key: "review:acme/widget#{{ steps.fix.outputs.pr_number }}@{{ steps.fix.outputs.head_sha }}"
dispatch_if_missing: true
inputs:
pr_number: "{{ steps.fix.outputs.pr_number }}"
head_sha: "{{ steps.fix.outputs.head_sha }}"
timeout: 1h
on:
approved: cooldown
changes_requested: fix
timeout: maintainer_gate
cooldown:
kind: sleep
duration: 5m
on:
done: merge
maintainer_gate:
kind: gate
title: "Decision needed on #{{ event.acme.issue_number }}"
summary: "{{ steps.wait_review.outputs.reason ?? 'manual review' }}"
recommended: rework
choices:
- { id: merge_anyway, label: Merge anyway }
- { id: rework, label: Rework, description: Try fix again }
timeout: 14d
on_timeout:
terminal: cancelled
reason: gate_expired
on:
merge_anyway: merge
rework: fix
merge:
kind: acme.merge_pr
auth:
acme:
connection: acme-main
scope: write
input:
pr_number: "{{ steps.fix.outputs.pr_number }}"
note: "{{ gate.note ?? 'auto-merged' }}"
on:
merged: done
conflict: fix
publish:
key: "issue:acme/widget#{{ event.acme.issue_number }}"
payload:
pr_number: "{{ steps.fix.outputs.pr_number }}"
head_sha: "{{ steps.fix.outputs.head_sha }}"
`;
const yamlIR = compileWorkflowYaml(yamlSource);
expect(JSON.stringify(dslIR)).toBe(JSON.stringify(yamlIR));
expect(validateWorkflowIR(JSON.parse(JSON.stringify(dslIR)) as WorkflowIR)).toEqual(dslIR);
});
it("compiles scheduled 1-state trigger shorthand with recurrence unchanged", () => {
const scheduledYaml = `
name: acme-scheduled-sweep
enabled: false
on:
manual.run: {}
schedule.tick:
recurrence:
start: "2026-10-13T12:20:00"
rule: "FREQ=HOURLY;INTERVAL=2;BYMINUTE=20;BYSECOND=0"
timezone: "Europe/Berlin"
run:
target:
daemon: factory
cwd: /srv/acme/bot
agent:
provider: codex
model: gpt-6.1-terra
mode: full-access
thinkingOptionId: medium
continuation:
mode: new
max_runtime: 40m
idle_timeout: 10m
auto_archive: true
background: true
acme:
connection: acme-main
repositories: [acme/widget]
permissions:
issues: write
duration: 1h
prompt: |
Run sweep.
\${{ paseo.prompt }}
`;
const ir = compileWorkflowYaml(scheduledYaml);
expect(ir.id).toBe("acme-scheduled-sweep");
expect(ir.enabled).toBe(false);
expect(ir.initial).toBe("run");
expect(ir.on["schedule.tick"]?.recurrence?.rule).toContain("FREQ=HOURLY");
const runStep = ir.states["run"];
expect(runStep?.kind).toBe("agent");
if (runStep?.kind === "agent") {
expect(runStep.auth?.["acme"]?.connection).toBe("acme-main");
}
});
it("compiles ALL 19 real factory trigger YAML files in ~/dev/skills/hub/.paseo/triggers/ read-only when present", () => {
const triggersDir = path.join(homedir(), "dev", "skills", "hub", ".paseo", "triggers");
if (!existsSync(triggersDir)) {
return;
}
const files = readdirSync(triggersDir)
.filter((name) => name.endsWith(".yml") || name.endsWith(".yaml"))
.sort();
expect(files.length).toBeGreaterThanOrEqual(19);
for (const file of files) {
const source = readFileSync(path.join(triggersDir, file), "utf8");
const ir = compileWorkflowYaml(source);
const roundTripped = JSON.parse(JSON.stringify(ir)) as WorkflowIR;
validateWorkflowIR(roundTripped);
expect(roundTripped.version, file).toBe(1);
expect(roundTripped.id.length, file).toBeGreaterThan(0);
expect(roundTripped.initial, file).toBe("run");
expect(Object.keys(roundTripped.states), file).toEqual(["run"]);
expect(roundTripped.states["run"]?.kind, file).toBe("agent");
}
});
});
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,202 @@
import { describe, expect, it } from "vitest";
import { defineWorkflow, expr, ref, step, terminal, tpl } from "../src/dsl.js";
import {
evaluateExpression,
evaluateStringExpression,
parseExpression,
parseTemplateExpression,
type ExpressionContext,
} from "../src/internal/expression.js";
import { validateWorkflowIR, WorkflowValidationError, type WorkflowIR } from "../src/ir.js";
const sampleContext: ExpressionContext = {
event: {
acme: {
repo: "acme/widget",
item: { number: 42 },
},
},
prompt: "Please inspect this issue",
inputs: { repo: "acme/override", retries: 3 },
subject: { key: "acme/widget#42", data: { priority: "p0" } },
steps: {
reproduce: {
outcome: "reproduced",
outputs: { root_cause: "race condition", contributor_pr: null },
attempts: 1,
},
fix: {
outcome: "pr_ready",
outputs: { pr_number: 108, head_sha: "abc123" },
attempts: 2,
},
},
gate: { choice: "rework", note: "add a regression test", actor: "alice" },
values: {
active_pr: parseExpression(
"steps.fix.outputs.pr_number ?? steps.reproduce.outputs.contributor_pr",
),
},
executionId: "exec_99",
};
describe("expressions and templates", () => {
it("parses both ${{ ... }} and {{ ... }} to identical ASTs and evaluates all namespaces", () => {
const dollarAst = parseTemplateExpression(
"Issue #${{ event.acme.item.number }} ({{ execution.id }})",
);
const bareAst = parseTemplateExpression(
"Issue #{{ event.acme.item.number }} (${{ paseo.execution.id }})",
);
const dslAst = tpl`Issue #${ref("event.acme.item.number")} (${expr.executionId()})`;
expect(JSON.stringify(dollarAst)).toBe(JSON.stringify(bareAst));
expect(JSON.stringify(dollarAst)).toBe(JSON.stringify(dslAst));
expect(evaluateStringExpression(dollarAst, sampleContext)).toBe("Issue #42 (exec_99)");
expect(evaluateExpression(parseExpression("paseo.context.acme.repo"), sampleContext)).toBe(
"acme/widget",
);
expect(evaluateExpression(parseExpression("paseo.inputs.repo"), sampleContext)).toBe(
"acme/override",
);
expect(evaluateExpression(parseExpression("paseo.prompt"), sampleContext)).toBe(
"Please inspect this issue",
);
expect(evaluateExpression(parseExpression("subject.key"), sampleContext)).toBe(
"acme/widget#42",
);
expect(evaluateExpression(parseExpression("subject.data.priority"), sampleContext)).toBe("p0");
expect(evaluateExpression(parseExpression("steps.fix.attempts"), sampleContext)).toBe(2);
expect(evaluateExpression(parseExpression("steps.fix.outcome"), sampleContext)).toBe(
"pr_ready",
);
expect(evaluateExpression(parseExpression("gate.note"), sampleContext)).toBe(
"add a regression test",
);
expect(evaluateExpression(parseExpression("values.active_pr"), sampleContext)).toBe(108);
});
it("preserves typed non-string values for standalone interpolations", () => {
const numExpr = parseTemplateExpression("${{ steps.fix.outputs.pr_number }}");
expect(evaluateExpression(numExpr, sampleContext)).toBe(108);
const boolExpr = parseTemplateExpression("{{ steps.fix.outcome == 'pr_ready' && !false }}");
expect(evaluateExpression(boolExpr, sampleContext)).toBe(true);
});
});
describe("static WorkflowIR validation", () => {
it("rejects unknown transition target states", () => {
expect(() =>
defineWorkflow({
id: "bad-target",
on: { "acme.go": {} },
initial: "first",
steps: {
first: step.agent({
prompt: "hi",
on: { ok: "does_not_exist" },
}),
},
}),
).toThrowError(WorkflowValidationError);
});
it("rejects unguarded cycles lacking maxLoops + max_loops_exceeded", () => {
expect(() =>
defineWorkflow({
id: "unguarded-cycle",
on: { "acme.go": {} },
initial: "a",
steps: {
a: step.agent({ prompt: "a", on: { ok: "b" } }),
b: step.agent({ prompt: "b", on: { retry: "a", ok: terminal.done() } }),
},
}),
).toThrowError(/unguarded cycle/i);
});
it("rejects cycles with maxLoops set but missing max_loops_exceeded transition", () => {
expect(() =>
defineWorkflow({
id: "missing-exceeded",
on: { "acme.go": {} },
initial: "a",
steps: {
a: step.agent({ prompt: "a", maxLoops: 3, on: { ok: "b" } }),
b: step.agent({ prompt: "b", on: { retry: "a", ok: terminal.done() } }),
},
}),
).toThrowError(/unguarded cycle/i);
});
it("accepts cycles guarded by maxLoops + on.max_loops_exceeded", () => {
const ir = defineWorkflow({
id: "guarded-cycle",
on: { "acme.go": {} },
initial: "a",
steps: {
a: step.agent({
prompt: "a",
maxLoops: 3,
on: { ok: "b", max_loops_exceeded: terminal.failed("loop_limit") },
}),
b: step.agent({ prompt: "b", on: { retry: "a", ok: terminal.done() } }),
},
});
expect(validateWorkflowIR(JSON.parse(JSON.stringify(ir)))).toEqual(ir);
});
it("rejects expressions referencing nonexistent steps", () => {
expect(() =>
defineWorkflow({
id: "bad-step-ref",
on: { "acme.go": {} },
initial: "first",
steps: {
first: step.agent({
prompt: tpl`Look at ${ref("steps.ghost.outputs.pr_number")}`,
on: { ok: terminal.done() },
}),
},
}),
).toThrowError(/unknown step "ghost"/i);
});
it("rejects invalid gate recommended choice and invalid sleep config", () => {
expect(() =>
defineWorkflow({
id: "bad-gate",
on: { "acme.go": {} },
initial: "ask",
steps: {
ask: step.gate({
title: "Decide",
recommended: "missing",
choices: [{ id: "yes", label: "Yes" }],
on: { yes: terminal.done() },
}),
},
}),
).toThrowError(/recommended choice "missing"/i);
const invalidSleep: WorkflowIR = {
version: 1,
id: "bad-sleep",
enabled: true,
on: { "acme.go": {} },
initial: "nap",
states: {
nap: {
id: "nap",
kind: "sleep",
on: { done: { terminal: "done" } },
},
},
};
expect(() => validateWorkflowIR(invalidSleep)).toThrowError(
/exactly one of durationMs or until/i,
);
});
});
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"target": "ES2023",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2023", "DOM"],
"types": [],
"skipLibCheck": true,
"resolveJsonModule": true,
"isolatedModules": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"outDir": "./dist",
"rootDir": "./src",
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "test"]
}
@@ -0,0 +1,10 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"types": ["node"],
"rootDir": ".",
"noEmit": true
},
"include": ["src/**/*", "test/**/*"],
"exclude": ["node_modules", "dist"]
}
+3
View File
@@ -269,6 +269,7 @@ test("PR routing declares stable behavior ownership", () => {
"packages/client/**",
"packages/highlight/**",
"packages/protocol/**",
"packages/workflows/**",
],
browser: [
"packages/server/src/server/agent/provider-snapshot-manager.ts",
@@ -548,6 +549,8 @@ test("quality preserves commands and routes each domain independently after fail
"npm run test --workspace=@getpaseo/protocol",
"npm run test --workspace=@getpaseo/client",
"npm run test --workspace=@getpaseo/highlight",
"npm run build:workflows",
"npm run test --workspace=@getpaseo/workflows",
"npm run typecheck:examples --workspace=@getpaseo/client",
],
};
+7
View File
@@ -27,6 +27,10 @@ const dependencySections = [
"optionalDependencies",
];
// Packages with independent semver lifecycles stay on their own version until
// folded into the main Paseo release train.
const INDEPENDENT_VERSION_WORKSPACES = new Set(["@getpaseo/workflows"]);
const touched = [];
for (const workspacePath of workspacePaths) {
@@ -36,6 +40,9 @@ for (const workspacePath of workspacePaths) {
}
const pkg = JSON.parse(readFileSync(packagePath, "utf8"));
if (INDEPENDENT_VERSION_WORKSPACES.has(pkg.name)) {
continue;
}
let changed = false;
if (pkg.version !== rootVersion) {