Merge commit '170aacd52cdd7a09b18c8ec2920556c7b01e11e8' into 3.x

# Conflicts:
#	packages/cli/src/executions/pre-execution-checks/__tests__/workflow-pre-execute.test.ts
#	packages/cli/src/executions/pre-execution-checks/workflow-pre-execute.ts
#	packages/cli/src/modules/mcp/__tests__/mcp-protected-resource.test.ts
This commit is contained in:
n8n-assistant[bot] committed 2026-12-01 06:03:08 +00:00
commit 1eb3965437
701 files changed
+44961 -5303

No files matched your search

+13
View File
@@ -63,6 +63,19 @@ git config remote.pushDefault origin # if multiple remotes exist (skips remo
9. **Use `gh stack link` for external tool workflows.** When branches are managed by an external tool (jj, Sapling, etc.), use `gh stack link branch-a branch-b`. `link` does not rely on local tracking state and is intended for API-driven PR and stack management. Provide at least two branches/PRs to create or update a stack, or a stack number followed by the new branches/PRs to append them to the top of an existing stack (e.g. `gh stack link 7 branch-c`).
10. **Use `gh stack merge --yes` to merge stacked PRs.** `gh pr merge` does not work with stacked PRs. In a non-interactive terminal `gh stack merge` runs without prompting and merges the entire stack (bottom to top) atomically; pass `--yes` to be explicit. Scope the merge by passing a pull request number (`gh stack merge 42 --yes` merges everything up to and including PR #42) or a stack number (`gh stack merge 7 --yes`, which needs no local checkout). Choose the method with `--squash`, `--rebase`, `--merge`, or `--merge-method <method>`; without one, the last-used method is used. The merge is all-or-nothing — if any PR can't be merged, none are, and the failure reason is reported. Only basic pull request state is checked before merging (open and not a draft); bypassing merge requirements is not supported for stacks. If the base branch uses a merge queue, the stack is added to the queue instead of merging directly: the queue chooses the merge method (any method you pass is ignored with a warning), and the pull requests are added to the queue together but merge as the queue processes them, so they may land in separate groups rather than all at once.
### n8n CI and stack hygiene
Every push, cascading rebase, or bottom-PR merge triggers CI on every active PR above it. Follow these rules to avoid quadratic CI churn:
1. **Keep active (ready-for-review) layers in a stack to 3–5 PRs.** Keep later WIP layers local with `gh stack add` or in draft until lower layers are close to landing. Upper-stack drafts do not run CI, while deep chains of ready-for-review PRs trigger quadratic CI fan-out on rebases and partial merges.
2. **Batch fixes before pushing.** Apply review fixes across lower branches, run `gh stack rebase --no-trunk`, and run `gh stack push` once. Do not push after every single comment.
3. **Avoid unnecessary trunk rebases mid-review.** Rebase onto `master` only to resolve a conflict or right before merge.
4. **Batch-merge approved layers.** When multiple consecutive layers are approved, merge from the highest approved PR (`gh stack merge <top-approved-pr> --yes`) instead of merging one PR at a time. Each 1-by-1 merge triggers a cascading rebase and new CI runs on every open PR above it.
5. **Know how n8n PR CI treats drafts:**
- Upper-stack draft PRs (draft + non-trunk base) skip `ci-pull-requests.yml` unless labeled `run-ci`.
- Bottom-of-stack and standalone draft PRs run build, lint, typecheck, unit, and DB tests, and skip E2E unless labeled `force-e2e`.
- Marking a PR ready for review (`ready_for_review`) runs full CI and E2E automatically.
**Never do any of the following — each triggers an interactive prompt or TUI that will hang:**
- ❌ `gh stack view` or `gh stack view --short` — always use `gh stack view --json`
- ❌ `gh stack submit` without `--auto` — always use `gh stack submit --auto`
+6
View File
@@ -38,6 +38,12 @@ declares.
**Add script:** Create `.mjs` in `scripts/`, document in `WORKFLOWS.md`
**Workflow tests:** Do not add boilerplate YAML-mirroring tests to
`scripts/workflow-validation.test.mjs` (assertions that just repeat workflow
YAML keys or `if:` strings). `actionlint` and CI already validate workflow
syntax and execution. Only add tests in `scripts/*.test.mjs` for non-trivial
script logic or cross-workflow invariants that a linter cannot catch.
### Reference
See `WORKFLOWS.md` for:
+25 -3
View File
@@ -201,14 +201,34 @@ the base branch, as before.
`ci-filter` tests the whole PR when one of these is true:
- The event is not a push to an open PR (`opened`, `reopened`, merge queue).
- No earlier PR commit passed CI.
- The event is not a push to an open PR (`opened`, `reopened`, `ready_for_review`, merge queue).
- No earlier PR commit passed CI (for a ready PR, runs created before the latest `ready_for_review` event are ignored because draft runs skip E2E).
- The earlier commit is not an ancestor of the head (force push or rebase).
- The new commits include a merge, for example from master.
- The merge base changed, for example because the PR now targets another branch.
- The PR has the `force-full-ci` label. The script reads the label from the
API, so a "Re-run all jobs" after you add the label tests the whole PR.
### Draft PRs and stacked PRs
`ci-pull-requests.yml` scopes work on draft PRs to keep fast feedback without
flooding runners on WIP stacks:
- **Upper-stack drafts** (`draft == true` and `base.ref` is not `master`, `3.x`,
`1.x`, `2.x`, `release/*`, `release-candidate/*`, or `bundle/*`): all jobs in
`ci-pull-requests.yml` (including `Required Checks`) are skipped. Add the
`run-ci` label to opt in while still in draft. CI runs automatically once the
PR retargets `master` or moves to ready for review.
- **All other drafts** (standalone drafts and bottom-of-stack drafts targeting
trunk or a release branch): build, format, lint, typecheck, unit, packaging,
and DB tests still run, but `prepare-docker`, `e2e`, `e2e-engine`, and
`e2e-performance` are skipped unless overridden by `force-e2e`,
`force-engine-e2e`, or `run-perf-tests`.
- **Ready for review:** marking a PR ready fires `ready_for_review`, which runs
the full PR diff (including E2E). `find-last-green-commit.mjs` ignores
draft-era runs on ready PRs so subsequent pushes never skip E2E for earlier
commits.
**Why:** a small fix, such as one line in a test, ran all E2E shards and DB
legs again because an earlier commit had changed runtime code. The earlier
commits passed CI against an older base branch. The merge queue runs the unit,
@@ -292,8 +312,9 @@ survive. The run is skipped when `latest` already matches the lockfile; a
| Event | Workflow | Effect |
|------------------------------------|----------------------------------------|--------|
| PR dequeued (not merged or manual) | `util-notify-merge-queue-removal.yml` | Writes one PR comment with the reason. Later removals update the same comment. |
| Merge group destroyed (`invalidated` or `dequeued`) | `util-cancel-destroyed-merge-group.yml` | Cancels queued and in-progress `merge_group` runs on the destroyed head SHA via `cancel-destroyed-merge-group.mjs`. |
This workflow uses `pull_request`, because GitHub does not start a
`util-notify-merge-queue-removal.yml` uses `pull_request`, because GitHub does not start a
`pull_request_target` run for the `dequeued` type. On PRs from external
contributors and bots, a run waits for approval. On fork PRs, the token is
read-only, so the comment step fails. The `concurrency` group keeps at most one
@@ -944,6 +965,7 @@ Scripts in `.github/scripts/`:
| `quality/check-cubic-config.mjs` | Validate `cubic.yaml` against the vendored cubic schema; enforce its silent agent/character limits. `--refresh` re-pulls the schema | `test-workflow-scripts-reusable.yml`, `util-refresh-cubic-schema.yml` |
| `glob.mjs` | Builtin-only glob matcher for changed-file paths (`**`, `*`, dot segments) | `quality/check-pr-size.mjs` |
| `probe-registry.mjs` | Registry path throughput probe (temporary) | `util-probe-registry.yml` |
| `cancel-destroyed-merge-group.mjs` | Cancel active `merge_group` runs when GitHub invalidates or dequeues a merge group | `util-cancel-destroyed-merge-group.yml` |
### Preview Scripts
@@ -0,0 +1,96 @@
/**
* Cancels queued or in-progress workflow runs for a destroyed merge group.
*
* When GitHub invalidates or dequeues a merge group, GitHub deletes the
* temporary queue ref and creates a replacement merge group, but GitHub
* Actions does not cancel runs already started on the dead head SHA.
*/
import { getEventFromGithubEventPath, initGithub } from './github-helpers.mjs';
const CANCELLABLE_REASONS = new Set(['invalidated', 'dequeued']);
/** @param {string | undefined} reason */
export function shouldCancelDestroyedMergeGroup(reason) {
return typeof reason === 'string' && CANCELLABLE_REASONS.has(reason);
}
/**
* Selects non-completed run IDs to cancel, excluding the current workflow run.
*
* @param {Array<{ id: number, status?: string }>} runs
* @param {number} currentRunId
*/
export function selectRunsToCancel(runs, currentRunId) {
const seen = new Set();
const ids = [];
for (const run of runs) {
if (!run?.id || run.id === currentRunId || run.status === 'completed' || seen.has(run.id)) {
continue;
}
seen.add(run.id);
ids.push(run.id);
}
return ids;
}
export async function main() {
const event = getEventFromGithubEventPath();
const reason = event.reason;
if (!shouldCancelDestroyedMergeGroup(reason)) {
console.log(`Skipping cancellation for merge_group destroy reason: ${reason ?? 'unknown'}`);
return '0';
}
const headSha = event.merge_group?.head_sha;
if (!headSha) {
console.log('Missing merge_group.head_sha in event payload');
return '0';
}
const currentRunId = Number(process.env.GITHUB_RUN_ID || 0);
const { octokit, owner, repo } = initGithub();
// Query all statuses in one call so runs in waiting/requested/pending or
// transitioning between queued and in_progress are never missed.
const allRuns = await octokit.paginate(octokit.rest.actions.listWorkflowRunsForRepo, {
owner,
repo,
event: 'merge_group',
head_sha: headSha,
per_page: 100,
});
const runIds = selectRunsToCancel(allRuns, currentRunId);
if (runIds.length === 0) {
console.log(`No active merge_group runs found for ${headSha} (reason: ${reason})`);
return '0';
}
let cancelled = 0;
for (const runId of runIds) {
try {
await octokit.rest.actions.cancelWorkflowRun({
owner,
repo,
run_id: runId,
});
cancelled++;
console.log(`Cancelled merge_group run ${runId} for ${headSha} (reason: ${reason})`);
} catch (error) {
const status = error && typeof error === 'object' ? error.status : undefined;
if (status === 409) {
console.log(`Run ${runId} already completed; skipping`);
continue;
}
console.log(
`::warning::Failed to cancel merge_group run ${runId}: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
return String(cancelled);
}
if (import.meta.url === `file://${process.argv[1]}`) {
console.log(await main());
}
@@ -0,0 +1,122 @@
import assert from 'node:assert/strict';
import { beforeEach, describe, it, mock } from 'node:test';
let event;
let runs;
const listWorkflowRunsForRepo = () => {};
const cancelWorkflowRun = mock.fn(async () => ({}));
const paginate = mock.fn(async () => runs);
const octokit = {
paginate,
rest: {
actions: {
listWorkflowRunsForRepo,
cancelWorkflowRun,
},
},
};
mock.module('./github-helpers.mjs', {
namedExports: {
getEventFromGithubEventPath: () => event,
initGithub: () => ({ octokit, owner: 'n8n-io', repo: 'n8n' }),
},
});
const { main, selectRunsToCancel, shouldCancelDestroyedMergeGroup } = await import(
'./cancel-destroyed-merge-group.mjs'
);
describe('shouldCancelDestroyedMergeGroup', () => {
it('cancels invalidated and dequeued merge groups', () => {
assert.equal(shouldCancelDestroyedMergeGroup('invalidated'), true);
assert.equal(shouldCancelDestroyedMergeGroup('dequeued'), true);
});
it('does not cancel merged or unknown reasons', () => {
assert.equal(shouldCancelDestroyedMergeGroup('merged'), false);
assert.equal(shouldCancelDestroyedMergeGroup(undefined), false);
});
});
describe('selectRunsToCancel', () => {
it('deduplicates non-completed run IDs and excludes completed and current runs', () => {
assert.deepEqual(
selectRunsToCancel(
[
{ id: 10, status: 'in_progress' },
{ id: 20, status: 'queued' },
{ id: 25, status: 'waiting' },
{ id: 30, status: 'completed' },
{ id: 10, status: 'in_progress' },
{ id: 99, status: 'in_progress' },
],
99,
),
[10, 20, 25],
);
});
});
describe('main', () => {
beforeEach(() => {
process.env.GITHUB_RUN_ID = '999';
event = {
reason: 'invalidated',
merge_group: { head_sha: 'deadbeef' },
};
runs = [
{ id: 101, status: 'in_progress' },
{ id: 102, status: 'queued' },
{ id: 103, status: 'pending' },
{ id: 104, status: 'completed' },
{ id: 999, status: 'in_progress' },
];
paginate.mock.resetCalls();
cancelWorkflowRun.mock.resetCalls();
cancelWorkflowRun.mock.restore();
});
it('cancels all non-completed merge_group runs for the dead SHA in one query', async () => {
assert.equal(await main(), '3');
assert.equal(paginate.mock.callCount(), 1);
assert.deepEqual(paginate.mock.calls[0].arguments[1], {
owner: 'n8n-io',
repo: 'n8n',
event: 'merge_group',
head_sha: 'deadbeef',
per_page: 100,
});
assert.deepEqual(
cancelWorkflowRun.mock.calls.map((c) => c.arguments[0]),
[
{ owner: 'n8n-io', repo: 'n8n', run_id: 101 },
{ owner: 'n8n-io', repo: 'n8n', run_id: 102 },
{ owner: 'n8n-io', repo: 'n8n', run_id: 103 },
],
);
});
it('skips cancellation when the merge group was merged', async () => {
event.reason = 'merged';
assert.equal(await main(), '0');
assert.equal(paginate.mock.callCount(), 0);
assert.equal(cancelWorkflowRun.mock.callCount(), 0);
});
it('continues when a run completes before cancellation (HTTP 409)', async () => {
runs = [
{ id: 101, status: 'in_progress' },
{ id: 102, status: 'queued' },
];
cancelWorkflowRun.mock.mockImplementation(async ({ run_id }) => {
if (run_id === 101) {
const err = new Error('Cannot cancel a workflow run that is completed.');
err.status = 409;
throw err;
}
});
assert.equal(await main(), '1');
assert.equal(cancelWorkflowRun.mock.callCount(), 2);
});
});
+67 -52
View File
@@ -15,70 +15,85 @@
* GITHUB_OUTPUT - Path to GitHub Actions output file (optional)
*/
import { execSync } from 'node:child_process';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { appendFileSync } from 'node:fs';
import { pathToFileURL } from 'node:url';
const githubOutput = process.env.GITHUB_OUTPUT || null;
function getDigest(imageRef) {
export function getDigest(imageRef, execFile = execFileSync) {
if (!imageRef) return '';
const raw = execSync(`docker buildx imagetools inspect "${imageRef}" --raw`, {
encoding: 'utf8',
if (imageRef.startsWith('-') || /[\s\r\n]/.test(imageRef)) {
throw new Error(`Invalid image reference: ${JSON.stringify(imageRef)}`);
}
const raw = execFile('docker', ['buildx', 'imagetools', 'inspect', imageRef, '--raw'], {
maxBuffer: 10 * 1024 * 1024,
});
const hash = execSync('sha256sum', { input: raw, encoding: 'utf8' }).split(' ')[0].trim();
const hash = createHash('sha256').update(raw).digest('hex');
return `sha256:${hash}`;
}
function getImageName(imageRef) {
export function getImageName(imageRef) {
if (!imageRef) return '';
return imageRef.replace(/:([^:]+)$/, '');
return imageRef.replace(/@[^@]+$/, '').replace(/:([^/:]+)$/, '');
}
function setOutput(name, value) {
if (githubOutput && value) appendFileSync(githubOutput, `${name}=${value}\n`);
function setOutput(githubOutput, name, value) {
if (!githubOutput || !value) return;
if (/[\r\n]/.test(value)) {
throw new Error(`Invalid output value for ${name}: contains newline`);
}
appendFileSync(githubOutput, `${name}=${value}\n`);
}
const n8nTag = process.env.N8N_TAG || '';
const n8nPcTag = process.env.N8N_PC_TAG || '';
const n8nDebianTag = process.env.N8N_DEBIAN_TAG || '';
const runnersTag = process.env.RUNNERS_TAG || '';
const distrolessTag = process.env.DISTROLESS_TAG || '';
const runnersDebianTag = process.env.RUNNERS_DEBIAN_TAG || '';
function main() {
const githubOutput = process.env.GITHUB_OUTPUT || null;
const results = {
n8n: { digest: getDigest(n8nTag), image: getImageName(n8nTag) },
n8n_pc: { digest: getDigest(n8nPcTag), image: getImageName(n8nPcTag) },
n8n_debian: { digest: getDigest(n8nDebianTag), image: getImageName(n8nDebianTag) },
runners: { digest: getDigest(runnersTag), image: getImageName(runnersTag) },
runners_distroless: { digest: getDigest(distrolessTag), image: getImageName(distrolessTag) },
runners_debian: { digest: getDigest(runnersDebianTag), image: getImageName(runnersDebianTag) },
};
const n8nTag = process.env.N8N_TAG || '';
const n8nPcTag = process.env.N8N_PC_TAG || '';
const n8nDebianTag = process.env.N8N_DEBIAN_TAG || '';
const runnersTag = process.env.RUNNERS_TAG || '';
const distrolessTag = process.env.DISTROLESS_TAG || '';
const runnersDebianTag = process.env.RUNNERS_DEBIAN_TAG || '';
setOutput('n8n_digest', results.n8n.digest);
setOutput('n8n_image', results.n8n.image);
setOutput('n8n_pc_digest', results.n8n_pc.digest);
setOutput('n8n_pc_image', results.n8n_pc.image);
setOutput('n8n_debian_digest', results.n8n_debian.digest);
setOutput('n8n_debian_image', results.n8n_debian.image);
setOutput('runners_digest', results.runners.digest);
setOutput('runners_image', results.runners.image);
setOutput('runners_distroless_digest', results.runners_distroless.digest);
setOutput('runners_distroless_image', results.runners_distroless.image);
setOutput('runners_debian_digest', results.runners_debian.digest);
setOutput('runners_debian_image', results.runners_debian.image);
const results = {
n8n: { digest: getDigest(n8nTag), image: getImageName(n8nTag) },
n8n_pc: { digest: getDigest(n8nPcTag), image: getImageName(n8nPcTag) },
n8n_debian: { digest: getDigest(n8nDebianTag), image: getImageName(n8nDebianTag) },
runners: { digest: getDigest(runnersTag), image: getImageName(runnersTag) },
runners_distroless: { digest: getDigest(distrolessTag), image: getImageName(distrolessTag) },
runners_debian: { digest: getDigest(runnersDebianTag), image: getImageName(runnersDebianTag) },
};
console.log('=== Manifest Digests ===');
console.log(`n8n: ${results.n8n.digest || 'N/A'}`);
console.log(`n8n-pc: ${results.n8n_pc.digest || 'N/A'}`);
console.log(`n8n-debian: ${results.n8n_debian.digest || 'N/A'}`);
console.log(`runners: ${results.runners.digest || 'N/A'}`);
console.log(`runners-distroless: ${results.runners_distroless.digest || 'N/A'}`);
console.log(`runners-debian: ${results.runners_debian.digest || 'N/A'}`);
console.log('');
console.log('=== Image Names ===');
console.log(`n8n: ${results.n8n.image || 'N/A'}`);
console.log(`n8n-pc: ${results.n8n_pc.image || 'N/A'}`);
console.log(`n8n-debian: ${results.n8n_debian.image || 'N/A'}`);
console.log(`runners: ${results.runners.image || 'N/A'}`);
console.log(`runners-distroless: ${results.runners_distroless.image || 'N/A'}`);
console.log(`runners-debian: ${results.runners_debian.image || 'N/A'}`);
setOutput(githubOutput, 'n8n_digest', results.n8n.digest);
setOutput(githubOutput, 'n8n_image', results.n8n.image);
setOutput(githubOutput, 'n8n_pc_digest', results.n8n_pc.digest);
setOutput(githubOutput, 'n8n_pc_image', results.n8n_pc.image);
setOutput(githubOutput, 'n8n_debian_digest', results.n8n_debian.digest);
setOutput(githubOutput, 'n8n_debian_image', results.n8n_debian.image);
setOutput(githubOutput, 'runners_digest', results.runners.digest);
setOutput(githubOutput, 'runners_image', results.runners.image);
setOutput(githubOutput, 'runners_distroless_digest', results.runners_distroless.digest);
setOutput(githubOutput, 'runners_distroless_image', results.runners_distroless.image);
setOutput(githubOutput, 'runners_debian_digest', results.runners_debian.digest);
setOutput(githubOutput, 'runners_debian_image', results.runners_debian.image);
console.log('=== Manifest Digests ===');
console.log(`n8n: ${results.n8n.digest || 'N/A'}`);
console.log(`n8n-pc: ${results.n8n_pc.digest || 'N/A'}`);
console.log(`n8n-debian: ${results.n8n_debian.digest || 'N/A'}`);
console.log(`runners: ${results.runners.digest || 'N/A'}`);
console.log(`runners-distroless: ${results.runners_distroless.digest || 'N/A'}`);
console.log(`runners-debian: ${results.runners_debian.digest || 'N/A'}`);
console.log('');
console.log('=== Image Names ===');
console.log(`n8n: ${results.n8n.image || 'N/A'}`);
console.log(`n8n-pc: ${results.n8n_pc.image || 'N/A'}`);
console.log(`n8n-debian: ${results.n8n_debian.image || 'N/A'}`);
console.log(`runners: ${results.runners.image || 'N/A'}`);
console.log(`runners-distroless: ${results.runners_distroless.image || 'N/A'}`);
console.log(`runners-debian: ${results.runners_debian.image || 'N/A'}`);
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
main();
}
@@ -0,0 +1,85 @@
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { describe, it } from 'node:test';
import { getDigest, getImageName } from './get-manifest-digests.mjs';
describe('getImageName', () => {
it('returns an empty string for empty input', () => {
assert.equal(getImageName(''), '');
});
it('strips a tag from a standard registry reference', () => {
assert.equal(getImageName('ghcr.io/n8n-io/n8n:nightly'), 'ghcr.io/n8n-io/n8n');
assert.equal(
getImageName('ghcr.io/n8n-io/runners:v3-nightly-distroless'),
'ghcr.io/n8n-io/runners',
);
assert.equal(getImageName('n8n:latest'), 'n8n');
});
it('preserves registry ports on tagless and tagged references', () => {
assert.equal(getImageName('localhost:5000/n8n'), 'localhost:5000/n8n');
assert.equal(getImageName('localhost:5000/n8n:1.2.3'), 'localhost:5000/n8n');
assert.equal(getImageName('registry.internal:8443/org/n8n'), 'registry.internal:8443/org/n8n');
assert.equal(
getImageName('registry.internal:8443/org/n8n:nightly'),
'registry.internal:8443/org/n8n',
);
});
it('strips digest suffixes with or without tags', () => {
const digest = 'sha256:' + 'a'.repeat(64);
assert.equal(getImageName(`ghcr.io/n8n-io/n8n@${digest}`), 'ghcr.io/n8n-io/n8n');
assert.equal(getImageName(`ghcr.io/n8n-io/n8n:nightly@${digest}`), 'ghcr.io/n8n-io/n8n');
assert.equal(getImageName(`localhost:5000/n8n@${digest}`), 'localhost:5000/n8n');
assert.equal(getImageName(`localhost:5000/n8n:1.0@${digest}`), 'localhost:5000/n8n');
});
});
describe('getDigest', () => {
it('returns an empty string for empty input without invoking docker', () => {
let called = false;
const digest = getDigest('', () => {
called = true;
return Buffer.from('');
});
assert.equal(digest, '');
assert.equal(called, false);
});
it('invokes docker via argument array and computes the sha256 digest of raw manifest bytes', () => {
const payload = Buffer.from('{"schemaVersion":2,"manifests":[]}\n', 'utf8');
const expected = `sha256:${createHash('sha256').update(payload).digest('hex')}`;
let receivedCmd;
let receivedArgs;
const digest = getDigest('localhost:5000/n8n:nightly', (cmd, args) => {
receivedCmd = cmd;
receivedArgs = args;
return payload;
});
assert.equal(receivedCmd, 'docker');
assert.deepEqual(receivedArgs, [
'buildx',
'imagetools',
'inspect',
'localhost:5000/n8n:nightly',
'--raw',
]);
assert.equal(digest, expected);
});
it('rejects image references with leading dashes or whitespace/newlines', () => {
const noop = () => Buffer.from('');
assert.throws(() => getDigest('--raw', noop), /Invalid image reference/);
assert.throws(
() => getDigest('ghcr.io/n8n-io/n8n:nightly\nextra=1', noop),
/Invalid image reference/,
);
assert.throws(
() => getDigest('ghcr.io/n8n-io/n8n:nightly extra', noop),
/Invalid image reference/,
);
});
});
+33 -3
View File
@@ -42,11 +42,28 @@ export function workflowFileFromRef(workflowRef) {
return match[1];
}
/**
* Finds the timestamp of the latest `ready_for_review` event on a PR.
* Draft runs skip E2E, so a ready PR must not reuse a draft-era green run.
*
* @param {Array<{ event?: string, created_at?: string }>} events
*/
export function findLastReadyForReviewAt(events) {
let latest = '';
for (const event of events) {
if (event?.event === 'ready_for_review' && event.created_at && event.created_at > latest) {
latest = event.created_at;
}
}
return latest;
}
export async function main() {
try {
const pr = getEventFromGithubEventPath().pull_request;
// Read the labels from the API: a re-run reuses the labels of the original event.
if (readPrLabels(await getPullRequestById(pr.number)).includes(FULL_CI_LABEL)) {
// Read live PR state from the API: a re-run reuses the labels and draft flag of the original event.
const livePr = await getPullRequestById(pr.number);
if (readPrLabels(livePr).includes(FULL_CI_LABEL)) {
console.log(`The PR has the ${FULL_CI_LABEL} label`);
return '';
}
@@ -59,6 +76,19 @@ export async function main() {
pull_number: pr.number,
per_page: 100,
});
let minCreatedAt = pr.created_at;
if (!livePr.draft) {
const issueEvents = await octokit.paginate(octokit.rest.issues.listEvents, {
owner,
repo,
issue_number: pr.number,
per_page: 100,
});
const lastReadyAt = findLastReadyForReviewAt(issueEvents);
if (lastReadyAt && lastReadyAt > minCreatedAt) {
minCreatedAt = lastReadyAt;
}
}
// Older runs on the same branch name cannot belong to this PR.
const runs = await octokit.paginate(octokit.rest.actions.listWorkflowRuns, {
owner,
@@ -67,7 +97,7 @@ export async function main() {
event: 'pull_request',
branch: pr.head.ref,
status: 'success',
created: `>=${pr.created_at}`,
created: `>=${minCreatedAt}`,
per_page: 100,
});
@@ -5,11 +5,25 @@ import { readPrLabels } from './github-helpers.mjs';
let event;
let commits;
let runs;
let issueEvents;
let labels;
let draft;
const listCommits = () => {};
const listWorkflowRuns = () => {};
const paginate = mock.fn(async (method) => (method === listCommits ? commits : runs));
const octokit = { paginate, rest: { pulls: { listCommits }, actions: { listWorkflowRuns } } };
const listEvents = () => {};
const paginate = mock.fn(async (method) => {
if (method === listCommits) return commits;
if (method === listEvents) return issueEvents;
return runs;
});
const octokit = {
paginate,
rest: {
pulls: { listCommits },
actions: { listWorkflowRuns },
issues: { listEvents },
},
};
mock.module('./github-helpers.mjs', {
namedExports: {
@@ -18,13 +32,13 @@ mock.module('./github-helpers.mjs', {
return process.env[name];
},
getEventFromGithubEventPath: () => event,
getPullRequestById: async () => ({ labels }),
getPullRequestById: async () => ({ labels, draft }),
readPrLabels,
initGithub: () => ({ octokit, owner: 'n8n-io', repo: 'n8n' }),
},
});
const { main, pickLastGreenCommit, workflowFileFromRef } = await import(
const { findLastReadyForReviewAt, main, pickLastGreenCommit, workflowFileFromRef } = await import(
'./find-last-green-commit.mjs'
);
@@ -68,6 +82,26 @@ describe('workflowFileFromRef', () => {
});
});
describe('findLastReadyForReviewAt', () => {
it('returns an empty string when there is no ready_for_review event', () => {
assert.equal(
findLastReadyForReviewAt([{ event: 'labeled', created_at: '2026-11-01T11:00:00Z' }]),
'',
);
});
it('returns the latest ready_for_review timestamp', () => {
assert.equal(
findLastReadyForReviewAt([
{ event: 'ready_for_review', created_at: '2026-11-01T11:00:00Z' },
{ event: 'convert_to_draft', created_at: '2026-11-01T12:00:00Z' },
{ event: 'ready_for_review', created_at: '2026-11-01T13:00:00Z' },
]),
'2026-11-01T13:00:00Z',
);
});
});
describe('main', () => {
beforeEach(() => {
process.env.GITHUB_WORKFLOW_REF =
@@ -81,7 +115,9 @@ describe('main', () => {
};
commits = [{ sha: 'a' }, { sha: 'b' }, { sha: 'c' }];
runs = [run('a')];
issueEvents = [];
labels = [];
draft = false;
paginate.mock.resetCalls();
paginate.mock.restore();
});
@@ -101,6 +137,23 @@ describe('main', () => {
});
});
it('ignores draft-era runs when a ready PR has a ready_for_review event', async () => {
issueEvents = [{ event: 'ready_for_review', created_at: '2026-11-01T12:30:00Z' }];
assert.equal(await main(), 'a');
const runsCall = paginate.mock.calls.find((call) => call.arguments[0] === listWorkflowRuns);
assert.equal(runsCall?.arguments[1]?.created, '>=2026-11-01T12:30:00Z');
});
it('does not query issue events while the PR is still a draft', async () => {
draft = true;
issueEvents = [{ event: 'ready_for_review', created_at: '2026-11-01T12:30:00Z' }];
assert.equal(await main(), 'a');
const eventsCall = paginate.mock.calls.find((call) => call.arguments[0] === listEvents);
assert.equal(eventsCall, undefined);
const runsCall = paginate.mock.calls.find((call) => call.arguments[0] === listWorkflowRuns);
assert.equal(runsCall?.arguments[1]?.created, '>=2026-11-01T10:00:00Z');
});
it('returns an empty string when the PR has the force-full-ci label', async () => {
labels = [{ name: 'force-full-ci' }];
assert.equal(await main(), '');
+49 -1
View File
@@ -300,7 +300,7 @@ describe('automated release PR CI bypass', () => {
assert.equal(ci.jobs['pr-policy'].uses, './.github/workflows/ci-pr-policy-reusable.yml');
assertUsesPrPolicy(ci.jobs['install-and-build']);
assertUsesPrPolicy(ci.jobs['format-check']);
assert.equal(ci.jobs['required-checks'].if, 'always()');
assert.equal(ci.jobs['required-checks'].if, "always() && needs.pr-policy.result != 'skipped'");
assertNeedsPrPolicy(ci.jobs['required-checks']);
assert.equal(
stepNamed(ci, 'required-checks', 'Validate required checks').if,
@@ -334,6 +334,54 @@ describe('automated release PR CI bypass', () => {
});
});
describe('draft and upper-stack draft PR CI gating', () => {
const ci = workflowFile('ci-pull-requests.yml');
it('triggers on ready_for_review so undrafted PRs run full CI and E2E', () => {
const types = triggersOf(ci).pull_request?.types ?? [];
assert.deepEqual(types, ['opened', 'synchronize', 'reopened', 'ready_for_review']);
});
it('skips all CI jobs on upper-stack drafts unless run-ci is applied', () => {
const prPolicyIf = ci.jobs['pr-policy'].if;
assert.match(prPolicyIf, /github\.event_name == 'pull_request'/);
assert.match(prPolicyIf, /github\.event\.pull_request\.draft == true/);
assert.match(
prPolicyIf,
/!contains\(github\.event\.pull_request\.labels\.\*\.name, 'run-ci'\)/,
);
for (const base of ['master', '3.x', '1.x', '2.x']) {
assert.ok(prPolicyIf.includes(`base.ref != '${base}'`), `missing ${base} check`);
}
for (const prefix of ['release/', 'release-candidate/', 'bundle/']) {
assert.ok(
prPolicyIf.includes(`!startsWith(github.event.pull_request.base.ref, '${prefix}')`),
`missing ${prefix} check`,
);
}
assert.match(ci.jobs['install-and-build'].if, /needs\.pr-policy\.result == 'success'/);
assert.match(ci.jobs['format-check'].if, /needs\.pr-policy\.result == 'success'/);
assert.equal(ci.jobs['required-checks'].if, "always() && needs.pr-policy.result != 'skipped'");
});
it('skips E2E jobs on draft PRs unless overridden by force labels', () => {
assert.match(
ci.jobs['install-and-build'].outputs.run_e2e,
/!github\.event\.pull_request\.draft/,
);
assert.match(ci.jobs['install-and-build'].outputs.run_e2e, /'force-e2e'/);
assert.match(ci.jobs['prepare-docker'].if, /!github\.event\.pull_request\.draft/);
assert.match(ci.jobs['e2e-engine'].if, /!github\.event\.pull_request\.draft/);
assert.match(ci.jobs['e2e-engine'].if, /'force-engine-e2e'/);
assert.match(ci.jobs['e2e-performance'].if, /!github\.event\.pull_request\.draft/);
assert.match(ci.jobs['e2e-performance'].if, /'run-perf-tests'/);
});
it('grants issues: read to install-and-build for ready_for_review event lookups', () => {
assert.equal(ci.jobs['install-and-build'].permissions?.issues, 'read');
});
});
describe('release SBOM validation in PR CI', () => {
const workflow = workflowFile('ci-pull-requests.yml');
const filterStep = stepNamed(workflow, 'install-and-build', 'Check for relevant changes');
+1 -1
View File
@@ -1 +1 @@
{"sha":"48a8cc1b17fd8c2c6f7349089c430b830d2e9500","specs":["tests/e2e/instance-ai/instance-ai-artifacts.spec.ts","tests/e2e/instance-ai/instance-ai-confirmations.spec.ts","tests/e2e/instance-ai/instance-ai-remediation-guard.spec.ts","tests/e2e/instance-ai/instance-ai-workflow-execution.spec.ts","tests/e2e/instance-ai/instance-ai-workflow-preview.spec.ts","tests/e2e/instance-ai/instance-ai-attachments.spec.ts","tests/e2e/instance-ai/instance-ai-chat-basics.spec.ts","tests/e2e/instance-ai/instance-ai-mentions.spec.ts","tests/e2e/instance-ai/instance-ai-out-of-credits.spec.ts","tests/e2e/instance-ai/instance-ai-oversized-attachments.spec.ts","tests/e2e/instance-ai/instance-ai-sidebar.spec.ts","tests/e2e/instance-ai/thread-launcher.spec.ts","tests/e2e/agents/agent-builder-chat-modes.spec.ts","tests/e2e/agents/agent-builder-write-lock.spec.ts","tests/e2e/agents/agent-data-table-tool.spec.ts","tests/e2e/agents/agent-test-layout.spec.ts","tests/e2e/agents/background-workflow-stop.spec.ts","tests/e2e/instance-ai/instance-ai-agent-test-layout.spec.ts","<boot>","tests/e2e/scheduling/schedule-trigger-restart.spec.ts","tests/e2e/auth/authenticated.spec.ts","tests/e2e/instance-ai/instance-ai-background-lifecycle.spec.ts","tests/e2e/instance-ai/instance-ai-connector-menu.spec.ts","tests/e2e/instance-ai/instance-ai-multimain.spec.ts","tests/e2e/instance-ai/instance-ai-onboarding.spec.ts","tests/e2e/instance-ai/instance-ai-workflow-setup.spec.ts","tests/e2e/instance-ai/open-by-default.spec.ts","tests/e2e/chat-hub/chat-hub-attachment.spec.ts","tests/e2e/chat-hub/chat-hub-basic.spec.ts","tests/e2e/chat-hub/chat-hub-chat-user.spec.ts","tests/e2e/chat-hub/chat-hub-personal-agent.spec.ts","tests/e2e/chat-hub/chat-hub-settings.spec.ts","tests/e2e/workflows/editor/execution/logs.spec.ts","tests/e2e/ai/ai-2505-pdf-embed.spec.ts","tests/e2e/ai/langchain-vectorstores.spec.ts","tests/e2e/ai/langchain-agents.spec.ts","tests/e2e/ai/langchain-chains.spec.ts","tests/e2e/chat-hub/chat-hub-workflow-agent.spec.ts","tests/e2e/inbound-auth/instance-mcp.spec.ts","tests/e2e/mcp/mcp-oauth.spec.ts","tests/e2e/mcp/mcp-service.spec.ts","tests/e2e/nodes/mcp-trigger.spec.ts","tests/e2e/chat-hub/chat-hub-tools.spec.ts","tests/e2e/dynamic-credentials/mcp-trigger-credential-gate.spec.ts","tests/e2e/inbound-auth/mcp-trigger.spec.ts","tests/e2e/workflows/editor/ndv/ndv-floating-nodes.spec.ts","tests/e2e/api/publish-unreachable-node.spec.ts","tests/e2e/credentials/crud.spec.ts","tests/e2e/mcp-registry/mcp-registry.spec.ts","tests/e2e/regression/AI-1401-sub-nodes-input-panel.spec.ts","tests/e2e/regression/ado-5599-from-ai-button-alignment.spec.ts","tests/e2e/workflows/editor/ndv/ndv-parameters.spec.ts","tests/e2e/ai/workflow-builder.spec.ts","tests/e2e/ai/workflow-builder-smoke.spec.ts","tests/e2e/agents/agent-chat-description.spec.ts","tests/e2e/agents/agent-sessions.spec.ts","tests/e2e/ai/assistant-basic.spec.ts","tests/e2e/ai/assistant-code-help.spec.ts","tests/e2e/ai/assistant-credential-help.spec.ts","tests/e2e/ai/assistant-support-chat.spec.ts","tests/e2e/ai/builder-setup-wizard.spec.ts","tests/e2e/ai/chat-session.spec.ts","tests/e2e/ai/eval-collections-compare.spec.ts","tests/e2e/api/wait-form-resume.spec.ts","tests/e2e/api/waiting-endpoint-security.spec.ts","tests/e2e/app-config/demo-reimport.spec.ts","tests/e2e/app-config/demo.spec.ts","tests/e2e/app-config/embedded-settings.spec.ts","tests/e2e/app-config/security-notifications.spec.ts","tests/e2e/app-config/versions.spec.ts","tests/e2e/auth/admin-smoke.spec.ts","tests/e2e/auth/oidc.spec.ts","tests/e2e/auth/signin.spec.ts","tests/e2e/building-blocks/canvas-actions.spec.ts","tests/e2e/building-blocks/credential-mismatch.spec.ts","tests/e2e/building-blocks/credentials.spec.ts","tests/e2e/building-blocks/node-details-configuration.spec.ts","tests/e2e/building-blocks/user-service.spec.ts","tests/e2e/building-blocks/workflow-entry-points.spec.ts","tests/e2e/capabilities/proxy-server.spec.ts","tests/e2e/capabilities/task-runner.spec.ts","tests/e2e/cloud/cloud.spec.ts","tests/e2e/context/skill-diagrams-enforced-policy.spec.ts","tests/e2e/context/skill-diagrams.spec.ts","tests/e2e/context/skill-source-updates.spec.ts","tests/e2e/credentials/global.spec.ts","tests/e2e/credentials/oauth.spec.ts","tests/e2e/data-tables/details.spec.ts","tests/e2e/data-tables/tables.spec.ts","tests/e2e/dynamic-credentials/form-trigger-submit-gate-client.spec.ts","tests/e2e/mcp/mcp-copy-button-hover.spec.ts","tests/e2e/node-creator/actions.spec.ts","tests/e2e/node-creator/navigation.spec.ts","tests/e2e/node-creator/special-nodes.spec.ts","tests/e2e/node-creator/vector-stores.spec.ts","tests/e2e/node-creator/workflows.spec.ts","tests/e2e/nodes/community-nodes.spec.ts","tests/e2e/nodes/deprecated-nodes.spec.ts","tests/e2e/nodes/email-send-node.spec.ts","tests/e2e/nodes/form-trigger-node.spec.ts","tests/e2e/nodes/http-request-node.spec.ts","tests/e2e/nodes/if-node.spec.ts","tests/e2e/nodes/kafka-nodes.spec.ts","tests/e2e/nodes/pdLine truncated
{"sha":"061dbc1b08709f5a8f29165e4e5c6ce58eda3131","specs":["tests/e2e/instance-ai/instance-ai-artifacts.spec.ts","tests/e2e/instance-ai/instance-ai-confirmations.spec.ts","tests/e2e/instance-ai/instance-ai-remediation-guard.spec.ts","tests/e2e/instance-ai/instance-ai-workflow-execution.spec.ts","tests/e2e/instance-ai/instance-ai-workflow-preview.spec.ts","tests/e2e/instance-ai/instance-ai-attachments.spec.ts","tests/e2e/instance-ai/instance-ai-chat-basics.spec.ts","tests/e2e/instance-ai/instance-ai-mentions.spec.ts","tests/e2e/instance-ai/instance-ai-out-of-credits.spec.ts","tests/e2e/instance-ai/instance-ai-oversized-attachments.spec.ts","tests/e2e/instance-ai/instance-ai-sidebar.spec.ts","tests/e2e/instance-ai/thread-launcher.spec.ts","tests/e2e/agents/agent-builder-chat-modes.spec.ts","tests/e2e/agents/agent-builder-write-lock.spec.ts","tests/e2e/agents/agent-data-table-tool.spec.ts","tests/e2e/agents/agent-test-layout.spec.ts","tests/e2e/agents/background-workflow-stop.spec.ts","tests/e2e/instance-ai/instance-ai-agent-test-layout.spec.ts","<boot>","tests/e2e/scheduling/schedule-trigger-restart.spec.ts","tests/e2e/auth/authenticated.spec.ts","tests/e2e/instance-ai/instance-ai-background-lifecycle.spec.ts","tests/e2e/instance-ai/instance-ai-connector-menu.spec.ts","tests/e2e/instance-ai/instance-ai-multimain.spec.ts","tests/e2e/instance-ai/instance-ai-onboarding.spec.ts","tests/e2e/instance-ai/instance-ai-workflow-setup.spec.ts","tests/e2e/instance-ai/open-by-default.spec.ts","tests/e2e/chat-hub/chat-hub-attachment.spec.ts","tests/e2e/chat-hub/chat-hub-basic.spec.ts","tests/e2e/chat-hub/chat-hub-chat-user.spec.ts","tests/e2e/chat-hub/chat-hub-personal-agent.spec.ts","tests/e2e/chat-hub/chat-hub-settings.spec.ts","tests/e2e/workflows/editor/execution/logs.spec.ts","tests/e2e/ai/ai-2505-pdf-embed.spec.ts","tests/e2e/ai/langchain-vectorstores.spec.ts","tests/e2e/ai/langchain-agents.spec.ts","tests/e2e/ai/langchain-chains.spec.ts","tests/e2e/chat-hub/chat-hub-workflow-agent.spec.ts","tests/e2e/inbound-auth/instance-mcp.spec.ts","tests/e2e/mcp/mcp-oauth.spec.ts","tests/e2e/mcp/mcp-service.spec.ts","tests/e2e/nodes/mcp-trigger.spec.ts","tests/e2e/chat-hub/chat-hub-tools.spec.ts","tests/e2e/dynamic-credentials/mcp-trigger-credential-gate.spec.ts","tests/e2e/inbound-auth/mcp-trigger.spec.ts","tests/e2e/workflows/editor/ndv/ndv-floating-nodes.spec.ts","tests/e2e/api/publish-unreachable-node.spec.ts","tests/e2e/credentials/crud.spec.ts","tests/e2e/regression/AI-1401-sub-nodes-input-panel.spec.ts","tests/e2e/regression/ado-5599-from-ai-button-alignment.spec.ts","tests/e2e/workflows/editor/canvas/actions.spec.ts","tests/e2e/workflows/editor/ndv/ndv-parameters.spec.ts","tests/e2e/ai/workflow-builder.spec.ts","tests/e2e/ai/workflow-builder-smoke.spec.ts","tests/e2e/agents/agent-chat-description.spec.ts","tests/e2e/agents/agent-sessions.spec.ts","tests/e2e/ai/assistant-basic.spec.ts","tests/e2e/ai/assistant-code-help.spec.ts","tests/e2e/ai/assistant-credential-help.spec.ts","tests/e2e/ai/assistant-support-chat.spec.ts","tests/e2e/ai/builder-setup-wizard.spec.ts","tests/e2e/ai/chat-session.spec.ts","tests/e2e/ai/eval-collections-compare.spec.ts","tests/e2e/api/wait-form-resume.spec.ts","tests/e2e/api/waiting-endpoint-security.spec.ts","tests/e2e/app-config/demo-reimport.spec.ts","tests/e2e/app-config/demo.spec.ts","tests/e2e/app-config/embedded-settings.spec.ts","tests/e2e/app-config/security-notifications.spec.ts","tests/e2e/app-config/versions.spec.ts","tests/e2e/auth/admin-smoke.spec.ts","tests/e2e/auth/oidc.spec.ts","tests/e2e/auth/signin.spec.ts","tests/e2e/building-blocks/canvas-actions.spec.ts","tests/e2e/building-blocks/credential-mismatch.spec.ts","tests/e2e/building-blocks/credentials.spec.ts","tests/e2e/building-blocks/node-details-configuration.spec.ts","tests/e2e/building-blocks/user-service.spec.ts","tests/e2e/building-blocks/workflow-entry-points.spec.ts","tests/e2e/capabilities/proxy-server.spec.ts","tests/e2e/capabilities/task-runner.spec.ts","tests/e2e/cloud/cloud.spec.ts","tests/e2e/context/skill-diagrams-enforced-policy.spec.ts","tests/e2e/context/skill-diagrams.spec.ts","tests/e2e/context/skill-source-updates.spec.ts","tests/e2e/credentials/global.spec.ts","tests/e2e/credentials/oauth.spec.ts","tests/e2e/data-tables/details.spec.ts","tests/e2e/data-tables/tables.spec.ts","tests/e2e/dynamic-credentials/form-trigger-submit-gate-client.spec.ts","tests/e2e/mcp-registry/mcp-registry.spec.ts","tests/e2e/mcp/mcp-copy-button-hover.spec.ts","tests/e2e/node-creator/actions.spec.ts","tests/e2e/node-creator/navigation.spec.ts","tests/e2e/node-creator/special-nodes.spec.ts","tests/e2e/node-creator/vector-stores.spec.ts","tests/e2e/node-creator/workflows.spec.ts","tests/e2e/nodes/community-nodes.spec.ts","tests/e2e/nodes/deprecated-nodes.spec.ts","tests/e2e/nodes/email-send-node.spec.ts","tests/e2e/nodes/form-trigger-node.spec.ts","tests/e2e/nodes/http-request-node.spec.ts","tests/e2e/nodes/if-node.spec.ts","testLine truncated
File diff suppressed because it is too large. Load diff
+36 -19
View File
@@ -2,6 +2,7 @@ name: 'CI: Pull Requests (Build, Test, Lint)'
on:
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
merge_group:
concurrency:
@@ -9,18 +10,32 @@ concurrency:
cancel-in-progress: true
jobs:
# Skip all CI on upper-stack draft PRs (draft targeting a non-trunk/non-release branch)
# unless opted in with `run-ci`. Runs automatically when promoted to master or marked ready.
pr-policy:
if: >-
!(github.event_name == 'pull_request' &&
github.event.pull_request.draft == true &&
!contains(github.event.pull_request.labels.*.name, 'run-ci') &&
github.event.pull_request.base.ref != 'master' &&
github.event.pull_request.base.ref != '3.x' &&
github.event.pull_request.base.ref != '1.x' &&
github.event.pull_request.base.ref != '2.x' &&
!startsWith(github.event.pull_request.base.ref, 'release/') &&
!startsWith(github.event.pull_request.base.ref, 'release-candidate/') &&
!startsWith(github.event.pull_request.base.ref, 'bundle/'))
uses: ./.github/workflows/ci-pr-policy-reusable.yml
install-and-build:
name: Install & Build
needs: pr-policy
if: needs.pr-policy.outputs.skip-ci != 'true'
if: needs.pr-policy.result == 'success' && needs.pr-policy.outputs.skip-ci != 'true'
runs-on: ${{ vars.RUNNER_PROVIDER == 'github' && 'ubuntu-latest' || 'blacksmith-8vcpu-bmi-n8n' }}
# find-last-green-commit.mjs reads the workflow runs and the PR commits.
# find-last-green-commit.mjs reads the workflow runs, PR commits, and ready_for_review events.
permissions:
contents: read
actions: read
issues: read
pull-requests: read
env:
NODE_OPTIONS: '--max-old-space-size=7168'
@@ -43,11 +58,13 @@ jobs:
e2e_performance: ${{ fromJSON(steps.ci-filter.outputs.results)['e2e-performance'] == true }}
engine_e2e: ${{ fromJSON(steps.ci-filter.outputs.results)['engine-e2e'] == true }}
# The main E2E suite runs. Read by e2e-matrix and e2e.
# Skip E2E on draft PRs unless the PR has the `force-e2e` label.
run_e2e: >-
${{ github.repository == 'n8n-io/n8n' && github.event_name != 'merge_group' &&
(fromJSON(steps.ci-filter.outputs.results).runtime == true
|| fromJSON(steps.ci-filter.outputs.results).e2e == true
|| contains(github.event.pull_request.labels.*.name, 'force-e2e')) }}
(contains(github.event.pull_request.labels.*.name, 'force-e2e')
|| (!github.event.pull_request.draft &&
(fromJSON(steps.ci-filter.outputs.results).runtime == true
|| fromJSON(steps.ci-filter.outputs.results).e2e == true))) }}
instance_ai_workflow_eval: ${{ fromJSON(steps.ci-filter.outputs.results)['instance-ai-workflow-eval'] == true }}
commit_sha: ${{ steps.commit-sha.outputs.sha }}
affected_base: ${{ steps.affected-base.outputs.sha }}
@@ -207,7 +224,7 @@ jobs:
# data plane, and the executions code merges v1 and v2 rows. A path
# this list misses skips `e2e-engine`, and `required-checks` counts
# a skipped job as a pass, so the gap would be silent.
# Use force-engine-e2e when changing the engine job in this workflow.
# Use force-engine-e2e when changing Playwright tests or the engine job in this workflow.
engine-e2e:
packages/@n8n/engine/**
packages/@n8n/node-engine-compatibility/**
@@ -221,7 +238,6 @@ jobs:
packages/cli/src/workflows/triggers/**
packages/cli/src/workflow-runner.ts
packages/quality/environments/containers/**
packages/quality/testing/playwright/**
instance-ai-workflow-eval:
packages/@n8n/instance-ai/src/**
packages/@n8n/instance-ai/evaluations/**
@@ -345,7 +361,7 @@ jobs:
format-check:
name: Format check
needs: pr-policy
if: needs.pr-policy.outputs.skip-ci != 'true'
if: needs.pr-policy.result == 'success' && needs.pr-policy.outputs.skip-ci != 'true'
runs-on: ${{ vars.RUNNER_PROVIDER == 'github' && 'ubuntu-latest' || 'blacksmith-2vcpu-bmi-n8n' }}
permissions:
contents: read
@@ -457,13 +473,14 @@ jobs:
if: >-
github.repository == 'n8n-io/n8n' &&
github.event_name != 'merge_group' &&
(needs.install-and-build.outputs.runtime == 'true'
|| needs.install-and-build.outputs.e2e == 'true'
|| needs.install-and-build.outputs.e2e_performance == 'true'
|| needs.install-and-build.outputs.engine_e2e == 'true'
|| contains(github.event.pull_request.labels.*.name, 'force-e2e')
(contains(github.event.pull_request.labels.*.name, 'force-e2e')
|| contains(github.event.pull_request.labels.*.name, 'run-perf-tests')
|| contains(github.event.pull_request.labels.*.name, 'force-engine-e2e'))
|| contains(github.event.pull_request.labels.*.name, 'force-engine-e2e')
|| (!github.event.pull_request.draft &&
(needs.install-and-build.outputs.runtime == 'true'
|| needs.install-and-build.outputs.e2e == 'true'
|| needs.install-and-build.outputs.e2e_performance == 'true'
|| needs.install-and-build.outputs.engine_e2e == 'true')))
uses: ./.github/workflows/prepare-docker-reusable.yml
with:
branch: ${{ needs.install-and-build.outputs.commit_sha }}
@@ -557,8 +574,8 @@ jobs:
needs: [install-and-build, prepare-docker]
if: >-
needs.prepare-docker.result == 'success' &&
(needs.install-and-build.outputs.engine_e2e == 'true'
|| contains(github.event.pull_request.labels.*.name, 'force-engine-e2e')) &&
(contains(github.event.pull_request.labels.*.name, 'force-engine-e2e')
|| (!github.event.pull_request.draft && needs.install-and-build.outputs.engine_e2e == 'true')) &&
github.event.pull_request.head.repo.fork != true &&
github.event_name != 'merge_group'
permissions:
@@ -619,8 +636,8 @@ jobs:
# would otherwise miss).
if: >-
needs.prepare-docker.result == 'success' &&
(needs.install-and-build.outputs.e2e_performance == 'true' ||
contains(github.event.pull_request.labels.*.name, 'run-perf-tests')) &&
(contains(github.event.pull_request.labels.*.name, 'run-perf-tests') ||
(!github.event.pull_request.draft && needs.install-and-build.outputs.e2e_performance == 'true')) &&
github.event.pull_request.head.repo.fork != true
permissions:
contents: read
@@ -698,7 +715,7 @@ jobs:
workflow-scripts,
validate-sbom,
]
if: always()
if: always() && needs.pr-policy.result != 'skipped'
runs-on: ubuntu-slim
steps:
- name: Checkout CI filter
+3
View File
@@ -94,6 +94,9 @@ jobs:
- name: Setup Environment
uses: ./.github/actions/setup-nodejs
with:
# Container runs test the prebuilt Docker image and only need host Playwright deps.
build-command: ${{ inputs.test-mode == 'docker-artifact' && 'pnpm --filter=n8n-playwright build:host-deps' || 'pnpm build' }}
env:
QA_METRICS_WEBHOOK_URL: ${{ secrets.QA_METRICS_WEBHOOK_URL }}
QA_METRICS_WEBHOOK_USER: ${{ secrets.QA_METRICS_WEBHOOK_USER }}
+635
View File
@@ -0,0 +1,635 @@
# Runs the external-URL Playwright smoke suite (tests/smoke/) against published
# nightly and release images for master and 3.x and reports results to Currents
# project n8n-nightly-compatibility (tlfUav).
#
# Images are pinned by digest from GHCR before profile jobs start. Nothing is
# built from product source here, and specs run with 0 retries against the
# booted profile over HTTP.
name: 'Test: Release smoke'
on:
workflow_run: # zizmor: ignore[dangerous-triggers] nothing from the triggering run is checked out or reaches a shell
workflows:
- 'Docker: Build and Push'
- 'Build: v3 Nightly Docker Images'
types: [completed]
workflow_dispatch:
inputs:
channel:
description: 'Release channel to test'
required: false
type: choice
options:
- master
- 3.x
default: master
workflow_call:
inputs:
channel:
description: 'Release channel or track label (for example master, 3.x, or release track)'
required: false
type: string
default: master
n8n_image:
description: 'Optional n8n image reference (repo@sha256:... or repo:tag); overrides channel default'
required: false
type: string
default: ''
n8n_pc_image:
description: 'Optional pointer-compressed n8n image reference (repo@sha256:... or repo:tag)'
required: false
type: string
default: ''
runners_image:
description: 'Optional runners image reference (repo@sha256:... or repo:tag); overrides channel default'
required: false
type: string
default: ''
runners_distroless_image:
description: 'Optional distroless runners image reference (repo@sha256:... or repo:tag)'
required: false
type: string
default: ''
permissions:
contents: read
packages: read
concurrency:
group: >-
release-smoke-${{
github.event_name == 'workflow_run'
&& contains(github.workflow_ref, '/.github/workflows/test-release-smoke.yml@')
&& inputs.channel == ''
&& (
github.repository == 'n8n-io/n8n'
&& github.event.workflow_run.conclusion == 'success'
&& github.event.workflow_run.head_branch == 'master'
&& (
(github.event.workflow_run.name == 'Docker: Build and Push'
&& github.event.workflow_run.event == 'schedule'
&& 'master')
|| (github.event.workflow_run.name == 'Build: v3 Nightly Docker Images'
&& (github.event.workflow_run.event == 'schedule'
|| github.event.workflow_run.event == 'workflow_dispatch')
&& '3.x')
)
|| format('skip-{0}', github.run_id)
)
|| (inputs.channel || 'master')
}}
cancel-in-progress: false
jobs:
resolve:
name: Resolve published images
# Skip fork repos, failed builds, and ad-hoc branch dispatches of Docker: Build and Push.
# For workflow_call, github.event_name matches the caller's trigger (which may itself be
# workflow_run), so only direct workflow_run triggers of this file go through the nightly filter.
if: |
github.repository == 'n8n-io/n8n' &&
(!(github.event_name == 'workflow_run' &&
contains(github.workflow_ref, '/.github/workflows/test-release-smoke.yml@') &&
inputs.channel == '' &&
inputs.n8n_image == '' &&
inputs.n8n_pc_image == '' &&
inputs.runners_image == '' &&
inputs.runners_distroless_image == '') ||
(github.event.workflow_run.conclusion == 'success' &&
github.event.workflow_run.head_branch == 'master' &&
((github.event.workflow_run.name == 'Docker: Build and Push' &&
github.event.workflow_run.event == 'schedule') ||
(github.event.workflow_run.name == 'Build: v3 Nightly Docker Images' &&
(github.event.workflow_run.event == 'schedule' ||
github.event.workflow_run.event == 'workflow_dispatch')))))
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
packages: read
outputs:
channel: ${{ steps.context.outputs.channel }}
channel_slug: ${{ steps.context.outputs.channel_slug }}
n8n: ${{ steps.pin.outputs.n8n }}
n8n_pc: ${{ steps.pin.outputs.n8n_pc }}
runners: ${{ steps.pin.outputs.runners }}
runners_distroless: ${{ steps.pin.outputs.runners_distroless }}
steps:
- name: Checkout CI helpers
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
sparse-checkout: .github
persist-credentials: false
- name: Determine channel and image references
id: context
env:
EVENT_NAME: ${{ github.event_name }}
WORKFLOW_REF: ${{ github.workflow_ref }}
INPUT_CHANNEL: ${{ inputs.channel }}
INPUT_N8N_IMAGE: ${{ inputs.n8n_image }}
INPUT_N8N_PC_IMAGE: ${{ inputs.n8n_pc_image }}
INPUT_RUNNERS_IMAGE: ${{ inputs.runners_image }}
INPUT_RUNNERS_DISTROLESS_IMAGE: ${{ inputs.runners_distroless_image }}
TRIGGER_WORKFLOW: ${{ github.event.workflow_run.name }}
run: |
set -euo pipefail
IS_DIRECT_WORKFLOW_RUN=false
if [ "$EVENT_NAME" = "workflow_run" ] && \
[[ "$WORKFLOW_REF" == *"/.github/workflows/test-release-smoke.yml@"* ]] && \
[ -z "$INPUT_CHANNEL" ] && \
[ -z "$INPUT_N8N_IMAGE" ] && \
[ -z "$INPUT_N8N_PC_IMAGE" ] && \
[ -z "$INPUT_RUNNERS_IMAGE" ] && \
[ -z "$INPUT_RUNNERS_DISTROLESS_IMAGE" ]; then
IS_DIRECT_WORKFLOW_RUN=true
fi
if [ "$IS_DIRECT_WORKFLOW_RUN" = "true" ]; then
case "$TRIGGER_WORKFLOW" in
'Build: v3 Nightly Docker Images') CHANNEL="3.x" ;;
'Docker: Build and Push') CHANNEL="master" ;;
*)
echo "::error::Unexpected workflow_run trigger workflow '${TRIGGER_WORKFLOW}'"
exit 1
;;
esac
else
CHANNEL="${INPUT_CHANNEL:-master}"
fi
if [[ "$CHANNEL" == *$'\n'* || "$CHANNEL" == *$'\r'* || ! "$CHANNEL" =~ ^[A-Za-z0-9._/-]+$ ]]; then
echo "::error::Invalid channel '${CHANNEL}'"
exit 1
fi
IMAGE_NAME_RE='([A-Za-z0-9][A-Za-z0-9._-]*(:[0-9]+)?/)?[A-Za-z0-9][A-Za-z0-9._-]*(/[A-Za-z0-9][A-Za-z0-9._-]*)*'
IMAGE_TAG_RE=':[A-Za-z0-9_][A-Za-z0-9._-]{0,127}'
IMAGE_DIGEST_RE='@sha256:[a-f0-9]{64}'
IMAGE_REF_RE="^${IMAGE_NAME_RE}(${IMAGE_TAG_RE})?(${IMAGE_DIGEST_RE})?$"
validate_image_ref() {
local name="$1" ref="$2"
if [ -z "$ref" ]; then
return 0
fi
if [[ "$ref" == *$'\n'* || "$ref" == *$'\r'* || ! "$ref" =~ $IMAGE_REF_RE ]]; then
echo "::error::Invalid Docker image reference for ${name}: '${ref}'"
exit 1
fi
}
validate_image_ref "n8n_image" "$INPUT_N8N_IMAGE"
validate_image_ref "n8n_pc_image" "$INPUT_N8N_PC_IMAGE"
validate_image_ref "runners_image" "$INPUT_RUNNERS_IMAGE"
validate_image_ref "runners_distroless_image" "$INPUT_RUNNERS_DISTROLESS_IMAGE"
DEFAULT_TAG=""
case "$CHANNEL" in
master) DEFAULT_TAG="nightly" ;;
3.x) DEFAULT_TAG="v3-nightly" ;;
esac
resolve_ref() {
local override="$1" fallback_repo="$2" fallback_suffix="$3"
if [ -n "$override" ]; then
printf '%s\n' "$override"
elif [ -n "$DEFAULT_TAG" ]; then
printf '%s:%s%s\n' "$fallback_repo" "$DEFAULT_TAG" "$fallback_suffix"
fi
}
N8N_REF="$(resolve_ref "$INPUT_N8N_IMAGE" "ghcr.io/n8n-io/n8n" "")"
RUNNERS_REF="$(resolve_ref "$INPUT_RUNNERS_IMAGE" "ghcr.io/n8n-io/runners" "")"
# Only resolve -pc and -distroless when explicitly passed via workflow_call;
# default resolution for those tags belongs with the cloud-runtime profile job.
N8N_PC_REF="$INPUT_N8N_PC_IMAGE"
RUNNERS_DISTROLESS_REF="$INPUT_RUNNERS_DISTROLESS_IMAGE"
if [ -z "$N8N_REF" ] || [ -z "$RUNNERS_REF" ]; then
echo "::error::Unsupported channel '${CHANNEL}' without explicit n8n_image and runners_image inputs"
exit 1
fi
emit_ref() {
local key="$1" ref="$2"
if [[ "$ref" == *@* ]]; then
echo "${key}_pinned=${ref}" >> "$GITHUB_OUTPUT"
elif [ -n "$ref" ]; then
echo "${key}_tag=${ref}" >> "$GITHUB_OUTPUT"
fi
}
CHANNEL_SLUG="$(printf '%s' "$CHANNEL" | tr -c 'A-Za-z0-9._-' '-' | sed 's/^-*//; s/-*$//')"
echo "channel=${CHANNEL}" >> "$GITHUB_OUTPUT"
echo "channel_slug=${CHANNEL_SLUG:-unknown}" >> "$GITHUB_OUTPUT"
emit_ref "n8n" "$N8N_REF"
emit_ref "n8n_pc" "$N8N_PC_REF"
emit_ref "runners" "$RUNNERS_REF"
emit_ref "runners_distroless" "$RUNNERS_DISTROLESS_REF"
- name: Login to GHCR
if: >-
steps.context.outputs.n8n_tag != '' ||
steps.context.outputs.n8n_pc_tag != '' ||
steps.context.outputs.runners_tag != '' ||
steps.context.outputs.runners_distroless_tag != ''
uses: ./.github/actions/docker-registry-login
with:
login-ghcr: true
- name: Resolve image digests
id: digests
if: >-
steps.context.outputs.n8n_tag != '' ||
steps.context.outputs.n8n_pc_tag != '' ||
steps.context.outputs.runners_tag != '' ||
steps.context.outputs.runners_distroless_tag != ''
env:
N8N_TAG: ${{ steps.context.outputs.n8n_tag }}
N8N_PC_TAG: ${{ steps.context.outputs.n8n_pc_tag }}
RUNNERS_TAG: ${{ steps.context.outputs.runners_tag }}
DISTROLESS_TAG: ${{ steps.context.outputs.runners_distroless_tag }}
run: node .github/scripts/docker/get-manifest-digests.mjs
- name: Pin image references by digest
id: pin
env:
CHANNEL: ${{ steps.context.outputs.channel }}
N8N_PINNED: ${{ steps.context.outputs.n8n_pinned }}
N8N_IMAGE: ${{ steps.digests.outputs.n8n_image }}
N8N_DIGEST: ${{ steps.digests.outputs.n8n_digest }}
N8N_PC_PINNED: ${{ steps.context.outputs.n8n_pc_pinned }}
N8N_PC_IMAGE: ${{ steps.digests.outputs.n8n_pc_image }}
N8N_PC_DIGEST: ${{ steps.digests.outputs.n8n_pc_digest }}
RUNNERS_PINNED: ${{ steps.context.outputs.runners_pinned }}
RUNNERS_IMAGE: ${{ steps.digests.outputs.runners_image }}
RUNNERS_DIGEST: ${{ steps.digests.outputs.runners_digest }}
RUNNERS_DISTROLESS_PINNED: ${{ steps.context.outputs.runners_distroless_pinned }}
RUNNERS_DISTROLESS_IMAGE: ${{ steps.digests.outputs.runners_distroless_image }}
RUNNERS_DISTROLESS_DIGEST: ${{ steps.digests.outputs.runners_distroless_digest }}
run: |
set -euo pipefail
IMAGE_NAME_RE='([A-Za-z0-9][A-Za-z0-9._-]*(:[0-9]+)?/)?[A-Za-z0-9][A-Za-z0-9._-]*(/[A-Za-z0-9][A-Za-z0-9._-]*)*'
IMAGE_TAG_RE=':[A-Za-z0-9_][A-Za-z0-9._-]{0,127}'
PINNED_REF_RE="^${IMAGE_NAME_RE}(${IMAGE_TAG_RE})?@sha256:[a-f0-9]{64}$"
pin() {
local key="$1" pinned="$2" image="$3" digest="$4" required="$5"
local ref=""
if [ -n "$pinned" ]; then
ref="$pinned"
if [[ "$ref" == *$'\n'* || "$ref" == *$'\r'* || ! "$ref" =~ $PINNED_REF_RE ]]; then
echo "::error::Invalid pinned image reference for ${key}: '${ref}'"
exit 1
fi
elif [ -n "$image" ] || [ -n "$digest" ] || [ "$required" = "true" ]; then
if [[ "$image" == *$'\n'* || "$image" == *$'\r'* || ! "$image" =~ ^${IMAGE_NAME_RE}$ || ! "$digest" =~ ^sha256:[a-f0-9]{64}$ ]]; then
echo "::error::Failed to resolve valid digest for ${key}: image='${image}' digest='${digest}'"
exit 1
fi
ref="${image}@${digest}"
else
return 0
fi
echo "${key}=${ref}" >> "$GITHUB_OUTPUT"
echo "- \`${key}\`: \`${ref}\`" >> "$GITHUB_STEP_SUMMARY"
}
echo "### Resolved smoke images (${CHANNEL})" >> "$GITHUB_STEP_SUMMARY"
pin "n8n" "$N8N_PINNED" "$N8N_IMAGE" "$N8N_DIGEST" "true"
pin "n8n_pc" "$N8N_PC_PINNED" "$N8N_PC_IMAGE" "$N8N_PC_DIGEST" "false"
pin "runners" "$RUNNERS_PINNED" "$RUNNERS_IMAGE" "$RUNNERS_DIGEST" "true"
pin "runners_distroless" "$RUNNERS_DISTROLESS_PINNED" "$RUNNERS_DISTROLESS_IMAGE" "$RUNNERS_DISTROLESS_DIGEST" "false"
compose:
name: smoke · ${{ needs.resolve.outputs.channel }} · compose
needs: resolve
runs-on: ${{ vars.RUNNER_PROVIDER == 'github' && 'ubuntu-latest' || 'blacksmith-4vcpu-bmi-n8n' }}
timeout-minutes: 25
permissions:
contents: read
packages: read
id-token: write
env:
NODE_OPTIONS: '--max-old-space-size=6144'
COMPOSE_PROJECT_NAME: 'release-smoke-compose'
SMOKE_N8N_IMAGE: ${{ needs.resolve.outputs.n8n }}
SMOKE_RUNNERS_IMAGE: ${{ needs.resolve.outputs.runners }}
SMOKE_CHANNEL: ${{ needs.resolve.outputs.channel }}
SMOKE_PROFILE: 'compose'
# Keep http://localhost:5678 (not 127.0.0.1) and leave N8N_SECURE_COOKIE at the
# get-n8n.sh default (true) to test the real one-line installer defaults: Chromium
# and Playwright's APIRequestContext both treat localhost as a secure context.
# Leave SMOKE_EXTERNAL_URL unset so spec 03 uses the deterministic local echo
# webhook (N8N_SSRF_PROTECTION_ENABLED defaults to false on master and 3.x).
N8N_BASE_URL: 'http://localhost:5678'
CURRENTS_PROJECT_ID: 'tlfUav'
CURRENTS_CI_BUILD_ID: ${{ github.repository }}-${{ github.run_id }}-${{ github.run_attempt }}
steps:
- name: Checkout
uses: useblacksmith/checkout@bcec731f1eb1367240608d1c889a75b96db6ec53 # v1.5.0
with:
fetch-depth: 1
persist-credentials: false
- name: Setup Environment
uses: ./.github/actions/setup-nodejs
with:
build-command: pnpm turbo run build --filter=n8n-workflow...
- name: Install Playwright Chromium
run: |
set -euo pipefail
PREINSTALLED_VERSION="$(cat /opt/playwright-browsers/.playwright-version 2>/dev/null || true)"
EXPECTED_VERSION="$(cat packages/quality/testing/playwright/.playwright-version)"
if [ -n "$PREINSTALLED_VERSION" ] && [ "$PREINSTALLED_VERSION" = "$EXPECTED_VERSION" ]; then
echo "PLAYWRIGHT_BROWSERS_PATH=/opt/playwright-browsers" >> "$GITHUB_ENV"
else
echo "PLAYWRIGHT_BROWSERS_PATH=$GITHUB_WORKSPACE/packages/quality/testing/playwright/.playwright-browsers" >> "$GITHUB_ENV"
pnpm turbo run install-browsers --filter=n8n-playwright
fi
- name: Authenticate with Currents
if: vars.CURRENTS_OIDC_POLICY_ID != ''
env:
CURRENTS_OIDC_POLICY_ID: ${{ vars.CURRENTS_OIDC_POLICY_ID }}
run: |
KEY=$(pnpm --silent --filter=n8n-playwright exec currents ci auth get-record-key --oidc-provider github-actions)
echo "CURRENTS_RECORD_KEY=$KEY" >> "$GITHUB_ENV"
- name: Login to GHCR
uses: ./.github/actions/docker-registry-login
with:
login-ghcr: true
# Fetch 3.x's own get-n8n.sh and get-n8n-compose.yml while keeping the
# smoke suite itself on the workflow's checked-out test ref.
- name: Checkout 3.x Compose profile
if: needs.resolve.outputs.channel == '3.x'
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: '3.x'
path: .smoke-compose-source
sparse-checkout: |
docker/get-n8n.sh
docker/get-n8n-compose.yml
sparse-checkout-cone-mode: false
fetch-depth: 1
persist-credentials: false
- name: Prepare Compose profile
env:
COMPOSE_DIR: ${{ runner.temp }}/release-smoke-compose
run: |
set -euo pipefail
if [ -z "$SMOKE_N8N_IMAGE" ] || [ -z "$SMOKE_RUNNERS_IMAGE" ]; then
echo "::error::SMOKE_N8N_IMAGE and SMOKE_RUNNERS_IMAGE must be non-empty"
exit 1
fi
COMPOSE_SOURCE_DIR="$GITHUB_WORKSPACE/docker"
if [ "$SMOKE_CHANNEL" = "3.x" ]; then
COMPOSE_SOURCE_DIR="$GITHUB_WORKSPACE/.smoke-compose-source/docker"
fi
rm -rf "$COMPOSE_DIR"
# Generate compose.yml, searxng-settings.yml, and .env from the channel's
# one-line installer so sandbox pins and secrets stay in lockstep with get-n8n.sh.
N8N_DIR="$COMPOSE_DIR" \
N8N_COMPOSE_URL="$COMPOSE_SOURCE_DIR/get-n8n-compose.yml" \
DO_NOT_TRACK=1 \
sh "$COMPOSE_SOURCE_DIR/get-n8n.sh" --no-start --version 0.0.0
rm -rf .smoke-compose-source
cat > "$COMPOSE_DIR/compose.override.yml" <<'EOF'
services:
n8n:
image: ${SMOKE_N8N_IMAGE}
runners:
image: ${SMOKE_RUNNERS_IMAGE}
EOF
docker compose -f "$COMPOSE_DIR/compose.yml" -f "$COMPOSE_DIR/compose.override.yml" config --format json | \
node -e '
const fs = require("node:fs");
const cfg = JSON.parse(fs.readFileSync(0, "utf8"));
for (const [svc, expected] of [
["n8n", process.env.SMOKE_N8N_IMAGE],
["runners", process.env.SMOKE_RUNNERS_IMAGE],
]) {
const actual = cfg.services?.[svc]?.image;
if (actual !== expected) {
console.error(`::error::Compose service "${svc}" image is "${actual ?? ""}", expected "${expected}"`);
process.exit(1);
}
}
'
- name: Pull images and start Compose stack
env:
COMPOSE_DIR: ${{ runner.temp }}/release-smoke-compose
run: |
set -euo pipefail
node .github/scripts/retry.mjs --attempts 3 --delay 10 -- \
docker compose \
-f "$COMPOSE_DIR/compose.yml" \
-f "$COMPOSE_DIR/compose.override.yml" \
pull --quiet
docker compose \
-f "$COMPOSE_DIR/compose.yml" \
-f "$COMPOSE_DIR/compose.override.yml" \
up -d --quiet-pull
- name: Wait for /healthz readiness
env:
COMPOSE_DIR: ${{ runner.temp }}/release-smoke-compose
run: |
set -euo pipefail
compose_cmd=(docker compose -f "$COMPOSE_DIR/compose.yml" -f "$COMPOSE_DIR/compose.override.yml")
timeout_s=180
SECONDS=0
ready=false
while [ "$SECONDS" -lt "$timeout_s" ]; do
if curl -sf --max-time 3 http://127.0.0.1:5678/healthz > /dev/null && \
curl -sf --max-time 3 http://127.0.0.1:5678/healthz/readiness > /dev/null; then
echo "n8n /healthz and /healthz/readiness ready after ${SECONDS}s"
ready=true
break
fi
sleep 2
done
if [ "$ready" != "true" ]; then
echo "::error::n8n did not reach /healthz readiness within ${timeout_s}s"
"${compose_cmd[@]}" ps -a || true
exit 1
fi
ps_out="$("${compose_cmd[@]}" ps -a --format '{{.Service}} {{.State}} {{.ExitCode}}')"
echo "$ps_out"
echo "$ps_out" | grep -q '^sandbox-certs exited 0' || {
echo "::error::Expected compose service 'sandbox-certs' to exit 0"
exit 1
}
for svc in sandbox-api sandbox-runner-1 n8n runners searxng; do
if ! echo "$ps_out" | grep -q "^${svc} running"; then
echo "::error::Expected compose service '${svc}' to be running"
exit 1
fi
done
- name: Run smoke suite (phase 1 + pre-restart seed)
env:
SMOKE_STATE_FILE: ${{ runner.temp }}/release-smoke-restart-state.json
run: |
set -euo pipefail
PW_DIR="packages/quality/testing/playwright"
PHASE_DIR="$RUNNER_TEMP/playwright-artifacts/phase-1"
rm -rf "$RUNNER_TEMP/playwright-artifacts"
mkdir -p "$PHASE_DIR"
preserve_artifacts() {
for artifact in test-results playwright-report results.xml test-results.json; do
if [ -e "$PW_DIR/$artifact" ]; then
mv "$PW_DIR/$artifact" "$PHASE_DIR/$artifact" || true
fi
done
}
trap preserve_artifacts EXIT
pnpm --filter n8n-playwright test:smoke
- name: Restart n8n and wait for /healthz readiness
env:
COMPOSE_DIR: ${{ runner.temp }}/release-smoke-compose
run: |
set -euo pipefail
compose_cmd=(docker compose -f "$COMPOSE_DIR/compose.yml" -f "$COMPOSE_DIR/compose.override.yml")
n8n_cid="$("${compose_cmd[@]}" ps -q n8n)"
if [ -z "$n8n_cid" ]; then
echo "::error::Could not resolve n8n container ID before restart"
exit 1
fi
started_before="$(docker inspect -f '{{.State.StartedAt}}' "$n8n_cid")"
"${compose_cmd[@]}" restart n8n
started_after="$(docker inspect -f '{{.State.StartedAt}}' "$n8n_cid")"
if [ "$started_before" = "$started_after" ]; then
echo "::error::n8n container StartedAt did not change after restart (${started_before})"
exit 1
fi
echo "n8n restarted (${started_before} -> ${started_after})"
# Cap post-restart readiness tightly so Phase 2 starts well within Currents'
# run-completion inactivity timeout for the shared CURRENTS_CI_BUILD_ID.
timeout_s=90
SECONDS=0
ready=false
while [ "$SECONDS" -lt "$timeout_s" ]; do
if curl -sf --max-time 2 http://127.0.0.1:5678/healthz > /dev/null && \
curl -sf --max-time 2 http://127.0.0.1:5678/healthz/readiness > /dev/null; then
echo "n8n /healthz and /healthz/readiness ready after restart (${SECONDS}s)"
ready=true
break
fi
sleep 1
done
if [ "$ready" != "true" ]; then
echo "::error::n8n did not reach /healthz readiness within ${timeout_s}s after restart"
"${compose_cmd[@]}" ps -a || true
exit 1
fi
ps_out="$("${compose_cmd[@]}" ps -a --format '{{.Service}} {{.State}} {{.ExitCode}}')"
echo "$ps_out"
echo "$ps_out" | grep -q '^sandbox-certs exited 0' || {
echo "::error::Expected compose service 'sandbox-certs' to exit 0 after restart"
exit 1
}
for svc in sandbox-api sandbox-runner-1 n8n runners searxng; do
if ! echo "$ps_out" | grep -q "^${svc} running"; then
echo "::error::Expected compose service '${svc}' to be running after restart"
exit 1
fi
done
- name: Run post-restart persistence check
env:
SMOKE_PHASE: 'post-restart'
SMOKE_STATE_FILE: ${{ runner.temp }}/release-smoke-restart-state.json
run: |
set -euo pipefail
PW_DIR="packages/quality/testing/playwright"
PHASE_DIR="$RUNNER_TEMP/playwright-artifacts/phase-2"
rm -rf "$PHASE_DIR"
mkdir -p "$PHASE_DIR"
preserve_artifacts() {
for artifact in test-results playwright-report results.xml test-results.json; do
if [ -e "$PW_DIR/$artifact" ]; then
mv "$PW_DIR/$artifact" "$PHASE_DIR/$artifact" || true
fi
done
}
trap preserve_artifacts EXIT
pnpm --filter n8n-playwright test:smoke
- name: Collect Compose logs on failure
if: failure()
env:
COMPOSE_DIR: ${{ runner.temp }}/release-smoke-compose
run: |
if [ ! -f "$COMPOSE_DIR/compose.yml" ]; then
exit 0
fi
compose_files=(-f "$COMPOSE_DIR/compose.yml")
if [ -f "$COMPOSE_DIR/compose.override.yml" ]; then
compose_files+=(-f "$COMPOSE_DIR/compose.override.yml")
fi
DIAG_DIR="$RUNNER_TEMP/compose-diagnostics"
rm -rf "$DIAG_DIR"
mkdir -p "$DIAG_DIR"
docker compose "${compose_files[@]}" ps -a > "$DIAG_DIR/compose-ps.txt" 2>&1 || true
docker compose "${compose_files[@]}" logs --timestamps --no-color > "$DIAG_DIR/compose-logs.txt" 2>&1 || true
for svc in sandbox-certs sandbox-api sandbox-runner-1 n8n runners searxng; do
docker compose "${compose_files[@]}" logs --timestamps --no-color "$svc" > "$DIAG_DIR/${svc}.log" 2>&1 || true
done
- name: Upload failure artifacts
if: failure()
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
with:
name: release-smoke-${{ needs.resolve.outputs.channel_slug }}-compose-${{ github.run_attempt }}
path: |
${{ runner.temp }}/playwright-artifacts/
${{ runner.temp }}/compose-diagnostics/
retention-days: 7
if-no-files-found: ignore
- name: Tear down Compose stack
if: always()
env:
COMPOSE_DIR: ${{ runner.temp }}/release-smoke-compose
SMOKE_STATE_FILE: ${{ runner.temp }}/release-smoke-restart-state.json
run: |
if [ -f "$COMPOSE_DIR/compose.yml" ]; then
compose_files=(-f "$COMPOSE_DIR/compose.yml")
if [ -f "$COMPOSE_DIR/compose.override.yml" ]; then
compose_files+=(-f "$COMPOSE_DIR/compose.override.yml")
fi
docker compose "${compose_files[@]}" down -v --remove-orphans || true
fi
rm -rf "$COMPOSE_DIR" "$RUNNER_TEMP/compose-diagnostics" "$RUNNER_TEMP/playwright-artifacts" .smoke-compose-source
rm -f "$SMOKE_STATE_FILE"
- name: Cancel Currents run if workflow is cancelled
if: ${{ cancelled() && env.CURRENTS_RECORD_KEY != '' }}
run: pnpm --filter=n8n-playwright exec currents run cancel || true
- name: Revoke Currents OIDC credential
if: ${{ always() && env.CURRENTS_RECORD_KEY != '' }}
run: pnpm --filter=n8n-playwright exec currents ci auth revoke || true
@@ -0,0 +1,30 @@
name: 'Util: Cancel Destroyed Merge Group Runs'
on:
merge_group:
types: [destroyed]
permissions: {}
jobs:
cancel:
name: Cancel orphaned runs
if: contains(fromJSON('["invalidated", "dequeued"]'), github.event.reason)
runs-on: ubuntu-slim
timeout-minutes: 5
permissions:
actions: write
contents: read
steps:
# Check out the default branch because GitHub already deleted the destroyed queue ref.
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ github.event.repository.default_branch }}
persist-credentials: false
sparse-checkout: .github
- name: Cancel active merge_group runs
uses: ./.github/actions/run-workflow-script
with:
script: .github/scripts/cancel-destroyed-merge-group.mjs
github-token: ${{ secrets.GITHUB_TOKEN }}
+2 -1
View File
@@ -44,7 +44,8 @@ pre-commit:
- rebase
actionlint_check:
glob: '.github/workflows/*.{yml,yaml}'
run: actionlint {staged_files}
# actionlint <=1.7.12 does not yet recognize the valid `merge_group.destroyed` activity type.
run: actionlint -ignore 'invalid activity type "destroyed" for "merge_group" Webhook event' {staged_files}
skip:
- merge
- rebase
@@ -125,7 +125,7 @@
{
"type": "tool_result",
"tool_use_id": "toolu_01AvHg8o8w8rvyMtUJqa9Zxy",
"content": "Error: Tool call stopped by guardrail: tool.blocked",
"content": "GuardrailStopError: Tool call stopped by guardrail: tool.blocked",
"is_error": true
}
]
@@ -14,6 +14,7 @@ import { Agent } from '../../index';
import type {
GuardrailDecision,
GuardrailModelCallContext,
GuardrailModelCallDecision,
GuardrailToolCallContext,
GuardrailsOptions,
ModelGuardrail,
@@ -26,7 +27,7 @@ const IDS = { agentId: 'agent-1', threadId: 'thread-1' };
type Decide = {
/** Called with the 1-based index of the model call. */
before?: (callNumber: number) => GuardrailDecision | undefined;
before?: (callNumber: number) => GuardrailModelCallDecision | undefined;
beforeTool?: (ctx: GuardrailToolCallContext) => GuardrailDecision | undefined;
};
@@ -60,7 +61,7 @@ function recordingGuardrail(decide: Decide = {}) {
return { guardrails, calls };
}
const stop = (code: string): GuardrailDecision => ({ action: 'stop', code });
const stop = (code: string): GuardrailModelCallDecision => ({ action: 'stop', code });
describe('guardrails integration', () => {
it('refuses the first model call in generate', async () => {
+8 -1
View File
@@ -9,8 +9,11 @@ export type {
GuardrailDecision,
GuardrailModelCallContext,
GuardrailModelCallSource,
GuardrailModelCallDecision,
GuardrailNotice,
GuardrailStop,
GuardrailToolCallContext,
GuardrailToolCallOutcome,
GuardrailsOptions,
ModelGuardrail,
PiiDetectionType,
@@ -187,7 +190,11 @@ export {
} from './sdk/vector-store-filter';
export type { VectorFilterInput } from './sdk/vector-store-filter';
export { Guardrail } from './sdk/guardrail';
export { budgetMonthKey, createBudgetGuardrail } from './runtime/guardrails/budget-guardrail';
export {
budgetMonthKey,
chargeModelSpend,
createBudgetGuardrail,
} from './runtime/guardrails/budget-guardrail';
export type {
BudgetGuardrailOptions,
SpendEntry,
@@ -25,11 +25,7 @@ import type {
import { AgentEvent } from '../../types/runtime/event';
import type { AgentEventData } from '../../types/runtime/event';
import type { ExecutionOptions, GenerateResult, StreamChunk } from '../../types/sdk/agent';
import type {
GuardrailDecision,
GuardrailsOptions,
ModelGuardrail,
} from '../../types/sdk/guardrail';
import type { GuardrailsOptions, ModelGuardrail } from '../../types/sdk/guardrail';
import type { AgentDbMessage, ContentToolCall, Message } from '../../types/sdk/message';
import { stripHydratedFileData } from '../../types/sdk/message';
import type {
@@ -1915,7 +1911,10 @@ describe('AgentRuntime — guardrails', () => {
streamText.mockReset();
});
const stopDecision = (code: string): GuardrailDecision => ({ action: 'stop', code });
const stopDecision = (code: string): { action: 'stop'; code: string } => ({
action: 'stop',
code,
});
type GuardrailSpies = {
[K in keyof Required<ModelGuardrail>]: MockedFunction<NonNullable<ModelGuardrail[K]>>;
@@ -2222,6 +2221,253 @@ describe('AgentRuntime — guardrails', () => {
expect(toolResult).toEqual({ echoed: 'x' });
});
it('runs the tool with the rewritten input when beforeTool() redacts', async () => {
generateText
.mockResolvedValueOnce(makeGenerateWithToolCall('tc-1', 'echo', { v: 'x' }))
.mockResolvedValueOnce(makeGenerateSuccess('Done'));
const handler = vi.fn(async ({ v }: { v: string }) => await Promise.resolve({ echoed: v }));
const hook = makeGuardrail({
beforeTool: vi.fn<NonNullable<ModelGuardrail['beforeTool']>>().mockResolvedValue({
action: 'redact',
code: 'guardrail.redact',
value: { v: '<KEYWORD>' },
}),
});
const runtime = createRuntimeWithEchoTool(handler);
const result = await runtime.generate('go', { guardrails: guardrailsOption(hook) });
expect(handler.mock.calls[0]?.[0]).toEqual({ v: '<KEYWORD>' });
const [, toolResult] = hook.afterTool.mock.calls[0];
expect(toolResult).toEqual({ echoed: '<KEYWORD>' });
expect(result.finishReason).toBe('stop');
});
it('feeds the rewritten result to the model when afterTool() redacts', async () => {
generateText
.mockResolvedValueOnce(makeGenerateWithToolCall('tc-1', 'echo', { v: 'x' }))
.mockResolvedValueOnce(makeGenerateSuccess('Done'));
const hook = makeGuardrail({
afterTool: vi.fn<NonNullable<ModelGuardrail['afterTool']>>().mockResolvedValue({
action: 'redact',
code: 'guardrail.redact',
value: '<REDACTED_RESULT>',
}),
});
const runtime = createRuntimeWithEchoTool(
async ({ v }) => await Promise.resolve({ echoed: v }),
);
await runtime.generate('go', { guardrails: guardrailsOption(hook) });
const secondModelCall = generateText.mock.calls[1]?.[0];
// The model sees the rewritten result, not the raw handler output.
expect(JSON.stringify(secondModelCall?.messages)).toContain('<REDACTED_RESULT>');
expect(JSON.stringify(secondModelCall?.messages)).not.toContain('echoed');
});
it('runs a resumed suspension with the before-stage redacted input', async () => {
const handlerInputs: unknown[] = [];
const suspendTool: BuiltTool = {
...makeInterruptibleTool(),
handler: async (input: unknown, ctx: unknown) => {
const { suspend, resumeData } = ctx as InterruptibleToolContext;
handlerInputs.push(input);
if (!resumeData) {
return await suspend({ question: 'approve?' });
}
return { approved: true };
},
};
const hook = makeGuardrail({
beforeTool: vi.fn<NonNullable<ModelGuardrail['beforeTool']>>().mockResolvedValue({
action: 'redact',
code: 'guardrail.redact',
value: { question: '<KEYWORD>' },
}),
});
const { runtime } = createRuntimeWithTools([suspendTool], 1);
generateText.mockResolvedValueOnce(
makeGenerateWithToolCalls([
{ toolCallId: 'tc-1', toolName: 'approve', args: { question: 'continue?' } },
]),
);
const first = await runtime.generate('needs approval', { guardrails: guardrailsOption(hook) });
// The tool received the rewritten input, and the suspension persists
// that input, not the original the model sent.
expect(handlerInputs[0]).toEqual({ question: '<KEYWORD>' });
expect(first.pendingSuspend![0]).toMatchObject({
toolName: 'approve',
input: { question: '<KEYWORD>' },
});
generateText.mockResolvedValueOnce(makeGenerateSuccess('approved'));
await runtime.resume(
'generate',
{ approved: true },
{
runId: first.pendingSuspend![0].runId,
toolCallId: 'tc-1',
},
);
// The resumed call skips the before hooks, so the persisted redacted
// input is what reaches the tool.
expect(handlerInputs[1]).toEqual({ question: '<KEYWORD>' });
expect(hook.beforeTool).toHaveBeenCalledTimes(1);
});
it('parses the original input again on resume, so schema transforms run once', async () => {
const handlerInputs: unknown[] = [];
const transformTool: BuiltTool = {
name: 'stamp',
description: 'Appends a stamp and suspends once',
inputSchema: z.object({ text: z.string().transform((value) => `${value}!`) }),
suspendSchema: z.object({ question: z.string() }),
resumeSchema: z.object({ approved: z.boolean() }),
handler: async (input: unknown, ctx: unknown) => {
const { suspend, resumeData } = ctx as InterruptibleToolContext;
handlerInputs.push(input);
if (!resumeData) {
return await suspend({ question: 'approve?' });
}
return { done: true };
},
};
const { runtime } = createRuntimeWithTools([transformTool], 1);
generateText.mockResolvedValueOnce(makeGenerateWithToolCall('tc-1', 'stamp', { text: 'a' }));
const first = await runtime.generate('go');
expect(handlerInputs[0]).toEqual({ text: 'a!' });
generateText.mockResolvedValueOnce(makeGenerateSuccess('done'));
await runtime.resume(
'generate',
{ approved: true },
{
runId: first.pendingSuspend![0].runId,
toolCallId: 'tc-1',
},
);
// The checkpoint kept the model's raw input, so the resume parses it
// again: the transform runs once more on the raw value, not on its
// own output.
expect(handlerInputs[1]).toEqual({ text: 'a!' });
});
it('keeps a redaction to null through the suspension and resume', async () => {
const handlerInputs: unknown[] = [];
const suspendTool: BuiltTool = {
...makeInterruptibleTool(),
handler: async (input: unknown, ctx: unknown) => {
const { suspend, resumeData } = ctx as InterruptibleToolContext;
handlerInputs.push(input);
if (!resumeData) {
return await suspend({ question: 'approve?' });
}
return { approved: true };
},
};
const hook = makeGuardrail({
beforeTool: vi.fn<NonNullable<ModelGuardrail['beforeTool']>>().mockResolvedValue({
action: 'redact',
code: 'guardrail.redact',
value: null,
}),
});
const { runtime } = createRuntimeWithTools([suspendTool], 1);
generateText.mockResolvedValueOnce(
makeGenerateWithToolCall('tc-1', 'approve', { question: 'continue?' }),
);
const first = await runtime.generate('needs approval', {
guardrails: guardrailsOption(hook),
});
expect(handlerInputs[0]).toBeNull();
generateText.mockResolvedValueOnce(makeGenerateSuccess('approved'));
await runtime.resume(
'generate',
{ approved: true },
{
runId: first.pendingSuspend![0].runId,
toolCallId: 'tc-1',
},
);
// A redaction to null is a result, not an absence: the resume must not
// fall back to the original input the guardrail removed.
expect(handlerInputs[1]).toBeNull();
});
it('resumes a deferred call_tool suspension that suspends a second time', async () => {
const twoPhase: BuiltTool = {
...makeInterruptibleTool(),
suspendSchema: z.object({ question: z.string() }),
resumeSchema: z.object({ step: z.number() }),
handler: async (_input: unknown, ctx: unknown) => {
const { suspend, resumeData } = ctx as InterruptibleToolContext;
const step = (resumeData as { step?: number } | undefined)?.step;
if (step === undefined) {
return await suspend({ question: 'first' });
}
if (step < 2) {
return await suspend({ question: 'second' });
}
return { done: true };
},
};
const runtime = new AgentRuntime({
name: 'test',
model: 'openai/gpt-4o-mini',
instructions: 'You are a test assistant.',
deferredTools: [twoPhase],
toolDeferral: { mode: 'tool-catalog' },
checkpointStorage: 'memory',
});
generateText.mockResolvedValueOnce(
makeGenerateWithToolCalls([
{
toolCallId: 'tc-1',
toolName: 'call_tool',
args: { tool: 'approve', arguments: { question: 'continue?' } },
},
]),
);
const first = await runtime.generate('needs approval');
expect(first.pendingSuspend![0]).toMatchObject({ toolName: 'approve' });
// The first resume re-suspends: the checkpoint must keep the
// dispatcher's own call_tool input for the second resume to resolve.
const second = await runtime.resume(
'generate',
{ step: 1 },
{
runId: first.pendingSuspend![0].runId,
toolCallId: first.pendingSuspend![0].toolCallId,
},
);
expect(second.error).toBeUndefined();
expect(second.pendingSuspend![0]).toMatchObject({ toolName: 'approve' });
generateText.mockResolvedValueOnce(makeGenerateSuccess('done'));
const third = await runtime.resume(
'generate',
{ step: 2 },
{
runId: second.pendingSuspend![0].runId,
toolCallId: second.pendingSuspend![0].toolCallId,
},
);
expect(third.error).toBeUndefined();
expect(third.pendingSuspend).toBeUndefined();
expect(third.toolCalls).toEqual(
expect.arrayContaining([expect.objectContaining({ output: { done: true } })]),
);
});
it.each([false, true])('checks approval once with native deferral %s', async (native) => {
const approvalTool = new ToolBuilder('delete')
.description('Delete a record')
@@ -314,6 +314,55 @@ describe('ToolCallRunner guardrail after-stage stop', () => {
expect(handler).toHaveBeenCalledTimes(1);
});
it('keeps a guardrail refusal plain for an untrusted tool', async () => {
const handler = vi.fn<NonNullable<BuiltTool['handler']>>().mockResolvedValue('tool output');
const tool: BuiltTool = {
name: 'fetch_page',
description: 'Synthetic tool',
handler,
outputTrust: 'untrusted',
};
const { runner } = makeRunner();
const { params } = makeCall(tool);
const outcome = await runner.processToolCall({
...params,
guardrails: {
hooks: [
{
afterTool: async () => ({ action: 'stop' as const, code: 'guardrail.urls.g1' }),
},
],
},
});
const error = outcome.outcome === 'error' ? outcome.error : '';
expect(error).toContain('Tool result blocked by guardrail: guardrail.urls.g1');
// Runtime-authored guardrail text is not tool output: it must not carry
// the untrusted-data wrapper.
expect(error).not.toContain('<untrusted_data');
});
it('still wraps a handler failure for an untrusted tool', async () => {
const handler = vi
.fn<NonNullable<BuiltTool['handler']>>()
.mockRejectedValue(new Error('boom from the tool'));
const tool: BuiltTool = {
name: 'fetch_page',
description: 'Synthetic tool',
handler,
outputTrust: 'untrusted',
};
const { runner } = makeRunner();
const { params } = makeCall(tool);
const outcome = await runner.processToolCall(params);
const error = outcome.outcome === 'error' ? outcome.error : '';
// Tool-authored errors stay protected by the untrusted wrapper.
expect(error).toContain('<untrusted_data');
});
it('keeps the success outcome when the after-stage hook only observes', async () => {
const handler = vi.fn<NonNullable<BuiltTool['handler']>>().mockResolvedValue('clean result');
const tool: BuiltTool = { name: 'fetch_page', description: 'Synthetic tool', handler };
@@ -1,7 +1,12 @@
import type { GuardrailModelCallContext, TokenUsage } from '../../../types';
import { budgetMonthKey, createBudgetGuardrail } from '../budget-guardrail';
import { computeSideCallCost } from '../../loop/side-call-cost';
import { budgetMonthKey, chargeModelSpend, createBudgetGuardrail } from '../budget-guardrail';
import { spendLedger } from './spend-ledger';
vi.mock('../../loop/side-call-cost', () => ({
computeSideCallCost: vi.fn(),
}));
const usage = (cost?: number): TokenUsage => ({
promptTokens: 1,
completionTokens: 1,
@@ -126,6 +131,78 @@ describe('createBudgetGuardrail', () => {
expect(await ledger.read(monthKey('agent-1'))).toBe(0);
});
it('charges a guardrail call onto the session and the month, once per call id', async () => {
vi.mocked(computeSideCallCost).mockResolvedValue(6);
const ledger = spendLedger();
const onNotice = vi.fn();
const budget = {
ledger,
sessionId: 'session-1',
agentId: 'agent-1',
sessionCostCapUsd: 1,
monthlyBudgetUsd: 10,
alertThresholdPercent: 50,
onNotice,
};
const usage = { inputTokens: 6, outputTokens: 0, totalTokens: 6 };
await chargeModelSpend({ modelId: 'openai/gpt-4o-mini', usage, callId: 'call-1', budget });
await chargeModelSpend({ modelId: 'openai/gpt-4o-mini', usage, callId: 'call-1', budget });
expect(computeSideCallCost).toHaveBeenCalledWith(
'openai/gpt-4o-mini',
expect.objectContaining({ promptTokens: 6, completionTokens: 0 }),
);
expect(await ledger.read('session-1')).toBe(6);
expect(await ledger.read(monthKey('agent-1'))).toBe(6);
expect(onNotice).toHaveBeenCalledTimes(1);
expect(onNotice).toHaveBeenCalledWith({ code: 'budget.alert' });
const guardrail = createBudgetGuardrail(budget);
await expect(guardrail.before?.(ctx('call-2'))).resolves.toEqual({
action: 'stop',
code: 'budget.session',
});
});
it('adds nothing when the model has no price', async () => {
vi.mocked(computeSideCallCost).mockResolvedValueOnce(undefined);
const ledger = spendLedger();
await chargeModelSpend({
modelId: 'openai/gpt-4o-mini',
usage: { inputTokens: 10, outputTokens: 5, totalTokens: 15 },
callId: 'call-1',
budget: {
ledger,
sessionId: 'session-1',
agentId: 'agent-1',
sessionCostCapUsd: 1,
monthlyBudgetUsd: 1,
},
});
expect(await ledger.read('session-1')).toBe(0);
expect(await ledger.read(monthKey('agent-1'))).toBe(0);
});
it('adds nothing when pricing throws', async () => {
vi.mocked(computeSideCallCost).mockRejectedValueOnce(new Error('catalog down'));
const ledger = spendLedger();
await chargeModelSpend({
modelId: 'openai/gpt-4o-mini',
usage: { inputTokens: 10, outputTokens: 5, totalTokens: 15 },
callId: 'call-1',
budget: {
ledger,
sessionId: 'session-1',
agentId: 'agent-1',
sessionCostCapUsd: 1,
},
});
expect(await ledger.read('session-1')).toBe(0);
});
it('stops with budget.misconfigured when a limit has no id', async () => {
const ledger = spendLedger();
const missingSession = createBudgetGuardrail({ ledger, sessionCostCapUsd: 1 });
@@ -12,7 +12,7 @@ const stop = (code: string): GuardrailDecision => ({ action: 'stop', code });
function makeHook(overrides: Partial<ModelGuardrail> = {}) {
return {
before: vi.fn<NonNullable<ModelGuardrail['before']>>().mockResolvedValue(allow),
before: vi.fn<NonNullable<ModelGuardrail['before']>>().mockResolvedValue({ action: 'allow' }),
after: vi.fn<NonNullable<ModelGuardrail['after']>>().mockResolvedValue(undefined),
beforeTool: vi.fn<NonNullable<ModelGuardrail['beforeTool']>>().mockResolvedValue(allow),
afterTool: vi.fn<NonNullable<ModelGuardrail['afterTool']>>().mockResolvedValue(undefined),
@@ -174,7 +174,7 @@ describe('GuardrailRunner', () => {
const result = await runnerFor([first, second, third]).afterTool(toolCtx, {});
expect(result).toEqual({ code: 'tool.a' });
expect(result).toEqual({ stop: { code: 'tool.a' } });
expect(first.afterTool).toHaveBeenCalledWith(toolCtx, {});
expect(third.afterTool).not.toHaveBeenCalled();
});
@@ -187,5 +187,60 @@ describe('GuardrailRunner', () => {
expect(result).toBeUndefined();
});
it('threads a before-stage redact into the context and later hooks', async () => {
const redact = makeHook({
beforeTool: vi.fn<NonNullable<ModelGuardrail['beforeTool']>>().mockResolvedValue({
action: 'redact',
code: 'guardrail.redact',
value: { rewritten: true },
}),
});
const later = makeHook();
const ctx = { ...toolCtx };
const result = await runnerFor([redact, later]).beforeTool(ctx);
expect(result).toBeUndefined();
expect(ctx.input).toEqual({ rewritten: true });
expect(later.beforeTool).toHaveBeenCalledWith(ctx);
// The rewritten input was visible to the later hook at call time.
expect(vi.mocked(later.beforeTool).mock.calls[0]?.[0].input).toEqual({ rewritten: true });
});
it('stops even when a later hook would redact', async () => {
const first = makeHook();
const stopper = makeHook({ beforeTool: vi.fn().mockResolvedValue(stop('tool.a')) });
const redacts = makeHook({
beforeTool: vi.fn<NonNullable<ModelGuardrail['beforeTool']>>().mockResolvedValue({
action: 'redact',
code: 'guardrail.redact',
value: { rewritten: true },
}),
});
const ctx = { ...toolCtx };
const result = await runnerFor([first, stopper, redacts]).beforeTool(ctx);
expect(result).toEqual({ code: 'tool.a' });
expect(ctx.input).toBe(toolCtx.input);
expect(redacts.beforeTool).not.toHaveBeenCalled();
});
it('returns the redacted result and lets later hooks see it', async () => {
const redact = makeHook({
afterTool: vi.fn<NonNullable<ModelGuardrail['afterTool']>>().mockResolvedValue({
action: 'redact',
code: 'guardrail.redact',
value: { clean: true },
}),
});
const later = makeHook();
const result = await runnerFor([redact, later]).afterTool(toolCtx, { dirty: true });
expect(result).toEqual({ redacted: { clean: true } });
expect(later.afterTool).toHaveBeenCalledWith(toolCtx, { clean: true });
});
});
});
@@ -1,4 +1,6 @@
import type { GuardrailDecision, ModelGuardrail, TokenUsage } from '../../types';
import type { GuardrailModelCallDecision, ModelGuardrail, TokenUsage } from '../../types';
import { computeSideCallCost } from '../loop/side-call-cost';
import { toTokenUsage } from '../streaming/stream';
export interface SpendEntry {
key: string;
@@ -27,10 +29,10 @@ export interface BudgetGuardrailOptions {
onNotice?: (notice: { code: 'budget.alert' }) => void;
}
const SESSION_STOP: GuardrailDecision = { action: 'stop', code: 'budget.session' };
const MONTHLY_STOP: GuardrailDecision = { action: 'stop', code: 'budget.monthly' };
const MISCONFIGURED: GuardrailDecision = { action: 'stop', code: 'budget.misconfigured' };
const ALLOW: GuardrailDecision = { action: 'allow' };
const SESSION_STOP: GuardrailModelCallDecision = { action: 'stop', code: 'budget.session' };
const MONTHLY_STOP: GuardrailModelCallDecision = { action: 'stop', code: 'budget.monthly' };
const MISCONFIGURED: GuardrailModelCallDecision = { action: 'stop', code: 'budget.misconfigured' };
const ALLOW: GuardrailModelCallDecision = { action: 'allow' };
/** UTC month bucket shared by the guardrail and the settings spend read. */
export function budgetMonthKey(agentId: string, now: Date = new Date()): string {
@@ -52,16 +54,12 @@ function positiveUsd(value: number | undefined): number | undefined {
* spent. The crossing call is recorded. A missing `usage.cost` adds nothing.
*/
export function createBudgetGuardrail(options: BudgetGuardrailOptions): ModelGuardrail {
const { ledger, sessionId, agentId, alertThresholdPercent, onNotice } = options;
const { ledger, sessionId, agentId } = options;
const sessionCostCapUsd = positiveUsd(options.sessionCostCapUsd);
const monthlyBudgetUsd = positiveUsd(options.monthlyBudgetUsd);
const alertLine =
monthlyBudgetUsd !== undefined && alertThresholdPercent !== undefined
? (monthlyBudgetUsd * alertThresholdPercent) / 100
: undefined;
return {
async before(): Promise<GuardrailDecision> {
async before(): Promise<GuardrailModelCallDecision> {
if (sessionCostCapUsd !== undefined && !hasId(sessionId)) return MISCONFIGURED;
if (monthlyBudgetUsd !== undefined && !hasId(agentId)) return MISCONFIGURED;
@@ -75,28 +73,71 @@ export function createBudgetGuardrail(options: BudgetGuardrailOptions): ModelGua
}
return ALLOW;
},
async after(ctx, usage: TokenUsage | undefined): Promise<void> {
const cost = usage?.cost;
if (cost === undefined) return;
const entries: SpendEntry[] = [];
if (sessionCostCapUsd !== undefined && hasId(sessionId)) {
entries.push({ key: sessionId, usd: cost });
}
const month = hasId(agentId) ? budgetMonthKey(agentId) : undefined;
if (monthlyBudgetUsd !== undefined && month !== undefined) {
entries.push({ key: month, usd: cost });
}
if (entries.length === 0) return;
const totals = await ledger.add(ctx.callId, entries);
if (alertLine === undefined || month === undefined) return;
const monthTotal = totals.find((total) => total.key === month);
if (!monthTotal) return;
if (monthTotal.previousUsd < alertLine && monthTotal.totalUsd >= alertLine) {
onNotice?.({ code: 'budget.alert' });
}
await recordBudgetSpend(options, ctx.callId, usage?.cost);
},
};
}
/**
* Writes one priced call to the session key and the month key. Fires the
* alert once, when the month total crosses the line. A missing cost adds
* nothing. A repeated `callId` does not add the cost twice.
*/
async function recordBudgetSpend(
options: BudgetGuardrailOptions,
callId: string,
cost: number | undefined,
): Promise<void> {
if (cost === undefined) return;
const { ledger, sessionId, agentId, alertThresholdPercent, onNotice } = options;
const sessionCostCapUsd = positiveUsd(options.sessionCostCapUsd);
const monthlyBudgetUsd = positiveUsd(options.monthlyBudgetUsd);
const alertLine =
monthlyBudgetUsd !== undefined && alertThresholdPercent !== undefined
? (monthlyBudgetUsd * alertThresholdPercent) / 100
: undefined;
const entries: SpendEntry[] = [];
if (sessionCostCapUsd !== undefined && hasId(sessionId)) {
entries.push({ key: sessionId, usd: cost });
}
const month = hasId(agentId) ? budgetMonthKey(agentId) : undefined;
if (monthlyBudgetUsd !== undefined && month !== undefined) {
entries.push({ key: month, usd: cost });
}
if (entries.length === 0) return;
const totals = await ledger.add(callId, entries);
if (alertLine === undefined || month === undefined) return;
const monthTotal = totals.find((total) => total.key === month);
if (!monthTotal) return;
if (monthTotal.previousUsd < alertLine && monthTotal.totalUsd >= alertLine) {
onNotice?.({ code: 'budget.alert' });
}
}
/**
* Prices one side model call and writes it to the budget ledger. A missing
* price, or a catalog failure, adds nothing and does not throw: the tool
* call still finishes.
*/
export async function chargeModelSpend(input: {
modelId: string;
usage: Parameters<typeof toTokenUsage>[0];
providerMetadata?: Parameters<typeof toTokenUsage>[1];
callId: string;
budget: BudgetGuardrailOptions;
}): Promise<void> {
let cost: number | undefined;
try {
const usage = toTokenUsage(input.usage, input.providerMetadata);
if (!usage) return;
cost = await computeSideCallCost(input.modelId, usage);
} catch {
// The catalog can fail. This call adds no spend.
return;
}
await recordBudgetSpend(input.budget, input.callId, cost);
}
@@ -3,6 +3,7 @@ import type {
GuardrailModelCallSource,
GuardrailStop,
GuardrailToolCallContext,
GuardrailToolCallOutcome,
GuardrailsOptions,
ModelGuardrail,
TokenUsage,
@@ -61,6 +62,9 @@ export class GuardrailRunner {
for (const hook of this.hooks) {
const decision = await hook.beforeTool?.(ctx);
if (decision?.action === 'stop') return { code: decision.code };
// A redact rewrites the input the tool receives; later hooks see
// the rewritten value.
if (decision?.action === 'redact') ctx.input = decision.value;
}
return undefined;
}
@@ -68,11 +72,17 @@ export class GuardrailRunner {
async afterTool(
ctx: GuardrailToolCallContext,
result: unknown,
): Promise<GuardrailStop | undefined> {
): Promise<GuardrailToolCallOutcome | undefined> {
let redacted = false;
for (const hook of this.hooks) {
const decision = await hook.afterTool?.(ctx, result);
if (decision?.action === 'stop') return { code: decision.code };
if (decision?.action === 'stop') return { stop: { code: decision.code } };
// A redact rewrites the result the model receives
if (decision?.action === 'redact') {
result = decision.value;
redacted = true;
}
}
return undefined;
return redacted ? { redacted: result } : undefined;
}
}
@@ -0,0 +1,19 @@
/**
* A tool call refused by a tool guardrail. The message is authored by the
* runtime, not the tool, so it must reach the model plainly even for untrusted
* tools — unlike tool-authored errors, which the untrusted-output protection
* wraps.
*/
export class GuardrailStopError extends Error {
constructor(
readonly stage: 'before' | 'after',
readonly code: string,
) {
super(
stage === 'before'
? `Tool call stopped by guardrail: ${code}`
: `Tool result blocked by guardrail: ${code}`,
);
this.name = 'GuardrailStopError';
}
}
@@ -246,10 +246,16 @@ export class ToolCallExecutor {
}
const outcome = result.value;
switch (outcome.outcome) {
case 'suspended':
batch.suspensions.push(this.buildToolCallSuspension(call, outcome));
batch.pending[call.toolCallId] = this.buildPendingToolCall(call, outcome, ctx.runId);
case 'suspended': {
this.collectSuspendedToolCall(
call,
outcome,
this.isDispatchedCall(ctx.toolMap, call),
batch,
ctx.runId,
);
return true;
}
case 'success':
case 'cancelled':
this.appendCompletedToolCall(call, outcome, batch.results);
@@ -266,14 +272,48 @@ export class ToolCallExecutor {
return false;
}
/**
* A dispatcher (the tool catalog's `call_tool`) resolves the target on
* every run, so a suspended dispatched call must checkpoint the
* dispatcher's own input: the inner tool's input would not resolve the
* dispatch on resume.
*/
private isDispatchedCall(
toolMap: Map<string, BuiltTool>,
call: Pick<ToolCallIdentity, 'toolName' | 'input'>,
): boolean {
return resolveToolCallTarget(toolMap, call.toolName, call.input)?.dispatchedBy !== undefined;
}
/**
* Record a suspended call on the batch: the stream suspension carries the
* input the tool received, while the pending record keeps what a resume
* needs — the dispatcher's input for a dispatched call, the redacted
* input for a redacted direct call, and otherwise the original input so
* the resume parses it fresh, exactly like a first run.
*/
private collectSuspendedToolCall(
call: ToolCallIdentity,
outcome: SuspendedToolOutcome,
dispatched: boolean,
batch: ToolCallBatchResult,
runId: string,
): void {
batch.suspensions.push(this.buildToolCallSuspension(call, outcome, dispatched));
batch.pending[call.toolCallId] = this.buildPendingToolCall(call, outcome, dispatched, runId);
}
private buildToolCallSuspension(
call: ToolCallIdentity,
outcome: SuspendedToolOutcome,
dispatched: boolean,
): ToolCallSuspension {
return {
toolCallId: call.toolCallId,
toolName: call.toolName,
input: call.input,
// A dispatched call reports the dispatcher's input; a direct call
// reports the one the tool received, after any redaction.
input: dispatched ? call.input : outcome.input,
payload: outcome.payload,
resumeSchema: outcome.resumeSchema,
};
@@ -282,13 +322,21 @@ export class ToolCallExecutor {
private buildPendingToolCall(
call: ToolCallIdentity,
outcome: SuspendedToolOutcome,
dispatched: boolean,
runId: string,
): PendingToolCall {
return {
suspended: true,
toolCallId: call.toolCallId,
toolName: call.toolName,
input: call.input,
// The dispatcher re-runs on resume, so a dispatched call keeps its
// own input, redaction or not. A direct call keeps the redacted
// input — a resume skips the before hooks, so the original would
// reach the tool — and otherwise the original, so the resume
// parses it fresh instead of re-running schema transforms on an
// already-parsed value.
input: dispatched || !outcome.inputRedacted ? call.input : outcome.input,
...(outcome.inputRedacted ? { inputRedacted: true } : {}),
suspendPayload: outcome.payload,
resumeSchema: outcome.resumeSchema,
...(outcome.continuation !== undefined ? { continuation: outcome.continuation } : {}),
@@ -398,7 +446,7 @@ export class ToolCallExecutor {
return await this.finalizeBatch(batch, ctx);
}
this.collectResumedToolCall(resumedId, resumedEntry, outcome, batch, ctx.runId);
this.collectResumedToolCall(resumedId, resumedEntry, outcome, batch, ctx.toolMap, ctx.runId);
await this.executeRemainingToolCalls(ctx, batch);
return await this.finalizeBatch(batch, ctx);
}
@@ -408,12 +456,21 @@ export class ToolCallExecutor {
entry: PendingToolCall,
outcome: ToolCallOutcome,
batch: ToolCallBatchResult,
toolMap: Map<string, BuiltTool>,
runId: string,
): void {
switch (outcome.outcome) {
case 'suspended':
batch.pending[id] = this.buildPendingToolCall(entry, outcome, runId);
batch.suspensions.push(this.buildToolCallSuspension({ ...entry, toolCallId: id }, outcome));
// The same dispatched rule as a first suspension: a resumed
// call_tool that suspends again must keep the dispatcher's
// input, or the next resume cannot resolve the dispatch.
this.collectSuspendedToolCall(
{ ...entry, toolCallId: id },
outcome,
this.isDispatchedCall(toolMap, entry),
batch,
runId,
);
break;
case 'success':
this.appendCompletedToolCall(entry, outcome, batch.results);
@@ -539,6 +596,8 @@ export class ToolCallExecutor {
abortSignal: ctx.abortSignal,
countToolCall: false,
previouslySuspended: entry.suspended,
// A redacted checkpointed input was validated before the redaction.
...(entry.suspended && entry.inputRedacted ? { inputRedacted: true } : {}),
...(entry.suspended
? {
suspendPayload: entry.suspendPayload,
@@ -24,6 +24,7 @@ import { isCancellation } from '../../sdk/cancellation';
import { isLlmMessage } from '../../sdk/message';
import type { BuiltTool, ToolSuspendOptions } from '../../types';
import { AgentEvent } from '../../types/runtime/event';
import { GuardrailStopError } from '../guardrails/guardrail-stop-error';
import type {
ProcessToolCallParams,
ToolCallExecutorDeps,
@@ -158,7 +159,12 @@ export class ToolCallRunner {
incrementToolCallCount(params.executionCounter);
}
const validation = await this.validateToolInput(params, builtTool, !!target.dispatchedBy);
// A checkpointed input that a guardrail redacted was validated before
// the redaction: re-running validation would reject the mask, which is
// the guardrail working as configured, not a bad input.
const validation = params.inputRedacted
? { ok: true as const, input: params.input }
: await this.validateToolInput(params, builtTool, !!target.dispatchedBy);
if (!validation.ok) return validation.outcome;
const input = validation.input;
@@ -175,29 +181,40 @@ export class ToolCallRunner {
if (guardrails && guardCtx && !params.previouslySuspended) {
const stop = await guardrails.beforeTool(guardCtx);
if (stop) {
return await this.toolError(
params,
new Error(`Tool call stopped by guardrail: ${stop.code}`),
);
return await this.toolError(params, new GuardrailStopError('before', stop.code));
}
}
// A before-stage redact rewrote the input inside the context. The
// context wins whenever it exists, so a redaction to `null` or
// `undefined` is preserved instead of falling back to the original.
const effectiveInput = (guardCtx !== undefined ? guardCtx.input : input) as typeof input;
const inputRedacted =
params.inputRedacted === true || (guardCtx !== undefined && guardCtx.input !== input);
if (shouldEmitToolExecutionStart(builtTool, resumeData)) {
this.eventBus.emit({
type: AgentEvent.ToolExecutionStart,
toolCallId,
toolName,
args: input,
args: effectiveInput,
});
}
return await this.executeValidatedToolCall(params, builtTool, input, guardrails, guardCtx);
return await this.executeValidatedToolCall(
params,
builtTool,
effectiveInput,
inputRedacted,
guardrails,
guardCtx,
);
}
private async executeValidatedToolCall(
params: ProcessToolCallParams,
builtTool: BuiltTool,
input: JSONValue,
inputRedacted: boolean,
guardrails: GuardrailRunner | undefined,
guardCtx: ReturnType<GuardrailRunner['toolCallContext']> | undefined,
): Promise<ToolCallOutcome> {
@@ -234,11 +251,16 @@ export class ToolCallRunner {
'[Tool call canceled because the run stopped]',
);
}
// A guardrail refusal is runtime-authored text: it reaches the model
// plainly even for untrusted tools, matching the before-stage stop.
if (error instanceof GuardrailStopError) {
return await this.toolError(params, error);
}
return await this.toolError(params, error, builtTool);
}
if (isSuspendedToolResult(toolResult)) {
return await this.buildSuspendedOutcome(params, builtTool, toolResult);
return await this.buildSuspendedOutcome(params, builtTool, toolResult, input, inputRedacted);
}
return await this.buildSuccessOutcome(params, builtTool, input, toolResult);
@@ -490,11 +512,15 @@ export class ToolCallRunner {
// Final result only: a call that suspended reports once,
// after resume. The after-stage check runs inside the span
// so a refused result is recorded as the refusal, never as
// span output; the throw becomes a tool error upstream.
// span output; the throw becomes a tool error upstream. An
// after-stage redact returns the rewritten result instead.
if (guardrails && guardCtx && !isSuspendedToolResult(result)) {
const stop = await guardrails.afterTool(guardCtx, result);
if (stop) {
throw new Error(`Tool result blocked by guardrail: ${stop.code}`);
const outcome = await guardrails.afterTool(guardCtx, result);
if (outcome && 'stop' in outcome) {
throw new GuardrailStopError('after', outcome.stop.code);
}
if (outcome && 'redacted' in outcome) {
return outcome.redacted;
}
}
return result;
@@ -507,6 +533,8 @@ export class ToolCallRunner {
params: ProcessToolCallParams,
builtTool: BuiltTool,
toolResult: SuspendedToolResult,
input: JSONValue,
inputRedacted: boolean,
): Promise<ToolCallOutcome> {
if (builtTool.suspendSchema) {
const parseResult = await parseWithSchema(builtTool.suspendSchema, toolResult.payload);
@@ -527,6 +555,10 @@ export class ToolCallRunner {
}
return {
outcome: 'suspended',
// The input the tool received, redactions included, so the
// executor can persist the redacted input instead of the original.
input,
inputRedacted,
payload: toolResult.payload,
resumeSchema,
...(toolResult.continuation !== undefined ? { continuation: toolResult.continuation } : {}),
@@ -101,4 +101,17 @@ describe('Agent MCP validation', () => {
expect(new Set(config.tools?.map((tool) => tool.name)).size).toBe(2);
});
it('lists MCP tools with the names that the built agent uses', async () => {
const agent = new Agent('listed-mcp-tools')
.model(fakeModel)
.instructions('test')
.mcp(makeMcpClient('foo bar'))
.mcp(makeMcpClient('foo_bar'));
const config = await buildAgentConfig(agent);
const listed = await agent.listMcpTools();
expect(listed.map((tool) => tool.name)).toEqual(config.tools?.map((tool) => tool.name));
});
});
+10 -3
View File
@@ -725,6 +725,15 @@ export class Agent implements BuiltAgent, AgentBuilder {
* hosts can show the user that an MCP server was unavailable without
* aborting inference.
*/
/**
* Resolve the tools of every attached MCP client, with the names that the
* built agent gives them. Servers that fail to connect are skipped.
*/
async listMcpTools(): Promise<BuiltTool[]> {
const mcpToolLists = await Promise.all(this.mcpClients.map(async (c) => await c.listTools()));
return ensureUniqueMcpToolNames(mcpToolLists.flat());
}
getMcpConnectionFailures(): McpConnectionFailedEvent[] {
return [
...this.mcpClients.flatMap((c) => [...c.getConnectionFailures()]),
@@ -1129,9 +1138,7 @@ export class Agent implements BuiltAgent, AgentBuilder {
);
}
// Resolve tools from all MCP clients.
const mcpToolLists = await Promise.all(this.mcpClients.map(async (c) => await c.listTools()));
const mcpTools = ensureUniqueMcpToolNames(mcpToolLists.flat());
const mcpTools = await this.listMcpTools();
const mcpConnectionFailures = this.getMcpConnectionFailures();
// Detect collisions between direct, deferred, and MCP tools.
+3
View File
@@ -243,5 +243,8 @@ export type {
GuardrailModelCallContext,
GuardrailToolCallContext,
GuardrailDecision,
GuardrailModelCallDecision,
GuardrailNotice,
GuardrailStop,
GuardrailToolCallOutcome,
} from './sdk/guardrail';
@@ -48,6 +48,19 @@ export type ToolCallOutcome =
payload: unknown;
resumeSchema: JSONSchema7;
continuation?: JSONValue;
/**
* The input the tool actually received, after any before-stage
* guardrail redaction. The executor persists it with the
* suspension when a redaction rewrote it, so a resumed call keeps
* the redacted input instead of the original.
*/
input: JSONValue;
/**
* A before-stage guardrail rewrote `input`, so the value is
* already schema-validated and must not be re-validated on
* resume — the mask can legitimately break the input schema.
*/
inputRedacted: boolean;
}
| {
outcome: 'cancelled';
@@ -135,6 +148,8 @@ export interface ProcessToolCallParams extends ToolCallIdentity {
countToolCall?: boolean;
/** The call already suspended, so `beforeTool` already ran. */
previouslySuspended?: boolean;
/** The checkpointed input was validated before a guardrail redacted it, so validation is skipped. */
inputRedacted?: boolean;
/** Checkpointed suspend payload of the tool call being resumed. */
suspendPayload?: unknown;
/** Checkpointed private continuation of the tool call being resumed. */
@@ -557,6 +557,11 @@ export type PendingToolCall = {
resumeSchema: JsonSchema7Type;
continuation?: JSONValue;
runId: string;
/**
* If the input was schema-validated and then rewritten by a
* before-stage guardrail redaction.
*/
inputRedacted?: true;
}
| {
suspended: false;
@@ -12,7 +12,17 @@ export interface BuiltGuardrail {
/** @internal */ readonly _config: Record<string, unknown>;
}
export type GuardrailDecision = { action: 'allow' } | { action: 'stop'; code: string };
export type GuardrailDecision =
| { action: 'allow' }
| { action: 'stop'; code: string }
| { action: 'redact'; code: string; value: unknown };
/**
* A model-call hook can only allow or stop: the model-call runner has no
* redact handling, so a redact there would silently send the unredacted
* request. Redaction belongs to the tool-call stages.
*/
export type GuardrailModelCallDecision = { action: 'allow' } | { action: 'stop'; code: string };
export type GuardrailStop = { code: string };
export type GuardrailModelCallSource = 'turn' | 'title' | 'memory';
@@ -36,11 +46,14 @@ export interface GuardrailToolCallContext {
}
/**
* Hooks around model and tool calls. A `before*` hook returns `undefined` or
* `allow` to continue, or `stop` to refuse the call.
* Hooks around model and tool calls. A tool-call hook returns `undefined` or
* `allow` to continue, `stop` to refuse the call, or `redact` to continue
* with the rewritten value: a before-stage redact rewrites the tool input,
* an after-stage redact rewrites the tool result. A model-call hook can only
* allow or stop.
*/
export interface ModelGuardrail {
before?(ctx: GuardrailModelCallContext): Promise<GuardrailDecision | undefined>;
before?(ctx: GuardrailModelCallContext): Promise<GuardrailModelCallDecision | undefined>;
after?(ctx: GuardrailModelCallContext, usage: TokenUsage | undefined): Promise<void>;
beforeTool?(ctx: GuardrailToolCallContext): Promise<GuardrailDecision | undefined>;
afterTool?(
@@ -49,6 +62,12 @@ export interface ModelGuardrail {
): Promise<GuardrailDecision> | Promise<void>;
}
/**
* What an after-stage tool check decided: stop the call, or continue with the
* redacted result.
*/
export type GuardrailToolCallOutcome = { stop: GuardrailStop } | { redacted: unknown };
/** Host-supplied on `ExecutionOptions`. The SDK never looks up settings. */
export interface GuardrailsOptions {
hooks: ModelGuardrail[];
@@ -60,4 +79,6 @@ export interface GuardrailsOptions {
export type GuardrailNotice = {
code: string;
agentId?: string;
/** Marks a non-blocking outcome so the session timeline can show it later. */
outcome?: 'redact' | 'approval';
};
@@ -1,12 +1,21 @@
import { runLLMValidation } from '../llm';
const runWith = (output: string) => ({
run: vi.fn().mockResolvedValue(output),
run: vi.fn().mockResolvedValue({ text: output }),
prompt: 'Test prompt',
threshold: 0.7,
});
describe('runLLMValidation', () => {
it('supports adapters that return only model text', async () => {
const result = await runLLMValidation('test-guardrail', 'input', {
run: async () => '{"confidenceScore":0.9,"flagged":true}',
prompt: 'check',
threshold: 0.5,
});
expect(result).toMatchObject({ tripwireTriggered: true, executionFailed: false });
});
describe('output format validation', () => {
it('should validate output contains only expected fields', async () => {
const result = await runLLMValidation(
@@ -0,0 +1,70 @@
import { redactMatches } from '../mask';
import type { GuardrailResult } from '../types';
const result = (info: GuardrailResult['info']): GuardrailResult => ({
guardrailName: 'test',
tripwireTriggered: true,
info,
});
describe('redactMatches', () => {
it('returns the text unchanged when no check reported matches', () => {
expect(redactMatches('hello', [])).toBe('hello');
expect(redactMatches('hello', [result({})])).toBe('hello');
expect(redactMatches('hello', [result({ maskEntities: {} })])).toBe('hello');
});
it('masks maskEntities with their type token', () => {
const masked = redactMatches('Email john@example.com or call 555-1234 about SSN 111-22-3333', [
result({
maskEntities: {
EMAIL_ADDRESS: ['john@example.com'],
PHONE_NUMBER: ['555-1234'],
US_SSN: ['111-22-3333'],
},
}),
]);
expect(masked).toBe('Email <EMAIL_ADDRESS> or call <PHONE_NUMBER> about SSN <US_SSN>');
});
it('merges matches from several results, longest match first', () => {
const masked = redactMatches('Visit https://example.com/a and https://example.com/a/b', [
result({ maskEntities: { URL: ['https://example.com/a/b', 'https://example.com/a'] } }),
result({ maskEntities: { HOST: ['example.com'] } }),
]);
expect(masked).toBe('Visit <URL> and <URL>');
});
it('masks matchedKeywords with a KEYWORD token', () => {
const masked = redactMatches('The secret plans are internal only', [
result({ matchedKeywords: ['secret', 'internal'] }),
]);
expect(masked).toBe('The <KEYWORD> plans are <KEYWORD> only');
});
it('ignores non-string keyword entries', () => {
const masked = redactMatches('unchanged', [result({ matchedKeywords: [42, null] })]);
expect(masked).toBe('unchanged');
});
it('masks every casing of a matched keyword, not only the reported one', () => {
const masked = redactMatches('The Secret plan and a secret key', [
result({ matchedKeywords: ['Secret'] }),
]);
expect(masked).toBe('The <KEYWORD> plan and a <KEYWORD> key');
});
it('treats regex metacharacters literally', () => {
const masked = redactMatches('Key a.b*c present', [
result({ maskEntities: { SECRET: ['a.b*c'] } }),
]);
expect(masked).toBe('Key <SECRET> present');
});
it('masks a literal __proto__ keyword', () => {
const masked = redactMatches('value __proto__ and secret', [
result({ matchedKeywords: ['__proto__'] }),
]);
expect(masked).toBe('value <KEYWORD> and secret');
});
});
@@ -1,6 +1,8 @@
export type {
GuardrailResult,
GuardrailModelRun,
GuardrailModelRunner,
GuardrailModelUsage,
LlmGuardrailConfig,
CheckFn,
CreateCheckFn,
@@ -21,3 +23,4 @@ export {
createTopicalAlignmentCheckFn,
TOPICAL_ALIGNMENT_SYSTEM_PROMPT,
} from './checks/topical-alignment';
export { redactMatches } from './mask';
@@ -91,7 +91,8 @@ async function runLLM(
const fullPrompt = buildFullPrompt(prompt, outputParser.getFormatInstructions(), systemMessage);
try {
const text = await run(fullPrompt, inputText);
const result = await run(fullPrompt, inputText);
const text = typeof result === 'string' ? result : result.text;
const { confidenceScore, flagged } = await outputParser.parse(text);
// Validate output consistency
@@ -0,0 +1,51 @@
import type { GuardrailResult } from './types';
/** Escapes regex metacharacters so a match replaces literally. Same form as the keywords check. */
const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
/**
* Replaces the matches the guardrail checks reported with typed mask tokens:
* `maskEntities` become `<TYPE>` and `matchedKeywords` become `<KEYWORD>`.
* Longer matches replace first, so a shorter match cannot leave a partial of a
* longer one behind. Replacement treats every character literally, so a match
* cannot inject regex syntax.
*/
export function redactMatches(text: string, results: GuardrailResult[]): string {
// A null prototype keeps a literal `__proto__` keyword from hitting the
// inherited setter instead of creating an entry.
const entities: Record<string, string> = Object.create(null);
const keywords: Record<string, string> = Object.create(null);
for (const result of results) {
for (const [entityType, values] of Object.entries(result.info?.maskEntities ?? {})) {
for (const value of values) {
entities[value] = `<${entityType}>`;
}
}
const matched = result.info?.matchedKeywords;
if (Array.isArray(matched)) {
for (const keyword of matched) {
if (typeof keyword === 'string') keywords[keyword] = '<KEYWORD>';
}
}
}
if (Object.keys(entities).length === 0 && Object.keys(keywords).length === 0) return text;
let masked = text;
// Longest matches replace first, so a shorter match cannot leave a partial
// of a longer one behind.
const entityEntries = Object.entries(entities).sort((a, b) => b[0].length - a[0].length);
for (const [match, token] of entityEntries) {
if (masked.includes(match)) {
masked = masked.split(match).join(token);
}
}
// The keyword check matches case-insensitively and reports only the
// first-seen casing, so replacement must ignore case too or the other
// spellings of a flagged word survive. Without word boundaries this can
// over-mask a word that contains the keyword, which is the safe direction.
const keywordEntries = Object.entries(keywords).sort((a, b) => b[0].length - a[0].length);
for (const [keyword, token] of keywordEntries) {
masked = masked.replace(new RegExp(escapeRegExp(keyword), 'giu'), token);
}
return masked;
}
@@ -18,11 +18,40 @@ export interface GuardrailResult<TInfo extends Record<string, unknown> = Record<
}
/**
* Model-agnostic seam for LLM guardrails: the full system prompt goes in,
* the raw model text comes out. Adapters wrap a concrete model client
* (LangChain in the Guardrails node, AI SDK in the agent runtime).
* Token counts from one guardrail model call. The shape matches the AI SDK
* usage object that the agent runtime prices, so a host can charge the call
* without depending on a model client.
*/
export type GuardrailModelRunner = (systemPrompt: string, input: string) => Promise<string>;
export type GuardrailModelUsage = {
inputTokens?: number;
outputTokens?: number;
totalTokens?: number;
inputTokenDetails?: {
noCacheTokens?: number;
cacheReadTokens?: number;
cacheWriteTokens?: number;
};
outputTokenDetails?: {
reasoningTokens?: number;
};
};
/** Text the check parses, plus the token counts of the model call when known. */
export type GuardrailModelRun = {
text: string;
usage?: GuardrailModelUsage;
};
/**
* Model-agnostic seam for LLM guardrails: the full system prompt goes in,
* the raw model text and its token usage come out. Adapters wrap a concrete
* model client (LangChain in the Guardrails node, AI SDK in the agent runtime).
* An adapter that cannot read usage returns the text only.
*/
export type GuardrailModelRunner = (
systemPrompt: string,
input: string,
) => Promise<string | GuardrailModelRun>;
export type LlmGuardrailConfig = {
run: GuardrailModelRunner;
@@ -1,9 +1,11 @@
import {
AgentJsonConfigSchema,
RunnableAgentJsonConfigSchema,
findToolGuardrailRefIssues,
findVectorStoreToolNameCollisions,
formatAgentConfigZodError,
McpOAuth2CredentialTypeSchema,
TOOL_GUARDRAIL_RESPONSES,
resolveAgentSandboxEgressEnabled,
} from '../agent-json-config.schema';
@@ -952,9 +954,9 @@ describe('AgentJsonConfigSchema — config.guardrails.tools', () => {
blockUserinfo: true,
allowSubdomains: false,
},
{ kind: 'jailbreak' },
{ kind: 'jailbreak', prompt: 'Detect jailbreaks', threshold: 0.7 },
{ kind: 'nsfw', threshold: 0 },
{ kind: 'jailbreak', stage: 'after' },
{ kind: 'jailbreak', stage: 'after', prompt: 'Detect jailbreaks', threshold: 0.7 },
{ kind: 'nsfw', stage: 'after', threshold: 0 },
{ kind: 'topicalAlignment', prompt: 'Stay on topic', threshold: 1 },
{ kind: 'workflow', workflowId: 'wf-1' },
])('accepts a valid %s guardrail', (guardrail) => {
@@ -1056,6 +1058,175 @@ describe('AgentJsonConfigSchema — config.guardrails.tools', () => {
);
}
});
it('accepts an explicit stage outside the kind preset: an older config keeps working', () => {
const result = parseGuardrails([
{ ...baseGuardrail, kind: 'pii', type: 'all', stage: 'after' },
{ ...baseGuardrail, kind: 'jailbreak', stage: 'before', id: 'guardrail_2' },
]);
expect(result.success).toBe(true);
});
it('accepts an absent response and presets it from the kind table', () => {
const result = parseGuardrails([
{ ...baseGuardrail, kind: 'pii', type: 'all' },
{ ...baseGuardrail, kind: 'jailbreak', stage: 'after', id: 'guardrail_2' },
]);
expect(result.success).toBe(true);
if (result.success) {
expect(result.data.config?.guardrails?.tools?.[0]?.response).toBeUndefined();
}
// The runtime and the modal resolve an absent response from the preset.
expect(TOOL_GUARDRAIL_RESPONSES.pii.default).toBe('redact');
expect(TOOL_GUARDRAIL_RESPONSES.keywords.default).toBe('block');
expect(TOOL_GUARDRAIL_RESPONSES.jailbreak.default).toBe('block');
});
it('rejects a response the kind does not allow', () => {
expect(
parseGuardrails([{ ...baseGuardrail, kind: 'jailbreak', stage: 'after', response: 'redact' }])
.success,
).toBe(false);
expect(
parseGuardrails([{ ...baseGuardrail, kind: 'keywords', keywords: ['a'], response: 'warn' }])
.success,
).toBe(false);
});
it('rejects review without a configuration and a configuration without review', () => {
const reviewless = parseGuardrails([
{ ...baseGuardrail, kind: 'keywords', keywords: ['a'], response: 'approval' },
]);
expect(reviewless.success).toBe(false);
if (!reviewless.success) {
expect(reviewless.error.errors[0].message).toBe(
'Send to review requires a human-review configuration',
);
}
const misconfigured = parseGuardrails([
{
...baseGuardrail,
kind: 'keywords',
keywords: ['a'],
response: 'block',
approvalConfigurationId: 'config-1',
},
]);
expect(misconfigured.success).toBe(false);
if (!misconfigured.success) {
expect(misconfigured.error.errors[0].message).toBe(
'A human-review configuration only applies to send to review',
);
}
});
it('rejects a review configuration that is not one of the agent configurations', () => {
const result = AgentJsonConfigSchema.safeParse({
...minimalConfig,
hitlConfigurations: [
{ id: 'config-1', name: 'Review', method: 'workflow', workflowId: 'wf-9' },
],
config: {
guardrails: {
tools: [
{
...baseGuardrail,
kind: 'keywords',
keywords: ['a'],
response: 'approval',
approvalConfigurationId: 'config-missing',
},
],
},
},
});
expect(result.success).toBe(false);
if (!result.success) {
expect(result.error.errors[0].message).toBe(
'Select a human-review configuration of this agent',
);
}
});
it('accepts a review guardrail pointing at an agent configuration', () => {
const result = AgentJsonConfigSchema.safeParse({
...minimalConfig,
hitlConfigurations: [
{ id: 'config-1', name: 'Review', method: 'workflow', workflowId: 'wf-9' },
],
config: {
guardrails: {
tools: [
{
...baseGuardrail,
kind: 'keywords',
keywords: ['a'],
response: 'approval',
approvalConfigurationId: 'config-1',
},
],
},
},
});
expect(result.success).toBe(true);
});
it('rejects a review guardrail pointing at a channel configuration', () => {
const result = AgentJsonConfigSchema.safeParse({
...minimalConfig,
hitlConfigurations: [
{
id: 'config-1',
name: 'Slack approval',
method: 'channel',
channel: 'slack',
credentialId: 'cred-1',
recipient: { kind: 'channel', id: 'C1', name: '#security' },
},
],
config: {
guardrails: {
tools: [
{
...baseGuardrail,
kind: 'keywords',
keywords: ['a'],
response: 'approval',
approvalConfigurationId: 'config-1',
},
],
},
},
});
expect(result.success).toBe(false);
if (!result.success) {
expect(result.error.errors[0].message).toBe(
'Send to review requires a workflow review; a channel review cannot receive guardrail flags',
);
}
});
it('rejects a dangling review reference on a runnable config too', () => {
const result = RunnableAgentJsonConfigSchema.safeParse({
...minimalConfig,
credential: 'cred-1',
config: {
guardrails: {
tools: [
{
...baseGuardrail,
kind: 'keywords',
keywords: ['a'],
response: 'approval',
approvalConfigurationId: 'config-missing',
},
],
},
},
});
expect(result.success).toBe(false);
});
});
describe('findToolGuardrailRefIssues', () => {
@@ -1083,6 +1254,7 @@ describe('findToolGuardrailRefIssues', () => {
kind: 'keywords',
id: 'g1',
stage: 'before',
response: 'block',
keywords: ['a'],
tools: [
{ type: 'workflow', workflowId: 'wf-1' },
@@ -1103,7 +1275,9 @@ describe('findToolGuardrailRefIssues', () => {
tools: configuredTools,
config: {
guardrails: {
tools: [{ kind: 'keywords', id: 'g1', stage: 'before', keywords: ['a'] }],
tools: [
{ kind: 'keywords', id: 'g1', stage: 'before', response: 'block', keywords: ['a'] },
],
},
},
});
@@ -1121,6 +1295,7 @@ describe('findToolGuardrailRefIssues', () => {
kind: 'nsfw',
id: 'g1',
stage: 'after',
response: 'block',
tools: [
{ type: 'workflow', workflowId: 'wf-1' },
{ type: 'workflow', workflowId: 'wf-missing' },
@@ -722,6 +722,134 @@ describe('sanitizeAgentJsonConfig', () => {
});
expect(AgentJsonConfigSchema.safeParse(sanitized).success).toBe(true);
});
it('heals a review guardrail whose configuration was deleted', () => {
const sanitized = sanitizeAgentJsonConfig({
...baseConfig,
config: {
guardrails: {
tools: [
{
kind: 'keywords',
id: 'g1',
keywords: ['secret'],
response: 'approval',
approvalConfigurationId: 'deleted-config',
},
],
},
},
});
expect(sanitized).toEqual({
...baseConfig,
config: {
guardrails: {
// The review can no longer route, so the guardrail falls back
// to blocking and drops the dead reference.
tools: [{ kind: 'keywords', id: 'g1', keywords: ['secret'], response: 'block' }],
},
},
});
expect(AgentJsonConfigSchema.safeParse(sanitized).success).toBe(true);
});
it('heals a approval response without a configuration', () => {
const sanitized = sanitizeAgentJsonConfig({
...baseConfig,
config: {
guardrails: {
tools: [{ kind: 'pii', id: 'g1', type: 'all', response: 'approval' }],
},
},
});
expect(sanitized).toEqual({
...baseConfig,
config: {
guardrails: {
tools: [{ kind: 'pii', id: 'g1', type: 'all', response: 'block' }],
},
},
});
expect(AgentJsonConfigSchema.safeParse(sanitized).success).toBe(true);
});
it('keeps a review guardrail whose configuration still exists', () => {
const config = {
...baseConfig,
hitlConfigurations: [
{ id: 'config-1', name: 'Review', method: 'workflow', workflowId: 'wf-9' },
],
config: {
guardrails: {
tools: [
{
kind: 'keywords',
id: 'g1',
keywords: ['secret'],
response: 'approval',
approvalConfigurationId: 'config-1',
},
],
},
},
};
expect(sanitizeAgentJsonConfig(config)).toEqual(config);
expect(AgentJsonConfigSchema.safeParse(sanitizeAgentJsonConfig(config)).success).toBe(true);
});
it('heals a review guardrail pointing at a channel configuration', () => {
const sanitized = sanitizeAgentJsonConfig({
...baseConfig,
hitlConfigurations: [
{
id: 'config-1',
name: 'Slack approval',
method: 'channel',
channel: 'slack',
credentialId: 'cred-1',
recipient: { kind: 'channel', id: 'C1', name: '#security' },
},
],
config: {
guardrails: {
tools: [
{
kind: 'keywords',
id: 'g1',
keywords: ['secret'],
response: 'approval',
approvalConfigurationId: 'config-1',
},
],
},
},
});
// A channel destination cannot receive guardrail flags, so the
// guardrail falls back to blocking and drops the reference.
expect(sanitized).toEqual({
...baseConfig,
hitlConfigurations: [
{
id: 'config-1',
name: 'Slack approval',
method: 'channel',
channel: 'slack',
credentialId: 'cred-1',
recipient: { kind: 'channel', id: 'C1', name: '#security' },
},
],
config: {
guardrails: {
tools: [{ kind: 'keywords', id: 'g1', keywords: ['secret'], response: 'block' }],
},
},
});
expect(AgentJsonConfigSchema.safeParse(sanitized).success).toBe(true);
});
});
describe('sanitizeAgentSkillBodies', () => {
@@ -4,6 +4,7 @@ import { describe, expect, it } from 'vitest';
import {
INCOMPATIBLE_WORKFLOW_TOOL_BODY_NODE_TYPES,
SUPPORTED_WORKFLOW_TOOL_TRIGGERS,
getGuardrailCheckWorkflowIncompatibilityReason,
getWorkflowToolIncompatibilityReason,
} from '../types';
@@ -132,3 +133,54 @@ describe('getWorkflowToolIncompatibilityReason', () => {
});
});
});
describe('getGuardrailCheckWorkflowIncompatibilityReason', () => {
it('accepts a decision-trigger workflow that the tool check rejects', () => {
const decisionWorkflow = wf('n8n-nodes-base.agentDecisionTrigger', 'n8n-nodes-base.set');
expect(getWorkflowToolIncompatibilityReason(decisionWorkflow)).toEqual({
reason: 'no_supported_trigger',
});
expect(getGuardrailCheckWorkflowIncompatibilityReason(decisionWorkflow)).toBeNull();
});
it('still accepts the tool trigger', () => {
expect(getGuardrailCheckWorkflowIncompatibilityReason(wf(compatibleTrigger))).toBeNull();
});
it('keeps the incompatible body node rules', () => {
const result = getGuardrailCheckWorkflowIncompatibilityReason(
wfNamed(
[
{ type: 'n8n-nodes-base.agentDecisionTrigger', name: 'Trigger' },
{ type: incompatibleBodyNode, name: 'Form' },
],
link('Trigger', 'Form'),
),
);
expect(result).toEqual({
reason: 'incompatible_nodes',
nodeTypes: [incompatibleBodyNode],
});
});
it('checks reachability from the decision trigger as the entry point', () => {
const result = getGuardrailCheckWorkflowIncompatibilityReason(
wfNamed(
[
{ type: 'n8n-nodes-base.agentDecisionTrigger', name: 'Trigger' },
{ type: 'n8n-nodes-base.set', name: 'Set' },
{ type: 'n8n-nodes-base.cronTrigger', name: 'Cron' },
{ type: incompatibleBodyNode, name: 'Form' },
],
{ ...link('Trigger', 'Set'), ...link('Cron', 'Form') },
),
);
expect(result).toBeNull();
});
it('returns no_supported_trigger without any known entry trigger', () => {
expect(
getGuardrailCheckWorkflowIncompatibilityReason(wf('n8n-nodes-base.cronTrigger')),
).toEqual({ reason: 'no_supported_trigger' });
});
});
@@ -555,6 +555,12 @@ const toolGuardrailBaseShape = {
stage: z.enum(['before', 'after']).optional(),
/** Covers every tool when absent. At least one ref when present. */
tools: z.array(ToolGuardrailToolRefSchema).min(1).optional(),
/**
* The human-review configuration the `approval` response routes flagged
* content to. Required for `approval`, rejected for every other response.
* Refers to an entry of the agent's `hitlConfigurations`.
*/
approvalConfigurationId: z.string().min(1).optional(),
};
const modelToolGuardrailShape = {
@@ -562,6 +568,50 @@ const modelToolGuardrailShape = {
threshold: z.number().min(0).max(1).optional(),
};
export type ToolGuardrailResponse = 'block' | 'redact' | 'approval';
/**
* Stage scope per kind: absent `stage` means these stages, so a kind cannot
* run outside its scope. Single source for the backend hook builder and the
* builder modal presets.
*/
export const TOOL_GUARDRAIL_STAGE_SCOPE: Record<
AgentToolGuardrailKind,
ReadonlyArray<'before' | 'after'>
> = {
keywords: ['before', 'after'],
pii: ['before'],
secretKeys: ['before'],
urls: ['before'],
jailbreak: ['after'],
nsfw: ['after'],
topicalAlignment: ['before', 'after'],
workflow: ['before'],
};
/**
* Response presets per kind: the agreed default and the allowed alternatives.
* Absent `response` means the kind's default; the schema rejects a response
* the kind does not allow.
*/
export const TOOL_GUARDRAIL_RESPONSES = {
keywords: { default: 'block', allowed: ['block', 'redact', 'approval'] },
pii: { default: 'redact', allowed: ['redact', 'block', 'approval'] },
secretKeys: { default: 'redact', allowed: ['redact', 'block', 'approval'] },
urls: { default: 'block', allowed: ['block', 'redact', 'approval'] },
jailbreak: { default: 'block', allowed: ['block', 'approval'] },
nsfw: { default: 'block', allowed: ['block', 'approval'] },
topicalAlignment: { default: 'block', allowed: ['block', 'approval'] },
workflow: { default: 'block', allowed: ['block', 'approval'] },
} as const;
const toolGuardrailResponseSchema = <K extends keyof typeof TOOL_GUARDRAIL_RESPONSES>(kind: K) =>
// Optional: the kind's preset in TOOL_GUARDRAIL_RESPONSES is the default
// the runtime and the modal resolve for an absent response.
z
.enum(TOOL_GUARDRAIL_RESPONSES[kind].allowed)
.optional();
/**
* A guardrail running before or after the referenced tools. Pattern kinds
* run locally; model kinds call a model with an optional prompt and
@@ -571,22 +621,26 @@ export const ToolGuardrailConfigSchema = z.discriminatedUnion('kind', [
z.object({
kind: z.literal('keywords'),
...toolGuardrailBaseShape,
response: toolGuardrailResponseSchema('keywords'),
keywords: z.array(z.string().min(1)).min(1),
}),
z.object({
kind: z.literal('pii'),
...toolGuardrailBaseShape,
response: toolGuardrailResponseSchema('pii'),
type: z.enum(['all', 'selected']),
entities: z.array(z.enum(TOOL_GUARDRAIL_PII_ENTITIES)).min(1).optional(),
}),
z.object({
kind: z.literal('secretKeys'),
...toolGuardrailBaseShape,
response: toolGuardrailResponseSchema('secretKeys'),
permissiveness: z.enum(['strict', 'balanced', 'permissive']),
}),
z.object({
kind: z.literal('urls'),
...toolGuardrailBaseShape,
response: toolGuardrailResponseSchema('urls'),
allowedUrls: z.array(z.string().min(1)).optional(),
allowedSchemes: z.array(z.string().min(1)).optional(),
blockUserinfo: z.boolean().optional(),
@@ -595,17 +649,25 @@ export const ToolGuardrailConfigSchema = z.discriminatedUnion('kind', [
z.object({
kind: z.literal('jailbreak'),
...toolGuardrailBaseShape,
response: toolGuardrailResponseSchema('jailbreak'),
...modelToolGuardrailShape,
}),
z.object({
kind: z.literal('nsfw'),
...toolGuardrailBaseShape,
response: toolGuardrailResponseSchema('nsfw'),
...modelToolGuardrailShape,
}),
z.object({ kind: z.literal('nsfw'), ...toolGuardrailBaseShape, ...modelToolGuardrailShape }),
z.object({
kind: z.literal('topicalAlignment'),
...toolGuardrailBaseShape,
response: toolGuardrailResponseSchema('topicalAlignment'),
...modelToolGuardrailShape,
}),
z.object({
kind: z.literal('workflow'),
...toolGuardrailBaseShape,
response: toolGuardrailResponseSchema('workflow'),
/** The check workflow, run before each covered call. */
workflowId: z.string().min(1),
}),
@@ -760,7 +822,9 @@ export const AgentJsonConfigBaseSchema = z.object({
}
// The workflow kind registers before-only, so an
// after-stage check workflow cannot run: reject the
// config instead of silently dropping the hook.
// config instead of silently dropping the hook. Every
// other kind honors an explicit stage, so an older
// config saved with one stays valid.
if (guardrail.kind === 'workflow' && guardrail.stage === 'after') {
ctx.addIssue({
code: z.ZodIssueCode.custom,
@@ -768,6 +832,23 @@ export const AgentJsonConfigBaseSchema = z.object({
message: 'A workflow guardrail cannot run after a tool call',
});
}
// The approval response routes flagged content to a
// human-review configuration; no other response has
// anywhere to route it to.
if (guardrail.response === 'approval' && !guardrail.approvalConfigurationId) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: [index, 'approvalConfigurationId'],
message: 'Send to review requires a human-review configuration',
});
}
if (guardrail.response !== 'approval' && guardrail.approvalConfigurationId) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: [index, 'approvalConfigurationId'],
message: 'A human-review configuration only applies to send to review',
});
}
}
})
.optional(),
@@ -777,6 +858,44 @@ export const AgentJsonConfigBaseSchema = z.object({
.optional(),
});
/**
* An approval-response guardrail routes through a human-review configuration of
* the same agent, so the referenced id must exist on the document and the
* configuration must be able to receive the flagged content. Shared by
* the draft and runnable schemas: a runnable or sub-agent config must not
* carry a dangling reference either.
*/
function checkApprovalConfigurationReferences(
config: z.infer<typeof AgentJsonConfigBaseSchema>,
ctx: z.RefinementCtx,
): void {
const configurations = new Map(
(config.hitlConfigurations ?? []).map((entry) => [entry.id, entry]),
);
for (const [index, guardrail] of (config.config?.guardrails?.tools ?? []).entries()) {
if (!guardrail.approvalConfigurationId) continue;
const configuration = configurations.get(guardrail.approvalConfigurationId);
if (!configuration) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['config', 'guardrails', 'tools', index, 'approvalConfigurationId'],
message: 'Select a human-review configuration of this agent',
});
continue;
}
// A channel destination has no notify-only delivery, so an approval
// routed there would neither block, redact, nor notify.
if (configuration.method === 'channel') {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['config', 'guardrails', 'tools', index, 'approvalConfigurationId'],
message:
'Send to review requires a workflow review; a channel review cannot receive guardrail flags',
});
}
}
}
export const AgentJsonConfigSchema = AgentJsonConfigBaseSchema.superRefine((config, ctx) => {
if (config.credential?.trim() && isDraftAgentConfig(config)) {
ctx.addIssue({
@@ -785,6 +904,7 @@ export const AgentJsonConfigSchema = AgentJsonConfigBaseSchema.superRefine((conf
message: 'A credential requires a model to be set',
});
}
checkApprovalConfigurationReferences(config, ctx);
});
export const RunnableAgentJsonConfigSchema = AgentJsonConfigBaseSchema.extend({
@@ -792,7 +912,7 @@ export const RunnableAgentJsonConfigSchema = AgentJsonConfigBaseSchema.extend({
credential: z.string().refine((value) => value.trim().length > 0, {
message: 'Credential is required',
}),
});
}).superRefine(checkApprovalConfigurationReferences);
export type AgentJsonConfig = z.infer<typeof AgentJsonConfigSchema>;
+12 -1
View File
@@ -31,7 +31,10 @@ import {
createAgentSkillSchema,
} from './agent-skill.schema';
import { agentTaskSchema } from './agent-task.schema';
import { agentChatModeSchema } from '../schemas/agent-safe-testing.schema';
import {
agentChatModeSchema,
agentTestRunCommitRequestSchema,
} from '../schemas/agent-safe-testing.schema';
import { alsoNullable } from '../dto/openapi-nullable';
import { workflowParentFolderPublicSchema } from '../dto/workflows/workflow-public.dto';
import {
@@ -1116,6 +1119,9 @@ export class AgentChatQueueReorderDto extends Z.class({
expectedQueueIds: z.array(z.string().regex(/^[1-9]\d*$/)).min(2),
}) {}
/** Request body to replay held write actions from a test run against real services. */
export class AgentTestRunCommitRequestDto extends Z.class(agentTestRunCommitRequestSchema.shape) {}
export class AgentTaskApprovalDto extends Z.class({
toolCallId: z.string().min(1),
resumeData: z.unknown(),
@@ -1271,4 +1277,9 @@ export class AgentTaskCancellationDto extends Z.class({
planId: z.string().uuid().toLowerCase().nullable(),
}) {}
/** Request body to reset the simulated world of one test chat. */
export class AgentTestRunResetDto extends Z.class({
sessionId: z.string().trim().min(1),
}) {}
export class AgentHitlOptionsQueryDto extends Z.class(AgentHitlOptionsQuerySchema.shape) {}
@@ -230,9 +230,54 @@ export function sanitizeAgentJsonConfig(raw: unknown): unknown {
}
}
healApprovalGuardrailReferences(sanitized);
return sanitized;
}
/**
* Heal approval guardrails whose human-review configuration is gone: deleting a
* configuration must not wedge every later save. A guardrail whose
* `approval` response can no longer route falls back to the blocking response
* and drops the unusable reference, so it keeps firing without a dead link.
* The runtime already treats an unroutable approval as a warn-and-skip, so
* `block` is the honest fallback: the guardrail still stops the call.
*/
function healApprovalGuardrailReferences(sanitized: Record<string, unknown>): void {
const config = sanitized.config;
if (!isRecord(config)) return;
const guardrails = config.guardrails;
if (!isRecord(guardrails) || !Array.isArray(guardrails.tools)) return;
const configurations = new Map(
(Array.isArray(sanitized.hitlConfigurations) ? sanitized.hitlConfigurations : [])
.filter((entry) => isRecord(entry) && typeof entry.id === 'string')
.map((entry) => [
(entry as Record<string, unknown>).id as string,
(entry as Record<string, unknown>).method,
]),
);
let healed = false;
const healedTools = guardrails.tools.map((tool) => {
if (!isRecord(tool)) return tool;
const approvalId = tool.approvalConfigurationId;
// An `approval` response with no configuration, any response with a
// configuration that no longer exists, and a configuration that cannot
// receive guardrail flags, are the reject paths; all heal to the
// blocking response.
const approvalWithoutTarget = tool.response === 'approval' && typeof approvalId !== 'string';
const danglingTarget = typeof approvalId === 'string' && !configurations.has(approvalId);
const channelTarget =
typeof approvalId === 'string' && configurations.get(approvalId) === 'channel';
if (!approvalWithoutTarget && !danglingTarget && !channelTarget) return tool;
healed = true;
const { approvalConfigurationId, ...rest } = tool;
return { ...rest, response: 'block' };
});
if (healed) guardrails.tools = healedTools;
}
/**
* Strip unknown fields from embedded skill bodies before strict Zod
* validation, so persisted bodies degrade gracefully as `agentSkillSchema`
+38 -3
View File
@@ -3,8 +3,10 @@ import { EXECUTE_WORKFLOW_TRIGGER_NODE_TYPE, getChildNodes, type IConnections }
import type { AgentApproval, AgentIntegrationSettings } from './agent-integration.schema';
import type { AgentJsonConfig } from './agent-json-config.schema';
import type { AgentPersonalisation } from './agent-personalisation';
import type { ToolCallSimulation } from '../schemas/agent-safe-testing.schema';
import type { AgentSkillReference } from './agent-skill.schema';
import type { AgentBackgroundJobSignal } from './background-job';
import { AGENT_DECISION_TRIGGER_NODE_TYPE } from './agent-hitl.schema';
import type { ProviderAttachmentCapabilities } from './provider-capabilities';
export type AgentActor = 'user' | 'builder' | 'mcp';
@@ -23,6 +25,17 @@ export interface AgentSessionPreviewAccess {
export const SUPPORTED_WORKFLOW_TOOL_TRIGGERS = [EXECUTE_WORKFLOW_TRIGGER_NODE_TYPE] as const;
/**
* Triggers a `workflow`-kind guardrail check may start with: the callable
* tool trigger, plus the decision trigger — a check reuses the decision
* request contract. Tools keep the stricter tool list: a decision-trigger
* workflow cannot be attached as an agent tool.
*/
export const SUPPORTED_GUARDRAIL_CHECK_TRIGGERS = [
...SUPPORTED_WORKFLOW_TOOL_TRIGGERS,
AGENT_DECISION_TRIGGER_NODE_TYPE,
] as const;
/** Display name of each supported trigger, keyed by node type so a rename is a one-line change. */
const WORKFLOW_TOOL_TRIGGER_DISPLAY_NAMES: Record<
(typeof SUPPORTED_WORKFLOW_TOOL_TRIGGERS)[number],
@@ -71,15 +84,35 @@ export function getWorkflowToolIncompatibilityReason(workflow: {
nodes?: Array<{ type: string; name: string; disabled?: boolean }>;
connections?: IConnections;
}): WorkflowToolIncompatibilityReason | null {
return getWorkflowIncompatibilityReason(workflow, SUPPORTED_WORKFLOW_TOOL_TRIGGERS);
}
/**
* Why a workflow can't run as a `workflow`-kind guardrail check. `null` means
* compatible. Same rules as the tool check, except the entry point may also
* be a decision trigger.
*/
export function getGuardrailCheckWorkflowIncompatibilityReason(workflow: {
nodes?: Array<{ type: string; name: string; disabled?: boolean }>;
connections?: IConnections;
}): WorkflowToolIncompatibilityReason | null {
return getWorkflowIncompatibilityReason(workflow, SUPPORTED_GUARDRAIL_CHECK_TRIGGERS);
}
function getWorkflowIncompatibilityReason(
workflow: {
nodes?: Array<{ type: string; name: string; disabled?: boolean }>;
connections?: IConnections;
},
entryTriggers: readonly string[],
): WorkflowToolIncompatibilityReason | null {
const nodes = workflow.nodes ?? [];
// Entry point the agent invokes — the first supported trigger in node
// order, matching the runtime `detectTriggerNode` selection. Runtime does
// not skip disabled triggers, so neither do we; this keeps the picker and
// the runtime from disagreeing on which subgraph executes.
const triggerNode = nodes.find((n) =>
(SUPPORTED_WORKFLOW_TOOL_TRIGGERS as readonly string[]).includes(n.type),
);
const triggerNode = nodes.find((n) => entryTriggers.includes(n.type));
// Only nodes reachable from the entry-point trigger run when the workflow
// is invoked as an agent tool. With no trigger (or no connections to
@@ -594,6 +627,8 @@ export interface AgentPersistedMessageContentPart {
key?: string;
/** Event payload of a `host-event` part. */
payload?: unknown;
/** How the tool call ran in a test run (safe testing). */
simulation?: ToolCallSimulation;
}
/** Platform user who wrote a turn in a shared integration thread. */
@@ -1,2 +0,0 @@
/** Boolean PostHog flag. Evaluate it for the instance (`company`) group. */
export const CREDENTIAL_DESCRIPTIONS_FLAG = '120_credential_descriptions';
@@ -17,9 +17,9 @@ export const credentialSharedPublicSchema = z.object({
});
export const credentialPublicSchema = publicApiCredentialResponseSchema.extend({
description: z.string().nullable().optional().openapi({
description: z.string().nullable().openapi({
example: 'Read-only key for the reporting database',
description: 'Present only when credential descriptions are enabled.',
description: 'Plain text description of the credential, or null.',
}),
resolverId: z.string().nullable(),
createdAt: z.string().datetime(),
@@ -56,8 +56,7 @@ export class CreateCredentialPublicDto extends Z.class({
name: z.string().openapi({ example: "Joe's Github Credentials" }),
description: credentialDescriptionSchema.optional().openapi({
example: 'Read-only key for the reporting database',
description:
'Plain text, up to 512 characters. A blank value is saved as null. Ignored when credential descriptions are disabled.',
description: 'Plain text, up to 512 characters. A blank value is saved as null.',
}),
type: z.string().openapi({ example: 'githubApi' }),
data: z.record(z.string(), z.unknown()).openapi({
@@ -96,7 +95,7 @@ export class UpdateCredentialPublicDto extends Z.class({
description: credentialDescriptionSchema.optional().openapi({
example: 'Read-only key for the reporting database',
description:
'Plain text, up to 512 characters. Send null or a blank value to clear it. Omit it to keep the stored value. Ignored when credential descriptions are disabled.',
'Plain text, up to 512 characters. Send null or a blank value to clear it. Omit it to keep the stored value.',
}),
type: z.string().optional().openapi({
example: 'githubApi',
@@ -0,0 +1,163 @@
import { EXECUTION_LIMIT_MAX_EXECUTIONS_CEILING } from '../../../schemas/execution-limit-settings.schema';
import {
ExecutionUsageDto,
toExecutionUsage,
type ExecutionUsageSource,
} from '../execution-usage.dto';
const DTO_KEYS = [
'periodUnit',
'periodStart',
'resetsAt',
'maxExecutions',
'workflowExecutions',
'remaining',
];
const makeUsage = (executions: number): ExecutionUsageSource => ({
period: {
unit: 'month',
firstDay: '2026-11-01',
resetsAt: new Date('2026-12-01T00:00:00.000Z'),
},
executions,
});
const valid = {
periodUnit: 'month',
periodStart: '2026-11-01',
resetsAt: '2026-12-01T00:00:00.000Z',
maxExecutions: 100,
workflowExecutions: 40,
remaining: 60,
};
describe('toExecutionUsage', () => {
describe('a scope with a limit', () => {
test('maps each field and calculates remaining', () => {
const result = toExecutionUsage(makeUsage(40), 100);
expect(result).toEqual({
periodUnit: 'month',
periodStart: '2026-11-01',
resetsAt: '2026-12-01T00:00:00.000Z',
maxExecutions: 100,
workflowExecutions: 40,
remaining: 60,
});
expect(ExecutionUsageDto.safeParse(result).success).toBe(true);
});
test('returns the full limit as remaining when no executions are counted', () => {
const result = toExecutionUsage(makeUsage(0), 100);
expect(result.workflowExecutions).toBe(0);
expect(result.remaining).toBe(100);
expect(ExecutionUsageDto.safeParse(result).success).toBe(true);
});
test('returns 0 as remaining when the executions equal the limit', () => {
const result = toExecutionUsage(makeUsage(100), 100);
expect(result.remaining).toBe(0);
expect(ExecutionUsageDto.safeParse(result).success).toBe(true);
});
});
describe('a scope with no limit', () => {
test('returns null for maxExecutions and remaining', () => {
const result = toExecutionUsage(makeUsage(40), null);
expect(result.maxExecutions).toBeNull();
expect(result.remaining).toBeNull();
expect(result.workflowExecutions).toBe(40);
expect(ExecutionUsageDto.safeParse(result).success).toBe(true);
});
});
describe('usage above the limit', () => {
test('returns 0 as remaining', () => {
const result = toExecutionUsage(makeUsage(150), 100);
expect(result.workflowExecutions).toBe(150);
expect(result.remaining).toBe(0);
expect(ExecutionUsageDto.safeParse(result).success).toBe(true);
});
test('accepts a count above the limit ceiling', () => {
const executions = EXECUTION_LIMIT_MAX_EXECUTIONS_CEILING + 10;
const result = toExecutionUsage(
makeUsage(executions),
EXECUTION_LIMIT_MAX_EXECUTIONS_CEILING,
);
expect(result.workflowExecutions).toBe(executions);
expect(result.remaining).toBe(0);
expect(ExecutionUsageDto.safeParse(result).success).toBe(true);
});
});
test('returns only the DTO fields', () => {
const source = {
scope: { type: 'instance' },
period: {
unit: 'week' as const,
firstDay: '2026-11-23',
lastDay: '2026-11-29',
resetsAt: new Date('2026-11-30T00:00:00.000Z'),
},
executions: 5,
lastCountedAt: new Date('2026-11-27T10:00:00.000Z'),
};
const result = toExecutionUsage(source, 10);
expect(Object.keys(result).sort()).toEqual([...DTO_KEYS].sort());
expect(result).toEqual({
periodUnit: 'week',
periodStart: '2026-11-23',
resetsAt: '2026-11-30T00:00:00.000Z',
maxExecutions: 10,
workflowExecutions: 5,
remaining: 5,
});
});
});
describe('ExecutionUsageDto', () => {
test('removes unknown fields on parse', () => {
const result = ExecutionUsageDto.parse({
...valid,
lastCountedAt: '2026-11-15T10:00:00.000Z',
extra: true,
});
expect(result).toEqual(valid);
expect(Object.keys(result).sort()).toEqual([...DTO_KEYS].sort());
});
test.each(DTO_KEYS)('rejects input without %s', (key) => {
const input: Record<string, unknown> = { ...valid };
delete input[key];
expect(ExecutionUsageDto.safeParse(input).success).toBe(false);
});
test.each([
{ field: 'periodUnit', value: 'year' },
{ field: 'periodStart', value: '2026-11-01T00:00:00.000Z' },
{ field: 'periodStart', value: '2026-02-30' },
{ field: 'resetsAt', value: '2026-12-01' },
{ field: 'maxExecutions', value: 0 },
{ field: 'maxExecutions', value: -1 },
{ field: 'maxExecutions', value: 1.5 },
{ field: 'maxExecutions', value: EXECUTION_LIMIT_MAX_EXECUTIONS_CEILING + 1 },
{ field: 'workflowExecutions', value: -1 },
{ field: 'workflowExecutions', value: 1.5 },
{ field: 'workflowExecutions', value: null },
{ field: 'remaining', value: -1 },
{ field: 'remaining', value: 1.5 },
])('rejects $field: $value', ({ field, value }) => {
expect(ExecutionUsageDto.safeParse({ ...valid, [field]: value }).success).toBe(false);
});
});
@@ -0,0 +1,62 @@
import '../../openapi-extend';
import { z } from 'zod';
import {
executionLimitMaxExecutionsSchema,
executionLimitPeriodUnitSchema,
type ExecutionLimitPeriodUnit,
} from '../../schemas/execution-limit-settings.schema';
import { Z } from '../../zod-class';
const executionUsageShape = {
periodUnit: executionLimitPeriodUnitSchema.openapi({
description: 'The period over which executions are counted.',
example: 'month',
}),
periodStart: z.string().date().openapi({
format: 'date',
description: 'The first UTC day of the current period.',
example: '2026-11-01',
}),
resetsAt: z.string().datetime().openapi({
description: 'Start of the next period, at 00:00 UTC.',
example: '2026-12-01T00:00:00.000Z',
}),
maxExecutions: executionLimitMaxExecutionsSchema.nullable().openapi({
description:
'Maximum executions allowed for the scope per period, or null when the scope has no limit.',
example: 100_000,
}),
workflowExecutions: z.number().int().min(0).openapi({
description: 'Workflow executions counted in the current period.',
example: 42_500,
}),
remaining: z.number().int().min(0).nullable().openapi({
description:
'Executions left before the limit is reached, never below 0, or null when the scope has no limit.',
example: 57_500,
}),
};
/** Read-only execution usage of a scope. Shared by the internal and the public API. */
export class ExecutionUsageDto extends Z.class(executionUsageShape) {}
/** Same structure as `ExecutionUsage` in the execution limits backend module. */
export type ExecutionUsageSource = {
period: { unit: ExecutionLimitPeriodUnit; firstDay: string; resetsAt: Date };
executions: number;
};
export function toExecutionUsage(
usage: ExecutionUsageSource,
maxExecutions: number | null,
): ExecutionUsageDto {
return {
periodUnit: usage.period.unit,
periodStart: usage.period.firstDay,
resetsAt: usage.period.resetsAt.toISOString(),
maxExecutions,
workflowExecutions: usage.executions,
remaining: maxExecutions === null ? null : Math.max(0, maxExecutions - usage.executions),
};
}
+10 -1
View File
@@ -187,13 +187,22 @@ export { UserPublicDto, UserListPublicDto, userPublicSchema } from './user/user-
export { CreateUsersPublicDto, InvitedUsersPublicDto } from './user/create-users-public.dto';
export { DeleteUserQueryPublicDto } from './user/delete-user-query-public.dto';
export {
ExecutionUsageDto,
toExecutionUsage,
type ExecutionUsageSource,
} from './execution-limits/execution-usage.dto';
export { CommunityRegisteredRequestDto } from './license/community-registered-request.dto';
export {
PullWorkFolderRequestDto,
AUTO_PUBLISH_MODE,
} from './source-control/pull-work-folder-request.dto';
export { PushWorkFolderRequestDto } from './source-control/push-work-folder-request.dto';
export {
PushWorkFolderRequestDto,
SOURCE_CONTROL_PUSH_REMOTE_AHEAD_REASON,
} from './source-control/push-work-folder-request.dto';
export { type GitCommitInfo } from './source-control/push-work-folder-response.dto';
export { SourceControlStatusQueryPublicDto } from './source-control/source-control-status-query-public.dto';
export { SourceControlStatusPublicDto } from './source-control/source-control-status-public.dto';
@@ -31,7 +31,7 @@ export const serializedCredentialSchema = z
id: z.string().min(1),
name: z.string().min(1),
type: z.string().min(1),
// Present only when the source instance has credential descriptions on.
// Absent in packages that older n8n versions exported.
description: credentialDescriptionSchema.optional(),
data: serializedCredentialDataSchema.optional(),
dataIsComplete: z.boolean().optional(),
@@ -7,7 +7,7 @@ export const exportPackageRequestFieldDocs = {
},
includePreferences: {
description:
'Include the shared Preferences of selected projects. Defaults to false. Instance Preferences require explicit preferenceIds. Requires package format 3 support on the destination.',
'Include the shared Preferences of selected projects. Defaults to false. Instance Preferences require explicit preferenceIds. Requires package format 2 support on the destination.',
},
agentIds: {
description: 'IDs of the agents to include. Requires the agents module.',
@@ -5,6 +5,11 @@ import { Z } from '../../zod-class';
export class PushWorkFolderRequestDto extends Z.class({
force: z.boolean().optional(),
/** Pushes files that differ from the remote. Does not force the git push. */
acceptConflicts: z.boolean().optional(),
commitMessage: z.string().optional(),
fileNames: z.array(SourceControlledFileSchema),
}) {}
/** `meta.reason` of the 409 error when the remote has commits the instance has not pulled. */
export const SOURCE_CONTROL_PUSH_REMOTE_AHEAD_REASON = 'remote-ahead';
@@ -5,5 +5,6 @@ import { Z } from '../../zod-class';
export class SourceControlPushConflictErrorPublicDto extends Z.class({
message: z.string(),
conflicts: z.array(SourceControlledFileSchema),
/** Only present when files have unresolved conflicts. A remote-ahead 409 has no file list. */
conflicts: z.array(SourceControlledFileSchema).optional(),
}) {}
@@ -218,6 +218,8 @@ export interface FrontendSettings {
hideUsagePage: boolean;
license: {
planName?: string;
/** License plan group, such as `trial` or `free`. */
planGroup?: string;
consumerId: string;
environment: 'development' | 'production' | 'staging';
};
+13 -4
View File
@@ -228,7 +228,6 @@ export {
updateCredentialDescriptionSchema,
UPDATE_CREDENTIAL_DESCRIPTION_TOOL_DESCRIPTION,
} from './schemas/credential-description.schema';
export { CREDENTIAL_DESCRIPTIONS_FLAG } from './constants/credential-descriptions';
export { EMPTY_CANVAS_GROUPS_FLAG } from './constants/empty-canvas-groups';
export type {
DependencyType,
@@ -456,6 +455,7 @@ export {
statusPayloadSchema,
runStartPayloadSchema,
runFinishPayloadSchema,
ASSISTANT_RUN_EVENT,
ASSISTANT_WORKFLOWS_ARCHIVED_EVENT,
workflowsArchivedPayloadSchema,
ASSISTANT_TRACE_EVENT,
@@ -568,6 +568,8 @@ export {
InstanceAiEventsQuery,
InstanceAiCorrectTaskRequest,
InstanceAiCloudBrowserReturnControlRequest,
type InstanceAiCloudBrowserReturnControlResponse,
type InstanceAiCloudBrowserLoginToSaveResponse,
InstanceAiEnsureThreadRequest,
InstanceAiPersistPendingAgentRequest,
instanceAiAgentAttachmentSchema,
@@ -917,9 +919,6 @@ export {
} from './schemas/evaluations.schema';
export {
MCP_APPS_FLAG,
MCP_APPS_VARIANT_CONTROL,
MCP_APPS_VARIANT_ENABLED,
MCP_AGENT_SCOPES,
MCP_SKILL_SCOPES,
MCP_PREFERENCE_SCOPES,
@@ -1178,6 +1177,11 @@ export {
type AgentChatMode,
toolTestKindSchema,
toolTestCapabilitySchema,
AGENT_TEST_RUN_MAX_HELD_ACTIONS,
agentTestRunCommitRequestSchema,
agentTestRunCommitActionStatusSchema,
agentTestRunCommitActionResultSchema,
agentTestRunCommitResponseSchema,
} from './schemas/agent-safe-testing.schema';
export type {
ToolCallRoute,
@@ -1187,5 +1191,10 @@ export type {
ToolTestability,
ToolTestKind,
ToolTestCapability,
AgentTestRunResetResponse,
AgentTestRunToolsResponse,
AgentTestRunCommitRequest,
AgentTestRunCommitActionStatus,
AgentTestRunCommitActionResult,
AgentTestRunCommitResponse,
} from './schemas/agent-safe-testing.schema';
@@ -1,4 +1,8 @@
import {
AGENT_TEST_RUN_MAX_HELD_ACTIONS,
agentTestRunCommitActionResultSchema,
agentTestRunCommitRequestSchema,
agentTestRunCommitResponseSchema,
toolCallEvidenceSchema,
toolCallSimulationSchema,
toolTestCapabilitySchema,
@@ -77,3 +81,68 @@ describe('toolTestCapabilitySchema', () => {
expect(toolTestCapabilitySchema.safeParse(capability).success).toBe(false);
});
});
describe('agentTestRunCommitRequestSchema', () => {
it('accepts a valid commit request with and without executionId', () => {
expect(
agentTestRunCommitRequestSchema.safeParse({
testChatId: 'chat-1',
actionIds: ['tc-1', 'tc-2'],
}).success,
).toBe(true);
expect(
agentTestRunCommitRequestSchema.safeParse({
testChatId: 'chat-1',
executionId: 'exec-1',
actionIds: ['tc-1'],
}).success,
).toBe(true);
});
it.each([
{ name: 'empty actionIds', body: { testChatId: 'chat-1', actionIds: [] } },
{ name: 'blank actionId', body: { testChatId: 'chat-1', actionIds: [''] } },
{ name: 'missing testChatId', body: { actionIds: ['tc-1'] } },
{ name: 'blank testChatId', body: { testChatId: '', actionIds: ['tc-1'] } },
{
name: 'blank executionId',
body: { testChatId: 'chat-1', executionId: '', actionIds: ['tc-1'] },
},
{
name: 'more actionIds than a test chat can hold',
body: {
testChatId: 'chat-1',
actionIds: Array.from(
{ length: AGENT_TEST_RUN_MAX_HELD_ACTIONS + 1 },
(_, index) => `tc-${index}`,
),
},
},
])('rejects $name', ({ body }) => {
expect(agentTestRunCommitRequestSchema.safeParse(body).success).toBe(false);
});
});
describe('agentTestRunCommitResponseSchema', () => {
it('accepts per-action done, failed, and already_committed results', () => {
const payload = {
committedAt: '2026-11-24T09:30:00.000Z',
results: [
{ actionId: 'tc-1', toolName: 'send_slack', status: 'done' },
{ actionId: 'tc-2', toolName: 'send_email', status: 'failed', error: 'Rate limited' },
{ actionId: 'tc-3', toolName: 'create_issue', status: 'already_committed' },
],
};
expect(agentTestRunCommitResponseSchema.safeParse(payload).success).toBe(true);
});
it('rejects an unknown action status', () => {
expect(
agentTestRunCommitActionResultSchema.safeParse({
actionId: 'tc-1',
toolName: 'send_slack',
status: 'pending',
}).success,
).toBe(false);
});
});
@@ -129,3 +129,37 @@ export type ToolTestability = ToolTestCapability['testability'];
export interface AgentTestRunToolsResponse {
tools: ToolTestCapability[];
}
export interface AgentTestRunResetResponse {
reset: boolean;
}
/** The most held write actions a test chat keeps, and so the most one commit can replay. */
export const AGENT_TEST_RUN_MAX_HELD_ACTIONS = 500;
/** Request body to replay held write actions from a test run against real services. */
export const agentTestRunCommitRequestSchema = z.object({
testChatId: z.string().min(1),
executionId: z.string().min(1).optional(),
/** Non-empty list of held tool call IDs to replay in order. */
actionIds: z.array(z.string().min(1)).min(1).max(AGENT_TEST_RUN_MAX_HELD_ACTIONS),
});
export type AgentTestRunCommitRequest = z.infer<typeof agentTestRunCommitRequestSchema>;
/** Outcome of one held action replay. */
export const agentTestRunCommitActionStatusSchema = z.enum(['done', 'failed', 'already_committed']);
export type AgentTestRunCommitActionStatus = z.infer<typeof agentTestRunCommitActionStatusSchema>;
export const agentTestRunCommitActionResultSchema = z.object({
actionId: z.string(),
toolName: z.string(),
status: agentTestRunCommitActionStatusSchema,
error: z.string().optional(),
});
export type AgentTestRunCommitActionResult = z.infer<typeof agentTestRunCommitActionResultSchema>;
export const agentTestRunCommitResponseSchema = z.object({
committedAt: z.string(),
results: z.array(agentTestRunCommitActionResultSchema),
});
export type AgentTestRunCommitResponse = z.infer<typeof agentTestRunCommitResponseSchema>;
@@ -1226,7 +1226,9 @@ export interface InstanceAiBrowserCreateLinkResponse {
* - `live`: a session is open. The link lets anyone who has it control the browser, so the
* client keeps it in memory only. `windowId` names the window the link shows, so the client
* can tell a new window from a new link to the same one. `userHasTakenOver` is set after the
* user clicked "Take over", until they give control back.
* user clicked "Take over", until they give control back. `loginProfile` is where the session
* keeps its sign-ins: `domain` is its site, and `savedAt`, an ISO date, is set once it is saved.
* `willBeSavedOnSessionEnd` is set once the user chose to save it.
* - `starting`: a session is opening.
* - `no-session`: the task runs, but the agent has not opened a session yet.
* - `disconnected`: the session closed while the task runs. The agent can open a new one.
@@ -1234,7 +1236,13 @@ export interface InstanceAiBrowserCreateLinkResponse {
* task runs on another main, or it is not the user's.
*/
export type InstanceAiCloudBrowserLiveViewResponse =
| { status: 'live'; liveViewUrl: string; windowId: string; userHasTakenOver?: boolean }
| {
status: 'live';
liveViewUrl: string;
windowId: string;
userHasTakenOver?: boolean;
loginProfile?: { domain: string; savedAt?: string; willBeSavedOnSessionEnd?: boolean };
}
| { status: 'starting' }
| { status: 'no-session' }
| { status: 'disconnected'; reason: 'connectionLost' | 'idleTimeout' | 'userControlTimeout' }
@@ -1253,6 +1261,12 @@ export const tasksUpdatePayloadSchema = z.object({
/** Host event of an Assistant agent turn with the temporary workflows that the turn end archived. */
export const ASSISTANT_WORKFLOWS_ARCHIVED_EVENT = 'workflows-archived';
/**
* Transient host event of an Assistant agent turn: the id of the run that the
* turn belongs to. The turns that resume a card keep the id of their run.
*/
export const ASSISTANT_RUN_EVENT = 'assistant-run';
export const workflowsArchivedPayloadSchema = z.object({
workflowIds: z.array(z.string()),
});
@@ -2020,11 +2034,33 @@ export class InstanceAiCorrectTaskRequest extends Z.class({
message: z.string().min(1),
}) {}
/** The user hands a cloud browser back to its agent, with what they changed. */
/**
* The user hands a cloud browser back to its agent, with what they changed. `shouldSaveLogin`
* determines whether the login should be saved, after asking the user.
*/
export class InstanceAiCloudBrowserReturnControlRequest extends Z.class({
note: z.string().trim().max(2000).optional(),
shouldSaveLogin: z.boolean().optional(),
}) {}
/**
* The browser is back with its agent. `loginWillBeSaved` is false when the user did not ask to
* save the login, or when the server could not tell where they signed in.
*/
export interface InstanceAiCloudBrowserReturnControlResponse {
ok: true;
loginWillBeSaved: boolean;
}
/**
* The login the user can save now, before they give control back. `domain` is the site of the
* login. It is not set when the user cannot save a login, for example when the current page is on
* another site.
*/
export interface InstanceAiCloudBrowserLoginToSaveResponse {
domain?: string;
}
/**
* Entry-point taxonomy for Instance AI thread creation. Every new entry point
* must register a value here — `InstanceAiEnsureThreadRequest.source` requires
@@ -1,15 +1,3 @@
// PostHog rollout flag id gating MCP Apps support (the iframe UI attached to
// the create-workflow-from-code MCP tool). Single source of truth shared
// between FE and BE so the two cannot drift. Follows the `NNN_<feature>`
// numeric-prefix convention used by every other n8n PostHog flag.
export const MCP_APPS_FLAG = '087_mcp_apps';
// Variant strings used by the `087_mcp_apps` experiment.
// - 'control': MCP Apps disabled (legacy behaviour)
// - 'variant': MCP Apps enabled
export const MCP_APPS_VARIANT_CONTROL = 'control';
export const MCP_APPS_VARIANT_ENABLED = 'variant';
export const MCP_AGENT_SCOPES = ['agent:read', 'agent:write', 'agent:execute'] as const;
export const MCP_SKILL_SCOPES = ['skill:read', 'skill:write'] as const;
@@ -55,6 +55,8 @@ export const IMMEDIATE_COMMANDS = new Set<PubSub.Command['command']>([
'self-healing-failure',
'cancel-agent-background-job',
'wake-agent-background-job',
// Debouncing by name would drop the resets of other chats sent at the same time.
'reset-agent-test-run',
'relay-instance-ai-event',
'relay-instance-ai-task-control',
'agent-chat-subscription-changed',
@@ -74,6 +74,7 @@ export namespace PubSub {
export type ResumeAgentWorkflowTool = ToCommand<'resume-agent-workflow-tool'>;
export type CancelAgentBackgroundJob = ToCommand<'cancel-agent-background-job'>;
export type WakeAgentBackgroundJob = ToCommand<'wake-agent-background-job'>;
export type ResetAgentTestRun = ToCommand<'reset-agent-test-run'>;
export type RelayChatStreamEvent = ToCommand<'relay-chat-stream-event'>;
export type RelayInstanceAiEvent = ToCommand<'relay-instance-ai-event'>;
export type RelayInstanceAiTaskControl = ToCommand<'relay-instance-ai-task-control'>;
@@ -138,6 +139,7 @@ export namespace PubSub {
| Commands.ResumeAgentWorkflowTool
| Commands.CancelAgentBackgroundJob
| Commands.WakeAgentBackgroundJob
| Commands.ResetAgentTestRun
| Commands.RelayChatStreamEvent
| Commands.RelayInstanceAiEvent
| Commands.RelayInstanceAiTaskControl
@@ -1,6 +1,5 @@
import {
AGENT_SANDBOX_FILES_FLAG,
CREDENTIAL_DESCRIPTIONS_FLAG,
CUSTOM_MCP_SERVERS_FLAG,
INSTANCE_AI_CLOUD_BROWSER_FLAG,
KNOWLEDGE_COLLECTIONS_FLAG,
@@ -257,7 +256,6 @@ describe('PostHog', () => {
async (firstReader) => {
(PostHog.prototype.evaluateFlags as Mock).mockImplementation(async (distinctId: string) =>
mockEvaluatedFlags({
[CREDENTIAL_DESCRIPTIONS_FLAG]: distinctId === `company_${instanceId}`,
[AGENT_SANDBOX_FILES_FLAG]: distinctId === `company_${instanceId}`,
[INSTANCE_AI_CLOUD_BROWSER_FLAG]: distinctId === `company_${instanceId}`,
[KNOWLEDGE_COLLECTIONS_FLAG]: distinctId === `company_${instanceId}`,
@@ -271,12 +269,10 @@ describe('PostHog', () => {
}
for (const id of ['user-1', 'user-2']) {
const flags = await ph.getFeatureFlags({ id, createdAt });
expect(flags[CREDENTIAL_DESCRIPTIONS_FLAG]).toBe(true);
expect(flags[AGENT_SANDBOX_FILES_FLAG]).toBe(true);
expect(flags[INSTANCE_AI_CLOUD_BROWSER_FLAG]).toBe(true);
expect(flags[KNOWLEDGE_COLLECTIONS_FLAG]).toBe(true);
}
expect(await ph.getFeatureFlagForInstance(CREDENTIAL_DESCRIPTIONS_FLAG)).toBe(true);
expect(await ph.getFeatureFlagForInstance(AGENT_SANDBOX_FILES_FLAG)).toBe(true);
expect(await ph.getFeatureFlagForInstance(INSTANCE_AI_CLOUD_BROWSER_FLAG)).toBe(true);
expect(await ph.getFeatureFlagForInstance(KNOWLEDGE_COLLECTIONS_FLAG)).toBe(true);
@@ -284,7 +280,6 @@ describe('PostHog', () => {
expect(PostHog.prototype.evaluateFlags).toHaveBeenCalledWith(`company_${instanceId}`, {
groups: { company: instanceId },
flagKeys: [
CREDENTIAL_DESCRIPTIONS_FLAG,
AGENT_SANDBOX_FILES_FLAG,
INSTANCE_AI_CLOUD_BROWSER_FLAG,
KNOWLEDGE_COLLECTIONS_FLAG,
@@ -330,17 +325,15 @@ describe('PostHog', () => {
? instanceResult === undefined
? {}
: {
[CREDENTIAL_DESCRIPTIONS_FLAG]: instanceResult,
[AGENT_SANDBOX_FILES_FLAG]: instanceResult,
}
: { [CREDENTIAL_DESCRIPTIONS_FLAG]: true, [AGENT_SANDBOX_FILES_FLAG]: true },
: { [AGENT_SANDBOX_FILES_FLAG]: true },
),
);
const ph = new PostHogClient(instanceSettings, globalConfig);
await ph.init();
const flags = await ph.getFeatureFlags({ id: userId, createdAt });
expect(flags[CREDENTIAL_DESCRIPTIONS_FLAG]).toBe(false);
expect(flags[AGENT_SANDBOX_FILES_FLAG]).toBe(false);
},
);
@@ -374,7 +367,6 @@ describe('PostHog', () => {
const expected = {
featureFlags: {
...flags,
[CREDENTIAL_DESCRIPTIONS_FLAG]: false,
[AGENT_SANDBOX_FILES_FLAG]: false,
[INSTANCE_AI_CLOUD_BROWSER_FLAG]: false,
[KNOWLEDGE_COLLECTIONS_FLAG]: false,
@@ -405,7 +397,6 @@ describe('PostHog', () => {
const { featureFlags } = await ph.getFeatureFlagsAndPayloads({ id: userId, createdAt });
expect(featureFlags).toEqual({
[CREDENTIAL_DESCRIPTIONS_FLAG]: false,
[AGENT_SANDBOX_FILES_FLAG]: false,
[INSTANCE_AI_CLOUD_BROWSER_FLAG]: false,
[KNOWLEDGE_COLLECTIONS_FLAG]: false,
@@ -427,7 +418,6 @@ describe('PostHog', () => {
expect(first).toEqual({
...flags,
[CREDENTIAL_DESCRIPTIONS_FLAG]: false,
[AGENT_SANDBOX_FILES_FLAG]: false,
[INSTANCE_AI_CLOUD_BROWSER_FLAG]: false,
[KNOWLEDGE_COLLECTIONS_FLAG]: false,
@@ -437,7 +427,6 @@ describe('PostHog', () => {
});
expect(second).toEqual({
...flags,
[CREDENTIAL_DESCRIPTIONS_FLAG]: false,
[AGENT_SANDBOX_FILES_FLAG]: false,
[INSTANCE_AI_CLOUD_BROWSER_FLAG]: false,
[KNOWLEDGE_COLLECTIONS_FLAG]: false,
@@ -575,7 +564,6 @@ describe('PostHog', () => {
const flags = await ph.getFeatureFlags({ id: userId, createdAt });
expect(flags).toEqual({
[CREDENTIAL_DESCRIPTIONS_FLAG]: false,
[AGENT_SANDBOX_FILES_FLAG]: false,
[INSTANCE_AI_CLOUD_BROWSER_FLAG]: false,
[KNOWLEDGE_COLLECTIONS_FLAG]: false,
@@ -600,7 +588,6 @@ describe('PostHog', () => {
const flags = await ph.getFeatureFlags({ id: userId, createdAt });
expect(flags).toEqual({
[CREDENTIAL_DESCRIPTIONS_FLAG]: false,
[AGENT_SANDBOX_FILES_FLAG]: false,
[INSTANCE_AI_CLOUD_BROWSER_FLAG]: false,
[KNOWLEDGE_COLLECTIONS_FLAG]: false,
@@ -641,7 +628,6 @@ describe('PostHog', () => {
expect(data).toEqual({
featureFlags: {
[CREDENTIAL_DESCRIPTIONS_FLAG]: false,
[AGENT_SANDBOX_FILES_FLAG]: false,
[INSTANCE_AI_CLOUD_BROWSER_FLAG]: false,
[KNOWLEDGE_COLLECTIONS_FLAG]: false,
@@ -673,7 +659,6 @@ describe('PostHog', () => {
const flags = await ph.getFeatureFlags({ id: userId, createdAt });
expect(flags).toEqual({
[CREDENTIAL_DESCRIPTIONS_FLAG]: false,
[AGENT_SANDBOX_FILES_FLAG]: false,
[INSTANCE_AI_CLOUD_BROWSER_FLAG]: false,
[KNOWLEDGE_COLLECTIONS_FLAG]: false,
@@ -710,7 +695,6 @@ describe('PostHog', () => {
const flags = await ph.getFeatureFlags({ id: userId, createdAt });
expect(flags).toEqual({
[CREDENTIAL_DESCRIPTIONS_FLAG]: false,
[AGENT_SANDBOX_FILES_FLAG]: false,
[INSTANCE_AI_CLOUD_BROWSER_FLAG]: false,
[KNOWLEDGE_COLLECTIONS_FLAG]: false,
@@ -731,7 +715,6 @@ describe('PostHog', () => {
const flags = await ph.getFeatureFlags({ id: userId, createdAt });
expect(flags).toEqual({
[CREDENTIAL_DESCRIPTIONS_FLAG]: false,
[AGENT_SANDBOX_FILES_FLAG]: false,
[INSTANCE_AI_CLOUD_BROWSER_FLAG]: false,
[KNOWLEDGE_COLLECTIONS_FLAG]: false,
@@ -764,7 +747,6 @@ describe('PostHog', () => {
const flags = await ph.getFeatureFlags({ id: userId, createdAt });
expect(flags).toEqual({
[CREDENTIAL_DESCRIPTIONS_FLAG]: false,
[AGENT_SANDBOX_FILES_FLAG]: false,
[INSTANCE_AI_CLOUD_BROWSER_FLAG]: false,
[KNOWLEDGE_COLLECTIONS_FLAG]: false,
@@ -788,7 +770,6 @@ describe('PostHog', () => {
const flags = await ph.getFeatureFlags({ id: userId, createdAt });
expect(flags).toEqual({
[CREDENTIAL_DESCRIPTIONS_FLAG]: false,
[AGENT_SANDBOX_FILES_FLAG]: false,
[INSTANCE_AI_CLOUD_BROWSER_FLAG]: false,
[KNOWLEDGE_COLLECTIONS_FLAG]: false,
@@ -1,7 +1,6 @@
import {
AGENT_EVALS_FLAG,
AGENT_SANDBOX_FILES_FLAG,
CREDENTIAL_DESCRIPTIONS_FLAG,
CUSTOM_MCP_SERVERS_FLAG,
INSTANCE_AI_NODE_USAGE_FLAG,
INSTANCE_AI_CLOUD_BROWSER_FLAG,
@@ -37,7 +36,6 @@ const FLAGS_CACHE_TTL_MS = 10 * 60 * 1000; // 10 minutes
*/
const EMPTY_INSTANCE_FLAGS_CACHE_TTL_MS = 60 * 1000;
const EDITOR_INSTANCE_FLAGS = [
CREDENTIAL_DESCRIPTIONS_FLAG,
AGENT_SANDBOX_FILES_FLAG,
INSTANCE_AI_CLOUD_BROWSER_FLAG,
KNOWLEDGE_COLLECTIONS_FLAG,
@@ -7,6 +7,7 @@ export type CredentialPayload = {
name: string;
type: string;
data: ICredentialDataDecryptedObject;
description?: string | null;
isManaged?: boolean;
isGlobal?: boolean;
isResolvable?: boolean;
+5 -6
View File
@@ -370,10 +370,9 @@ needs only `aiPreference:import`. The user must still have access to each
Preference. Project permissions and permissions for other package entities still
apply.
Packages with a Preferences collection use package format `3`. They require an
Packages with a Preferences collection use package format `2`. They require an
n8n destination that supports this format and has Preferences enabled. Older
readers reject the package. Packages without the collection retain format `1`.
The source n8n version does not override the format check. Format `2` belongs to
the separate standalone Skills change; readers must support every collection
before they accept a package. Do not change the format number to bypass a
rejection.
readers reject the package. Packages without the collection keep format `1`. The source n8n
version does not override the format check. A format `2` manifest with an
unknown field fails before any writes. Other format numbers also fail. Do not
change the format number to bypass a rejection.
@@ -228,12 +228,12 @@ export class EndpointsConfig {
mcpBuilderEnabled: boolean = true;
/**
* Force-enable MCP Apps support (the iframe UI attached to MCP tools).
* Acts as an operator-level override of the PostHog experiment.
* Cannot force-disable: setting this to `false` falls back to PostHog.
* Whether MCP clients can show an interactive workflow preview when they
* build a workflow through the MCP server. Set to false to return the
* workflow without the preview.
*/
@Env('N8N_MCP_APPS_ENABLED')
mcpAppsEnabled: boolean = false;
mcpAppsEnabled: boolean = true;
/** Maximum number of OAuth clients that can be registered for MCP. */
@Env('N8N_MCP_MAX_REGISTERED_CLIENTS')
@@ -19,18 +19,16 @@ export class InstanceAiConfig {
enabled?: boolean;
/**
* Enable workflow suggestions, self-healing investigations, and result review.
* Whether workflow suggestions, self-healing investigations, and result review are enabled. Set to `false` to turn them off. Restart n8n after changing this variable.
*/
@Env('N8N_INSTANCE_AI_WORKFLOW_SUGGESTIONS_ENABLED')
workflowSuggestionsEnabled: boolean = false;
workflowSuggestionsEnabled: boolean = true;
/**
* Whether n8n runs the n8n Assistant on the agents runtime as well. This is an
* experimental preview for development and evaluation. Don't turn it on in
* production.
* Whether n8n runs the n8n Assistant on the agents runtime as well.
*/
@Env('N8N_INSTANCE_AI_ASSISTANT_AGENT_ENABLED')
assistantAgentEnabled: boolean = false;
assistantAgentEnabled: boolean = true;
/** LLM model in provider/model format, or a bare model name for a custom endpoint. */
@Env('N8N_INSTANCE_AI_MODEL')
+3 -3
View File
@@ -323,7 +323,7 @@ describe('GlobalConfig', () => {
formTest: 'form-test',
formWaiting: 'form-waiting',
mcp: 'mcp',
mcpAppsEnabled: false,
mcpAppsEnabled: true,
mcpBuilderEnabled: true,
mcpMaxRegisteredClients: 5000,
mcpTest: 'mcp-test',
@@ -368,8 +368,8 @@ describe('GlobalConfig', () => {
streamStateTtl: 300,
},
instanceAi: {
workflowSuggestionsEnabled: false,
assistantAgentEnabled: false,
workflowSuggestionsEnabled: true,
assistantAgentEnabled: true,
model: 'anthropic/claude-opus-5-5',
modelUrl: '',
modelRequestLabels: false,
@@ -91,8 +91,9 @@ export type PolicedArtifactRef = {
};
/**
* A run that asks for its execution row. The fields match a ledger row, so a check can apply
* the shared counting rules. There are no nodes: a check here must read memory only.
* A run that asks for its execution row. A check builds a `LedgerFact` from it with
* `entityType: artifact.kind`, `mode`, `source ?? 'none'`, `event: 'started'` and
* `outcome: 'none'`. There are no nodes: a check here must read memory only.
*/
export type ExecutionAdmissionContext = {
readonly artifact: PolicedArtifactRef;
@@ -220,6 +220,14 @@ export type PubSubCommandMap = {
threadId: string;
};
/** Ask other mains to drop their simulated world of a test chat that the user reset. */
'reset-agent-test-run': {
userId: string;
projectId: string;
agentId: string;
testChatId: string;
};
'clear-test-webhooks': {
webhookKey: string;
workflowEntity: IWorkflowBase;
+19 -17
View File
@@ -34,31 +34,33 @@ a deployable engine worker) without touching core logic.
(the `createScheduler(deps)` pattern).
- **Core interfaces** — interfaces the core depends on, each defined in its own
core module beside a default/reference use: `AdmittanceService` (`admittance/`),
`WorkQueue` (`queue/`), `ExecutionStore` / `StepStore` / `ExecutionViewStore`
`WorkQueuePublisher` and `WorkQueueConsumer` (`queue/`), `ExecutionStore` / `StepStore` / `ExecutionViewStore`
(`execution/`), `LifecycleEventPublisher` (`lifecycle-events/`). Adapters
implement them; the core never imports the interface from an adapter. Handed
in at construction.
- **Adapters (do)** — effectful implementations: `database/` (TypeORM entities,
migrations, the Postgres `DataSource`, and `TypeOrmExecutionStore`), `queue/`
(`InMemoryWorkQueue`, and `RedisWorkQueue` on a Redis list). The Postgres/ORM
coupling lives *here only*. `createInMemoryWorkQueues` builds the pair of
in-memory queues. `createRedisWorkQueues` builds the pair of Redis queues:
the engine sets the list names and the message schemas. The host gives the
Redis connections, the key prefix and the concurrency limits.
`RedisWorkQueue` never closes a connection. A queue opens its consumer
connection on its first `start()`, so a process that only publishes to a
queue opens none for it. The factory's `close()` closes only the consumer
connections that were opened; the host closes the publisher. The engine has
no runtime dependency on `ioredis`; the adapter declares the client commands
it needs as interfaces.
(`InMemoryWorkQueue`, and `RedisWorkQueuePublisher` and
`RedisWorkQueueConsumer` on a Redis list). The Postgres/ORM
coupling lives *here only*. A host gives the engine a `WorkQueueFactory`,
which builds a publisher or a consumer from a queue name. A publisher and a
consumer with the same name use the same queue, and the adapter knows no
queue names. `createInMemoryWorkQueueFactory` keeps one queue for each name.
The `n8n engine` process builds its Redis factory in `packages/cli` from
`RedisWorkQueuePublisher` and `RedisWorkQueueConsumer`. Neither closes its
client. The host closes each consumer client after the runtime stopped, and
then the publisher client, so a fetch still pending fails instead of taking a
message. The engine has no runtime dependency on `ioredis`; the adapter
declares the client commands it needs as interfaces.
- **Serving infra** — `server/` (express), `serve.ts` (standalone entrypoint),
Dockerfile. First candidate to be extracted later.
- **Runtime factory** — `runtime/` (`createEngineRuntime`). Owns the engine's
internal topology: the stores, the handlers, the workers, the HTTP app and the
start/stop order. It takes the adapters a host chooses and returns a running
engine, so no host repeats the wiring. The host gives it the queues. It
starts and stops the queues its roles consume, but never closes their
connections.
engine, so no host repeats the wiring. The host gives it a `WorkQueueFactory`
and the concurrency limits. The runtime decides which queues exist, with
their names and message schemas. It creates a publisher for each queue, and
creates, starts and stops a consumer only for the queues of its roles.
A process runs one or more roles (all three by default): `api` mounts `/api`,
`orchestrator` runs the orchestration worker and the reconciliation sweeper,
and `step-worker` runs the step worker and the wait sweeper. Every role serves
@@ -71,8 +73,8 @@ a deployable engine worker) without touching core logic.
- **Composition roots** — `serve.ts` (standalone) and, in integrated mode,
`packages/cli`. These construct the concrete adapters (the `DataSource`, the
admittance policy, the v1 step executor and, in the `n8n engine` process, the
Redis connections for the work queues) and hand them to the engine factories
(`createEngineRuntime`, `createInMemoryWorkQueues`, `createRedisWorkQueues`).
Redis work queue factory) and hand them to the engine factories
(`createEngineRuntime`, `createInMemoryWorkQueueFactory`).
**Construction lives here, not in the core** — but the topology does not:
that belongs to the factories.
@@ -33,6 +33,7 @@ import {
isEndedExecutionStatus,
LIVE_EXECUTION_STATUSES,
stepKeyId,
type EndedExecutionStatus,
type ExecutionStatus,
type StepKey,
type StepKeyId,
@@ -199,7 +200,11 @@ export class TypeOrmExecutionStore implements ExecutionStore {
return row.status;
}
async transitionStatus(id: string, from: ExecutionStatus, to: ExecutionStatus): Promise<boolean> {
async transitionStatus(
id: string,
from: ExecutionStatus,
to: Exclude<ExecutionStatus, EndedExecutionStatus>,
): Promise<boolean> {
const result = await this.repo.update(
{ id, status: from },
{ status: to, staleAfter: this.staleAfterFor(to) },
@@ -4,7 +4,7 @@ import {
LifecycleEventPublisherFactory,
type LifecycleEventPublisher,
} from '../../lifecycle-events';
import type { StepMessage, WorkQueue } from '../../queue';
import type { StepMessage, WorkQueuePublisher } from '../../queue';
import type { ExecutionResponseSender } from '../../response-channel';
import { CancelExecutionService } from '../cancel-execution.service';
import {
@@ -14,7 +14,7 @@ import {
} from '../execution-store';
import type { ExecutionStatus } from '../execution.types';
import type { StepStore } from '../step-store';
import { fakeWorkQueue } from '../../queue/__tests__/fake-work-queue';
import { fakeWorkQueuePublisher } from '../../queue/__tests__/fake-work-queue';
const execution: ExecutionRecord = {
id: 'exec-1',
@@ -70,7 +70,7 @@ function makeService(executionStore: ExecutionStore) {
send: vi.fn(),
stop: vi.fn(),
};
const stepQueue: WorkQueue<StepMessage> = fakeWorkQueue();
const stepQueue: WorkQueuePublisher<StepMessage> = fakeWorkQueuePublisher();
const service = new CancelExecutionService(
executionStore,
stepStore,
@@ -11,24 +11,20 @@ import {
type LifecycleEvent,
type LifecycleEventPublisher,
} from '../../lifecycle-events';
import type { OrchestrationMessage, StepMessage, WorkQueue } from '../../queue';
import type { OrchestrationMessage, StepMessage, WorkQueuePublisher } from '../../queue';
import { noopExecutionResponseSender } from '../../response-channel';
import type { CancelExecutionService } from '../cancel-execution.service';
import { stepKeyId, type StepSlots } from '../execution.types';
import { StepSettledHandler } from '../step-settled-handler';
/** Records what is published and never dispatches it, so each test picks the delivery order. */
class RecordingQueue<T> implements WorkQueue<T> {
class RecordingQueue<T> implements WorkQueuePublisher<T> {
published: T[] = [];
async publish(message: T) {
this.published.push(message);
}
start() {}
async stop() {}
async size() {
return this.published.length;
}
@@ -5,11 +5,11 @@ import {
LifecycleEventPublisherFactory,
type LifecycleEventPublisher,
} from '../../lifecycle-events';
import type { OrchestrationMessage, WorkQueue } from '../../queue';
import type { OrchestrationMessage, WorkQueuePublisher } from '../../queue';
import { ExecutionStartHandler } from '../execution-start-handler';
import type { ExecutionRecord, ExecutionStore } from '../execution-store';
import type { StepStore } from '../step-store';
import { fakeWorkQueue } from '../../queue/__tests__/fake-work-queue';
import { fakeWorkQueuePublisher } from '../../queue/__tests__/fake-work-queue';
/** A publisher fake; tests that care assert on `publish`. */
function makeLifecycleEventPublisher(): LifecycleEventPublisher {
@@ -20,7 +20,7 @@ function makeLifecycleEventPublisher(): LifecycleEventPublisher {
function makeHandler(
executionStore: ExecutionStore,
stepStore: StepStore,
queue: WorkQueue<OrchestrationMessage>,
queue: WorkQueuePublisher<OrchestrationMessage>,
lifecycleEventPublisher: LifecycleEventPublisher = makeLifecycleEventPublisher(),
): ExecutionStartHandler {
return new ExecutionStartHandler(
@@ -51,8 +51,8 @@ function makeExecutionStore(overrides: Partial<ExecutionStore> = {}): ExecutionS
};
}
function makeOrchestrationQueue(): WorkQueue<OrchestrationMessage> {
return fakeWorkQueue();
function makeOrchestrationQueue(): WorkQueuePublisher<OrchestrationMessage> {
return fakeWorkQueuePublisher();
}
/** Only `createSteps` is exercised here; the rest belong to other handlers. */
@@ -18,7 +18,7 @@ import {
noopLifecycleEventPublisher,
} from '../../lifecycle-events';
import { InMemoryWorkQueue, type OrchestrationMessage, type StepMessage } from '../../queue';
import { fakeWorkQueue } from '../../queue/__tests__/fake-work-queue';
import { fakeWorkQueuePublisher } from '../../queue/__tests__/fake-work-queue';
import { noopExecutionResponseSender } from '../../response-channel';
import type { CancelExecutionService } from '../cancel-execution.service';
import { ExecutionStartHandler } from '../execution-start-handler';
@@ -138,7 +138,7 @@ describe('execution start (integration)', () => {
it('is idempotent across duplicate execution:enqueued deliveries', async () => {
const { executionStore, stepStore } = stores();
const queue = fakeWorkQueue<OrchestrationMessage>();
const queue = fakeWorkQueuePublisher<OrchestrationMessage>();
const { publish } = queue;
const handler = new ExecutionStartHandler(
executionStore,
@@ -10,7 +10,7 @@ import { ExecutionNotFoundError, type ExecutionStore } from '../execution-store'
import type { ExecutionStatus } from '../execution.types';
import { ResumeRequestService, type ResumeHold } from '../resume-request.service';
import { StepNotFoundError, type StepRecord, type StepStore } from '../step-store';
import { fakeWorkQueue } from '../../queue/__tests__/fake-work-queue';
import { fakeWorkQueuePublisher } from '../../queue/__tests__/fake-work-queue';
const secret = 'a'.repeat(32);
const executionId = '0199a1b2-0000-7000-8000-000000000001';
@@ -81,7 +81,7 @@ function setup({
return { status };
}),
} as unknown as ExecutionStore;
const stepQueue = fakeWorkQueue<StepMessage>();
const stepQueue = fakeWorkQueuePublisher<StepMessage>();
const service = new ResumeRequestService(
executionStore,
@@ -372,15 +372,6 @@ describe('ResumeRequestService.resolve', () => {
);
});
it('leaves the step queue running', async () => {
const { service, stepQueue } = setup();
await service.resolve('s1', token, outputs);
expect(stepQueue.start).not.toHaveBeenCalled();
expect(stepQueue.stop).not.toHaveBeenCalled();
});
it('checks the token against the execution of the step', async () => {
const { service, stepStore } = setup({
step: { ...accepting('s1'), executionId: otherExecutionId },
@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest';
import { AdmittanceRejectedError, type AdmittanceService } from '../../admittance';
import { GraphValidationError, type WorkflowGraph } from '../../graph';
import type { OrchestrationMessage, WorkQueue } from '../../queue';
import type { OrchestrationMessage, WorkQueuePublisher } from '../../queue';
import {
ExecutionNotFoundError,
ParentExecutionEndedError,
@@ -16,7 +16,7 @@ import type {
} from '../execution.types';
import { StartExecutionService, type InvalidParentLinkReason } from '../start-execution.service';
import { StepNotFoundError, type StepRecord, type StepStore } from '../step-store';
import { fakeWorkQueue } from '../../queue/__tests__/fake-work-queue';
import { fakeWorkQueuePublisher } from '../../queue/__tests__/fake-work-queue';
const sampleGraph: WorkflowGraph = {
nodes: [{ id: 'trigger', name: 'Manual Trigger', type: 'trigger', config: {} }],
@@ -30,8 +30,8 @@ const sampleWorkflow: WorkflowDocument = {
connections: {},
};
function makeQueue(): WorkQueue<OrchestrationMessage> {
return fakeWorkQueue();
function makeQueue(): WorkQueuePublisher<OrchestrationMessage> {
return fakeWorkQueuePublisher();
}
function makeStore(overrides: Partial<ExecutionStore> = {}): ExecutionStore {
@@ -25,7 +25,7 @@ import type {
LifecycleEventSubscription,
} from '../../lifecycle-events';
import {
createInMemoryWorkQueues,
createInMemoryWorkQueueFactory,
InMemoryWorkQueue,
type OrchestrationMessage,
} from '../../queue';
@@ -122,7 +122,16 @@ describe('step execution (integration)', () => {
identityVerifier: new SharedSecretIdentityVerifier(secret),
responseSender: noopExecutionResponseSender,
waitSweepIntervalMs,
queues: createInMemoryWorkQueues({ concurrency }),
workQueueFactory: createInMemoryWorkQueueFactory(),
concurrency,
// The spies below sit on the wrappers, so a handler that bypasses them never resolves the run.
instrumentation: {
wrapStores: (stores) => ({
executionStore: Object.create(stores.executionStore),
stepStore: Object.create(stores.stepStore),
executionViewStore: Object.create(stores.executionViewStore),
}),
},
// also how the test reaches the stores the runtime owns
externalDependencies: ({ executionStore, stepStore }) => {
const finishExecution = executionStore.finishExecution.bind(executionStore);
@@ -8,7 +8,7 @@ import {
type LifecycleEvent,
} from '../../lifecycle-events';
import { noopExecutionResponseSender, type ExecutionResponseSender } from '../../response-channel';
import type { OrchestrationMessage, WorkQueue } from '../../queue';
import type { OrchestrationMessage, WorkQueuePublisher } from '../../queue';
import {
ExecutionNotFoundError,
type ExecutionRecord,
@@ -24,7 +24,7 @@ import { InvalidParentLinkError, type StartExecutionService } from '../start-exe
import { attachStepErrorDetails } from '../step-error-details';
import { resolveInputReads, StepReadyHandler } from '../step-ready-handler';
import type { StepRecord, StepStore, StepSummary } from '../step-store';
import { fakeWorkQueue } from '../../queue/__tests__/fake-work-queue';
import { fakeWorkQueuePublisher } from '../../queue/__tests__/fake-work-queue';
/** Key for a `loadStepsByKeys` result at iteration 0, as the handler requests them. */
const at = (nodeId: string) => stepKeyId({ nodeId, iteration: 0 });
@@ -74,7 +74,7 @@ function makeSubExecutionStarter(): SubExecutionStarter {
function makeHandler(
executionStore: ExecutionStore,
stepStore: StepStore,
queue: WorkQueue<OrchestrationMessage>,
queue: WorkQueuePublisher<OrchestrationMessage>,
dependencies: ExternalDependencies,
lifecycleEventPublisher: LifecycleEventPublisher = makeLifecycleEventPublisher(),
responseSender: ExecutionResponseSender = noopExecutionResponseSender,
@@ -177,8 +177,8 @@ function makeStepStore(step: Partial<StepRecord> = {}, overrides: Partial<StepSt
} satisfies StepStore;
}
function makeQueue(): WorkQueue<OrchestrationMessage> {
return fakeWorkQueue();
function makeQueue(): WorkQueuePublisher<OrchestrationMessage> {
return fakeWorkQueuePublisher();
}
function makeExecutor(result: unknown = { outputs: [[{ json: { ok: true } }]] }): IStepExecutor {
@@ -1793,7 +1793,7 @@ describe('StepReadyHandler lifecycle events', () => {
}),
stop: vi.fn(),
};
const queue = fakeWorkQueue<OrchestrationMessage>();
const queue = fakeWorkQueuePublisher<OrchestrationMessage>();
queue.publish.mockImplementation(async (message) => {
order.push(`queue:${message.type}`);
await Promise.resolve();
@@ -6,7 +6,7 @@ import {
type LifecycleEventPublisher,
} from '../../lifecycle-events';
import type { EngineLogger } from '../../logging';
import type { OrchestrationMessage, StepMessage, WorkQueue } from '../../queue';
import type { OrchestrationMessage, StepMessage, WorkQueuePublisher } from '../../queue';
import type { ExecutionResponseSender } from '../../response-channel';
import type { CancelExecutionService } from '../cancel-execution.service';
import {
@@ -23,7 +23,7 @@ import {
type StepStore,
type StepSummary,
} from '../step-store';
import { fakeWorkQueue } from '../../queue/__tests__/fake-work-queue';
import { fakeWorkQueuePublisher } from '../../queue/__tests__/fake-work-queue';
/**
* trigger -> a -> {b (out 0), c (out 1)} -> m. So `a` fans out across two output
@@ -166,12 +166,12 @@ function makeStepStore(
} satisfies StepStore;
}
function makeStepQueue(): WorkQueue<StepMessage> {
return fakeWorkQueue();
function makeStepQueue(): WorkQueuePublisher<StepMessage> {
return fakeWorkQueuePublisher();
}
function makeOrchestrationQueue(): WorkQueue<OrchestrationMessage> {
return fakeWorkQueue();
function makeOrchestrationQueue(): WorkQueuePublisher<OrchestrationMessage> {
return fakeWorkQueuePublisher();
}
/** A publisher fake; tests that care assert on `publish`. */
@@ -1,15 +1,15 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { EngineLogger } from '../../logging';
import type { StepMessage, WorkQueue } from '../../queue';
import type { StepMessage, WorkQueuePublisher } from '../../queue';
import type { DueStep, StepStore } from '../step-store';
import { WaitSweeper } from '../wait-sweeper';
import { fakeWorkQueue } from '../../queue/__tests__/fake-work-queue';
import { fakeWorkQueuePublisher } from '../../queue/__tests__/fake-work-queue';
const SWEEP_MS = 1_000;
function makeStepQueue(): WorkQueue<StepMessage> {
return fakeWorkQueue();
function makeStepQueue(): WorkQueuePublisher<StepMessage> {
return fakeWorkQueuePublisher();
}
function makeLogger(): EngineLogger {
@@ -11,7 +11,7 @@ import { generateId } from '../../database/generate-id';
import type { IStepExecutor } from '../../dependencies';
import type { WorkflowGraph } from '../../graph';
import type { LifecycleEvent } from '../../lifecycle-events';
import { createInMemoryWorkQueues } from '../../queue';
import { createInMemoryWorkQueueFactory } from '../../queue';
import { noopExecutionResponseSender } from '../../response-channel';
import { createEngineRuntime, type EngineRuntime } from '../../runtime';
import type { StartExecutionResult } from '../start-execution.service';
@@ -79,7 +79,8 @@ describe('a step that starts to wait after its execution ended (integration)', (
admittance: new AllowAllAdmittance(),
identityVerifier: new SharedSecretIdentityVerifier(secret),
responseSender: noopExecutionResponseSender,
queues: createInMemoryWorkQueues({ concurrency: { step: stepConcurrency } }),
workQueueFactory: createInMemoryWorkQueueFactory(),
concurrency: { step: stepConcurrency },
externalDependencies: ({ stepStore }) => {
spyOn(stepStore);
return {
@@ -1,5 +1,5 @@
import type { LifecycleEventPublisherFactory } from '../lifecycle-events';
import type { StepMessage, WorkQueue } from '../queue';
import type { StepMessage, WorkQueuePublisher } from '../queue';
import type { ExecutionResponseSender } from '../response-channel';
import type { ExecutionStore } from './execution-store';
import type { ExecutionStatus } from './execution.types';
@@ -25,7 +25,7 @@ export class CancelExecutionService {
private readonly stepStore: StepStore,
private readonly lifecycleEventPublisherFactory: LifecycleEventPublisherFactory,
private readonly responseSender: ExecutionResponseSender,
private readonly stepQueue: WorkQueue<StepMessage>,
private readonly stepQueue: WorkQueuePublisher<StepMessage>,
) {}
/** @throws {ExecutionNotFoundError} if absent. */
@@ -1,7 +1,7 @@
import { UnexpectedError } from '../common';
import { findTriggerNode } from '../graph';
import type { LifecycleEventPublisherFactory } from '../lifecycle-events';
import type { ExecutionEnqueuedEvent, OrchestrationMessage, WorkQueue } from '../queue';
import type { ExecutionEnqueuedEvent, OrchestrationMessage, WorkQueuePublisher } from '../queue';
import type { ExecutionStore } from './execution-store';
import { DEFAULT_TRIGGER_OUTPUTS } from './execution.types';
import type { StepStore } from './step-store';
@@ -18,7 +18,7 @@ export class ExecutionStartHandler {
constructor(
private readonly executionStore: ExecutionStore,
private readonly stepStore: StepStore,
private readonly orchestrationQueue: WorkQueue<OrchestrationMessage>,
private readonly orchestrationQueue: WorkQueuePublisher<OrchestrationMessage>,
private readonly lifecycleEventPublisherFactory: LifecycleEventPublisherFactory,
) {}
@@ -3,6 +3,7 @@ import type { LifecycleEventSubscription } from '../lifecycle-events';
import type { ResponseExpectation } from '../response-channel';
import type {
CallerContext,
EndedExecutionStatus,
ErrorSourceLink,
ExecutionMode,
ExecutionStatus,
@@ -125,6 +126,9 @@ export function isMissingExecution(error: unknown, executionId: string): boolean
* A write that makes an execution `queued` also records when the engine treats
* it as stuck in that status (see `StalenessThresholds`). A transition out of
* `queued` clears that time.
*
* Only `finishExecution` and `cancelExecution` move a `queued` or live
* execution to an ended status, so a host that wraps the store sees every end.
*/
export interface ExecutionStore {
/**
@@ -160,7 +164,11 @@ export interface ExecutionStore {
* Compare-and-set status transition. Returns `true` iff this call performed
* the transition, so duplicate/redelivered events are handled idempotently.
*/
transitionStatus(id: string, from: ExecutionStatus, to: ExecutionStatus): Promise<boolean>;
transitionStatus(
id: string,
from: ExecutionStatus,
to: Exclude<ExecutionStatus, EndedExecutionStatus>,
): Promise<boolean>;
/**
* Record an execution's outcome: writes the final status and the finish time
@@ -26,6 +26,8 @@ export function isLiveExecutionStatus(status: ExecutionStatus): boolean {
/** Ended for good. Every other status is `queued` or live. */
export const ENDED_EXECUTION_STATUSES = ['completed', 'failed', 'cancelled'] as const;
export type EndedExecutionStatus = (typeof ENDED_EXECUTION_STATUSES)[number];
export function isEndedExecutionStatus(status: ExecutionStatus): boolean {
return (ENDED_EXECUTION_STATUSES as readonly ExecutionStatus[]).includes(status);
}
@@ -1,5 +1,5 @@
import { UnimplementedError } from '../common';
import type { OrchestrationMessage, WorkQueue } from '../queue';
import type { OrchestrationMessage, WorkQueueConsumer } from '../queue';
import type { ExecutionStartHandler } from './execution-start-handler';
import type { StepSettledHandler } from './step-settled-handler';
@@ -8,7 +8,7 @@ import type { StepSettledHandler } from './step-settled-handler';
*/
export class OrchestrationWorker {
constructor(
private readonly orchestrationQueue: WorkQueue<OrchestrationMessage>,
private readonly orchestrationQueue: WorkQueueConsumer<OrchestrationMessage>,
private readonly startHandler: ExecutionStartHandler,
private readonly settledHandler: StepSettledHandler,
) {}
@@ -1,7 +1,7 @@
import { setTimeout as sleep } from 'node:timers/promises';
import { verifyResumeToken, type ResumeTokenClaims } from '../auth/resume-token';
import type { StepMessage, WorkQueue } from '../queue';
import type { StepMessage, WorkQueuePublisher } from '../queue';
import { ExecutionNotFoundError, type ExecutionStore } from './execution-store';
import {
isLiveExecutionStatus,
@@ -102,7 +102,7 @@ export class ResumeRequestService {
constructor(
private readonly executionStore: ExecutionStore,
private readonly stepStore: StepStore,
private readonly stepQueue: WorkQueue<StepMessage>,
private readonly stepQueue: WorkQueuePublisher<StepMessage>,
private readonly secret: string,
private readonly hold: ResumeHold = DEFAULT_RESUME_HOLD,
) {}
@@ -12,7 +12,7 @@ import {
type WorkflowLoop,
} from '../graph';
import type { LifecycleEventSubscription } from '../lifecycle-events';
import type { OrchestrationMessage, WorkQueue } from '../queue';
import type { OrchestrationMessage, WorkQueuePublisher } from '../queue';
import type { ResponseExpectation } from '../response-channel';
import {
ExecutionNotFoundError,
@@ -107,7 +107,7 @@ export class StartExecutionService {
private readonly admittance: AdmittanceService,
private readonly executionStore: ExecutionStore,
private readonly stepStore: StepStore,
private readonly workQueue: WorkQueue<OrchestrationMessage>,
private readonly workQueue: WorkQueuePublisher<OrchestrationMessage>,
private readonly validateGraph: (graph: WorkflowGraph) => void = validateExecutableGraph,
) {}
@@ -1,6 +1,6 @@
import type { GraphNode } from '../graph';
import type { LifecycleEventPublisherFactory } from '../lifecycle-events';
import type { OrchestrationMessage, WorkQueue } from '../queue';
import type { OrchestrationMessage, WorkQueuePublisher } from '../queue';
import type { ExecutionRecord } from './execution-store';
import type { StepError } from './execution.types';
import type { StepRecord } from './step-store';
@@ -24,7 +24,7 @@ export function stepEventFields(step: StepRecord, node: GraphNode) {
*/
export async function announceStepFailed(
lifecycleEventPublisherFactory: LifecycleEventPublisherFactory,
orchestrationQueue: WorkQueue<OrchestrationMessage>,
orchestrationQueue: WorkQueuePublisher<OrchestrationMessage>,
execution: ExecutionRecord,
step: StepRecord,
node: GraphNode,
@@ -17,7 +17,7 @@ import {
import type { LifecycleEventPublisherFactory } from '../lifecycle-events';
import { createResponseEmitter, type ExecutionResponseSender } from '../response-channel';
import { runBatchStep, type BatchStepResult } from './batch-step';
import type { OrchestrationMessage, StepReadyEvent, WorkQueue } from '../queue';
import type { OrchestrationMessage, StepReadyEvent, WorkQueuePublisher } from '../queue';
import { isMissingExecution, type ExecutionRecord, type ExecutionStore } from './execution-store';
import {
stepKeyId,
@@ -79,7 +79,7 @@ export class StepReadyHandler {
constructor(
private readonly executionStore: ExecutionStore,
private readonly stepStore: StepStore,
private readonly orchestrationQueue: WorkQueue<OrchestrationMessage>,
private readonly orchestrationQueue: WorkQueuePublisher<OrchestrationMessage>,
private readonly dependencies: ExternalDependencies,
private readonly lifecycleEventPublisherFactory: LifecycleEventPublisherFactory,
private readonly responseSender: ExecutionResponseSender,
@@ -9,7 +9,12 @@ import {
import type { LifecycleEventPublisherFactory } from '../lifecycle-events';
import type { EngineLogger } from '../logging';
import type { ExecutionResponseSender } from '../response-channel';
import type { OrchestrationMessage, StepMessage, StepSettledEvent, WorkQueue } from '../queue';
import type {
OrchestrationMessage,
StepMessage,
StepSettledEvent,
WorkQueuePublisher,
} from '../queue';
import type { CancelExecutionService } from './cancel-execution.service';
import { countExpectedSettledSteps } from './completion';
import { isMissingExecution, type ExecutionRecord, type ExecutionStore } from './execution-store';
@@ -48,8 +53,8 @@ export class StepSettledHandler {
constructor(
private readonly executionStore: ExecutionStore,
private readonly stepStore: StepStore,
private readonly stepQueue: WorkQueue<StepMessage>,
private readonly orchestrationQueue: WorkQueue<OrchestrationMessage>,
private readonly stepQueue: WorkQueuePublisher<StepMessage>,
private readonly orchestrationQueue: WorkQueuePublisher<OrchestrationMessage>,
private readonly lifecycleEventPublisherFactory: LifecycleEventPublisherFactory,
private readonly responseSender: ExecutionResponseSender,
private readonly cancelExecution: CancelExecutionService,
@@ -1,5 +1,5 @@
import { UnimplementedError } from '../common';
import type { StepMessage, WorkQueue } from '../queue';
import type { StepMessage, WorkQueueConsumer } from '../queue';
import type { StepReadyHandler } from './step-ready-handler';
/**
@@ -8,7 +8,7 @@ import type { StepReadyHandler } from './step-ready-handler';
*/
export class StepWorker {
constructor(
private readonly stepQueue: WorkQueue<StepMessage>,
private readonly stepQueue: WorkQueueConsumer<StepMessage>,
private readonly readyHandler: StepReadyHandler,
) {}
@@ -1,5 +1,5 @@
import { deriveLoops, type WorkflowGraph } from '../graph';
import type { StepMessage, WorkQueue } from '../queue';
import type { StepMessage, WorkQueuePublisher } from '../queue';
import type { ExecutionRecord, ExecutionStore } from './execution-store';
import type { SubExecutionOutcome, SubExecutionResult } from './execution.types';
import type { StepRecord, StepStore } from './step-store';
@@ -7,7 +7,7 @@ import type { StepRecord, StepStore } from './step-store';
export interface SubExecutionResumeDeps {
executionStore: ExecutionStore;
stepStore: StepStore;
stepQueue: WorkQueue<StepMessage>;
stepQueue: WorkQueuePublisher<StepMessage>;
}
/** Resume the parent step with the sub-execution outcome, and announce the step on the work queue. */
@@ -1,6 +1,6 @@
import type { EngineLogger } from '../logging';
import { createConsoleLogger } from '../logging';
import type { StepMessage, WorkQueue } from '../queue';
import type { StepMessage, WorkQueuePublisher } from '../queue';
import type { DueStep, StepStore } from './step-store';
/** v1 resolves waits on a 60-second poll, so timer resolution matches it. */
@@ -31,7 +31,7 @@ export class WaitSweeper {
constructor(
private readonly stepStore: StepStore,
private readonly stepQueue: WorkQueue<StepMessage>,
private readonly stepQueue: WorkQueuePublisher<StepMessage>,
private readonly logger: EngineLogger = createConsoleLogger(),
private readonly intervalMs: number = DEFAULT_WAIT_SWEEP_INTERVAL_MS,
private readonly batchSize: number = DEFAULT_WAIT_SWEEP_BATCH_SIZE,
Loaded 100 of 701 files, more files were not shown because too many files have changed in this diff. Show more