Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ad7f2aede1 | ||
|
|
f13b51db9c | ||
|
|
e994be2958 | ||
|
|
e0eebe3307 | ||
|
|
6d8938e260 | ||
|
|
b15ac514d9 | ||
|
|
c539fc1dc6 | ||
|
|
1c053e207e | ||
|
|
14734843fd | ||
|
|
10a71e6904 |
@@ -60,6 +60,7 @@ sdk:
|
||||
- "packages/client/**"
|
||||
- "packages/highlight/**"
|
||||
- "packages/protocol/**"
|
||||
- "packages/workflows/**"
|
||||
|
||||
browser:
|
||||
- "packages/server/src/server/agent/provider-snapshot-manager.ts"
|
||||
|
||||
@@ -127,6 +127,14 @@ jobs:
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||
run: npm run test --workspace=@getpaseo/highlight
|
||||
|
||||
- name: Build workflows package
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||
run: npm run build:workflows
|
||||
|
||||
- name: Run workflows tests
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||
run: npm run test --workspace=@getpaseo/workflows
|
||||
|
||||
- name: Typecheck client examples
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||
run: npm run typecheck:examples --workspace=@getpaseo/client
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
"*.lock",
|
||||
"**/*.gen.ts",
|
||||
"**/*.gen.tsx",
|
||||
"**/*.icon/**",
|
||||
"packages/react-native-enriched-markdown/**"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Brand assets
|
||||
|
||||
Canonical marks, lockups, and wordmark font for **Paseo** and **Paseo Hub**. These are the source assets that will replace the existing icons across the app, desktop client, website, docs, and Hub in follow-up work.
|
||||
Canonical marks, lockups, and wordmark font for **Paseo** and **Paseo Hub**. These are the source assets for the icons across the app, desktop client, website, docs, and Hub.
|
||||
|
||||
## Brand architecture
|
||||
|
||||
@@ -37,6 +37,10 @@ All lockups (`lockups/*.svg`) share a `144`-unit height (`140`-unit flower ink h
|
||||
```text
|
||||
assets/brand/
|
||||
build.mjs Regenerates all marks and lockups
|
||||
build-app-icons.mjs Regenerates the desktop and mobile app icons
|
||||
app-icons/
|
||||
paseo-lit.png
|
||||
paseo-dev-lit.png
|
||||
fonts/
|
||||
PlusJakartaSans-SemiBold.ttf
|
||||
OFL.txt
|
||||
@@ -61,3 +65,25 @@ assets/brand/
|
||||
```sh
|
||||
node assets/brand/build.mjs
|
||||
```
|
||||
|
||||
## App icons
|
||||
|
||||
`build-app-icons.mjs` renders every desktop and mobile app icon from `marks/paseo-white.svg`: the white butterfly on a black tile, and a blueprint tile for desktop development builds. Regenerate them after changing the butterfly:
|
||||
|
||||
```sh
|
||||
node assets/brand/build-app-icons.mjs
|
||||
```
|
||||
|
||||
The icons that ship are flat. Each platform masks and lights its own icons, so lit artwork ends up lit twice. `app-icons/` keeps a lit version of the two desktop icons, a baked approximation of macOS Liquid Glass. Nothing uses them.
|
||||
|
||||
The packaged Mac app takes its icon from `packages/desktop/assets/icon.icon`, an Icon Composer document the script also writes. macOS draws Liquid Glass on it and derives the dark, tinted, and clear variants. electron-builder compiles the document with `actool`, so packaging the Mac app needs Xcode 26 or later. The Nix build has no Xcode and uses `icon.icns`.
|
||||
|
||||
To see what macOS draws from the document without packaging the app, export it with Icon Composer's command line tool on a Mac:
|
||||
|
||||
```sh
|
||||
"/Applications/Xcode.app/Contents/Applications/Icon Composer.app/Contents/Executables/ictool" \
|
||||
packages/desktop/assets/icon.icon --export-image --output-file icon.png \
|
||||
--platform macOS --rendition Default --width 1024 --height 1024 --scale 1
|
||||
```
|
||||
|
||||
`--rendition` also takes `Dark`, `TintedLight`, `TintedDark`, `ClearLight`, and `ClearDark`.
|
||||
|
||||
|
After Width: | Height: | Size: 212 KiB |
|
After Width: | Height: | Size: 109 KiB |
@@ -0,0 +1,464 @@
|
||||
// Generates every Paseo app icon from the canonical butterfly mark.
|
||||
//
|
||||
// node assets/brand/build-app-icons.mjs
|
||||
//
|
||||
// The artwork is the white butterfly on a black tile. A desktop development build gets the same
|
||||
// tile drawn as a blueprint, so it is never mistaken for an installed app.
|
||||
//
|
||||
// The icons that ship are flat. Each platform masks and lights its own icons, and artwork that
|
||||
// arrives already lit ends up lit twice. The lit finish is a baked approximation of the Liquid
|
||||
// Glass material macOS draws for Icon Composer icons. It is written to app-icons/ so it stays
|
||||
// available, and nothing consumes it.
|
||||
//
|
||||
// A packaged Mac app gets its icon from the Icon Composer document in the desktop assets, which
|
||||
// macOS masks and lights itself. macOS draws a dev build's Dock icon and an .icns exactly as
|
||||
// supplied, so those carry the system's tile in the artwork. Its geometry is measured from the icon
|
||||
// macOS 27 draws for that document: the tile covers 824 of the 1024 canvas pixels and its corners
|
||||
// are continuous curves with a radius of 26.4% of the tile.
|
||||
//
|
||||
// sharp is not a declared dependency. It resolves from the workspace root, the way opentype.js
|
||||
// does for build.mjs.
|
||||
|
||||
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import sharp from "sharp";
|
||||
|
||||
const brandDir = path.dirname(fileURLToPath(import.meta.url));
|
||||
const repoRoot = path.resolve(brandDir, "../..");
|
||||
const brandMarkPath = path.join(brandDir, "marks/paseo-white.svg");
|
||||
|
||||
const CANVAS = 1024;
|
||||
const MACOS_TILE_ON_CANVAS = 824 / CANVAS;
|
||||
// Windows and Linux have no icon grid, and a tile with the macOS margin looks small next to their
|
||||
// other icons.
|
||||
const WINDOWS_LINUX_TILE_ON_CANVAS = 928 / CANVAS;
|
||||
|
||||
// Artwork is drawn in the brand mark's own 700-unit box, which the tile fills.
|
||||
const TILE = 700;
|
||||
const TILE_RADIUS = 185;
|
||||
const MARK_INK = 527;
|
||||
// Scaled down, the mark keeps clear of the tile's corners and covers as much of the tile as the
|
||||
// glyphs in Apple's icons do.
|
||||
const MARK_SCALE = 0.9;
|
||||
const MARK_INK_ON_TILE = (MARK_INK * MARK_SCALE) / TILE;
|
||||
|
||||
// Android shows the middle 72 of an adaptive icon's 108 units.
|
||||
const ANDROID_ADAPTIVE_VISIBLE = 72 / 108;
|
||||
const NOTIFICATION_MARK_INK = 0.75;
|
||||
|
||||
// Apple's continuous corner. Each pair is a distance back along the incoming edge and a distance
|
||||
// along the outgoing edge, in units of the corner radius.
|
||||
const CORNER_SEGMENTS = [
|
||||
["C", [1.08849296, 0], [0.86840694, 0], [0.66993427, 0.065496]],
|
||||
["L", [0.63149399, 0.074911]],
|
||||
["C", [0.37282392, 0.16905899], [0.16905899, 0.37282392], [0.074911, 0.63149399]],
|
||||
["L", [0.065496, 0.66993427]],
|
||||
["C", [0, 0.86840694], [0, 1.08849296], [0, 1.52866483]],
|
||||
];
|
||||
const CORNER_START = [1.52866483, 0];
|
||||
|
||||
function continuousSquarePath(inset) {
|
||||
const near = inset;
|
||||
const far = TILE - inset;
|
||||
const radius = TILE_RADIUS - inset;
|
||||
const corners = [
|
||||
{ at: [far, near], incoming: [1, 0], outgoing: [0, 1] },
|
||||
{ at: [far, far], incoming: [0, 1], outgoing: [-1, 0] },
|
||||
{ at: [near, far], incoming: [-1, 0], outgoing: [0, -1] },
|
||||
{ at: [near, near], incoming: [0, -1], outgoing: [1, 0] },
|
||||
];
|
||||
const commands = corners.map(({ at, incoming, outgoing }, cornerIndex) => {
|
||||
const point = ([back, along]) =>
|
||||
[0, 1]
|
||||
.map((axis) => at[axis] - incoming[axis] * back * radius + outgoing[axis] * along * radius)
|
||||
.map((value) => Number(value.toFixed(2)))
|
||||
.join(" ");
|
||||
const segments = CORNER_SEGMENTS.map(
|
||||
([command, ...points]) => `${command}${points.map(point).join(" ")}`,
|
||||
);
|
||||
return `${cornerIndex === 0 ? "M" : "L"}${point(CORNER_START)}${segments.join("")}`;
|
||||
});
|
||||
return `${commands.join("")}Z`;
|
||||
}
|
||||
|
||||
const TILE_SHAPE = `<path d="${continuousSquarePath(0)}" />`;
|
||||
const FILL_TILE = `<rect width="${TILE}" height="${TILE}" fill="url(#surface)" />`;
|
||||
|
||||
const PRODUCTION = {
|
||||
flat: {
|
||||
defs: `<linearGradient id="surface"><stop stop-color="#000000" /></linearGradient>`,
|
||||
surface: FILL_TILE,
|
||||
},
|
||||
lit: {
|
||||
defs: `
|
||||
<linearGradient id="surface" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#202022" />
|
||||
<stop offset="1" stop-color="#0E0E10" />
|
||||
</linearGradient>`,
|
||||
surface: FILL_TILE,
|
||||
tileEdge: { color: "#000000", opacity: 0.75 },
|
||||
markEdge: { color: "#4A5568", opacity: 0.45 },
|
||||
markShadow: { color: "#000000", opacity: 0.5 },
|
||||
},
|
||||
};
|
||||
|
||||
const GRID_DIVISIONS = 8;
|
||||
const GRID_MAJOR_EVERY = 2;
|
||||
const OUTLINE_INSET = 28;
|
||||
|
||||
function gridLines(isIncluded) {
|
||||
const step = TILE / GRID_DIVISIONS;
|
||||
const segments = [];
|
||||
for (let index = 1; index < GRID_DIVISIONS; index += 1) {
|
||||
if (!isIncluded(index)) continue;
|
||||
const at = index * step;
|
||||
segments.push(`M${at} 0V${TILE}`, `M0 ${at}H${TILE}`);
|
||||
}
|
||||
return segments.join("");
|
||||
}
|
||||
|
||||
const isMajorLine = (index) => index % GRID_MAJOR_EVERY === 0;
|
||||
|
||||
const BLUEPRINT_SHEET = {
|
||||
defs: `
|
||||
<linearGradient id="surface" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#05C2FE" />
|
||||
<stop offset="0.5" stop-color="#0191FD" />
|
||||
<stop offset="1" stop-color="#026CFA" />
|
||||
</linearGradient>`,
|
||||
surface: `
|
||||
${FILL_TILE}
|
||||
<g fill="none" stroke="#FFFFFF">
|
||||
<path d="${gridLines((index) => !isMajorLine(index))}" stroke-opacity="0.16" stroke-width="1.5" />
|
||||
<path d="${gridLines(isMajorLine)}" stroke-opacity="0.34" stroke-width="2" />
|
||||
<circle cx="${TILE / 2}" cy="${TILE / 2}" r="${TILE / 2 - OUTLINE_INSET}" stroke-opacity="0.45" stroke-width="2" stroke-dasharray="10 8" />
|
||||
<path d="${continuousSquarePath(OUTLINE_INSET)}" stroke-opacity="0.34" stroke-width="2" />
|
||||
</g>`,
|
||||
};
|
||||
|
||||
const BLUEPRINT = {
|
||||
flat: BLUEPRINT_SHEET,
|
||||
lit: {
|
||||
...BLUEPRINT_SHEET,
|
||||
tileEdge: { color: "#0034B4", opacity: 0.55 },
|
||||
markEdge: { color: "#1E5FD0", opacity: 0.5 },
|
||||
markShadow: { color: "#00308F", opacity: 0.4 },
|
||||
},
|
||||
};
|
||||
|
||||
// The lit finish, tuned against Apple's own renders. The light comes from straight above: a
|
||||
// layer's upward-facing edge gets a bright highlight, its downward-facing edge a fainter one, and
|
||||
// its side edges darken.
|
||||
//
|
||||
// An edge highlight is the part of the layer that a vertically shifted copy does not cover. A
|
||||
// vertical blur of the shifted copy makes the highlight brightest at the edge and absent on
|
||||
// vertical edges. A wider, round blur of the same band dims it where the edge turns away from
|
||||
// the light, which is what keeps the tile's corners quieter than its top.
|
||||
function glassFilter({ id, edge, edgeWidth, lightWidth, upperLight, lowerLight, shadow }) {
|
||||
const light = (name, direction, opacity) => `
|
||||
<feOffset in="SourceAlpha" dy="${direction * lightWidth}" />
|
||||
<feGaussianBlur stdDeviation="0 ${lightWidth}" result="${name}Shifted" />
|
||||
<feComposite in="SourceAlpha" in2="${name}Shifted" operator="out" result="${name}Edge" />
|
||||
<feOffset in="SourceAlpha" dy="${direction * lightWidth * 2}" result="${name}Far" />
|
||||
<feComposite in="SourceAlpha" in2="${name}Far" operator="out" />
|
||||
<feGaussianBlur stdDeviation="${lightWidth * 3}" />
|
||||
<feComponentTransfer><feFuncA type="gamma" exponent="3" amplitude="65" /></feComponentTransfer>
|
||||
<feComposite in2="${name}Edge" operator="arithmetic" k1="1" result="${name}Shape" />
|
||||
<feFlood flood-color="#FFFFFF" flood-opacity="${opacity}" />
|
||||
<feComposite in2="${name}Shape" operator="in" result="${name}" />`;
|
||||
const dropShadow = shadow
|
||||
? `
|
||||
<feGaussianBlur in="SourceAlpha" stdDeviation="${shadow.blur}" />
|
||||
<feOffset dy="${shadow.offset}" result="shadowShape" />
|
||||
<feFlood flood-color="${shadow.color}" flood-opacity="${shadow.opacity}" />
|
||||
<feComposite in2="shadowShape" operator="in" result="shadow" />`
|
||||
: "";
|
||||
return `
|
||||
<filter id="${id}" x="-20%" y="-20%" width="140%" height="140%" color-interpolation-filters="sRGB">${dropShadow}
|
||||
<feMorphology in="SourceAlpha" operator="erode" radius="${edgeWidth * 0.6}" />
|
||||
<feGaussianBlur stdDeviation="${edgeWidth}" result="core" />
|
||||
<feFlood flood-color="${edge.color}" flood-opacity="${edge.opacity}" />
|
||||
<feComposite in2="core" operator="out" />
|
||||
<feComposite in2="SourceAlpha" operator="in" result="edge" />
|
||||
${light("upper", 1, upperLight)}
|
||||
${light("lower", -1, lowerLight)}
|
||||
<feMerge>
|
||||
${shadow ? '<feMergeNode in="shadow" />' : ""}
|
||||
<feMergeNode in="SourceGraphic" />
|
||||
<feMergeNode in="edge" />
|
||||
<feMergeNode in="upper" />
|
||||
<feMergeNode in="lower" />
|
||||
</feMerge>
|
||||
</filter>`;
|
||||
}
|
||||
|
||||
function litDefs({ tileEdge, markEdge, markShadow }) {
|
||||
const markBody = `
|
||||
<linearGradient id="markBody" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#FFFFFF" />
|
||||
<stop offset="0.4" stop-color="#FFFFFF" />
|
||||
<stop offset="1" stop-color="#D9DFE9" />
|
||||
</linearGradient>`;
|
||||
const tileGlass = glassFilter({
|
||||
id: "tileGlass",
|
||||
edge: tileEdge,
|
||||
edgeWidth: 3,
|
||||
lightWidth: 3.6,
|
||||
upperLight: 0.82,
|
||||
lowerLight: 0.45,
|
||||
});
|
||||
const markGlass = glassFilter({
|
||||
id: "markGlass",
|
||||
edge: markEdge,
|
||||
edgeWidth: 1.2,
|
||||
lightWidth: 1.6,
|
||||
upperLight: 1,
|
||||
lowerLight: 0.6,
|
||||
shadow: { ...markShadow, blur: 9, offset: 8 },
|
||||
});
|
||||
return `${markBody}${tileGlass}${markGlass}`;
|
||||
}
|
||||
|
||||
function brandMark(stroke) {
|
||||
const svg = readFileSync(brandMarkPath, "utf8");
|
||||
const outline = svg.match(/\bd="([^"]+)"/);
|
||||
const strokeWidth = svg.match(/\bstroke-width="([^"]+)"/);
|
||||
if (!outline || !strokeWidth) {
|
||||
throw new Error(`No stroked mark path in ${brandMarkPath}`);
|
||||
}
|
||||
// The path carries its own `fill="none"`: Icon Composer ignores the one on the <svg> element and
|
||||
// draws a hairline from the end of the stroke back to its start.
|
||||
return `<path d="${outline[1]}" fill="none" stroke="${stroke}" stroke-width="${strokeWidth[1]}" stroke-linecap="round" stroke-linejoin="round" />`;
|
||||
}
|
||||
|
||||
function scaledAboutCentre(scale, content) {
|
||||
const centre = TILE / 2;
|
||||
return `<g transform="translate(${centre} ${centre}) scale(${scale}) translate(${-centre} ${-centre})">${content}</g>`;
|
||||
}
|
||||
|
||||
// A square canvas with the 700-unit artwork box centred on it and covering `boxOnCanvas` of its
|
||||
// width.
|
||||
function canvasSvg(boxOnCanvas, content) {
|
||||
const canvasUnits = TILE / boxOnCanvas;
|
||||
const origin = (TILE - canvasUnits) / 2;
|
||||
return [
|
||||
`<svg width="${CANVAS}" height="${CANVAS}" viewBox="${origin} ${origin} ${canvasUnits} ${canvasUnits}" fill="none" xmlns="http://www.w3.org/2000/svg">`,
|
||||
content,
|
||||
"</svg>",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
// The tile with the mark on it. A masked tile has the continuous corners cut into the artwork. A
|
||||
// square tile is for platforms that apply their own mask.
|
||||
function tileIconSvg({ artwork, finish, tileOnCanvas, corners }) {
|
||||
const look = artwork[finish];
|
||||
const isLit = finish === "lit";
|
||||
const filtered = (id, content) => (isLit ? `<g filter="url(#${id})">${content}</g>` : content);
|
||||
const tile =
|
||||
corners === "continuous" ? `<g clip-path="url(#tile)">${look.surface}</g>` : look.surface;
|
||||
const mark = scaledAboutCentre(MARK_SCALE, brandMark(isLit ? "url(#markBody)" : "#FFFFFF"));
|
||||
return canvasSvg(
|
||||
tileOnCanvas,
|
||||
[
|
||||
`<defs><clipPath id="tile">${TILE_SHAPE}</clipPath>${look.defs}${isLit ? litDefs(look) : ""}</defs>`,
|
||||
filtered("tileGlass", tile),
|
||||
filtered("markGlass", mark),
|
||||
].join("\n"),
|
||||
);
|
||||
}
|
||||
|
||||
// The white mark alone on a transparent canvas, its ink covering `inkOnCanvas` of the width.
|
||||
function markOnlySvg(inkOnCanvas) {
|
||||
return canvasSvg((inkOnCanvas * TILE) / MARK_INK, brandMark("#FFFFFF"));
|
||||
}
|
||||
|
||||
function rasterizer(svg) {
|
||||
const source = Buffer.from(svg);
|
||||
const sized = (size) => sharp(source).resize(size, size);
|
||||
return {
|
||||
png: (size) => sized(size).png({ compressionLevel: 9 }).toBuffer(),
|
||||
opaquePng: (size) => sized(size).removeAlpha().png({ compressionLevel: 9 }).toBuffer(),
|
||||
rgba: (size) => sized(size).ensureAlpha().raw().toBuffer(),
|
||||
};
|
||||
}
|
||||
|
||||
// ICO: a directory of PNG-encoded entries. A size byte of 0 means 256.
|
||||
function encodeIco(entries) {
|
||||
const header = Buffer.alloc(6);
|
||||
header.writeUInt16LE(1, 2);
|
||||
header.writeUInt16LE(entries.length, 4);
|
||||
|
||||
let offset = header.length + entries.length * 16;
|
||||
const directory = entries.map(({ size, png }) => {
|
||||
const entry = Buffer.alloc(16);
|
||||
entry.writeUInt8(size % 256, 0);
|
||||
entry.writeUInt8(size % 256, 1);
|
||||
entry.writeUInt16LE(1, 4);
|
||||
entry.writeUInt16LE(32, 6);
|
||||
entry.writeUInt32LE(png.length, 8);
|
||||
entry.writeUInt32LE(offset, 12);
|
||||
offset += png.length;
|
||||
return entry;
|
||||
});
|
||||
|
||||
return Buffer.concat([header, ...directory, ...entries.map((entry) => entry.png)]);
|
||||
}
|
||||
|
||||
function icnsElement(type, data) {
|
||||
const header = Buffer.alloc(8);
|
||||
header.write(type, 0, "latin1");
|
||||
header.writeUInt32BE(header.length + data.length, 4);
|
||||
return Buffer.concat([header, data]);
|
||||
}
|
||||
|
||||
// The 16 and 32 pixel ICNS slots predate PNG: three run-length-encoded colour planes plus a
|
||||
// separate 8-bit alpha mask. A control byte below 128 copies the next (byte + 1) values, so
|
||||
// literal-only chunks are a valid encoding.
|
||||
function icnsLegacyElements(colorType, maskType, rgba) {
|
||||
const pixels = rgba.length / 4;
|
||||
const chunks = [];
|
||||
for (let channel = 0; channel < 3; channel += 1) {
|
||||
for (let start = 0; start < pixels; start += 128) {
|
||||
const length = Math.min(128, pixels - start);
|
||||
const chunk = Buffer.alloc(length + 1);
|
||||
chunk[0] = length - 1;
|
||||
for (let index = 0; index < length; index += 1) {
|
||||
chunk[index + 1] = rgba[(start + index) * 4 + channel];
|
||||
}
|
||||
chunks.push(chunk);
|
||||
}
|
||||
}
|
||||
const mask = Buffer.alloc(pixels);
|
||||
for (let index = 0; index < pixels; index += 1) {
|
||||
mask[index] = rgba[index * 4 + 3];
|
||||
}
|
||||
return [icnsElement(colorType, Buffer.concat(chunks)), icnsElement(maskType, mask)];
|
||||
}
|
||||
|
||||
async function encodeIcns(icon) {
|
||||
const pngSlots = [
|
||||
["ic07", 128],
|
||||
["ic08", 256],
|
||||
["ic09", 512],
|
||||
["ic10", 1024],
|
||||
["ic11", 32],
|
||||
["ic12", 64],
|
||||
["ic13", 256],
|
||||
["ic14", 512],
|
||||
];
|
||||
const elements = [
|
||||
...icnsLegacyElements("is32", "s8mk", await icon.rgba(16)),
|
||||
...icnsLegacyElements("il32", "l8mk", await icon.rgba(32)),
|
||||
];
|
||||
for (const [type, size] of pngSlots) {
|
||||
elements.push(icnsElement(type, await icon.png(size)));
|
||||
}
|
||||
const body = Buffer.concat(elements);
|
||||
const header = Buffer.alloc(8);
|
||||
header.write("icns", 0, "latin1");
|
||||
header.writeUInt32BE(header.length + body.length, 4);
|
||||
return Buffer.concat([header, body]);
|
||||
}
|
||||
|
||||
// The Icon Composer document macOS 26 and later build the app icon from. The canvas is the whole
|
||||
// tile: macOS adds the mask, the margin, and the lighting. The mark stays opaque so it reads as
|
||||
// solid white on the black tile.
|
||||
function iconComposerFiles() {
|
||||
const layer = "butterfly.svg";
|
||||
const document = {
|
||||
fill: { solid: "srgb:0.00000,0.00000,0.00000,1.00000" },
|
||||
groups: [
|
||||
{
|
||||
layers: [{ "image-name": layer, name: "butterfly" }],
|
||||
shadow: { kind: "neutral", opacity: 0.5 },
|
||||
translucency: { enabled: false, value: 0.5 },
|
||||
},
|
||||
],
|
||||
"supported-platforms": { squares: ["macOS"] },
|
||||
};
|
||||
return [
|
||||
["icon.json", `${JSON.stringify(document, null, 2)}\n`],
|
||||
[`Assets/${layer}`, `${markOnlySvg(MARK_INK_ON_TILE)}\n`],
|
||||
];
|
||||
}
|
||||
|
||||
function write(file, data) {
|
||||
const target = path.join(repoRoot, file);
|
||||
mkdirSync(path.dirname(target), { recursive: true });
|
||||
writeFileSync(target, data);
|
||||
}
|
||||
|
||||
function desktopIcon(artwork, finish, tileOnCanvas) {
|
||||
return rasterizer(tileIconSvg({ artwork, finish, tileOnCanvas, corners: "continuous" }));
|
||||
}
|
||||
|
||||
async function buildDesktopIcons() {
|
||||
const production = desktopIcon(PRODUCTION, "flat", WINDOWS_LINUX_TILE_ON_CANVAS);
|
||||
const assets = "packages/desktop/assets";
|
||||
|
||||
const pngFiles = [
|
||||
["icon.png", 512],
|
||||
["32x32.png", 32],
|
||||
["64x64.png", 64],
|
||||
["128x128.png", 128],
|
||||
["128x128@2x.png", 256],
|
||||
];
|
||||
for (const [file, size] of pngFiles) {
|
||||
write(`${assets}/${file}`, await production.png(size));
|
||||
}
|
||||
|
||||
const icoEntries = [];
|
||||
for (const size of [32, 16, 24, 48, 64, 256]) {
|
||||
icoEntries.push({ size, png: await production.png(size) });
|
||||
}
|
||||
write(`${assets}/icon.ico`, encodeIco(icoEntries));
|
||||
write(
|
||||
`${assets}/icon.icns`,
|
||||
await encodeIcns(desktopIcon(PRODUCTION, "flat", MACOS_TILE_ON_CANVAS)),
|
||||
);
|
||||
for (const [file, content] of iconComposerFiles()) {
|
||||
write(`${assets}/icon.icon/${file}`, content);
|
||||
}
|
||||
write(
|
||||
`${assets}/icon-dev.png`,
|
||||
await desktopIcon(BLUEPRINT, "flat", MACOS_TILE_ON_CANVAS).png(CANVAS),
|
||||
);
|
||||
}
|
||||
|
||||
async function buildMobileIcons() {
|
||||
const flat = (corners) =>
|
||||
rasterizer(tileIconSvg({ artwork: PRODUCTION, finish: "flat", tileOnCanvas: 1, corners }));
|
||||
// iOS masks these itself, and Expo flattens any transparency in the app icon onto white.
|
||||
const square = flat("square");
|
||||
// Shown as supplied, so the corners are part of the artwork.
|
||||
const masked = flat("continuous");
|
||||
const adaptiveForeground = rasterizer(markOnlySvg(ANDROID_ADAPTIVE_VISIBLE * MARK_INK_ON_TILE));
|
||||
const notification = rasterizer(markOnlySvg(NOTIFICATION_MARK_INK));
|
||||
|
||||
write("packages/app/assets/images/icon.png", await square.opaquePng(1024));
|
||||
write("packages/app/public/apple-touch-icon.png", await square.opaquePng(180));
|
||||
write(
|
||||
"packages/app/assets/images/android-icon-foreground.png",
|
||||
await adaptiveForeground.png(1024),
|
||||
);
|
||||
write("packages/app/assets/images/notification-icon.png", await notification.png(96));
|
||||
write("packages/app/assets/images/splash-icon.png", await masked.png(1024));
|
||||
write("packages/app/public/pwa-icon-192.png", await masked.png(192));
|
||||
write("packages/app/public/pwa-icon-512.png", await masked.png(512));
|
||||
write("fastlane/metadata/android/en-US/images/icon.png", await masked.png(512));
|
||||
}
|
||||
|
||||
async function buildLitIcons() {
|
||||
for (const [file, artwork] of [
|
||||
["paseo-lit.png", PRODUCTION],
|
||||
["paseo-dev-lit.png", BLUEPRINT],
|
||||
]) {
|
||||
const icon = desktopIcon(artwork, "lit", MACOS_TILE_ON_CANVAS);
|
||||
write(`assets/brand/app-icons/${file}`, await icon.png(CANVAS));
|
||||
}
|
||||
}
|
||||
|
||||
await buildDesktopIcons();
|
||||
await buildMobileIcons();
|
||||
await buildLitIcons();
|
||||
|
Before Width: | Height: | Size: 19 KiB After Width: | Height: | Size: 19 KiB |
@@ -67,6 +67,17 @@
|
||||
"entry": ["src/index.ts", "src/**/*.test.ts"],
|
||||
"project": ["src/**/*.ts"]
|
||||
},
|
||||
"packages/workflows": {
|
||||
"entry": [
|
||||
"src/index.ts",
|
||||
"src/ir.ts",
|
||||
"src/dsl.ts",
|
||||
"src/yaml.ts",
|
||||
"src/testing.ts",
|
||||
"test/**/*.test.ts"
|
||||
],
|
||||
"project": ["src/**/*.ts", "test/**/*.ts"]
|
||||
},
|
||||
"packages/expo-two-way-audio": {
|
||||
"entry": ["src/index.ts"],
|
||||
"project": ["src/**/*.ts"]
|
||||
|
||||
@@ -128,6 +128,8 @@ buildNpmPackage {
|
||||
cd packages/desktop
|
||||
# The Nix output is not a distributable DMG, so leave it unsigned and
|
||||
# disable the hardened runtime that requires a matching signature.
|
||||
# Compiling the Icon Composer document needs Xcode, which the build
|
||||
# does not have, so use the prebuilt icns.
|
||||
CSC_IDENTITY_AUTO_DISCOVERY=false \
|
||||
npm exec --offline -- electron-builder \
|
||||
--config electron-builder.yml \
|
||||
@@ -138,7 +140,8 @@ buildNpmPackage {
|
||||
--config.buildVersion=${lib.escapeShellArg buildVersion} \
|
||||
--config.mac.identity=null \
|
||||
--config.mac.hardenedRuntime=false \
|
||||
--config.mac.notarize=false
|
||||
--config.mac.notarize=false \
|
||||
--config.mac.icon=assets/icon.icns
|
||||
)
|
||||
''}
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
sha256-SZV3WTKLb+JhxWNo/jWyx+2sipzfL93YbbqQSihd3Wo=
|
||||
sha256-aal9eR571blWuL7CZt1LR+KfA4QPJ0ivVl/GSTWy93o=
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
"packages/highlight",
|
||||
"packages/plugin",
|
||||
"packages/protocol",
|
||||
"packages/workflows",
|
||||
"packages/client",
|
||||
"packages/server",
|
||||
"packages/app",
|
||||
@@ -6709,6 +6710,10 @@
|
||||
"resolved": "packages/website",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@getpaseo/workflows": {
|
||||
"resolved": "packages/workflows",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@gorhom/bottom-sheet": {
|
||||
"version": "5.2.14",
|
||||
"resolved": "https://registry.npmjs.org/@gorhom/bottom-sheet/-/bottom-sheet-5.2.14.tgz",
|
||||
@@ -14924,7 +14929,6 @@
|
||||
"version": "8.11.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.11.0.tgz",
|
||||
"integrity": "sha512-wGgprdCvMalC0BztXvitD2hC04YffAvtsUn93JbGXYLAtCUO4xd17mCCZQxUOItiBwZvJScWo8NIvQMQ71rdpg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.1",
|
||||
@@ -31398,7 +31402,6 @@
|
||||
"version": "2.3.1",
|
||||
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
|
||||
"integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
@@ -36228,7 +36231,6 @@
|
||||
"version": "4.4.1",
|
||||
"resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
|
||||
"integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"punycode": "^2.1.0"
|
||||
@@ -43159,6 +43161,21 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"packages/workflows": {
|
||||
"name": "@getpaseo/workflows",
|
||||
"version": "0.1.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"ajv": "^8.11.0",
|
||||
"js-yaml": "^4.1.1",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.9.0",
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^4.1.6"
|
||||
}
|
||||
},
|
||||
"plugins": {
|
||||
"name": "@getpaseo/builtin-plugins",
|
||||
"version": "0.18.1",
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"packages/highlight",
|
||||
"packages/plugin",
|
||||
"packages/protocol",
|
||||
"packages/workflows",
|
||||
"packages/client",
|
||||
"packages/server",
|
||||
"packages/app",
|
||||
@@ -60,6 +61,8 @@
|
||||
"build:relay:clean": "npm run build:clean --workspace=@getpaseo/relay",
|
||||
"build:protocol": "npm run build --workspace=@getpaseo/protocol",
|
||||
"build:protocol:clean": "npm run build:clean --workspace=@getpaseo/protocol",
|
||||
"build:workflows": "npm run build --workspace=@getpaseo/workflows",
|
||||
"build:workflows:clean": "npm run build:clean --workspace=@getpaseo/workflows",
|
||||
"build:client": "npm run build --workspace=@getpaseo/client",
|
||||
"build:client:clean": "npm run build:protocol:clean && npm run build:clean --workspace=@getpaseo/client",
|
||||
"build:server-deps": "npm run build:client && concurrently --kill-others-on-fail --names highlight,plugin,relay --prefix-colors yellow,green,blue \"npm run build:highlight\" \"npm run build:plugin\" \"npm run build:relay\"",
|
||||
|
||||
|
Before Width: | Height: | Size: 18 KiB After Width: | Height: | Size: 18 KiB |
|
Before Width: | Height: | Size: 62 KiB After Width: | Height: | Size: 31 KiB |
|
Before Width: | Height: | Size: 2.3 KiB After Width: | Height: | Size: 1.9 KiB |
|
Before Width: | Height: | Size: 7.9 KiB After Width: | Height: | Size: 43 KiB |
|
Before Width: | Height: | Size: 8.2 KiB After Width: | Height: | Size: 4.0 KiB |
|
Before Width: | Height: | Size: 9.0 KiB After Width: | Height: | Size: 6.0 KiB |
|
Before Width: | Height: | Size: 32 KiB After Width: | Height: | Size: 19 KiB |
@@ -92,11 +92,11 @@ function shapedCharactersFor(options: { lineCount: number; lineLength: number })
|
||||
}
|
||||
|
||||
describe("diff document measurement cost", () => {
|
||||
it("keeps additive wrapped search work proportional to long source lines", () => {
|
||||
it.each(["a", "一", "--"])("keeps wrapped search work proportional for %s", (unit) => {
|
||||
function measuredGraphemes(length: number): number {
|
||||
let count = 0;
|
||||
measureFragments({
|
||||
text: "a".repeat(length),
|
||||
text: unit.repeat(length),
|
||||
availableWidth: 200,
|
||||
wrapLines: true,
|
||||
lineHeight: 18,
|
||||
|
||||
@@ -655,17 +655,16 @@ export function measureFragments(input: {
|
||||
const measureWidth =
|
||||
input.measureText.measureWidth?.bind(input.measureText) ??
|
||||
((slice: readonly string[]) => advancesFor(input.measureText)(slice).at(-1) ?? 0);
|
||||
// Joining/ligatures can make a longer prefix narrower. Preserve the existing
|
||||
// search order for those runs; changing the probes can change their breaks.
|
||||
const canBoundSearch = !requiresShaping(input.text);
|
||||
const shaped = requiresShaping(input.text);
|
||||
let graphemeIndex = 0;
|
||||
while (graphemeIndex < graphemes.length) {
|
||||
let low = graphemeIndex + 1;
|
||||
// A small first probe finishes short lines in one query. Grow it only when
|
||||
// it fits, so narrow wrapping never repeatedly measures a huge line's tail.
|
||||
let high = canBoundSearch ? Math.min(graphemes.length, graphemeIndex + 64) : graphemes.length;
|
||||
// Preserve the search order for short shaped runs, whose widths can shrink
|
||||
// when another character joins them. Start long searches near the viewport
|
||||
// boundary so each wrap does not measure the entire remaining line.
|
||||
let high = Math.min(graphemes.length, graphemeIndex + 64);
|
||||
let fitting = low;
|
||||
if (canBoundSearch) {
|
||||
if (!shaped || high < graphemes.length) {
|
||||
while (measureWidth(displayGraphemes.slice(graphemeIndex, high)) <= input.availableWidth) {
|
||||
fitting = high;
|
||||
low = high + 1;
|
||||
|
||||
@@ -3,24 +3,30 @@ import {
|
||||
normalizePickedImageAssetsWith,
|
||||
type ExpoImagePickerAssetLike,
|
||||
type PickedImageAttachmentInput,
|
||||
type RenderPickedImageOptions,
|
||||
} from "./picked-image-normalizer";
|
||||
|
||||
export type {
|
||||
ExportPickedImageAsPng,
|
||||
ExpoImagePickerAssetLike,
|
||||
PickedImageAttachmentInput,
|
||||
PickedImageSource,
|
||||
RenderPickedImage,
|
||||
} from "./picked-image-normalizer";
|
||||
|
||||
async function exportPickedImageAsPng(uri: string): Promise<string> {
|
||||
async function renderPickedImage(uri: string, options: RenderPickedImageOptions): Promise<string> {
|
||||
const context = ImageManipulator.manipulate(uri);
|
||||
let image: Awaited<ReturnType<typeof context.renderAsync>> | null = null;
|
||||
|
||||
try {
|
||||
if (options.resize) {
|
||||
context.resize(options.resize);
|
||||
}
|
||||
image = await context.renderAsync();
|
||||
const result = await image.saveAsync({
|
||||
format: SaveFormat.PNG,
|
||||
});
|
||||
const result = await image.saveAsync(
|
||||
options.format === "jpeg"
|
||||
? { format: SaveFormat.JPEG, compress: options.compress }
|
||||
: { format: SaveFormat.PNG },
|
||||
);
|
||||
return result.uri;
|
||||
} finally {
|
||||
image?.release();
|
||||
@@ -31,7 +37,7 @@ async function exportPickedImageAsPng(uri: string): Promise<string> {
|
||||
export async function normalizePickedImageAssets(
|
||||
assets: readonly ExpoImagePickerAssetLike[],
|
||||
): Promise<PickedImageAttachmentInput[]> {
|
||||
return normalizePickedImageAssetsWith(assets, exportPickedImageAsPng);
|
||||
return normalizePickedImageAssetsWith(assets, renderPickedImage);
|
||||
}
|
||||
|
||||
export async function pickImagesWithDesktopDialog(
|
||||
|
||||
@@ -1,26 +1,28 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
MAX_PICKED_IMAGE_EDGE,
|
||||
normalizePickedImageAssetsWith,
|
||||
type ExportPickedImageAsPng,
|
||||
type RenderPickedImage,
|
||||
type RenderPickedImageOptions,
|
||||
} from "./picked-image-normalizer";
|
||||
|
||||
function fakeExportAsPng(): {
|
||||
exportAsPng: ExportPickedImageAsPng;
|
||||
recordedUris: string[];
|
||||
function fakeRenderer(): {
|
||||
render: RenderPickedImage;
|
||||
calls: { uri: string; options: RenderPickedImageOptions }[];
|
||||
} {
|
||||
const recordedUris: string[] = [];
|
||||
const calls: { uri: string; options: RenderPickedImageOptions }[] = [];
|
||||
return {
|
||||
exportAsPng: async (uri: string) => {
|
||||
recordedUris.push(uri);
|
||||
return "file:///cache/ImageManipulator/safe-picked.png";
|
||||
render: async (uri, options) => {
|
||||
calls.push({ uri, options });
|
||||
return `file:///cache/ImageManipulator/rendered.${options.format === "jpeg" ? "jpg" : "png"}`;
|
||||
},
|
||||
recordedUris,
|
||||
calls,
|
||||
};
|
||||
}
|
||||
|
||||
describe("native image attachment picker", () => {
|
||||
it("preserves native picked JPEG and PNG attachment inputs", async () => {
|
||||
const { exportAsPng, recordedUris } = fakeExportAsPng();
|
||||
const { render, calls } = fakeRenderer();
|
||||
|
||||
const result = await normalizePickedImageAssetsWith(
|
||||
[
|
||||
@@ -28,6 +30,8 @@ describe("native image attachment picker", () => {
|
||||
uri: "file:///photos/IMG_0001.JPG",
|
||||
mimeType: "image/jpeg",
|
||||
fileName: "picked.jpeg",
|
||||
width: 1600,
|
||||
height: 1200,
|
||||
},
|
||||
{
|
||||
uri: "file:///photos/screenshot.png",
|
||||
@@ -35,7 +39,7 @@ describe("native image attachment picker", () => {
|
||||
fileName: "screenshot.png",
|
||||
},
|
||||
],
|
||||
exportAsPng,
|
||||
render,
|
||||
);
|
||||
|
||||
expect(result).toEqual([
|
||||
@@ -50,11 +54,11 @@ describe("native image attachment picker", () => {
|
||||
fileName: "screenshot.png",
|
||||
},
|
||||
]);
|
||||
expect(recordedUris).toEqual([]);
|
||||
expect(calls).toEqual([]);
|
||||
});
|
||||
|
||||
it("uses explicit native MIME metadata before the URI extension", async () => {
|
||||
const { exportAsPng, recordedUris } = fakeExportAsPng();
|
||||
const { render, calls } = fakeRenderer();
|
||||
|
||||
const result = await normalizePickedImageAssetsWith(
|
||||
[
|
||||
@@ -64,7 +68,7 @@ describe("native image attachment picker", () => {
|
||||
fileName: "screenshot.png",
|
||||
},
|
||||
],
|
||||
exportAsPng,
|
||||
render,
|
||||
);
|
||||
|
||||
expect(result).toEqual([
|
||||
@@ -74,11 +78,11 @@ describe("native image attachment picker", () => {
|
||||
fileName: "screenshot.png",
|
||||
},
|
||||
]);
|
||||
expect(recordedUris).toEqual([]);
|
||||
expect(calls).toEqual([]);
|
||||
});
|
||||
|
||||
it("turns a native picked HEIC-like asset into a PNG attachment input", async () => {
|
||||
const { exportAsPng, recordedUris } = fakeExportAsPng();
|
||||
it("turns a full-resolution HEIC photo into a downscaled JPEG", async () => {
|
||||
const { render, calls } = fakeRenderer();
|
||||
|
||||
const result = await normalizePickedImageAssetsWith(
|
||||
[
|
||||
@@ -86,18 +90,101 @@ describe("native image attachment picker", () => {
|
||||
uri: "file:///photos/IMG_0001.HEIC",
|
||||
mimeType: "image/png",
|
||||
fileName: "picked.png",
|
||||
width: 4032,
|
||||
height: 3024,
|
||||
},
|
||||
],
|
||||
exportAsPng,
|
||||
render,
|
||||
);
|
||||
|
||||
expect(result).toEqual([
|
||||
{
|
||||
source: { kind: "file_uri", uri: "file:///cache/ImageManipulator/safe-picked.png" },
|
||||
mimeType: "image/png",
|
||||
fileName: "picked.png",
|
||||
source: { kind: "file_uri", uri: "file:///cache/ImageManipulator/rendered.jpg" },
|
||||
mimeType: "image/jpeg",
|
||||
fileName: "picked.jpg",
|
||||
},
|
||||
]);
|
||||
expect(recordedUris).toEqual(["file:///photos/IMG_0001.HEIC"]);
|
||||
expect(calls).toEqual([
|
||||
{
|
||||
uri: "file:///photos/IMG_0001.HEIC",
|
||||
options: { format: "jpeg", compress: 0.85, resize: { width: MAX_PICKED_IMAGE_EDGE } },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("converts a HEIC photo of unknown size to JPEG without resizing", async () => {
|
||||
const { render, calls } = fakeRenderer();
|
||||
|
||||
await normalizePickedImageAssetsWith(
|
||||
[{ uri: "file:///photos/IMG_0002.heic", mimeType: "image/heic", width: 0, height: 0 }],
|
||||
render,
|
||||
);
|
||||
|
||||
expect(calls).toEqual([
|
||||
{
|
||||
uri: "file:///photos/IMG_0002.heic",
|
||||
options: { format: "jpeg", compress: 0.85, resize: null },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("downscales an oversized portrait JPEG and keeps it JPEG", async () => {
|
||||
const { render, calls } = fakeRenderer();
|
||||
|
||||
const result = await normalizePickedImageAssetsWith(
|
||||
[
|
||||
{
|
||||
uri: "file:///camera/photo.jpg",
|
||||
mimeType: "image/jpeg",
|
||||
fileName: "photo.jpg",
|
||||
width: 3024,
|
||||
height: 4032,
|
||||
},
|
||||
],
|
||||
render,
|
||||
);
|
||||
|
||||
expect(result[0]?.mimeType).toBe("image/jpeg");
|
||||
expect(calls).toEqual([
|
||||
{
|
||||
uri: "file:///camera/photo.jpg",
|
||||
options: { format: "jpeg", compress: 0.85, resize: { height: MAX_PICKED_IMAGE_EDGE } },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("downscales an oversized screenshot and keeps it lossless PNG", async () => {
|
||||
const { render, calls } = fakeRenderer();
|
||||
|
||||
const result = await normalizePickedImageAssetsWith(
|
||||
[
|
||||
{
|
||||
uri: "file:///photos/screenshot.png",
|
||||
mimeType: "image/png",
|
||||
width: 1290,
|
||||
height: 2796,
|
||||
},
|
||||
],
|
||||
render,
|
||||
);
|
||||
|
||||
expect(result[0]?.mimeType).toBe("image/png");
|
||||
expect(calls[0]?.options).toEqual({
|
||||
format: "png",
|
||||
compress: 0.85,
|
||||
resize: { height: MAX_PICKED_IMAGE_EDGE },
|
||||
});
|
||||
});
|
||||
|
||||
it("converts other unsupported formats to PNG so transparency survives", async () => {
|
||||
const { render, calls } = fakeRenderer();
|
||||
|
||||
const result = await normalizePickedImageAssetsWith(
|
||||
[{ uri: "file:///photos/sticker.webp", mimeType: "image/webp", width: 512, height: 512 }],
|
||||
render,
|
||||
);
|
||||
|
||||
expect(result[0]?.mimeType).toBe("image/png");
|
||||
expect(calls[0]?.options).toEqual({ format: "png", compress: 0.85, resize: null });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,23 +11,45 @@ export interface ExpoImagePickerAssetLike {
|
||||
mimeType?: string | null;
|
||||
fileName?: string | null;
|
||||
file?: File | null;
|
||||
/** Pixel size reported by the picker; 0 or missing when the system did not provide it. */
|
||||
width?: number | null;
|
||||
height?: number | null;
|
||||
}
|
||||
|
||||
export type ExportPickedImageAsPng = (uri: string) => Promise<string>;
|
||||
/**
|
||||
* Longest edge, in pixels, of an image attached from a phone. Models downscale
|
||||
* larger images anyway, and full-resolution photos exceed the message size limit
|
||||
* once they are inlined in the send request.
|
||||
*/
|
||||
export const MAX_PICKED_IMAGE_EDGE = 2000;
|
||||
const JPEG_COMPRESS = 0.85;
|
||||
|
||||
export interface RenderPickedImageOptions {
|
||||
format: "jpeg" | "png";
|
||||
/** Quality for JPEG output, 0..1. */
|
||||
compress: number;
|
||||
/** Fit the longest edge to this size; null keeps the original size. */
|
||||
resize: { width: number } | { height: number } | null;
|
||||
}
|
||||
|
||||
export type RenderPickedImage = (uri: string, options: RenderPickedImageOptions) => Promise<string>;
|
||||
|
||||
interface SupportedPickedImageFormat {
|
||||
mimeType: "image/jpeg" | "image/png";
|
||||
extension: "jpg" | "png";
|
||||
render: RenderPickedImageOptions["format"];
|
||||
}
|
||||
|
||||
const JPEG_FORMAT: SupportedPickedImageFormat = {
|
||||
mimeType: "image/jpeg",
|
||||
extension: "jpg",
|
||||
render: "jpeg",
|
||||
};
|
||||
|
||||
const PNG_FORMAT: SupportedPickedImageFormat = {
|
||||
mimeType: "image/png",
|
||||
extension: "png",
|
||||
render: "png",
|
||||
};
|
||||
|
||||
function extensionFromPath(path: string | null | undefined): string | null {
|
||||
@@ -74,6 +96,34 @@ function pickedAssetSupportedFormat(
|
||||
);
|
||||
}
|
||||
|
||||
function isHeifAsset(asset: ExpoImagePickerAssetLike): boolean {
|
||||
const mimeType = asset.mimeType?.toLowerCase();
|
||||
if (mimeType === "image/heic" || mimeType === "image/heif") {
|
||||
return true;
|
||||
}
|
||||
return [asset.uri, asset.fileName].some((path) => {
|
||||
const extension = extensionFromPath(path);
|
||||
return extension === "heic" || extension === "heif";
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Camera photos (HEIC on iPhone) have no transparency, so JPEG keeps them small.
|
||||
* Other unsupported formats may carry alpha and become lossless PNG.
|
||||
*/
|
||||
function convertedFormat(asset: ExpoImagePickerAssetLike): SupportedPickedImageFormat {
|
||||
return isHeifAsset(asset) ? JPEG_FORMAT : PNG_FORMAT;
|
||||
}
|
||||
|
||||
function resizeToFit(asset: ExpoImagePickerAssetLike): RenderPickedImageOptions["resize"] {
|
||||
const width = asset.width ?? 0;
|
||||
const height = asset.height ?? 0;
|
||||
if (width <= 0 || height <= 0 || Math.max(width, height) <= MAX_PICKED_IMAGE_EDGE) {
|
||||
return null;
|
||||
}
|
||||
return width >= height ? { width: MAX_PICKED_IMAGE_EDGE } : { height: MAX_PICKED_IMAGE_EDGE };
|
||||
}
|
||||
|
||||
function replaceFileExtension(
|
||||
fileName: string | null | undefined,
|
||||
extension: SupportedPickedImageFormat["extension"],
|
||||
@@ -87,12 +137,13 @@ function replaceFileExtension(
|
||||
|
||||
export async function normalizePickedImageAssetsWith(
|
||||
assets: readonly ExpoImagePickerAssetLike[],
|
||||
exportAsPng: ExportPickedImageAsPng,
|
||||
render: RenderPickedImage,
|
||||
): Promise<PickedImageAttachmentInput[]> {
|
||||
return await Promise.all(
|
||||
assets.map(async (asset) => {
|
||||
const supportedFormat = pickedAssetSupportedFormat(asset);
|
||||
if (supportedFormat) {
|
||||
const resize = resizeToFit(asset);
|
||||
if (supportedFormat && !resize) {
|
||||
return {
|
||||
source: { kind: "file_uri", uri: asset.uri },
|
||||
mimeType: supportedFormat.mimeType,
|
||||
@@ -100,12 +151,17 @@ export async function normalizePickedImageAssetsWith(
|
||||
};
|
||||
}
|
||||
|
||||
const convertedUri = await exportAsPng(asset.uri);
|
||||
const outputFormat = supportedFormat ?? convertedFormat(asset);
|
||||
const renderedUri = await render(asset.uri, {
|
||||
format: outputFormat.render,
|
||||
compress: JPEG_COMPRESS,
|
||||
resize,
|
||||
});
|
||||
|
||||
return {
|
||||
source: { kind: "file_uri", uri: convertedUri },
|
||||
mimeType: PNG_FORMAT.mimeType,
|
||||
fileName: replaceFileExtension(asset.fileName, PNG_FORMAT.extension),
|
||||
source: { kind: "file_uri", uri: renderedUri },
|
||||
mimeType: outputFormat.mimeType,
|
||||
fileName: replaceFileExtension(asset.fileName, outputFormat.extension),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -196,6 +196,18 @@ function makeStreamReducerEvent(
|
||||
};
|
||||
}
|
||||
|
||||
function receiveSteer() {
|
||||
return processAgentStreamEvents({
|
||||
events: [
|
||||
makeStreamReducerEvent(makeAssistantTimelineEvent("with the uncommit", "m1"), 2),
|
||||
makeStreamReducerEvent(makeTimelineEvent("keep going", "user_message"), 3),
|
||||
],
|
||||
currentTail: [],
|
||||
currentHead: [],
|
||||
currentCursor: { epoch: "epoch-1", startSeq: 1, endSeq: 1 },
|
||||
});
|
||||
}
|
||||
|
||||
function makeAssistantItem(
|
||||
text: string,
|
||||
id = `assistant-${text.length}`,
|
||||
@@ -1780,6 +1792,52 @@ describe("processTimelineResponse", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ source: "live prefix", text: "with the uncommit", seq: 2 },
|
||||
{ source: "earlier projected page", text: "with the uncommitted changes.", seq: 4 },
|
||||
])("reuses the assistant row from the $source across a steer", ({ text, seq }) => {
|
||||
const live = receiveSteer();
|
||||
const result = processTimelineResponse({
|
||||
...baseTimelineInput,
|
||||
currentTail: [
|
||||
{
|
||||
...makeAssistantItem(text, "m1"),
|
||||
messageId: "m1",
|
||||
timelineCursor: { epoch: "epoch-1", seq },
|
||||
},
|
||||
...live.tail.slice(1),
|
||||
],
|
||||
currentHead: live.head,
|
||||
currentCursor: live.cursor ?? undefined,
|
||||
payload: {
|
||||
...baseTimelineInput.payload,
|
||||
direction: "after",
|
||||
epoch: "epoch-1",
|
||||
startCursor: { seq: 4 },
|
||||
endCursor: { seq: 4 },
|
||||
entries: [
|
||||
{
|
||||
...makeTimelineEntry(2, "with the uncommitted changes.", "assistant_message", 4),
|
||||
sourceSeqRanges: [
|
||||
{ startSeq: 2, endSeq: 2 },
|
||||
{ startSeq: 4, endSeq: 4 },
|
||||
],
|
||||
item: {
|
||||
type: "assistant_message",
|
||||
text: "with the uncommitted changes.",
|
||||
messageId: "m1",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect([...result.tail, ...result.head]).toMatchObject([
|
||||
{ kind: "assistant_message", text: "with the uncommitted changes.", messageId: "m1" },
|
||||
{ kind: "user_message", text: "keep going" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps a tail submitted prompt before a reconciled live assistant head", () => {
|
||||
const prompt = makeSubmittedUserMessage("new prompt", "submitted-new-prompt");
|
||||
|
||||
@@ -3977,6 +4035,22 @@ describe("processAgentStreamEvent", () => {
|
||||
});
|
||||
|
||||
describe("processAgentStreamEvents", () => {
|
||||
it("keeps a live reply in one row across a steer", () => {
|
||||
const live = receiveSteer();
|
||||
const result = processAgentStreamEvents({
|
||||
events: [makeStreamReducerEvent(makeAssistantTimelineEvent("ted changes.", "m1"), 4)],
|
||||
currentTail: live.tail,
|
||||
currentHead: live.head,
|
||||
currentCursor: live.cursor ?? undefined,
|
||||
});
|
||||
|
||||
expect(result.tail).toEqual([]);
|
||||
expect(result.head).toMatchObject([
|
||||
{ kind: "assistant_message", text: "with the uncommitted changes.", messageId: "m1" },
|
||||
{ kind: "user_message", text: "keep going" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("coalesces contiguous assistant stream events into one head update and final cursor", () => {
|
||||
const result = processAgentStreamEvents({
|
||||
events: [
|
||||
|
||||
@@ -791,21 +791,38 @@ function reconcileOverlappingProjectedAssistant(params: {
|
||||
epoch: string;
|
||||
currentEndSeq: number;
|
||||
}): { tail: StreamItem[]; head: StreamItem[]; reconciled: boolean } {
|
||||
const { unit } = params;
|
||||
if (
|
||||
unit.event.type !== "timeline" ||
|
||||
unit.event.item.type !== "assistant_message" ||
|
||||
!unit.sourceSeqRanges.some(
|
||||
(range) => range.startSeq <= params.currentEndSeq && range.endSeq > params.currentEndSeq,
|
||||
)
|
||||
) {
|
||||
return { tail: params.tail, head: params.head, reconciled: false };
|
||||
const { unit, currentEndSeq, epoch } = params;
|
||||
const unchanged = { tail: params.tail, head: params.head, reconciled: false };
|
||||
if (unit.event.type !== "timeline" || unit.event.item.type !== "assistant_message") {
|
||||
return unchanged;
|
||||
}
|
||||
|
||||
const projectedText = unit.event.item.text;
|
||||
const projectedMessageId = unit.event.item.messageId;
|
||||
const crossesCursor = unit.sourceSeqRanges.some(
|
||||
(range) => range.startSeq <= currentEndSeq && range.endSeq > currentEndSeq,
|
||||
);
|
||||
// A steer occupies the gap between source ranges. Match that projected reply
|
||||
// by its source positions because a tool call can split rows with the same id.
|
||||
const coversItem = (item: AssistantMessageItem) => {
|
||||
const cursor = item.timelineCursor;
|
||||
return (
|
||||
cursor?.epoch === epoch &&
|
||||
unit.sourceSeqRanges.some(
|
||||
(range) => range.startSeq <= cursor.seq && cursor.seq <= range.endSeq,
|
||||
)
|
||||
);
|
||||
};
|
||||
const bridgesSteer =
|
||||
unit.sourceSeqRanges.length > 1 &&
|
||||
projectedMessageId !== undefined &&
|
||||
unit.seqEnd > currentEndSeq &&
|
||||
unit.sourceSeqRanges.some((range) => range.endSeq <= currentEndSeq);
|
||||
if (!crossesCursor && !bridgesSteer) return unchanged;
|
||||
|
||||
const matches = (item: StreamItem) => {
|
||||
if (item.kind !== "assistant_message") return false;
|
||||
if (bridgesSteer) return item.messageId === projectedMessageId && coversItem(item);
|
||||
if (projectedMessageId && item.messageId) return item.messageId === projectedMessageId;
|
||||
return projectedText.startsWith(item.text);
|
||||
};
|
||||
@@ -817,15 +834,13 @@ function reconcileOverlappingProjectedAssistant(params: {
|
||||
|
||||
const headMatch = findMatch(params.head);
|
||||
const tailMatch = findMatch(params.tail);
|
||||
const match = headMatch ?? tailMatch;
|
||||
if (!match) {
|
||||
return { tail: params.tail, head: params.head, reconciled: false };
|
||||
}
|
||||
// Keep a cached reply before the steer even if a live suffix also exists.
|
||||
const match = bridgesSteer ? (tailMatch ?? headMatch) : (headMatch ?? tailMatch);
|
||||
if (!match) return unchanged;
|
||||
|
||||
const messageId = projectedMessageId ?? match.current.messageId;
|
||||
const replacement: AssistantMessageItem = {
|
||||
kind: "assistant_message",
|
||||
id: match.current.id,
|
||||
...match.current,
|
||||
...(messageId !== undefined ? { messageId } : {}),
|
||||
text: projectedText,
|
||||
timestamp: unit.timestamp,
|
||||
@@ -837,21 +852,26 @@ function reconcileOverlappingProjectedAssistant(params: {
|
||||
return next;
|
||||
};
|
||||
|
||||
const removeMatch = (items: StreamItem[], index: number) => [
|
||||
...items.slice(0, index),
|
||||
...items.slice(index + 1),
|
||||
];
|
||||
if (bridgesSteer && tailMatch) {
|
||||
return {
|
||||
tail: replaceMatch(params.tail, tailMatch.index),
|
||||
head: headMatch ? removeMatch(params.head, headMatch.index) : params.head,
|
||||
reconciled: true,
|
||||
};
|
||||
}
|
||||
if (headMatch) {
|
||||
const tailCursor = tailMatch?.current.timelineCursor;
|
||||
const replacesCachedPrefix =
|
||||
tailMatch !== null &&
|
||||
tailCursor?.epoch === params.epoch &&
|
||||
unit.sourceSeqRanges.some(
|
||||
(range) => range.startSeq <= tailCursor.seq && tailCursor.seq <= range.endSeq,
|
||||
);
|
||||
return {
|
||||
// Live chunks can arrive before catch-up while their cached prefix is still painted.
|
||||
// The projected reply owns both copies; keeping the prefix would duplicate it and
|
||||
// cause completion to discard the updated head as an already-committed item.
|
||||
tail: replacesCachedPrefix
|
||||
? [...params.tail.slice(0, tailMatch.index), ...params.tail.slice(tailMatch.index + 1)]
|
||||
: params.tail,
|
||||
tail:
|
||||
tailMatch && coversItem(tailMatch.current)
|
||||
? removeMatch(params.tail, tailMatch.index)
|
||||
: params.tail,
|
||||
head: replaceMatch(params.head, headMatch.index),
|
||||
reconciled: true,
|
||||
};
|
||||
|
||||
@@ -959,6 +959,24 @@ function appendUserMessage(
|
||||
return upsertUserMessage(state, nextItem);
|
||||
}
|
||||
|
||||
function findSteeredAssistantIndex(
|
||||
items: StreamItem[],
|
||||
messageId: string,
|
||||
turnId: string | undefined,
|
||||
): number {
|
||||
let index = items.length - 1;
|
||||
while (items[index]?.kind === "user_message") {
|
||||
index -= 1;
|
||||
}
|
||||
const candidate = items[index];
|
||||
return index < items.length - 1 &&
|
||||
candidate?.kind === "assistant_message" &&
|
||||
candidate.messageId === messageId &&
|
||||
candidate.turnId === turnId
|
||||
? index
|
||||
: -1;
|
||||
}
|
||||
|
||||
function appendAssistantMessage(
|
||||
state: StreamItem[],
|
||||
text: string,
|
||||
@@ -967,43 +985,41 @@ function appendAssistantMessage(
|
||||
messageId?: string,
|
||||
reservedItemIds?: ReadonlySet<string>,
|
||||
timelineCursor?: TimelinePosition,
|
||||
turnId?: string,
|
||||
): StreamItem[] {
|
||||
const { chunk, hasContent } = normalizeChunk(text);
|
||||
if (!chunk) {
|
||||
return state;
|
||||
}
|
||||
|
||||
const last = state[state.length - 1];
|
||||
const shouldAppendToLast =
|
||||
last &&
|
||||
last.kind === "assistant_message" &&
|
||||
(messageId === undefined || last.messageId === messageId);
|
||||
if (shouldAppendToLast) {
|
||||
const updated: AssistantMessageItem = {
|
||||
...last,
|
||||
text: `${last.text}${chunk}`,
|
||||
timestamp,
|
||||
...(timelineCursor ? { timelineCursor } : {}),
|
||||
};
|
||||
return [...state.slice(0, -1), updated];
|
||||
const lastIndex = state.length - 1;
|
||||
const last = state[lastIndex];
|
||||
let index = -1;
|
||||
if (
|
||||
last?.kind === "assistant_message" &&
|
||||
(messageId === undefined || last.messageId === messageId)
|
||||
) {
|
||||
index = lastIndex;
|
||||
} else if (source === "live") {
|
||||
if (messageId !== undefined) {
|
||||
index = findSteeredAssistantIndex(state, messageId, turnId);
|
||||
} else if (
|
||||
last?.kind === "user_message" &&
|
||||
state[lastIndex - 1]?.kind === "assistant_message"
|
||||
) {
|
||||
index = lastIndex - 1;
|
||||
}
|
||||
}
|
||||
|
||||
// A submitted user row can follow the streaming assistant during interrupt.
|
||||
// In that case, look one row further back for the assistant to extend.
|
||||
const secondLast = state[state.length - 2];
|
||||
if (
|
||||
source === "live" &&
|
||||
last?.kind === "user_message" &&
|
||||
secondLast?.kind === "assistant_message" &&
|
||||
(messageId === undefined || secondLast.messageId === messageId)
|
||||
) {
|
||||
const previous = state[index];
|
||||
if (previous?.kind === "assistant_message") {
|
||||
const updated: AssistantMessageItem = {
|
||||
...secondLast,
|
||||
text: `${secondLast.text}${chunk}`,
|
||||
...previous,
|
||||
text: `${previous.text}${chunk}`,
|
||||
timestamp,
|
||||
...(timelineCursor ? { timelineCursor } : {}),
|
||||
};
|
||||
return [...state.slice(0, -2), updated, last];
|
||||
return [...state.slice(0, index), updated, ...state.slice(index + 1)];
|
||||
}
|
||||
|
||||
if (!hasContent) {
|
||||
@@ -1573,6 +1589,7 @@ function reduceTimelineEvent(
|
||||
item.messageId,
|
||||
reservedItemIds,
|
||||
timelineCursor,
|
||||
event.turnId,
|
||||
);
|
||||
case "reasoning":
|
||||
return appendThought(state, item.text, timestamp, timelineCursor, event.turnId);
|
||||
@@ -1810,23 +1827,27 @@ function getActiveAssistantHeadIndex(head: StreamItem[]): number {
|
||||
return -1;
|
||||
}
|
||||
|
||||
function getTailAssistantToResume(params: {
|
||||
function getTailAssistantResumeIndex(params: {
|
||||
incomingKind: StreamItem["kind"] | null;
|
||||
event: AgentStreamEventPayload;
|
||||
nextHead: StreamItem[];
|
||||
tailAssistant: StreamItem | undefined;
|
||||
}): AssistantMessageItem | null {
|
||||
if (params.incomingKind !== "assistant_message" || params.nextHead.length !== 0) {
|
||||
return null;
|
||||
tail: StreamItem[];
|
||||
source: StreamUpdateSource;
|
||||
}): number {
|
||||
const { incomingKind, event, nextHead, tail, source } = params;
|
||||
if (incomingKind !== "assistant_message" || nextHead.length !== 0) return -1;
|
||||
|
||||
const messageId = getIncomingAssistantMessageId(event);
|
||||
const last = tail.at(-1);
|
||||
if (
|
||||
last?.kind === "assistant_message" &&
|
||||
(messageId === undefined || last.messageId === messageId)
|
||||
) {
|
||||
return tail.length - 1;
|
||||
}
|
||||
if (params.tailAssistant?.kind !== "assistant_message") {
|
||||
return null;
|
||||
}
|
||||
const incomingMessageId = getIncomingAssistantMessageId(params.event);
|
||||
if (incomingMessageId !== undefined && params.tailAssistant.messageId !== incomingMessageId) {
|
||||
return null;
|
||||
}
|
||||
return params.tailAssistant;
|
||||
return source === "live" && event.type === "timeline" && messageId !== undefined
|
||||
? findSteeredAssistantIndex(tail, messageId, event.turnId)
|
||||
: -1;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2055,15 +2076,17 @@ export function applyStreamEvent(params: {
|
||||
flushHead();
|
||||
}
|
||||
|
||||
const tailAssistant = getTailAssistantToResume({
|
||||
const resumeIndex = getTailAssistantResumeIndex({
|
||||
incomingKind,
|
||||
event,
|
||||
nextHead,
|
||||
tailAssistant: nextTail.at(-1),
|
||||
tail: nextTail,
|
||||
source,
|
||||
});
|
||||
if (tailAssistant) {
|
||||
nextTail = nextTail.slice(0, -1);
|
||||
nextHead = [tailAssistant];
|
||||
if (resumeIndex >= 0) {
|
||||
// Move any steers with the reply so the reply stays above them as it streams.
|
||||
nextHead = nextTail.slice(resumeIndex);
|
||||
nextTail = nextTail.slice(0, resumeIndex);
|
||||
changedTail = true;
|
||||
changedHead = true;
|
||||
}
|
||||
|
||||
|
Before Width: | Height: | Size: 6.9 KiB After Width: | Height: | Size: 3.6 KiB |
|
Before Width: | Height: | Size: 14 KiB After Width: | Height: | Size: 7.7 KiB |
|
Before Width: | Height: | Size: 1.6 KiB After Width: | Height: | Size: 994 B |
|
Before Width: | Height: | Size: 3.3 KiB After Width: | Height: | Size: 1.8 KiB |
|
Before Width: | Height: | Size: 863 KiB After Width: | Height: | Size: 72 KiB |
|
Before Width: | Height: | Size: 27 KiB After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 5.9 KiB |
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"fill": {
|
||||
"solid": "srgb:0.00000,0.00000,0.00000,1.00000"
|
||||
},
|
||||
"groups": [
|
||||
{
|
||||
"layers": [
|
||||
{
|
||||
"image-name": "butterfly.svg",
|
||||
"name": "butterfly"
|
||||
}
|
||||
],
|
||||
"shadow": {
|
||||
"kind": "neutral",
|
||||
"opacity": 0.5
|
||||
},
|
||||
"translucency": {
|
||||
"enabled": false,
|
||||
"value": 0.5
|
||||
}
|
||||
}
|
||||
],
|
||||
"supported-platforms": {
|
||||
"squares": [
|
||||
"macOS"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 31 KiB After Width: | Height: | Size: 18 KiB |
@@ -43,7 +43,8 @@ mac:
|
||||
artifactName: "Paseo-${version}-${arch}.${ext}"
|
||||
minimumSystemVersion: "13.0.0"
|
||||
category: public.app-category.developer-tools
|
||||
icon: assets/icon.icns
|
||||
# An Icon Composer document, compiled by Xcode's actool (26 or later) at build time.
|
||||
icon: assets/icon.icon
|
||||
hardenedRuntime: true
|
||||
notarize: true
|
||||
entitlements: build/entitlements.mac.plist
|
||||
@@ -56,6 +57,9 @@ mac:
|
||||
target:
|
||||
- dmg
|
||||
- zip
|
||||
dmg:
|
||||
# actool also derives an .icns from the document, but only up to 256 px.
|
||||
icon: assets/icon.icns
|
||||
linux:
|
||||
category: Development
|
||||
icon: assets
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Duplex, PassThrough } from "node:stream";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
import {
|
||||
decodeNetworkTunnelFrame,
|
||||
encodeNetworkTunnelFrame,
|
||||
@@ -278,20 +278,30 @@ describe("TunnelMuxClient", () => {
|
||||
});
|
||||
|
||||
test("sends heartbeat pings and closes a silent half-open wire after heartbeatTimeoutMs", async () => {
|
||||
const fake = createFakeWire();
|
||||
const mux = new TunnelMuxClient(fake.wire, {
|
||||
heartbeatIntervalMs: 25,
|
||||
heartbeatTimeoutMs: 65,
|
||||
});
|
||||
// The clock is faked: on a slow machine the first real interval tick can land after the
|
||||
// timeout, and then the wire closes before any ping goes out.
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const fake = createFakeWire();
|
||||
const mux = new TunnelMuxClient(fake.wire, {
|
||||
heartbeatIntervalMs: 25,
|
||||
heartbeatTimeoutMs: 65,
|
||||
});
|
||||
let closeErr: Error | undefined;
|
||||
mux.onClose((err) => {
|
||||
closeErr = err;
|
||||
});
|
||||
|
||||
const closed = new Promise<Error | undefined>((resolve) => {
|
||||
mux.onClose((err) => resolve(err));
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
expect(fake.sentFrames.filter((f) => f.type === "ping")).toHaveLength(2);
|
||||
expect(mux.isClosed()).toBe(false);
|
||||
|
||||
const closeErr = await closed;
|
||||
expect(mux.isClosed()).toBe(true);
|
||||
expect(fake.sentFrames.some((f) => f.type === "ping")).toBe(true);
|
||||
expect(closeErr?.message).toMatch(/heartbeat/i);
|
||||
await vi.advanceTimersByTimeAsync(25);
|
||||
expect(mux.isClosed()).toBe(true);
|
||||
expect(closeErr?.message).toMatch(/heartbeat/i);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
test("closes an unresponsive wire when openStream times out with zero inbound frames", async () => {
|
||||
|
||||
@@ -4,7 +4,8 @@ import path from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const STAMP_CACHE_VERSION = "v2";
|
||||
// Stamped icons are cached under this version. Bump it when the stamp or the base icon art changes.
|
||||
const STAMP_CACHE_VERSION = "v3";
|
||||
|
||||
export const MONOSPACE_FONT_CANDIDATES = [
|
||||
"Menlo-Bold",
|
||||
|
||||
@@ -10,6 +10,8 @@ import {
|
||||
type Client,
|
||||
type AgentCapabilities,
|
||||
type ContentBlock,
|
||||
type CreateElicitationRequest,
|
||||
type CreateElicitationResponse,
|
||||
type NewSessionResponse,
|
||||
type RequestPermissionRequest,
|
||||
type RequestPermissionResponse,
|
||||
@@ -33,6 +35,7 @@ import type {
|
||||
AcpVendorUpdate,
|
||||
RunAcpProviderOptions,
|
||||
} from "../acp.js";
|
||||
import { AcpFormElicitation } from "./elicitation.js";
|
||||
import { standardToolCallDetail } from "./tool-call-detail.js";
|
||||
import {
|
||||
PROVIDER_PROTOCOL_VERSION,
|
||||
@@ -536,12 +539,22 @@ interface StartRuntimeOptions {
|
||||
onRetired?: () => void;
|
||||
}
|
||||
|
||||
interface PendingPermission {
|
||||
interface PendingToolPermission {
|
||||
kind: "tool";
|
||||
request: RequestPermissionRequest;
|
||||
turnId: string | undefined;
|
||||
resolve(response: RequestPermissionResponse): void;
|
||||
}
|
||||
|
||||
interface PendingElicitation {
|
||||
kind: "elicitation";
|
||||
form: AcpFormElicitation;
|
||||
turnId: string | undefined;
|
||||
resolve(response: CreateElicitationResponse): void;
|
||||
}
|
||||
|
||||
type PendingPermission = PendingToolPermission | PendingElicitation;
|
||||
|
||||
type DeferredTurnOutcome =
|
||||
| { type: "complete"; terminalizeTools: boolean }
|
||||
| { type: "cancel" }
|
||||
@@ -593,6 +606,7 @@ class AcpRuntime {
|
||||
private readonly vendorToolCalls = new Map<string, ToolCallTimelineItem>();
|
||||
private readonly pendingCompactions = new Set<string>();
|
||||
private readonly permissions = new Map<string, PendingPermission>();
|
||||
private elicitationSequence = 0;
|
||||
private readonly transformers: readonly AcpTransformer[];
|
||||
private configOptions: SessionConfigOption[] = [];
|
||||
private modes: NewSessionResponse["modes"] = null;
|
||||
@@ -686,7 +700,7 @@ class AcpRuntime {
|
||||
runtime.call(
|
||||
runtime.connection.initialize({
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
clientCapabilities: {},
|
||||
clientCapabilities: { elicitation: { form: {} } },
|
||||
clientInfo: options.clientInfo ?? DEFAULT_CLIENT_INFO,
|
||||
}),
|
||||
),
|
||||
@@ -722,6 +736,7 @@ class AcpRuntime {
|
||||
this.transformers = options.options.transformers ?? [];
|
||||
const client: Client = {
|
||||
requestPermission: (request) => this.requestPermission(request),
|
||||
createElicitation: (request) => this.createElicitation(request),
|
||||
sessionUpdate: (notification) => {
|
||||
const wireSeq = this.sessionUpdateWireSeqs.shift() ?? ++this.incomingWireSeq;
|
||||
return this.enqueueNotification(() => this.sessionUpdate(notification, wireSeq));
|
||||
@@ -1120,6 +1135,10 @@ class AcpRuntime {
|
||||
if (!pending) return;
|
||||
const active = this.activePrompt;
|
||||
if (active?.cancelling && pending.turnId === active.turnId) return;
|
||||
if (pending.kind === "elicitation") {
|
||||
this.resolveElicitation(permissionId, pending, pending.form.respond(response));
|
||||
return;
|
||||
}
|
||||
const selected = selectPermissionOption(pending.request.options, response);
|
||||
if (response.selectedActionId !== undefined && !selected) {
|
||||
throw new Error(
|
||||
@@ -1135,7 +1154,10 @@ class AcpRuntime {
|
||||
|
||||
private finishTurnPermissions(turnId: string): void {
|
||||
for (const [permissionId, pending] of this.permissions) {
|
||||
if (pending.turnId === turnId) {
|
||||
if (pending.turnId !== turnId) continue;
|
||||
if (pending.kind === "elicitation") {
|
||||
this.resolveElicitation(permissionId, pending, { action: "cancel" });
|
||||
} else {
|
||||
this.resolvePermission(permissionId, pending, { outcome: { outcome: "cancelled" } });
|
||||
}
|
||||
}
|
||||
@@ -1143,7 +1165,7 @@ class AcpRuntime {
|
||||
|
||||
private resolvePermission(
|
||||
permissionId: string,
|
||||
pending: PendingPermission,
|
||||
pending: PendingToolPermission,
|
||||
response: RequestPermissionResponse,
|
||||
): void {
|
||||
this.permissions.delete(permissionId);
|
||||
@@ -1156,6 +1178,21 @@ class AcpRuntime {
|
||||
if (this.activePrompt?.deferred) this.scheduleDeferredSettle();
|
||||
}
|
||||
|
||||
private resolveElicitation(
|
||||
permissionId: string,
|
||||
pending: PendingElicitation,
|
||||
response: CreateElicitationResponse,
|
||||
): void {
|
||||
this.permissions.delete(permissionId);
|
||||
pending.resolve(response);
|
||||
this.emit({
|
||||
type: "session.permission_resolved",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
permissionId,
|
||||
});
|
||||
if (this.activePrompt?.deferred) this.scheduleDeferredSettle();
|
||||
}
|
||||
|
||||
async configure(
|
||||
changes: Extract<ProviderInput, { type: "session.configure" }>["changes"],
|
||||
): Promise<void> {
|
||||
@@ -1219,6 +1256,10 @@ class AcpRuntime {
|
||||
}
|
||||
|
||||
async closeSession(): Promise<void> {
|
||||
if (this.cancelPendingPermissions()) {
|
||||
// Let the ACP SDK flush the cancel response on the wire before closing the session/stream.
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
}
|
||||
if (this.nativeSessionId) {
|
||||
await withTimeout(
|
||||
this.call(this.connection.closeSession({ sessionId: this.nativeSessionId })),
|
||||
@@ -1495,7 +1536,12 @@ class AcpRuntime {
|
||||
const permissionId = `permission:${request.toolCall.toolCallId}`;
|
||||
const { presentation } = this.presentToolCall(request.toolCall);
|
||||
return new Promise((resolve) => {
|
||||
this.permissions.set(permissionId, { request, resolve, turnId: this.activePrompt?.turnId });
|
||||
this.permissions.set(permissionId, {
|
||||
kind: "tool",
|
||||
request,
|
||||
resolve,
|
||||
turnId: this.activePrompt?.turnId,
|
||||
});
|
||||
if (this.activePrompt?.deferred) this.scheduleDeferredSettle();
|
||||
this.emit({
|
||||
type: "session.permission",
|
||||
@@ -1517,6 +1563,54 @@ class AcpRuntime {
|
||||
});
|
||||
}
|
||||
|
||||
private async createElicitation(
|
||||
request: CreateElicitationRequest,
|
||||
): Promise<CreateElicitationResponse> {
|
||||
await this.notificationLane;
|
||||
if (this.closing || this.processFailed || this.activePrompt?.cancelling) {
|
||||
return { action: "cancel" };
|
||||
}
|
||||
// Forms are only answerable during an active turn of this session; declining out-of-turn
|
||||
// or mismatched requests avoids hanging session open, discovery, or idle connections.
|
||||
if (
|
||||
!this.activePrompt ||
|
||||
request.mode !== "form" ||
|
||||
!("sessionId" in request) ||
|
||||
typeof request.sessionId !== "string" ||
|
||||
!this.nativeSessionId ||
|
||||
request.sessionId !== this.nativeSessionId
|
||||
) {
|
||||
return { action: "decline" };
|
||||
}
|
||||
const toolCallId =
|
||||
"toolCallId" in request && typeof request.toolCallId === "string"
|
||||
? request.toolCallId
|
||||
: undefined;
|
||||
const toolName = toolCallId ? this.toolCalls.get(toolCallId)?.presentation.name : undefined;
|
||||
const form = AcpFormElicitation.parse(request, { toolName });
|
||||
if (!form) {
|
||||
return { action: "decline" };
|
||||
}
|
||||
const permissionId = toolCallId
|
||||
? `elicitation:${toolCallId}:${++this.elicitationSequence}`
|
||||
: `elicitation:${++this.elicitationSequence}`;
|
||||
const turnId = this.activePrompt.turnId;
|
||||
return new Promise((resolve) => {
|
||||
this.permissions.set(permissionId, {
|
||||
kind: "elicitation",
|
||||
form,
|
||||
resolve,
|
||||
turnId,
|
||||
});
|
||||
if (this.activePrompt?.deferred) this.scheduleDeferredSettle();
|
||||
this.emit({
|
||||
type: "session.permission",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
request: { id: permissionId, ...form.request },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private observeWireMessage(message: unknown): void {
|
||||
if (typeof message !== "object" || message === null) return;
|
||||
const record = message as Record<string, unknown>;
|
||||
@@ -1898,11 +1992,21 @@ class AcpRuntime {
|
||||
});
|
||||
}
|
||||
|
||||
private settlePendingWork(failureMessage?: string): void {
|
||||
private cancelPendingPermissions(): boolean {
|
||||
if (this.permissions.size === 0) return false;
|
||||
for (const permission of this.permissions.values()) {
|
||||
permission.resolve({ outcome: { outcome: "cancelled" } });
|
||||
if (permission.kind === "elicitation") {
|
||||
permission.resolve({ action: "cancel" });
|
||||
} else {
|
||||
permission.resolve({ outcome: { outcome: "cancelled" } });
|
||||
}
|
||||
}
|
||||
this.permissions.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
private settlePendingWork(failureMessage?: string): void {
|
||||
this.cancelPendingPermissions();
|
||||
if (this.activePrompt?.deferred) {
|
||||
this.finishDeferredTurn(
|
||||
this.activePrompt,
|
||||
|
||||
@@ -0,0 +1,716 @@
|
||||
import type { CreateElicitationRequest } from "@agentclientprotocol/sdk";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { AcpFormElicitation } from "./elicitation.js";
|
||||
|
||||
function formRequest(
|
||||
properties: Record<string, unknown>,
|
||||
options: {
|
||||
message?: string;
|
||||
title?: string;
|
||||
required?: string[];
|
||||
toolCallId?: string;
|
||||
} = {},
|
||||
): CreateElicitationRequest {
|
||||
return {
|
||||
sessionId: "sess-1",
|
||||
mode: "form",
|
||||
message: options.message ?? "The agent has a question.",
|
||||
...(options.toolCallId ? { toolCallId: options.toolCallId } : {}),
|
||||
requestedSchema: {
|
||||
type: "object",
|
||||
...(options.title ? { title: options.title } : {}),
|
||||
...(options.required ? { required: options.required } : {}),
|
||||
properties,
|
||||
},
|
||||
} as CreateElicitationRequest;
|
||||
}
|
||||
|
||||
describe("AcpFormElicitation.parse and respond", () => {
|
||||
it("maps agy single-select oneOf + sibling _other (no sentinel) and resolves choices and custom answers", () => {
|
||||
const request = formRequest(
|
||||
{
|
||||
q1: {
|
||||
type: "string",
|
||||
title: "Pick a color:",
|
||||
oneOf: [
|
||||
{ const: "1", title: "(Recommended) Red" },
|
||||
{ const: "2", title: "Blue" },
|
||||
],
|
||||
},
|
||||
q1_other: {
|
||||
type: "string",
|
||||
title: "Other",
|
||||
description: "Optional free-form answer to: Pick a color:",
|
||||
},
|
||||
},
|
||||
{ toolCallId: "ask-1" },
|
||||
);
|
||||
|
||||
const parsed = AcpFormElicitation.parse(request, { toolName: "ask_question" });
|
||||
expect(parsed).not.toBeNull();
|
||||
expect(parsed!.request).toEqual({
|
||||
name: "ask_question",
|
||||
kind: "question",
|
||||
title: "Pick a color:",
|
||||
description: "The agent has a question.",
|
||||
input: {
|
||||
questions: [
|
||||
{
|
||||
id: "q1",
|
||||
header: "Question",
|
||||
question: "Pick a color:",
|
||||
options: [{ label: "(Recommended) Red" }, { label: "Blue" }],
|
||||
multiSelect: false,
|
||||
allowOther: true,
|
||||
allowEmpty: false,
|
||||
placeholder: "Optional free-form answer to: Pick a color:",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
parsed!.respond({
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { Question: "Blue" } },
|
||||
}),
|
||||
).toEqual({ action: "accept", content: { q1: "2" } });
|
||||
|
||||
expect(
|
||||
parsed!.respond({
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { Question: "Green" } },
|
||||
}),
|
||||
).toEqual({ action: "accept", content: { q1_other: "Green" } });
|
||||
|
||||
expect(parsed!.respond({ behavior: "deny" })).toEqual({ action: "decline" });
|
||||
});
|
||||
|
||||
it("folds Factory Droid 'other' sentinel option with sibling _other for both single-select and multi-select", () => {
|
||||
const request = formRequest(
|
||||
{
|
||||
question_0: {
|
||||
type: "string",
|
||||
title: "Approach",
|
||||
description: "How should the theme be added?",
|
||||
oneOf: [
|
||||
{ const: "option_0", title: "Extend the palette" },
|
||||
{ const: "option_1", title: "New theme file" },
|
||||
{ const: "other", title: "Other answer" },
|
||||
],
|
||||
},
|
||||
question_0_other: {
|
||||
type: "string",
|
||||
title: "Approach: Other answer",
|
||||
description: "Enter your answer here if you select Other answer.",
|
||||
},
|
||||
question_1: {
|
||||
type: "array",
|
||||
title: "Platforms",
|
||||
description: "Which platforms should get it?",
|
||||
items: {
|
||||
anyOf: [
|
||||
{ const: "option_0", title: "Web" },
|
||||
{ const: "option_1", title: "iOS" },
|
||||
{ const: "other", title: "Other answer" },
|
||||
],
|
||||
},
|
||||
minItems: 1,
|
||||
},
|
||||
question_1_other: {
|
||||
type: "string",
|
||||
title: "Platforms: Other answer",
|
||||
description: "Enter your answer here if you select Other answer.",
|
||||
},
|
||||
},
|
||||
{ message: "Need your input", required: ["question_0", "question_1"] },
|
||||
);
|
||||
|
||||
const parsed = AcpFormElicitation.parse(request)!;
|
||||
expect(parsed.request.input).toEqual({
|
||||
questions: [
|
||||
{
|
||||
id: "question_0",
|
||||
header: "Approach",
|
||||
question: "How should the theme be added?",
|
||||
options: [{ label: "Extend the palette" }, { label: "New theme file" }],
|
||||
multiSelect: false,
|
||||
allowOther: true,
|
||||
allowEmpty: false,
|
||||
placeholder: "Enter your answer here if you select Other answer.",
|
||||
},
|
||||
{
|
||||
id: "question_1",
|
||||
header: "Platforms",
|
||||
question: "Which platforms should get it?",
|
||||
options: [{ label: "Web" }, { label: "iOS" }],
|
||||
multiSelect: true,
|
||||
allowOther: true,
|
||||
allowEmpty: false,
|
||||
placeholder: "Enter your answer here if you select Other answer.",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// Picking normal options omits _other.
|
||||
expect(
|
||||
parsed.respond({
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { Approach: "New theme file", Platforms: "Web, iOS" } },
|
||||
}),
|
||||
).toEqual({
|
||||
action: "accept",
|
||||
content: { question_0: "option_1", question_1: ["option_0", "option_1"] },
|
||||
});
|
||||
|
||||
// Typing custom text includes the "other" sentinel alongside _other.
|
||||
expect(
|
||||
parsed.respond({
|
||||
behavior: "allow",
|
||||
updatedInput: {
|
||||
answers: { Approach: "Hybrid CSS", Platforms: "Web, Android" },
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
action: "accept",
|
||||
content: {
|
||||
question_0: "other",
|
||||
question_0_other: "Hybrid CSS",
|
||||
question_1: ["option_0", "other"],
|
||||
question_1_other: "Android",
|
||||
},
|
||||
});
|
||||
|
||||
// Multi-select custom text alone still sends ["other"] sentinel.
|
||||
expect(
|
||||
parsed.respond({
|
||||
behavior: "allow",
|
||||
updatedInput: {
|
||||
answers: { Approach: "Extend the palette", Platforms: "Desktop only" },
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
action: "accept",
|
||||
content: {
|
||||
question_0: "option_0",
|
||||
question_1: ["other"],
|
||||
question_1_other: "Desktop only",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("supports single-select enum and multi-select items.anyOf, items.oneOf, and items.enum", () => {
|
||||
const parsed = AcpFormElicitation.parse(
|
||||
formRequest({
|
||||
size: {
|
||||
type: "string",
|
||||
title: "Size",
|
||||
description: "Choose a size",
|
||||
enum: ["S", "M", "L"],
|
||||
},
|
||||
tagsAny: {
|
||||
type: "array",
|
||||
title: "Tags",
|
||||
description: "Pick tags",
|
||||
items: {
|
||||
anyOf: [
|
||||
{ const: "a", title: "Alpha" },
|
||||
{ const: "b", title: "Beta" },
|
||||
],
|
||||
},
|
||||
},
|
||||
tagsOne: {
|
||||
type: "array",
|
||||
title: "Scopes",
|
||||
description: "Pick scopes",
|
||||
items: {
|
||||
oneOf: [
|
||||
{ const: "ui", title: "UI" },
|
||||
{ const: "api", title: "API" },
|
||||
],
|
||||
},
|
||||
},
|
||||
flags: {
|
||||
type: "array",
|
||||
title: "Flags",
|
||||
description: "Pick flags",
|
||||
items: { type: "string", enum: ["fast", "strict"] },
|
||||
},
|
||||
}),
|
||||
)!;
|
||||
|
||||
expect(
|
||||
parsed.respond({
|
||||
behavior: "allow",
|
||||
updatedInput: {
|
||||
answers: {
|
||||
Size: "M",
|
||||
Tags: "Alpha, Beta",
|
||||
Scopes: "API",
|
||||
Flags: "fast, strict",
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
action: "accept",
|
||||
content: {
|
||||
size: "M",
|
||||
tagsAny: ["a", "b"],
|
||||
tagsOne: ["api"],
|
||||
flags: ["fast", "strict"],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("disambiguates multi-select option labels containing ', ' and preserves ', ' in custom Other answers", () => {
|
||||
const parsed = AcpFormElicitation.parse(
|
||||
formRequest({
|
||||
t: {
|
||||
type: "array",
|
||||
title: "Pick targets",
|
||||
items: {
|
||||
anyOf: [
|
||||
{ const: "ab", title: "A, B" },
|
||||
{ const: "a", title: "A" },
|
||||
{ const: "b", title: "B" },
|
||||
],
|
||||
},
|
||||
},
|
||||
t_other: { type: "string", title: "Other" },
|
||||
}),
|
||||
)!;
|
||||
|
||||
const question = (
|
||||
parsed.request.input as { questions: Array<{ options: Array<{ label: string }> }> }
|
||||
).questions[0]!;
|
||||
expect(question.options.map((option) => option.label)).toEqual(["A,B", "A", "B"]);
|
||||
|
||||
// Checking "A" and "B" separately cannot be confused with "A, B".
|
||||
expect(
|
||||
parsed.respond({
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { Question: "A, B" } },
|
||||
}),
|
||||
).toEqual({ action: "accept", content: { t: ["a", "b"] } });
|
||||
|
||||
// Checking the sanitized "A,B" option alone resolves to "ab".
|
||||
expect(
|
||||
parsed.respond({
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { Question: "A,B" } },
|
||||
}),
|
||||
).toEqual({ action: "accept", content: { t: ["ab"] } });
|
||||
|
||||
// Checking "A,B" plus custom Other text containing ", " keeps both intact.
|
||||
expect(
|
||||
parsed.respond({
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { Question: "A,B, Teal, Navy" } },
|
||||
}),
|
||||
).toEqual({ action: "accept", content: { t: ["ab"], t_other: "Teal, Navy" } });
|
||||
|
||||
// Custom Other text alone omits empty t array when no sentinel exists.
|
||||
expect(
|
||||
parsed.respond({
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { Question: "Teal, Navy" } },
|
||||
}),
|
||||
).toEqual({ action: "accept", content: { t_other: "Teal, Navy" } });
|
||||
});
|
||||
|
||||
it("keeps option labels unique when duplicate titles appear", () => {
|
||||
const parsed = AcpFormElicitation.parse(
|
||||
formRequest({
|
||||
plan: {
|
||||
type: "string",
|
||||
title: "Plan",
|
||||
description: "Pick a plan",
|
||||
oneOf: [
|
||||
{ const: "v1", title: "Standard" },
|
||||
{ const: "v2", title: "Standard" },
|
||||
{ const: "v2", title: "Standard" },
|
||||
],
|
||||
},
|
||||
}),
|
||||
)!;
|
||||
|
||||
const labels = (
|
||||
parsed.request.input as { questions: Array<{ options: Array<{ label: string }> }> }
|
||||
).questions[0]!.options.map((option) => option.label);
|
||||
expect(new Set(labels).size).toBe(3);
|
||||
expect(labels[0]).toBe("Standard");
|
||||
expect(labels[1]).toBe("Standard (v2)");
|
||||
|
||||
expect(
|
||||
parsed.respond({
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { Plan: labels[1]! } },
|
||||
}),
|
||||
).toEqual({ action: "accept", content: { plan: "v2" } });
|
||||
});
|
||||
|
||||
it("produces concise unique headers when titles are long, verbatim, or duplicated", () => {
|
||||
const longTitle =
|
||||
"Which deployment strategy should we use for the upcoming multi-region migration?";
|
||||
const parsed = AcpFormElicitation.parse(
|
||||
formRequest({
|
||||
first: { type: "string", title: longTitle, description: "Choose carefully." },
|
||||
second: { type: "string", title: "Scope", description: "First scope" },
|
||||
third: { type: "string", title: "Scope", description: "Second scope" },
|
||||
fourth: { type: "string", title: "Same text", description: "Same text" },
|
||||
}),
|
||||
)!;
|
||||
|
||||
const questions = (
|
||||
parsed.request.input as {
|
||||
questions: Array<{ header: string; question: string }>;
|
||||
}
|
||||
).questions;
|
||||
expect(questions.map((q) => q.header)).toEqual([
|
||||
"Question 1",
|
||||
"Scope",
|
||||
"Scope (2)",
|
||||
"Question 4",
|
||||
]);
|
||||
expect(questions[0]!.question).toBe(`${longTitle}\n\nChoose carefully.`);
|
||||
expect(questions[3]!.question).toBe("Same text");
|
||||
});
|
||||
|
||||
it("marks defaults on single-select, multi-select, boolean, and prefilled text fields", () => {
|
||||
const parsed = AcpFormElicitation.parse(
|
||||
formRequest({
|
||||
env: {
|
||||
type: "string",
|
||||
title: "Env",
|
||||
description: "Target environment",
|
||||
default: "prod",
|
||||
oneOf: [
|
||||
{ const: "dev", title: "Dev" },
|
||||
{ const: "prod", title: "Prod", description: "Live cluster" },
|
||||
],
|
||||
},
|
||||
regions: {
|
||||
type: "array",
|
||||
title: "Regions",
|
||||
description: "Deploy regions",
|
||||
default: ["eu"],
|
||||
items: {
|
||||
anyOf: [
|
||||
{ const: "us", title: "US" },
|
||||
{ const: "eu", title: "EU" },
|
||||
],
|
||||
},
|
||||
},
|
||||
dryRun: {
|
||||
type: "boolean",
|
||||
title: "Dry run",
|
||||
description: "Run without applying changes?",
|
||||
default: true,
|
||||
},
|
||||
tag: {
|
||||
type: "string",
|
||||
title: "Tag",
|
||||
description: "Release tag",
|
||||
default: "v1.0.0",
|
||||
},
|
||||
}),
|
||||
)!;
|
||||
|
||||
const questions = (
|
||||
parsed.request.input as {
|
||||
questions: Array<{
|
||||
header: string;
|
||||
options: Array<{ label: string; description?: string }>;
|
||||
allowOther: boolean;
|
||||
allowEmpty: boolean;
|
||||
}>;
|
||||
}
|
||||
).questions;
|
||||
|
||||
expect(questions[0]!.options).toEqual([
|
||||
{ label: "Dev" },
|
||||
{ label: "Prod", description: "Live cluster (Default)" },
|
||||
]);
|
||||
expect(questions[1]!.options).toEqual([
|
||||
{ label: "US" },
|
||||
{ label: "EU", description: "Default" },
|
||||
{ label: "None" },
|
||||
]);
|
||||
expect(questions[2]!.options).toEqual([
|
||||
{ label: "Yes", description: "Default" },
|
||||
{ label: "No" },
|
||||
]);
|
||||
expect(questions[3]).toMatchObject({
|
||||
options: [{ label: "v1.0.0", description: "Default" }],
|
||||
allowOther: true,
|
||||
allowEmpty: true,
|
||||
});
|
||||
|
||||
// Unanswered prefilled text and boolean fall back to their defaults; explicit answers override.
|
||||
expect(
|
||||
parsed.respond({
|
||||
behavior: "allow",
|
||||
updatedInput: {
|
||||
answers: {
|
||||
Env: "Dev",
|
||||
Regions: "None",
|
||||
"Dry run": "No",
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
action: "accept",
|
||||
content: {
|
||||
env: "dev",
|
||||
regions: [],
|
||||
dryRun: false,
|
||||
tag: "v1.0.0",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("uses 'No selection' when an optional multi-select without Other already has a 'None' option", () => {
|
||||
const parsed = AcpFormElicitation.parse(
|
||||
formRequest({
|
||||
extras: {
|
||||
type: "array",
|
||||
title: "Extras",
|
||||
description: "Pick extras",
|
||||
items: { type: "string", enum: ["None", "Docs"] },
|
||||
},
|
||||
}),
|
||||
)!;
|
||||
|
||||
const options = (
|
||||
parsed.request.input as { questions: Array<{ options: Array<{ label: string }> }> }
|
||||
).questions[0]!.options;
|
||||
expect(options.map((o) => o.label)).toEqual(["None", "Docs", "No selection"]);
|
||||
|
||||
expect(
|
||||
parsed.respond({
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { Extras: "No selection" } },
|
||||
}),
|
||||
).toEqual({ action: "accept", content: { extras: [] } });
|
||||
|
||||
expect(
|
||||
parsed.respond({
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { Extras: "None" } },
|
||||
}),
|
||||
).toEqual({ action: "accept", content: { extras: ["None"] } });
|
||||
});
|
||||
|
||||
it("sets dismissLabel 'Skip' when every field is optional free text, and omits it otherwise", () => {
|
||||
const allOptionalText = AcpFormElicitation.parse(
|
||||
formRequest({
|
||||
note: { type: "string", title: "Note", description: "Any notes?" },
|
||||
ref: { type: "string", title: "Ref", description: "Ticket link?" },
|
||||
}),
|
||||
)!;
|
||||
const optionalQuestions = (
|
||||
allOptionalText.request.input as {
|
||||
questions: Array<{ allowEmpty: boolean; dismissLabel?: string }>;
|
||||
}
|
||||
).questions;
|
||||
expect(optionalQuestions.every((q) => q.allowEmpty && q.dismissLabel === "Skip")).toBe(true);
|
||||
expect(
|
||||
allOptionalText.respond({
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { Note: "", Ref: "" } },
|
||||
}),
|
||||
).toEqual({ action: "accept", content: {} });
|
||||
|
||||
const mixedRequired = AcpFormElicitation.parse(
|
||||
formRequest(
|
||||
{
|
||||
name: { type: "string", title: "Name", description: "Project name" },
|
||||
note: { type: "string", title: "Note", description: "Optional note" },
|
||||
},
|
||||
{ required: ["name"] },
|
||||
),
|
||||
)!;
|
||||
const mixedQuestions = (
|
||||
mixedRequired.request.input as {
|
||||
questions: Array<{ allowEmpty: boolean; dismissLabel?: string }>;
|
||||
}
|
||||
).questions;
|
||||
expect(mixedQuestions[0]!.allowEmpty).toBe(false);
|
||||
expect(mixedQuestions[1]!.allowEmpty).toBe(true);
|
||||
expect(mixedQuestions.some((q) => q.dismissLabel !== undefined)).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps __proto__ and Object.prototype keys safe in schema properties and answer maps", () => {
|
||||
const properties = Object.fromEntries([
|
||||
["__proto__", { type: "string", title: "__proto__", description: "Proto value" }],
|
||||
["toString", { type: "string", title: "toString", description: "String value" }],
|
||||
]);
|
||||
const parsed = AcpFormElicitation.parse(formRequest(properties))!;
|
||||
const answers = Object.fromEntries([
|
||||
["__proto__", "safe-proto"],
|
||||
["toString", "safe-string"],
|
||||
]);
|
||||
|
||||
const response = parsed.respond({
|
||||
behavior: "allow",
|
||||
updatedInput: { answers },
|
||||
});
|
||||
expect(response.action).toBe("accept");
|
||||
const content = (response as { action: "accept"; content: Record<string, unknown> }).content;
|
||||
expect(Object.hasOwn(content, "__proto__")).toBe(true);
|
||||
expect(content["__proto__"]).toBe("safe-proto");
|
||||
expect(content.toString).toBe("safe-string");
|
||||
expect(({} as Record<string, unknown>).polluted).toBeUndefined();
|
||||
});
|
||||
|
||||
it("does not absorb a required or non-plain-string sibling _other property", () => {
|
||||
const requiredOther = AcpFormElicitation.parse(
|
||||
formRequest(
|
||||
{
|
||||
q1: { type: "string", title: "Q1", enum: ["a", "b"] },
|
||||
q1_other: { type: "string", title: "Extra", description: "Always required" },
|
||||
},
|
||||
{ required: ["q1_other"] },
|
||||
),
|
||||
)!;
|
||||
const questions = (requiredOther.request.input as { questions: Array<{ id: string }> })
|
||||
.questions;
|
||||
expect(questions.map((q) => q.id)).toEqual(["q1", "q1_other"]);
|
||||
|
||||
// A malformed _other property with an invalid oneOf declines the whole form instead of being absorbed.
|
||||
const malformedOther = AcpFormElicitation.parse(
|
||||
formRequest({
|
||||
q1: { type: "string", title: "Q1", enum: ["a", "b"] },
|
||||
q1_other: { type: "string", title: "Other", oneOf: [{ title: "missing-const" }] },
|
||||
}),
|
||||
);
|
||||
expect(malformedOther).toBeNull();
|
||||
|
||||
// A required choice (or minItems > 0 multi-select) without an "other" sentinel keeps
|
||||
// <key>_other as a separate optional text field so accepted content always satisfies the schema.
|
||||
const requiredPrimaryWithoutSentinel = AcpFormElicitation.parse(
|
||||
formRequest(
|
||||
{
|
||||
q1: { type: "string", title: "Mode", description: "Pick mode", enum: ["fast", "safe"] },
|
||||
q1_other: { type: "string", title: "Notes", description: "Optional notes" },
|
||||
tags: {
|
||||
type: "array",
|
||||
title: "Tags",
|
||||
description: "Pick at least one",
|
||||
minItems: 1,
|
||||
items: { type: "string", enum: ["a", "b"] },
|
||||
},
|
||||
tags_other: { type: "string", title: "Extra tag", description: "Optional extra" },
|
||||
},
|
||||
{ required: ["q1"] },
|
||||
),
|
||||
)!;
|
||||
const sepQuestions = (
|
||||
requiredPrimaryWithoutSentinel.request.input as {
|
||||
questions: Array<{ id: string; allowOther: boolean; allowEmpty: boolean }>;
|
||||
}
|
||||
).questions;
|
||||
expect(sepQuestions.map((q) => [q.id, q.allowOther, q.allowEmpty])).toEqual([
|
||||
["q1", false, false],
|
||||
["q1_other", true, true],
|
||||
["tags", false, false],
|
||||
["tags_other", true, true],
|
||||
]);
|
||||
expect(
|
||||
requiredPrimaryWithoutSentinel.respond({
|
||||
behavior: "allow",
|
||||
updatedInput: {
|
||||
answers: { Mode: "fast", Notes: "custom", Tags: "a", "Extra tag": "" },
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
action: "accept",
|
||||
content: { q1: "fast", q1_other: "custom", tags: ["a"] },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"url mode",
|
||||
{
|
||||
sessionId: "sess-1",
|
||||
mode: "url",
|
||||
elicitationId: "e-1",
|
||||
url: "https://example.com/auth",
|
||||
message: "Sign in",
|
||||
} as CreateElicitationRequest,
|
||||
],
|
||||
[
|
||||
"unknown mode",
|
||||
{
|
||||
sessionId: "sess-1",
|
||||
mode: "custom",
|
||||
message: "Custom",
|
||||
} as CreateElicitationRequest,
|
||||
],
|
||||
["empty properties", formRequest({})],
|
||||
["number field", formRequest({ n: { type: "number", title: "Amount" } })],
|
||||
["integer field", formRequest({ count: { type: "integer", title: "Count" } })],
|
||||
["unknown field type", formRequest({ meta: { type: "object" } })],
|
||||
["empty string oneOf", formRequest({ c: { type: "string", oneOf: [] } })],
|
||||
[
|
||||
"malformed string oneOf (missing const)",
|
||||
formRequest({ c: { type: "string", oneOf: [{ title: "Alpha" }] } }),
|
||||
],
|
||||
[
|
||||
"malformed string oneOf (non-string const)",
|
||||
formRequest({ c: { type: "string", oneOf: [{ const: 1, title: "One" }] } }),
|
||||
],
|
||||
["empty string enum", formRequest({ c: { type: "string", enum: [] } })],
|
||||
[
|
||||
"malformed string enum (non-string entry)",
|
||||
formRequest({ c: { type: "string", enum: [1, 2] } }),
|
||||
],
|
||||
["malformed string anyOf", formRequest({ c: { type: "string", anyOf: [{ const: "a" }] } })],
|
||||
["array without items", formRequest({ a: { type: "array" } })],
|
||||
["array with empty anyOf", formRequest({ a: { type: "array", items: { anyOf: [] } } })],
|
||||
[
|
||||
"array with malformed oneOf",
|
||||
formRequest({ a: { type: "array", items: { oneOf: [{ title: "x" }] } } }),
|
||||
],
|
||||
["array with malformed enum", formRequest({ a: { type: "array", items: { enum: [1] } } })],
|
||||
])("returns null for %s", (_name, request) => {
|
||||
expect(AcpFormElicitation.parse(request)).toBeNull();
|
||||
});
|
||||
|
||||
it("declines cleanly without throwing when a response is missing required fields or has invalid values", () => {
|
||||
const requiredClosed = AcpFormElicitation.parse(
|
||||
formRequest(
|
||||
{
|
||||
choice: { type: "string", title: "Choice", description: "Pick one", enum: ["A", "B"] },
|
||||
flag: { type: "boolean", title: "Flag", description: "Continue?" },
|
||||
},
|
||||
{ required: ["choice", "flag"] },
|
||||
),
|
||||
)!;
|
||||
|
||||
// Missing answers
|
||||
expect(requiredClosed.respond({ behavior: "allow" })).toEqual({ action: "decline" });
|
||||
// Unmatched option on closed enum
|
||||
expect(
|
||||
requiredClosed.respond({
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { Choice: "Unknown", Flag: "Yes" } },
|
||||
}),
|
||||
).toEqual({ action: "decline" });
|
||||
// Invalid boolean value
|
||||
expect(
|
||||
requiredClosed.respond({
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { Choice: "A", Flag: "Maybe" } },
|
||||
}),
|
||||
).toEqual({ action: "decline" });
|
||||
// Non-object updatedInput.answers
|
||||
expect(
|
||||
requiredClosed.respond({
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: "bad" as unknown as Record<string, string> },
|
||||
}),
|
||||
).toEqual({ action: "decline" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,707 @@
|
||||
import type {
|
||||
CreateElicitationRequest,
|
||||
CreateElicitationResponse,
|
||||
ElicitationContentValue,
|
||||
} from "@agentclientprotocol/sdk";
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import type { ProviderPermissionRequest, ProviderPermissionResponse } from "../provider.js";
|
||||
|
||||
const OTHER_SUFFIX = "_other";
|
||||
const OTHER_SENTINEL = "other";
|
||||
const YES = "Yes";
|
||||
const NO = "No";
|
||||
const DEFAULT = "Default";
|
||||
const SKIP = "Skip";
|
||||
const NONE = "None";
|
||||
const NO_SELECTION = "No selection";
|
||||
const MAX_HEADER_LENGTH = 48;
|
||||
const MAX_TITLE_LENGTH = 120;
|
||||
|
||||
interface RawChoiceOption {
|
||||
value: string;
|
||||
label: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
interface CardOption {
|
||||
label: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
interface CardQuestion {
|
||||
id: string;
|
||||
header: string;
|
||||
question: string;
|
||||
options: CardOption[];
|
||||
multiSelect: boolean;
|
||||
allowOther: boolean;
|
||||
allowEmpty: boolean;
|
||||
placeholder?: string;
|
||||
dismissLabel?: string;
|
||||
}
|
||||
|
||||
interface OtherPairing {
|
||||
key: string;
|
||||
schema: Record<string, unknown>;
|
||||
}
|
||||
|
||||
interface OtherTarget {
|
||||
key: string;
|
||||
/** Present when the schema declares an explicit `"other"` sentinel option alongside `<key>_other`. */
|
||||
sentinelValue?: string;
|
||||
}
|
||||
|
||||
type FieldOutcome = { ok: true; entries: Array<[string, ElicitationContentValue]> } | { ok: false };
|
||||
|
||||
interface ParsedField {
|
||||
question: CardQuestion;
|
||||
resolve(answer: string | undefined): FieldOutcome;
|
||||
}
|
||||
|
||||
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function nonEmpty(value: unknown): string | undefined {
|
||||
if (typeof value !== "string") return undefined;
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function firstLine(text: string): string {
|
||||
return text.split("\n", 1)[0]?.trim() ?? text;
|
||||
}
|
||||
|
||||
function readTitledOptions(value: unknown): RawChoiceOption[] | null {
|
||||
if (!Array.isArray(value) || value.length === 0) return null;
|
||||
const options: RawChoiceOption[] = [];
|
||||
for (const entry of value) {
|
||||
if (!isPlainRecord(entry) || typeof entry.const !== "string") return null;
|
||||
if (entry.title !== undefined && entry.title !== null && typeof entry.title !== "string") {
|
||||
return null;
|
||||
}
|
||||
options.push({
|
||||
value: entry.const,
|
||||
label: nonEmpty(entry.title) ?? entry.const,
|
||||
description: nonEmpty(entry.description),
|
||||
});
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
function readEnumOptions(value: unknown): RawChoiceOption[] | null {
|
||||
if (!Array.isArray(value) || value.length === 0) return null;
|
||||
if (!value.every((entry): entry is string => typeof entry === "string")) return null;
|
||||
return value.map((entry) => ({ value: entry, label: entry }));
|
||||
}
|
||||
|
||||
type SingleSelectParse =
|
||||
| { kind: "choice"; options: RawChoiceOption[] }
|
||||
| { kind: "invalid" }
|
||||
| { kind: "plain" };
|
||||
|
||||
function parseStringChoice(schema: Record<string, unknown>): SingleSelectParse {
|
||||
if (schema.oneOf !== undefined && schema.oneOf !== null) {
|
||||
const options = readTitledOptions(schema.oneOf);
|
||||
return options ? { kind: "choice", options } : { kind: "invalid" };
|
||||
}
|
||||
if (schema.enum !== undefined && schema.enum !== null) {
|
||||
const options = readEnumOptions(schema.enum);
|
||||
return options ? { kind: "choice", options } : { kind: "invalid" };
|
||||
}
|
||||
if (schema.anyOf !== undefined && schema.anyOf !== null) {
|
||||
return { kind: "invalid" };
|
||||
}
|
||||
return { kind: "plain" };
|
||||
}
|
||||
|
||||
function readMultiSelectOptions(schema: Record<string, unknown>): RawChoiceOption[] | null {
|
||||
if (!isPlainRecord(schema.items)) return null;
|
||||
const items = schema.items;
|
||||
if (items.anyOf !== undefined && items.anyOf !== null) return readTitledOptions(items.anyOf);
|
||||
if (items.oneOf !== undefined && items.oneOf !== null) return readTitledOptions(items.oneOf);
|
||||
if (items.enum !== undefined && items.enum !== null) return readEnumOptions(items.enum);
|
||||
return null;
|
||||
}
|
||||
|
||||
function isPlainStringProperty(schema: unknown): schema is Record<string, unknown> {
|
||||
return (
|
||||
isPlainRecord(schema) &&
|
||||
schema.type === "string" &&
|
||||
schema.oneOf == null &&
|
||||
schema.enum == null &&
|
||||
schema.anyOf == null
|
||||
);
|
||||
}
|
||||
|
||||
function readChoiceOptions(schema: unknown): RawChoiceOption[] | null {
|
||||
if (!isPlainRecord(schema)) return null;
|
||||
if (schema.type === "string") {
|
||||
const parsed = parseStringChoice(schema);
|
||||
return parsed.kind === "choice" ? parsed.options : null;
|
||||
}
|
||||
if (schema.type === "array") return readMultiSelectOptions(schema);
|
||||
return null;
|
||||
}
|
||||
|
||||
function readMinItems(schema: Record<string, unknown>): number {
|
||||
return typeof schema.minItems === "number" &&
|
||||
Number.isFinite(schema.minItems) &&
|
||||
schema.minItems > 0
|
||||
? schema.minItems
|
||||
: 0;
|
||||
}
|
||||
|
||||
function pairOtherFields(
|
||||
entries: readonly [string, unknown][],
|
||||
properties: Record<string, unknown>,
|
||||
requiredSet: ReadonlySet<string>,
|
||||
): { absorbed: Set<string>; paired: Map<string, OtherPairing> } {
|
||||
const absorbed = new Set<string>();
|
||||
const paired = new Map<string, OtherPairing>();
|
||||
for (const [key, schema] of entries) {
|
||||
const options = readChoiceOptions(schema);
|
||||
if (!options || !isPlainRecord(schema)) continue;
|
||||
const otherKey = `${key}${OTHER_SUFFIX}`;
|
||||
if (!Object.hasOwn(properties, otherKey) || requiredSet.has(otherKey)) continue;
|
||||
const otherSchema = properties[otherKey];
|
||||
if (!isPlainStringProperty(otherSchema)) continue;
|
||||
// Only fold `<key>_other` as a replacement Other input when the primary field can be
|
||||
// omitted or declares an explicit `"other"` sentinel; otherwise keep `_other` as its own
|
||||
// optional follow-up field so `required` / `minItems` on `<key>` are always satisfied.
|
||||
const mustSelectPrimary =
|
||||
requiredSet.has(key) || (schema.type === "array" && readMinItems(schema) > 0);
|
||||
const hasSentinel = options.some((option) => option.value === OTHER_SENTINEL);
|
||||
if (mustSelectPrimary && !hasSentinel) continue;
|
||||
absorbed.add(otherKey);
|
||||
paired.set(key, { key: otherKey, schema: otherSchema });
|
||||
}
|
||||
return { absorbed, paired };
|
||||
}
|
||||
|
||||
function sanitizeMultiLabel(text: string): string {
|
||||
return text.replace(/,\s+/g, ",");
|
||||
}
|
||||
|
||||
function formatOptionDescription(
|
||||
description: string | undefined,
|
||||
isDefault: boolean,
|
||||
): string | undefined {
|
||||
if (!isDefault) return description;
|
||||
return description ? `${description} (${DEFAULT})` : DEFAULT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Labels the card answers with must be unique within a question. The card joins
|
||||
* multi-select labels with ", ", so those labels must not contain ", " or one
|
||||
* selection could read as another ("A", "B" versus "A, B").
|
||||
*/
|
||||
function buildCardOptions(
|
||||
options: readonly RawChoiceOption[],
|
||||
multiSelect: boolean,
|
||||
defaults: ReadonlySet<string>,
|
||||
): Array<{ value: string; card: CardOption }> {
|
||||
const used = new Set<string>();
|
||||
return options.map((option, index) => {
|
||||
const rawLabel = option.label || option.value;
|
||||
let cardLabel = multiSelect ? sanitizeMultiLabel(rawLabel) : rawLabel;
|
||||
if (used.has(cardLabel)) {
|
||||
const valueTag = multiSelect ? sanitizeMultiLabel(option.value) : option.value;
|
||||
cardLabel = `${cardLabel} (${valueTag})`;
|
||||
}
|
||||
let suffix = index + 1;
|
||||
while (used.has(cardLabel)) {
|
||||
cardLabel = `${cardLabel} ${suffix}`;
|
||||
suffix += 1;
|
||||
}
|
||||
used.add(cardLabel);
|
||||
const description = formatOptionDescription(option.description, defaults.has(option.value));
|
||||
return {
|
||||
value: option.value,
|
||||
card: description ? { label: cardLabel, description } : { label: cardLabel },
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function buildHeaderAndQuestion(
|
||||
key: string,
|
||||
schema: Record<string, unknown>,
|
||||
index: number,
|
||||
total: number,
|
||||
usedHeaders: Set<string>,
|
||||
): { header: string; question: string } {
|
||||
const title = nonEmpty(schema.title);
|
||||
const description = nonEmpty(schema.description);
|
||||
const fallbackHeader = total === 1 ? "Question" : `Question ${index + 1}`;
|
||||
|
||||
let rawHeader: string;
|
||||
let question: string;
|
||||
if (title && description) {
|
||||
if (title === description) {
|
||||
rawHeader = fallbackHeader;
|
||||
question = title;
|
||||
} else if (title.length <= MAX_HEADER_LENGTH && !title.includes("\n")) {
|
||||
rawHeader = title;
|
||||
question = description;
|
||||
} else {
|
||||
rawHeader = fallbackHeader;
|
||||
question = `${title}\n\n${description}`;
|
||||
}
|
||||
} else if (title) {
|
||||
rawHeader = fallbackHeader;
|
||||
question = title;
|
||||
} else if (description) {
|
||||
rawHeader = fallbackHeader;
|
||||
question = description;
|
||||
} else {
|
||||
rawHeader = key.length <= MAX_HEADER_LENGTH && !key.includes("\n") ? key : fallbackHeader;
|
||||
question = key;
|
||||
}
|
||||
|
||||
let header = rawHeader;
|
||||
let suffix = 2;
|
||||
while (usedHeaders.has(header)) {
|
||||
header = `${rawHeader} (${suffix})`;
|
||||
suffix += 1;
|
||||
}
|
||||
usedHeaders.add(header);
|
||||
return { header, question };
|
||||
}
|
||||
|
||||
/**
|
||||
* The shared question card sends a multi-select answer as one string: the checked option
|
||||
* labels in click order, then any typed answer, joined with ", ". Consume exact option
|
||||
* labels from the front, longest first; any remaining text is the typed answer.
|
||||
*/
|
||||
function splitMultiSelectAnswer(
|
||||
answer: string,
|
||||
labels: readonly string[],
|
||||
): { selected: string[]; custom: string | null } {
|
||||
let remaining = answer;
|
||||
const selected: string[] = [];
|
||||
while (remaining.length > 0) {
|
||||
const label = labels
|
||||
.filter((candidate) => !selected.includes(candidate))
|
||||
.sort((left, right) => right.length - left.length)
|
||||
.find((candidate) => remaining === candidate || remaining.startsWith(`${candidate}, `));
|
||||
if (!label) break;
|
||||
selected.push(label);
|
||||
remaining = remaining === label ? "" : remaining.slice(label.length + 2);
|
||||
}
|
||||
return { selected, custom: remaining || null };
|
||||
}
|
||||
|
||||
function splitSentinelOptions(
|
||||
rawOptions: readonly RawChoiceOption[],
|
||||
otherPairing: OtherPairing | undefined,
|
||||
): { options: RawChoiceOption[]; other: OtherTarget | undefined } {
|
||||
if (!otherPairing) return { options: [...rawOptions], other: undefined };
|
||||
const sentinel = rawOptions.find((option) => option.value === OTHER_SENTINEL);
|
||||
if (!sentinel) {
|
||||
return { options: [...rawOptions], other: { key: otherPairing.key } };
|
||||
}
|
||||
return {
|
||||
options: rawOptions.filter((option) => option.value !== OTHER_SENTINEL),
|
||||
other: { key: otherPairing.key, sentinelValue: sentinel.value },
|
||||
};
|
||||
}
|
||||
|
||||
function buildSingleSelectField(input: {
|
||||
key: string;
|
||||
header: string;
|
||||
question: string;
|
||||
rawOptions: readonly RawChoiceOption[];
|
||||
schema: Record<string, unknown>;
|
||||
required: boolean;
|
||||
otherPairing?: OtherPairing;
|
||||
}): ParsedField {
|
||||
const { key, header, question, rawOptions, schema, required, otherPairing } = input;
|
||||
const { options: selectableOptions, other } = splitSentinelOptions(rawOptions, otherPairing);
|
||||
const rawDefault = typeof schema.default === "string" ? schema.default : undefined;
|
||||
const defaultValue =
|
||||
rawDefault !== undefined && selectableOptions.some((option) => option.value === rawDefault)
|
||||
? rawDefault
|
||||
: undefined;
|
||||
const defaults = new Set(defaultValue !== undefined ? [defaultValue] : []);
|
||||
const built = buildCardOptions(selectableOptions, false, defaults);
|
||||
const valueByLabel = new Map(built.map((item) => [item.card.label, item.value]));
|
||||
const placeholder = nonEmpty(otherPairing?.schema.description);
|
||||
|
||||
return {
|
||||
question: {
|
||||
id: key,
|
||||
header,
|
||||
question,
|
||||
options: built.map((item) => item.card),
|
||||
multiSelect: false,
|
||||
allowOther: other !== undefined,
|
||||
allowEmpty: defaultValue !== undefined,
|
||||
...(placeholder ? { placeholder } : {}),
|
||||
},
|
||||
resolve(answer) {
|
||||
const trimmed = answer?.trim();
|
||||
if (!trimmed) {
|
||||
if (defaultValue !== undefined) return { ok: true, entries: [[key, defaultValue]] };
|
||||
return required ? { ok: false } : { ok: true, entries: [] };
|
||||
}
|
||||
const matched = valueByLabel.get(trimmed);
|
||||
if (matched !== undefined) return { ok: true, entries: [[key, matched]] };
|
||||
if (!other) return { ok: false };
|
||||
if (other.sentinelValue !== undefined) {
|
||||
return {
|
||||
ok: true,
|
||||
entries: [
|
||||
[key, other.sentinelValue],
|
||||
[other.key, trimmed],
|
||||
],
|
||||
};
|
||||
}
|
||||
return { ok: true, entries: [[other.key, trimmed]] };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildMultiSelectField(input: {
|
||||
key: string;
|
||||
header: string;
|
||||
question: string;
|
||||
rawOptions: readonly RawChoiceOption[];
|
||||
schema: Record<string, unknown>;
|
||||
required: boolean;
|
||||
otherPairing?: OtherPairing;
|
||||
}): ParsedField {
|
||||
const { key, header, question, rawOptions, schema, required, otherPairing } = input;
|
||||
const { options: selectableOptions, other } = splitSentinelOptions(rawOptions, otherPairing);
|
||||
const selectableValues = new Set(selectableOptions.map((option) => option.value));
|
||||
const rawDefaults = Array.isArray(schema.default)
|
||||
? [
|
||||
...new Set(
|
||||
schema.default.filter(
|
||||
(value): value is string => typeof value === "string" && selectableValues.has(value),
|
||||
),
|
||||
),
|
||||
]
|
||||
: [];
|
||||
const defaultValues = rawDefaults.length > 0 ? rawDefaults : undefined;
|
||||
const built = buildCardOptions(selectableOptions, true, new Set(rawDefaults));
|
||||
const valueByLabel = new Map(built.map((item) => [item.card.label, item.value]));
|
||||
|
||||
const minItems = readMinItems(schema);
|
||||
const effectiveRequired = required || minItems > 0;
|
||||
// The card submits zero choices only beside a text input, so an optional
|
||||
// multi-select without Other gets an explicit None choice.
|
||||
const needsNone = !other && !effectiveRequired;
|
||||
let noneLabel: string | undefined;
|
||||
if (needsNone) {
|
||||
noneLabel = valueByLabel.has(NONE) ? NO_SELECTION : NONE;
|
||||
}
|
||||
const allLabels = [...valueByLabel.keys(), ...(noneLabel ? [noneLabel] : [])];
|
||||
const cardOptions = [
|
||||
...built.map((item) => item.card),
|
||||
...(noneLabel ? [{ label: noneLabel }] : []),
|
||||
];
|
||||
const placeholder = nonEmpty(otherPairing?.schema.description);
|
||||
|
||||
return {
|
||||
question: {
|
||||
id: key,
|
||||
header,
|
||||
question,
|
||||
options: cardOptions,
|
||||
multiSelect: true,
|
||||
allowOther: other !== undefined,
|
||||
allowEmpty: defaultValues !== undefined,
|
||||
...(placeholder ? { placeholder } : {}),
|
||||
},
|
||||
resolve(answer) {
|
||||
const trimmed = answer?.trim();
|
||||
if (!trimmed) {
|
||||
if (defaultValues !== undefined) return { ok: true, entries: [[key, defaultValues]] };
|
||||
return effectiveRequired ? { ok: false } : { ok: true, entries: [] };
|
||||
}
|
||||
const { selected, custom } = splitMultiSelectAnswer(trimmed, allLabels);
|
||||
const values = selected.flatMap((label) => {
|
||||
const value = valueByLabel.get(label);
|
||||
return value !== undefined ? [value] : [];
|
||||
});
|
||||
if (custom !== null) {
|
||||
if (!other) return { ok: false };
|
||||
if (other.sentinelValue !== undefined) {
|
||||
const withSentinel = [...values, other.sentinelValue];
|
||||
if (withSentinel.length < minItems) return { ok: false };
|
||||
return {
|
||||
ok: true,
|
||||
entries: [
|
||||
[key, withSentinel],
|
||||
[other.key, custom],
|
||||
],
|
||||
};
|
||||
}
|
||||
const entries: Array<[string, ElicitationContentValue]> = [];
|
||||
if (values.length > 0) entries.push([key, values]);
|
||||
entries.push([other.key, custom]);
|
||||
return { ok: true, entries };
|
||||
}
|
||||
if (values.length < minItems) return { ok: false };
|
||||
if (values.length === 0 && required) return { ok: false };
|
||||
if (values.length > 0 || noneLabel !== undefined) {
|
||||
return { ok: true, entries: [[key, values]] };
|
||||
}
|
||||
return { ok: true, entries: [] };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildBooleanField(input: {
|
||||
key: string;
|
||||
header: string;
|
||||
question: string;
|
||||
schema: Record<string, unknown>;
|
||||
required: boolean;
|
||||
}): ParsedField {
|
||||
const { key, header, question, schema, required } = input;
|
||||
const defaultValue = typeof schema.default === "boolean" ? schema.default : undefined;
|
||||
const options: CardOption[] = [
|
||||
defaultValue === true ? { label: YES, description: DEFAULT } : { label: YES },
|
||||
defaultValue === false ? { label: NO, description: DEFAULT } : { label: NO },
|
||||
];
|
||||
|
||||
return {
|
||||
question: {
|
||||
id: key,
|
||||
header,
|
||||
question,
|
||||
options,
|
||||
multiSelect: false,
|
||||
allowOther: false,
|
||||
allowEmpty: false,
|
||||
},
|
||||
resolve(answer) {
|
||||
const trimmed = answer?.trim();
|
||||
if (!trimmed) {
|
||||
if (defaultValue !== undefined) return { ok: true, entries: [[key, defaultValue]] };
|
||||
return required ? { ok: false } : { ok: true, entries: [] };
|
||||
}
|
||||
if (trimmed === YES) return { ok: true, entries: [[key, true]] };
|
||||
if (trimmed === NO) return { ok: true, entries: [[key, false]] };
|
||||
return { ok: false };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildTextField(input: {
|
||||
key: string;
|
||||
header: string;
|
||||
question: string;
|
||||
schema: Record<string, unknown>;
|
||||
required: boolean;
|
||||
}): ParsedField {
|
||||
const { key, header, question, schema, required } = input;
|
||||
const defaultValue = typeof schema.default === "string" ? schema.default : undefined;
|
||||
const prefilled = defaultValue !== undefined && defaultValue.length > 0;
|
||||
|
||||
return {
|
||||
question: {
|
||||
id: key,
|
||||
header,
|
||||
question,
|
||||
options: prefilled ? [{ label: defaultValue, description: DEFAULT }] : [],
|
||||
multiSelect: false,
|
||||
allowOther: true,
|
||||
allowEmpty: prefilled || !required,
|
||||
},
|
||||
resolve(answer) {
|
||||
if (answer !== undefined && answer.trim().length > 0) {
|
||||
return { ok: true, entries: [[key, answer]] };
|
||||
}
|
||||
if (defaultValue !== undefined) return { ok: true, entries: [[key, defaultValue]] };
|
||||
return required ? { ok: false } : { ok: true, entries: [] };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function parseField(input: {
|
||||
key: string;
|
||||
schema: Record<string, unknown>;
|
||||
otherPairing?: OtherPairing;
|
||||
header: string;
|
||||
question: string;
|
||||
required: boolean;
|
||||
}): ParsedField | null {
|
||||
const { key, schema, otherPairing, header, question, required } = input;
|
||||
if (schema.type === "string") {
|
||||
const choice = parseStringChoice(schema);
|
||||
if (choice.kind === "invalid") return null;
|
||||
if (choice.kind === "choice") {
|
||||
return buildSingleSelectField({
|
||||
key,
|
||||
header,
|
||||
question,
|
||||
rawOptions: choice.options,
|
||||
schema,
|
||||
required,
|
||||
otherPairing,
|
||||
});
|
||||
}
|
||||
return buildTextField({ key, header, question, schema, required });
|
||||
}
|
||||
if (schema.type === "array") {
|
||||
const options = readMultiSelectOptions(schema);
|
||||
if (!options) return null;
|
||||
return buildMultiSelectField({
|
||||
key,
|
||||
header,
|
||||
question,
|
||||
rawOptions: options,
|
||||
schema,
|
||||
required,
|
||||
otherPairing,
|
||||
});
|
||||
}
|
||||
if (schema.type === "boolean") {
|
||||
return buildBooleanField({ key, header, question, schema, required });
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function toJsonQuestion(question: CardQuestion): Record<string, JsonValue> {
|
||||
const record: Record<string, JsonValue> = {
|
||||
id: question.id,
|
||||
header: question.header,
|
||||
question: question.question,
|
||||
options: question.options.map((option): Record<string, JsonValue> => {
|
||||
const item: Record<string, JsonValue> = { label: option.label };
|
||||
if (option.description) item.description = option.description;
|
||||
return item;
|
||||
}),
|
||||
multiSelect: question.multiSelect,
|
||||
allowOther: question.allowOther,
|
||||
allowEmpty: question.allowEmpty,
|
||||
};
|
||||
if (question.placeholder) record.placeholder = question.placeholder;
|
||||
if (question.dismissLabel) record.dismissLabel = question.dismissLabel;
|
||||
return record;
|
||||
}
|
||||
|
||||
function readAnswers(response: ProviderPermissionResponse): Record<string, unknown> {
|
||||
if (response.behavior !== "allow") return {};
|
||||
const answers = response.updatedInput?.answers;
|
||||
return isPlainRecord(answers) ? answers : {};
|
||||
}
|
||||
|
||||
function readFormSchema(
|
||||
request: CreateElicitationRequest,
|
||||
): { schema: Record<string, unknown>; properties: Record<string, unknown> } | null {
|
||||
if (request.mode !== "form") return null;
|
||||
const requestedSchema: unknown = (request as { requestedSchema?: unknown }).requestedSchema;
|
||||
if (!isPlainRecord(requestedSchema)) return null;
|
||||
if (requestedSchema.type !== undefined && requestedSchema.type !== "object") return null;
|
||||
if (!isPlainRecord(requestedSchema.properties)) return null;
|
||||
return { schema: requestedSchema, properties: requestedSchema.properties };
|
||||
}
|
||||
|
||||
function resolveFormTitle(
|
||||
schemaTitle: unknown,
|
||||
message: string | undefined,
|
||||
questions: readonly CardQuestion[],
|
||||
): string {
|
||||
const explicit = nonEmpty(schemaTitle);
|
||||
if (explicit) return explicit.slice(0, MAX_TITLE_LENGTH);
|
||||
if (questions.length === 1) return firstLine(questions[0]!.question).slice(0, MAX_TITLE_LENGTH);
|
||||
return message?.slice(0, MAX_TITLE_LENGTH) ?? `Questions (${questions.length})`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates an ACP 1.x form elicitation request (`elicitation/create`, mode `"form"`)
|
||||
* into a Paseo `kind: "question"` permission request and maps the user's answer back to
|
||||
* an ACP `CreateElicitationResponse` without throwing.
|
||||
*/
|
||||
export class AcpFormElicitation {
|
||||
private constructor(
|
||||
readonly request: Omit<ProviderPermissionRequest, "id">,
|
||||
private readonly fields: readonly ParsedField[],
|
||||
) {}
|
||||
|
||||
static parse(
|
||||
request: CreateElicitationRequest,
|
||||
options?: { toolName?: string },
|
||||
): AcpFormElicitation | null {
|
||||
const formSchema = readFormSchema(request);
|
||||
if (!formSchema) return null;
|
||||
const { schema: requestedSchema, properties } = formSchema;
|
||||
|
||||
const entries = Object.entries(properties);
|
||||
if (entries.length === 0) return null;
|
||||
|
||||
const requiredSet = new Set(
|
||||
Array.isArray(requestedSchema.required)
|
||||
? requestedSchema.required.filter((key): key is string => typeof key === "string")
|
||||
: [],
|
||||
);
|
||||
|
||||
const { absorbed, paired } = pairOtherFields(entries, properties, requiredSet);
|
||||
const primaryEntries = entries.filter(([key]) => !absorbed.has(key));
|
||||
if (primaryEntries.length === 0) return null;
|
||||
|
||||
const usedHeaders = new Set<string>();
|
||||
const fields: ParsedField[] = [];
|
||||
for (let index = 0; index < primaryEntries.length; index += 1) {
|
||||
const [key, rawSchema] = primaryEntries[index]!;
|
||||
if (!isPlainRecord(rawSchema)) return null;
|
||||
const { header, question } = buildHeaderAndQuestion(
|
||||
key,
|
||||
rawSchema,
|
||||
index,
|
||||
primaryEntries.length,
|
||||
usedHeaders,
|
||||
);
|
||||
const parsed = parseField({
|
||||
key,
|
||||
schema: rawSchema,
|
||||
otherPairing: paired.get(key),
|
||||
header,
|
||||
question,
|
||||
required: requiredSet.has(key),
|
||||
});
|
||||
if (!parsed) return null;
|
||||
fields.push(parsed);
|
||||
}
|
||||
|
||||
const questions = fields.map((field) => field.question);
|
||||
// The card submits instead of cancelling when every question is optional free text;
|
||||
// name that button for what it does.
|
||||
if (questions.every((question) => question.options.length === 0 && question.allowEmpty)) {
|
||||
for (const question of questions) question.dismissLabel = SKIP;
|
||||
}
|
||||
|
||||
const message = nonEmpty(request.message);
|
||||
const title = resolveFormTitle(requestedSchema.title, message, questions);
|
||||
|
||||
return new AcpFormElicitation(
|
||||
{
|
||||
name: options?.toolName ?? "Question",
|
||||
kind: "question",
|
||||
title,
|
||||
...(message ? { description: message } : {}),
|
||||
input: { questions: questions.map(toJsonQuestion) },
|
||||
},
|
||||
fields,
|
||||
);
|
||||
}
|
||||
|
||||
respond(response: ProviderPermissionResponse): CreateElicitationResponse {
|
||||
if (response.behavior === "deny") return { action: "decline" };
|
||||
const answers = readAnswers(response);
|
||||
const entries: Array<[string, ElicitationContentValue]> = [];
|
||||
for (const field of this.fields) {
|
||||
const header = field.question.header;
|
||||
const raw = Object.hasOwn(answers, header) ? answers[header] : undefined;
|
||||
const outcome = field.resolve(typeof raw === "string" ? raw : undefined);
|
||||
if (!outcome.ok) return { action: "decline" };
|
||||
entries.push(...outcome.entries);
|
||||
}
|
||||
// Object.fromEntries defines own data properties, keeping keys like "__proto__" safe.
|
||||
const content: Record<string, ElicitationContentValue> = Object.fromEntries(entries);
|
||||
return { action: "accept", content };
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,12 @@ import {
|
||||
type Agent,
|
||||
type SessionUpdate,
|
||||
} from "@agentclientprotocol/sdk";
|
||||
import type { ProviderConnection, ProviderEvent, ProviderInput } from "./provider.js";
|
||||
import type {
|
||||
ProviderConnection,
|
||||
ProviderEvent,
|
||||
ProviderInput,
|
||||
ProviderPermissionResponse,
|
||||
} from "./provider.js";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import { AgentTimelineItemPayloadSchema } from "@getpaseo/protocol/messages";
|
||||
@@ -7586,3 +7591,435 @@ describe("respectful ACP probing defaults and hygiene", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("ACP form elicitation", () => {
|
||||
const agySchema = {
|
||||
type: "object",
|
||||
properties: {
|
||||
q1: {
|
||||
type: "string",
|
||||
title: "Pick one:",
|
||||
oneOf: [
|
||||
{ const: "1", title: "alpha" },
|
||||
{ const: "2", title: "beta" },
|
||||
],
|
||||
},
|
||||
q1_other: {
|
||||
type: "string",
|
||||
title: "Other",
|
||||
description: "Optional free-form answer",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
type PermissionEvent = Extract<ProviderEvent, { type: "session.permission" }>;
|
||||
|
||||
const formPayload = (overrides: Record<string, unknown> = {}) => ({
|
||||
sessionId: "connector-session",
|
||||
message: "Pick one",
|
||||
mode: "form",
|
||||
requestedSchema: agySchema,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const replyPermission = (
|
||||
permissionId: string,
|
||||
response: ProviderPermissionResponse,
|
||||
): ProviderInput => ({
|
||||
type: "session.permission",
|
||||
sessionId: "session-1",
|
||||
permissionId,
|
||||
response,
|
||||
});
|
||||
|
||||
async function openSession(
|
||||
options: {
|
||||
acpOptions?: Parameters<typeof runAcpProvider>[0]["acpOptions"];
|
||||
configOptions?: ConnectorHarnessOptions["configOptions"];
|
||||
handleRequest?: ConnectorHarnessOptions["handleRequest"];
|
||||
handleMessage?: ConnectorHarnessOptions["handleMessage"];
|
||||
settings?: Record<string, string>;
|
||||
} = {},
|
||||
) {
|
||||
const harness = connectorHarness({
|
||||
configOptions: options.configOptions,
|
||||
handleRequest: options.handleRequest,
|
||||
handleMessage: options.handleMessage,
|
||||
});
|
||||
const connection = await runAcpProvider({
|
||||
id: "elicit",
|
||||
label: "Elicit",
|
||||
connector: harness.connector,
|
||||
acpOptions: options.acpOptions,
|
||||
}).connect({
|
||||
versions: [1],
|
||||
capabilities: ["prompt.message", "permission", "session.configure"],
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
await connection.send(openInput(options.settings));
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
return { harness, connection, events };
|
||||
}
|
||||
|
||||
async function openInTurn(options: Parameters<typeof openSession>[0] = {}) {
|
||||
let promptRequest: AcpRequestMessage | null = null;
|
||||
const opened = await openSession({
|
||||
...options,
|
||||
handleRequest(runtime, request) {
|
||||
if (options.handleRequest?.(runtime, request)) return true;
|
||||
if (request.method === "session/prompt") {
|
||||
promptRequest = request;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
});
|
||||
await opened.connection.send({
|
||||
type: "session.prompt",
|
||||
sessionId: "session-1",
|
||||
prompt: {
|
||||
clientMessageId: "turn-1",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "Ask me" }] },
|
||||
},
|
||||
});
|
||||
await expect.poll(() => promptRequest).not.toBeNull();
|
||||
return {
|
||||
...opened,
|
||||
finishPrompt(stopReason = "end_turn") {
|
||||
if (promptRequest) {
|
||||
opened.harness.instances[1]!.respond(promptRequest, { stopReason });
|
||||
promptRequest = null;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
it("advertises elicitation.form on initialize by default", async () => {
|
||||
const { harness, connection } = await openSession();
|
||||
try {
|
||||
const initReq = harness.instances
|
||||
.flatMap((instance) => instance.requests)
|
||||
.find((request) => request.method === "initialize");
|
||||
expect(
|
||||
(initReq?.params as { clientCapabilities?: unknown } | undefined)?.clientCapabilities,
|
||||
).toEqual({
|
||||
elicitation: { form: {} },
|
||||
});
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("bridges form elicitation to a question card and maps chosen and custom answers", async () => {
|
||||
const { harness, connection, events, finishPrompt } = await openInTurn();
|
||||
try {
|
||||
const agent = harness.instances[1]!;
|
||||
const response = agent.request("elicitation/create", formPayload());
|
||||
const event = (await waitForEvent(
|
||||
events,
|
||||
(e) => e.type === "session.permission",
|
||||
)) as PermissionEvent;
|
||||
|
||||
expect(event.request).toMatchObject({
|
||||
kind: "question",
|
||||
input: {
|
||||
questions: [
|
||||
{
|
||||
id: "q1",
|
||||
header: "Question",
|
||||
question: "Pick one:",
|
||||
options: [{ label: "alpha" }, { label: "beta" }],
|
||||
multiSelect: false,
|
||||
allowOther: true,
|
||||
allowEmpty: false,
|
||||
placeholder: "Optional free-form answer",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
await connection.send(
|
||||
replyPermission(event.request.id, {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { Question: "beta" } },
|
||||
}),
|
||||
);
|
||||
await expect(response).resolves.toEqual({ action: "accept", content: { q1: "2" } });
|
||||
await waitForEvent(
|
||||
events,
|
||||
(e) => e.type === "session.permission_resolved" && e.permissionId === event.request.id,
|
||||
);
|
||||
|
||||
// Second question answered via custom Other text.
|
||||
const second = agent.request("elicitation/create", formPayload());
|
||||
const secondEvent = (await waitForEvent(
|
||||
events,
|
||||
(e) => e.type === "session.permission" && e.request.id !== event.request.id,
|
||||
)) as PermissionEvent;
|
||||
await connection.send(
|
||||
replyPermission(secondEvent.request.id, {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { Question: "gamma" } },
|
||||
}),
|
||||
);
|
||||
await expect(second).resolves.toEqual({ action: "accept", content: { q1_other: "gamma" } });
|
||||
finishPrompt();
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("declines url mode, unsupported schemas, out-of-turn requests, and mismatched sessions", async () => {
|
||||
let duringOpenResult: unknown;
|
||||
const { harness, connection, events } = await openSession({
|
||||
handleRequest(runtime, request) {
|
||||
if (request.method !== "session/new") return false;
|
||||
void runtime.request("elicitation/create", formPayload()).then((result) => {
|
||||
duringOpenResult = result;
|
||||
runtime.respond(request, {
|
||||
sessionId: "connector-session",
|
||||
modes: null,
|
||||
configOptions: [],
|
||||
});
|
||||
return undefined;
|
||||
});
|
||||
return true;
|
||||
},
|
||||
});
|
||||
try {
|
||||
// Out-of-turn during session/new
|
||||
expect(duringOpenResult).toEqual({ action: "decline" });
|
||||
|
||||
// Out-of-turn while idle
|
||||
const agent = harness.instances[1]!;
|
||||
await expect(agent.request("elicitation/create", formPayload())).resolves.toEqual({
|
||||
action: "decline",
|
||||
});
|
||||
expect(events.some((e) => e.type === "session.permission")).toBe(false);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
|
||||
// Active turn: mismatched sessionId, request-scoped, url mode, and number/integer schemas decline.
|
||||
const active = await openInTurn();
|
||||
try {
|
||||
const agent = active.harness.instances[1]!;
|
||||
await expect(
|
||||
agent.request("elicitation/create", formPayload({ sessionId: "other-session" })),
|
||||
).resolves.toEqual({ action: "decline" });
|
||||
await expect(
|
||||
agent.request("elicitation/create", {
|
||||
requestId: "req-1",
|
||||
mode: "form",
|
||||
message: "Auth",
|
||||
requestedSchema: agySchema,
|
||||
}),
|
||||
).resolves.toEqual({ action: "decline" });
|
||||
await expect(
|
||||
agent.request("elicitation/create", {
|
||||
sessionId: "connector-session",
|
||||
mode: "url",
|
||||
elicitationId: "e-1",
|
||||
url: "https://example.com",
|
||||
message: "Sign in",
|
||||
}),
|
||||
).resolves.toEqual({ action: "decline" });
|
||||
await expect(
|
||||
agent.request(
|
||||
"elicitation/create",
|
||||
formPayload({
|
||||
requestedSchema: { type: "object", properties: { n: { type: "integer" } } },
|
||||
}),
|
||||
),
|
||||
).resolves.toEqual({ action: "decline" });
|
||||
expect(active.events.some((e) => e.type === "session.permission")).toBe(false);
|
||||
active.finishPrompt();
|
||||
} finally {
|
||||
await active.connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("never auto-accepts elicitations in autoAcceptMode", async () => {
|
||||
const { harness, connection, events, finishPrompt } = await openInTurn({
|
||||
configOptions: [
|
||||
{
|
||||
id: "mode",
|
||||
name: "Mode",
|
||||
category: "mode",
|
||||
type: "select",
|
||||
currentValue: "default",
|
||||
options: [{ value: "default", name: "Default" }],
|
||||
},
|
||||
],
|
||||
acpOptions: {
|
||||
autoAcceptMode: {
|
||||
mode: { id: "full-access", label: "Full access" },
|
||||
nativeMode: "default",
|
||||
default: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
try {
|
||||
const agent = harness.instances[1]!;
|
||||
// Tool permission IS auto-accepted in autoAcceptMode.
|
||||
await expect(
|
||||
agent.request("session/request_permission", {
|
||||
sessionId: "connector-session",
|
||||
toolCall: { toolCallId: "tool-1", title: "Run cmd" },
|
||||
options: [
|
||||
{ optionId: "allow", name: "Allow", kind: "allow_once" },
|
||||
{ optionId: "reject", name: "Reject", kind: "reject_once" },
|
||||
],
|
||||
}),
|
||||
).resolves.toEqual({ outcome: { outcome: "selected", optionId: "allow" } });
|
||||
|
||||
// Form elicitation is NOT auto-accepted — it must surface as a question card.
|
||||
const elicitation = agent.request("elicitation/create", formPayload());
|
||||
const event = (await waitForEvent(
|
||||
events,
|
||||
(e) => e.type === "session.permission",
|
||||
)) as PermissionEvent;
|
||||
expect(event.request.kind).toBe("question");
|
||||
|
||||
await connection.send(replyPermission(event.request.id, { behavior: "deny" }));
|
||||
await expect(elicitation).resolves.toEqual({ action: "decline" });
|
||||
finishPrompt();
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("cancels a pending elicitation when the turn is interrupted", async () => {
|
||||
let stopping = false;
|
||||
let elicitationPromise: Promise<unknown> | null = null;
|
||||
const { connection, events } = await openSession({
|
||||
handleMessage(_runtime, message) {
|
||||
if ("method" in message && message.method === "session/cancel") {
|
||||
stopping = true;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
handleRequest(runtime, request) {
|
||||
if (request.method !== "session/prompt") return false;
|
||||
elicitationPromise = runtime.request("elicitation/create", formPayload());
|
||||
void elicitationPromise.then(() => {
|
||||
if (stopping) runtime.respond(request, { stopReason: "cancelled" });
|
||||
return undefined;
|
||||
});
|
||||
return true;
|
||||
},
|
||||
});
|
||||
try {
|
||||
await connection.send({
|
||||
type: "session.prompt",
|
||||
sessionId: "session-1",
|
||||
prompt: {
|
||||
clientMessageId: "cancel-turn",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "Ask" }] },
|
||||
},
|
||||
});
|
||||
const event = (await waitForEvent(
|
||||
events,
|
||||
(e) => e.type === "session.permission",
|
||||
)) as PermissionEvent;
|
||||
await connection.send({
|
||||
type: "session.interrupt",
|
||||
requestId: "stop-1",
|
||||
sessionId: "session-1",
|
||||
});
|
||||
await expect(elicitationPromise).resolves.toEqual({ action: "cancel" });
|
||||
await waitForEvent(
|
||||
events,
|
||||
(e) => e.type === "session.permission_resolved" && e.permissionId === event.request.id,
|
||||
);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("cancels a pending elicitation when the turn ends", async () => {
|
||||
const { harness, connection, events, finishPrompt } = await openInTurn();
|
||||
try {
|
||||
const agent = harness.instances[1]!;
|
||||
const elicitation = agent.request("elicitation/create", formPayload());
|
||||
const event = (await waitForEvent(
|
||||
events,
|
||||
(e) => e.type === "session.permission",
|
||||
)) as PermissionEvent;
|
||||
finishPrompt("end_turn");
|
||||
await expect(elicitation).resolves.toEqual({ action: "cancel" });
|
||||
await waitForEvent(
|
||||
events,
|
||||
(e) => e.type === "session.permission_resolved" && e.permissionId === event.request.id,
|
||||
);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("cancels a pending elicitation when the connection closes", async () => {
|
||||
const { harness, connection, events } = await openInTurn();
|
||||
const agent = harness.instances[1]!;
|
||||
const elicitation = agent.request("elicitation/create", formPayload());
|
||||
await waitForEvent(events, (e) => e.type === "session.permission");
|
||||
await connection.close();
|
||||
await expect(elicitation).resolves.toEqual({ action: "cancel" });
|
||||
});
|
||||
|
||||
it("settles cleanly on unexpected transport close while an elicitation is pending", async () => {
|
||||
const { harness, connection, events } = await openInTurn();
|
||||
try {
|
||||
const agent = harness.instances[1]!;
|
||||
void agent.request("elicitation/create", formPayload());
|
||||
await waitForEvent(events, (e) => e.type === "session.permission");
|
||||
agent.closeFromAgent();
|
||||
await waitForEvent(events, (e) => e.type === "session.runtime_failed");
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("declines cleanly without emitting session.runtime_failed on an invalid elicitation response", async () => {
|
||||
const { harness, connection, events, finishPrompt } = await openInTurn();
|
||||
try {
|
||||
const agent = harness.instances[1]!;
|
||||
const elicitation = agent.request(
|
||||
"elicitation/create",
|
||||
formPayload({
|
||||
requestedSchema: {
|
||||
type: "object",
|
||||
required: ["choice"],
|
||||
properties: {
|
||||
choice: { type: "string", title: "Choice", description: "Pick", enum: ["A", "B"] },
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
const event = (await waitForEvent(
|
||||
events,
|
||||
(e) => e.type === "session.permission",
|
||||
)) as PermissionEvent;
|
||||
|
||||
await connection.send(
|
||||
replyPermission(event.request.id, {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { Choice: "InvalidOption" } },
|
||||
}),
|
||||
);
|
||||
await expect(elicitation).resolves.toEqual({ action: "decline" });
|
||||
await waitForEvent(
|
||||
events,
|
||||
(e) => e.type === "session.permission_resolved" && e.permissionId === event.request.id,
|
||||
);
|
||||
expect(events.some((e) => e.type === "session.runtime_failed")).toBe(false);
|
||||
finishPrompt();
|
||||
await waitForEvent(events, (e) => e.type === "session.turn" && e.state === "completed");
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1481,6 +1481,74 @@ test("a steer the provider names without echoing it can be rewound to", async ()
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps one assistant message whole when a steer lands between its chunks", async () => {
|
||||
const session = new SteeringTestSession({ provider: "codex", cwd: process.cwd() });
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-steer-split-"));
|
||||
const manager = new AgentManager({
|
||||
clients: {
|
||||
codex: new (class extends TestAgentClient {
|
||||
override async createSession(): Promise<AgentSession> {
|
||||
return session;
|
||||
}
|
||||
})(),
|
||||
},
|
||||
// Zero window: every streamed chunk flushes on the coalescer's leading edge,
|
||||
// so the timeline reaches its next state without waiting on a timer.
|
||||
agentStreamCoalesceWindowMs: 0,
|
||||
logger,
|
||||
});
|
||||
let agentId: string | null = null;
|
||||
try {
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
agentId = agent.id;
|
||||
const run = manager.streamAgent(agent.id, "initial");
|
||||
void (async () => {
|
||||
for await (const _event of run) {
|
||||
}
|
||||
})();
|
||||
await manager.waitForAgentRunStart(agent.id);
|
||||
|
||||
const conversation = () =>
|
||||
manager
|
||||
.fetchTimeline(agent.id, { limit: 0 })
|
||||
.rows.filter(
|
||||
(row) => row.item.type === "assistant_message" || row.item.type === "user_message",
|
||||
)
|
||||
.map((row) => row.item);
|
||||
|
||||
session.pushEvent({
|
||||
type: "timeline",
|
||||
provider: "codex",
|
||||
turnId: "active-turn-1",
|
||||
item: { type: "assistant_message", text: "with the uncommit", messageId: "msg-1" },
|
||||
});
|
||||
await expect
|
||||
.poll(conversation)
|
||||
.toMatchObject([
|
||||
{ type: "assistant_message", text: "with the uncommit", messageId: "msg-1" },
|
||||
]);
|
||||
await expect(
|
||||
manager.steerAgentRun(agent.id, "keep going", { clientMessageId: "keep-going-client" }),
|
||||
).resolves.toEqual({ status: "accepted" });
|
||||
session.pushEvent({
|
||||
type: "timeline",
|
||||
provider: "codex",
|
||||
turnId: "active-turn-1",
|
||||
item: { type: "assistant_message", text: "ted changes.", messageId: "msg-1" },
|
||||
});
|
||||
|
||||
await expect.poll(conversation).toMatchObject([
|
||||
{ type: "assistant_message", text: "with the uncommitted changes.", messageId: "msg-1" },
|
||||
{ type: "user_message", text: "keep going" },
|
||||
]);
|
||||
} finally {
|
||||
if (agentId) await manager.closeAgent(agentId).catch(() => undefined);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("orders a concurrent replacement after a pending accepted steer", async () => {
|
||||
const entered = deferred<void>();
|
||||
const release = deferred<void>();
|
||||
|
||||
@@ -7,6 +7,62 @@ import type { AgentTimelineItem } from "./agent-sdk-types.js";
|
||||
import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js";
|
||||
|
||||
describe("InMemoryAgentTimelineStore", () => {
|
||||
it("keeps a streaming assistant message whole when a steering prompt is recorded mid-stream", () => {
|
||||
const store = new InMemoryAgentTimelineStore();
|
||||
store.initialize("agent-1");
|
||||
store.append("agent-1", {
|
||||
type: "assistant_message",
|
||||
text: "with the uncommit",
|
||||
messageId: "msg-1",
|
||||
});
|
||||
store.append("agent-1", { type: "user_message", text: "keep going" });
|
||||
store.append("agent-1", {
|
||||
type: "assistant_message",
|
||||
text: "ted changes.",
|
||||
messageId: "msg-1",
|
||||
});
|
||||
|
||||
expect(store.getItems("agent-1")).toEqual([
|
||||
{ type: "assistant_message", text: "with the uncommitted changes.", messageId: "msg-1" },
|
||||
{ type: "user_message", text: "keep going" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps text written after a tool call below it when both share a message id", () => {
|
||||
const store = new InMemoryAgentTimelineStore();
|
||||
store.initialize("agent-1");
|
||||
store.append("agent-1", { type: "assistant_message", text: "Let me check.", messageId: "m1" });
|
||||
store.append("agent-1", {
|
||||
type: "tool_call",
|
||||
callId: "c1",
|
||||
name: "shell",
|
||||
status: "completed",
|
||||
detail: { type: "unknown", input: null, output: null },
|
||||
error: null,
|
||||
});
|
||||
store.append("agent-1", { type: "assistant_message", text: "Found it.", messageId: "m1" });
|
||||
|
||||
expect(store.getItems("agent-1").map((item) => item.type)).toEqual([
|
||||
"assistant_message",
|
||||
"tool_call",
|
||||
"assistant_message",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps chunks without a message id apart when a user message is recorded between them", () => {
|
||||
const store = new InMemoryAgentTimelineStore();
|
||||
store.initialize("agent-1");
|
||||
store.append("agent-1", { type: "assistant_message", text: "First." });
|
||||
store.append("agent-1", { type: "user_message", text: "keep going" });
|
||||
store.append("agent-1", { type: "assistant_message", text: "Second." });
|
||||
|
||||
expect(store.getItems("agent-1")).toEqual([
|
||||
{ type: "assistant_message", text: "First." },
|
||||
{ type: "user_message", text: "keep going" },
|
||||
{ type: "assistant_message", text: "Second." },
|
||||
]);
|
||||
});
|
||||
|
||||
it("resets stale forward cursors to complete available turns", () => {
|
||||
const store = new InMemoryAgentTimelineStore();
|
||||
store.initialize("agent", { epoch: "current" });
|
||||
@@ -360,6 +416,34 @@ describe("turn metrics", () => {
|
||||
expect(rows[1]).toMatchObject({ item: { text: "Done" }, turnMetrics: metrics });
|
||||
});
|
||||
|
||||
it("keeps the stats on a steered message whose chunks carry a message id", () => {
|
||||
const store = new InMemoryAgentTimelineStore();
|
||||
const at = "2026-11-22T00:00:00.000Z";
|
||||
store.initialize("a", {
|
||||
rows: [
|
||||
{ seq: 1, timestamp: at, item: { type: "user_message", text: "go" } },
|
||||
{ seq: 2, timestamp: at, item: { type: "assistant_message", text: "Do", messageId: "m1" } },
|
||||
{ seq: 3, timestamp: at, item: { type: "assistant_message", text: "n", messageId: "m1" } },
|
||||
{ seq: 4, timestamp: at, item: { type: "user_message", text: "keep going" } },
|
||||
{
|
||||
seq: 5,
|
||||
timestamp: at,
|
||||
item: { type: "assistant_message", text: "e", messageId: "m1" },
|
||||
turnMetrics: metrics,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const rows = store.fetch("a").rows;
|
||||
|
||||
expect(rows.map((row) => row.item)).toEqual([
|
||||
{ type: "user_message", text: "go" },
|
||||
{ type: "assistant_message", text: "Done", messageId: "m1" },
|
||||
{ type: "user_message", text: "keep going" },
|
||||
]);
|
||||
expect(rows[1]).toMatchObject({ turnMetrics: metrics });
|
||||
});
|
||||
|
||||
it("keeps the stats on a tool card whose updates the projection merges", () => {
|
||||
const store = new InMemoryAgentTimelineStore();
|
||||
const at = "2026-11-22T00:00:00.000Z";
|
||||
|
||||
@@ -64,6 +64,68 @@ describe("projectTimelineRows", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps one assistant message whole when a steering user message lands mid-stream", () => {
|
||||
const rows: AgentTimelineRow[] = [
|
||||
{
|
||||
seq: 1,
|
||||
timestamp: "2026-02-13T00:00:00.000Z",
|
||||
item: { type: "assistant_message", text: "with the uncommit", messageId: "msg-1" },
|
||||
},
|
||||
{
|
||||
seq: 2,
|
||||
timestamp: "2026-02-13T00:00:00.100Z",
|
||||
item: { type: "user_message", text: "keep going" },
|
||||
},
|
||||
{
|
||||
seq: 3,
|
||||
timestamp: "2026-02-13T00:00:00.200Z",
|
||||
item: { type: "assistant_message", text: "ted changes.", messageId: "msg-1" },
|
||||
},
|
||||
];
|
||||
|
||||
const projected = projectTimelineRows({ rows, mode: "projected" });
|
||||
|
||||
expect(projected.map((entry) => entry.item)).toEqual([
|
||||
{ type: "assistant_message", text: "with the uncommitted changes.", messageId: "msg-1" },
|
||||
{ type: "user_message", text: "keep going" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("keeps text written after a tool call below it when both share a message id", () => {
|
||||
const rows: AgentTimelineRow[] = [
|
||||
{
|
||||
seq: 1,
|
||||
timestamp: "2026-02-13T00:00:00.000Z",
|
||||
item: { type: "assistant_message", text: "Let me check.", messageId: "msg-1" },
|
||||
},
|
||||
{
|
||||
seq: 2,
|
||||
timestamp: "2026-02-13T00:00:00.100Z",
|
||||
item: {
|
||||
type: "tool_call",
|
||||
callId: "c1",
|
||||
name: "shell",
|
||||
status: "completed",
|
||||
detail: { type: "unknown", input: null, output: null },
|
||||
error: null,
|
||||
},
|
||||
},
|
||||
{
|
||||
seq: 3,
|
||||
timestamp: "2026-02-13T00:00:00.200Z",
|
||||
item: { type: "assistant_message", text: "Found it.", messageId: "msg-1" },
|
||||
},
|
||||
];
|
||||
|
||||
const projected = projectTimelineRows({ rows, mode: "projected" });
|
||||
|
||||
expect(projected.map((entry) => entry.item.type)).toEqual([
|
||||
"assistant_message",
|
||||
"tool_call",
|
||||
"assistant_message",
|
||||
]);
|
||||
});
|
||||
|
||||
test("keeps adjacent assistant chunks with different message ids separate in projected mode", () => {
|
||||
const rows: AgentTimelineRow[] = [
|
||||
{
|
||||
|
||||
@@ -261,46 +261,69 @@ export function continuesAssistantMessage(
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The index of the row in `rows` that `entry` continues, or null when `entry` starts a new
|
||||
* row. A chunk continues the assistant message right before it. A chunk that carries a
|
||||
* provider message id also continues its message across user rows recorded mid-stream, as
|
||||
* a steer is. Any other row in between, such as a tool call, keeps the provider's order.
|
||||
*/
|
||||
function assistantContinuationIndex(
|
||||
rows: readonly WorkingEntry[],
|
||||
entry: WorkingEntry,
|
||||
): number | null {
|
||||
if (entry.item.type !== "assistant_message") return null;
|
||||
let index = rows.length - 1;
|
||||
let coveredThrough = rows[index]?.seqEnd ?? Number.NEGATIVE_INFINITY;
|
||||
while (index >= 0 && rows[index].item.type === "user_message") {
|
||||
index -= 1;
|
||||
coveredThrough = Math.max(coveredThrough, rows[index]?.seqEnd ?? coveredThrough);
|
||||
}
|
||||
const previous = rows[index];
|
||||
if (!previous || !continuesAssistantMessage(previous, entry)) return null;
|
||||
const skipsUserRows = index < rows.length - 1;
|
||||
if (skipsUserRows && entry.item.messageId === undefined) return null;
|
||||
return coveredThrough + 1 === entry.seqStart ? index : null;
|
||||
}
|
||||
|
||||
function mergeAssistantEntries(previous: WorkingEntry, entry: WorkingEntry): WorkingEntry {
|
||||
const previousAssistant = previous.item as Extract<
|
||||
AgentTimelineItem,
|
||||
{ type: "assistant_message" }
|
||||
>;
|
||||
const entryAssistant = entry.item as Extract<AgentTimelineItem, { type: "assistant_message" }>;
|
||||
|
||||
const collapsedKinds = new Set<TimelineProjectionKind>([
|
||||
...previous.collapsed,
|
||||
...entry.collapsed,
|
||||
"assistant_merge",
|
||||
]);
|
||||
|
||||
return {
|
||||
...previous,
|
||||
item: {
|
||||
type: "assistant_message",
|
||||
text: `${previousAssistant.text}${entryAssistant.text}`,
|
||||
...(previousAssistant.messageId ? { messageId: previousAssistant.messageId } : {}),
|
||||
},
|
||||
timestamp: entry.timestamp,
|
||||
seqEnd: Math.max(previous.seqEnd, entry.seqEnd),
|
||||
sourceSeqRanges: mergeSeqRanges(previous.sourceSeqRanges, entry.sourceSeqRanges),
|
||||
collapsed: Array.from(collapsedKinds),
|
||||
// The turn's stats ride on its last row, which is the later chunk of a merged message.
|
||||
...(entry.turnMetrics ? { turnMetrics: entry.turnMetrics } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function mergeAssistantChunks(entries: readonly WorkingEntry[]): WorkingEntry[] {
|
||||
const output: WorkingEntry[] = [];
|
||||
|
||||
for (const entry of entries) {
|
||||
const previous = output[output.length - 1];
|
||||
const shouldMerge =
|
||||
previous &&
|
||||
previous.seqEnd + 1 === entry.seqStart &&
|
||||
continuesAssistantMessage(previous, entry);
|
||||
|
||||
if (!shouldMerge || !previous) {
|
||||
const index = assistantContinuationIndex(output, entry);
|
||||
if (index === null) {
|
||||
output.push(entry);
|
||||
continue;
|
||||
}
|
||||
const previousAssistant = previous.item as Extract<
|
||||
AgentTimelineItem,
|
||||
{ type: "assistant_message" }
|
||||
>;
|
||||
const entryAssistant = entry.item as Extract<AgentTimelineItem, { type: "assistant_message" }>;
|
||||
|
||||
const collapsedKinds = new Set<TimelineProjectionKind>([
|
||||
...previous.collapsed,
|
||||
...entry.collapsed,
|
||||
"assistant_merge",
|
||||
]);
|
||||
|
||||
output[output.length - 1] = {
|
||||
...previous,
|
||||
item: {
|
||||
type: "assistant_message",
|
||||
text: `${previousAssistant.text}${entryAssistant.text}`,
|
||||
...(previousAssistant.messageId ? { messageId: previousAssistant.messageId } : {}),
|
||||
},
|
||||
timestamp: entry.timestamp,
|
||||
seqEnd: entry.seqEnd,
|
||||
sourceSeqRanges: mergeSeqRanges(previous.sourceSeqRanges, entry.sourceSeqRanges),
|
||||
collapsed: Array.from(collapsedKinds),
|
||||
// The turn's stats ride on its last row, which is the later chunk of a merged message.
|
||||
...(entry.turnMetrics ? { turnMetrics: entry.turnMetrics } : {}),
|
||||
};
|
||||
output[index] = mergeAssistantEntries(output[index], entry);
|
||||
}
|
||||
|
||||
return output;
|
||||
@@ -358,10 +381,15 @@ export class TimelineProjection {
|
||||
this.extendSpan(index);
|
||||
return index;
|
||||
}
|
||||
const continued = assistantContinuationIndex(this.rows, entry);
|
||||
if (continued !== null) {
|
||||
const mergedText = mergeAssistantEntries(this.rows[continued], entry);
|
||||
this.rows[continued] = { ...mergedText, seq: mergedText.seqEnd };
|
||||
this.extendSpan(continued);
|
||||
return continued;
|
||||
}
|
||||
const previous = this.rows.at(-1);
|
||||
const adjacent = previous
|
||||
? mergeReasoningChunks(mergeAssistantChunks([previous, entry]))
|
||||
: [entry];
|
||||
const adjacent = previous ? mergeReasoningChunks([previous, entry]) : [entry];
|
||||
if (previous && adjacent.length === 1) {
|
||||
const mergedText = adjacent[0];
|
||||
this.rows[this.rows.length - 1] = { ...mergedText, seq: mergedText.seqEnd };
|
||||
|
||||
@@ -197,7 +197,12 @@ test("script status started and stopped by one client reaches every subscribed c
|
||||
await writeFile(
|
||||
path.join(cwd, "paseo.json"),
|
||||
JSON.stringify({
|
||||
scripts: { sleeper: { type: "script", command: 'node -e "setInterval(() => {}, 60000)"' } },
|
||||
scripts: {
|
||||
sleeper: {
|
||||
type: "script",
|
||||
command: `node -e "require('node:fs').writeFileSync('sleeper.pid', String(process.pid)); setInterval(() => {}, 60000)"`,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
const observer = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
@@ -216,10 +221,20 @@ test("script status started and stopped by one client reaches every subscribed c
|
||||
expect((await client.startWorkspaceScript(workspaceId, "sleeper")).error).toBeNull();
|
||||
await expect.poll(() => actorSeen.at(-1)).toBe("running");
|
||||
await expect.poll(() => observerSeen.at(-1)).toBe("running");
|
||||
const pidFile = path.join(cwd, "sleeper.pid");
|
||||
await expect
|
||||
.poll(async () => Number(await readFile(pidFile, "utf8").catch(() => "0")), {
|
||||
timeout: 10_000,
|
||||
})
|
||||
.toBeGreaterThan(0);
|
||||
const pid = Number(await readFile(pidFile, "utf8"));
|
||||
|
||||
expect((await client.stopWorkspaceScript(workspaceId, "sleeper")).error).toBeNull();
|
||||
await expect.poll(() => actorSeen.at(-1)).toBe("stopped");
|
||||
await expect.poll(() => observerSeen.at(-1)).toBe("stopped");
|
||||
// On Windows the PTY kill ends the shell at once and the script's own process a moment
|
||||
// later, while it still holds cwd; the stop is complete once the program has exited.
|
||||
await expect.poll(() => isFixtureProcessRunning(pid), { timeout: 15_000 }).toBe(false);
|
||||
expect(bystanderEvents).not.toContain("script_status_update");
|
||||
} finally {
|
||||
await observer.close();
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
Copyright (c) 2025-present Mohamed Boudra
|
||||
|
||||
Portions of this software are licensed as follows:
|
||||
|
||||
* Third-party components incorporated into Paseo remain licensed under
|
||||
the licenses provided by their respective copyright holders.
|
||||
* Except for those third-party components, Paseo is licensed under the
|
||||
Apache License, Version 2.0, reproduced below.
|
||||
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,60 @@
|
||||
{
|
||||
"name": "@getpaseo/workflows",
|
||||
"version": "0.1.0",
|
||||
"description": "Durable, subject-keyed workflow state machine, IR, DSL, and YAML compiler for Paseo",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
"dist",
|
||||
"!dist/**/*.map",
|
||||
"LICENSE"
|
||||
],
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"source": "./src/index.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./ir": {
|
||||
"types": "./dist/ir.d.ts",
|
||||
"source": "./src/ir.ts",
|
||||
"default": "./dist/ir.js"
|
||||
},
|
||||
"./dsl": {
|
||||
"types": "./dist/dsl.d.ts",
|
||||
"source": "./src/dsl.ts",
|
||||
"default": "./dist/dsl.js"
|
||||
},
|
||||
"./yaml": {
|
||||
"types": "./dist/yaml.d.ts",
|
||||
"source": "./src/yaml.ts",
|
||||
"default": "./dist/yaml.js"
|
||||
},
|
||||
"./testing": {
|
||||
"types": "./dist/testing.d.ts",
|
||||
"source": "./src/testing.ts",
|
||||
"default": "./dist/testing.js"
|
||||
}
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "node ../../scripts/clean-package-dist.mjs",
|
||||
"build": "tsc -p tsconfig.json --incremental false",
|
||||
"build:clean": "npm run clean && npm run build",
|
||||
"prepack": "npm run build:clean",
|
||||
"typecheck": "tsgo --noEmit && tsgo -p tsconfig.typecheck.json --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"ajv": "^8.11.0",
|
||||
"js-yaml": "^4.1.1",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.9.0",
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^4.1.6"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,549 @@
|
||||
import type { z } from "zod";
|
||||
import { createWorkflowEngineImpl } from "./internal/engine.js";
|
||||
import type {
|
||||
AgentSpecIR,
|
||||
AgentTargetIR,
|
||||
AllowOutputIR,
|
||||
AuthGrantIR,
|
||||
GateChoiceIR,
|
||||
JsonObject,
|
||||
JsonSchema,
|
||||
JsonValue,
|
||||
TerminalStatus,
|
||||
WorkflowIR,
|
||||
} from "./ir.js";
|
||||
|
||||
export type {
|
||||
AgentSpecIR,
|
||||
AgentTargetIR,
|
||||
AllowOutputIR,
|
||||
AuthGrantIR,
|
||||
GateChoiceIR,
|
||||
JsonObject,
|
||||
JsonSchema,
|
||||
JsonValue,
|
||||
TerminalStatus,
|
||||
WorkflowIR,
|
||||
};
|
||||
export { validateWorkflowIR, WorkflowValidationError } from "./ir.js";
|
||||
|
||||
export interface Clock {
|
||||
now(): Date;
|
||||
}
|
||||
|
||||
export interface EventActor {
|
||||
readonly id: string;
|
||||
readonly login?: string;
|
||||
readonly isBot: boolean;
|
||||
readonly isSelfApp: boolean;
|
||||
}
|
||||
|
||||
export interface NormalizedIntegrationEvent {
|
||||
readonly id: string;
|
||||
readonly type: string;
|
||||
readonly connection?: string;
|
||||
readonly actor?: EventActor;
|
||||
readonly subject?: {
|
||||
readonly key?: string;
|
||||
readonly data?: JsonObject;
|
||||
};
|
||||
readonly payload: JsonObject;
|
||||
readonly prompt?: string;
|
||||
readonly occurredAt: Date;
|
||||
}
|
||||
|
||||
export interface IntegrationStorageEntry {
|
||||
readonly key: string;
|
||||
readonly value: JsonValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrow scoped key-value/document storage provided to integrations.
|
||||
* Backed by one generic table or store in the host runtime — never a raw database handle.
|
||||
*/
|
||||
export interface IntegrationStorage {
|
||||
get<T extends JsonValue = JsonValue>(key: string): Promise<T | undefined>;
|
||||
set(key: string, value: JsonValue, options?: { readonly ttlMs?: number }): Promise<void>;
|
||||
delete(key: string): Promise<void>;
|
||||
list(prefix?: string): Promise<readonly IntegrationStorageEntry[]>;
|
||||
withLock<T>(key: string, ttlMs: number, fn: () => Promise<T>): Promise<T>;
|
||||
}
|
||||
|
||||
export interface IntegrationConnectionRecord {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly integration: string;
|
||||
readonly config?: JsonObject;
|
||||
readonly secret?: JsonObject;
|
||||
}
|
||||
|
||||
export interface IntegrationConnections {
|
||||
get(connectionNameOrId: string): Promise<IntegrationConnectionRecord | undefined>;
|
||||
list(): Promise<readonly IntegrationConnectionRecord[]>;
|
||||
}
|
||||
|
||||
export interface IntegrationLogger {
|
||||
debug(message: string, meta?: JsonObject): void;
|
||||
info(message: string, meta?: JsonObject): void;
|
||||
warn(message: string, meta?: JsonObject): void;
|
||||
error(message: string, meta?: JsonObject): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The ONLY host context passed into integration hooks (`triggers`, `steps`, `auth`, `tools`).
|
||||
* Deliberately excludes database handles, SQL clients, and workflow engine internals.
|
||||
*/
|
||||
export interface IntegrationContext {
|
||||
readonly scopeId: string;
|
||||
readonly storage: IntegrationStorage;
|
||||
readonly connections: IntegrationConnections;
|
||||
readonly ingest: (event: NormalizedIntegrationEvent) => Promise<void>;
|
||||
readonly fetch: typeof globalThis.fetch;
|
||||
readonly log: IntegrationLogger;
|
||||
readonly now: () => Date;
|
||||
}
|
||||
|
||||
export interface IntegrationTriggerSpec {
|
||||
readonly event: string;
|
||||
readonly filterSchema?: z.ZodType;
|
||||
readonly normalize?: (
|
||||
raw: JsonObject,
|
||||
ctx: IntegrationContext,
|
||||
) => Promise<NormalizedIntegrationEvent> | NormalizedIntegrationEvent;
|
||||
readonly matchFilters?: (event: NormalizedIntegrationEvent, filters: JsonObject) => boolean;
|
||||
}
|
||||
|
||||
export type IntegrationStepExecuteResult =
|
||||
| { readonly status: "completed"; readonly outcome: string; readonly output?: JsonObject }
|
||||
| { readonly status: "suspended"; readonly waitKey: string; readonly timeoutMs?: number };
|
||||
|
||||
export type IntegrationStepEventResult =
|
||||
| { readonly status: "completed"; readonly outcome: string; readonly output?: JsonObject }
|
||||
| { readonly status: "still_waiting" };
|
||||
|
||||
/** Uniform contract covering both synchronous actions and suspended event waits. */
|
||||
export interface IntegrationStepSpec {
|
||||
readonly inputSchema: JsonSchema | z.ZodType;
|
||||
readonly outputSchema?: JsonSchema | z.ZodType;
|
||||
readonly outcomes: readonly string[];
|
||||
execute(input: JsonObject, ctx: IntegrationContext): Promise<IntegrationStepExecuteResult>;
|
||||
onEvent?(
|
||||
event: NormalizedIntegrationEvent,
|
||||
input: JsonObject,
|
||||
ctx: IntegrationContext,
|
||||
): Promise<IntegrationStepEventResult>;
|
||||
}
|
||||
|
||||
export interface IntegrationAuthLease {
|
||||
readonly leaseId: string;
|
||||
readonly env: Readonly<Record<string, string>>;
|
||||
readonly expiresAt?: Date;
|
||||
}
|
||||
|
||||
export interface IntegrationAuthSlot {
|
||||
mint(scope: AuthGrantIR, ctx: IntegrationContext): Promise<IntegrationAuthLease>;
|
||||
revoke(leaseId: string, ctx: IntegrationContext): Promise<void>;
|
||||
}
|
||||
|
||||
export interface IntegrationToolDefinition {
|
||||
readonly name: string;
|
||||
readonly description: string;
|
||||
readonly inputSchema: JsonSchema;
|
||||
}
|
||||
|
||||
export interface IntegrationToolsSlot {
|
||||
readonly grantSchema: z.ZodType<JsonValue>;
|
||||
readonly tools: readonly IntegrationToolDefinition[];
|
||||
execute(
|
||||
tool: string,
|
||||
args: JsonObject,
|
||||
grant: JsonValue,
|
||||
ctx: IntegrationContext,
|
||||
): Promise<JsonValue>;
|
||||
}
|
||||
|
||||
/** 4-slot opt-in integration contract (triggers, steps, auth, tools). */
|
||||
export interface WorkflowIntegration {
|
||||
readonly id: string;
|
||||
readonly triggers?: Readonly<Record<string, IntegrationTriggerSpec>>;
|
||||
readonly steps?: Readonly<Record<string, IntegrationStepSpec>>;
|
||||
readonly auth?: IntegrationAuthSlot;
|
||||
readonly tools?: IntegrationToolsSlot;
|
||||
}
|
||||
|
||||
export interface IntegrationRegistry {
|
||||
get(id: string): WorkflowIntegration | undefined;
|
||||
list(): readonly WorkflowIntegration[];
|
||||
}
|
||||
|
||||
export function createIntegrationRegistry(
|
||||
integrations: readonly WorkflowIntegration[],
|
||||
): IntegrationRegistry {
|
||||
const byId = new Map<string, WorkflowIntegration>();
|
||||
for (const integration of integrations) {
|
||||
if (byId.has(integration.id)) {
|
||||
throw new Error(`duplicate workflow integration id "${integration.id}"`);
|
||||
}
|
||||
byId.set(integration.id, integration);
|
||||
}
|
||||
return {
|
||||
get(id: string): WorkflowIntegration | undefined {
|
||||
return byId.get(id);
|
||||
},
|
||||
list(): readonly WorkflowIntegration[] {
|
||||
return [...byId.values()];
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export interface ActiveAuthLease {
|
||||
readonly integrationId: string;
|
||||
readonly leaseId: string;
|
||||
}
|
||||
|
||||
export type WorkflowRunStatus =
|
||||
| "queued"
|
||||
| "running"
|
||||
| "waiting"
|
||||
| "paused"
|
||||
| "done"
|
||||
| "failed"
|
||||
| "cancelled";
|
||||
|
||||
export type StepAttemptStatus =
|
||||
| "running"
|
||||
| "waiting"
|
||||
| "completed"
|
||||
| "failed"
|
||||
| "cancelled"
|
||||
| "skipped";
|
||||
|
||||
export type StepWaitSpec =
|
||||
| {
|
||||
readonly kind: "integration";
|
||||
readonly integrationId: string;
|
||||
readonly stepName: string;
|
||||
readonly waitKey: string;
|
||||
readonly input: JsonObject;
|
||||
readonly wakeAt?: Date;
|
||||
}
|
||||
| {
|
||||
readonly kind: "wait_workflow";
|
||||
readonly workflowId: string;
|
||||
readonly outputKey: string;
|
||||
readonly wakeAt?: Date;
|
||||
}
|
||||
| {
|
||||
readonly kind: "gate";
|
||||
readonly gateId: string;
|
||||
readonly wakeAt?: Date;
|
||||
}
|
||||
| {
|
||||
readonly kind: "sleep";
|
||||
readonly wakeAt: Date;
|
||||
};
|
||||
|
||||
export interface StepAttemptRecord {
|
||||
readonly id: string;
|
||||
readonly runId: string;
|
||||
readonly stepId: string;
|
||||
readonly attempt: number;
|
||||
readonly executionId: string;
|
||||
readonly status: StepAttemptStatus;
|
||||
readonly outcome?: string;
|
||||
readonly output?: JsonObject;
|
||||
readonly error?: string;
|
||||
readonly wait?: StepWaitSpec;
|
||||
readonly activeLeases: readonly ActiveAuthLease[];
|
||||
readonly startedAt: Date;
|
||||
readonly finishedAt?: Date;
|
||||
}
|
||||
|
||||
export interface WorkflowGateRecord {
|
||||
readonly id: string;
|
||||
readonly runId: string;
|
||||
readonly workflowId: string;
|
||||
readonly stepId: string;
|
||||
readonly attemptId: string;
|
||||
readonly title: string;
|
||||
readonly summary?: string;
|
||||
readonly recommended?: string;
|
||||
readonly choices: readonly GateChoiceIR[];
|
||||
readonly status: "open" | "resolved" | "expired" | "cancelled";
|
||||
readonly openedAt: Date;
|
||||
readonly expiresAt?: Date;
|
||||
readonly resolution?: GateResolution;
|
||||
}
|
||||
|
||||
export interface GateResolution {
|
||||
readonly choice: string;
|
||||
readonly note?: string;
|
||||
readonly actor?: string;
|
||||
readonly resolvedAt: Date;
|
||||
}
|
||||
|
||||
export interface GateResolutionInput {
|
||||
readonly choice: string;
|
||||
readonly note?: string;
|
||||
readonly actor?: string;
|
||||
}
|
||||
|
||||
export interface PublishedWorkflowOutput {
|
||||
readonly workflowId: string;
|
||||
readonly outputKey: string;
|
||||
readonly payload: JsonObject;
|
||||
readonly publishedAt: Date;
|
||||
}
|
||||
|
||||
export interface SuspendedWaitRecord {
|
||||
readonly runId: string;
|
||||
readonly attemptId: string;
|
||||
readonly stepId: string;
|
||||
readonly wait: StepWaitSpec;
|
||||
}
|
||||
|
||||
export interface WorkflowRunSnapshot {
|
||||
readonly id: string;
|
||||
readonly workflowId: string;
|
||||
readonly status: WorkflowRunStatus;
|
||||
readonly pausedFromStatus?: "running" | "waiting";
|
||||
readonly subjectKey?: string;
|
||||
readonly subjectData: JsonObject;
|
||||
readonly inputs: Readonly<Record<string, JsonValue>>;
|
||||
readonly event?: NormalizedIntegrationEvent;
|
||||
readonly currentState: string;
|
||||
readonly loopCounts: Readonly<Record<string, number>>;
|
||||
readonly attempts: readonly StepAttemptRecord[];
|
||||
readonly lastGate?: {
|
||||
readonly choice: string;
|
||||
readonly note: string | null;
|
||||
readonly actor: string | null;
|
||||
};
|
||||
readonly terminalReason?: string;
|
||||
readonly terminalOutputs?: JsonObject;
|
||||
readonly createdAt: Date;
|
||||
readonly updatedAt: Date;
|
||||
readonly completedAt?: Date;
|
||||
}
|
||||
|
||||
export interface AcceptWorkflowRunInput {
|
||||
readonly workflowId: string;
|
||||
readonly initialState: string;
|
||||
readonly subjectKey?: string;
|
||||
readonly subjectData: JsonObject;
|
||||
readonly onConflict?: "signal" | "queue" | "ignore" | "cancel_previous";
|
||||
readonly inputs: Readonly<Record<string, JsonValue>>;
|
||||
readonly event?: NormalizedIntegrationEvent;
|
||||
readonly now: Date;
|
||||
}
|
||||
|
||||
export type AcceptWorkflowRunResult =
|
||||
| { readonly action: "started"; readonly run: WorkflowRunSnapshot }
|
||||
| { readonly action: "queued"; readonly run: WorkflowRunSnapshot }
|
||||
| { readonly action: "ignored"; readonly existingRun: WorkflowRunSnapshot }
|
||||
| { readonly action: "signal"; readonly existingRun: WorkflowRunSnapshot }
|
||||
| {
|
||||
readonly action: "replaced";
|
||||
readonly run: WorkflowRunSnapshot;
|
||||
readonly cancelledRun: WorkflowRunSnapshot;
|
||||
};
|
||||
|
||||
export interface BeginStepAttemptInput {
|
||||
readonly runId: string;
|
||||
readonly stepId: string;
|
||||
readonly incrementLoop: boolean;
|
||||
readonly now: Date;
|
||||
}
|
||||
|
||||
export interface CompleteStepAttemptInput {
|
||||
readonly runId: string;
|
||||
readonly attemptId: string;
|
||||
readonly status: "completed" | "failed" | "cancelled" | "skipped";
|
||||
readonly outcome?: string;
|
||||
readonly output?: JsonObject;
|
||||
readonly error?: string;
|
||||
readonly now: Date;
|
||||
}
|
||||
|
||||
export interface TransitionRunInput {
|
||||
readonly runId: string;
|
||||
readonly status: WorkflowRunStatus;
|
||||
readonly currentState?: string;
|
||||
readonly pausedFromStatus?: "running" | "waiting";
|
||||
readonly lastGate?: WorkflowRunSnapshot["lastGate"];
|
||||
readonly terminalReason?: string;
|
||||
readonly terminalOutputs?: JsonObject;
|
||||
readonly now: Date;
|
||||
}
|
||||
|
||||
export interface OpenGateInput {
|
||||
readonly runId: string;
|
||||
readonly workflowId: string;
|
||||
readonly stepId: string;
|
||||
readonly attemptId: string;
|
||||
readonly title: string;
|
||||
readonly summary?: string;
|
||||
readonly recommended?: string;
|
||||
readonly choices: readonly GateChoiceIR[];
|
||||
readonly openedAt: Date;
|
||||
readonly expiresAt?: Date;
|
||||
}
|
||||
|
||||
export interface ListRunsFilter {
|
||||
readonly workflowId?: string;
|
||||
readonly subjectKey?: string;
|
||||
readonly status?: WorkflowRunStatus | readonly WorkflowRunStatus[];
|
||||
}
|
||||
|
||||
export interface ListOpenGatesFilter {
|
||||
readonly workflowId?: string;
|
||||
readonly runId?: string;
|
||||
}
|
||||
|
||||
/** Persistence seam implemented by host storage backends (remote, embedded, or in-memory). */
|
||||
export interface WorkflowStore {
|
||||
acceptRun(input: AcceptWorkflowRunInput): Promise<AcceptWorkflowRunResult>;
|
||||
loadRun(runId: string): Promise<WorkflowRunSnapshot | undefined>;
|
||||
listRuns(filter?: ListRunsFilter): Promise<readonly WorkflowRunSnapshot[]>;
|
||||
dequeueNextRun(
|
||||
workflowId: string,
|
||||
subjectKey: string,
|
||||
now: Date,
|
||||
): Promise<WorkflowRunSnapshot | undefined>;
|
||||
|
||||
beginStepAttempt(input: BeginStepAttemptInput): Promise<StepAttemptRecord>;
|
||||
setAttemptLeases(attemptId: string, leases: readonly ActiveAuthLease[]): Promise<void>;
|
||||
setAttemptExecutionId(attemptId: string, executionId: string): Promise<void>;
|
||||
suspendStepAttempt(attemptId: string, wait: StepWaitSpec): Promise<void>;
|
||||
completeStepAttempt(input: CompleteStepAttemptInput): Promise<WorkflowRunSnapshot>;
|
||||
transitionRun(input: TransitionRunInput): Promise<WorkflowRunSnapshot>;
|
||||
|
||||
listSuspendedWaits(
|
||||
kind?: StepWaitSpec["kind"],
|
||||
options?: { readonly includePaused?: boolean },
|
||||
): Promise<readonly SuspendedWaitRecord[]>;
|
||||
findExpiredWaits(now: Date): Promise<readonly SuspendedWaitRecord[]>;
|
||||
|
||||
publishWorkflowOutput(input: PublishedWorkflowOutput): Promise<readonly SuspendedWaitRecord[]>;
|
||||
findWorkflowOutput(
|
||||
workflowId: string,
|
||||
outputKey: string,
|
||||
): Promise<PublishedWorkflowOutput | undefined>;
|
||||
|
||||
openGate(input: OpenGateInput): Promise<WorkflowGateRecord>;
|
||||
getGate(gateId: string): Promise<WorkflowGateRecord | undefined>;
|
||||
listOpenGates(filter?: ListOpenGatesFilter): Promise<readonly WorkflowGateRecord[]>;
|
||||
resolveGate(gateId: string, resolution: GateResolution): Promise<WorkflowGateRecord | undefined>;
|
||||
expireGate(gateId: string): Promise<WorkflowGateRecord | undefined>;
|
||||
cancelRunGates(runId: string): Promise<readonly WorkflowGateRecord[]>;
|
||||
}
|
||||
|
||||
export interface AgentStepRequest {
|
||||
readonly runId: string;
|
||||
readonly workflowId: string;
|
||||
readonly stepId: string;
|
||||
readonly attempt: number;
|
||||
readonly executionId: string;
|
||||
readonly prompt: string;
|
||||
readonly title?: string;
|
||||
readonly target?: AgentTargetIR;
|
||||
readonly agent?: AgentSpecIR;
|
||||
readonly continuation?: { readonly mode: string };
|
||||
readonly env: Readonly<Record<string, string>>;
|
||||
readonly outputSchema?: JsonSchema;
|
||||
readonly tools?: Readonly<Record<string, JsonValue>>;
|
||||
readonly allowOutputs?: Readonly<Record<string, AllowOutputIR>>;
|
||||
readonly maxRuntimeMs?: number;
|
||||
readonly idleTimeoutMs?: number;
|
||||
readonly startupTimeoutMs?: number;
|
||||
readonly autoArchive?: boolean;
|
||||
readonly background?: boolean;
|
||||
}
|
||||
|
||||
export type AgentStepStartResult =
|
||||
| { readonly status: "completed"; readonly outcome?: string; readonly output?: JsonObject }
|
||||
| { readonly status: "running"; readonly executionId?: string }
|
||||
| { readonly status: "failed"; readonly error: string };
|
||||
|
||||
export interface AgentRunner {
|
||||
start(request: AgentStepRequest): Promise<AgentStepStartResult>;
|
||||
cancel(executionId: string, reason: string): Promise<void>;
|
||||
inspect?(executionId: string): Promise<AgentStepStartResult>;
|
||||
}
|
||||
|
||||
export interface GateSink {
|
||||
onGateOpened(gate: WorkflowGateRecord): Promise<void>;
|
||||
onGateResolved?(gate: WorkflowGateRecord): Promise<void>;
|
||||
onGateExpired?(gate: WorkflowGateRecord): Promise<void>;
|
||||
}
|
||||
|
||||
export interface StartWorkflowInput {
|
||||
readonly workflowId: string;
|
||||
readonly inputs?: Readonly<Record<string, JsonValue>>;
|
||||
readonly event?: NormalizedIntegrationEvent;
|
||||
readonly subjectKey?: string;
|
||||
readonly subjectData?: JsonObject;
|
||||
}
|
||||
|
||||
export interface CompleteAgentStepInput {
|
||||
readonly runId: string;
|
||||
readonly executionId: string;
|
||||
readonly outcome?: string;
|
||||
readonly output?: JsonObject;
|
||||
readonly error?: string;
|
||||
}
|
||||
|
||||
export interface PublishOutputInput {
|
||||
readonly workflowId: string;
|
||||
readonly outputKey: string;
|
||||
readonly payload: JsonObject;
|
||||
}
|
||||
|
||||
export interface PublishOutputResult {
|
||||
readonly output: PublishedWorkflowOutput;
|
||||
readonly resumedRuns: readonly WorkflowRunSnapshot[];
|
||||
}
|
||||
|
||||
export interface IngestResult {
|
||||
readonly matchedRuns: readonly WorkflowRunSnapshot[];
|
||||
readonly resumedRuns: readonly WorkflowRunSnapshot[];
|
||||
}
|
||||
|
||||
export interface TickResult {
|
||||
readonly wokenRuns: readonly WorkflowRunSnapshot[];
|
||||
}
|
||||
|
||||
export interface WorkflowEngineOptions {
|
||||
readonly store: WorkflowStore;
|
||||
readonly runner: AgentRunner;
|
||||
readonly gates: GateSink;
|
||||
readonly integrations: IntegrationRegistry | readonly WorkflowIntegration[];
|
||||
readonly clock: Clock;
|
||||
readonly workflows?: readonly WorkflowIR[];
|
||||
readonly scopeId?: string;
|
||||
readonly storage?: IntegrationStorage;
|
||||
readonly connections?: IntegrationConnections;
|
||||
readonly fetch?: typeof globalThis.fetch;
|
||||
readonly log?: IntegrationLogger;
|
||||
}
|
||||
|
||||
/** Opaque durable execution engine interface (storage- and runtime-agnostic). */
|
||||
export interface WorkflowEngine {
|
||||
registerWorkflow(workflow: WorkflowIR): void;
|
||||
ingest(event: NormalizedIntegrationEvent): Promise<IngestResult>;
|
||||
start(input: StartWorkflowInput): Promise<WorkflowRunSnapshot>;
|
||||
completeAgentStep(input: CompleteAgentStepInput): Promise<WorkflowRunSnapshot>;
|
||||
resolveGate(gateId: string, resolution: GateResolutionInput): Promise<WorkflowRunSnapshot>;
|
||||
publishOutput(input: PublishOutputInput): Promise<PublishOutputResult>;
|
||||
pause(runId: string): Promise<WorkflowRunSnapshot>;
|
||||
resume(runId: string): Promise<WorkflowRunSnapshot>;
|
||||
cancel(runId: string, reason?: string): Promise<WorkflowRunSnapshot>;
|
||||
tick(): Promise<TickResult>;
|
||||
getRun(runId: string): Promise<WorkflowRunSnapshot | undefined>;
|
||||
listRuns(filter?: ListRunsFilter): Promise<readonly WorkflowRunSnapshot[]>;
|
||||
listOpenGates(filter?: ListOpenGatesFilter): Promise<readonly WorkflowGateRecord[]>;
|
||||
}
|
||||
|
||||
export function createWorkflowEngine(options: WorkflowEngineOptions): WorkflowEngine {
|
||||
return createWorkflowEngineImpl(options);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
const DURATION_PATTERN = /^([1-9][0-9]*)(ms|s|m|h|d)$/u;
|
||||
|
||||
const UNIT_MS: Readonly<Record<string, number>> = {
|
||||
ms: 1,
|
||||
s: 1_000,
|
||||
m: 60_000,
|
||||
h: 3_600_000,
|
||||
d: 86_400_000,
|
||||
};
|
||||
|
||||
export type DurationInput = number | string;
|
||||
|
||||
export function parseDurationMs(value: DurationInput, fieldName = "duration"): number {
|
||||
if (typeof value === "number") {
|
||||
if (!Number.isFinite(value) || value <= 0) {
|
||||
throw new Error(`${fieldName} must be a positive finite number of milliseconds`);
|
||||
}
|
||||
return Math.trunc(value);
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
const match = DURATION_PATTERN.exec(trimmed);
|
||||
if (match === null) {
|
||||
throw new Error(
|
||||
`${fieldName} must be a positive duration like "30s", "15m", "2h", or "14d" (got ${JSON.stringify(value)})`,
|
||||
);
|
||||
}
|
||||
const amount = Number(match[1]);
|
||||
const unit = match[2];
|
||||
const multiplier = unit === undefined ? undefined : UNIT_MS[unit];
|
||||
if (multiplier === undefined) {
|
||||
throw new Error(`${fieldName} has unsupported unit in ${JSON.stringify(value)}`);
|
||||
}
|
||||
const total = amount * multiplier;
|
||||
if (!Number.isSafeInteger(total) || total <= 0) {
|
||||
throw new Error(`${fieldName} is out of range: ${JSON.stringify(value)}`);
|
||||
}
|
||||
return total;
|
||||
}
|
||||
@@ -0,0 +1,745 @@
|
||||
export type JsonPrimitive = string | number | boolean | null;
|
||||
export type JsonValue =
|
||||
| JsonPrimitive
|
||||
| readonly JsonValue[]
|
||||
| { readonly [key: string]: JsonValue };
|
||||
export interface JsonObject {
|
||||
readonly [key: string]: JsonValue;
|
||||
}
|
||||
export type JsonSchema = JsonObject;
|
||||
|
||||
export type ExprPath =
|
||||
| { readonly namespace: "event"; readonly path: readonly string[] }
|
||||
| { readonly namespace: "inputs"; readonly name: string }
|
||||
| { readonly namespace: "subject"; readonly field: "key" }
|
||||
| { readonly namespace: "subject"; readonly field: "data"; readonly path: readonly string[] }
|
||||
| { readonly namespace: "steps"; readonly stepId: string; readonly field: "outcome" | "attempts" }
|
||||
| {
|
||||
readonly namespace: "steps";
|
||||
readonly stepId: string;
|
||||
readonly field: "outputs";
|
||||
readonly path: readonly string[];
|
||||
}
|
||||
| { readonly namespace: "gate"; readonly field: "choice" | "note" | "actor" }
|
||||
| { readonly namespace: "execution"; readonly field: "id" }
|
||||
| { readonly namespace: "paseo"; readonly field: "prompt" }
|
||||
| { readonly namespace: "values"; readonly name: string };
|
||||
|
||||
export type BinaryOperator = "==" | "!=" | "&&" | "||" | "??";
|
||||
|
||||
export type ExprNode =
|
||||
| { readonly kind: "literal"; readonly value: JsonValue }
|
||||
| { readonly kind: "path"; readonly path: ExprPath }
|
||||
| { readonly kind: "not"; readonly value: ExprNode }
|
||||
| {
|
||||
readonly kind: "binary";
|
||||
readonly operator: BinaryOperator;
|
||||
readonly left: ExprNode;
|
||||
readonly right: ExprNode;
|
||||
}
|
||||
| { readonly kind: "template"; readonly parts: readonly (string | ExprNode)[] };
|
||||
|
||||
export interface StepEvalState {
|
||||
readonly outcome: string | null;
|
||||
readonly outputs: JsonObject | null;
|
||||
readonly attempts: number;
|
||||
}
|
||||
|
||||
export interface GateEvalState {
|
||||
readonly choice: string | null;
|
||||
readonly note: string | null;
|
||||
readonly actor: string | null;
|
||||
}
|
||||
|
||||
export interface ExpressionContext {
|
||||
readonly event: JsonValue;
|
||||
readonly prompt: string;
|
||||
readonly inputs: Readonly<Record<string, JsonValue>>;
|
||||
readonly subject: {
|
||||
readonly key: string | null;
|
||||
readonly data: JsonObject;
|
||||
};
|
||||
readonly steps: Readonly<Record<string, StepEvalState>>;
|
||||
readonly gate: GateEvalState;
|
||||
readonly values: Readonly<Record<string, ExprNode>>;
|
||||
readonly executionId: string | null;
|
||||
}
|
||||
|
||||
export class ExpressionSyntaxError extends Error {
|
||||
constructor(message: string) {
|
||||
super(`invalid workflow expression: ${message}`);
|
||||
this.name = "ExpressionSyntaxError";
|
||||
}
|
||||
}
|
||||
|
||||
export class ExpressionEvaluationError extends Error {
|
||||
constructor(message: string) {
|
||||
super(`workflow expression could not be evaluated: ${message}`);
|
||||
this.name = "ExpressionEvaluationError";
|
||||
}
|
||||
}
|
||||
|
||||
type Operator = "!" | BinaryOperator;
|
||||
|
||||
type Token =
|
||||
| { readonly kind: "literal"; readonly value: JsonValue }
|
||||
| { readonly kind: "identifier"; readonly value: string }
|
||||
| { readonly kind: "operator"; readonly value: Operator }
|
||||
| { readonly kind: "dot" }
|
||||
| { readonly kind: "left" }
|
||||
| { readonly kind: "right" }
|
||||
| { readonly kind: "array-left" }
|
||||
| { readonly kind: "array-right" }
|
||||
| { readonly kind: "object-left" }
|
||||
| { readonly kind: "object-right" }
|
||||
| { readonly kind: "comma" }
|
||||
| { readonly kind: "colon" }
|
||||
| { readonly kind: "end" };
|
||||
|
||||
const TOKEN_PATTERN =
|
||||
/\s*(?:(true|false|null)\b|(-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)|("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')|([a-zA-Z_][a-zA-Z0-9_-]*)|(!=|==|&&|\|\||\?\?|!)|(\.)|(\()|(\))|(\[)|(\])|(\{)|(\})|(,)|(:)|(.))/gy;
|
||||
|
||||
export function isJsonValue(value: unknown): value is JsonValue {
|
||||
if (value === null || typeof value === "string" || typeof value === "boolean") {
|
||||
return true;
|
||||
}
|
||||
if (typeof value === "number") {
|
||||
return Number.isFinite(value);
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return value.every(isJsonValue);
|
||||
}
|
||||
if (typeof value === "object") {
|
||||
return Object.values(value).every(isJsonValue);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function isJsonObject(value: unknown): value is JsonObject {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value) && isJsonValue(value);
|
||||
}
|
||||
|
||||
export function parseExprPath(dotted: string): ExprPath {
|
||||
const parts = dotted
|
||||
.trim()
|
||||
.split(".")
|
||||
.map((segment) => segment.trim())
|
||||
.filter((segment) => segment.length > 0);
|
||||
if (parts.length === 0) {
|
||||
throw new ExpressionSyntaxError("empty reference path");
|
||||
}
|
||||
return parsePathSegments(parts);
|
||||
}
|
||||
|
||||
export function parseExpression(source: string): ExprNode {
|
||||
const text = unwrapExpression(source);
|
||||
const tokens = tokenize(text);
|
||||
let index = 0;
|
||||
|
||||
const parse = (minimumPrecedence = 0): ExprNode => {
|
||||
let left = parsePrefix();
|
||||
while (true) {
|
||||
const token = tokens[index];
|
||||
if (token?.kind !== "operator" || token.value === "!") {
|
||||
break;
|
||||
}
|
||||
const operator = token.value;
|
||||
const precedence = operatorPrecedence(operator);
|
||||
if (precedence < minimumPrecedence) {
|
||||
break;
|
||||
}
|
||||
index += 1;
|
||||
const right = parse(precedence + 1);
|
||||
left = { kind: "binary", operator, left, right };
|
||||
}
|
||||
return left;
|
||||
};
|
||||
|
||||
const parsePrefix = (): ExprNode => {
|
||||
const token = tokens[index++];
|
||||
if (token === undefined) {
|
||||
throw new ExpressionSyntaxError("expression ended unexpectedly");
|
||||
}
|
||||
if (token.kind === "literal") {
|
||||
return { kind: "literal", value: token.value };
|
||||
}
|
||||
if (token.kind === "operator" && token.value === "!") {
|
||||
return { kind: "not", value: parsePrefix() };
|
||||
}
|
||||
if (token.kind === "left") {
|
||||
const inner = parse();
|
||||
if (tokens[index]?.kind !== "right") {
|
||||
throw new ExpressionSyntaxError("missing ')'");
|
||||
}
|
||||
index += 1;
|
||||
return inner;
|
||||
}
|
||||
if (token.kind === "array-left") {
|
||||
return parseArrayLiteral();
|
||||
}
|
||||
if (token.kind === "object-left") {
|
||||
return parseObjectLiteral();
|
||||
}
|
||||
if (token.kind !== "identifier") {
|
||||
throw new ExpressionSyntaxError("expected a value");
|
||||
}
|
||||
return parsePath(token.value);
|
||||
};
|
||||
|
||||
const result = parse();
|
||||
if (tokens[index]?.kind !== "end") {
|
||||
throw new ExpressionSyntaxError("unexpected trailing token");
|
||||
}
|
||||
return result;
|
||||
|
||||
function parsePath(first: string): ExprNode {
|
||||
const parts = [first];
|
||||
while (tokens[index]?.kind === "dot") {
|
||||
index += 1;
|
||||
const next = tokens[index++];
|
||||
if (next?.kind !== "identifier") {
|
||||
throw new ExpressionSyntaxError("expected path segment");
|
||||
}
|
||||
parts.push(next.value);
|
||||
}
|
||||
return { kind: "path", path: parsePathSegments(parts) };
|
||||
}
|
||||
|
||||
function parseArrayLiteral(): ExprNode {
|
||||
const values: JsonValue[] = [];
|
||||
if (tokens[index]?.kind === "array-right") {
|
||||
index += 1;
|
||||
return { kind: "literal", value: values };
|
||||
}
|
||||
while (true) {
|
||||
values.push(readJsonLiteral());
|
||||
const separator = tokens[index++];
|
||||
if (separator?.kind === "array-right") {
|
||||
break;
|
||||
}
|
||||
if (separator?.kind !== "comma") {
|
||||
throw new ExpressionSyntaxError("expected ',' or ']'");
|
||||
}
|
||||
if (tokens[index]?.kind === "array-right") {
|
||||
throw new ExpressionSyntaxError("trailing comma in array literal");
|
||||
}
|
||||
}
|
||||
return { kind: "literal", value: values };
|
||||
}
|
||||
|
||||
function parseObjectLiteral(): ExprNode {
|
||||
const value: Record<string, JsonValue> = {};
|
||||
if (tokens[index]?.kind === "object-right") {
|
||||
index += 1;
|
||||
return { kind: "literal", value };
|
||||
}
|
||||
while (true) {
|
||||
const key = tokens[index++];
|
||||
if (key?.kind !== "literal" || typeof key.value !== "string") {
|
||||
throw new ExpressionSyntaxError("object keys must be strings");
|
||||
}
|
||||
if (tokens[index++]?.kind !== "colon") {
|
||||
throw new ExpressionSyntaxError("expected ':'");
|
||||
}
|
||||
value[key.value] = readJsonLiteral();
|
||||
const separator = tokens[index++];
|
||||
if (separator?.kind === "object-right") {
|
||||
break;
|
||||
}
|
||||
if (separator?.kind !== "comma") {
|
||||
throw new ExpressionSyntaxError("expected ',' or '}'");
|
||||
}
|
||||
if (tokens[index]?.kind === "object-right") {
|
||||
throw new ExpressionSyntaxError("trailing comma in object literal");
|
||||
}
|
||||
}
|
||||
return { kind: "literal", value };
|
||||
}
|
||||
|
||||
function readJsonLiteral(): JsonValue {
|
||||
const expression = parsePrefix();
|
||||
if (expression.kind !== "literal") {
|
||||
throw new ExpressionSyntaxError("JSON literals cannot contain paths or operators");
|
||||
}
|
||||
return expression.value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a string containing zero, one, or many `${{ ... }}` or `{{ ... }}` interpolations into
|
||||
* a canonical `ExprNode`.
|
||||
* - A plain string with no interpolations becomes `{ kind: "literal", value }`.
|
||||
* - A string whose entire content is a single interpolation becomes that inner `ExprNode`
|
||||
* (preserving typed non-string values such as numbers, booleans, arrays, or objects).
|
||||
* - A mixed template becomes `{ kind: "template", parts }` with adjacent strings merged.
|
||||
*/
|
||||
export function parseTemplateExpression(template: string): ExprNode {
|
||||
const parts: (string | ExprNode)[] = [];
|
||||
let cursor = 0;
|
||||
|
||||
while (cursor < template.length) {
|
||||
const next = findNextInterpolation(template, cursor);
|
||||
if (next === undefined) {
|
||||
parts.push(template.slice(cursor));
|
||||
break;
|
||||
}
|
||||
if (next.start > cursor) {
|
||||
parts.push(template.slice(cursor, next.start));
|
||||
}
|
||||
const end = template.indexOf("}}", next.exprStart);
|
||||
if (end < 0) {
|
||||
throw new ExpressionSyntaxError("unterminated template interpolation");
|
||||
}
|
||||
const exprText = template.slice(next.exprStart, end).trim();
|
||||
if (exprText.length === 0) {
|
||||
throw new ExpressionSyntaxError("empty template interpolation");
|
||||
}
|
||||
parts.push(parseExpression(exprText));
|
||||
cursor = end + 2;
|
||||
}
|
||||
|
||||
return normalizeTemplateParts(parts);
|
||||
}
|
||||
|
||||
/** Build a canonical `ExprNode` from template literal segments and expressions. */
|
||||
export function buildTemplateExpr(parts: readonly (string | ExprNode)[]): ExprNode {
|
||||
return normalizeTemplateParts(parts);
|
||||
}
|
||||
|
||||
function appendTemplatePart(merged: (string | ExprNode)[], part: string | ExprNode): void {
|
||||
if (typeof part === "string") {
|
||||
if (part.length === 0) {
|
||||
return;
|
||||
}
|
||||
const prev = merged[merged.length - 1];
|
||||
if (typeof prev === "string") {
|
||||
merged[merged.length - 1] = prev + part;
|
||||
} else {
|
||||
merged.push(part);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (part.kind === "template") {
|
||||
for (const nested of part.parts) {
|
||||
appendTemplatePart(merged, nested);
|
||||
}
|
||||
return;
|
||||
}
|
||||
merged.push(part);
|
||||
}
|
||||
|
||||
export function normalizeTemplateParts(rawParts: readonly (string | ExprNode)[]): ExprNode {
|
||||
const merged: (string | ExprNode)[] = [];
|
||||
for (const part of rawParts) {
|
||||
appendTemplatePart(merged, part);
|
||||
}
|
||||
|
||||
if (merged.length === 0) {
|
||||
return { kind: "literal", value: "" };
|
||||
}
|
||||
if (merged.length === 1) {
|
||||
const sole = merged[0]!;
|
||||
return typeof sole === "string" ? { kind: "literal", value: sole } : sole;
|
||||
}
|
||||
return { kind: "template", parts: merged };
|
||||
}
|
||||
|
||||
export function collectExprPaths(expression: ExprNode): ExprPath[] {
|
||||
switch (expression.kind) {
|
||||
case "literal":
|
||||
return [];
|
||||
case "path":
|
||||
return [expression.path];
|
||||
case "not":
|
||||
return collectExprPaths(expression.value);
|
||||
case "binary":
|
||||
return [...collectExprPaths(expression.left), ...collectExprPaths(expression.right)];
|
||||
case "template": {
|
||||
const paths: ExprPath[] = [];
|
||||
for (const part of expression.parts) {
|
||||
if (typeof part !== "string") {
|
||||
paths.push(...collectExprPaths(part));
|
||||
}
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function evaluateExpression(expression: ExprNode, context: ExpressionContext): JsonValue {
|
||||
return evaluateInternal(expression, context, new Set());
|
||||
}
|
||||
|
||||
export function evaluateStringExpression(expression: ExprNode, context: ExpressionContext): string {
|
||||
const value = evaluateExpression(expression, context);
|
||||
return formatInterpolatedValue(value);
|
||||
}
|
||||
|
||||
function evaluateInternal(
|
||||
expression: ExprNode,
|
||||
context: ExpressionContext,
|
||||
seenValues: Set<string>,
|
||||
): JsonValue {
|
||||
switch (expression.kind) {
|
||||
case "literal":
|
||||
return expression.value;
|
||||
case "path":
|
||||
return readPath(expression.path, context, seenValues);
|
||||
case "not":
|
||||
return !isTruthy(evaluateInternal(expression.value, context, seenValues));
|
||||
case "binary": {
|
||||
const left = evaluateInternal(expression.left, context, seenValues);
|
||||
if (expression.operator === "&&") {
|
||||
return isTruthy(left) ? evaluateInternal(expression.right, context, seenValues) : left;
|
||||
}
|
||||
if (expression.operator === "||") {
|
||||
return isTruthy(left) ? left : evaluateInternal(expression.right, context, seenValues);
|
||||
}
|
||||
if (expression.operator === "??") {
|
||||
return left === null ? evaluateInternal(expression.right, context, seenValues) : left;
|
||||
}
|
||||
const right = evaluateInternal(expression.right, context, seenValues);
|
||||
if (expression.operator === "==") {
|
||||
return sameJsonValue(left, right);
|
||||
}
|
||||
return !sameJsonValue(left, right);
|
||||
}
|
||||
case "template": {
|
||||
let output = "";
|
||||
for (const part of expression.parts) {
|
||||
if (typeof part === "string") {
|
||||
output += part;
|
||||
} else {
|
||||
output += formatInterpolatedValue(evaluateInternal(part, context, seenValues));
|
||||
}
|
||||
}
|
||||
return output;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function readPath(path: ExprPath, context: ExpressionContext, seenValues: Set<string>): JsonValue {
|
||||
switch (path.namespace) {
|
||||
case "event":
|
||||
return readNestedValue(context.event, path.path);
|
||||
case "inputs":
|
||||
return context.inputs[path.name] ?? null;
|
||||
case "subject":
|
||||
if (path.field === "key") {
|
||||
return context.subject.key;
|
||||
}
|
||||
return readNestedValue(context.subject.data, path.path);
|
||||
case "steps": {
|
||||
const step = context.steps[path.stepId];
|
||||
if (step === undefined) {
|
||||
return path.field === "attempts" ? 0 : null;
|
||||
}
|
||||
if (path.field === "outputs") {
|
||||
if (step.outputs === null) {
|
||||
return null;
|
||||
}
|
||||
return readNestedValue(step.outputs, path.path);
|
||||
}
|
||||
if (path.field === "outcome") {
|
||||
return step.outcome;
|
||||
}
|
||||
return step.attempts;
|
||||
}
|
||||
case "gate":
|
||||
return context.gate[path.field];
|
||||
case "execution":
|
||||
return context.executionId;
|
||||
case "paseo":
|
||||
return context.prompt;
|
||||
case "values": {
|
||||
const valueExpr = context.values[path.name];
|
||||
if (valueExpr === undefined) {
|
||||
throw new ExpressionEvaluationError(`value ${path.name} is unavailable`);
|
||||
}
|
||||
if (seenValues.has(path.name)) {
|
||||
throw new ExpressionEvaluationError(`cyclic value reference: ${path.name}`);
|
||||
}
|
||||
seenValues.add(path.name);
|
||||
try {
|
||||
return evaluateInternal(valueExpr, context, seenValues);
|
||||
} finally {
|
||||
seenValues.delete(path.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function readNestedValue(root: JsonValue, segments: readonly string[]): JsonValue {
|
||||
let current: unknown = root;
|
||||
for (const segment of segments) {
|
||||
if (typeof current !== "object" || current === null || Array.isArray(current)) {
|
||||
return null;
|
||||
}
|
||||
if (!Object.hasOwn(current, segment)) {
|
||||
return null;
|
||||
}
|
||||
current = Reflect.get(current, segment);
|
||||
}
|
||||
if (current === undefined) {
|
||||
return null;
|
||||
}
|
||||
if (!isJsonValue(current)) {
|
||||
throw new ExpressionEvaluationError("path resolved to a non-JSON value");
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
function parseSubjectPath(parts: readonly string[]): ExprPath {
|
||||
if (parts[1] === "key" && parts.length === 2) {
|
||||
return { namespace: "subject", field: "key" };
|
||||
}
|
||||
if (parts[1] === "data" && parts.length >= 3) {
|
||||
return { namespace: "subject", field: "data", path: parts.slice(2) };
|
||||
}
|
||||
throw new ExpressionSyntaxError(`unsupported path ${parts.join(".")}`);
|
||||
}
|
||||
|
||||
function parseStepsPath(parts: readonly string[]): ExprPath {
|
||||
if (parts.length < 3) {
|
||||
throw new ExpressionSyntaxError(`unsupported path ${parts.join(".")}`);
|
||||
}
|
||||
const stepId = parts[1]!;
|
||||
const field = parts[2];
|
||||
if ((field === "outcome" || field === "attempts") && parts.length === 3) {
|
||||
return { namespace: "steps", stepId, field };
|
||||
}
|
||||
if (field === "outputs" && parts.length >= 4) {
|
||||
return { namespace: "steps", stepId, field: "outputs", path: parts.slice(3) };
|
||||
}
|
||||
throw new ExpressionSyntaxError(`unsupported path ${parts.join(".")}`);
|
||||
}
|
||||
|
||||
function parsePaseoAliasPath(parts: readonly string[]): ExprPath {
|
||||
if (parts[1] === "prompt" && parts.length === 2) {
|
||||
return { namespace: "paseo", field: "prompt" };
|
||||
}
|
||||
if (parts[1] === "context") {
|
||||
return { namespace: "event", path: parts.slice(2) };
|
||||
}
|
||||
if (parts[1] === "inputs" && parts.length === 3) {
|
||||
return { namespace: "inputs", name: parts[2]! };
|
||||
}
|
||||
if (parts[1] === "execution" && parts[2] === "id" && parts.length === 3) {
|
||||
return { namespace: "execution", field: "id" };
|
||||
}
|
||||
throw new ExpressionSyntaxError(`unsupported path ${parts.join(".")}`);
|
||||
}
|
||||
|
||||
function parsePathSegments(parts: readonly string[]): ExprPath {
|
||||
switch (parts[0]) {
|
||||
case "event":
|
||||
return { namespace: "event", path: parts.slice(1) };
|
||||
case "inputs":
|
||||
if (parts.length === 2) return { namespace: "inputs", name: parts[1]! };
|
||||
break;
|
||||
case "subject":
|
||||
return parseSubjectPath(parts);
|
||||
case "steps":
|
||||
return parseStepsPath(parts);
|
||||
case "gate":
|
||||
if (
|
||||
parts.length === 2 &&
|
||||
(parts[1] === "choice" || parts[1] === "note" || parts[1] === "actor")
|
||||
) {
|
||||
return { namespace: "gate", field: parts[1] };
|
||||
}
|
||||
break;
|
||||
case "execution":
|
||||
if (parts.length === 2 && parts[1] === "id") return { namespace: "execution", field: "id" };
|
||||
break;
|
||||
case "values":
|
||||
if (parts.length === 2) return { namespace: "values", name: parts[1]! };
|
||||
break;
|
||||
case "paseo":
|
||||
return parsePaseoAliasPath(parts);
|
||||
}
|
||||
throw new ExpressionSyntaxError(`unsupported path ${parts.join(".")}`);
|
||||
}
|
||||
|
||||
function findNextInterpolation(
|
||||
template: string,
|
||||
fromIndex: number,
|
||||
): { readonly start: number; readonly exprStart: number } | undefined {
|
||||
const dollarIdx = template.indexOf("${{", fromIndex);
|
||||
const bareIdx = template.indexOf("{{", fromIndex);
|
||||
|
||||
if (dollarIdx < 0 && bareIdx < 0) {
|
||||
return undefined;
|
||||
}
|
||||
if (dollarIdx >= 0 && (bareIdx < 0 || dollarIdx <= bareIdx)) {
|
||||
return { start: dollarIdx, exprStart: dollarIdx + 3 };
|
||||
}
|
||||
// If bareIdx is immediately preceded by '$', it is actually a '${{' delimiter.
|
||||
if (bareIdx > 0 && template[bareIdx - 1] === "$") {
|
||||
return { start: bareIdx - 1, exprStart: bareIdx + 2 };
|
||||
}
|
||||
return { start: bareIdx, exprStart: bareIdx + 2 };
|
||||
}
|
||||
|
||||
function tokenize(source: string): Token[] {
|
||||
const tokens: Token[] = [];
|
||||
TOKEN_PATTERN.lastIndex = 0;
|
||||
while (TOKEN_PATTERN.lastIndex < source.length) {
|
||||
const match = TOKEN_PATTERN.exec(source);
|
||||
if (match === null) {
|
||||
throw new ExpressionSyntaxError("unexpected character");
|
||||
}
|
||||
const token = tokenFromMatch(match);
|
||||
if (token !== undefined) {
|
||||
tokens.push(token);
|
||||
}
|
||||
}
|
||||
tokens.push({ kind: "end" });
|
||||
return tokens;
|
||||
}
|
||||
|
||||
function tokenFromMatch(match: RegExpExecArray): Token | undefined {
|
||||
const [
|
||||
raw,
|
||||
word,
|
||||
numberLiteral,
|
||||
stringLiteral,
|
||||
identifier,
|
||||
operator,
|
||||
dot,
|
||||
left,
|
||||
right,
|
||||
arrayLeft,
|
||||
arrayRight,
|
||||
objectLeft,
|
||||
objectRight,
|
||||
comma,
|
||||
colon,
|
||||
other,
|
||||
] = match;
|
||||
if (other !== undefined) {
|
||||
throw new ExpressionSyntaxError(`unexpected token ${other}`);
|
||||
}
|
||||
if (word !== undefined) {
|
||||
let value: JsonValue = null;
|
||||
if (word === "true") {
|
||||
value = true;
|
||||
} else if (word === "false") {
|
||||
value = false;
|
||||
}
|
||||
return { kind: "literal", value };
|
||||
}
|
||||
if (numberLiteral !== undefined) {
|
||||
return { kind: "literal", value: Number(numberLiteral) };
|
||||
}
|
||||
if (stringLiteral !== undefined) {
|
||||
return { kind: "literal", value: parseStringLiteral(stringLiteral) };
|
||||
}
|
||||
if (identifier !== undefined) {
|
||||
return { kind: "identifier", value: identifier };
|
||||
}
|
||||
if (operator !== undefined && isOperator(operator)) {
|
||||
return { kind: "operator", value: operator };
|
||||
}
|
||||
if (dot !== undefined) {
|
||||
return { kind: "dot" };
|
||||
}
|
||||
if (left !== undefined) {
|
||||
return { kind: "left" };
|
||||
}
|
||||
if (right !== undefined) {
|
||||
return { kind: "right" };
|
||||
}
|
||||
if (arrayLeft !== undefined) {
|
||||
return { kind: "array-left" };
|
||||
}
|
||||
if (arrayRight !== undefined) {
|
||||
return { kind: "array-right" };
|
||||
}
|
||||
if (objectLeft !== undefined) {
|
||||
return { kind: "object-left" };
|
||||
}
|
||||
if (objectRight !== undefined) {
|
||||
return { kind: "object-right" };
|
||||
}
|
||||
if (comma !== undefined) {
|
||||
return { kind: "comma" };
|
||||
}
|
||||
if (colon !== undefined) {
|
||||
return { kind: "colon" };
|
||||
}
|
||||
if (raw.trim() === "") {
|
||||
return undefined;
|
||||
}
|
||||
throw new ExpressionSyntaxError("unexpected token");
|
||||
}
|
||||
|
||||
function parseStringLiteral(value: string): string {
|
||||
if (value.startsWith('"')) {
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
if (typeof parsed !== "string") {
|
||||
throw new ExpressionSyntaxError("invalid string literal");
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
return value.slice(1, -1).replace(/\\([\\'])/gu, "$1");
|
||||
}
|
||||
|
||||
function isOperator(value: string): value is Operator {
|
||||
return (
|
||||
value === "!" ||
|
||||
value === "==" ||
|
||||
value === "!=" ||
|
||||
value === "&&" ||
|
||||
value === "||" ||
|
||||
value === "??"
|
||||
);
|
||||
}
|
||||
|
||||
function unwrapExpression(source: string): string {
|
||||
const trimmed = source.trim();
|
||||
if (trimmed.startsWith("${{")) {
|
||||
if (!trimmed.endsWith("}}")) {
|
||||
throw new ExpressionSyntaxError("unterminated expression");
|
||||
}
|
||||
return trimmed.slice(3, -2).trim();
|
||||
}
|
||||
if (trimmed.startsWith("{{")) {
|
||||
if (!trimmed.endsWith("}}")) {
|
||||
throw new ExpressionSyntaxError("unterminated expression");
|
||||
}
|
||||
return trimmed.slice(2, -2).trim();
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function operatorPrecedence(operator: BinaryOperator): number {
|
||||
if (operator === "??") {
|
||||
return 1;
|
||||
}
|
||||
if (operator === "||") {
|
||||
return 2;
|
||||
}
|
||||
if (operator === "&&") {
|
||||
return 3;
|
||||
}
|
||||
return 4;
|
||||
}
|
||||
|
||||
function isTruthy(value: JsonValue): boolean {
|
||||
return value !== false && value !== null && value !== 0 && value !== "";
|
||||
}
|
||||
|
||||
function sameJsonValue(left: JsonValue, right: JsonValue): boolean {
|
||||
if (typeof left !== typeof right) {
|
||||
return false;
|
||||
}
|
||||
return JSON.stringify(left) === JSON.stringify(right);
|
||||
}
|
||||
|
||||
function formatInterpolatedValue(value: JsonValue): string {
|
||||
if (value === null) {
|
||||
return "";
|
||||
}
|
||||
return typeof value === "string" ? value : JSON.stringify(value);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
declare module "js-yaml" {
|
||||
export interface LoadOptions {
|
||||
readonly filename?: string;
|
||||
readonly json?: boolean;
|
||||
}
|
||||
|
||||
export function load(input: string, options?: LoadOptions): unknown;
|
||||
|
||||
const yaml: {
|
||||
readonly load: typeof load;
|
||||
};
|
||||
export default yaml;
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import AjvImport, { type ErrorObject, type ValidateFunction } from "ajv";
|
||||
import { z } from "zod";
|
||||
import { isJsonObject, isJsonValue, type JsonSchema, type JsonValue } from "./expression.js";
|
||||
|
||||
interface AjvInstance {
|
||||
compile(schema: JsonSchema): ValidateFunction;
|
||||
}
|
||||
|
||||
type AjvConstructor = new (options?: {
|
||||
readonly allErrors?: boolean;
|
||||
readonly strict?: boolean;
|
||||
}) => AjvInstance;
|
||||
|
||||
function resolveAjvConstructor(): AjvConstructor {
|
||||
const mod: unknown = AjvImport;
|
||||
if (typeof mod === "function") {
|
||||
return mod as unknown as AjvConstructor;
|
||||
}
|
||||
if (typeof mod === "object" && mod !== null && "default" in mod) {
|
||||
const inner = (mod as { readonly default: unknown }).default;
|
||||
if (typeof inner === "function") {
|
||||
return inner as unknown as AjvConstructor;
|
||||
}
|
||||
}
|
||||
throw new Error("unable to resolve Ajv constructor");
|
||||
}
|
||||
|
||||
const AjvCtor = resolveAjvConstructor();
|
||||
|
||||
export interface CompiledJsonSchema {
|
||||
readonly validate: ValidateFunction;
|
||||
readonly schema: JsonSchema;
|
||||
}
|
||||
|
||||
export function normalizeJsonSchema(schema: JsonSchema): JsonSchema {
|
||||
const cloned = structuredClone(schema) as Record<string, unknown>;
|
||||
delete cloned["$schema"];
|
||||
if (!isJsonObject(cloned)) {
|
||||
throw new Error("JSON Schema must be a plain JSON object");
|
||||
}
|
||||
return cloned;
|
||||
}
|
||||
|
||||
export function zodToJsonSchema(schema: z.ZodType): JsonSchema {
|
||||
const raw = z.toJSONSchema(schema, { target: "draft-7" }) as Record<string, unknown>;
|
||||
delete raw["$schema"];
|
||||
if (!isJsonObject(raw)) {
|
||||
throw new Error("compiled Zod schema is not a plain JSON object");
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
export function isZodSchema(value: unknown): value is z.ZodType {
|
||||
return value instanceof z.ZodType;
|
||||
}
|
||||
|
||||
export function compileJsonSchema(schema: JsonSchema): CompiledJsonSchema {
|
||||
const normalized = normalizeJsonSchema(schema);
|
||||
const ajv = new AjvCtor({ allErrors: true, strict: true });
|
||||
return {
|
||||
schema: normalized,
|
||||
validate: ajv.compile(normalized),
|
||||
};
|
||||
}
|
||||
|
||||
export function validateAgainstSchema(
|
||||
schema: JsonSchema | z.ZodType,
|
||||
value: unknown,
|
||||
prefix = "value",
|
||||
): { readonly ok: true } | { readonly ok: false; readonly errors: readonly string[] } {
|
||||
if (isZodSchema(schema)) {
|
||||
const parsed = schema.safeParse(value);
|
||||
if (parsed.success) {
|
||||
return { ok: true };
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
errors: parsed.error.issues.map((issue) => {
|
||||
const path = issue.path.length === 0 ? prefix : `${prefix}.${issue.path.join(".")}`;
|
||||
return `${path} ${issue.message}`;
|
||||
}),
|
||||
};
|
||||
}
|
||||
const compiled = compileJsonSchema(schema);
|
||||
if (compiled.validate(value)) {
|
||||
return { ok: true };
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
errors: formatJsonSchemaErrors(compiled.validate.errors, prefix),
|
||||
};
|
||||
}
|
||||
|
||||
export function formatJsonSchemaErrors(
|
||||
errors: readonly ErrorObject[] | null | undefined,
|
||||
prefix = "output",
|
||||
): string[] {
|
||||
return (errors ?? []).map((error) => {
|
||||
const path = error.instancePath === "" ? prefix : `${prefix}${error.instancePath}`;
|
||||
return `${path} ${error.message ?? "is invalid"}`;
|
||||
});
|
||||
}
|
||||
|
||||
export function finiteSchemaChoices(
|
||||
schema: JsonSchema,
|
||||
path: readonly string[],
|
||||
): readonly JsonValue[] | undefined {
|
||||
const node = resolveSchemaAtPath(schema, path, schema, new Set());
|
||||
if (node === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
return finiteChoices(node, schema, new Set());
|
||||
}
|
||||
|
||||
function resolveSchemaAtPath(
|
||||
schema: unknown,
|
||||
path: readonly string[],
|
||||
root: unknown,
|
||||
seen: Set<unknown>,
|
||||
): unknown {
|
||||
const resolved = resolveSchema(schema, root, seen);
|
||||
if (resolved === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (path.length === 0) {
|
||||
return resolved;
|
||||
}
|
||||
if (!isRecord(resolved)) {
|
||||
return undefined;
|
||||
}
|
||||
const properties = resolved["properties"];
|
||||
if (!isRecord(properties)) {
|
||||
return undefined;
|
||||
}
|
||||
return resolveSchemaAtPath(properties[path[0]!], path.slice(1), root, seen);
|
||||
}
|
||||
|
||||
function finiteChoices(
|
||||
schema: unknown,
|
||||
root: unknown,
|
||||
seen: Set<unknown>,
|
||||
): readonly JsonValue[] | undefined {
|
||||
const resolved = resolveSchema(schema, root, seen);
|
||||
if (!isRecord(resolved)) {
|
||||
return undefined;
|
||||
}
|
||||
if (Array.isArray(resolved["enum"]) && resolved["enum"].length > 0) {
|
||||
return resolved["enum"].filter(isJsonValue);
|
||||
}
|
||||
if (isJsonValue(resolved["const"])) {
|
||||
return [resolved["const"]];
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function resolveSchema(schema: unknown, root: unknown, seen: Set<unknown>): unknown {
|
||||
if (!isRecord(schema)) {
|
||||
return undefined;
|
||||
}
|
||||
if (typeof schema["$ref"] !== "string") {
|
||||
return schema;
|
||||
}
|
||||
if (seen.has(schema)) {
|
||||
return undefined;
|
||||
}
|
||||
seen.add(schema);
|
||||
const target = resolveLocalReference(root, schema["$ref"]);
|
||||
return target === undefined ? undefined : resolveSchema(target, root, seen);
|
||||
}
|
||||
|
||||
function resolveLocalReference(root: unknown, reference: string): unknown {
|
||||
if (!reference.startsWith("#/")) {
|
||||
return undefined;
|
||||
}
|
||||
let current: unknown = root;
|
||||
for (const segment of reference.slice(2).split("/")) {
|
||||
if (!isRecord(current)) {
|
||||
return undefined;
|
||||
}
|
||||
current = current[segment.replaceAll("~1", "/").replaceAll("~0", "~")];
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import type { StepIR, TransitionTargetIR, WorkflowValidationIssue } from "../ir.js";
|
||||
|
||||
/**
|
||||
* Validate transition targets and bounded-cycle safety:
|
||||
* 1. Every `{ next }` target must refer to an existing state.
|
||||
* 2. Every cycle in the state graph must contain at least one state that sets
|
||||
* `maxLoops >= 1` AND declares `on.max_loops_exceeded`.
|
||||
* (Graph-theoretically equivalent to: removing all loop-guarded states yields a DAG.)
|
||||
* 3. A loop-guarded state's `max_loops_exceeded` transition cannot target itself.
|
||||
*/
|
||||
export function validateStateGraph(
|
||||
states: Readonly<Record<string, StepIR>>,
|
||||
): WorkflowValidationIssue[] {
|
||||
const issues: WorkflowValidationIssue[] = [];
|
||||
const stateIds = new Set(Object.keys(states));
|
||||
|
||||
for (const [stateId, step] of Object.entries(states)) {
|
||||
for (const [outcome, target] of Object.entries(step.on)) {
|
||||
if ("next" in target && !stateIds.has(target.next)) {
|
||||
issues.push({
|
||||
path: `states.${stateId}.on.${outcome}`,
|
||||
message: `transition target "${target.next}" does not exist in states`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const exceededTarget = step.on["max_loops_exceeded"];
|
||||
if (
|
||||
exceededTarget !== undefined &&
|
||||
"next" in exceededTarget &&
|
||||
exceededTarget.next === stateId
|
||||
) {
|
||||
issues.push({
|
||||
path: `states.${stateId}.on.max_loops_exceeded`,
|
||||
message: `max_loops_exceeded transition on "${stateId}" cannot target itself`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// States that guard any cycle passing through them.
|
||||
const guarded = new Set<string>();
|
||||
for (const [stateId, step] of Object.entries(states)) {
|
||||
if (
|
||||
step.maxLoops !== undefined &&
|
||||
step.maxLoops >= 1 &&
|
||||
step.on["max_loops_exceeded"] !== undefined
|
||||
) {
|
||||
guarded.add(stateId);
|
||||
}
|
||||
}
|
||||
|
||||
// Check whether the subgraph induced by unguarded states contains any cycle.
|
||||
const unguardedCycle = findCycle(states, stateIds, (id) => !guarded.has(id));
|
||||
if (unguardedCycle !== undefined) {
|
||||
issues.push({
|
||||
path: `states.${unguardedCycle[0]}`,
|
||||
message:
|
||||
`unguarded cycle detected (${unguardedCycle.join(" -> ")}): ` +
|
||||
"at least one state in every cycle must declare both maxLoops and on.max_loops_exceeded",
|
||||
});
|
||||
}
|
||||
|
||||
return issues;
|
||||
}
|
||||
|
||||
export type TransitionResolution =
|
||||
| { readonly kind: "next"; readonly stateId: string }
|
||||
| {
|
||||
readonly kind: "terminal";
|
||||
readonly target: Extract<TransitionTargetIR, { readonly terminal: string }>;
|
||||
}
|
||||
| { readonly kind: "unhandled"; readonly outcome: string };
|
||||
|
||||
/**
|
||||
* Pure transition resolver: given a completed step's outcome, look up `on[outcome] ?? on["*"]`.
|
||||
* If the target state would exceed its `maxLoops` budget, route through `target.on.max_loops_exceeded`.
|
||||
*/
|
||||
export function resolveTransition(
|
||||
states: Readonly<Record<string, StepIR>>,
|
||||
currentStateId: string,
|
||||
outcome: string,
|
||||
loopCounts: Readonly<Record<string, number>>,
|
||||
): TransitionResolution {
|
||||
const currentStep = states[currentStateId];
|
||||
if (currentStep === undefined) {
|
||||
return { kind: "unhandled", outcome };
|
||||
}
|
||||
|
||||
const target = currentStep.on[outcome] ?? currentStep.on["*"];
|
||||
if (target === undefined) {
|
||||
return { kind: "unhandled", outcome };
|
||||
}
|
||||
|
||||
return followTarget(states, target, loopCounts, new Set());
|
||||
}
|
||||
|
||||
function followTarget(
|
||||
states: Readonly<Record<string, StepIR>>,
|
||||
target: TransitionTargetIR,
|
||||
loopCounts: Readonly<Record<string, number>>,
|
||||
visited: Set<string>,
|
||||
): TransitionResolution {
|
||||
if ("terminal" in target) {
|
||||
return { kind: "terminal", target };
|
||||
}
|
||||
const nextStep = states[target.next];
|
||||
if (nextStep === undefined) {
|
||||
return { kind: "unhandled", outcome: target.next };
|
||||
}
|
||||
|
||||
const executedCount = loopCounts[nextStep.id] ?? 0;
|
||||
if (nextStep.maxLoops !== undefined && executedCount >= nextStep.maxLoops) {
|
||||
const exceededTarget = nextStep.on["max_loops_exceeded"];
|
||||
if (exceededTarget === undefined || visited.has(nextStep.id)) {
|
||||
return { kind: "unhandled", outcome: "max_loops_exceeded" };
|
||||
}
|
||||
visited.add(nextStep.id);
|
||||
return followTarget(states, exceededTarget, loopCounts, visited);
|
||||
}
|
||||
|
||||
return { kind: "next", stateId: nextStep.id };
|
||||
}
|
||||
|
||||
function findCycle(
|
||||
states: Readonly<Record<string, StepIR>>,
|
||||
stateIds: ReadonlySet<string>,
|
||||
include: (stateId: string) => boolean,
|
||||
): string[] | undefined {
|
||||
// 0 = unvisited, 1 = visiting (on stack), 2 = visited
|
||||
const color = new Map<string, number>();
|
||||
const stack: string[] = [];
|
||||
|
||||
const dfs = (nodeId: string): string[] | undefined => {
|
||||
color.set(nodeId, 1);
|
||||
stack.push(nodeId);
|
||||
|
||||
const step = states[nodeId];
|
||||
if (step !== undefined) {
|
||||
for (const target of Object.values(step.on)) {
|
||||
if (!("next" in target)) {
|
||||
continue;
|
||||
}
|
||||
const nextId = target.next;
|
||||
if (!stateIds.has(nextId) || !include(nextId)) {
|
||||
continue;
|
||||
}
|
||||
const nextColor = color.get(nextId) ?? 0;
|
||||
if (nextColor === 1) {
|
||||
const cycleStart = stack.indexOf(nextId);
|
||||
return [...stack.slice(cycleStart), nextId];
|
||||
}
|
||||
if (nextColor === 0) {
|
||||
const found = dfs(nextId);
|
||||
if (found !== undefined) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stack.pop();
|
||||
color.set(nodeId, 2);
|
||||
return undefined;
|
||||
};
|
||||
|
||||
for (const stateId of Object.keys(states)) {
|
||||
if (!include(stateId)) {
|
||||
continue;
|
||||
}
|
||||
if ((color.get(stateId) ?? 0) === 0) {
|
||||
const found = dfs(stateId);
|
||||
if (found !== undefined) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
@@ -0,0 +1,691 @@
|
||||
import { z } from "zod";
|
||||
import { parseDurationMs, type DurationInput } from "./internal/duration.js";
|
||||
import {
|
||||
collectExprPaths,
|
||||
isJsonObject,
|
||||
isJsonValue,
|
||||
type BinaryOperator,
|
||||
type ExprNode,
|
||||
type ExprPath,
|
||||
type JsonObject,
|
||||
type JsonPrimitive,
|
||||
type JsonSchema,
|
||||
type JsonValue,
|
||||
} from "./internal/expression.js";
|
||||
import { compileJsonSchema } from "./internal/json-schema.js";
|
||||
import { validateStateGraph } from "./internal/machine.js";
|
||||
|
||||
export type {
|
||||
BinaryOperator,
|
||||
DurationInput,
|
||||
ExprNode,
|
||||
ExprPath,
|
||||
JsonObject,
|
||||
JsonPrimitive,
|
||||
JsonSchema,
|
||||
JsonValue,
|
||||
};
|
||||
export { parseDurationMs };
|
||||
|
||||
export type TerminalStatus = "done" | "failed" | "cancelled";
|
||||
export type SubjectConflictPolicy = "signal" | "queue" | "ignore" | "cancel_previous";
|
||||
|
||||
export type TransitionTargetIR =
|
||||
| { readonly next: string }
|
||||
| {
|
||||
readonly terminal: TerminalStatus;
|
||||
readonly reason?: string;
|
||||
readonly outputs?: Readonly<Record<string, ExprNode>>;
|
||||
};
|
||||
|
||||
export interface TriggerRecurrenceIR {
|
||||
readonly start: string;
|
||||
readonly rule: string;
|
||||
readonly timezone?: string;
|
||||
}
|
||||
|
||||
export interface TriggerBindingIR {
|
||||
readonly connection?: string;
|
||||
readonly filters?: JsonObject;
|
||||
readonly recurrence?: TriggerRecurrenceIR;
|
||||
}
|
||||
|
||||
export interface InputSpecIR {
|
||||
readonly type: "string" | "number" | "boolean";
|
||||
readonly required?: boolean;
|
||||
readonly default?: JsonPrimitive;
|
||||
readonly choices?: readonly JsonPrimitive[];
|
||||
}
|
||||
|
||||
export type WorktreeTargetIR =
|
||||
| { readonly mode: "branch-off"; readonly newBranch: ExprNode; readonly base?: string }
|
||||
| { readonly mode: "checkout-branch"; readonly branch: ExprNode }
|
||||
| { readonly mode: "checkout-pr"; readonly prNumber: ExprNode };
|
||||
|
||||
export interface AgentTargetIR {
|
||||
readonly daemon?: string;
|
||||
readonly cwd?: string;
|
||||
readonly environment?: string;
|
||||
readonly worktree?: WorktreeTargetIR;
|
||||
}
|
||||
|
||||
export interface AgentSpecIR {
|
||||
readonly provider: string;
|
||||
readonly model?: string;
|
||||
readonly mode?: string;
|
||||
readonly thinkingOptionId?: string;
|
||||
readonly options?: JsonObject;
|
||||
}
|
||||
|
||||
export interface ContinuationIR {
|
||||
readonly mode: string;
|
||||
}
|
||||
|
||||
export interface AuthGrantIR {
|
||||
readonly connection?: string;
|
||||
readonly [key: string]: JsonValue | undefined;
|
||||
}
|
||||
|
||||
export interface AllowOutputIR {
|
||||
readonly max?: number;
|
||||
readonly required?: boolean;
|
||||
}
|
||||
|
||||
export interface GateChoiceIR {
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
readonly description?: string;
|
||||
}
|
||||
|
||||
export interface StepBaseIR {
|
||||
readonly id: string;
|
||||
readonly when?: ExprNode;
|
||||
readonly maxLoops?: number;
|
||||
readonly on: Readonly<Record<string, TransitionTargetIR>>;
|
||||
}
|
||||
|
||||
export interface AgentStepIR extends StepBaseIR {
|
||||
readonly kind: "agent";
|
||||
readonly target?: AgentTargetIR;
|
||||
readonly agent?: AgentSpecIR;
|
||||
readonly continuation?: ContinuationIR;
|
||||
readonly title?: ExprNode;
|
||||
readonly prompt: ExprNode;
|
||||
readonly maxRuntimeMs?: number;
|
||||
readonly idleTimeoutMs?: number;
|
||||
readonly startupTimeoutMs?: number;
|
||||
readonly autoArchive?: boolean;
|
||||
readonly background?: boolean;
|
||||
readonly env?: Readonly<Record<string, ExprNode>>;
|
||||
readonly auth?: Readonly<Record<string, AuthGrantIR>>;
|
||||
readonly tools?: Readonly<Record<string, JsonValue>>;
|
||||
readonly outputSchema?: JsonSchema;
|
||||
readonly allowOutputs?: Readonly<Record<string, AllowOutputIR>>;
|
||||
}
|
||||
|
||||
export interface IntegrationStepIR extends StepBaseIR {
|
||||
readonly kind: "integration";
|
||||
readonly integration: string;
|
||||
readonly step: string;
|
||||
readonly input: Readonly<Record<string, ExprNode>>;
|
||||
readonly auth?: Readonly<Record<string, AuthGrantIR>>;
|
||||
readonly timeoutMs?: number;
|
||||
}
|
||||
|
||||
export interface WaitWorkflowStepIR extends StepBaseIR {
|
||||
readonly kind: "wait_workflow";
|
||||
readonly workflow: string;
|
||||
readonly outputKey: ExprNode;
|
||||
readonly dispatchIfMissing?: boolean;
|
||||
readonly inputs?: Readonly<Record<string, ExprNode>>;
|
||||
readonly timeoutMs?: number;
|
||||
}
|
||||
|
||||
export interface GateStepIR extends StepBaseIR {
|
||||
readonly kind: "gate";
|
||||
readonly title: ExprNode;
|
||||
readonly summary?: ExprNode;
|
||||
readonly recommended?: string;
|
||||
readonly choices: readonly GateChoiceIR[];
|
||||
readonly timeoutMs?: number;
|
||||
}
|
||||
|
||||
export interface SleepStepIR extends StepBaseIR {
|
||||
readonly kind: "sleep";
|
||||
readonly durationMs?: number;
|
||||
readonly until?: ExprNode;
|
||||
}
|
||||
|
||||
export type StepIR =
|
||||
| AgentStepIR
|
||||
| IntegrationStepIR
|
||||
| WaitWorkflowStepIR
|
||||
| GateStepIR
|
||||
| SleepStepIR;
|
||||
|
||||
export interface WorkflowSubjectIR {
|
||||
readonly key: ExprNode;
|
||||
readonly onConflict: SubjectConflictPolicy;
|
||||
}
|
||||
|
||||
export interface WorkflowPublishIR {
|
||||
readonly key: ExprNode;
|
||||
readonly schema?: JsonSchema;
|
||||
readonly payload: Readonly<Record<string, ExprNode>> | ExprNode;
|
||||
}
|
||||
|
||||
export interface WorkflowIR {
|
||||
readonly version: 1;
|
||||
readonly id: string;
|
||||
readonly enabled: boolean;
|
||||
readonly on: Readonly<Record<string, TriggerBindingIR>>;
|
||||
readonly intake?: JsonObject;
|
||||
readonly inputs?: Readonly<Record<string, InputSpecIR>>;
|
||||
readonly values?: Readonly<Record<string, ExprNode>>;
|
||||
readonly subject?: WorkflowSubjectIR;
|
||||
readonly maxRuntimeMs?: number;
|
||||
readonly initial: string;
|
||||
readonly states: Readonly<Record<string, StepIR>>;
|
||||
readonly publish?: WorkflowPublishIR;
|
||||
}
|
||||
|
||||
export interface WorkflowValidationIssue {
|
||||
readonly path: string;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
export class WorkflowValidationError extends Error {
|
||||
constructor(readonly issues: readonly WorkflowValidationIssue[]) {
|
||||
super(
|
||||
`Invalid workflow IR:\n${issues.map((issue) => `- ${issue.path}: ${issue.message}`).join("\n")}`,
|
||||
);
|
||||
this.name = "WorkflowValidationError";
|
||||
}
|
||||
}
|
||||
|
||||
const JsonValueSchema: z.ZodType<JsonValue> = z.custom<JsonValue>(isJsonValue, {
|
||||
message: "expected a valid JSON value",
|
||||
});
|
||||
|
||||
const JsonObjectSchema: z.ZodType<JsonObject> = z.custom<JsonObject>(isJsonObject, {
|
||||
message: "expected a plain JSON object",
|
||||
});
|
||||
|
||||
const ExprPathSchema: z.ZodType<ExprPath> = z.union([
|
||||
z.object({ namespace: z.literal("event"), path: z.array(z.string().min(1)) }).strict(),
|
||||
z.object({ namespace: z.literal("inputs"), name: z.string().min(1) }).strict(),
|
||||
z.object({ namespace: z.literal("subject"), field: z.literal("key") }).strict(),
|
||||
z
|
||||
.object({
|
||||
namespace: z.literal("subject"),
|
||||
field: z.literal("data"),
|
||||
path: z.array(z.string().min(1)).min(1),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
namespace: z.literal("steps"),
|
||||
stepId: z.string().min(1),
|
||||
field: z.enum(["outcome", "attempts"]),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
namespace: z.literal("steps"),
|
||||
stepId: z.string().min(1),
|
||||
field: z.literal("outputs"),
|
||||
path: z.array(z.string().min(1)).min(1),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
namespace: z.literal("gate"),
|
||||
field: z.enum(["choice", "note", "actor"]),
|
||||
})
|
||||
.strict(),
|
||||
z.object({ namespace: z.literal("execution"), field: z.literal("id") }).strict(),
|
||||
z.object({ namespace: z.literal("paseo"), field: z.literal("prompt") }).strict(),
|
||||
z.object({ namespace: z.literal("values"), name: z.string().min(1) }).strict(),
|
||||
]);
|
||||
|
||||
export const ExprNodeSchema: z.ZodType<ExprNode> = z.lazy(() =>
|
||||
z.union([
|
||||
z.object({ kind: z.literal("literal"), value: JsonValueSchema }).strict(),
|
||||
z.object({ kind: z.literal("path"), path: ExprPathSchema }).strict(),
|
||||
z.object({ kind: z.literal("not"), value: ExprNodeSchema }).strict(),
|
||||
z
|
||||
.object({
|
||||
kind: z.literal("binary"),
|
||||
operator: z.enum(["==", "!=", "&&", "||", "??"]),
|
||||
left: ExprNodeSchema,
|
||||
right: ExprNodeSchema,
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
kind: z.literal("template"),
|
||||
parts: z.array(z.union([z.string(), ExprNodeSchema])),
|
||||
})
|
||||
.strict(),
|
||||
]),
|
||||
);
|
||||
|
||||
const TransitionTargetSchema: z.ZodType<TransitionTargetIR> = z.union([
|
||||
z.object({ next: z.string().min(1) }).strict(),
|
||||
z
|
||||
.object({
|
||||
terminal: z.enum(["done", "failed", "cancelled"]),
|
||||
reason: z.string().min(1).optional(),
|
||||
outputs: z.record(z.string().min(1), ExprNodeSchema).optional(),
|
||||
})
|
||||
.strict(),
|
||||
]);
|
||||
|
||||
const TriggerRecurrenceSchema = z
|
||||
.object({
|
||||
start: z.string().min(1),
|
||||
rule: z.string().min(1),
|
||||
timezone: z.string().min(1).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const TriggerBindingSchema: z.ZodType<TriggerBindingIR> = z
|
||||
.object({
|
||||
connection: z.string().min(1).optional(),
|
||||
filters: JsonObjectSchema.optional(),
|
||||
recurrence: TriggerRecurrenceSchema.optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const InputValueSchema = z.union([z.string(), z.number().finite(), z.boolean(), z.null()]);
|
||||
|
||||
const InputSpecSchema: z.ZodType<InputSpecIR> = z
|
||||
.object({
|
||||
type: z.enum(["string", "number", "boolean"]),
|
||||
required: z.boolean().optional(),
|
||||
default: InputValueSchema.optional(),
|
||||
choices: z.array(InputValueSchema).min(1).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const WorktreeTargetSchema: z.ZodType<WorktreeTargetIR> = z.discriminatedUnion("mode", [
|
||||
z
|
||||
.object({
|
||||
mode: z.literal("branch-off"),
|
||||
newBranch: ExprNodeSchema,
|
||||
base: z.string().min(1).optional(),
|
||||
})
|
||||
.strict(),
|
||||
z.object({ mode: z.literal("checkout-branch"), branch: ExprNodeSchema }).strict(),
|
||||
z.object({ mode: z.literal("checkout-pr"), prNumber: ExprNodeSchema }).strict(),
|
||||
]);
|
||||
|
||||
const AgentTargetSchema: z.ZodType<AgentTargetIR> = z
|
||||
.object({
|
||||
daemon: z.string().min(1).optional(),
|
||||
cwd: z.string().min(1).optional(),
|
||||
environment: z.string().min(1).optional(),
|
||||
worktree: WorktreeTargetSchema.optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const AgentSpecSchema: z.ZodType<AgentSpecIR> = z
|
||||
.object({
|
||||
provider: z.string().min(1),
|
||||
model: z.string().min(1).optional(),
|
||||
mode: z.string().min(1).optional(),
|
||||
thinkingOptionId: z.string().min(1).optional(),
|
||||
options: JsonObjectSchema.optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const ContinuationSchema: z.ZodType<ContinuationIR> = z
|
||||
.object({ mode: z.string().min(1) })
|
||||
.strict();
|
||||
|
||||
const AuthGrantSchema: z.ZodType<AuthGrantIR> = z.custom<AuthGrantIR>(
|
||||
(value) => isJsonObject(value),
|
||||
{ message: "auth grant must be a plain JSON object" },
|
||||
);
|
||||
|
||||
const AllowOutputSchema: z.ZodType<AllowOutputIR> = z
|
||||
.object({
|
||||
max: z.number().int().positive().optional(),
|
||||
required: z.boolean().optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const GateChoiceSchema: z.ZodType<GateChoiceIR> = z
|
||||
.object({
|
||||
id: z.string().min(1),
|
||||
label: z.string().min(1),
|
||||
description: z.string().optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const StepBaseFields = {
|
||||
id: z.string().min(1),
|
||||
when: ExprNodeSchema.optional(),
|
||||
maxLoops: z.number().int().positive().optional(),
|
||||
on: z.record(z.string().min(1), TransitionTargetSchema),
|
||||
};
|
||||
|
||||
const AgentStepSchema = z
|
||||
.object({
|
||||
...StepBaseFields,
|
||||
kind: z.literal("agent"),
|
||||
target: AgentTargetSchema.optional(),
|
||||
agent: AgentSpecSchema.optional(),
|
||||
continuation: ContinuationSchema.optional(),
|
||||
title: ExprNodeSchema.optional(),
|
||||
prompt: ExprNodeSchema,
|
||||
maxRuntimeMs: z.number().int().positive().optional(),
|
||||
idleTimeoutMs: z.number().int().positive().optional(),
|
||||
startupTimeoutMs: z.number().int().positive().optional(),
|
||||
autoArchive: z.boolean().optional(),
|
||||
background: z.boolean().optional(),
|
||||
env: z.record(z.string().min(1), ExprNodeSchema).optional(),
|
||||
auth: z.record(z.string().min(1), AuthGrantSchema).optional(),
|
||||
tools: z.record(z.string().min(1), JsonValueSchema).optional(),
|
||||
outputSchema: JsonObjectSchema.optional(),
|
||||
allowOutputs: z.record(z.string().min(1), AllowOutputSchema).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const IntegrationStepSchema = z
|
||||
.object({
|
||||
...StepBaseFields,
|
||||
kind: z.literal("integration"),
|
||||
integration: z.string().min(1),
|
||||
step: z.string().min(1),
|
||||
input: z.record(z.string().min(1), ExprNodeSchema),
|
||||
auth: z.record(z.string().min(1), AuthGrantSchema).optional(),
|
||||
timeoutMs: z.number().int().positive().optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const WaitWorkflowStepSchema = z
|
||||
.object({
|
||||
...StepBaseFields,
|
||||
kind: z.literal("wait_workflow"),
|
||||
workflow: z.string().min(1),
|
||||
outputKey: ExprNodeSchema,
|
||||
dispatchIfMissing: z.boolean().optional(),
|
||||
inputs: z.record(z.string().min(1), ExprNodeSchema).optional(),
|
||||
timeoutMs: z.number().int().positive().optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const GateStepSchema = z
|
||||
.object({
|
||||
...StepBaseFields,
|
||||
kind: z.literal("gate"),
|
||||
title: ExprNodeSchema,
|
||||
summary: ExprNodeSchema.optional(),
|
||||
recommended: z.string().min(1).optional(),
|
||||
choices: z.array(GateChoiceSchema).min(1),
|
||||
timeoutMs: z.number().int().positive().optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const SleepStepSchema = z
|
||||
.object({
|
||||
...StepBaseFields,
|
||||
kind: z.literal("sleep"),
|
||||
durationMs: z.number().int().positive().optional(),
|
||||
until: ExprNodeSchema.optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const StepIRSchema: z.ZodType<StepIR> = z.discriminatedUnion("kind", [
|
||||
AgentStepSchema,
|
||||
IntegrationStepSchema,
|
||||
WaitWorkflowStepSchema,
|
||||
GateStepSchema,
|
||||
SleepStepSchema,
|
||||
]);
|
||||
|
||||
export const WorkflowIRSchema: z.ZodType<WorkflowIR> = z
|
||||
.object({
|
||||
version: z.literal(1),
|
||||
id: z.string().min(1),
|
||||
enabled: z.boolean(),
|
||||
on: z.record(z.string().min(1), TriggerBindingSchema),
|
||||
intake: JsonObjectSchema.optional(),
|
||||
inputs: z.record(z.string().min(1), InputSpecSchema).optional(),
|
||||
values: z.record(z.string().min(1), ExprNodeSchema).optional(),
|
||||
subject: z
|
||||
.object({
|
||||
key: ExprNodeSchema,
|
||||
onConflict: z.enum(["signal", "queue", "ignore", "cancel_previous"]),
|
||||
})
|
||||
.strict()
|
||||
.optional(),
|
||||
maxRuntimeMs: z.number().int().positive().optional(),
|
||||
initial: z.string().min(1),
|
||||
states: z.record(z.string().min(1), StepIRSchema),
|
||||
publish: z
|
||||
.object({
|
||||
key: ExprNodeSchema,
|
||||
schema: JsonObjectSchema.optional(),
|
||||
payload: z.union([ExprNodeSchema, z.record(z.string().min(1), ExprNodeSchema)]),
|
||||
})
|
||||
.strict()
|
||||
.optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
/**
|
||||
* Validate a `WorkflowIR` structurally and statically:
|
||||
* - Schema shape (pure JSON, zero closures)
|
||||
* - Initial state and all transition targets exist (or valid terminals)
|
||||
* - Every cycle contains a state with `maxLoops` and an `on.max_loops_exceeded` transition
|
||||
* - All `steps.<id>.*` expression references point to existing states
|
||||
* - Gate choices are unique and `recommended` matches a declared choice
|
||||
* - Sleep steps declare either `durationMs` or `until` (not neither, not both)
|
||||
* - Output and publish JSON Schemas compile under strict AJV
|
||||
*/
|
||||
function validateStepDefinition(
|
||||
key: string,
|
||||
step: StepIR,
|
||||
issues: WorkflowValidationIssue[],
|
||||
): void {
|
||||
if (step.id !== key) {
|
||||
issues.push({
|
||||
path: `states.${key}.id`,
|
||||
message: `step id "${step.id}" must match state key "${key}"`,
|
||||
});
|
||||
}
|
||||
|
||||
if (step.kind === "gate") {
|
||||
const seenChoiceIds = new Set<string>();
|
||||
for (const choice of step.choices) {
|
||||
if (seenChoiceIds.has(choice.id)) {
|
||||
issues.push({
|
||||
path: `states.${key}.choices`,
|
||||
message: `duplicate gate choice id "${choice.id}"`,
|
||||
});
|
||||
}
|
||||
seenChoiceIds.add(choice.id);
|
||||
}
|
||||
if (step.recommended !== undefined && !seenChoiceIds.has(step.recommended)) {
|
||||
issues.push({
|
||||
path: `states.${key}.recommended`,
|
||||
message: `recommended choice "${step.recommended}" is not in choices`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (step.kind === "sleep" && (step.durationMs !== undefined) === (step.until !== undefined)) {
|
||||
issues.push({
|
||||
path: `states.${key}`,
|
||||
message: "sleep step must specify exactly one of durationMs or until",
|
||||
});
|
||||
}
|
||||
|
||||
if (step.kind === "agent" && step.outputSchema !== undefined) {
|
||||
try {
|
||||
compileJsonSchema(step.outputSchema);
|
||||
} catch (error) {
|
||||
issues.push({
|
||||
path: `states.${key}.outputSchema`,
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function validateWorkflowIR(input: unknown): WorkflowIR {
|
||||
const parsed = WorkflowIRSchema.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
throw new WorkflowValidationError(
|
||||
parsed.error.issues.map((issue) => ({
|
||||
path: issue.path.length === 0 ? "$" : issue.path.join("."),
|
||||
message: issue.message,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
const ir = parsed.data;
|
||||
const issues: WorkflowValidationIssue[] = [];
|
||||
const stateIds = new Set(Object.keys(ir.states));
|
||||
|
||||
if (stateIds.size === 0) {
|
||||
issues.push({ path: "states", message: "workflow must declare at least one state" });
|
||||
}
|
||||
if (!stateIds.has(ir.initial)) {
|
||||
issues.push({
|
||||
path: "initial",
|
||||
message: `initial state "${ir.initial}" does not exist in states`,
|
||||
});
|
||||
}
|
||||
|
||||
for (const [key, step] of Object.entries(ir.states)) {
|
||||
validateStepDefinition(key, step, issues);
|
||||
}
|
||||
|
||||
if (ir.publish?.schema !== undefined) {
|
||||
try {
|
||||
compileJsonSchema(ir.publish.schema);
|
||||
} catch (error) {
|
||||
issues.push({
|
||||
path: "publish.schema",
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
issues.push(...validateStateGraph(ir.states));
|
||||
issues.push(...validateExpressionReferences(ir, stateIds));
|
||||
|
||||
if (issues.length > 0) {
|
||||
throw new WorkflowValidationError(issues);
|
||||
}
|
||||
|
||||
return ir;
|
||||
}
|
||||
|
||||
function validateStepExpressionReferences(
|
||||
prefix: string,
|
||||
step: StepIR,
|
||||
checkExpr: (expr: ExprNode | undefined, location: string) => void,
|
||||
): void {
|
||||
checkExpr(step.when, `${prefix}.when`);
|
||||
for (const [outcome, target] of Object.entries(step.on)) {
|
||||
if ("terminal" in target && target.outputs !== undefined) {
|
||||
for (const [outKey, outExpr] of Object.entries(target.outputs)) {
|
||||
checkExpr(outExpr, `${prefix}.on.${outcome}.outputs.${outKey}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
switch (step.kind) {
|
||||
case "agent":
|
||||
checkExpr(step.title, `${prefix}.title`);
|
||||
checkExpr(step.prompt, `${prefix}.prompt`);
|
||||
if (step.target?.worktree !== undefined) {
|
||||
const wt = step.target.worktree;
|
||||
if (wt.mode === "branch-off") {
|
||||
checkExpr(wt.newBranch, `${prefix}.target.worktree.newBranch`);
|
||||
} else if (wt.mode === "checkout-branch") {
|
||||
checkExpr(wt.branch, `${prefix}.target.worktree.branch`);
|
||||
} else {
|
||||
checkExpr(wt.prNumber, `${prefix}.target.worktree.prNumber`);
|
||||
}
|
||||
}
|
||||
if (step.env !== undefined) {
|
||||
for (const [envKey, envExpr] of Object.entries(step.env)) {
|
||||
checkExpr(envExpr, `${prefix}.env.${envKey}`);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case "integration":
|
||||
for (const [inputKey, inputExpr] of Object.entries(step.input)) {
|
||||
checkExpr(inputExpr, `${prefix}.input.${inputKey}`);
|
||||
}
|
||||
break;
|
||||
case "wait_workflow":
|
||||
checkExpr(step.outputKey, `${prefix}.outputKey`);
|
||||
if (step.inputs !== undefined) {
|
||||
for (const [inputKey, inputExpr] of Object.entries(step.inputs)) {
|
||||
checkExpr(inputExpr, `${prefix}.inputs.${inputKey}`);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case "gate":
|
||||
checkExpr(step.title, `${prefix}.title`);
|
||||
checkExpr(step.summary, `${prefix}.summary`);
|
||||
break;
|
||||
case "sleep":
|
||||
checkExpr(step.until, `${prefix}.until`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function validateExpressionReferences(
|
||||
ir: WorkflowIR,
|
||||
stateIds: ReadonlySet<string>,
|
||||
): WorkflowValidationIssue[] {
|
||||
const issues: WorkflowValidationIssue[] = [];
|
||||
const declaredValues = new Set(Object.keys(ir.values ?? {}));
|
||||
|
||||
const checkExpr = (expr: ExprNode | undefined, location: string): void => {
|
||||
if (expr === undefined) {
|
||||
return;
|
||||
}
|
||||
for (const refPath of collectExprPaths(expr)) {
|
||||
if (refPath.namespace === "steps" && !stateIds.has(refPath.stepId)) {
|
||||
issues.push({
|
||||
path: location,
|
||||
message: `expression references unknown step "${refPath.stepId}"`,
|
||||
});
|
||||
}
|
||||
if (refPath.namespace === "values" && !declaredValues.has(refPath.name)) {
|
||||
issues.push({
|
||||
path: location,
|
||||
message: `expression references undeclared value "${refPath.name}"`,
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
checkExpr(ir.subject?.key, "subject.key");
|
||||
for (const [name, valueExpr] of Object.entries(ir.values ?? {})) {
|
||||
checkExpr(valueExpr, `values.${name}`);
|
||||
}
|
||||
if (ir.publish !== undefined) {
|
||||
checkExpr(ir.publish.key, "publish.key");
|
||||
if ("kind" in ir.publish.payload) {
|
||||
checkExpr(ir.publish.payload as ExprNode, "publish.payload");
|
||||
} else {
|
||||
for (const [field, fieldExpr] of Object.entries(ir.publish.payload)) {
|
||||
checkExpr(fieldExpr, `publish.payload.${field}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const [stateId, step] of Object.entries(ir.states)) {
|
||||
validateStepExpressionReferences(`states.${stateId}`, step, checkExpr);
|
||||
}
|
||||
|
||||
return issues;
|
||||
}
|
||||
@@ -0,0 +1,713 @@
|
||||
import type {
|
||||
AcceptWorkflowRunInput,
|
||||
AcceptWorkflowRunResult,
|
||||
ActiveAuthLease,
|
||||
AgentRunner,
|
||||
AgentStepRequest,
|
||||
AgentStepStartResult,
|
||||
BeginStepAttemptInput,
|
||||
Clock,
|
||||
CompleteStepAttemptInput,
|
||||
GateResolution,
|
||||
GateSink,
|
||||
IntegrationConnectionRecord,
|
||||
IntegrationConnections,
|
||||
IntegrationStorage,
|
||||
IntegrationStorageEntry,
|
||||
JsonValue,
|
||||
ListOpenGatesFilter,
|
||||
ListRunsFilter,
|
||||
OpenGateInput,
|
||||
PublishedWorkflowOutput,
|
||||
StepAttemptRecord,
|
||||
StepWaitSpec,
|
||||
SuspendedWaitRecord,
|
||||
TransitionRunInput,
|
||||
WorkflowGateRecord,
|
||||
WorkflowRunSnapshot,
|
||||
WorkflowStore,
|
||||
} from "./index.js";
|
||||
|
||||
export interface FakeClock extends Clock {
|
||||
advance(ms: number): Date;
|
||||
set(date: Date | string | number): Date;
|
||||
}
|
||||
|
||||
/** Deterministic clock for tests and local simulation. */
|
||||
export function createFakeClock(
|
||||
initial: Date | string | number = "2026-01-01T00:00:00.000Z",
|
||||
): FakeClock {
|
||||
let currentMs = new Date(initial).getTime();
|
||||
return {
|
||||
now(): Date {
|
||||
return new Date(currentMs);
|
||||
},
|
||||
advance(ms: number): Date {
|
||||
if (!Number.isFinite(ms) || ms < 0) {
|
||||
throw new Error("FakeClock.advance requires a non-negative finite ms value");
|
||||
}
|
||||
currentMs += ms;
|
||||
return new Date(currentMs);
|
||||
},
|
||||
set(date: Date | string | number): Date {
|
||||
currentMs = new Date(date).getTime();
|
||||
return new Date(currentMs);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** In-memory scoped `IntegrationStorage` with real TTL expiry and serialized locking. */
|
||||
export function createMemoryIntegrationStorage(clock?: Clock): IntegrationStorage {
|
||||
const nowMs = (): number => (clock === undefined ? Date.now() : clock.now().getTime());
|
||||
const records = new Map<string, { value: JsonValue; expiresAt?: number }>();
|
||||
const lockChains = new Map<string, Promise<void>>();
|
||||
|
||||
const isExpired = (entry: { expiresAt?: number }): boolean =>
|
||||
entry.expiresAt !== undefined && nowMs() >= entry.expiresAt;
|
||||
|
||||
return {
|
||||
async get<T extends JsonValue = JsonValue>(key: string): Promise<T | undefined> {
|
||||
const entry = records.get(key);
|
||||
if (entry === undefined || isExpired(entry)) {
|
||||
records.delete(key);
|
||||
return undefined;
|
||||
}
|
||||
return structuredClone(entry.value) as T;
|
||||
},
|
||||
async set(key: string, value: JsonValue, options?: { readonly ttlMs?: number }): Promise<void> {
|
||||
const expiresAt = options?.ttlMs !== undefined ? nowMs() + options.ttlMs : undefined;
|
||||
records.set(key, { value: structuredClone(value), expiresAt });
|
||||
},
|
||||
async delete(key: string): Promise<void> {
|
||||
records.delete(key);
|
||||
},
|
||||
async list(prefix = ""): Promise<readonly IntegrationStorageEntry[]> {
|
||||
const out: IntegrationStorageEntry[] = [];
|
||||
for (const [key, entry] of records.entries()) {
|
||||
if (isExpired(entry)) {
|
||||
records.delete(key);
|
||||
continue;
|
||||
}
|
||||
if (key.startsWith(prefix)) {
|
||||
out.push({ key, value: structuredClone(entry.value) });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
},
|
||||
async withLock<T>(key: string, _ttlMs: number, fn: () => Promise<T>): Promise<T> {
|
||||
const prior = lockChains.get(key) ?? Promise.resolve();
|
||||
let release!: () => void;
|
||||
const current = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const tail = prior.then(() => current);
|
||||
lockChains.set(key, tail);
|
||||
await prior;
|
||||
try {
|
||||
return await fn();
|
||||
} finally {
|
||||
release();
|
||||
if (lockChains.get(key) === tail) {
|
||||
lockChains.delete(key);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** In-memory `IntegrationConnections` registry for tests and local daemon runs. */
|
||||
export function createMemoryIntegrationConnections(
|
||||
initial: readonly IntegrationConnectionRecord[] = [],
|
||||
): IntegrationConnections {
|
||||
const list = initial.map((item) => structuredClone(item));
|
||||
return {
|
||||
async get(connectionNameOrId: string): Promise<IntegrationConnectionRecord | undefined> {
|
||||
const found = list.find(
|
||||
(item) => item.id === connectionNameOrId || item.name === connectionNameOrId,
|
||||
);
|
||||
return found === undefined ? undefined : structuredClone(found);
|
||||
},
|
||||
async list(): Promise<readonly IntegrationConnectionRecord[]> {
|
||||
return list.map((item) => structuredClone(item));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export interface FakeGateSink extends GateSink {
|
||||
readonly opened: WorkflowGateRecord[];
|
||||
readonly resolved: WorkflowGateRecord[];
|
||||
readonly expired: WorkflowGateRecord[];
|
||||
}
|
||||
|
||||
/** Records all gate lifecycle notifications without mocks. */
|
||||
export function createFakeGateSink(): FakeGateSink {
|
||||
const opened: WorkflowGateRecord[] = [];
|
||||
const resolved: WorkflowGateRecord[] = [];
|
||||
const expired: WorkflowGateRecord[] = [];
|
||||
return {
|
||||
opened,
|
||||
resolved,
|
||||
expired,
|
||||
async onGateOpened(gate: WorkflowGateRecord): Promise<void> {
|
||||
opened.push(structuredClone(gate));
|
||||
},
|
||||
async onGateResolved(gate: WorkflowGateRecord): Promise<void> {
|
||||
resolved.push(structuredClone(gate));
|
||||
},
|
||||
async onGateExpired(gate: WorkflowGateRecord): Promise<void> {
|
||||
expired.push(structuredClone(gate));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type FakeAgentHandler = (
|
||||
request: AgentStepRequest,
|
||||
) => Promise<AgentStepStartResult> | AgentStepStartResult;
|
||||
|
||||
export interface CancelledAgentRecord {
|
||||
readonly executionId: string;
|
||||
readonly reason: string;
|
||||
}
|
||||
|
||||
export interface FakeAgentRunner extends AgentRunner {
|
||||
readonly requests: AgentStepRequest[];
|
||||
readonly cancelled: CancelledAgentRecord[];
|
||||
setHandler(handler: FakeAgentHandler): void;
|
||||
}
|
||||
|
||||
/** Programmable fake `AgentRunner` with full call recording and zero mocks. */
|
||||
export function createFakeAgentRunner(initialHandler?: FakeAgentHandler): FakeAgentRunner {
|
||||
const requests: AgentStepRequest[] = [];
|
||||
const cancelled: CancelledAgentRecord[] = [];
|
||||
let handler: FakeAgentHandler =
|
||||
initialHandler ??
|
||||
(() => ({
|
||||
status: "completed",
|
||||
outcome: "ok",
|
||||
}));
|
||||
|
||||
return {
|
||||
requests,
|
||||
cancelled,
|
||||
setHandler(next: FakeAgentHandler): void {
|
||||
handler = next;
|
||||
},
|
||||
async start(request: AgentStepRequest): Promise<AgentStepStartResult> {
|
||||
requests.push(structuredClone(request));
|
||||
return handler(request);
|
||||
},
|
||||
async cancel(executionId: string, reason: string): Promise<void> {
|
||||
cancelled.push({ executionId, reason });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
interface MutableRun {
|
||||
id: string;
|
||||
workflowId: string;
|
||||
status: WorkflowRunSnapshot["status"];
|
||||
pausedFromStatus?: "running" | "waiting";
|
||||
subjectKey?: string;
|
||||
subjectData: WorkflowRunSnapshot["subjectData"];
|
||||
inputs: Record<string, JsonValue>;
|
||||
event?: WorkflowRunSnapshot["event"];
|
||||
currentState: string;
|
||||
loopCounts: Record<string, number>;
|
||||
attempts: MutableAttempt[];
|
||||
lastGate?: WorkflowRunSnapshot["lastGate"];
|
||||
terminalReason?: string;
|
||||
terminalOutputs?: WorkflowRunSnapshot["terminalOutputs"];
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
completedAt?: Date;
|
||||
}
|
||||
|
||||
interface MutableAttempt {
|
||||
id: string;
|
||||
runId: string;
|
||||
stepId: string;
|
||||
attempt: number;
|
||||
executionId: string;
|
||||
status: StepAttemptRecord["status"];
|
||||
outcome?: string;
|
||||
output?: StepAttemptRecord["output"];
|
||||
error?: string;
|
||||
wait?: StepWaitSpec;
|
||||
activeLeases: ActiveAuthLease[];
|
||||
startedAt: Date;
|
||||
finishedAt?: Date;
|
||||
}
|
||||
|
||||
interface MutableGate {
|
||||
id: string;
|
||||
runId: string;
|
||||
workflowId: string;
|
||||
stepId: string;
|
||||
attemptId: string;
|
||||
title: string;
|
||||
summary?: string;
|
||||
recommended?: string;
|
||||
choices: WorkflowGateRecord["choices"];
|
||||
status: WorkflowGateRecord["status"];
|
||||
openedAt: Date;
|
||||
expiresAt?: Date;
|
||||
resolution?: GateResolution;
|
||||
}
|
||||
|
||||
function isTerminalStatus(status: WorkflowRunSnapshot["status"]): boolean {
|
||||
return status === "done" || status === "failed" || status === "cancelled";
|
||||
}
|
||||
|
||||
function cloneRun(run: MutableRun): WorkflowRunSnapshot {
|
||||
return structuredClone(run);
|
||||
}
|
||||
|
||||
function cloneAttempt(attempt: MutableAttempt): StepAttemptRecord {
|
||||
return structuredClone(attempt);
|
||||
}
|
||||
|
||||
function cloneGate(gate: MutableGate): WorkflowGateRecord {
|
||||
return structuredClone(gate);
|
||||
}
|
||||
|
||||
/**
|
||||
* Full in-memory implementation of `WorkflowStore`.
|
||||
* Suitable both for zero-mock unit/contract tests and as the foundation for local daemon execution.
|
||||
*/
|
||||
export function createMemoryWorkflowStore(): WorkflowStore {
|
||||
let runSeq = 0;
|
||||
let attemptSeq = 0;
|
||||
let gateSeq = 0;
|
||||
|
||||
const runs = new Map<string, MutableRun>();
|
||||
const attemptsById = new Map<string, MutableAttempt>();
|
||||
const gates = new Map<string, MutableGate>();
|
||||
const outputs = new Map<string, PublishedWorkflowOutput>();
|
||||
|
||||
const outputMapKey = (workflowId: string, outputKey: string): string =>
|
||||
`${workflowId}\0${outputKey}`;
|
||||
|
||||
const findActiveRunForSubject = (
|
||||
workflowId: string,
|
||||
subjectKey: string,
|
||||
): MutableRun | undefined => {
|
||||
for (const run of runs.values()) {
|
||||
if (
|
||||
run.workflowId === workflowId &&
|
||||
run.subjectKey === subjectKey &&
|
||||
!isTerminalStatus(run.status) &&
|
||||
run.status !== "queued"
|
||||
) {
|
||||
return run;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
return {
|
||||
async acceptRun(input: AcceptWorkflowRunInput): Promise<AcceptWorkflowRunResult> {
|
||||
const existing =
|
||||
input.subjectKey === undefined
|
||||
? undefined
|
||||
: findActiveRunForSubject(input.workflowId, input.subjectKey);
|
||||
|
||||
if (existing !== undefined) {
|
||||
const policy = input.onConflict ?? "ignore";
|
||||
if (policy === "ignore") {
|
||||
return { action: "ignored", existingRun: cloneRun(existing) };
|
||||
}
|
||||
if (policy === "signal") {
|
||||
return { action: "signal", existingRun: cloneRun(existing) };
|
||||
}
|
||||
if (policy === "queue") {
|
||||
const queuedId = `run_${++runSeq}`;
|
||||
const queued: MutableRun = {
|
||||
id: queuedId,
|
||||
workflowId: input.workflowId,
|
||||
status: "queued",
|
||||
subjectKey: input.subjectKey,
|
||||
subjectData: structuredClone(input.subjectData),
|
||||
inputs: structuredClone(input.inputs) as Record<string, JsonValue>,
|
||||
event: input.event === undefined ? undefined : structuredClone(input.event),
|
||||
currentState: input.initialState,
|
||||
loopCounts: {},
|
||||
attempts: [],
|
||||
createdAt: new Date(input.now.getTime()),
|
||||
updatedAt: new Date(input.now.getTime()),
|
||||
};
|
||||
runs.set(queuedId, queued);
|
||||
return { action: "queued", run: cloneRun(queued) };
|
||||
}
|
||||
if (policy === "cancel_previous") {
|
||||
const cancelledSnapshot = cloneRun(existing);
|
||||
existing.status = "cancelled";
|
||||
existing.terminalReason = "superseded_by_new_run";
|
||||
existing.updatedAt = new Date(input.now.getTime());
|
||||
existing.completedAt = new Date(input.now.getTime());
|
||||
for (const attempt of existing.attempts) {
|
||||
if (attempt.status === "running" || attempt.status === "waiting") {
|
||||
attempt.status = "cancelled";
|
||||
attempt.wait = undefined;
|
||||
attempt.finishedAt = new Date(input.now.getTime());
|
||||
}
|
||||
}
|
||||
|
||||
const nextId = `run_${++runSeq}`;
|
||||
const nextRun: MutableRun = {
|
||||
id: nextId,
|
||||
workflowId: input.workflowId,
|
||||
status: "running",
|
||||
subjectKey: input.subjectKey,
|
||||
subjectData: structuredClone(input.subjectData),
|
||||
inputs: structuredClone(input.inputs) as Record<string, JsonValue>,
|
||||
event: input.event === undefined ? undefined : structuredClone(input.event),
|
||||
currentState: input.initialState,
|
||||
loopCounts: {},
|
||||
attempts: [],
|
||||
createdAt: new Date(input.now.getTime()),
|
||||
updatedAt: new Date(input.now.getTime()),
|
||||
};
|
||||
runs.set(nextId, nextRun);
|
||||
return { action: "replaced", run: cloneRun(nextRun), cancelledRun: cancelledSnapshot };
|
||||
}
|
||||
}
|
||||
|
||||
const id = `run_${++runSeq}`;
|
||||
const run: MutableRun = {
|
||||
id,
|
||||
workflowId: input.workflowId,
|
||||
status: "running",
|
||||
subjectKey: input.subjectKey,
|
||||
subjectData: structuredClone(input.subjectData),
|
||||
inputs: structuredClone(input.inputs) as Record<string, JsonValue>,
|
||||
event: input.event === undefined ? undefined : structuredClone(input.event),
|
||||
currentState: input.initialState,
|
||||
loopCounts: {},
|
||||
attempts: [],
|
||||
createdAt: new Date(input.now.getTime()),
|
||||
updatedAt: new Date(input.now.getTime()),
|
||||
};
|
||||
runs.set(id, run);
|
||||
return { action: "started", run: cloneRun(run) };
|
||||
},
|
||||
|
||||
async loadRun(runId: string): Promise<WorkflowRunSnapshot | undefined> {
|
||||
const run = runs.get(runId);
|
||||
return run === undefined ? undefined : cloneRun(run);
|
||||
},
|
||||
|
||||
async listRuns(filter?: ListRunsFilter): Promise<readonly WorkflowRunSnapshot[]> {
|
||||
let statuses: Set<WorkflowRunSnapshot["status"]> | undefined;
|
||||
if (filter?.status !== undefined) {
|
||||
statuses = Array.isArray(filter.status) ? new Set(filter.status) : new Set([filter.status]);
|
||||
}
|
||||
const result: WorkflowRunSnapshot[] = [];
|
||||
for (const run of runs.values()) {
|
||||
if (filter?.workflowId !== undefined && run.workflowId !== filter.workflowId) {
|
||||
continue;
|
||||
}
|
||||
if (filter?.subjectKey !== undefined && run.subjectKey !== filter.subjectKey) {
|
||||
continue;
|
||||
}
|
||||
if (statuses !== undefined && !statuses.has(run.status)) {
|
||||
continue;
|
||||
}
|
||||
result.push(cloneRun(run));
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async dequeueNextRun(
|
||||
workflowId: string,
|
||||
subjectKey: string,
|
||||
now: Date,
|
||||
): Promise<WorkflowRunSnapshot | undefined> {
|
||||
if (findActiveRunForSubject(workflowId, subjectKey) !== undefined) {
|
||||
return undefined;
|
||||
}
|
||||
for (const run of runs.values()) {
|
||||
if (
|
||||
run.workflowId === workflowId &&
|
||||
run.subjectKey === subjectKey &&
|
||||
run.status === "queued"
|
||||
) {
|
||||
run.status = "running";
|
||||
run.updatedAt = new Date(now.getTime());
|
||||
return cloneRun(run);
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
|
||||
async beginStepAttempt(input: BeginStepAttemptInput): Promise<StepAttemptRecord> {
|
||||
const run = runs.get(input.runId);
|
||||
if (run === undefined) {
|
||||
throw new Error(`run "${input.runId}" not found`);
|
||||
}
|
||||
const nextCount = (run.loopCounts[input.stepId] ?? 0) + (input.incrementLoop ? 1 : 0);
|
||||
if (input.incrementLoop) {
|
||||
run.loopCounts[input.stepId] = nextCount;
|
||||
}
|
||||
const attemptId = `att_${++attemptSeq}`;
|
||||
const attempt: MutableAttempt = {
|
||||
id: attemptId,
|
||||
runId: input.runId,
|
||||
stepId: input.stepId,
|
||||
attempt: nextCount,
|
||||
executionId: `exec_${attemptSeq}`,
|
||||
status: "running",
|
||||
activeLeases: [],
|
||||
startedAt: new Date(input.now.getTime()),
|
||||
};
|
||||
run.attempts.push(attempt);
|
||||
run.updatedAt = new Date(input.now.getTime());
|
||||
attemptsById.set(attemptId, attempt);
|
||||
return cloneAttempt(attempt);
|
||||
},
|
||||
|
||||
async setAttemptLeases(attemptId: string, leases: readonly ActiveAuthLease[]): Promise<void> {
|
||||
const attempt = attemptsById.get(attemptId);
|
||||
if (attempt === undefined) {
|
||||
return;
|
||||
}
|
||||
attempt.activeLeases = leases.map((lease) => ({ ...lease }));
|
||||
},
|
||||
|
||||
async setAttemptExecutionId(attemptId: string, executionId: string): Promise<void> {
|
||||
const attempt = attemptsById.get(attemptId);
|
||||
if (attempt === undefined) {
|
||||
return;
|
||||
}
|
||||
attempt.executionId = executionId;
|
||||
},
|
||||
|
||||
async suspendStepAttempt(attemptId: string, wait: StepWaitSpec): Promise<void> {
|
||||
const attempt = attemptsById.get(attemptId);
|
||||
if (attempt === undefined) {
|
||||
throw new Error(`attempt "${attemptId}" not found`);
|
||||
}
|
||||
attempt.status = "waiting";
|
||||
attempt.wait = structuredClone(wait);
|
||||
},
|
||||
|
||||
async completeStepAttempt(input: CompleteStepAttemptInput): Promise<WorkflowRunSnapshot> {
|
||||
const run = runs.get(input.runId);
|
||||
if (run === undefined) {
|
||||
throw new Error(`run "${input.runId}" not found`);
|
||||
}
|
||||
const attempt = attemptsById.get(input.attemptId);
|
||||
if (attempt === undefined) {
|
||||
throw new Error(`attempt "${input.attemptId}" not found`);
|
||||
}
|
||||
attempt.status = input.status;
|
||||
attempt.outcome = input.outcome;
|
||||
attempt.output = input.output === undefined ? undefined : structuredClone(input.output);
|
||||
attempt.error = input.error;
|
||||
attempt.wait = undefined;
|
||||
attempt.finishedAt = new Date(input.now.getTime());
|
||||
run.updatedAt = new Date(input.now.getTime());
|
||||
return cloneRun(run);
|
||||
},
|
||||
|
||||
async transitionRun(input: TransitionRunInput): Promise<WorkflowRunSnapshot> {
|
||||
const run = runs.get(input.runId);
|
||||
if (run === undefined) {
|
||||
throw new Error(`run "${input.runId}" not found`);
|
||||
}
|
||||
run.status = input.status;
|
||||
if (input.status === "paused") {
|
||||
run.pausedFromStatus = input.pausedFromStatus;
|
||||
} else {
|
||||
run.pausedFromStatus = undefined;
|
||||
}
|
||||
if (input.currentState !== undefined) {
|
||||
run.currentState = input.currentState;
|
||||
}
|
||||
if (input.lastGate !== undefined) {
|
||||
run.lastGate = { ...input.lastGate };
|
||||
}
|
||||
if (input.terminalReason !== undefined) {
|
||||
run.terminalReason = input.terminalReason;
|
||||
}
|
||||
if (input.terminalOutputs !== undefined) {
|
||||
run.terminalOutputs = structuredClone(input.terminalOutputs);
|
||||
}
|
||||
run.updatedAt = new Date(input.now.getTime());
|
||||
if (isTerminalStatus(input.status)) {
|
||||
run.completedAt = new Date(input.now.getTime());
|
||||
}
|
||||
return cloneRun(run);
|
||||
},
|
||||
|
||||
async listSuspendedWaits(
|
||||
kind?: StepWaitSpec["kind"],
|
||||
options?: { readonly includePaused?: boolean },
|
||||
): Promise<readonly SuspendedWaitRecord[]> {
|
||||
const includePaused = options?.includePaused === true;
|
||||
const result: SuspendedWaitRecord[] = [];
|
||||
for (const attempt of attemptsById.values()) {
|
||||
if (attempt.status !== "waiting" || attempt.wait === undefined) {
|
||||
continue;
|
||||
}
|
||||
if (kind !== undefined && attempt.wait.kind !== kind) {
|
||||
continue;
|
||||
}
|
||||
const run = runs.get(attempt.runId);
|
||||
if (run === undefined) {
|
||||
continue;
|
||||
}
|
||||
if (run.status !== "waiting" && !(includePaused && run.status === "paused")) {
|
||||
continue;
|
||||
}
|
||||
result.push({
|
||||
runId: attempt.runId,
|
||||
attemptId: attempt.id,
|
||||
stepId: attempt.stepId,
|
||||
wait: structuredClone(attempt.wait),
|
||||
});
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async findExpiredWaits(now: Date): Promise<readonly SuspendedWaitRecord[]> {
|
||||
const nowMs = now.getTime();
|
||||
const result: SuspendedWaitRecord[] = [];
|
||||
for (const attempt of attemptsById.values()) {
|
||||
if (attempt.status !== "waiting" || attempt.wait === undefined) {
|
||||
continue;
|
||||
}
|
||||
const run = runs.get(attempt.runId);
|
||||
if (run === undefined || run.status !== "waiting") {
|
||||
continue;
|
||||
}
|
||||
const wakeAt = attempt.wait.wakeAt;
|
||||
if (wakeAt !== undefined && wakeAt.getTime() <= nowMs) {
|
||||
result.push({
|
||||
runId: attempt.runId,
|
||||
attemptId: attempt.id,
|
||||
stepId: attempt.stepId,
|
||||
wait: structuredClone(attempt.wait),
|
||||
});
|
||||
}
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async publishWorkflowOutput(
|
||||
input: PublishedWorkflowOutput,
|
||||
): Promise<readonly SuspendedWaitRecord[]> {
|
||||
outputs.set(outputMapKey(input.workflowId, input.outputKey), structuredClone(input));
|
||||
const matched: SuspendedWaitRecord[] = [];
|
||||
for (const attempt of attemptsById.values()) {
|
||||
if (attempt.status !== "waiting" || attempt.wait?.kind !== "wait_workflow") {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
attempt.wait.workflowId !== input.workflowId ||
|
||||
attempt.wait.outputKey !== input.outputKey
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const run = runs.get(attempt.runId);
|
||||
if (run === undefined || run.status !== "waiting") {
|
||||
continue;
|
||||
}
|
||||
matched.push({
|
||||
runId: attempt.runId,
|
||||
attemptId: attempt.id,
|
||||
stepId: attempt.stepId,
|
||||
wait: structuredClone(attempt.wait),
|
||||
});
|
||||
}
|
||||
return matched;
|
||||
},
|
||||
|
||||
async findWorkflowOutput(
|
||||
workflowId: string,
|
||||
outputKey: string,
|
||||
): Promise<PublishedWorkflowOutput | undefined> {
|
||||
const found = outputs.get(outputMapKey(workflowId, outputKey));
|
||||
return found === undefined ? undefined : structuredClone(found);
|
||||
},
|
||||
|
||||
async openGate(input: OpenGateInput): Promise<WorkflowGateRecord> {
|
||||
const id = `gate_${++gateSeq}`;
|
||||
const gate: MutableGate = {
|
||||
id,
|
||||
runId: input.runId,
|
||||
workflowId: input.workflowId,
|
||||
stepId: input.stepId,
|
||||
attemptId: input.attemptId,
|
||||
title: input.title,
|
||||
summary: input.summary,
|
||||
recommended: input.recommended,
|
||||
choices: structuredClone(input.choices),
|
||||
status: "open",
|
||||
openedAt: new Date(input.openedAt.getTime()),
|
||||
expiresAt: input.expiresAt === undefined ? undefined : new Date(input.expiresAt.getTime()),
|
||||
};
|
||||
gates.set(id, gate);
|
||||
return cloneGate(gate);
|
||||
},
|
||||
|
||||
async getGate(gateId: string): Promise<WorkflowGateRecord | undefined> {
|
||||
const gate = gates.get(gateId);
|
||||
return gate === undefined ? undefined : cloneGate(gate);
|
||||
},
|
||||
|
||||
async listOpenGates(filter?: ListOpenGatesFilter): Promise<readonly WorkflowGateRecord[]> {
|
||||
const result: WorkflowGateRecord[] = [];
|
||||
for (const gate of gates.values()) {
|
||||
if (gate.status !== "open") {
|
||||
continue;
|
||||
}
|
||||
if (filter?.workflowId !== undefined && gate.workflowId !== filter.workflowId) {
|
||||
continue;
|
||||
}
|
||||
if (filter?.runId !== undefined && gate.runId !== filter.runId) {
|
||||
continue;
|
||||
}
|
||||
result.push(cloneGate(gate));
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async resolveGate(
|
||||
gateId: string,
|
||||
resolution: GateResolution,
|
||||
): Promise<WorkflowGateRecord | undefined> {
|
||||
const gate = gates.get(gateId);
|
||||
if (gate === undefined || gate.status !== "open") {
|
||||
return undefined;
|
||||
}
|
||||
gate.status = "resolved";
|
||||
gate.resolution = {
|
||||
choice: resolution.choice,
|
||||
note: resolution.note,
|
||||
actor: resolution.actor,
|
||||
resolvedAt: new Date(resolution.resolvedAt.getTime()),
|
||||
};
|
||||
return cloneGate(gate);
|
||||
},
|
||||
|
||||
async expireGate(gateId: string): Promise<WorkflowGateRecord | undefined> {
|
||||
const gate = gates.get(gateId);
|
||||
if (gate === undefined || gate.status !== "open") {
|
||||
return undefined;
|
||||
}
|
||||
gate.status = "expired";
|
||||
return cloneGate(gate);
|
||||
},
|
||||
|
||||
async cancelRunGates(runId: string): Promise<readonly WorkflowGateRecord[]> {
|
||||
const cancelled: WorkflowGateRecord[] = [];
|
||||
for (const gate of gates.values()) {
|
||||
if (gate.runId === runId && gate.status === "open") {
|
||||
gate.status = "cancelled";
|
||||
cancelled.push(cloneGate(gate));
|
||||
}
|
||||
}
|
||||
return cancelled;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
import { readdirSync, readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
import { defineWorkflow, step, terminal } from "../src/dsl.js";
|
||||
import {
|
||||
createWorkflowEngine,
|
||||
type IntegrationContext,
|
||||
type WorkflowIntegration,
|
||||
type WorkflowIR,
|
||||
} from "../src/index.js";
|
||||
import {
|
||||
createFakeAgentRunner,
|
||||
createFakeClock,
|
||||
createFakeGateSink,
|
||||
createMemoryIntegrationConnections,
|
||||
createMemoryIntegrationStorage,
|
||||
createMemoryWorkflowStore,
|
||||
} from "../src/testing.js";
|
||||
|
||||
const packageDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const srcDir = path.join(packageDir, "src");
|
||||
|
||||
function collectSourceFiles(dir: string): string[] {
|
||||
const results: string[] = [];
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
const fullPath = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
results.push(...collectSourceFiles(fullPath));
|
||||
} else if (entry.isFile() && /\.(?:ts|mts|js|mjs)$/u.test(entry.name)) {
|
||||
results.push(fullPath);
|
||||
}
|
||||
}
|
||||
return results.sort();
|
||||
}
|
||||
|
||||
describe("hard mechanical boundaries", () => {
|
||||
it("exports ONLY the 5 agreed entrypoints and allows ONLY pure runtime dependencies", () => {
|
||||
const pkg = JSON.parse(readFileSync(path.join(packageDir, "package.json"), "utf8")) as {
|
||||
readonly exports: Record<string, unknown>;
|
||||
readonly dependencies?: Record<string, string>;
|
||||
};
|
||||
|
||||
expect(Object.keys(pkg.exports).sort()).toEqual([".", "./dsl", "./ir", "./testing", "./yaml"]);
|
||||
|
||||
const allowedDeps = new Set(["zod", "ajv", "js-yaml"]);
|
||||
const actualDeps = Object.keys(pkg.dependencies ?? {});
|
||||
expect(actualDeps.length).toBeGreaterThan(0);
|
||||
for (const dep of actualDeps) {
|
||||
expect(allowedDeps.has(dep), `disallowed runtime dependency "${dep}"`).toBe(true);
|
||||
}
|
||||
|
||||
const forbiddenDeps = ["pg", "drizzle-orm", "react", "@octokit/rest", "@octokit/core"];
|
||||
for (const forbidden of forbiddenDeps) {
|
||||
expect(actualDeps).not.toContain(forbidden);
|
||||
}
|
||||
});
|
||||
|
||||
it("contains zero Node builtin imports in src/ (including ./ir and ./dsl)", () => {
|
||||
const files = collectSourceFiles(srcDir);
|
||||
expect(files.length).toBeGreaterThan(0);
|
||||
|
||||
const nodeImportPattern =
|
||||
/(?:from\s+["'](?:node:|fs|net|http|https|path|os|crypto|child_process|stream|worker_threads)["']|require\(["'](?:node:|fs|net|http|https|path|os|crypto|child_process)["']\))/gu;
|
||||
|
||||
for (const file of files) {
|
||||
const content = readFileSync(file, "utf8");
|
||||
const matches = content.match(nodeImportPattern);
|
||||
expect(
|
||||
matches,
|
||||
`unexpected Node builtin import in ${path.relative(packageDir, file)}`,
|
||||
).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("contains zero hardcoded provider or database names anywhere in packages/workflows/src/", () => {
|
||||
const files = collectSourceFiles(srcDir);
|
||||
const forbiddenProviders = ["github", "slack", "discord", "linear", "notion", "postgres"];
|
||||
|
||||
for (const file of files) {
|
||||
const content = readFileSync(file, "utf8");
|
||||
for (const provider of forbiddenProviders) {
|
||||
const pattern = new RegExp(`\\b${provider}\\b`, "i");
|
||||
expect(
|
||||
pattern.test(content),
|
||||
`forbidden hardcoded provider "${provider}" found in ${path.relative(packageDir, file)}`,
|
||||
).toBe(false);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("passes ONLY the narrow IntegrationContext (zero Database/SQL/engine handles) to integration hooks", async () => {
|
||||
// Compile-time type-level verification of exact IntegrationContext keys.
|
||||
type ExpectedKeys = "scopeId" | "storage" | "connections" | "ingest" | "fetch" | "log" | "now";
|
||||
type AssertExact<T, U> = [T] extends [U] ? ([U] extends [T] ? true : never) : never;
|
||||
const _exactContextKeys: AssertExact<keyof IntegrationContext, ExpectedKeys> = true;
|
||||
expect(_exactContextKeys).toBe(true);
|
||||
|
||||
const observedKeySets: string[][] = [];
|
||||
const expectedSortedKeys = [
|
||||
"connections",
|
||||
"fetch",
|
||||
"ingest",
|
||||
"log",
|
||||
"now",
|
||||
"scopeId",
|
||||
"storage",
|
||||
];
|
||||
|
||||
const recordCtx = (ctx: IntegrationContext): void => {
|
||||
observedKeySets.push(Object.keys(ctx).sort());
|
||||
const asRecord = ctx as unknown as Record<string, unknown>;
|
||||
expect(asRecord["db"]).toBeUndefined();
|
||||
expect(asRecord["database"]).toBeUndefined();
|
||||
expect(asRecord["sql"]).toBeUndefined();
|
||||
expect(asRecord["drizzle"]).toBeUndefined();
|
||||
expect(asRecord["store"]).toBeUndefined();
|
||||
expect(asRecord["engine"]).toBeUndefined();
|
||||
};
|
||||
|
||||
const acme: WorkflowIntegration = {
|
||||
id: "acme",
|
||||
auth: {
|
||||
async mint(_scope, ctx) {
|
||||
recordCtx(ctx);
|
||||
return { leaseId: "lease_1", env: { ACME_TOKEN: "tok_1" } };
|
||||
},
|
||||
async revoke(_leaseId, ctx) {
|
||||
recordCtx(ctx);
|
||||
},
|
||||
},
|
||||
steps: {
|
||||
check: {
|
||||
inputSchema: z.object({ ticket: z.string() }),
|
||||
outcomes: ["ok"],
|
||||
async execute(input, ctx) {
|
||||
recordCtx(ctx);
|
||||
await ctx.storage.set("last_ticket", input["ticket"] as string, { ttlMs: 5_000 });
|
||||
const stored = await ctx.storage.get<string>("last_ticket");
|
||||
expect(stored).toBe("ACME-1");
|
||||
const conn = await ctx.connections.get("acme-main");
|
||||
expect(conn?.name).toBe("acme-main");
|
||||
return { status: "completed", outcome: "ok", output: { seen: stored ?? "" } };
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const ir = defineWorkflow({
|
||||
id: "boundary-ctx-check",
|
||||
on: { "acme.ping": {} },
|
||||
initial: "run_check",
|
||||
steps: {
|
||||
run_check: step.integration("acme.check", {
|
||||
auth: { acme: { connection: "acme-main" } },
|
||||
input: { ticket: "ACME-1" },
|
||||
on: { ok: terminal.done() },
|
||||
}),
|
||||
},
|
||||
});
|
||||
const roundTripped = JSON.parse(JSON.stringify(ir)) as WorkflowIR;
|
||||
|
||||
const clock = createFakeClock();
|
||||
const engine = createWorkflowEngine({
|
||||
store: createMemoryWorkflowStore(),
|
||||
runner: createFakeAgentRunner(),
|
||||
gates: createFakeGateSink(),
|
||||
integrations: [acme],
|
||||
clock,
|
||||
scopeId: "tenant-a",
|
||||
storage: createMemoryIntegrationStorage(clock),
|
||||
connections: createMemoryIntegrationConnections([
|
||||
{ id: "conn_1", name: "acme-main", integration: "acme" },
|
||||
]),
|
||||
workflows: [roundTripped],
|
||||
});
|
||||
|
||||
const run = await engine.start({ workflowId: "boundary-ctx-check" });
|
||||
expect(run.status).toBe("done");
|
||||
expect(observedKeySets.length).toBe(3); // mint + execute + revoke
|
||||
for (const keys of observedKeySets) {
|
||||
expect(keys).toEqual(expectedSortedKeys);
|
||||
}
|
||||
});
|
||||
|
||||
it("enforces IntegrationStorage TTL expiry, listing, deletion, and lock serialization", async () => {
|
||||
const clock = createFakeClock("2026-06-01T00:00:00.000Z");
|
||||
const storage = createMemoryIntegrationStorage(clock);
|
||||
|
||||
await storage.set("cache:a", { count: 1 }, { ttlMs: 1_000 });
|
||||
await storage.set("cache:b", { count: 2 });
|
||||
await storage.set("other:c", "hello");
|
||||
|
||||
expect(await storage.get("cache:a")).toEqual({ count: 1 });
|
||||
expect((await storage.list("cache:")).map((e) => e.key).sort()).toEqual(["cache:a", "cache:b"]);
|
||||
|
||||
clock.advance(1_000);
|
||||
expect(await storage.get("cache:a")).toBeUndefined();
|
||||
expect((await storage.list("cache:")).map((e) => e.key)).toEqual(["cache:b"]);
|
||||
|
||||
await storage.delete("cache:b");
|
||||
expect(await storage.get("cache:b")).toBeUndefined();
|
||||
|
||||
const order: string[] = [];
|
||||
const p1 = storage.withLock("lock-1", 5_000, async () => {
|
||||
order.push("start-1");
|
||||
await Promise.resolve();
|
||||
order.push("end-1");
|
||||
return "first";
|
||||
});
|
||||
const p2 = storage.withLock("lock-1", 5_000, async () => {
|
||||
order.push("start-2");
|
||||
order.push("end-2");
|
||||
return "second";
|
||||
});
|
||||
expect(await Promise.all([p1, p2])).toEqual(["first", "second"]);
|
||||
expect(order).toEqual(["start-1", "end-1", "start-2", "end-2"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,386 @@
|
||||
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
import { defineTrigger, defineWorkflow, expr, ref, step, terminal, tpl } from "../src/dsl.js";
|
||||
import { validateWorkflowIR, type WorkflowIR } from "../src/ir.js";
|
||||
import { compileWorkflowYaml } from "../src/yaml.js";
|
||||
|
||||
describe("DSL and YAML byte-identical IR compilation", () => {
|
||||
it("compiles 1-state trigger shorthand identically from TS DSL and YAML", () => {
|
||||
const yamlSource = `
|
||||
name: acme-priority-review
|
||||
enabled: true
|
||||
on:
|
||||
acme.pull_request_label_added:
|
||||
connection: acme-main
|
||||
filters:
|
||||
repo: acme/widget
|
||||
label: priority-review
|
||||
max_runtime: 1h
|
||||
run:
|
||||
target:
|
||||
daemon: factory
|
||||
cwd: /srv/acme/widget
|
||||
worktree:
|
||||
mode: branch-off
|
||||
base: origin/main
|
||||
newBranch: priority-review-\${{ paseo.execution.id }}
|
||||
agent:
|
||||
provider: claude
|
||||
model: claude-opus-5-5
|
||||
mode: bypassPermissions
|
||||
thinkingOptionId: medium
|
||||
continuation:
|
||||
mode: new
|
||||
max_runtime: 30m
|
||||
idle_timeout: 10m
|
||||
auto_archive: true
|
||||
background: true
|
||||
acme:
|
||||
connection: acme-main
|
||||
repositories: [acme/widget]
|
||||
permissions:
|
||||
contents: read
|
||||
pull_requests: write
|
||||
prompt: "Review priority PR #\${{ paseo.context.acme.item.number }}."
|
||||
outputs:
|
||||
acme.reply:
|
||||
max: 3
|
||||
`;
|
||||
|
||||
const dslIR = defineTrigger({
|
||||
name: "acme-priority-review",
|
||||
enabled: true,
|
||||
on: {
|
||||
"acme.pull_request_label_added": {
|
||||
connection: "acme-main",
|
||||
filters: { repo: "acme/widget", label: "priority-review" },
|
||||
},
|
||||
},
|
||||
maxRuntime: "1h",
|
||||
run: {
|
||||
target: {
|
||||
daemon: "factory",
|
||||
cwd: "/srv/acme/widget",
|
||||
worktree: {
|
||||
mode: "branch-off",
|
||||
base: "origin/main",
|
||||
newBranch: tpl`priority-review-${expr.executionId()}`,
|
||||
},
|
||||
},
|
||||
agent: {
|
||||
provider: "claude",
|
||||
model: "claude-opus-5-5",
|
||||
mode: "bypassPermissions",
|
||||
thinkingOptionId: "medium",
|
||||
},
|
||||
continuation: { mode: "new" },
|
||||
maxRuntime: "30m",
|
||||
idleTimeout: "10m",
|
||||
autoArchive: true,
|
||||
background: true,
|
||||
auth: {
|
||||
acme: {
|
||||
connection: "acme-main",
|
||||
repositories: ["acme/widget"],
|
||||
permissions: { contents: "read", pull_requests: "write" },
|
||||
},
|
||||
},
|
||||
prompt: tpl`Review priority PR #${ref("event.acme.item.number")}.`,
|
||||
outputs: {
|
||||
"acme.reply": { max: 3 },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const yamlIR = compileWorkflowYaml(yamlSource);
|
||||
|
||||
expect(JSON.stringify(dslIR)).toBe(JSON.stringify(yamlIR));
|
||||
expect(JSON.parse(JSON.stringify(yamlIR))).toEqual(yamlIR);
|
||||
expect(yamlIR.initial).toBe("run");
|
||||
expect(Object.keys(yamlIR.states)).toEqual(["run"]);
|
||||
expect(yamlIR.states["run"]?.kind).toBe("agent");
|
||||
});
|
||||
|
||||
it("compiles a full multi-step workflow with Zod schemas, integration waits, wait.workflow, gates, and sleep identically", () => {
|
||||
const FixOutputSchema = z.object({
|
||||
outcome: z.enum(["pr_ready", "needs_maintainer"]),
|
||||
pr_number: z.number(),
|
||||
head_sha: z.string(),
|
||||
});
|
||||
|
||||
const dslIR = defineWorkflow({
|
||||
id: "acme-issue-to-pr",
|
||||
on: {
|
||||
"acme.issue_created": {
|
||||
connection: "acme-main",
|
||||
filters: { repo: "acme/widget" },
|
||||
},
|
||||
},
|
||||
subject: {
|
||||
key: tpl`${ref("event.acme.repo")}#${ref("event.acme.issue_number")}`,
|
||||
onConflict: "ignore",
|
||||
},
|
||||
initial: "fix",
|
||||
steps: {
|
||||
fix: step.agent({
|
||||
maxLoops: 3,
|
||||
prompt: tpl`Fix #${ref("event.acme.issue_number")}.`,
|
||||
auth: { acme: { connection: "acme-main", scope: "write" } },
|
||||
output: FixOutputSchema,
|
||||
on: {
|
||||
pr_ready: "wait_ci",
|
||||
needs_maintainer: "maintainer_gate",
|
||||
max_loops_exceeded: "maintainer_gate",
|
||||
},
|
||||
}),
|
||||
wait_ci: step.integration("acme.wait_ci", {
|
||||
input: {
|
||||
repo: "acme/widget",
|
||||
pr_number: ref("steps.fix.outputs.pr_number"),
|
||||
head_sha: ref("steps.fix.outputs.head_sha"),
|
||||
},
|
||||
timeout: "90m",
|
||||
on: {
|
||||
green: "wait_review",
|
||||
red: "fix",
|
||||
timeout: "maintainer_gate",
|
||||
},
|
||||
}),
|
||||
wait_review: step.waitWorkflow({
|
||||
workflow: "acme-review",
|
||||
outputKey: tpl`review:acme/widget#${ref("steps.fix.outputs.pr_number")}@${ref("steps.fix.outputs.head_sha")}`,
|
||||
dispatchIfMissing: true,
|
||||
inputs: {
|
||||
pr_number: ref("steps.fix.outputs.pr_number"),
|
||||
head_sha: ref("steps.fix.outputs.head_sha"),
|
||||
},
|
||||
timeout: "1h",
|
||||
on: {
|
||||
approved: "cooldown",
|
||||
changes_requested: "fix",
|
||||
timeout: "maintainer_gate",
|
||||
},
|
||||
}),
|
||||
cooldown: step.sleep({
|
||||
duration: "5m",
|
||||
on: { done: "merge" },
|
||||
}),
|
||||
maintainer_gate: step.gate({
|
||||
title: tpl`Decision needed on #${ref("event.acme.issue_number")}`,
|
||||
summary: expr.coalesce(ref("steps.wait_review.outputs.reason"), "manual review"),
|
||||
recommended: "rework",
|
||||
choices: [
|
||||
{ id: "merge_anyway", label: "Merge anyway" },
|
||||
{ id: "rework", label: "Rework", description: "Try fix again" },
|
||||
],
|
||||
timeout: "14d",
|
||||
onTimeout: terminal.cancelled("gate_expired"),
|
||||
on: {
|
||||
merge_anyway: "merge",
|
||||
rework: "fix",
|
||||
},
|
||||
}),
|
||||
merge: step.integration("acme.merge_pr", {
|
||||
auth: { acme: { connection: "acme-main", scope: "write" } },
|
||||
input: {
|
||||
pr_number: ref("steps.fix.outputs.pr_number"),
|
||||
note: expr.coalesce(ref("gate.note"), "auto-merged"),
|
||||
},
|
||||
on: {
|
||||
merged: terminal.done(),
|
||||
conflict: "fix",
|
||||
},
|
||||
}),
|
||||
},
|
||||
publish: {
|
||||
key: tpl`issue:acme/widget#${ref("event.acme.issue_number")}`,
|
||||
payload: {
|
||||
pr_number: ref("steps.fix.outputs.pr_number"),
|
||||
head_sha: ref("steps.fix.outputs.head_sha"),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const yamlSource = `
|
||||
id: acme-issue-to-pr
|
||||
on:
|
||||
acme.issue_created:
|
||||
connection: acme-main
|
||||
filters:
|
||||
repo: acme/widget
|
||||
subject:
|
||||
key: "{{ event.acme.repo }}#{{ event.acme.issue_number }}"
|
||||
on_conflict: ignore
|
||||
initial: fix
|
||||
states:
|
||||
fix:
|
||||
kind: agent
|
||||
max_loops: 3
|
||||
prompt: "Fix #{{ event.acme.issue_number }}."
|
||||
auth:
|
||||
acme:
|
||||
connection: acme-main
|
||||
scope: write
|
||||
output:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
outcome:
|
||||
type: string
|
||||
enum: [pr_ready, needs_maintainer]
|
||||
pr_number:
|
||||
type: number
|
||||
head_sha:
|
||||
type: string
|
||||
required: [outcome, pr_number, head_sha]
|
||||
additionalProperties: false
|
||||
on:
|
||||
pr_ready: wait_ci
|
||||
needs_maintainer: maintainer_gate
|
||||
max_loops_exceeded: maintainer_gate
|
||||
wait_ci:
|
||||
kind: acme.wait_ci
|
||||
input:
|
||||
repo: acme/widget
|
||||
pr_number: "{{ steps.fix.outputs.pr_number }}"
|
||||
head_sha: "{{ steps.fix.outputs.head_sha }}"
|
||||
timeout: 90m
|
||||
on:
|
||||
green: wait_review
|
||||
red: fix
|
||||
timeout: maintainer_gate
|
||||
wait_review:
|
||||
kind: wait.workflow
|
||||
workflow: acme-review
|
||||
output_key: "review:acme/widget#{{ steps.fix.outputs.pr_number }}@{{ steps.fix.outputs.head_sha }}"
|
||||
dispatch_if_missing: true
|
||||
inputs:
|
||||
pr_number: "{{ steps.fix.outputs.pr_number }}"
|
||||
head_sha: "{{ steps.fix.outputs.head_sha }}"
|
||||
timeout: 1h
|
||||
on:
|
||||
approved: cooldown
|
||||
changes_requested: fix
|
||||
timeout: maintainer_gate
|
||||
cooldown:
|
||||
kind: sleep
|
||||
duration: 5m
|
||||
on:
|
||||
done: merge
|
||||
maintainer_gate:
|
||||
kind: gate
|
||||
title: "Decision needed on #{{ event.acme.issue_number }}"
|
||||
summary: "{{ steps.wait_review.outputs.reason ?? 'manual review' }}"
|
||||
recommended: rework
|
||||
choices:
|
||||
- { id: merge_anyway, label: Merge anyway }
|
||||
- { id: rework, label: Rework, description: Try fix again }
|
||||
timeout: 14d
|
||||
on_timeout:
|
||||
terminal: cancelled
|
||||
reason: gate_expired
|
||||
on:
|
||||
merge_anyway: merge
|
||||
rework: fix
|
||||
merge:
|
||||
kind: acme.merge_pr
|
||||
auth:
|
||||
acme:
|
||||
connection: acme-main
|
||||
scope: write
|
||||
input:
|
||||
pr_number: "{{ steps.fix.outputs.pr_number }}"
|
||||
note: "{{ gate.note ?? 'auto-merged' }}"
|
||||
on:
|
||||
merged: done
|
||||
conflict: fix
|
||||
publish:
|
||||
key: "issue:acme/widget#{{ event.acme.issue_number }}"
|
||||
payload:
|
||||
pr_number: "{{ steps.fix.outputs.pr_number }}"
|
||||
head_sha: "{{ steps.fix.outputs.head_sha }}"
|
||||
`;
|
||||
|
||||
const yamlIR = compileWorkflowYaml(yamlSource);
|
||||
|
||||
expect(JSON.stringify(dslIR)).toBe(JSON.stringify(yamlIR));
|
||||
expect(validateWorkflowIR(JSON.parse(JSON.stringify(dslIR)) as WorkflowIR)).toEqual(dslIR);
|
||||
});
|
||||
|
||||
it("compiles scheduled 1-state trigger shorthand with recurrence unchanged", () => {
|
||||
const scheduledYaml = `
|
||||
name: acme-scheduled-sweep
|
||||
enabled: false
|
||||
on:
|
||||
manual.run: {}
|
||||
schedule.tick:
|
||||
recurrence:
|
||||
start: "2026-10-13T12:20:00"
|
||||
rule: "FREQ=HOURLY;INTERVAL=2;BYMINUTE=20;BYSECOND=0"
|
||||
timezone: "Europe/Berlin"
|
||||
run:
|
||||
target:
|
||||
daemon: factory
|
||||
cwd: /srv/acme/bot
|
||||
agent:
|
||||
provider: codex
|
||||
model: gpt-6.1-terra
|
||||
mode: full-access
|
||||
thinkingOptionId: medium
|
||||
continuation:
|
||||
mode: new
|
||||
max_runtime: 40m
|
||||
idle_timeout: 10m
|
||||
auto_archive: true
|
||||
background: true
|
||||
acme:
|
||||
connection: acme-main
|
||||
repositories: [acme/widget]
|
||||
permissions:
|
||||
issues: write
|
||||
duration: 1h
|
||||
prompt: |
|
||||
Run sweep.
|
||||
\${{ paseo.prompt }}
|
||||
`;
|
||||
const ir = compileWorkflowYaml(scheduledYaml);
|
||||
expect(ir.id).toBe("acme-scheduled-sweep");
|
||||
expect(ir.enabled).toBe(false);
|
||||
expect(ir.initial).toBe("run");
|
||||
expect(ir.on["schedule.tick"]?.recurrence?.rule).toContain("FREQ=HOURLY");
|
||||
const runStep = ir.states["run"];
|
||||
expect(runStep?.kind).toBe("agent");
|
||||
if (runStep?.kind === "agent") {
|
||||
expect(runStep.auth?.["acme"]?.connection).toBe("acme-main");
|
||||
}
|
||||
});
|
||||
|
||||
it("compiles ALL 19 real factory trigger YAML files in ~/dev/skills/hub/.paseo/triggers/ read-only when present", () => {
|
||||
const triggersDir = path.join(homedir(), "dev", "skills", "hub", ".paseo", "triggers");
|
||||
if (!existsSync(triggersDir)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const files = readdirSync(triggersDir)
|
||||
.filter((name) => name.endsWith(".yml") || name.endsWith(".yaml"))
|
||||
.sort();
|
||||
|
||||
expect(files.length).toBeGreaterThanOrEqual(19);
|
||||
|
||||
for (const file of files) {
|
||||
const source = readFileSync(path.join(triggersDir, file), "utf8");
|
||||
const ir = compileWorkflowYaml(source);
|
||||
const roundTripped = JSON.parse(JSON.stringify(ir)) as WorkflowIR;
|
||||
validateWorkflowIR(roundTripped);
|
||||
|
||||
expect(roundTripped.version, file).toBe(1);
|
||||
expect(roundTripped.id.length, file).toBeGreaterThan(0);
|
||||
expect(roundTripped.initial, file).toBe("run");
|
||||
expect(Object.keys(roundTripped.states), file).toEqual(["run"]);
|
||||
expect(roundTripped.states["run"]?.kind, file).toBe("agent");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,202 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { defineWorkflow, expr, ref, step, terminal, tpl } from "../src/dsl.js";
|
||||
import {
|
||||
evaluateExpression,
|
||||
evaluateStringExpression,
|
||||
parseExpression,
|
||||
parseTemplateExpression,
|
||||
type ExpressionContext,
|
||||
} from "../src/internal/expression.js";
|
||||
import { validateWorkflowIR, WorkflowValidationError, type WorkflowIR } from "../src/ir.js";
|
||||
|
||||
const sampleContext: ExpressionContext = {
|
||||
event: {
|
||||
acme: {
|
||||
repo: "acme/widget",
|
||||
item: { number: 42 },
|
||||
},
|
||||
},
|
||||
prompt: "Please inspect this issue",
|
||||
inputs: { repo: "acme/override", retries: 3 },
|
||||
subject: { key: "acme/widget#42", data: { priority: "p0" } },
|
||||
steps: {
|
||||
reproduce: {
|
||||
outcome: "reproduced",
|
||||
outputs: { root_cause: "race condition", contributor_pr: null },
|
||||
attempts: 1,
|
||||
},
|
||||
fix: {
|
||||
outcome: "pr_ready",
|
||||
outputs: { pr_number: 108, head_sha: "abc123" },
|
||||
attempts: 2,
|
||||
},
|
||||
},
|
||||
gate: { choice: "rework", note: "add a regression test", actor: "alice" },
|
||||
values: {
|
||||
active_pr: parseExpression(
|
||||
"steps.fix.outputs.pr_number ?? steps.reproduce.outputs.contributor_pr",
|
||||
),
|
||||
},
|
||||
executionId: "exec_99",
|
||||
};
|
||||
|
||||
describe("expressions and templates", () => {
|
||||
it("parses both ${{ ... }} and {{ ... }} to identical ASTs and evaluates all namespaces", () => {
|
||||
const dollarAst = parseTemplateExpression(
|
||||
"Issue #${{ event.acme.item.number }} ({{ execution.id }})",
|
||||
);
|
||||
const bareAst = parseTemplateExpression(
|
||||
"Issue #{{ event.acme.item.number }} (${{ paseo.execution.id }})",
|
||||
);
|
||||
const dslAst = tpl`Issue #${ref("event.acme.item.number")} (${expr.executionId()})`;
|
||||
|
||||
expect(JSON.stringify(dollarAst)).toBe(JSON.stringify(bareAst));
|
||||
expect(JSON.stringify(dollarAst)).toBe(JSON.stringify(dslAst));
|
||||
|
||||
expect(evaluateStringExpression(dollarAst, sampleContext)).toBe("Issue #42 (exec_99)");
|
||||
expect(evaluateExpression(parseExpression("paseo.context.acme.repo"), sampleContext)).toBe(
|
||||
"acme/widget",
|
||||
);
|
||||
expect(evaluateExpression(parseExpression("paseo.inputs.repo"), sampleContext)).toBe(
|
||||
"acme/override",
|
||||
);
|
||||
expect(evaluateExpression(parseExpression("paseo.prompt"), sampleContext)).toBe(
|
||||
"Please inspect this issue",
|
||||
);
|
||||
expect(evaluateExpression(parseExpression("subject.key"), sampleContext)).toBe(
|
||||
"acme/widget#42",
|
||||
);
|
||||
expect(evaluateExpression(parseExpression("subject.data.priority"), sampleContext)).toBe("p0");
|
||||
expect(evaluateExpression(parseExpression("steps.fix.attempts"), sampleContext)).toBe(2);
|
||||
expect(evaluateExpression(parseExpression("steps.fix.outcome"), sampleContext)).toBe(
|
||||
"pr_ready",
|
||||
);
|
||||
expect(evaluateExpression(parseExpression("gate.note"), sampleContext)).toBe(
|
||||
"add a regression test",
|
||||
);
|
||||
expect(evaluateExpression(parseExpression("values.active_pr"), sampleContext)).toBe(108);
|
||||
});
|
||||
|
||||
it("preserves typed non-string values for standalone interpolations", () => {
|
||||
const numExpr = parseTemplateExpression("${{ steps.fix.outputs.pr_number }}");
|
||||
expect(evaluateExpression(numExpr, sampleContext)).toBe(108);
|
||||
|
||||
const boolExpr = parseTemplateExpression("{{ steps.fix.outcome == 'pr_ready' && !false }}");
|
||||
expect(evaluateExpression(boolExpr, sampleContext)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("static WorkflowIR validation", () => {
|
||||
it("rejects unknown transition target states", () => {
|
||||
expect(() =>
|
||||
defineWorkflow({
|
||||
id: "bad-target",
|
||||
on: { "acme.go": {} },
|
||||
initial: "first",
|
||||
steps: {
|
||||
first: step.agent({
|
||||
prompt: "hi",
|
||||
on: { ok: "does_not_exist" },
|
||||
}),
|
||||
},
|
||||
}),
|
||||
).toThrowError(WorkflowValidationError);
|
||||
});
|
||||
|
||||
it("rejects unguarded cycles lacking maxLoops + max_loops_exceeded", () => {
|
||||
expect(() =>
|
||||
defineWorkflow({
|
||||
id: "unguarded-cycle",
|
||||
on: { "acme.go": {} },
|
||||
initial: "a",
|
||||
steps: {
|
||||
a: step.agent({ prompt: "a", on: { ok: "b" } }),
|
||||
b: step.agent({ prompt: "b", on: { retry: "a", ok: terminal.done() } }),
|
||||
},
|
||||
}),
|
||||
).toThrowError(/unguarded cycle/i);
|
||||
});
|
||||
|
||||
it("rejects cycles with maxLoops set but missing max_loops_exceeded transition", () => {
|
||||
expect(() =>
|
||||
defineWorkflow({
|
||||
id: "missing-exceeded",
|
||||
on: { "acme.go": {} },
|
||||
initial: "a",
|
||||
steps: {
|
||||
a: step.agent({ prompt: "a", maxLoops: 3, on: { ok: "b" } }),
|
||||
b: step.agent({ prompt: "b", on: { retry: "a", ok: terminal.done() } }),
|
||||
},
|
||||
}),
|
||||
).toThrowError(/unguarded cycle/i);
|
||||
});
|
||||
|
||||
it("accepts cycles guarded by maxLoops + on.max_loops_exceeded", () => {
|
||||
const ir = defineWorkflow({
|
||||
id: "guarded-cycle",
|
||||
on: { "acme.go": {} },
|
||||
initial: "a",
|
||||
steps: {
|
||||
a: step.agent({
|
||||
prompt: "a",
|
||||
maxLoops: 3,
|
||||
on: { ok: "b", max_loops_exceeded: terminal.failed("loop_limit") },
|
||||
}),
|
||||
b: step.agent({ prompt: "b", on: { retry: "a", ok: terminal.done() } }),
|
||||
},
|
||||
});
|
||||
expect(validateWorkflowIR(JSON.parse(JSON.stringify(ir)))).toEqual(ir);
|
||||
});
|
||||
|
||||
it("rejects expressions referencing nonexistent steps", () => {
|
||||
expect(() =>
|
||||
defineWorkflow({
|
||||
id: "bad-step-ref",
|
||||
on: { "acme.go": {} },
|
||||
initial: "first",
|
||||
steps: {
|
||||
first: step.agent({
|
||||
prompt: tpl`Look at ${ref("steps.ghost.outputs.pr_number")}`,
|
||||
on: { ok: terminal.done() },
|
||||
}),
|
||||
},
|
||||
}),
|
||||
).toThrowError(/unknown step "ghost"/i);
|
||||
});
|
||||
|
||||
it("rejects invalid gate recommended choice and invalid sleep config", () => {
|
||||
expect(() =>
|
||||
defineWorkflow({
|
||||
id: "bad-gate",
|
||||
on: { "acme.go": {} },
|
||||
initial: "ask",
|
||||
steps: {
|
||||
ask: step.gate({
|
||||
title: "Decide",
|
||||
recommended: "missing",
|
||||
choices: [{ id: "yes", label: "Yes" }],
|
||||
on: { yes: terminal.done() },
|
||||
}),
|
||||
},
|
||||
}),
|
||||
).toThrowError(/recommended choice "missing"/i);
|
||||
|
||||
const invalidSleep: WorkflowIR = {
|
||||
version: 1,
|
||||
id: "bad-sleep",
|
||||
enabled: true,
|
||||
on: { "acme.go": {} },
|
||||
initial: "nap",
|
||||
states: {
|
||||
nap: {
|
||||
id: "nap",
|
||||
kind: "sleep",
|
||||
on: { done: { terminal: "done" } },
|
||||
},
|
||||
},
|
||||
};
|
||||
expect(() => validateWorkflowIR(invalidSleep)).toThrowError(
|
||||
/exactly one of durationMs or until/i,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2023",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"lib": ["ES2023", "DOM"],
|
||||
"types": [],
|
||||
"skipLibCheck": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist", "test"]
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"],
|
||||
"rootDir": ".",
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["src/**/*", "test/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
@@ -1017,3 +1017,212 @@ child.on("exit", (code) => process.exit(code ?? 1));
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("advertises form elicitation and bridges Antigravity ask_question into a question card even in default Full access mode", async () => {
|
||||
const { directory, launch } = await launchAgent(`
|
||||
const { createInterface } = require("node:readline");
|
||||
const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n");
|
||||
let clientCapabilities = null;
|
||||
let promptId = null;
|
||||
createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
const message = JSON.parse(line);
|
||||
if (message.method === "initialize") {
|
||||
clientCapabilities = message.params.clientCapabilities;
|
||||
send({ id: message.id, result: { protocolVersion: 1 } });
|
||||
return;
|
||||
}
|
||||
if (message.method === "session/new") {
|
||||
send({
|
||||
id: message.id,
|
||||
result: {
|
||||
sessionId: "agy-q",
|
||||
modes: {
|
||||
currentModeId: "default",
|
||||
availableModes: [{ id: "default", name: "Default" }],
|
||||
},
|
||||
},
|
||||
});
|
||||
send({
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "agy-q",
|
||||
update: { sessionUpdate: "available_commands_update", availableCommands: [] },
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (message.method === "session/prompt") {
|
||||
promptId = message.id;
|
||||
if (!clientCapabilities?.elicitation?.form) {
|
||||
send({
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "agy-q",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "- [1] Red\\n- [2] Blue" },
|
||||
},
|
||||
},
|
||||
});
|
||||
send({ id: message.id, result: { stopReason: "end_turn" } });
|
||||
return;
|
||||
}
|
||||
send({
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "agy-q",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "ask-1",
|
||||
name: "ask_question",
|
||||
title: "Run ask_question",
|
||||
kind: "other",
|
||||
status: "in_progress",
|
||||
rawInput: {
|
||||
questions: [
|
||||
{ question: "Pick a color:", options: ["Red", "Blue"], is_multi_select: false },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
send({
|
||||
id: "elicit-1",
|
||||
method: "elicitation/create",
|
||||
params: {
|
||||
sessionId: "agy-q",
|
||||
toolCallId: "ask-1",
|
||||
mode: "form",
|
||||
message: "The agent has a question.",
|
||||
requestedSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
q1: {
|
||||
type: "string",
|
||||
title: "Pick a color:",
|
||||
oneOf: [
|
||||
{ const: "1", title: "Red" },
|
||||
{ const: "2", title: "Blue" },
|
||||
],
|
||||
},
|
||||
q1_other: {
|
||||
type: "string",
|
||||
title: "Other",
|
||||
description: "Optional free-form answer to: Pick a color:",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (message.id === "elicit-1") {
|
||||
send({
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "agy-q",
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "ask-1",
|
||||
status: "completed",
|
||||
},
|
||||
},
|
||||
});
|
||||
send({
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "agy-q",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "Answer: " + JSON.stringify(message.result) },
|
||||
},
|
||||
},
|
||||
});
|
||||
send({ id: promptId, result: { stopReason: "end_turn" } });
|
||||
return;
|
||||
}
|
||||
if (message.method === "session/close") send({ id: message.id, result: {} });
|
||||
});
|
||||
`);
|
||||
const connection = await createAntigravityProvider().connect({
|
||||
launch,
|
||||
versions: [1],
|
||||
capabilities: ["prompt.message", "permission", "session.configure"],
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
await connection.send({
|
||||
type: "session.open",
|
||||
requestId: "open",
|
||||
sessionId: "test",
|
||||
history: "skip",
|
||||
config: { cwd: directory, env: {}, mcpServers: {}, settings: {}, persist: false },
|
||||
});
|
||||
await expect.poll(() => events.find((event) => event.type === "session.ready")).toBeDefined();
|
||||
await connection.send({
|
||||
type: "session.prompt",
|
||||
sessionId: "test",
|
||||
prompt: {
|
||||
clientMessageId: "ask-turn",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "Ask me a color" }] },
|
||||
},
|
||||
});
|
||||
await expect
|
||||
.poll(() => events.find((event) => event.type === "session.permission"))
|
||||
.toMatchObject({
|
||||
type: "session.permission",
|
||||
request: {
|
||||
name: "ask_question",
|
||||
kind: "question",
|
||||
input: {
|
||||
questions: [
|
||||
expect.objectContaining({
|
||||
header: "Question",
|
||||
question: "Pick a color:",
|
||||
options: [{ label: "Red" }, { label: "Blue" }],
|
||||
allowOther: true,
|
||||
allowEmpty: false,
|
||||
placeholder: "Optional free-form answer to: Pick a color:",
|
||||
}),
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
const permission = events.find((event) => event.type === "session.permission");
|
||||
if (permission?.type !== "session.permission") throw new Error("Expected permission");
|
||||
await connection.send({
|
||||
type: "session.permission",
|
||||
sessionId: "test",
|
||||
permissionId: permission.request.id,
|
||||
response: { behavior: "allow", updatedInput: { answers: { Question: "Blue" } } },
|
||||
});
|
||||
await expect
|
||||
.poll(() =>
|
||||
events.find(
|
||||
(event) =>
|
||||
event.type === "session.permission_resolved" &&
|
||||
event.permissionId === permission.request.id,
|
||||
),
|
||||
)
|
||||
.toBeDefined();
|
||||
await expect
|
||||
.poll(() =>
|
||||
events.find(
|
||||
(event) =>
|
||||
event.type === "timeline.item" &&
|
||||
event.item.type === "assistant_message" &&
|
||||
event.item.text.includes('"q1":"2"'),
|
||||
),
|
||||
)
|
||||
.toBeDefined();
|
||||
await expect
|
||||
.poll(() =>
|
||||
events.find((event) => event.type === "session.turn" && event.state === "completed"),
|
||||
)
|
||||
.toBeDefined();
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -269,6 +269,7 @@ test("PR routing declares stable behavior ownership", () => {
|
||||
"packages/client/**",
|
||||
"packages/highlight/**",
|
||||
"packages/protocol/**",
|
||||
"packages/workflows/**",
|
||||
],
|
||||
browser: [
|
||||
"packages/server/src/server/agent/provider-snapshot-manager.ts",
|
||||
@@ -548,6 +549,8 @@ test("quality preserves commands and routes each domain independently after fail
|
||||
"npm run test --workspace=@getpaseo/protocol",
|
||||
"npm run test --workspace=@getpaseo/client",
|
||||
"npm run test --workspace=@getpaseo/highlight",
|
||||
"npm run build:workflows",
|
||||
"npm run test --workspace=@getpaseo/workflows",
|
||||
"npm run typecheck:examples --workspace=@getpaseo/client",
|
||||
],
|
||||
};
|
||||
|
||||
@@ -27,6 +27,10 @@ const dependencySections = [
|
||||
"optionalDependencies",
|
||||
];
|
||||
|
||||
// Packages with independent semver lifecycles stay on their own version until
|
||||
// folded into the main Paseo release train.
|
||||
const INDEPENDENT_VERSION_WORKSPACES = new Set(["@getpaseo/workflows"]);
|
||||
|
||||
const touched = [];
|
||||
|
||||
for (const workspacePath of workspacePaths) {
|
||||
@@ -36,6 +40,9 @@ for (const workspacePath of workspacePaths) {
|
||||
}
|
||||
|
||||
const pkg = JSON.parse(readFileSync(packagePath, "utf8"));
|
||||
if (INDEPENDENT_VERSION_WORKSPACES.has(pkg.name)) {
|
||||
continue;
|
||||
}
|
||||
let changed = false;
|
||||
|
||||
if (pkg.version !== rootVersion) {
|
||||
|
||||