From 0eb38f16037ee3d9ecc961356af6e34da36b9071 Mon Sep 17 00:00:00 2001 From: Brendan Date: Wed, 16 Sep 2026 22:06:31 +0000 Subject: [PATCH] Remove custom webhooks and legacy flows --- README.md | 14 +- docs/cloudflare-tail.md | 14 +- docs/custom-sources-rollout.md | 9 -- docs/job-trigger-context.md | 3 +- docs/legacy-removal.md | 7 + packages/app/public/styles.css | 2 +- packages/app/src/custom-handler.ts | 35 +---- packages/app/src/flow-schemas.ts | 20 --- packages/app/src/flow-service.ts | 47 +----- packages/app/src/index.ts | 132 +---------------- packages/app/src/protected-api.ts | 27 +--- packages/app/src/source-lifecycle.ts | 53 ------- packages/app/src/tenant.ts | 147 +++---------------- packages/app/src/trigger-context.ts | 7 +- packages/app/src/types.ts | 29 ---- packages/app/src/ui.ts | 161 +-------------------- packages/app/src/webhook-trigger.ts | 2 +- packages/app/src/worker.ts | 2 +- packages/app/test/custom-handler.test.ts | 30 +--- packages/app/test/device-oauth.e2e.test.ts | 2 +- packages/app/test/flow-service.test.ts | 40 +---- packages/app/test/source-lifecycle.test.ts | 20 --- packages/app/test/trigger-context.test.ts | 3 +- packages/app/test/ui.test.ts | 84 +---------- packages/app/test/webhook-trigger.test.ts | 4 +- packages/app/test/worker.test.ts | 89 +----------- packages/app/wrangler.jsonc | 3 +- 27 files changed, 92 insertions(+), 894 deletions(-) delete mode 100644 docs/custom-sources-rollout.md create mode 100644 docs/legacy-removal.md delete mode 100644 packages/app/src/source-lifecycle.ts delete mode 100644 packages/app/test/source-lifecycle.test.ts diff --git a/README.md b/README.md index 5a1ea702..1dac7dd5 100644 --- a/README.md +++ b/README.md @@ -90,15 +90,15 @@ Use authorization-code OAuth and enable **Webhooks** on the OAuth application. C After changing the webhook settings, re-authorize existing workspaces so Linear creates a fresh workspace subscription. -## Create a flow +## Create a Job 1. Sign in with Linear. 2. Connect your exe.dev VM using its restricted HTTPS API token. Use the same user-qualified SSH destination you use interactively so Factorize and your terminal join the same Herdr session. -3. Create a flow, select a Linear project, and add matching rules. Every rule must match. +3. Create a Job, choose its execution target, and add authenticated provider triggers. Every Linear matching rule must match. -Matching issue updates queue work up to the flow’s configured concurrency. When a run finishes, Factorize fills its slot from the queue and posts a link to the Herdr session in Linear. +Matching provider events queue work up to the Job’s configured concurrency. When a run finishes, Factorize fills its slot from the queue and posts a link to the Herdr session in Linear. -Cloudflare Worker failures can also start flows through the separately deployable Tail relay. See [Cloudflare Tail flow source](docs/cloudflare-tail.md). +Cloudflare Worker failures can also start Jobs through the separately deployable Tail relay. See [Cloudflare Tail job trigger](docs/cloudflare-tail.md). ## Configuration reference @@ -138,7 +138,7 @@ The versioned API is rooted at `/api/v1`: ```bash curl -H "Authorization: Bearer $FACTORIZE_ACCESS_TOKEN" \ - https://app.factorize.sh/api/v1/flows + https://app.factorize.sh/api/v1/jobs curl -H "Authorization: Bearer $FACTORIZE_ACCESS_TOKEN" \ 'https://app.factorize.sh/api/v1/runs?jobId=JOB_ID&state=running&contextQuery=customer%20impact&limit=25' @@ -150,7 +150,7 @@ curl -X POST -H "Authorization: Bearer $FACTORIZE_ACCESS_TOKEN" \ https://app.factorize.sh/api/v1/runs/RUN_ID/stop ``` -Flow CRUD is available at `/flows` and `/flows/:id`; supporting collections are `/projects`, `/flow-options`, `/runs`, and `/flow-events`. Run and event collections return `{ "items": [...], "nextCursor": "..." }`; pass `nextCursor` back as the `cursor` query parameter. Runs can be filtered by `jobId`, `state`, and `contextQuery`; context queries use case-insensitive literal substring matching and matching items contain a bounded `context_excerpt`, never the full context. `GET /runs/:runId` returns the complete structured trigger `context` and invocation metadata, including the firing `trigger_id`. Legacy runs return `null` for `context` and `invocation`. The canonical Job prompt contract is documented in [docs/job-trigger-context.md](docs/job-trigger-context.md). Errors consistently use `{ "error": { "code": "...", "message": "..." } }`. +Job CRUD is available at `/jobs` and `/jobs/:id`. Run collections return `{ "items": [...], "nextCursor": "..." }`; pass `nextCursor` back as the `cursor` query parameter. Runs can be filtered by `jobId`, `state`, and `contextQuery`; context queries use case-insensitive literal substring matching and matching items contain a bounded `context_excerpt`, never the full context. `GET /runs/:runId` returns the complete structured trigger `context` and invocation metadata, including the firing `trigger_id`. The canonical Job prompt contract is documented in [docs/job-trigger-context.md](docs/job-trigger-context.md). Errors consistently use `{ "error": { "code": "...", "message": "..." } }`. ## MCP clients @@ -160,7 +160,7 @@ Configure a compatible remote MCP client with this single URL: https://app.factorize.sh/mcp ``` -The client discovers OAuth automatically, opens Factorize in a browser, completes Linear sign-in if necessary, requests consent, and returns to the client after PKCE authorization. No Linear or exe.dev credential is copied into the MCP client. The server is stateless Streamable HTTP and exposes flow CRUD, projects/options, run inspection/filtering, webhook activity, and active-run stopping tools. +The client discovers OAuth automatically, opens Factorize in a browser, completes Linear sign-in if necessary, requests consent, and returns to the client after PKCE authorization. No Linear or exe.dev credential is copied into the MCP client. The server is stateless Streamable HTTP and exposes Job CRUD, run inspection/filtering, provider webhook activity, and active-run stopping tools. Factorize also supports the OAuth 2.0 Device Authorization Grant (RFC 8628) for headless clients. Discovery advertises `device_authorization_endpoint`; clients obtain a code from `POST /oauth/device_authorization`, direct the user to `/device`, and poll `/oauth/token` with grant type `urn:ietf:params:oauth:grant-type:device_code`. Device codes expire after ten minutes, polling is rate-limited, and approved grants use the same scoped access and refresh tokens, tenant checks, and revocation behavior as browser PKCE authorization. diff --git a/docs/cloudflare-tail.md b/docs/cloudflare-tail.md index 1c89e747..0c26630f 100644 --- a/docs/cloudflare-tail.md +++ b/docs/cloudflare-tail.md @@ -1,10 +1,10 @@ -# Cloudflare Tail flow source +# Cloudflare Tail job trigger -Cloudflare Tail is a Factorize flow source for native uncaught Worker exceptions and structured `console.error` failures. Tail Workers require a Workers Paid or Enterprise plan. The relay is a separate Cloudflare Worker and must be deployed in the same Cloudflare account as the producer Workers; the Factorize app Worker may be in any account. +Cloudflare Tail is an authenticated Factorize Job trigger for native uncaught Worker exceptions and structured `console.error` failures. Tail Workers require a Workers Paid or Enterprise plan. The relay is a separate Cloudflare Worker and must be deployed in the same Cloudflare account as the producer Workers; the Factorize app Worker may be in any account. -## Configure the flow and relay +## Configure the job and relay -1. Create a flow, choose **Cloudflare Tail**, and save it. On the edit page, copy the relay destination and signing secret. You can show, copy, edit, or generate a replacement secret there; replacements remain local until **Save Changes** succeeds. +1. Create a Job, add a **Cloudflare Tail** trigger, and save it. Copy its relay destination and signing secret. 2. From the repository root, run `npm ci` and set `FACTORIZE_TAIL_DESTINATION` as a Wrangler variable in `packages/tail-relay/wrangler.jsonc`. 3. Authenticate Wrangler to the producer Workers' Cloudflare account, then run `npm exec --workspace=factorize-tail-relay -- wrangler secret put FACTORIZE_TAIL_SECRET` and `npm run deploy:tail-relay`. Keep the relay name `factorize-tail-relay`; Factorize excludes its own relay traces to prevent loops. 4. Add the relay to every producer Worker. One relay can consume multiple producers and forwards each event with its `scriptName`: @@ -15,9 +15,9 @@ Cloudflare Tail is a Factorize flow source for native uncaught Worker exceptions } ``` -Deploy each producer after changing `tail_consumers`. In the flow activity page, use the owner-only **Test Cloudflare Tail delivery** action before enabling concurrency/automation. The synthetic exception traverses the same isolated handler and normal queue path. +Deploy each producer after changing `tail_consumers`. -MCP clients should call `list_exe_connections`, select a `connectionId`, then call `create_flow` with `source: { "kind": "cloudflareTail" }`. The response contains the relay destination but never the signing secret. Omit `handlerCode` for the default exception/`console.error` filter. Protected REST and MCP cannot read or replace the secret; authenticated owners rotate it on the edit page and must then update `FACTORIZE_TAIL_SECRET` in Wrangler and redeploy the relay. +MCP clients create or update a Job with a `cloudflareTail` webhook trigger and an execution target returned by `list_execution_targets`. Protected REST and MCP never return the signing secret. After rotating it, update `FACTORIZE_TAIL_SECRET` in Wrangler and redeploy the relay. The relay redacts sensitive key names (authorization, cookies, tokens, secrets, credentials, prompts, and bodies), truncates oversized structures, signs the exact body with HMAC-SHA256, and aborts delivery after three seconds. Factorize sanitizes again before activity or agent context, rejects deliveries older than 60 seconds, deduplicates delivery IDs, and rate-limits repeated event fingerprints. @@ -27,4 +27,4 @@ For caught internal failures, log a structured event: console.error(JSON.stringify({ event: "factorize_unexpected_failure", component: "billing", message: error.message })); ``` -Do not include request bodies, headers, credentials, or prompts in the structured log. Expected 4xx/domain failures remain ordinary Tail events unless the flow handler explicitly accepts them. +Do not include request bodies, headers, credentials, or prompts in the structured log. Expected 4xx/domain failures remain ordinary Tail events unless the Job handler explicitly accepts them. diff --git a/docs/custom-sources-rollout.md b/docs/custom-sources-rollout.md deleted file mode 100644 index 1c973ce3..00000000 --- a/docs/custom-sources-rollout.md +++ /dev/null @@ -1,9 +0,0 @@ -# Custom source rollout - -Custom sources remain disabled unless `CUSTOM_SOURCES_ENABLED=true`. Before enabling them: - -1. Confirm the `CUSTOM_HANDLER_LOADER` Dynamic Worker Loader binding is available in production. -2. Run production probes that attempt HTTP and TCP egress, service binding access, cache persistence, and reads of secrets and every supported binding. Dynamic handlers receive an empty environment and `globalOutbound: null`; enable only when every access fails. -3. Enable one internal tenant and monitor invocation failures, CPU termination, and overflow drops. - -Custom triggers are intentionally lossy once a flow has 100 pending jobs. Valid signed provider deliveries are still acknowledged to prevent retry storms. diff --git a/docs/job-trigger-context.md b/docs/job-trigger-context.md index dcdc2bcd..5e3d47f1 100644 --- a/docs/job-trigger-context.md +++ b/docs/job-trigger-context.md @@ -19,10 +19,9 @@ The available value beneath a slug is: | Linear webhook | Complete Linear delivery, plus `provider`, `event`, `delivery_id` | | GitHub webhook | Complete GitHub delivery, plus `provider`, `event`, `delivery_id` | | Cloudflare Tail | Complete sanitized Tail delivery, plus `provider`, `event`, `delivery_id` | -| Custom webhook | Complete submitted JSON delivery, plus `provider`, `event`, `delivery_id` | | Job lifecycle | `source_job_id`, `source_run_id`, `final_state`, `transitioned_at`, `observation_destination` | -Every trigger returned by `GET /api/v1/jobs` and `GET /api/v1/jobs/:id` (and the corresponding MCP `list_jobs` and `get_job` tools) includes a `reflection` object. It contains the stable `slug`, trigger kind/provider, whether the result is dynamic, and a flat `paths` list with nested path, basic value type, description, and occasional example. The Job editor consumes this same canonical contract for Mustache autocomplete. A custom webhook, or any webhook with a replacing handler, reports `dynamic: true` and an explicit `*`/`unknown` fallback because arbitrary handler output cannot be inferred safely. +Every trigger returned by `GET /api/v1/jobs` and `GET /api/v1/jobs/:id` (and the corresponding MCP `list_jobs` and `get_job` tools) includes a `reflection` object. It contains the stable `slug`, trigger kind/provider, whether the result is dynamic, and a flat `paths` list with nested path, basic value type, description, and occasional example. The Job editor consumes this same canonical contract for Mustache autocomplete. A webhook with a replacing handler reports `dynamic: true` and an explicit `*`/`unknown` fallback because arbitrary handler output cannot be inferred safely. Manual invocation accepts `{ "prompt": "...", "idempotencyKey": "..." }`. Parameter defaults and invocation, schedule, or webhook parameter overrides are not accepted. diff --git a/docs/legacy-removal.md b/docs/legacy-removal.md new file mode 100644 index 00000000..946dcc7e --- /dev/null +++ b/docs/legacy-removal.md @@ -0,0 +1,7 @@ +# Legacy removal rollout + +Generic custom webhooks and the legacy Flow product are no longer accepted or exposed. Only Jobs and authenticated Linear, GitHub, and signed Cloudflare Tail triggers are supported. + +Deploy the application before removing stored legacy data so old endpoints fail closed with `404` and no unsupported record can launch work. Existing `pipes`, Flow event, custom-source, and legacy delivery rows are inert after deployment and may be deleted during a maintenance window. Preserve `jobs`, `triggers`, `invocations`, `job_runs`, and execution/run records associated with a Job ID. + +Before deletion, export any audit data that must be retained. There is intentionally no automatic bridge from a Flow or generic custom webhook to a Job because trigger provenance and authentication cannot be inferred safely. Recreate wanted automation as a Job with an authenticated provider trigger. diff --git a/packages/app/public/styles.css b/packages/app/public/styles.css index 29f709e6..25598eb3 100644 --- a/packages/app/public/styles.css +++ b/packages/app/public/styles.css @@ -1,2 +1,2 @@ /*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */ -@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-space-y-reverse:0;--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial}}}@layer theme{:root,:host{--font-sans:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-50:oklch(97.1% .013 17.38);--color-red-200:oklch(88.5% .062 18.334);--color-red-300:oklch(80.8% .114 19.571);--color-red-400:oklch(70.4% .191 22.216);--color-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-red-700:oklch(50.5% .213 27.518);--color-red-800:oklch(44.4% .177 26.899);--color-red-900:oklch(39.6% .141 25.723);--color-red-950:oklch(25.8% .092 26.042);--color-amber-50:oklch(98.7% .022 95.277);--color-amber-100:oklch(96.2% .059 95.617);--color-amber-200:oklch(92.4% .12 95.746);--color-amber-300:oklch(87.9% .169 91.605);--color-amber-800:oklch(47.3% .137 46.201);--color-amber-900:oklch(41.4% .112 45.904);--color-amber-950:oklch(27.9% .077 45.635);--color-green-100:oklch(96.2% .044 156.743);--color-green-200:oklch(92.5% .084 155.995);--color-green-500:oklch(72.3% .219 149.579);--color-green-600:oklch(62.7% .194 149.214);--color-green-800:oklch(44.8% .119 151.328);--color-green-950:oklch(26.6% .065 152.934);--color-blue-500:oklch(62.3% .214 259.815);--color-slate-100:#f5f1e8;--color-slate-200:#e7e1d4;--color-slate-300:#cec5b4;--color-slate-400:#9b9282;--color-slate-500:#71695e;--color-slate-600:#575047;--color-slate-700:#403b34;--color-slate-800:#2c2924;--color-slate-900:#201e1a;--color-slate-950:#151410;--color-stone-50:#fcfbf6;--color-stone-100:#f6f3e9;--color-stone-200:#e6e0d1;--color-stone-300:#d4cbb9;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--container-xl:36rem;--container-2xl:42rem;--container-3xl:48rem;--container-4xl:56rem;--container-5xl:64rem;--container-6xl:72rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75 / 1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-3xl:1.875rem;--text-3xl--line-height:calc(2.25 / 1.875);--text-4xl:2.25rem;--text-4xl--line-height:calc(2.5 / 2.25);--text-5xl:3rem;--text-5xl--line-height:1;--text-7xl:4.5rem;--text-7xl--line-height:1;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--tracking-wide:.025em;--radius-lg:.5rem;--radius-xl:.75rem;--radius-2xl:1rem;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--color-factorize-50:#fff9e6;--color-factorize-100:#fff0b8;--color-factorize-500:#fdc901;--color-factorize-600:#896300;--color-factorize-700:#705000}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components{.field{margin-top:calc(var(--spacing) * 1.5);border-radius:var(--radius-lg);border-style:var(--tw-border-style);border-width:1px;border-color:var(--color-slate-300);background-color:var(--color-white);width:100%;padding-inline:calc(var(--spacing) * 3);padding-block:calc(var(--spacing) * 2.5);color:var(--color-slate-950);transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration));--tw-outline-style:none;outline-style:none}.field::placeholder{color:var(--color-slate-400)}.field:focus{border-color:var(--color-factorize-500);--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);--tw-ring-color:#fdc90126}@supports (color:color-mix(in lab, red, red)){.field:focus{--tw-ring-color:color-mix(in oklab, var(--color-factorize-500) 15%, transparent)}}.field:where(.dark,.dark *){border-color:var(--color-slate-700);background-color:var(--color-slate-950);color:var(--color-white)}.field:where(.dark,.dark *)::placeholder{color:var(--color-slate-500)}select.field:not([multiple]){appearance:none;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20' fill='none' stroke='%23575047' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5'%3E%3Cpath d='m6 8 4 4 4-4'/%3E%3C/svg%3E");background-position:right .75rem center;background-repeat:no-repeat;background-size:1.25rem 1.25rem;padding-right:2.75rem}.dark select.field:not([multiple]){background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20' fill='none' stroke='%23cec5b4' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5'%3E%3Cpath d='m6 8 4 4 4-4'/%3E%3C/svg%3E")}.label{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height));--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold);color:var(--color-slate-700);display:block}.label:where(.dark,.dark *){color:var(--color-slate-300)}.navbar-bee{transition:filter .15s}.dark .navbar-bee{filter:invert()}.landing-honeycomb{background-color:var(--color-stone-50);background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='720' height='520' viewBox='0 0 720 520'%3E%3Cg transform='rotate(-7 360 260)' fill='none' stroke='%23705000' stroke-opacity='.07' stroke-width='1.5'%3E%3Cpath d='M25 140 87.5 31.75h125L275 140l-62.5 108.25h-125zM385 380l62.5-108.25h125L635 380l-62.5 108.25h-125z'/%3E%3C/g%3E%3C/svg%3E");background-position:top;background-size:720px 520px}.dark .landing-honeycomb{background-color:var(--color-slate-950);background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='720' height='520' viewBox='0 0 720 520'%3E%3Cg transform='rotate(-7 360 260)' fill='none' stroke='%23fdc901' stroke-opacity='.05' stroke-width='1.5'%3E%3Cpath d='M25 140 87.5 31.75h125L275 140l-62.5 108.25h-125zM385 380l62.5-108.25h125L635 380l-62.5 108.25h-125z'/%3E%3C/g%3E%3C/svg%3E")}@media (min-width:40rem){div:has(>label>select[name=agentKind]){grid-template-columns:max-content minmax(0,1fr)}div:has(>label>select[name=agentKind])>label:first-child{width:11rem}}}@layer utilities{.invisible{visibility:hidden}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.relative{position:relative}.right-0{right:0}.z-20{z-index:20}.m-auto{margin:auto}.mx-auto{margin-inline:auto}.mt-1{margin-top:var(--spacing)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mt-5{margin-top:calc(var(--spacing) * 5)}.mt-6{margin-top:calc(var(--spacing) * 6)}.mt-7{margin-top:calc(var(--spacing) * 7)}.mt-8{margin-top:calc(var(--spacing) * 8)}.mt-9{margin-top:calc(var(--spacing) * 9)}.mt-10{margin-top:calc(var(--spacing) * 10)}.mt-12{margin-top:calc(var(--spacing) * 12)}.mt-24{margin-top:calc(var(--spacing) * 24)}.mt-auto{margin-top:auto}.mb-1{margin-bottom:var(--spacing)}.mb-9{margin-bottom:calc(var(--spacing) * 9)}.ml-2{margin-left:calc(var(--spacing) * 2)}.ml-3{margin-left:calc(var(--spacing) * 3)}.block{display:block}.contents{display:contents}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline-flex{display:inline-flex}.table{display:table}.size-4{width:calc(var(--spacing) * 4);height:calc(var(--spacing) * 4)}.size-9{width:calc(var(--spacing) * 9);height:calc(var(--spacing) * 9)}.h-2\.5{height:calc(var(--spacing) * 2.5)}.h-3{height:calc(var(--spacing) * 3)}.h-5{height:calc(var(--spacing) * 5)}.h-6{height:calc(var(--spacing) * 6)}.h-8{height:calc(var(--spacing) * 8)}.h-9{height:calc(var(--spacing) * 9)}.h-11{height:calc(var(--spacing) * 11)}.h-16{height:calc(var(--spacing) * 16)}.h-px{height:1px}.max-h-56{max-height:calc(var(--spacing) * 56)}.max-h-\[32rem\]{max-height:32rem}.max-h-\[40rem\]{max-height:40rem}.max-h-\[70vh\]{max-height:70vh}.min-h-11{min-height:calc(var(--spacing) * 11)}.min-h-20{min-height:calc(var(--spacing) * 20)}.min-h-24{min-height:calc(var(--spacing) * 24)}.min-h-36{min-height:calc(var(--spacing) * 36)}.min-h-40{min-height:calc(var(--spacing) * 40)}.min-h-44{min-height:calc(var(--spacing) * 44)}.min-h-52{min-height:calc(var(--spacing) * 52)}.min-h-80{min-height:calc(var(--spacing) * 80)}.min-h-screen{min-height:100vh}.w-2\.5{width:calc(var(--spacing) * 2.5)}.w-5{width:calc(var(--spacing) * 5)}.w-6{width:calc(var(--spacing) * 6)}.w-8{width:calc(var(--spacing) * 8)}.w-9{width:calc(var(--spacing) * 9)}.w-11{width:calc(var(--spacing) * 11)}.w-56{width:calc(var(--spacing) * 56)}.w-\[min\(32rem\,calc\(100vw-4rem\)\)\]{width:min(32rem,100vw - 4rem)}.w-\[min\(44rem\,calc\(100\%-2rem\)\)\]{width:min(44rem,100% - 2rem)}.w-full{width:100%}.max-w-2xl{max-width:var(--container-2xl)}.max-w-3xl{max-width:var(--container-3xl)}.max-w-4xl{max-width:var(--container-4xl)}.max-w-5xl{max-width:var(--container-5xl)}.max-w-6xl{max-width:var(--container-6xl)}.max-w-none{max-width:none}.max-w-xl{max-width:var(--container-xl)}.max-w-xs{max-width:var(--container-xs)}.min-w-0{min-width:0}.min-w-16{min-width:calc(var(--spacing) * 16)}.min-w-\[48rem\]{min-width:48rem}.flex-1{flex:1}.shrink-0{flex-shrink:0}.cursor-pointer{cursor:pointer}.list-none{list-style-type:none}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.place-items-center{place-items:center}.items-center{align-items:center}.items-end{align-items:flex-end}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.gap-1{gap:var(--spacing)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-5{gap:calc(var(--spacing) * 5)}.gap-8{gap:calc(var(--spacing) * 8)}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)))}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px * var(--tw-divide-y-reverse));border-bottom-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-stone-200>:not(:last-child)){border-color:var(--color-stone-200)}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-xl{border-radius:var(--radius-xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-amber-300{border-color:var(--color-amber-300)}.border-factorize-100{border-color:var(--color-factorize-100)}.border-red-200{border-color:var(--color-red-200)}.border-stone-200{border-color:var(--color-stone-200)}.border-stone-300{border-color:var(--color-stone-300)}.bg-amber-50{background-color:var(--color-amber-50)}.bg-amber-100{background-color:var(--color-amber-100)}.bg-blue-500{background-color:var(--color-blue-500)}.bg-factorize-50{background-color:var(--color-factorize-50)}.bg-factorize-100{background-color:var(--color-factorize-100)}.bg-factorize-500{background-color:var(--color-factorize-500)}.bg-green-100{background-color:var(--color-green-100)}.bg-green-500{background-color:var(--color-green-500)}.bg-green-600{background-color:var(--color-green-600)}.bg-red-50{background-color:var(--color-red-50)}.bg-red-500{background-color:var(--color-red-500)}.bg-red-600{background-color:var(--color-red-600)}.bg-slate-300{background-color:var(--color-slate-300)}.bg-slate-900{background-color:var(--color-slate-900)}.bg-slate-950{background-color:var(--color-slate-950)}.bg-stone-50{background-color:var(--color-stone-50)}.bg-stone-100{background-color:var(--color-stone-100)}.bg-white{background-color:var(--color-white)}.bg-gradient-to-br{--tw-gradient-position:to bottom right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.from-factorize-50{--tw-gradient-from:var(--color-factorize-50);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.via-white{--tw-gradient-via:var(--color-white);--tw-gradient-via-stops:var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-via) var(--tw-gradient-via-position), var(--tw-gradient-to) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.to-amber-50{--tw-gradient-to:var(--color-amber-50);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.object-contain{object-fit:contain}.p-0{padding:0}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-5{padding:calc(var(--spacing) * 5)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.p-10{padding:calc(var(--spacing) * 10)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-5{padding-inline:calc(var(--spacing) * 5)}.px-6{padding-inline:calc(var(--spacing) * 6)}.py-1{padding-block:var(--spacing)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-2\.5{padding-block:calc(var(--spacing) * 2.5)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-3\.5{padding-block:calc(var(--spacing) * 3.5)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-5{padding-block:calc(var(--spacing) * 5)}.py-6{padding-block:calc(var(--spacing) * 6)}.py-8{padding-block:calc(var(--spacing) * 8)}.py-12{padding-block:calc(var(--spacing) * 12)}.py-20{padding-block:calc(var(--spacing) * 20)}.py-24{padding-block:calc(var(--spacing) * 24)}.pt-1{padding-top:var(--spacing)}.pt-5{padding-top:calc(var(--spacing) * 5)}.pr-4{padding-right:calc(var(--spacing) * 4)}.pb-3{padding-bottom:calc(var(--spacing) * 3)}.pb-5{padding-bottom:calc(var(--spacing) * 5)}.pl-5\.5{padding-left:calc(var(--spacing) * 5.5)}.text-center{text-align:center}.text-left{text-align:left}.text-right{text-align:right}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading,var(--text-3xl--line-height))}.text-4xl{font-size:var(--text-4xl);line-height:var(--tw-leading,var(--text-4xl--line-height))}.text-5xl{font-size:var(--text-5xl);line-height:var(--tw-leading,var(--text-5xl--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.leading-5{--tw-leading:calc(var(--spacing) * 5);line-height:calc(var(--spacing) * 5)}.leading-6{--tw-leading:calc(var(--spacing) * 6);line-height:calc(var(--spacing) * 6)}.leading-7{--tw-leading:calc(var(--spacing) * 7);line-height:calc(var(--spacing) * 7)}.leading-8{--tw-leading:calc(var(--spacing) * 8);line-height:calc(var(--spacing) * 8)}.leading-none{--tw-leading:1;line-height:1}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-\[\.18em\]{--tw-tracking:.18em;letter-spacing:.18em}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.tracking-wide{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.break-words{overflow-wrap:break-word}.whitespace-pre-wrap{white-space:pre-wrap}.text-amber-800{color:var(--color-amber-800)}.text-amber-900{color:var(--color-amber-900)}.text-factorize-600{color:var(--color-factorize-600)}.text-factorize-700{color:var(--color-factorize-700)}.text-green-800{color:var(--color-green-800)}.text-red-600{color:var(--color-red-600)}.text-red-700{color:var(--color-red-700)}.text-red-800{color:var(--color-red-800)}.text-slate-100{color:var(--color-slate-100)}.text-slate-400{color:var(--color-slate-400)}.text-slate-500{color:var(--color-slate-500)}.text-slate-600{color:var(--color-slate-600)}.text-slate-700{color:var(--color-slate-700)}.text-slate-950{color:var(--color-slate-950)}.text-white{color:var(--color-white)}.capitalize{text-transform:capitalize}.lowercase{text-transform:lowercase}.uppercase{text-transform:uppercase}.tabular-nums{--tw-numeric-spacing:tabular-nums;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.underline{text-decoration-line:underline}.decoration-slate-400\/60{text-decoration-color:#9b928299}@supports (color:color-mix(in lab, red, red)){.decoration-slate-400\/60{-webkit-text-decoration-color:color-mix(in oklab, var(--color-slate-400) 60%, transparent);-webkit-text-decoration-color:color-mix(in oklab, var(--color-slate-400) 60%, transparent);text-decoration-color:color-mix(in oklab, var(--color-slate-400) 60%, transparent)}}.underline-offset-4{text-underline-offset:4px}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.accent-factorize-600{accent-color:var(--color-factorize-600)}.\[color-scheme\:light\]{color-scheme:light}.shadow-2xl{--tw-shadow:0 25px 50px -12px var(--tw-shadow-color,#00000040);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a), 0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-xl{--tw-shadow:0 20px 25px -5px var(--tw-shadow-color,#0000001a), 0 8px 10px -6px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.blur{--tw-blur:blur(8px);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.outline-none{--tw-outline-style:none;outline-style:none}.backdrop\:bg-slate-950\/60::backdrop{background-color:#15141099}@supports (color:color-mix(in lab, red, red)){.backdrop\:bg-slate-950\/60::backdrop{background-color:color-mix(in oklab, var(--color-slate-950) 60%, transparent)}}.first\:border-t-0:first-child{border-top-style:var(--tw-border-style);border-top-width:0}@media (hover:hover){.hover\:bg-red-50:hover{background-color:var(--color-red-50)}.hover\:bg-slate-800:hover{background-color:var(--color-slate-800)}.hover\:bg-stone-50:hover{background-color:var(--color-stone-50)}.hover\:bg-stone-100:hover{background-color:var(--color-stone-100)}.hover\:text-factorize-700:hover{color:var(--color-factorize-700)}.hover\:text-red-700:hover{color:var(--color-red-700)}.hover\:text-slate-700:hover{color:var(--color-slate-700)}.hover\:text-slate-950:hover{color:var(--color-slate-950)}.hover\:underline:hover{text-decoration-line:underline}}.focus\:bg-stone-50:focus{background-color:var(--color-stone-50)}.focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}.focus-visible\:ring-2:focus-visible{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus-visible\:ring-factorize-500:focus-visible{--tw-ring-color:var(--color-factorize-500)}.focus-visible\:ring-factorize-600:focus-visible{--tw-ring-color:var(--color-factorize-600)}.focus-visible\:ring-red-500:focus-visible{--tw-ring-color:var(--color-red-500)}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width:2px;--tw-ring-offset-shadow:var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.focus-visible\:outline-none:focus-visible{--tw-outline-style:none;outline-style:none}.focus-visible\:ring-inset:focus-visible{--tw-ring-inset:inset}.disabled\:cursor-wait:disabled{cursor:wait}.disabled\:opacity-60:disabled{opacity:.6}.aria-\[current\=page\]\:bg-stone-100[aria-current=page]{background-color:var(--color-stone-100)}.aria-\[current\=page\]\:font-semibold[aria-current=page]{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.aria-\[current\=page\]\:text-slate-950[aria-current=page]{color:var(--color-slate-950)}.aria-\[current\=page\]\:underline[aria-current=page]{text-decoration-line:underline}.aria-\[current\=page\]\:underline-offset-8[aria-current=page]{text-underline-offset:8px}@media (min-width:40rem){.sm\:col-span-2{grid-column:span 2/span 2}.sm\:w-56{width:calc(var(--spacing) * 56)}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-\[minmax\(0\,1fr\)_minmax\(0\,1\.4fr\)_auto\]{grid-template-columns:minmax(0,1fr) minmax(0,1.4fr) auto}.sm\:grid-cols-\[minmax\(0\,1fr\)_minmax\(0\,1\.35fr\)_auto\]{grid-template-columns:minmax(0,1fr) minmax(0,1.35fr) auto}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:items-end{align-items:flex-end}.sm\:justify-between{justify-content:space-between}.sm\:gap-4{gap:calc(var(--spacing) * 4)}.sm\:p-8{padding:calc(var(--spacing) * 8)}.sm\:px-6{padding-inline:calc(var(--spacing) * 6)}.sm\:py-28{padding-block:calc(var(--spacing) * 28)}.sm\:text-4xl{font-size:var(--text-4xl);line-height:var(--tw-leading,var(--text-4xl--line-height))}.sm\:text-7xl{font-size:var(--text-7xl);line-height:var(--tw-leading,var(--text-7xl--line-height))}}@media (min-width:48rem){.md\:mb-1{margin-bottom:var(--spacing)}.md\:block{display:block}.md\:grid-cols-\[13rem_minmax\(0\,1fr\)\]{grid-template-columns:13rem minmax(0,1fr)}.md\:gap-10{gap:calc(var(--spacing) * 10)}.md\:border-b-0{border-bottom-style:var(--tw-border-style);border-bottom-width:0}.md\:pb-0{padding-bottom:0}}@media (min-width:64rem){.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.lg\:px-8{padding-inline:calc(var(--spacing) * 8)}}:where(.dark\:divide-slate-800:where(.dark,.dark *)>:not(:last-child)){border-color:var(--color-slate-800)}.dark\:border-factorize-500\/30:where(.dark,.dark *){border-color:#fdc9014d}@supports (color:color-mix(in lab, red, red)){.dark\:border-factorize-500\/30:where(.dark,.dark *){border-color:color-mix(in oklab, var(--color-factorize-500) 30%, transparent)}}.dark\:border-red-900:where(.dark,.dark *){border-color:var(--color-red-900)}.dark\:border-slate-700:where(.dark,.dark *){border-color:var(--color-slate-700)}.dark\:border-slate-800:where(.dark,.dark *){border-color:var(--color-slate-800)}.dark\:bg-amber-950:where(.dark,.dark *){background-color:var(--color-amber-950)}.dark\:bg-amber-950\/40:where(.dark,.dark *){background-color:#46190166}@supports (color:color-mix(in lab, red, red)){.dark\:bg-amber-950\/40:where(.dark,.dark *){background-color:color-mix(in oklab, var(--color-amber-950) 40%, transparent)}}.dark\:bg-factorize-500\/20:where(.dark,.dark *){background-color:#fdc90133}@supports (color:color-mix(in lab, red, red)){.dark\:bg-factorize-500\/20:where(.dark,.dark *){background-color:color-mix(in oklab, var(--color-factorize-500) 20%, transparent)}}.dark\:bg-green-950:where(.dark,.dark *){background-color:var(--color-green-950)}.dark\:bg-red-950\/40:where(.dark,.dark *){background-color:#46080966}@supports (color:color-mix(in lab, red, red)){.dark\:bg-red-950\/40:where(.dark,.dark *){background-color:color-mix(in oklab, var(--color-red-950) 40%, transparent)}}.dark\:bg-red-950\/50:where(.dark,.dark *){background-color:#46080980}@supports (color:color-mix(in lab, red, red)){.dark\:bg-red-950\/50:where(.dark,.dark *){background-color:color-mix(in oklab, var(--color-red-950) 50%, transparent)}}.dark\:bg-slate-600:where(.dark,.dark *){background-color:var(--color-slate-600)}.dark\:bg-slate-700:where(.dark,.dark *){background-color:var(--color-slate-700)}.dark\:bg-slate-800:where(.dark,.dark *){background-color:var(--color-slate-800)}.dark\:bg-slate-900:where(.dark,.dark *){background-color:var(--color-slate-900)}.dark\:bg-slate-950:where(.dark,.dark *){background-color:var(--color-slate-950)}.dark\:bg-white:where(.dark,.dark *){background-color:var(--color-white)}.dark\:from-factorize-500\/15:where(.dark,.dark *){--tw-gradient-from:#fdc90126}@supports (color:color-mix(in lab, red, red)){.dark\:from-factorize-500\/15:where(.dark,.dark *){--tw-gradient-from:color-mix(in oklab, var(--color-factorize-500) 15%, transparent)}}.dark\:from-factorize-500\/15:where(.dark,.dark *){--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.dark\:via-slate-900:where(.dark,.dark *){--tw-gradient-via:var(--color-slate-900);--tw-gradient-via-stops:var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-via) var(--tw-gradient-via-position), var(--tw-gradient-to) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.dark\:to-slate-900:where(.dark,.dark *){--tw-gradient-to:var(--color-slate-900);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.dark\:text-amber-200:where(.dark,.dark *){color:var(--color-amber-200)}.dark\:text-factorize-100:where(.dark,.dark *){color:var(--color-factorize-100)}.dark\:text-factorize-500:where(.dark,.dark *){color:var(--color-factorize-500)}.dark\:text-green-200:where(.dark,.dark *){color:var(--color-green-200)}.dark\:text-red-200:where(.dark,.dark *){color:var(--color-red-200)}.dark\:text-red-300:where(.dark,.dark *){color:var(--color-red-300)}.dark\:text-red-400:where(.dark,.dark *){color:var(--color-red-400)}.dark\:text-slate-100:where(.dark,.dark *){color:var(--color-slate-100)}.dark\:text-slate-200:where(.dark,.dark *){color:var(--color-slate-200)}.dark\:text-slate-300:where(.dark,.dark *){color:var(--color-slate-300)}.dark\:text-slate-400:where(.dark,.dark *){color:var(--color-slate-400)}.dark\:text-slate-500:where(.dark,.dark *){color:var(--color-slate-500)}.dark\:text-slate-950:where(.dark,.dark *){color:var(--color-slate-950)}.dark\:text-white:where(.dark,.dark *){color:var(--color-white)}.dark\:decoration-slate-500\/60:where(.dark,.dark *){text-decoration-color:#71695e99}@supports (color:color-mix(in lab, red, red)){.dark\:decoration-slate-500\/60:where(.dark,.dark *){-webkit-text-decoration-color:color-mix(in oklab, var(--color-slate-500) 60%, transparent);-webkit-text-decoration-color:color-mix(in oklab, var(--color-slate-500) 60%, transparent);text-decoration-color:color-mix(in oklab, var(--color-slate-500) 60%, transparent)}}.dark\:\[color-scheme\:dark\]:where(.dark,.dark *){color-scheme:dark}@media (hover:hover){.dark\:hover\:bg-red-950\/50:where(.dark,.dark *):hover{background-color:#46080980}@supports (color:color-mix(in lab, red, red)){.dark\:hover\:bg-red-950\/50:where(.dark,.dark *):hover{background-color:color-mix(in oklab, var(--color-red-950) 50%, transparent)}}.dark\:hover\:bg-slate-200:where(.dark,.dark *):hover{background-color:var(--color-slate-200)}.dark\:hover\:bg-slate-800:where(.dark,.dark *):hover{background-color:var(--color-slate-800)}.dark\:hover\:bg-slate-800\/60:where(.dark,.dark *):hover{background-color:#2c292499}@supports (color:color-mix(in lab, red, red)){.dark\:hover\:bg-slate-800\/60:where(.dark,.dark *):hover{background-color:color-mix(in oklab, var(--color-slate-800) 60%, transparent)}}.dark\:hover\:text-factorize-500:where(.dark,.dark *):hover{color:var(--color-factorize-500)}.dark\:hover\:text-red-300:where(.dark,.dark *):hover{color:var(--color-red-300)}.dark\:hover\:text-slate-200:where(.dark,.dark *):hover{color:var(--color-slate-200)}.dark\:hover\:text-white:where(.dark,.dark *):hover{color:var(--color-white)}}.dark\:focus-visible\:ring-offset-slate-900:where(.dark,.dark *):focus-visible{--tw-ring-offset-color:var(--color-slate-900)}.dark\:focus-visible\:ring-offset-slate-950:where(.dark,.dark *):focus-visible{--tw-ring-offset-color:var(--color-slate-950)}.dark\:aria-\[current\=page\]\:bg-slate-800:where(.dark,.dark *)[aria-current=page]{background-color:var(--color-slate-800)}.dark\:aria-\[current\=page\]\:text-white:where(.dark,.dark *)[aria-current=page]{color:var(--color-white)}}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-gradient-position{syntax:"*";inherits:false}@property --tw-gradient-from{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-via{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-to{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-stops{syntax:"*";inherits:false}@property --tw-gradient-via-stops{syntax:"*";inherits:false}@property --tw-gradient-from-position{syntax:"";inherits:false;initial-value:0%}@property --tw-gradient-via-position{syntax:"";inherits:false;initial-value:50%}@property --tw-gradient-to-position{syntax:"";inherits:false;initial-value:100%}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-ordinal{syntax:"*";inherits:false}@property --tw-slashed-zero{syntax:"*";inherits:false}@property --tw-numeric-figure{syntax:"*";inherits:false}@property --tw-numeric-spacing{syntax:"*";inherits:false}@property --tw-numeric-fraction{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false} \ No newline at end of file +@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-space-y-reverse:0;--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial}}}@layer theme{:root,:host{--font-sans:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-50:oklch(97.1% .013 17.38);--color-red-200:oklch(88.5% .062 18.334);--color-red-300:oklch(80.8% .114 19.571);--color-red-400:oklch(70.4% .191 22.216);--color-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-red-700:oklch(50.5% .213 27.518);--color-red-800:oklch(44.4% .177 26.899);--color-red-900:oklch(39.6% .141 25.723);--color-red-950:oklch(25.8% .092 26.042);--color-amber-50:oklch(98.7% .022 95.277);--color-amber-100:oklch(96.2% .059 95.617);--color-amber-200:oklch(92.4% .12 95.746);--color-amber-300:oklch(87.9% .169 91.605);--color-amber-800:oklch(47.3% .137 46.201);--color-amber-900:oklch(41.4% .112 45.904);--color-amber-950:oklch(27.9% .077 45.635);--color-green-100:oklch(96.2% .044 156.743);--color-green-200:oklch(92.5% .084 155.995);--color-green-500:oklch(72.3% .219 149.579);--color-green-600:oklch(62.7% .194 149.214);--color-green-800:oklch(44.8% .119 151.328);--color-green-950:oklch(26.6% .065 152.934);--color-blue-500:oklch(62.3% .214 259.815);--color-slate-100:#f5f1e8;--color-slate-200:#e7e1d4;--color-slate-300:#cec5b4;--color-slate-400:#9b9282;--color-slate-500:#71695e;--color-slate-600:#575047;--color-slate-700:#403b34;--color-slate-800:#2c2924;--color-slate-900:#201e1a;--color-slate-950:#151410;--color-stone-50:#fcfbf6;--color-stone-100:#f6f3e9;--color-stone-200:#e6e0d1;--color-stone-300:#d4cbb9;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--container-xl:36rem;--container-2xl:42rem;--container-3xl:48rem;--container-4xl:56rem;--container-5xl:64rem;--container-6xl:72rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75 / 1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-3xl:1.875rem;--text-3xl--line-height:calc(2.25 / 1.875);--text-4xl:2.25rem;--text-4xl--line-height:calc(2.5 / 2.25);--text-5xl:3rem;--text-5xl--line-height:1;--text-7xl:4.5rem;--text-7xl--line-height:1;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--tracking-wide:.025em;--radius-lg:.5rem;--radius-xl:.75rem;--radius-2xl:1rem;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--color-factorize-50:#fff9e6;--color-factorize-100:#fff0b8;--color-factorize-500:#fdc901;--color-factorize-600:#896300;--color-factorize-700:#705000}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components{.field{margin-top:calc(var(--spacing) * 1.5);border-radius:var(--radius-lg);border-style:var(--tw-border-style);border-width:1px;border-color:var(--color-slate-300);background-color:var(--color-white);width:100%;padding-inline:calc(var(--spacing) * 3);padding-block:calc(var(--spacing) * 2.5);color:var(--color-slate-950);transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration));--tw-outline-style:none;outline-style:none}.field::placeholder{color:var(--color-slate-400)}.field:focus{border-color:var(--color-factorize-500);--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);--tw-ring-color:#fdc90126}@supports (color:color-mix(in lab, red, red)){.field:focus{--tw-ring-color:color-mix(in oklab, var(--color-factorize-500) 15%, transparent)}}.field:where(.dark,.dark *){border-color:var(--color-slate-700);background-color:var(--color-slate-950);color:var(--color-white)}.field:where(.dark,.dark *)::placeholder{color:var(--color-slate-500)}select.field:not([multiple]){appearance:none;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20' fill='none' stroke='%23575047' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5'%3E%3Cpath d='m6 8 4 4 4-4'/%3E%3C/svg%3E");background-position:right .75rem center;background-repeat:no-repeat;background-size:1.25rem 1.25rem;padding-right:2.75rem}.dark select.field:not([multiple]){background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20' fill='none' stroke='%23cec5b4' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5'%3E%3Cpath d='m6 8 4 4 4-4'/%3E%3C/svg%3E")}.label{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height));--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold);color:var(--color-slate-700);display:block}.label:where(.dark,.dark *){color:var(--color-slate-300)}.navbar-bee{transition:filter .15s}.dark .navbar-bee{filter:invert()}.landing-honeycomb{background-color:var(--color-stone-50);background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='720' height='520' viewBox='0 0 720 520'%3E%3Cg transform='rotate(-7 360 260)' fill='none' stroke='%23705000' stroke-opacity='.07' stroke-width='1.5'%3E%3Cpath d='M25 140 87.5 31.75h125L275 140l-62.5 108.25h-125zM385 380l62.5-108.25h125L635 380l-62.5 108.25h-125z'/%3E%3C/g%3E%3C/svg%3E");background-position:top;background-size:720px 520px}.dark .landing-honeycomb{background-color:var(--color-slate-950);background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='720' height='520' viewBox='0 0 720 520'%3E%3Cg transform='rotate(-7 360 260)' fill='none' stroke='%23fdc901' stroke-opacity='.05' stroke-width='1.5'%3E%3Cpath d='M25 140 87.5 31.75h125L275 140l-62.5 108.25h-125zM385 380l62.5-108.25h125L635 380l-62.5 108.25h-125z'/%3E%3C/g%3E%3C/svg%3E")}@media (min-width:40rem){div:has(>label>select[name=agentKind]){grid-template-columns:max-content minmax(0,1fr)}div:has(>label>select[name=agentKind])>label:first-child{width:11rem}}}@layer utilities{.invisible{visibility:hidden}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.relative{position:relative}.right-0{right:0}.z-20{z-index:20}.m-auto{margin:auto}.mx-auto{margin-inline:auto}.mt-1{margin-top:var(--spacing)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mt-5{margin-top:calc(var(--spacing) * 5)}.mt-6{margin-top:calc(var(--spacing) * 6)}.mt-8{margin-top:calc(var(--spacing) * 8)}.mt-9{margin-top:calc(var(--spacing) * 9)}.mt-10{margin-top:calc(var(--spacing) * 10)}.mt-12{margin-top:calc(var(--spacing) * 12)}.mt-24{margin-top:calc(var(--spacing) * 24)}.mt-auto{margin-top:auto}.ml-2{margin-left:calc(var(--spacing) * 2)}.block{display:block}.contents{display:contents}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline-flex{display:inline-flex}.table{display:table}.size-4{width:calc(var(--spacing) * 4);height:calc(var(--spacing) * 4)}.size-9{width:calc(var(--spacing) * 9);height:calc(var(--spacing) * 9)}.h-5{height:calc(var(--spacing) * 5)}.h-8{height:calc(var(--spacing) * 8)}.h-9{height:calc(var(--spacing) * 9)}.h-11{height:calc(var(--spacing) * 11)}.h-16{height:calc(var(--spacing) * 16)}.max-h-56{max-height:calc(var(--spacing) * 56)}.max-h-\[70vh\]{max-height:70vh}.min-h-11{min-height:calc(var(--spacing) * 11)}.min-h-24{min-height:calc(var(--spacing) * 24)}.min-h-36{min-height:calc(var(--spacing) * 36)}.min-h-40{min-height:calc(var(--spacing) * 40)}.min-h-44{min-height:calc(var(--spacing) * 44)}.min-h-screen{min-height:100vh}.w-5{width:calc(var(--spacing) * 5)}.w-8{width:calc(var(--spacing) * 8)}.w-9{width:calc(var(--spacing) * 9)}.w-11{width:calc(var(--spacing) * 11)}.w-56{width:calc(var(--spacing) * 56)}.w-\[min\(32rem\,calc\(100vw-4rem\)\)\]{width:min(32rem,100vw - 4rem)}.w-\[min\(44rem\,calc\(100\%-2rem\)\)\]{width:min(44rem,100% - 2rem)}.w-full{width:100%}.max-w-2xl{max-width:var(--container-2xl)}.max-w-3xl{max-width:var(--container-3xl)}.max-w-4xl{max-width:var(--container-4xl)}.max-w-5xl{max-width:var(--container-5xl)}.max-w-6xl{max-width:var(--container-6xl)}.max-w-none{max-width:none}.max-w-xs{max-width:var(--container-xs)}.min-w-0{min-width:0}.min-w-\[48rem\]{min-width:48rem}.shrink-0{flex-shrink:0}.cursor-pointer{cursor:pointer}.list-none{list-style-type:none}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.place-items-center{place-items:center}.items-center{align-items:center}.items-end{align-items:flex-end}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.gap-1{gap:var(--spacing)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-5{gap:calc(var(--spacing) * 5)}.gap-8{gap:calc(var(--spacing) * 8)}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)))}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px * var(--tw-divide-y-reverse));border-bottom-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-stone-200>:not(:last-child)){border-color:var(--color-stone-200)}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-xl{border-radius:var(--radius-xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-red-200{border-color:var(--color-red-200)}.border-stone-200{border-color:var(--color-stone-200)}.border-stone-300{border-color:var(--color-stone-300)}.bg-amber-100{background-color:var(--color-amber-100)}.bg-factorize-50{background-color:var(--color-factorize-50)}.bg-factorize-100{background-color:var(--color-factorize-100)}.bg-factorize-500{background-color:var(--color-factorize-500)}.bg-green-100{background-color:var(--color-green-100)}.bg-red-50{background-color:var(--color-red-50)}.bg-slate-900{background-color:var(--color-slate-900)}.bg-slate-950{background-color:var(--color-slate-950)}.bg-stone-50{background-color:var(--color-stone-50)}.bg-stone-100{background-color:var(--color-stone-100)}.bg-white{background-color:var(--color-white)}.object-contain{object-fit:contain}.p-0{padding:0}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-5{padding:calc(var(--spacing) * 5)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.p-10{padding:calc(var(--spacing) * 10)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-5{padding-inline:calc(var(--spacing) * 5)}.px-6{padding-inline:calc(var(--spacing) * 6)}.py-1{padding-block:var(--spacing)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-2\.5{padding-block:calc(var(--spacing) * 2.5)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-3\.5{padding-block:calc(var(--spacing) * 3.5)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-6{padding-block:calc(var(--spacing) * 6)}.py-12{padding-block:calc(var(--spacing) * 12)}.py-20{padding-block:calc(var(--spacing) * 20)}.pt-1{padding-top:var(--spacing)}.pt-5{padding-top:calc(var(--spacing) * 5)}.pb-3{padding-bottom:calc(var(--spacing) * 3)}.pb-5{padding-bottom:calc(var(--spacing) * 5)}.text-center{text-align:center}.text-left{text-align:left}.text-right{text-align:right}.font-mono{font-family:var(--font-mono)}.text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading,var(--text-3xl--line-height))}.text-5xl{font-size:var(--text-5xl);line-height:var(--tw-leading,var(--text-5xl--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.leading-6{--tw-leading:calc(var(--spacing) * 6);line-height:calc(var(--spacing) * 6)}.leading-7{--tw-leading:calc(var(--spacing) * 7);line-height:calc(var(--spacing) * 7)}.leading-8{--tw-leading:calc(var(--spacing) * 8);line-height:calc(var(--spacing) * 8)}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-\[\.18em\]{--tw-tracking:.18em;letter-spacing:.18em}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.tracking-wide{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.break-words{overflow-wrap:break-word}.whitespace-pre-wrap{white-space:pre-wrap}.text-amber-800{color:var(--color-amber-800)}.text-factorize-600{color:var(--color-factorize-600)}.text-factorize-700{color:var(--color-factorize-700)}.text-green-800{color:var(--color-green-800)}.text-red-700{color:var(--color-red-700)}.text-red-800{color:var(--color-red-800)}.text-slate-100{color:var(--color-slate-100)}.text-slate-400{color:var(--color-slate-400)}.text-slate-500{color:var(--color-slate-500)}.text-slate-600{color:var(--color-slate-600)}.text-slate-700{color:var(--color-slate-700)}.text-slate-950{color:var(--color-slate-950)}.text-white{color:var(--color-white)}.capitalize{text-transform:capitalize}.lowercase{text-transform:lowercase}.uppercase{text-transform:uppercase}.underline{text-decoration-line:underline}.decoration-slate-400\/60{text-decoration-color:#9b928299}@supports (color:color-mix(in lab, red, red)){.decoration-slate-400\/60{-webkit-text-decoration-color:color-mix(in oklab, var(--color-slate-400) 60%, transparent);-webkit-text-decoration-color:color-mix(in oklab, var(--color-slate-400) 60%, transparent);text-decoration-color:color-mix(in oklab, var(--color-slate-400) 60%, transparent)}}.underline-offset-4{text-underline-offset:4px}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.\[color-scheme\:light\]{color-scheme:light}.shadow-2xl{--tw-shadow:0 25px 50px -12px var(--tw-shadow-color,#00000040);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a), 0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-xl{--tw-shadow:0 20px 25px -5px var(--tw-shadow-color,#0000001a), 0 8px 10px -6px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.blur{--tw-blur:blur(8px);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.outline-none{--tw-outline-style:none;outline-style:none}.backdrop\:bg-slate-950\/60::backdrop{background-color:#15141099}@supports (color:color-mix(in lab, red, red)){.backdrop\:bg-slate-950\/60::backdrop{background-color:color-mix(in oklab, var(--color-slate-950) 60%, transparent)}}@media (hover:hover){.hover\:bg-red-50:hover{background-color:var(--color-red-50)}.hover\:bg-slate-800:hover{background-color:var(--color-slate-800)}.hover\:bg-stone-50:hover{background-color:var(--color-stone-50)}.hover\:bg-stone-100:hover{background-color:var(--color-stone-100)}.hover\:text-factorize-700:hover{color:var(--color-factorize-700)}.hover\:text-red-700:hover{color:var(--color-red-700)}.hover\:text-slate-700:hover{color:var(--color-slate-700)}.hover\:text-slate-950:hover{color:var(--color-slate-950)}}.focus-visible\:ring-2:focus-visible{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus-visible\:ring-factorize-500:focus-visible{--tw-ring-color:var(--color-factorize-500)}.focus-visible\:ring-factorize-600:focus-visible{--tw-ring-color:var(--color-factorize-600)}.focus-visible\:ring-red-500:focus-visible{--tw-ring-color:var(--color-red-500)}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width:2px;--tw-ring-offset-shadow:var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.focus-visible\:outline-none:focus-visible{--tw-outline-style:none;outline-style:none}.focus-visible\:ring-inset:focus-visible{--tw-ring-inset:inset}.disabled\:cursor-wait:disabled{cursor:wait}.disabled\:opacity-60:disabled{opacity:.6}.aria-\[current\=page\]\:bg-stone-100[aria-current=page]{background-color:var(--color-stone-100)}.aria-\[current\=page\]\:font-semibold[aria-current=page]{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.aria-\[current\=page\]\:text-slate-950[aria-current=page]{color:var(--color-slate-950)}.aria-\[current\=page\]\:underline[aria-current=page]{text-decoration-line:underline}.aria-\[current\=page\]\:underline-offset-8[aria-current=page]{text-underline-offset:8px}@media (min-width:40rem){.sm\:col-span-2{grid-column:span 2/span 2}.sm\:w-56{width:calc(var(--spacing) * 56)}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-\[minmax\(0\,1fr\)_minmax\(0\,1\.4fr\)_auto\]{grid-template-columns:minmax(0,1fr) minmax(0,1.4fr) auto}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:items-end{align-items:flex-end}.sm\:justify-between{justify-content:space-between}.sm\:gap-4{gap:calc(var(--spacing) * 4)}.sm\:py-28{padding-block:calc(var(--spacing) * 28)}.sm\:text-4xl{font-size:var(--text-4xl);line-height:var(--tw-leading,var(--text-4xl--line-height))}.sm\:text-7xl{font-size:var(--text-7xl);line-height:var(--tw-leading,var(--text-7xl--line-height))}}@media (min-width:48rem){.md\:mb-1{margin-bottom:var(--spacing)}.md\:block{display:block}.md\:grid-cols-\[13rem_minmax\(0\,1fr\)\]{grid-template-columns:13rem minmax(0,1fr)}.md\:gap-10{gap:calc(var(--spacing) * 10)}.md\:border-b-0{border-bottom-style:var(--tw-border-style);border-bottom-width:0}.md\:pb-0{padding-bottom:0}}@media (min-width:64rem){.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.lg\:px-8{padding-inline:calc(var(--spacing) * 8)}}:where(.dark\:divide-slate-800:where(.dark,.dark *)>:not(:last-child)){border-color:var(--color-slate-800)}.dark\:border-red-900:where(.dark,.dark *){border-color:var(--color-red-900)}.dark\:border-slate-700:where(.dark,.dark *){border-color:var(--color-slate-700)}.dark\:border-slate-800:where(.dark,.dark *){border-color:var(--color-slate-800)}.dark\:bg-amber-950:where(.dark,.dark *){background-color:var(--color-amber-950)}.dark\:bg-factorize-500\/20:where(.dark,.dark *){background-color:#fdc90133}@supports (color:color-mix(in lab, red, red)){.dark\:bg-factorize-500\/20:where(.dark,.dark *){background-color:color-mix(in oklab, var(--color-factorize-500) 20%, transparent)}}.dark\:bg-green-950:where(.dark,.dark *){background-color:var(--color-green-950)}.dark\:bg-red-950\/40:where(.dark,.dark *){background-color:#46080966}@supports (color:color-mix(in lab, red, red)){.dark\:bg-red-950\/40:where(.dark,.dark *){background-color:color-mix(in oklab, var(--color-red-950) 40%, transparent)}}.dark\:bg-slate-700:where(.dark,.dark *){background-color:var(--color-slate-700)}.dark\:bg-slate-800:where(.dark,.dark *){background-color:var(--color-slate-800)}.dark\:bg-slate-900:where(.dark,.dark *){background-color:var(--color-slate-900)}.dark\:bg-slate-950:where(.dark,.dark *){background-color:var(--color-slate-950)}.dark\:bg-white:where(.dark,.dark *){background-color:var(--color-white)}.dark\:text-amber-200:where(.dark,.dark *){color:var(--color-amber-200)}.dark\:text-factorize-100:where(.dark,.dark *){color:var(--color-factorize-100)}.dark\:text-green-200:where(.dark,.dark *){color:var(--color-green-200)}.dark\:text-red-200:where(.dark,.dark *){color:var(--color-red-200)}.dark\:text-red-300:where(.dark,.dark *){color:var(--color-red-300)}.dark\:text-slate-100:where(.dark,.dark *){color:var(--color-slate-100)}.dark\:text-slate-200:where(.dark,.dark *){color:var(--color-slate-200)}.dark\:text-slate-300:where(.dark,.dark *){color:var(--color-slate-300)}.dark\:text-slate-400:where(.dark,.dark *){color:var(--color-slate-400)}.dark\:text-slate-500:where(.dark,.dark *){color:var(--color-slate-500)}.dark\:text-slate-950:where(.dark,.dark *){color:var(--color-slate-950)}.dark\:text-white:where(.dark,.dark *){color:var(--color-white)}.dark\:decoration-slate-500\/60:where(.dark,.dark *){text-decoration-color:#71695e99}@supports (color:color-mix(in lab, red, red)){.dark\:decoration-slate-500\/60:where(.dark,.dark *){-webkit-text-decoration-color:color-mix(in oklab, var(--color-slate-500) 60%, transparent);-webkit-text-decoration-color:color-mix(in oklab, var(--color-slate-500) 60%, transparent);text-decoration-color:color-mix(in oklab, var(--color-slate-500) 60%, transparent)}}.dark\:\[color-scheme\:dark\]:where(.dark,.dark *){color-scheme:dark}@media (hover:hover){.dark\:hover\:bg-red-950\/50:where(.dark,.dark *):hover{background-color:#46080980}@supports (color:color-mix(in lab, red, red)){.dark\:hover\:bg-red-950\/50:where(.dark,.dark *):hover{background-color:color-mix(in oklab, var(--color-red-950) 50%, transparent)}}.dark\:hover\:bg-slate-200:where(.dark,.dark *):hover{background-color:var(--color-slate-200)}.dark\:hover\:bg-slate-800:where(.dark,.dark *):hover{background-color:var(--color-slate-800)}.dark\:hover\:text-red-300:where(.dark,.dark *):hover{color:var(--color-red-300)}.dark\:hover\:text-slate-200:where(.dark,.dark *):hover{color:var(--color-slate-200)}.dark\:hover\:text-white:where(.dark,.dark *):hover{color:var(--color-white)}}.dark\:focus-visible\:ring-offset-slate-900:where(.dark,.dark *):focus-visible{--tw-ring-offset-color:var(--color-slate-900)}.dark\:focus-visible\:ring-offset-slate-950:where(.dark,.dark *):focus-visible{--tw-ring-offset-color:var(--color-slate-950)}.dark\:aria-\[current\=page\]\:bg-slate-800:where(.dark,.dark *)[aria-current=page]{background-color:var(--color-slate-800)}.dark\:aria-\[current\=page\]\:text-white:where(.dark,.dark *)[aria-current=page]{color:var(--color-white)}}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false} \ No newline at end of file diff --git a/packages/app/src/custom-handler.ts b/packages/app/src/custom-handler.ts index 12756a79..048ec37b 100644 --- a/packages/app/src/custom-handler.ts +++ b/packages/app/src/custom-handler.ts @@ -1,8 +1,3 @@ -import type { CustomOrigin, CustomSource } from "./types"; - -export const CUSTOM_HANDLER_SCAFFOLD = `function handler(webhook) { - return true; -}`; export const CUSTOM_HANDLER_MAX_CODE_BYTES = 16_384; export const CUSTOM_HANDLER_MAX_PAYLOAD_BYTES = 262_144; export const CUSTOM_HANDLER_COMPATIBILITY_DATE = "2026-09-10"; @@ -13,27 +8,6 @@ export type HandlerDecision = | { ok: false; category: "handler_error" | "invalid_return" | "timeout" | "platform_error" }; const encoder = new TextEncoder(); -const hex = (bytes: ArrayBuffer) => [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join(""); - -export async function sha256(value: string): Promise { - return hex(await crypto.subtle.digest("SHA-256", encoder.encode(value))); -} - -export async function customScriptName(tenantId: string, flowId: string): Promise { - return `fh-${(await sha256(`${tenantId}\0${flowId}`)).slice(0, 40)}`; -} - -export function validateCustomHandler(origin: unknown, handlerName: unknown, handlerCode: unknown): { origin: CustomOrigin; handlerName: string; handlerCode: string } { - if (origin !== "linear" && origin !== "github" && origin !== "cloudflare") throw new Error("Custom handler origin must be Linear, GitHub, or Cloudflare."); - if (typeof handlerName !== "string" || !handlerName.trim() || handlerName.trim().length > 80) throw new Error("Handler name must be between 1 and 80 characters."); - if (typeof handlerCode !== "string" || encoder.encode(handlerCode).byteLength > CUSTOM_HANDLER_MAX_CODE_BYTES) throw new Error(`Handler code must be at most ${CUSTOM_HANDLER_MAX_CODE_BYTES} bytes.`); - // This is input validation, not the isolation boundary. Requiring exactly one - // complete declaration prevents ambiguous adapters and accidental snippets. - const declaration = /^\s*function\s+handler\s*\(\s*webhook\s*\)\s*\{[\s\S]*\}\s*;?\s*$/; - if (!declaration.test(handlerCode)) throw new Error("Provide one complete function handler(webhook) declaration."); - return { origin, handlerName: handlerName.trim(), handlerCode }; -} - export function validateHandlerCode(handlerCode: unknown): string { if (typeof handlerCode !== "string" || encoder.encode(handlerCode).byteLength > CUSTOM_HANDLER_MAX_CODE_BYTES) throw new Error(`Handler code must be at most ${CUSTOM_HANDLER_MAX_CODE_BYTES} bytes.`); if (!/^\s*function\s+handler\s*\(\s*webhook\s*\)\s*\{[\s\S]*\}\s*;?\s*$/.test(handlerCode)) throw new Error("Provide one complete function handler(webhook) declaration."); @@ -71,7 +45,7 @@ export default { async fetch(request) { } };`; } -export async function invokeCustomHandler(loader: WorkerLoader, source: Pick, payload: unknown): Promise { +export async function invokeCustomHandler(loader: WorkerLoader, source: { handlerCode: string }, payload: unknown): Promise { const body = JSON.stringify(payload); if (encoder.encode(body).byteLength > CUSTOM_HANDLER_MAX_PAYLOAD_BYTES) return { ok: false, category: "platform_error" }; const controller = new AbortController(); @@ -94,10 +68,3 @@ export async function invokeCustomHandler(loader: WorkerLoader, source: Pick, previous?: CustomSource): Promise { - const scriptName = await customScriptName(tenantId, flowId); - const codeDigest = await sha256(source.handlerCode); - if (previous?.handlerDeployment.state === "ready" && previous.handlerDeployment.codeDigest === codeDigest) return { ...source, tail: source.tail ?? previous.tail, handlerDeployment: previous.handlerDeployment }; - return { ...source, handlerDeployment: { scriptName, codeDigest, state: "ready" } }; -} diff --git a/packages/app/src/flow-schemas.ts b/packages/app/src/flow-schemas.ts index 75f255d5..1d8c6dff 100644 --- a/packages/app/src/flow-schemas.ts +++ b/packages/app/src/flow-schemas.ts @@ -6,37 +6,18 @@ export const matchRuleSchema = z.object({ type: z.enum(["owner", "creator", "status", "label", "assignee"]), targetId: z.string().min(1), }); -export const publicSourceSchema = z.discriminatedUnion("kind", [ - z.object({ kind: z.literal("linear"), projectId: z.string().min(1), matchRules: z.array(matchRuleSchema).min(1) }).strict(), - z.object({ kind: z.literal("cloudflareTail"), handlerCode: z.string().max(16_384).optional() }).strict(), -]); -export const flowInputSchema = z.object({ - name: z.string().trim().min(1).max(120), - flowId: z.string().trim().regex(/^[a-z0-9][a-z0-9-]*$/).optional(), - source: publicSourceSchema, - maxConcurrency: z.number().int().min(0).max(50).default(3), - workspaceName: z.string().max(120).optional(), - contextTemplate: z.string().max(50_000).optional(), - cwd: z.string().max(1_000).optional(), - exeConnectionId: z.string().min(1), -}).strict(); -export const flowIdSchema = z.object({ flowId: z.string().min(1) }); export const listRunsSchema = z.object({ jobId: z.string().min(1).optional(), state: runStateSchema.optional(), contextQuery: z.string().min(1).max(50_000).optional(), limit: z.coerce.number().int().min(1).max(100).default(50), cursor: z.string().min(1).optional(), }); export const runIdSchema = z.object({ runId: z.string().min(1) }); -export const listEventsSchema = z.object({ - flowId: z.string().min(1), limit: z.coerce.number().int().min(1).max(100).default(50), cursor: z.string().min(1).optional(), -}); const webhookCommonSchema = z.object({ handlerCode: z.string().max(16_384).optional() }); export const webhookTriggerConfigSchema = z.discriminatedUnion("provider", [ webhookCommonSchema.extend({ provider: z.literal("linear"), projectId: z.string().min(1), matchRules: z.array(matchRuleSchema).min(1) }).strict(), webhookCommonSchema.extend({ provider: z.literal("github"), installationId: z.number().int().positive(), repositoryId: z.number().int().positive(), event: z.string().min(1).default("pull_request"), action: z.string().min(1).default("dequeued") }).strict(), webhookCommonSchema.extend({ provider: z.literal("cloudflareTail"), signingSecret: z.string().min(16).optional(), handlerCode: z.string().max(16_384).optional() }).strict(), - webhookCommonSchema.extend({ provider: z.literal("custom"), secret: z.string().min(16).optional() }).strict(), ]); export const triggerSchema = z.discriminatedUnion("kind", [ z.object({ id: z.string().min(1).optional(), slug: z.string().regex(/^trigger-[1-9][0-9]*$/).optional(), kind: z.literal("manual"), enabled: z.boolean().default(true), config: z.object({}).strict().default({}) }).strict(), @@ -64,6 +45,5 @@ export const jobHandlerTestSchema = z.object({ handlerCode: z.string().max(16_384), payload: z.record(z.string(), z.unknown()), }).strict(); -export type FlowInput = z.infer; export type JobInput = z.infer; export type ManualInvocationInput = z.infer; diff --git a/packages/app/src/flow-service.ts b/packages/app/src/flow-service.ts index ede14cbc..11205525 100644 --- a/packages/app/src/flow-service.ts +++ b/packages/app/src/flow-service.ts @@ -1,7 +1,5 @@ import type { Env, OAuthProps } from "./types"; -import type { FlowInput, JobInput, ManualInvocationInput } from "./flow-schemas"; -import { preparePublicSource, publicSource, resolveContextTemplate } from "./source-lifecycle"; -import type { FlowSource } from "./types"; +import type { JobInput, ManualInvocationInput } from "./flow-schemas"; export class ServiceError extends Error { constructor(public status: number, public code: string, message: string) { super(message); } @@ -9,7 +7,7 @@ export class ServiceError extends Error { type Scope = "flows:read" | "flows:write" | "runs:read" | "runs:write"; -export class FlowService { +export class ApiService { constructor(private env: Env, private auth: OAuthProps) {} private stub() { return this.env.TENANTS.get(this.env.TENANTS.idFromName(`tenant:${this.auth.tenantId}`)); } @@ -36,58 +34,17 @@ export class FlowService { return body; } - private publicFlow(row: any) { - let source: any = undefined; - let matchRules: unknown = undefined; - try { source = typeof row.source_config === "string" ? JSON.parse(row.source_config) : undefined; } catch { /* omit malformed internal config */ } - try { matchRules = typeof row.match_rules === "string" ? JSON.parse(row.match_rules) : undefined; } catch { /* omit malformed internal config */ } - if (source) source = publicSource(source); - return { - id: row.id, name: row.name, projectId: row.project_id, source, - matchRules, - maxConcurrency: row.max_concurrency, workspaceName: row.workspace_name, - agentKind: row.agent_kind, cwd: row.cwd, contextTemplate: row.context_template, - exeConnectionId: row.exe_connection_id, - ...(source?.kind === "cloudflareTail" ? { cloudflareTail: { destination: `${this.env.APP_ORIGIN}/webhooks/cloudflare/${encodeURIComponent(this.auth.tenantId)}/${encodeURIComponent(row.id)}` } } : {}), - enabled: Boolean(row.enabled), createdAt: row.created_at, - }; - } - private publicJob(value: any) { for (const trigger of value?.triggers ?? []) { const provider = trigger.kind === "webhook" ? trigger.config?.provider : undefined; if (provider === "cloudflareTail") trigger.config.destination = `${this.env.APP_ORIGIN}/webhooks/cloudflare/${encodeURIComponent(this.auth.tenantId)}/${encodeURIComponent(value.id)}`; - if (provider === "custom") trigger.config.destination = `${this.env.APP_ORIGIN}/webhooks/custom/${encodeURIComponent(this.auth.tenantId)}/${encodeURIComponent(value.id)}`; } return value; } - async listFlows() { return (await this.call("flows:read", "/pipes") as any[]).map(row => this.publicFlow(row)); } - async getFlow(flowId: string) { - const value = await this.call("flows:read", `/v1/flows/${encodeURIComponent(flowId)}`) as any; - return this.publicFlow(value); - } - async createFlow(input: FlowInput) { - const pipeId = crypto.randomUUID(); - const source = await preparePublicSource(this.auth.tenantId, pipeId, input.source); - await this.call("flows:write", "/pipes", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...input, pipeId, projectId: input.source.kind === "linear" ? input.source.projectId : "", matchRules: input.source.kind === "linear" ? input.source.matchRules : [], source, contextTemplate: resolveContextTemplate(input.source, input.contextTemplate) }) }); - return this.publicFlow(await this.call("flows:write", `/v1/flows/${encodeURIComponent(pipeId)}`)); - } - async updateFlow(flowId: string, input: FlowInput) { - const current = await this.call("flows:write", `/v1/flows/${encodeURIComponent(flowId)}`) as any; - let previous: FlowSource | undefined; - try { previous = JSON.parse(current.source_config); } catch { /* validation below will fail safely */ } - const source = await preparePublicSource(this.auth.tenantId, flowId, input.source, previous); - await this.call("flows:write", `/pipes/${encodeURIComponent(flowId)}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...input, projectId: input.source.kind === "linear" ? input.source.projectId : "", matchRules: input.source.kind === "linear" ? input.source.matchRules : [], source, contextTemplate: resolveContextTemplate(input.source, input.contextTemplate) }) }); - return this.publicFlow(await this.call("flows:write", `/v1/flows/${encodeURIComponent(flowId)}`)); - } - deleteFlow(flowId: string) { return this.call("flows:write", `/pipes/${encodeURIComponent(flowId)}`, { method: "DELETE" }); } - listProjects() { return this.call("flows:read", "/linear/projects"); } - listFlowOptions() { return this.call("flows:read", "/linear/options"); } listExeConnections() { return this.call("flows:read", "/connections/status").then((value: any) => value.exeConnections ?? []); } listRuns(query: URLSearchParams) { return this.call("runs:read", `/v1/runs?${query}`); } getRun(runId: string) { return this.call("runs:read", `/v1/runs/${encodeURIComponent(runId)}`); } - listFlowEvents(query: URLSearchParams) { return this.call("runs:read", `/v1/events?${query}`); } stopRun(runId: string) { return this.call("runs:write", `/v1/runs/${encodeURIComponent(runId)}/stop`, { method: "POST" }); } async listJobs() { return (await this.call("flows:read", "/v1/jobs") as any[]).map(value => this.publicJob(value)); } async getJob(jobId: string) { return this.publicJob(await this.call("flows:read", `/v1/jobs/${encodeURIComponent(jobId)}`)); } diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index 1cf99d28..e058d6c1 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -5,12 +5,8 @@ import { equalHmac, hmac } from "./crypto"; import { Tenant } from "./tenant"; import { GitHubInstallationRegistry } from "./github-registry"; import { createAppJwt, githubHeaders, readSetupState, signSetupState } from "./github"; -import { apiKeysSettingsPage, flowDetailPage, flowPage, flowWebhooksPage, flowsPage, jobDetailPage, jobPage, jobsPage, jobRunPage, landingPage, runDetailPage, settingsPage } from "./ui"; +import { apiKeysSettingsPage, jobDetailPage, jobPage, jobsPage, jobRunPage, landingPage, settingsPage } from "./ui"; import type { Env } from "./types"; -import type { CustomSource, PipeInput } from "./types"; -import { invokeCustomHandler, prepareCustomHandler, validateCustomHandler } from "./custom-handler"; -import { preparePublicSource, resolveContextTemplate } from "./source-lifecycle"; -import { generateTailSecret } from "./cloudflare-tail"; import { nextOccurrence, validateScheduleConfig } from "./schedule"; import { ACCESS_SCOPES, accessTokenDigest, issueAccessToken } from "./access-tokens"; @@ -146,28 +142,6 @@ app.post("/auth/logout", (c) => { return c.redirect("/"); }); -app.get("/api/pipes", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch("https://tenant/pipes"); -}); -app.get("/api/pipes/:id", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - const url = new URL(`https://tenant/pipes/${encodeURIComponent(c.req.param("id"))}`); - for (const key of ["view", "page"]) { const value = c.req.query(key); if (value) url.searchParams.set(key, value); } - const response = await tenant(c, session.tenantId).fetch(url); - if (!response.ok) return response; - const result = await response.json() as any; - let source: CustomSource | undefined; try { const parsed = JSON.parse(result.flow?.source_config ?? "{}"); if (parsed.kind === "custom" && parsed.origin === "cloudflare") source = parsed; } catch {} - return c.json({ ...result, ...(source ? { cloudflareTail: { destination: `${c.env.APP_ORIGIN}/webhooks/cloudflare/${encodeURIComponent(session.tenantId)}/${encodeURIComponent(c.req.param("id"))}`, signingSecret: source.tail?.signingSecret } } : {}) }); -}); -app.get("/api/runs", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch("https://tenant/runs"); -}); -app.get("/api/runs/:id", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch(`https://tenant/runs/${encodeURIComponent(c.req.param("id"))}`); -}); const jobApi = async (c: any, path: string, init?: RequestInit) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); return tenant(c, session.tenantId).fetch(`https://tenant/v1${path}`, init); @@ -257,85 +231,14 @@ app.post("/api/connections/amp/test", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); return tenant(c, session.tenantId).fetch("https://tenant/connections/amp/test", { method: "POST", headers: { "Content-Type": "application/json" }, body: await c.req.text() }); }); -app.post("/api/pipes", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - const input = await c.req.json() as PipeInput & { source?: any }; - if (input.source?.kind === "cloudflareTail") { - if (c.env.CUSTOM_SOURCES_ENABLED !== "true") return c.json({ error: "Custom sources are not enabled." }, 404); - const pipeId = crypto.randomUUID(); input.pipeId = pipeId; - input.contextTemplate = resolveContextTemplate(input.source, input.contextTemplate); - input.source = await preparePublicSource(session.tenantId, pipeId, input.source); - } - else if (input.source?.kind === "custom") { - if (c.env.CUSTOM_SOURCES_ENABLED !== "true") return c.json({ error: "Custom sources are not enabled." }, 404); - const valid = validateCustomHandler(input.source.origin, input.source.handlerName, input.source.handlerCode); - const pipeId = crypto.randomUUID(); - input.pipeId = pipeId; - input.source = await prepareCustomHandler(session.tenantId, pipeId, { kind: "custom", ...valid, ...(valid.origin === "cloudflare" ? { tail: { signingSecret: generateTailSecret() } } : {}) }); - } - const response = await tenant(c, session.tenantId).fetch("https://tenant/pipes", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) }); - if (!response.ok || input.source?.kind !== "custom" || input.source.origin !== "cloudflare") return response; - const result = await response.json() as Record; - return c.json({ ...result, cloudflareTail: { destination: `${c.env.APP_ORIGIN}/webhooks/cloudflare/${encodeURIComponent(session.tenantId)}/${encodeURIComponent(String(input.pipeId))}`, signingSecret: input.source.tail?.signingSecret } }, 201); -}); -app.put("/api/pipes/:id", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - const pipeId = c.req.param("id"), input = await c.req.json() as PipeInput & { source?: any; tailSigningSecret?: string }; - if (input.source?.kind === "cloudflareTail") { - if (c.env.CUSTOM_SOURCES_ENABLED !== "true") return c.json({ error: "Custom sources are not enabled." }, 404); - const currentResponse = await tenant(c, session.tenantId).fetch(`https://tenant/v1/flows/${encodeURIComponent(pipeId)}`); - if (!currentResponse.ok) return currentResponse; - const current = await currentResponse.json() as { source_config?: string }; - let previous: CustomSource | undefined; try { const parsed = JSON.parse(current.source_config ?? "{}"); if (parsed.kind === "custom") previous = parsed; } catch {} - input.contextTemplate = resolveContextTemplate(input.source, input.contextTemplate); - input.source = await preparePublicSource(session.tenantId, pipeId, input.source, previous, input.tailSigningSecret); - delete input.tailSigningSecret; - } - else if (input.source?.kind === "custom") { - if (c.env.CUSTOM_SOURCES_ENABLED !== "true") return c.json({ error: "Custom sources are not enabled." }, 404); - const currentResponse = await tenant(c, session.tenantId).fetch(`https://tenant/pipes/${encodeURIComponent(pipeId)}`); - if (!currentResponse.ok) return currentResponse; - const current = await currentResponse.json() as { flow: { source_config?: string } }; - let previous: CustomSource | undefined; - try { const source = JSON.parse(current.flow.source_config ?? "{}"); if (source.kind === "custom") previous = source; } catch { /* fail closed */ } - const valid = validateCustomHandler(input.source.origin, input.source.handlerName, input.source.handlerCode); - input.source = await prepareCustomHandler(session.tenantId, pipeId, { kind: "custom", ...valid }, previous); - } - return tenant(c, session.tenantId).fetch(`https://tenant/pipes/${encodeURIComponent(pipeId)}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) }); -}); -app.delete("/api/pipes/:id", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - const pipeId = c.req.param("id"); - return tenant(c, session.tenantId).fetch(`https://tenant/pipes/${encodeURIComponent(pipeId)}`, { method: "DELETE" }); -}); - -app.post("/api/custom-handlers/test", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - if (c.env.CUSTOM_SOURCES_ENABLED !== "true" || !c.env.CUSTOM_HANDLER_LOADER) return c.json({ error: "Custom sources are not enabled." }, 404); - const input = await c.req.json() as { origin?: unknown; handlerName?: unknown; handlerCode?: unknown; payload?: unknown }; - const valid = validateCustomHandler(input.origin, input.handlerName, input.handlerCode); - const testId = `test-${crypto.randomUUID()}`; - const source = await prepareCustomHandler(session.tenantId, testId, { kind: "custom", ...valid }); - return c.json(await invokeCustomHandler(c.env.CUSTOM_HANDLER_LOADER, source, input.payload)); -}); - -app.post("/api/pipes/:id/cloudflare-tail/test", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch(`https://tenant/cloudflare-tail/${encodeURIComponent(c.req.param("id"))}/test`, { method: "POST" }); -}); - -app.post("/webhooks/cloudflare/:tenantId/:flowId", async (c) => { +app.post("/webhooks/cloudflare/:tenantId/:jobId", async (c) => { const raw = await c.req.text(); if (new TextEncoder().encode(raw).byteLength > 262_144) return c.text("Payload too large", 413); - return tenant(c, c.req.param("tenantId")).fetch(`https://tenant/webhook/cloudflare/${encodeURIComponent(c.req.param("flowId"))}`, { + return tenant(c, c.req.param("tenantId")).fetch(`https://tenant/webhook/cloudflare/${encodeURIComponent(c.req.param("jobId"))}`, { method: "POST", headers: { "Content-Type": "application/json", "X-Factorize-Timestamp": c.req.header("X-Factorize-Timestamp") ?? "", "X-Factorize-Delivery": c.req.header("X-Factorize-Delivery") ?? "", "X-Factorize-Signature": c.req.header("X-Factorize-Signature") ?? "" }, body: raw, }); }); -app.post("/webhooks/custom/:tenantId/:jobId", async (c) => { - return tenant(c, c.req.param("tenantId")).fetch(`https://tenant/webhook/custom/${encodeURIComponent(c.req.param("jobId"))}`, { method: "POST", headers: c.req.raw.headers, body: await c.req.text() }); -}); - app.post("/webhooks/linear", async (c) => { if (!c.env.LINEAR_WEBHOOK_SIGNING_SECRET) return c.text("Webhook verification is not configured", 503); const raw = await c.req.text(); @@ -380,35 +283,6 @@ app.get("/", async (c) => { const session = await owner(c); return c.html(render(landingPage(session ? { email: session.email } : null), c.get("cspNonce"))); }); -app.get("/flows/new", async (c) => { - const session = await owner(c); - return c.html(render(flowPage(session ? { email: session.email } : null), c.get("cspNonce"))); -}); -app.get("/flows", async (c) => { - const session = await owner(c); - if (!session) return c.redirect("/auth/linear"); - return c.html(render(flowsPage({ email: session.email }), c.get("cspNonce"))); -}); -app.get("/flows/:id", async (c) => { - const session = await owner(c); - if (!session) return c.redirect("/auth/linear"); - return c.html(render(flowDetailPage({ email: session.email }, c.req.param("id")), c.get("cspNonce"))); -}); -app.get("/flows/:id/edit", async (c) => { - const session = await owner(c); - if (!session) return c.redirect("/auth/linear"); - return c.html(render(flowPage({ email: session.email }, c.req.param("id")), c.get("cspNonce"))); -}); -app.get("/flows/:id/webhooks", async (c) => { - const session = await owner(c); - if (!session) return c.redirect("/auth/linear"); - return c.html(render(flowWebhooksPage({ email: session.email }, c.req.param("id")), c.get("cspNonce"))); -}); -app.get("/runs/:id", async (c) => { - const session = await owner(c); - if (!session) return c.redirect("/auth/linear"); - return c.html(render(runDetailPage({ email: session.email }, c.req.param("id")), c.get("cspNonce"))); -}); app.get("/jobs", async (c) => { const session = await owner(c); return session ? c.html(render(jobsPage({ email: session.email }), c.get("cspNonce"))) : c.redirect("/auth/linear"); }); app.get("/jobs/new", async (c) => { const session = await owner(c); return session ? c.html(render(jobPage({ email: session.email }), c.get("cspNonce"))) : c.redirect("/auth/linear"); }); app.get("/jobs/:id", async (c) => { const session = await owner(c); return session ? c.html(render(jobDetailPage({ email: session.email }, c.req.param("id")), c.get("cspNonce"))) : c.redirect("/auth/linear"); }); diff --git a/packages/app/src/protected-api.ts b/packages/app/src/protected-api.ts index 9c90b4df..0369fcdb 100644 --- a/packages/app/src/protected-api.ts +++ b/packages/app/src/protected-api.ts @@ -2,8 +2,8 @@ import { WorkerEntrypoint } from "cloudflare:workers"; import { McpServer, WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/server"; import { createMcpHonoApp } from "@modelcontextprotocol/hono"; import { z } from "zod"; -import { FlowService, ServiceError } from "./flow-service"; -import { flowIdSchema, flowInputSchema, jobHandlerTestSchema, jobIdSchema, jobInputSchema, listEventsSchema, listRunsSchema, manualInvocationSchema, runIdSchema } from "./flow-schemas"; +import { ApiService, ServiceError } from "./flow-service"; +import { jobHandlerTestSchema, jobIdSchema, jobInputSchema, listRunsSchema, manualInvocationSchema, runIdSchema } from "./flow-schemas"; import type { Env, OAuthProps } from "./types"; function errorResponse(error: unknown): Response { @@ -35,17 +35,9 @@ function structured(value: unknown) { export async function protectedApiFetch(request: Request, env: Env, auth: OAuthProps, ctx: ExecutionContext): Promise { try { - const url = new URL(request.url), path = url.pathname, service = new FlowService(env, auth); + const url = new URL(request.url), path = url.pathname, service = new ApiService(env, auth); if (path === "/mcp") return mcp(request, service, env, ctx); if (!path.startsWith("/api/v1")) return Response.json({ error: { code: "not_found", message: "Not found" } }, { status: 404 }); - if (request.method === "GET" && path === "/api/v1/flows") return Response.json(await service.listFlows()); - if (request.method === "POST" && path === "/api/v1/flows") return Response.json(await service.createFlow(flowInputSchema.parse(await request.json())), { status: 201 }); - const flowMatch = path.match(/^\/api\/v1\/flows\/([^/]+)$/); - if (flowMatch && request.method === "GET") return Response.json(await service.getFlow(decodeURIComponent(flowMatch[1]))); - if (flowMatch && request.method === "PUT") return Response.json(await service.updateFlow(decodeURIComponent(flowMatch[1]), flowInputSchema.parse(await request.json()))); - if (flowMatch && request.method === "DELETE") return Response.json(await service.deleteFlow(decodeURIComponent(flowMatch[1]))); - if (request.method === "GET" && path === "/api/v1/projects") return Response.json(await service.listProjects()); - if (request.method === "GET" && path === "/api/v1/flow-options") return Response.json(await service.listFlowOptions()); if (request.method === "GET" && path === "/api/v1/exe-connections") return Response.json(await service.listExeConnections()); if (request.method === "GET" && path === "/api/v1/execution-targets") return Response.json(await service.listExecutionTargets()); if (request.method === "GET" && path === "/api/v1/jobs") return Response.json(await service.listJobs()); @@ -66,28 +58,19 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP if (runMatch && request.method === "GET") return Response.json(await service.getRun(decodeURIComponent(runMatch[1]))); const stopMatch = path.match(/^\/api\/v1\/runs\/([^/]+)\/stop$/); if (stopMatch && request.method === "POST") return Response.json(await service.stopRun(decodeURIComponent(stopMatch[1]))); - if (request.method === "GET" && path === "/api/v1/flow-events") { const q = listEventsSchema.parse(queryInput(url)); return Response.json(await service.listFlowEvents(queryOf(q))); } return Response.json({ error: { code: "not_found", message: "Not found" } }, { status: 404 }); } catch (error) { return errorResponse(error); } } -async function mcp(request: Request, service: FlowService, env: Env, ctx: ExecutionContext): Promise { +async function mcp(request: Request, service: ApiService, env: Env, ctx: ExecutionContext): Promise { const server = new McpServer({ name: "factorize", version: "1.0.0" }); const tool = (name: string, description: string, schema: any, action: (input: T) => Promise) => server.registerTool(name, { description, inputSchema: schema }, async (input: T) => { try { return structured(await action(input)); } catch (error) { const response = errorResponse(error), detail = await response.json() as any; throw new Error(`${detail.error?.code ?? "operation_failed"}: ${detail.error?.message ?? "Operation failed"}`); } }); - tool("list_flows", "List Factorize flows", z.object({}), () => service.listFlows()); - tool("get_flow", "Get a flow", flowIdSchema, ({ flowId }: any) => service.getFlow(flowId)); - tool("create_flow", "Create a flow. First call list_exe_connections, then select its connectionId. Cloudflare Tail returns a relay destination but never its signing secret.", flowInputSchema, (input: any) => service.createFlow(input)); - tool("update_flow", "Update a flow using a saved exe.dev connection ID. Cloudflare Tail secrets are preserved and cannot be submitted or returned.", flowInputSchema.extend({ flowId: z.string().min(1) }), ({ flowId, ...input }: any) => service.updateFlow(flowId, input)); - tool("delete_flow", "Delete a flow", flowIdSchema, ({ flowId }: any) => service.deleteFlow(flowId)); - tool("list_projects", "List Linear projects", z.object({}), () => service.listProjects()); - tool("list_flow_options", "List match-rule options", z.object({}), () => service.listFlowOptions()); - tool("list_exe_connections", "List safe metadata for saved exe.dev connections. Select a connectionId before creating or updating a flow; API tokens are never returned.", z.object({}), () => service.listExeConnections()); + tool("list_exe_connections", "List safe metadata for saved exe.dev connections. API tokens are never returned.", z.object({}), () => service.listExeConnections()); tool("list_runs", "List authoritative job runs by job ID, state, and an optional case-insensitive literal substring of triggered context. Automatic webhook, schedule, and lifecycle signals coalesce, so query runs and the provider API for authoritative work. Context matches include only a bounded excerpt.", listRunsSchema, (input: any) => service.listRuns(queryOf(input))); tool("get_run", "Get a run with its full triggered context, invocation metadata, execution metadata, output, and activity", runIdSchema, ({ runId }: any) => service.getRun(runId)); - tool("list_flow_events", "List webhook activity for a flow", listEventsSchema, (input: any) => service.listFlowEvents(queryOf(input))); tool("stop_run", "Stop an active run", runIdSchema, ({ runId }: any) => service.stopRun(runId)); tool("list_jobs", "List jobs", z.object({}), () => service.listJobs()); tool("get_job", "Get a job", jobIdSchema, ({ jobId }: any) => service.getJob(jobId)); diff --git a/packages/app/src/source-lifecycle.ts b/packages/app/src/source-lifecycle.ts deleted file mode 100644 index f655cebf..00000000 --- a/packages/app/src/source-lifecycle.ts +++ /dev/null @@ -1,53 +0,0 @@ -import Mustache from "mustache"; -import { generateTailSecret, TAIL_HANDLER_SCAFFOLD } from "./cloudflare-tail"; -import { prepareCustomHandler, validateCustomHandler } from "./custom-handler"; -import { DEFAULT_CONTEXT_TEMPLATE, renderContextTemplate } from "./linear-source"; -import type { CustomSource, FlowSource } from "./types"; - -export const TAIL_CONTEXT_TEMPLATE = `--- -pipe: "{{{flow.name}}}" -source: "Cloudflare Tail" -delivery: "{{{deliveryId}}}" ---- - -# Cloudflare Worker Tail event - -\`\`\`json -{{{eventJson}}} -\`\`\``; - -export type PublicSource = - | { kind: "linear"; projectId: string; matchRules: Array<{ type: "owner" | "creator" | "status" | "label" | "assignee"; targetId: string }> } - | { kind: "cloudflareTail"; handlerCode?: string }; - -export function defaultContextTemplate(source: { kind: string }): string { - return source.kind === "cloudflareTail" ? TAIL_CONTEXT_TEMPLATE : DEFAULT_CONTEXT_TEMPLATE; -} - -export function resolveContextTemplate(source: { kind: string }, value?: string): string { - const template = value || defaultContextTemplate(source); - if (template.length > 50_000) throw new Error("Context template must be 50,000 characters or fewer."); - try { Mustache.parse(template); } catch { throw new Error("Context template contains invalid Mustache syntax."); } - return template; -} - -export function renderSourcePrompt(source: FlowSource, template: string, payload: Record, flowName: string, deliveryId?: string): string { - if (source.kind === "custom" && source.origin === "cloudflare") return Mustache.render(template, { event: payload, eventJson: JSON.stringify(payload, null, 2), deliveryId, flow: { name: flowName } }); - return renderContextTemplate(template, payload, flowName); -} - -export async function preparePublicSource(tenantId: string, flowId: string, source: PublicSource, previous?: FlowSource, signingSecret?: string): Promise { - if (source.kind === "linear") return source; - const handlerCode = source.handlerCode ?? TAIL_HANDLER_SCAFFOLD; - const valid = validateCustomHandler("cloudflare", "Cloudflare Worker failures", handlerCode); - const old = previous?.kind === "custom" && previous.origin === "cloudflare" ? previous as CustomSource : undefined; - const secret = signingSecret ?? old?.tail?.signingSecret ?? generateTailSecret(); - if (secret.length < 32 || secret.length > 256) throw new Error("Cloudflare Tail signing secret must be between 32 and 256 characters."); - return prepareCustomHandler(tenantId, flowId, { kind: "custom", ...valid, tail: { signingSecret: secret } }, old); -} - -export function publicSource(source: FlowSource): PublicSource { - return source.kind === "custom" && source.origin === "cloudflare" - ? { kind: "cloudflareTail", handlerCode: source.handlerCode } - : source as PublicSource; -} diff --git a/packages/app/src/tenant.ts b/packages/app/src/tenant.ts index 425a597a..a28dc112 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -5,16 +5,15 @@ import { agentListCommand, agentOutputCommand, agentStartupBlocked, agentStatusC import { findOwnedAgent, ownsPane, parseAgent, parseAgentList, parsePaneProcess, type HerdrIdentity } from "./recovery"; import { LINEAR_ISSUE_PROJECT_QUERY, LINEAR_OPTION_QUERIES, LINEAR_PROJECTS_QUERY, isLinearAuthenticationError, refreshLinearToken } from "./linear"; import { matchingIssue } from "./matcher"; -import type { AmpConnectionInput, Env, ExeConnectionInput, FilterType, MatchRule, PipeInput, RunState } from "./types"; +import type { AmpConnectionInput, Env, ExeConnectionInput, FilterType, MatchRule, RunState } from "./types"; import { workingDirectoryFor, workspaceNameFor } from "./workspace"; import { githubClaimKey, githubHeaders, installationToken, normalizeRepository, renderGitHubPrompt } from "./github"; -import type { FlowSource, WorkItem } from "./types"; -import { invokeCustomHandler, validateCustomHandler } from "./custom-handler"; +import type { WorkItem } from "./types"; +import { invokeCustomHandler } from "./custom-handler"; import { sanitizeTailEvent, suppressTailEvent, tailFingerprint, verifyTailDelivery } from "./cloudflare-tail"; import { ExeHerdrBackend } from "./exe-herdr-backend"; import { AmpBackend, type AmpConnection } from "./amp-backend"; import { DEFAULT_CONTEXT_TEMPLATE, LinearSourceAdapter, linearTicketPrompt, renderContextTemplate } from "./linear-source"; -import { renderSourcePrompt } from "./source-lifecycle"; import { JOB_SCHEMA, renderJobPrompt } from "./job-domain"; import { normalizeExecutionState, type RunHandle } from "./execution"; import { catchUpOccurrence, nextOccurrence, validateScheduleConfig, type ScheduleConfig } from "./schedule"; @@ -33,6 +32,12 @@ const object = (value: unknown): Record => value !== null && typeof const text = (value: unknown): string => typeof value === "string" ? value : ""; const linearSource = new LinearSourceAdapter(); +type FlowSource = + | { kind: "linear"; projectId: string; matchRules: MatchRule[] } + | { kind: "github"; installationId: number; repositoryId: number; repositoryOwner?: string; repositoryName?: string; repositoryFullName?: string; baseRef: "main"; trigger: "merge_queue_conflict" } + | { kind: "custom"; origin: "linear" | "github" | "cloudflare"; handlerName: string; handlerCode: string; handlerDeployment: { scriptName: string; codeDigest: string; state: "deploying" | "ready" | "failed" }; tail?: { signingSecret: string } }; +type PipeInput = { pipeId?: string; name: string; flowId?: string; projectId?: string; matchRules: MatchRule[]; maxConcurrency: number; contextTemplate?: string; exeConnectionId?: string; cwd?: string; source?: FlowSource }; + export class Tenant extends DurableObject { private linearRefresh?: Promise; @@ -169,17 +174,9 @@ export class Tenant extends DurableObject { async fetch(request: Request): Promise { const url = new URL(request.url); try { - if (request.method === "GET" && url.pathname === "/pipes") return json(this.rows(`SELECT id, name, project_id, team_id, filter_type, filter_target_id, source_kind, source_config, trigger_kind, trigger_config, max_concurrency, workspace_name, agent_kind, enabled, created_at, - (SELECT count(*) FROM runs WHERE runs.pipe_id = pipes.id AND runs.state IN ('starting','running','blocked','recovering')) AS active_agents, - (SELECT state FROM runs WHERE runs.pipe_id = pipes.id ORDER BY updated_at DESC, id DESC LIMIT 1) AS latest_run_state - FROM pipes ORDER BY created_at DESC`)); - if (request.method === "GET" && url.pathname.startsWith("/pipes/")) return await this.flowDetail(url.pathname.split("/")[2] ?? "", url); - if (request.method === "GET" && url.pathname === "/runs") return json(this.rows("SELECT id, pipe_id, issue_id, agent_name, state, created_at, updated_at FROM runs ORDER BY created_at DESC LIMIT 100")); - if (request.method === "GET" && /^\/runs\/[^/]+$/.test(url.pathname)) return await this.runDetail(decodeURIComponent(url.pathname.split("/")[2] ?? "")); if (request.method === "GET" && url.pathname === "/v1/runs") return this.listRuns(url); if (request.method === "GET" && /^\/v1\/runs\/[^/]+$/.test(url.pathname)) return await this.getRun(decodeURIComponent(url.pathname.split("/")[3] ?? "")); if (request.method === "POST" && /^\/v1\/runs\/[^/]+\/stop$/.test(url.pathname)) return await this.stopRun(decodeURIComponent(url.pathname.split("/")[3] ?? "")); - if (request.method === "GET" && url.pathname === "/v1/events") return this.listEvents(url); if (request.method === "GET" && url.pathname === "/v1/execution-targets") return await this.executionTargets(); if (request.method === "GET" && url.pathname === "/v1/jobs") return json(await Promise.all(this.rows("SELECT * FROM jobs ORDER BY created_at DESC").map(row => this.publicJob(row)))); if (request.method === "POST" && url.pathname === "/v1/jobs") return await this.createJob(await request.json()); @@ -194,7 +191,6 @@ export class Tenant extends DurableObject { const jobEventsMatch = url.pathname.match(/^\/v1\/jobs\/([^/]+)\/events$/); if (request.method === "GET" && jobEventsMatch) return this.listJobEvents(decodeURIComponent(jobEventsMatch[1]), url); if (request.method === "POST" && url.pathname === "/v1/job-handlers/test") return await this.testJobHandler(await request.json()); - if (request.method === "GET" && /^\/v1\/flows\/[^/]+$/.test(url.pathname)) return this.getFlow(decodeURIComponent(url.pathname.split("/")[3] ?? "")); if (request.method === "GET" && url.pathname === "/connections/status") return await this.connectionStatus(); if (request.method === "POST" && url.pathname === "/members") return await this.upsertMember(await request.json()); if (request.method === "GET" && url.pathname.startsWith("/members/")) return this.getMember(url.pathname.split("/")[2] ?? ""); @@ -213,17 +209,10 @@ export class Tenant extends DurableObject { if (request.method === "POST" && url.pathname === "/connections/exe/test") return await this.testExe(await request.json()); if (request.method === "PUT" && url.pathname === "/connections/amp") return await this.saveAmp(await request.json()); if (request.method === "POST" && url.pathname === "/connections/amp/test") return await this.testAmp(await request.json()); - if (request.method === "POST" && url.pathname === "/pipes") return await this.createPipe(await request.json() as PipeInput); - if (request.method === "PUT" && url.pathname.startsWith("/pipes/")) return await this.updatePipe(url.pathname.split("/")[2] ?? "", await request.json() as PipeInput); - if (request.method === "DELETE" && url.pathname.startsWith("/pipes/")) return this.deletePipe(url.pathname.split("/")[2] ?? ""); if (request.method === "POST" && url.pathname === "/webhook/linear") return await this.acceptLinearWebhook(await request.json() as Record, request.headers.get("linear-delivery")); if (request.method === "POST" && url.pathname === "/webhook/github") return await this.acceptGitHubWebhook(await request.json() as Record, request.headers.get("github-delivery"), request.headers.get("github-event")); - const customJobMatch = url.pathname.match(/^\/webhook\/custom\/([^/]+)$/); - if (request.method === "POST" && customJobMatch) return await this.acceptCustomJobWebhook(decodeURIComponent(customJobMatch[1]), await request.text(), request.headers); const tailMatch = url.pathname.match(/^\/webhook\/cloudflare\/([^/]+)$/); if (request.method === "POST" && tailMatch) return await this.acceptCloudflareTail(decodeURIComponent(tailMatch[1]), await request.text(), request.headers); - const tailTestMatch = url.pathname.match(/^\/cloudflare-tail\/([^/]+)\/test$/); - if (request.method === "POST" && tailTestMatch) return await this.testCloudflareTail(decodeURIComponent(tailTestMatch[1])); if (request.method === "GET" && url.pathname === "/github/installations") return this.githubInstallations(); if (request.method === "PUT" && url.pathname === "/github/installations") return this.saveGitHubInstallation(await request.json()); if (request.method === "POST" && url.pathname === "/github/setup-state") return this.saveSetupState(await request.json()); @@ -246,9 +235,9 @@ export class Tenant extends DurableObject { await this.processDueSchedules(); // Release completed slots before looking at the queue, so capacity is used // immediately rather than waiting for the next polling alarm. - const running = this.rows("SELECT * FROM runs WHERE state IN ('starting','running','blocked','recovering') ORDER BY updated_at LIMIT 40"); + const running = this.rows("SELECT * FROM runs WHERE pipe_id IN (SELECT id FROM jobs) AND state IN ('starting','running','blocked','recovering') ORDER BY updated_at LIMIT 40"); for (const run of running) await this.pollRun(run); - const queued = this.rows("SELECT * FROM runs WHERE state = 'queued' ORDER BY created_at LIMIT 20"); + const queued = this.rows("SELECT * FROM runs WHERE pipe_id IN (SELECT id FROM jobs) AND state = 'queued' ORDER BY created_at LIMIT 20"); for (const run of queued) { const pipe = this.executionConfig(run.pipe_id); if (!pipe) continue; @@ -260,7 +249,7 @@ export class Tenant extends DurableObject { await this.startRun({ ...run, agent_name: name, workspace_name: pipe.workspace_name }, pipe); } - const pending = this.one("SELECT count(*) AS count FROM runs WHERE state IN ('queued','starting','running','blocked','recovering')") as Row; + const pending = this.one("SELECT count(*) AS count FROM runs WHERE pipe_id IN (SELECT id FROM jobs) AND state IN ('queued','starting','running','blocked','recovering')") as Row; const verification = this.one("SELECT min(next_attempt_at) AS next_attempt_at FROM pending_verifications") as Row; const nextVerification = Number(verification?.next_attempt_at || 0); const schedule = this.one("SELECT min(next_run_at) AS next_run_at FROM schedule_state") as Row; @@ -390,8 +379,6 @@ export class Tenant extends DurableObject { private triggersFor(jobId: unknown): Row[] { return this.rows("SELECT * FROM triggers WHERE job_id = ? ORDER BY position,created_at,id", jobId); } private executionConfig(value: unknown): Row | undefined { - const pipe = this.one("SELECT * FROM pipes WHERE id = ?", value) as Row | undefined; - if (pipe) return pipe; const job = this.one("SELECT * FROM jobs WHERE id = ? AND enabled=1", value) as Row | undefined; if (!job) return undefined; let target: Record = {}; @@ -894,7 +881,7 @@ export class Tenant extends DurableObject { } private async testJobHandler(input: { handlerCode?: unknown; payload?: unknown }): Promise { - const config: WebhookTriggerConfig = { provider: "custom", handlerCode: typeof input.handlerCode === "string" ? input.handlerCode : undefined }; + const config: WebhookTriggerConfig = { provider: "linear", projectId: "handler-test", matchRules: [], handlerCode: typeof input.handlerCode === "string" ? input.handlerCode : undefined }; validateWebhookHandler(config); if (!config.handlerCode) throw new Error("Handler code is required."); if (!this.env.CUSTOM_HANDLER_LOADER) return Response.json({ ok: false, category: "platform_error" }, { status: 503 }); @@ -909,50 +896,13 @@ export class Tenant extends DurableObject { private async acceptLinearWebhook(event: Record, deliveryId: string | null): Promise { if (!deliveryId) return new Response("Missing delivery ID", { status: 400 }); - if (this.one("SELECT id FROM deliveries WHERE id = ?", deliveryId)) return new Response(null, { status: 200 }); - this.ctx.storage.sql.exec("INSERT INTO deliveries (id,pipe_id,received_at) VALUES (?,?,?)", deliveryId, "app-webhook", now()); - let matchingEvent = event; - let data = matchingEvent.data ?? {}; - let projectId = data.project?.id ?? data.issue?.project?.id; - const issueId = data.issueId ?? data.issue?.id ?? (matchingEvent.type === "Issue" ? data.id : undefined); - const pipes = this.rows("SELECT * FROM pipes WHERE enabled = 1 AND source_kind = 'linear'"); - const custom = this.rows("SELECT * FROM pipes WHERE enabled = 1 AND source_kind = 'custom'"); - - // IssueLabel is a join entity. Linear serializes it with issueId and labelId, - // and does not consistently expand the linked issue or its project. Resolve it - // once so label flows can still be scoped to their selected project. - if (!projectId && matchingEvent.type === "IssueLabel" && typeof issueId === "string") { - const linear = await this.connection<{ accessToken: string }>("linear"); - const issue = linear ? await this.linear(linear.accessToken, LINEAR_ISSUE_PROJECT_QUERY, { id: issueId }) : null; - projectId = issue?.issue?.project?.id; - if (projectId) { - data = { ...data, ...issue.issue, issue: { ...data.issue, ...issue.issue, id: issueId, project: { id: projectId } } }; - matchingEvent = { ...matchingEvent, data }; - } - } - await this.invokeWebhookJobs("linear", deliveryId, matchingEvent); - - for (const pipe of pipes) { - if (projectId !== pipe.project_id) continue; - const matchingIssueId = matchingIssue(matchingEvent, { projectId: String(pipe.project_id), matchRules: this.savedMatchRules(pipe) }); - if (!matchingIssueId) { - this.recordFlowEvent(pipe, deliveryId, null, null, matchingEvent, "ignored", "Webhook did not match this flow's trigger."); - continue; - } - const workItem = linearSource.toWorkItem(data, matchingIssueId, matchingEvent); - await this.queueWorkItem(pipe, deliveryId, workItem, linearSource.renderPrompt(String(pipe.context_template || DEFAULT_CONTEXT_TEMPLATE), data, String(pipe.name))); - } - await Promise.all(custom.map((pipe) => this.evaluateCustom(pipe, "linear", deliveryId, event))); + await this.invokeWebhookJobs("linear", deliveryId, event); await this.ctx.storage.setAlarm(Date.now()); return new Response(null, { status: 200 }); } private async acceptGitHubWebhook(event: Record, deliveryId: string | null, eventName: string | null): Promise { if (!deliveryId || !eventName) return new Response("Missing delivery metadata", { status: 400 }); - if (this.one("SELECT id FROM deliveries WHERE id = ?", deliveryId)) return new Response(null, { status: 200 }); - this.ctx.storage.sql.exec("INSERT INTO deliveries (id,pipe_id,received_at) VALUES (?,?,?)", deliveryId, "github-app", now()); - const custom = this.rows("SELECT * FROM pipes WHERE enabled=1 AND source_kind='custom'"); - await Promise.all(custom.map((pipe) => this.evaluateCustom(pipe, "github", deliveryId, event))); if (eventName !== "pull_request" || event.action !== "dequeued") await this.invokeWebhookJobs("github", deliveryId, event, eventName); if (eventName !== "pull_request" || event.action !== "dequeued") { await this.ctx.storage.setAlarm(Date.now()); return new Response(null, { status: 202 }); } const installationId = event.installation?.id, repositoryId = event.repository?.id, pull = event.pull_request; @@ -963,63 +913,21 @@ export class Tenant extends DurableObject { this.ctx.storage.sql.exec("INSERT INTO pending_verifications VALUES (?,?,?,?,?,?,?,?,?,?,?)", id(), job.id, deliveryId, installationId, repositoryId, event.repository.owner?.login ?? "", event.repository.name ?? "", pull.number, 0, Date.now(), JSON.stringify(minimal)); this.recordJobEvent(String(job.id), "github", deliveryId, "candidate", "Candidate received; waiting for GitHub mergeability verification."); } - const pipes = this.rows("SELECT * FROM pipes WHERE enabled=1 AND source_kind='github'"); - for (const pipe of pipes) { - const source = this.sourceFor(pipe); - if (source.kind !== "github" || source.installationId !== installationId || source.repositoryId !== repositoryId || pull.state !== "open" || pull.base?.ref !== "main") continue; - const minimal = { number: pull.number, url: pull.html_url, title: pull.title ?? "", body: pull.body ?? "", author: pull.user?.login ?? "", base: { ref: pull.base.ref, sha: pull.base.sha }, head: { ref: pull.head?.ref ?? "", sha: pull.head?.sha ?? "", repository: pull.head?.repo?.full_name ?? "" } }; - this.ctx.storage.sql.exec("INSERT INTO pending_verifications VALUES (?,?,?,?,?,?,?,?,?,?,?)", id(), pipe.id, deliveryId, installationId, repositoryId, source.repositoryOwner ?? event.repository.owner?.login ?? "", source.repositoryName ?? event.repository.name ?? "", pull.number, 0, Date.now(), JSON.stringify(minimal)); - this.recordFlowEvent(pipe, deliveryId, githubClaimKey(repositoryId, pull.number), pull.html_url ?? null, { type: "pull_request", action: "dequeued" }, "candidate", "Candidate received; waiting for GitHub mergeability verification.", "github"); - } await this.ctx.storage.setAlarm(Date.now()); return new Response(null, { status: 202 }); } - private async acceptCloudflareTail(flowId: string, raw: string, headers: Headers): Promise { - const pipe = this.one("SELECT * FROM pipes WHERE id=? AND enabled=1", flowId) as Row | undefined; - if (!pipe) { - const item = this.webhookJobs("cloudflareTail").find(({ job }) => job.id === flowId); + private async acceptCloudflareTail(jobId: string, raw: string, headers: Headers): Promise { + const item = this.webhookJobs("cloudflareTail").find(({ job }) => job.id === jobId); if (!item?.config.signingSecret) return new Response("Not found", { status: 404 }); const timestamp = headers.get("x-factorize-timestamp") ?? "", delivery = headers.get("x-factorize-delivery") ?? "", signature = headers.get("x-factorize-signature") ?? ""; if (!timestamp || !delivery || !signature) return new Response("Missing delivery metadata", { status: 400 }); const verification = await verifyTailDelivery(item.config.signingSecret, timestamp, delivery, raw, signature); - if (verification !== "valid") { this.recordJobEvent(flowId, "cloudflareTail", delivery, verification, "Tail delivery verification failed."); return new Response(verification === "stale" ? "Stale delivery" : "Invalid signature", { status: 401 }); } + if (verification !== "valid") { this.recordJobEvent(jobId, "cloudflareTail", delivery, verification, "Tail delivery verification failed."); return new Response(verification === "stale" ? "Stale delivery" : "Invalid signature", { status: 401 }); } let payload: Record; try { payload = sanitizeTailEvent(JSON.parse(raw)) as Record; } catch { return new Response("Invalid JSON", { status: 400 }); } - if (suppressTailEvent(payload)) { this.recordJobEvent(flowId, "cloudflareTail", delivery, "rejected", "Tail delivery was suppressed to prevent an ingestion loop."); return new Response(null, { status: 202 }); } + if (suppressTailEvent(payload)) { this.recordJobEvent(jobId, "cloudflareTail", delivery, "rejected", "Tail delivery was suppressed to prevent an ingestion loop."); return new Response(null, { status: 202 }); } await this.invokeWebhookJobs("cloudflareTail", delivery, payload, "tail"); return new Response(null, { status: 202 }); - } - const source = this.sourceFor(pipe); - if (source.kind !== "custom" || source.origin !== "cloudflare" || !source.tail?.signingSecret) return new Response("Not found", { status: 404 }); - const timestamp = headers.get("x-factorize-timestamp") ?? "", delivery = headers.get("x-factorize-delivery") ?? "", signature = headers.get("x-factorize-signature") ?? ""; - const metadataEvent = { type: "tail", action: "delivery" }; - if (!timestamp || !delivery || !signature) { this.recordFlowEvent(pipe, delivery || "missing", null, null, metadataEvent, "invalid", "Tail delivery metadata was missing.", "cloudflare"); return new Response("Missing delivery metadata", { status: 400 }); } - const verification = await verifyTailDelivery(source.tail.signingSecret, timestamp, delivery, raw, signature); - if (verification !== "valid") { this.recordFlowEvent(pipe, delivery, null, null, metadataEvent, verification, verification === "stale" ? "Tail delivery timestamp was stale." : "Tail delivery signature was invalid.", "cloudflare"); return new Response(verification === "stale" ? "Stale delivery" : "Invalid signature", { status: 401 }); } - if (this.one("SELECT id FROM deliveries WHERE id=?", `cloudflare:${delivery}`)) { this.recordFlowEvent(pipe, delivery, null, null, metadataEvent, "duplicate", "Tail delivery ID was already processed.", "cloudflare"); return new Response("Duplicate delivery", { status: 409 }); } - let parsed: Record; try { parsed = JSON.parse(raw); } catch { this.recordFlowEvent(pipe, delivery, null, null, metadataEvent, "invalid", "Tail delivery was not valid JSON.", "cloudflare"); return new Response("Invalid JSON", { status: 400 }); } - const event = sanitizeTailEvent(parsed) as Record; - this.ctx.storage.sql.exec("INSERT INTO deliveries (id,pipe_id,received_at) VALUES (?,?,?)", `cloudflare:${delivery}`, pipe.id, now()); - if (suppressTailEvent(event)) { this.recordFlowEvent(pipe, delivery, null, null, metadataEvent, "rejected", "Tail delivery was suppressed to prevent a Factorize ingestion loop.", "cloudflare"); return new Response(null, { status: 202 }); } - const fingerprint = await tailFingerprint(event), windowMs = 5 * 60_000, limit = 5; - const seen = this.one("SELECT * FROM tail_fingerprints WHERE flow_id=? AND fingerprint=?", pipe.id, fingerprint) as Row | undefined; - if (seen && Date.now() - Number(seen.window_started) < windowMs && Number(seen.count) >= limit) { this.ctx.storage.sql.exec("UPDATE tail_fingerprints SET count=count+1 WHERE flow_id=? AND fingerprint=?", pipe.id, fingerprint); this.recordFlowEvent(pipe, delivery, null, null, metadataEvent, "rate_limited", "Repeated Tail event fingerprint exceeded the per-flow limit.", "cloudflare"); return new Response("Rate limited", { status: 429 }); } - if (!seen || Date.now() - Number(seen.window_started) >= windowMs) this.ctx.storage.sql.exec("INSERT INTO tail_fingerprints VALUES (?,?,?,1) ON CONFLICT(flow_id,fingerprint) DO UPDATE SET window_started=excluded.window_started,count=1", pipe.id, fingerprint, Date.now()); - else this.ctx.storage.sql.exec("UPDATE tail_fingerprints SET count=count+1 WHERE flow_id=? AND fingerprint=?", pipe.id, fingerprint); - await this.evaluateCustom(pipe, "cloudflare", delivery, event); - await this.ctx.storage.setAlarm(Date.now()); - return new Response(null, { status: 202 }); - } - - private async acceptCustomJobWebhook(jobId: string, raw: string, headers: Headers): Promise { - const item = this.webhookJobs("custom").find(({ job }) => job.id === jobId); - if (!item) return new Response("Not found", { status: 404 }); - if (item.config.secret && headers.get("x-factorize-secret") !== item.config.secret) { this.recordJobEvent(jobId, "custom", "unknown", "invalid", "Custom webhook secret was invalid."); return new Response("Invalid secret", { status: 401 }); } - let payload: Record; try { payload = JSON.parse(raw); } catch { return new Response("Invalid JSON", { status: 400 }); } - let delivery = headers.get("x-factorize-delivery"); - if (delivery === null) delivery = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(raw)).then(value => [...new Uint8Array(value)].map(byte => byte.toString(16).padStart(2, "0")).join("")); - await this.invokeWebhookJobs("custom", delivery!, payload, headers.get("x-factorize-event") ?? undefined); - return new Response(null, { status: 202 }); } private async testCloudflareTail(flowId: string): Promise { @@ -1066,7 +974,7 @@ export class Tenant extends DurableObject { return; } const workItem: WorkItem = { provider: origin, claimKey: deliveryId, identifier: deliveryId, title: source.handlerName, description: "", url: "", event: payload }; - const prompt = renderSourcePrompt(source, String(pipe.context_template || DEFAULT_CONTEXT_TEMPLATE), payload, String(pipe.name), deliveryId); + const prompt = Mustache.render(String(pipe.context_template || DEFAULT_CONTEXT_TEMPLATE), payload); await this.queueWorkItem(pipe, deliveryId, workItem, prompt); } @@ -1086,9 +994,8 @@ export class Tenant extends DurableObject { const pending = this.rows("SELECT * FROM pending_verifications WHERE next_attempt_at <= ? ORDER BY next_attempt_at LIMIT 20", Date.now()); const delays = [0, 5_000, 15_000, 30_000, 60_000]; for (const verification of pending) { - const pipe = this.one("SELECT * FROM pipes WHERE id=?", verification.flow_id) as Row | undefined; - const job = pipe ? undefined : this.one("SELECT j.*,t.id AS trigger_id,t.slug AS trigger_slug,t.config AS trigger_config FROM jobs j JOIN triggers t ON t.job_id=j.id WHERE j.id=? AND j.enabled=1 AND t.enabled=1 AND t.kind='webhook' ORDER BY t.created_at LIMIT 1", verification.flow_id) as Row | undefined; - const target = pipe ?? job; + const job = this.one("SELECT j.*,t.id AS trigger_id,t.slug AS trigger_slug,t.config AS trigger_config FROM jobs j JOIN triggers t ON t.job_id=j.id WHERE j.id=? AND j.enabled=1 AND t.enabled=1 AND t.kind='webhook' ORDER BY t.created_at LIMIT 1", verification.flow_id) as Row | undefined; + const target = job; if (!target) { this.ctx.storage.sql.exec("DELETE FROM pending_verifications WHERE id=?", verification.id); continue; } const installation = this.one("SELECT state FROM github_installations WHERE installation_id=?", verification.installation_id) as Row | undefined; if (installation?.state !== "active") { this.finishVerification(verification, target, "verification_failed", "GitHub installation is disconnected.", Boolean(job)); continue; } @@ -1122,13 +1029,6 @@ export class Tenant extends DurableObject { this.recordJobEvent(String(job.id), "github", String(verification.delivery_id), result?.duplicate ? "duplicate" : result ? "accepted" : "ignored", result?.duplicate ? "Webhook occurrence was already claimed." : result ? "Verified webhook queued through canonical job invocation." : "Job was unavailable."); continue; } - const legacyPipe = pipe!; - const source = this.sourceFor(legacyPipe); - if (source.kind !== "github" || source.repositoryId !== Number(verification.repository_id)) { this.finishVerification(verification, legacyPipe, "ignored", "Flow source changed while verification was pending."); continue; } - const saved = JSON.parse(String(verification.payload)); - const workItem: WorkItem = { provider: "github", claimKey: githubClaimKey(source.repositoryId, pull.number), identifier: `${source.repositoryFullName}#${pull.number}`, title: pull.title ?? saved.title, description: pull.body ?? saved.body, url: pull.html_url, event: { type: "pull_request", name: "pull_request", action: "dequeued", delivery: verification.delivery_id }, repository: { id: source.repositoryId, owner: source.repositoryOwner, name: source.repositoryName, fullName: source.repositoryFullName }, pullRequest: { number: pull.number, url: pull.html_url, title: pull.title ?? "", body: pull.body ?? "", author: pull.user?.login ?? "", base: { ref: pull.base.ref, sha: pull.base.sha }, head: { ref: pull.head?.ref ?? "", sha: pull.head?.sha ?? "", repository: pull.head?.repo?.full_name ?? "" } } }; - this.ctx.storage.sql.exec("DELETE FROM pending_verifications WHERE id=?", verification.id); - await this.queueWorkItem(legacyPipe, String(verification.delivery_id), workItem, renderGitHubPrompt(workItem, { id: String(legacyPipe.id), name: String(legacyPipe.name) })); } catch (error) { await this.retryVerification(verification, target, delays, error instanceof Error ? error.message : "GitHub verification failed.", undefined, Boolean(job)); } } } @@ -1515,10 +1415,7 @@ export class Tenant extends DurableObject { } const source = input.source; if (source.kind === "custom") { - const valid = validateCustomHandler(source.origin, source.handlerName, source.handlerCode); - if (!source.handlerDeployment || source.handlerDeployment.state !== "ready" || !/^fh-[a-f0-9]{40}$/.test(source.handlerDeployment.scriptName) || !/^[a-f0-9]{64}$/.test(source.handlerDeployment.codeDigest)) throw new Error("Custom handler deployment is not ready."); - if (valid.origin === "cloudflare" && (!source.tail?.signingSecret || source.tail.signingSecret.length < 32)) throw new Error("Cloudflare Tail signing is not configured."); - return { kind: "custom", ...valid, handlerDeployment: source.handlerDeployment, ...(valid.origin === "cloudflare" ? { tail: source.tail } : {}) }; + throw new Error("Custom Flow sources are no longer supported."); } if (source.baseRef !== "main" || source.trigger !== "merge_queue_conflict" || !Number.isSafeInteger(source.installationId) || !Number.isSafeInteger(source.repositoryId)) throw new Error("Invalid GitHub source"); const installation = this.one("SELECT state FROM github_installations WHERE installation_id=?", source.installationId) as Row | undefined; diff --git a/packages/app/src/trigger-context.ts b/packages/app/src/trigger-context.ts index 82b9f14d..d35e52e8 100644 --- a/packages/app/src/trigger-context.ts +++ b/packages/app/src/trigger-context.ts @@ -42,7 +42,6 @@ export const triggerContextCatalog: Record = { { path: "logs", type: "array", description: "Sanitized console log records." }, { path: "exceptions", type: "array", description: "Sanitized exception records." }, ], - custom: [...commonWebhook, { path: "*", type: "unknown", description: "Additional submitted JSON fields are dynamic and may be nested." }], jobLifecycle: [ { path: "source_job_id", type: "string", description: "Job whose run reached a final state." }, { path: "source_run_id", type: "string", description: "Run that reached a final state." }, @@ -53,10 +52,10 @@ export const triggerContextCatalog: Record = { }; export function reflectTriggerContext(trigger: { slug?: unknown; kind?: unknown; config?: any }): TriggerContextReflection { - const kind = String(trigger.kind ?? ""), provider = kind === "webhook" ? String(trigger.config?.provider ?? "custom") : undefined; + const kind = String(trigger.kind ?? ""), provider = kind === "webhook" ? String(trigger.config?.provider ?? "") : undefined; const key = provider ?? kind, handler = kind === "webhook" && typeof trigger.config?.handlerCode === "string" && trigger.config.handlerCode.trim().length > 0; return { - slug: String(trigger.slug ?? ""), kind, ...(provider ? { provider } : {}), dynamic: key === "custom" || handler, - paths: handler ? [{ path: "*", type: "unknown", description: "The custom handler replaces context with a dynamic JSON object; inspect the handler contract." }] : (triggerContextCatalog[key] ?? [{ path: "*", type: "unknown", description: "Context shape is not known." }]), + slug: String(trigger.slug ?? ""), kind, ...(provider ? { provider } : {}), dynamic: handler, + paths: handler ? [{ path: "*", type: "unknown", description: "The provider handler replaces context with a dynamic JSON object; inspect the handler contract." }] : (triggerContextCatalog[key] ?? [{ path: "*", type: "unknown", description: "Context shape is not known." }]), }; } diff --git a/packages/app/src/types.ts b/packages/app/src/types.ts index d49a1335..7c9370f1 100644 --- a/packages/app/src/types.ts +++ b/packages/app/src/types.ts @@ -17,7 +17,6 @@ export interface Env { GITHUB_APP_SLUG?: string; GITHUB_APP_PRIVATE_KEY?: string; GITHUB_WEBHOOK_SECRET?: string; - CUSTOM_SOURCES_ENABLED?: string; CUSTOM_HANDLER_LOADER?: WorkerLoader; RECOVERY_TIMEOUT_MS?: string; RECOVERY_MAX_ATTEMPTS?: string; @@ -33,14 +32,6 @@ export type OAuthProps = { accessTokenId?: string; }; -export type CustomOrigin = "linear" | "github" | "cloudflare"; -export type CustomSource = { kind: "custom"; origin: CustomOrigin; handlerName: string; handlerCode: string; handlerDeployment: { scriptName: string; codeDigest: string; state: "deploying" | "ready" | "failed"; lastError?: string }; tail?: { signingSecret: string } }; - -export type FlowSource = - | { kind: "linear"; projectId: string; matchRules: MatchRule[] } - | { kind: "github"; installationId: number; repositoryId: number; repositoryOwner?: string; repositoryName?: string; repositoryFullName?: string; baseRef: "main"; trigger: "merge_queue_conflict" } - | CustomSource; - export interface WorkItem { provider: "linear" | "github" | "cloudflare"; claimKey: string; @@ -53,26 +44,6 @@ export interface WorkItem { pullRequest?: Record; } -export interface PipeInput { - /** Edge-generated immutable identifier; never accepted from browser callers. */ - pipeId?: string; - name: string; - /** Optional stable, machine-friendly identifier; defaults from the name. */ - flowId?: string; - projectId?: string; - /** At least one rule is required. All rules must match the issue. */ - matchRules: MatchRule[]; - maxConcurrency: number; - workspaceName?: string; - /** Mustache template rendered with the Linear webhook payload for each run. */ - contextTemplate?: string; - /** Saved exe.dev connection selected for this flow. */ - exeConnectionId?: string; - /** Mustache template for the working directory; receives `flowId`. */ - cwd?: string; - source?: FlowSource; -} - export interface ExeConnectionInput { connectionId?: string; vmName: string; diff --git a/packages/app/src/ui.ts b/packages/app/src/ui.ts index 1fb75226..921782fc 100644 --- a/packages/app/src/ui.ts +++ b/packages/app/src/ui.ts @@ -43,157 +43,6 @@ export const landingPage = (viewer: Viewer) => shell("Factorize: Software Factor `); -export const flowPage = (viewer: Viewer, editFlowId?: string) => viewer ? shell(`${editFlowId ? "Edit" : "Create"} Flow — Factorize`, viewer, ` -
-
← My Flows

${editFlowId ? "Edit flow" : "Create a flow"}

Connect the pieces, then Factorize takes it from there.

-
-
-

Capacity

Max Concurrency

Choose how many agents can work on this flow at once.

3
-
0
Paused
2550
agents

At 0, new work stays queued until you raise the limit.

-
-
-
1

Source

Connected

Choose which provider event starts this flow.

-

Issue matching rules

An issue must match every rule. Add one or more rules.

-
-
-
-
2

Exe.dev config

Checking…

Connect to the VM where your working directory lives.

-
- -
-
-
-
-
3

Herdr config

Tell Factorize where to find Herdr on your VM.

-
-
-
4

Agent config

Choose the agent and customize the context sent for every matching Linear issue.

Uses Mustache. The complete Linear webhook payload is available directly (for example {{title}}); ticket is a normalized issue alias, and flow.name is this flow’s name. Use triple braces such as {{{ticket.description}}} to preserve Markdown.
-
- - -
-
`, ` -const editFlowId=${JSON.stringify(editFlowId ?? "")}; -const nameInput=document.querySelector('[name=name]'),flowConfig=document.querySelector('#max-concurrency').closest('section'),flowConfigHeading=flowConfig.querySelector('h2'); -flowConfigHeading.textContent='Flow config';flowConfigHeading.previousElementSibling.textContent='FLOW';flowConfigHeading.nextElementSibling.textContent='Name this flow, choose its stable ID, and set its capacity.'; -nameInput.removeAttribute('pattern');nameInput.removeAttribute('title');nameInput.removeAttribute('maxlength');nameInput.placeholder='Bug fixes'; -const flowIdInput=document.createElement('input'),flowIdLabel=document.createElement('label'),flowConfigFields=document.createElement('div'); -flowIdInput.className='field';flowIdInput.name='flowId';flowIdInput.placeholder='bug-fixes';flowIdInput.maxLength=30;flowIdInput.pattern='[a-z][a-z0-9_-]{0,29}';flowIdInput.title='Use lowercase letters, digits, hyphens, or underscores.'; -flowIdLabel.className='label';flowIdLabel.textContent='Flow ID';flowIdLabel.append(flowIdInput);const flowNameLabel=nameInput.closest('label');flowNameLabel.firstChild.textContent='Flow name'; -flowConfigFields.className='mt-6 grid gap-5 sm:grid-cols-2';flowConfigFields.append(flowNameLabel,flowIdLabel);flowConfig.querySelector('.mt-7').before(flowConfigFields); -const slugFor=value=>value.trim().toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-+|-+$/g,'').slice(0,30)||'flow';let flowIdEdited=false; -nameInput.oninput=()=>{if(!flowIdEdited)flowIdInput.value=slugFor(nameInput.value)};flowIdInput.oninput=()=>{flowIdEdited=flowIdInput.value!==''}; -if(editFlowId)fetch('/api/pipes/'+encodeURIComponent(editFlowId)).then(response=>response.ok?response.json():null).then(data=>{if(data?.flow?.workspace_name){flowIdInput.value=data.flow.workspace_name;flowIdEdited=true}}).catch(()=>{}); -const $=s=>document.querySelector(s), data=f=>Object.fromEntries(new FormData(f));let exeConnected=false,linearOptions={statuses:[],users:[],labels:[]}; -let githubRepositories=[];const sourceKind=$('#source-kind'),linearSource=$('#linear-source'),githubSource=$('#github-source'),customSource=$('#custom-source'),githubInstallation=$('#github-installation'),githubRepository=$('#github-repository'); -const tailCredentials=document.createElement('section');tailCredentials.id='tail-credentials';tailCredentials.className='hidden sm:col-span-2 rounded-xl border border-amber-300 bg-amber-50 p-4';tailCredentials.innerHTML='

Cloudflare Tail credentials

';customSource.append(tailCredentials); -const loadRepositories=async()=>{githubRepository.replaceChildren(new Option('Loading repositories…',''));const installation=githubInstallation.value;if(!installation)return;const response=await fetch('/api/github/installations/'+encodeURIComponent(installation)+'/repositories');if(!response.ok){githubRepository.replaceChildren(new Option('Repository access unavailable',''));return}githubRepositories=await response.json();githubRepository.replaceChildren(...githubRepositories.map(repo=>new Option(repo.fullName,repo.id)));}; -const syncSource=()=>{const github=sourceKind.value==='github',custom=sourceKind.value==='custom';linearSource.classList.toggle('hidden',github||custom);linearSource.classList.toggle('contents',!github&&!custom);githubSource.classList.toggle('hidden',!github);customSource.classList.toggle('hidden',!custom);tailCredentials.classList.toggle('hidden',!custom||!editFlowId);$('#project').required=!github&&!custom;$('#context-template').required=!github;};sourceKind.onchange=syncSource;githubInstallation.onchange=loadRepositories; -sourceKind.querySelector('option[value=custom]').textContent='Cloudflare Tail';const customOrigin=$('[name=customOrigin]');customOrigin.append(new Option('Cloudflare','cloudflare'));customOrigin.value='cloudflare';customOrigin.onchange=()=>{if(customOrigin.value==='cloudflare'){$('[name=handlerName]').value='Cloudflare Worker failures';$('[name=handlerCode]').value='function handler(webhook) {\\n return webhook.outcome === "exception" || webhook.logs.some((log) => log.level === "error");\\n}'}}; -fetch('/api/github/installations').then(async response=>{if(response.status===404){sourceKind.querySelector('option[value=github]')?.remove();return}if(!response.ok)return;const installations=await response.json(),active=installations.filter(item=>item.state==='active');githubInstallation.replaceChildren(...installations.map(item=>new Option(item.accountLogin+(item.state==='active'?'':' ('+item.state+')'),item.installationId)));$('#github-empty').classList.toggle('hidden',installations.length>0);if(active.length){githubInstallation.value=String(active[0].installationId);await loadRepositories()}else if(installations.length){$('#github-warning').textContent='This installation is disconnected. Reconnect it before saving the flow.';$('#github-warning').classList.remove('hidden')}}).catch(()=>{});syncSource(); -const defaultContextTemplate=$('#context-template').value; -const agentCommandDefaults={codex:'--dangerously-bypass-approvals-and-sandbox',claude:'--dangerously-skip-permissions',pi:''};let agentCommandCustomized=false; -const defaultAgentCommand=()=>agentCommandDefaults[$('[name=agentKind]').value]??''; -const agentCommandInput=$('#agent-command'); -agentCommandInput.value=defaultAgentCommand(); -$('[name=agentKind]').onchange=()=>{if(!agentCommandCustomized)agentCommandInput.value=defaultAgentCommand()}; -agentCommandInput.oninput=()=>{agentCommandCustomized=agentCommandInput.value!==defaultAgentCommand()}; -const maxConcurrency=$('#max-concurrency'),maxConcurrencyValue=$('#max-concurrency-value'); -const syncMaxConcurrency=()=>{maxConcurrencyValue.value=maxConcurrency.value;maxConcurrencyValue.textContent=maxConcurrency.value}; -maxConcurrency.oninput=syncMaxConcurrency; -const showError=(m,shouldScroll=true)=>{const el=$('#error');el.textContent=m;el.classList.remove('hidden');if(shouldScroll)el.scrollIntoView({behavior:'smooth',block:'center'})}; -const ruleNames={owner:'Owner',creator:'Creator',status:'Status',label:'Label',assignee:'Assignee'}; -const ruleItems=type=>type==='status'?linearOptions.statuses:['owner','creator','assignee'].includes(type)?linearOptions.users:linearOptions.labels; -const $$=s=>Array.from(document.querySelectorAll(s)); -const ruleRows=()=>$$('#match-rules .rule-row'); -function syncRuleControls(){const multiple=ruleRows().length>1;ruleRows().forEach(row=>row.querySelector('[data-remove-rule]').classList.toggle('hidden',!multiple))} -function addRule(rule={type:'status',targetId:''}){const rules=$('#match-rules');if(ruleRows().length){const join=document.createElement('div');join.className='rule-join flex items-center gap-3 py-1 text-xs font-semibold uppercase tracking-wide text-factorize-700 dark:text-factorize-100';join.setAttribute('aria-label','All rules must match');join.innerHTML='+All must match';rules.append(join)}const row=document.createElement('div');row.className='rule-row grid gap-3 rounded-xl border border-stone-200 bg-stone-50 p-3 sm:grid-cols-[minmax(0,1fr)_minmax(0,1.35fr)_auto] sm:items-end dark:border-slate-700 dark:bg-slate-950';const typeField=document.createElement('label');typeField.className='label';typeField.textContent='Match on';const type=document.createElement('select');type.className='field';type.innerHTML=Object.entries(ruleNames).map(([value,label])=>'').join('');type.value=rule.type;typeField.append(type);const targetField=document.createElement('label');targetField.className='label';targetField.textContent='Value';const target=document.createElement('select');target.className='field';const fill=()=>{target.replaceChildren(new Option('Choose '+ruleNames[type.value].toLowerCase(),''));ruleItems(type.value).forEach(item=>target.add(new Option(item.name,item.id)));target.value=rule.targetId||''};type.onchange=fill;fill();targetField.append(target);const remove=document.createElement('button');remove.type='button';remove.dataset.removeRule='';remove.className='rounded-lg border border-stone-300 px-3 py-2 text-sm font-semibold text-red-600 hover:bg-red-50 dark:border-slate-700 dark:text-red-400 dark:hover:bg-red-950/50';remove.textContent='Delete';remove.onclick=()=>{const previous=row.previousElementSibling,next=row.nextElementSibling;if(previous?.classList.contains('rule-join'))previous.remove();else if(next?.classList.contains('rule-join'))next.remove();row.remove();syncRuleControls()};row.append(typeField,targetField,remove);rules.append(row);syncRuleControls()} -function readRules(){return ruleRows().map(row=>{const [type,target]=row.querySelectorAll('select');return {type:type.value,targetId:target.value}})} -async function init(){try{const [projects,options,status,existing]=await Promise.all([fetch('/api/linear/projects'),fetch('/api/linear/options'),fetch('/api/connections/status'),editFlowId?fetch('/api/pipes/'+encodeURIComponent(editFlowId)):Promise.resolve(null)]);if(projects.status===401)return location.href='/auth/linear';if(!projects.ok){const result=await projects.json().catch(()=>({}));showError(result.error||'Could not load your Linear projects. Reconnect Linear and try again.',false);return}const projectList=await projects.json();const select=$('#project');select.replaceChildren(...projectList.map(p=>new Option(p.name,p.id)));if(projectList.length)select.value=projectList[0].id;if(options.ok)linearOptions=await options.json();let flow; if(existing){if(!existing.ok)throw new Error('Could not load this flow.');flow=(await existing.json()).flow;const form=$('#flow');form.elements.name.value=flow.name;select.value=flow.project_id;let saved=[];try{saved=JSON.parse(flow.match_rules||'[]')}catch{};(saved.length?saved:[{type:flow.filter_type,targetId:flow.filter_target_id}]).forEach(addRule);let source={};try{source=JSON.parse(flow.source_config||'{}')}catch{};if(flow.source_kind==='github'){sourceKind.value='github';syncSource();githubInstallation.value=String(source.installationId||'');await loadRepositories();githubRepository.value=String(source.repositoryId||'')}else if(flow.source_kind==='custom'){sourceKind.value='custom';form.elements.customOrigin.value=source.origin||'linear';form.elements.handlerName.value=source.handlerName||'';form.elements.handlerCode.value=source.handlerCode||'';syncSource()}form.elements.maxConcurrency.value=flow.max_concurrency;form.elements.contextTemplate.value=flow.context_template||form.elements.contextTemplate.value;form.elements.cwd.value=flow.cwd||''}else addRule();const connectionSelect=$('#exe-connection');if(status.ok){const s=await status.json(),connections=s.exeConnections||[];if(connections.length){connectionSelect.replaceChildren(...connections.map(c=>new Option(c.vmName+' · '+c.agentKind,c.connectionId)),new Option('Add a new connection…','new'));connectionSelect.value=flow?.exe_connection_id||connections[0].connectionId;exeConnected=true;const chosen=connections.find(c=>c.connectionId===connectionSelect.value)||connections[0],form=$('#flow');form.elements.agentKind.value=chosen.agentKind||'codex';if(!form.elements.cwd.value)form.elements.cwd.value=chosen.cwd||'';form.elements.herdrCommand.value=chosen.herdrCommand||'herdr';agentCommandInput.value=chosen.agentCommand??defaultAgentCommand();agentCommandCustomized=agentCommandInput.value!==defaultAgentCommand();$('#exe-status').textContent='Saved connection';$('#exe-status').className='rounded-full bg-factorize-50 px-2.5 py-1 text-xs font-medium text-factorize-700 dark:bg-factorize-500/20 dark:text-factorize-100'}else{connectionSelect.replaceChildren(new Option('Add a new connection…','new'));connectionSelect.value='new';$('#exe-fields').classList.remove('hidden');$('#exe-status').textContent='Not connected'}}else{connectionSelect.replaceChildren(new Option('Could not load connections',''));$('#exe-status').textContent='Unavailable'}connectionSelect.onchange=()=>{const adding=connectionSelect.value==='new';$('#exe-fields').classList.toggle('hidden',!adding);exeConnected=!adding;if(!adding){const chosen=connections.find(c=>c.connectionId===connectionSelect.value);if(chosen){$('#flow').elements.cwd.value=chosen.cwd||'';$('#flow').elements.agentKind.value=chosen.agentKind||'codex'}}}}catch(err){showError(err.message||'Could not reach Factorize. Check your connection and try again.',false)}} -// Connection choices identify only the VM destination. Agent kind belongs to -// the flow and is deliberately omitted from this picker. -if(editFlowId)fetch('/api/pipes/'+encodeURIComponent(editFlowId)).then(r=>r.ok?r.json():null).then(data=>{if(!data?.cloudflareTail)return;const form=$('#flow');form.elements.tailDestination.value=data.cloudflareTail.destination||'';form.elements.tailSigningSecret.value=data.cloudflareTail.signingSecret||''}).catch(()=>{}); -const tailSecret=$('[name=tailSigningSecret]');tailSecret.oninput=()=>$('#tail-secret-warning').classList.remove('hidden');$('#show-tail-secret').onclick=()=>{tailSecret.type=tailSecret.type==='password'?'text':'password';$('#show-tail-secret').textContent=tailSecret.type==='password'?'Show':'Hide'};$('#generate-tail-secret').onclick=()=>{const bytes=crypto.getRandomValues(new Uint8Array(32));tailSecret.value=btoa(String.fromCharCode(...bytes)).replaceAll('+','-').replaceAll('/','_').replaceAll('=','');tailSecret.dispatchEvent(new Event('input'))};$$('[data-copy]').forEach(button=>button.onclick=()=>navigator.clipboard.writeText($('[name='+button.dataset.copy+']').value)); -const browserFetch=window.fetch.bind(window);window.fetch=(input,init)=>{if(init?.body&&/^\/api\/pipes(?:\/|$)/.test(String(input))){try{const body=JSON.parse(String(init.body));if(body.source?.kind==='custom'&&body.source.origin==='cloudflare'){body.source={kind:'cloudflareTail',handlerCode:body.source.handlerCode};if(editFlowId)body.tailSigningSecret=tailSecret.value;init={...init,body:JSON.stringify(body)}}}catch{}}return browserFetch(input,init)}; -const connectionPicker=$('#exe-connection');new MutationObserver(()=>Array.from(connectionPicker.options).forEach(option=>{if(option.value!=='new')option.textContent=option.textContent.split(' · ')[0]})).observe(connectionPicker,{childList:true}); -$('#add-rule').onclick=()=>addRule(); -const tailContextTemplate='---\npipe: "{{{flow.name}}}"\nsource: "Cloudflare Tail"\ndelivery: "{{{deliveryId}}}"\n---\n\n# Cloudflare Worker Tail event\n\n\`\`\`json\n{{{eventJson}}}\n\`\`\`';$('#reset-context-template').onclick=()=>{if(confirm('Reset this context template to Factorize’s default? Your current edits will be discarded.'))$('#context-template').value=sourceKind.value==='custom'?tailContextTemplate:defaultContextTemplate}; -$('#test-exe').onclick=async()=>{const values=data($('#flow')),button=$('#test-exe'),result=$('#exe-test-result'),status=$('#exe-test-status');button.disabled=true;status.classList.add('hidden');result.classList.add('hidden');try{const payload=values.apiToken?{vmName:values.vmName,agentKind:values.agentKind,cwd:values.cwd,herdrCommand:values.herdrCommand,apiToken:values.apiToken}:{connectionId:values.exeConnection};const r=await fetch('/api/connections/exe/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload)});const body=await r.json().catch(()=>({}));if(r.ok&&body.ok){status.textContent='✓';status.className='grid h-6 w-6 place-items-center rounded-full bg-green-600 text-sm font-bold text-white';status.setAttribute('aria-label','Connection successful');return}status.textContent='×';status.className='grid h-6 w-6 place-items-center rounded-full bg-red-600 text-lg font-bold leading-none text-white';status.setAttribute('aria-label','Connection failed');result.textContent=body.error||('HTTP '+(body.httpStatus??r.status)+(body.exitCode!=null?' · VM exit '+body.exitCode:'')+'\\n\\n'+(body.output||'Connection test failed.'));result.classList.remove('hidden')}catch(err){status.textContent='×';status.className='grid h-6 w-6 place-items-center rounded-full bg-red-600 text-lg font-bold leading-none text-white';status.setAttribute('aria-label','Connection failed');result.textContent=err instanceof Error?err.message:'Connection test failed.';result.classList.remove('hidden')}finally{button.disabled=false}}; -$('#test-handler').onclick=async()=>{const values=data($('#flow')),result=$('#handler-test-result');result.classList.remove('hidden');result.textContent='Deploying isolated test…';try{const payload=JSON.parse(values.handlerSample||'{}'),response=await fetch('/api/custom-handlers/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({origin:values.customOrigin,handlerName:values.handlerName||'Test handler',handlerCode:values.handlerCode,payload})}),body=await response.json();result.textContent=response.ok?(body.ok?'Handler returned '+body.decision:'Handler failed: '+body.category):(body.error||'Test failed.')}catch(err){result.textContent=err instanceof Error?err.message:'Test failed.'}}; -$('#flow').onsubmit=async e=>{e.preventDefault();$('#error').classList.add('hidden');const values=data(e.currentTarget),button=$('#submit'),editing=!!editFlowId;button.disabled=true;button.textContent=editing?'Saving…':'Creating…';try{const matchRules=readRules(),isGitHub=values.sourceKind==='github',isCustom=values.sourceKind==='custom';if(!isGitHub&&!isCustom&&matchRules.some(rule=>!rule.targetId))throw new Error('Choose a target for every matching rule.');if(!values.cwd)throw new Error('Choose a working directory.');if(isGitHub&&(!values.githubInstallation||!values.githubRepository))throw new Error('Choose an active GitHub installation and repository.');if(isCustom&&(!values.handlerName||!values.handlerCode))throw new Error('Provide a handler name and complete function.');let connectionId=values.exeConnection;if(!exeConnected){if(!values.vmName||!values.apiToken)throw new Error('Complete the new Exe.dev connection.');const r=await fetch('/api/connections/exe',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify({vmName:values.vmName,agentKind:values.agentKind,cwd:values.cwd,herdrCommand:values.herdrCommand,agentCommand:values.agentCommand,apiToken:values.apiToken})});const result=await r.json().catch(()=>({}));if(!r.ok)throw new Error(result.error||'Could not connect to Herdr.');connectionId=result.connectionId}const source=isGitHub?{kind:'github',installationId:Number(values.githubInstallation),repositoryId:Number(values.githubRepository),baseRef:'main',trigger:'merge_queue_conflict'}:isCustom?{kind:'custom',origin:values.customOrigin,handlerName:values.handlerName,handlerCode:values.handlerCode}:{kind:'linear',projectId:values.projectId,matchRules};const r=await fetch('/api/pipes'+(editing?'/'+encodeURIComponent(editFlowId):''),{method:editing?'PUT':'POST',headers:{'content-type':'application/json'},body:JSON.stringify({name:values.name,flowId:values.flowId,projectId:values.projectId,matchRules,source,contextTemplate:values.contextTemplate,maxConcurrency:Number(values.maxConcurrency),exeConnectionId:connectionId,cwd:values.cwd})});const result=await r.json().catch(()=>({}));if(!r.ok)throw new Error(result.error||'Could not save the flow.');location.href=editing?'/flows/'+encodeURIComponent(editFlowId):'/flows'}catch(err){showError(err.message||'Something went wrong.');button.disabled=false;button.textContent=editing?'Save Changes':'Create Flow'}};syncMaxConcurrency();init().then(syncMaxConcurrency); -`) : shell("Create Flow — Factorize", null, `

Start with Linear

Connect your workspace to create your first flow.

Connect Linear
`); - -const legacyFlowDetailPage = (viewer: { email: string }, flowId: string) => shell("Flow activity — Factorize", viewer, ` -
- ← My Flows -

Loading flow activity…

-
`, ` -const root=document.querySelector('#flow-detail'),flowId=root.dataset.flowId; -const esc=v=>{const d=document.createElement('div');d.textContent=v??'';return d.innerHTML}; -const time=v=>new Date(v).toLocaleString(); -const badge=(value,good)=>''+esc(value)+''; -const issueLink=(id,url)=>{if(!id)return '—';const trusted=typeof url==='string'&&(url.startsWith('https://linear.app/')||/^https:\\/\\/github\\.com\\/[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+\\/pull\\/\\d+$/.test(url));const href=trusted?url:'https://linear.app/issue/'+encodeURIComponent(id);return ''+esc(id)+' ↗'}; -async function load(){const response=await fetch('/api/pipes/'+encodeURIComponent(flowId));if(response.status===401)return location.href='/auth/linear';if(!response.ok){root.innerHTML='

Could not load this flow.

';return}const data=await response.json(),flow=data.flow,events=data.events||[],runs=data.runs||[];const eventRows=events.map(event=>''+time(event.received_at)+''+issueLink(event.issue_id,event.issue_url)+''+esc(event.event_type)+' · '+esc(event.event_action)+''+badge(event.outcome,event.outcome==='triggered')+''+esc(event.detail)+'').join('')||'No relevant webhooks yet. Update an issue in this flow’s Linear project to see it here.';const runRows=runs.map(run=>''+esc(run.issue_title||run.issue_id)+''+issueLink(run.issue_id,run.issue_url)+''+esc(run.agent_kind||flow.agent_kind||'Herdr agent')+''+esc(run.agent_name)+''+esc(run.workspace_name||flow.workspace_name||'—')+''+badge(run.state,['queued','starting','running','recovering','done'].includes(run.state))+''+time(run.updated_at)+'').join('')||'No agent runs yet.';root.innerHTML='

'+esc(flow.name)+'

'+esc(flow.filter_type)+' trigger · '+esc(flow.max_concurrency)+' concurrent agents · '+esc(flow.agent_kind||'Herdr agent')+' · workspace '+esc(flow.workspace_name||'—')+'

Edit Flow

Webhook activity

Relevant Linear webhooks and whether they queued an agent.

'+eventRows+'
ReceivedIssueEventResultDetails

Agent runs

'+runRows+'
IssueHerdr agentWorkspaceStateUpdated
';root.querySelectorAll('[data-run-href]').forEach(row=>{row.onclick=e=>{if(!e.target.closest('a'))location.href=row.dataset.runHref};row.onkeydown=e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();location.href=row.dataset.runHref}}})} -const renderActivity=load; -load=async()=>{await renderActivity();const response=await fetch('/api/pipes/'+encodeURIComponent(flowId));if(!response.ok)return;const data=await response.json(),runs=(data.runs||[]).filter(run=>run.state!=='ignored');if(!runs.length)return;const diagnostics=runs.map(run=>'
'+esc(run.agent_name)+''+(run.exec_status!=null?'HTTP '+esc(String(run.exec_status))+(run.exec_exit_code!=null?' · VM exit '+esc(String(run.exec_exit_code)):'' ):esc(run.state))+'
'+(run.exec_status!=null?'

Harness launch request

'+esc(run.exec_request)+'

Harness launch response

'+esc(run.exec_response)+'
':'

No exe.dev request or response was recorded for this run. It did not reach the VM-command step.

')+(run.result?'

Herdr agent output

'+esc(run.result)+'
':'')+'
').join('');root.insertAdjacentHTML('beforeend','

Actual exe.dev command results

Only real agent runs appear here. The bearer token is never shown.

'+diagnostics+'
')}; -// Keep run details with the run they belong to. The native disclosure control -// makes the command and response available without expanding every run. -load=async()=>{await renderActivity();const response=await fetch('/api/pipes/'+encodeURIComponent(flowId));if(!response.ok)return;const data=await response.json(),runs=(data.runs||[]).filter(run=>run.state!=='ignored'),runSection=Array.from(root.querySelectorAll('section')).find(section=>section.querySelector('h2')?.textContent==='Agent runs'),webhookSection=Array.from(root.querySelectorAll('section')).find(section=>section.querySelector('h2')?.textContent==='Webhook activity');if(!runSection)return;const panels=runs.map(run=>{const recovery=run.state==='recovering'?'

Recovery attempt '+esc(run.recovery_attempt||0)+' · '+esc(run.recovery_reason||'Herdr state changed')+' · '+esc(run.recovery_last_action||'reconciling')+'

':'';const command=run.exec_status!=null?'

Harness launch request

'+esc(run.exec_request)+'

Harness launch response

'+esc(run.exec_response)+'
':'

No exe.dev request or response was recorded for this run. It did not reach the VM-command step.

';const prompt=run.prompt?'

Rendered prompt

'+esc(run.prompt)+'
':'';const output=run.result?'

Full agent output

'+esc(run.result)+'
':'';return '
'+issueLink(run.issue_id,run.issue_url)+''+esc(run.agent_kind||data.flow.agent_kind||'Herdr agent')+' · '+esc(run.agent_name)+''+badge(run.state,['queued','starting','running','recovering','done'].includes(run.state))+''+time(run.updated_at)+'
'+recovery+prompt+command+output+'
'}).join('')||'

No agent runs yet.

';runSection.innerHTML='

Agent runs

Open a completed run to inspect its full, scrollable output.

'+panels;if(webhookSection)webhookSection.before(runSection)}; -load(); -`); - -export const flowDetailPage = (viewer: { email: string }, flowId: string) => shell("Flow activity — Factorize", viewer, ` -
← My Flows

Loading agent runs…

`, ` -const root=document.querySelector('#flow-detail'),flowId=root.dataset.flowId,esc=v=>{const d=document.createElement('div');d.textContent=v??'';return d.innerHTML},time=v=>new Date(v).toLocaleString(),badge=value=>''+esc(value)+''; -const issueLink=(id,url)=>{if(!id)return '—';const trusted=typeof url==='string'&&(url.startsWith('https://linear.app/')||/^https:\\/\\/github\\.com\\/[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+\\/pull\\/\\d+$/.test(url)),href=trusted?url:'https://linear.app/issue/'+encodeURIComponent(id);return ''+esc(id)+' ↗'}; -const pager=p=>p.page===1&&!p.hasNext?'':''; -async function load(){const page=Math.max(1,parseInt(new URLSearchParams(location.search).get('page')||'1',10)||1),response=await fetch('/api/pipes/'+encodeURIComponent(flowId)+'?view=runs&page='+page);if(response.status===401)return location.href='/auth/linear';if(!response.ok){root.innerHTML='

Could not load this flow.

';return}const data=await response.json(),flow=data.flow,pagination=data.pagination||{page:1,hasNext:false},rows=(data.runs||[]).map(run=>''+esc(run.issue_id)+(run.issue_title?': '+esc(run.issue_title):'')+''+esc(run.agent_kind||flow.agent_kind||'Herdr agent')+' · '+esc(run.agent_name)+''+badge(run.state)+''+time(run.updated_at)+'').join('')||'

No agent runs yet.

';root.innerHTML='

'+esc(flow.name)+'

'+esc(flow.filter_type)+' trigger · '+esc(flow.max_concurrency)+' concurrent agents · '+esc(flow.agent_kind||'Herdr agent')+' · workspace '+esc(flow.workspace_name||'—')+'

Webhook activityEdit Flow

Agent runs

Select a run to inspect its details and full output.

'+rows+pager(pagination)+'
'}load(); -`); - -export const flowWebhooksPage = (viewer: { email: string }, flowId: string) => shell("Webhook activity — Factorize", viewer, ` -

Loading webhook activity…

`, ` -const root=document.querySelector('#webhook-activity'),flowId=root.dataset.flowId,esc=v=>{const d=document.createElement('div');d.textContent=v??'';return d.innerHTML},time=v=>new Date(v).toLocaleString(); -const issueLink=(id,url)=>{if(!id)return '—';const trusted=typeof url==='string'&&(url.startsWith('https://linear.app/')||/^https:\\/\\/github\\.com\\/[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+\\/pull\\/\\d+$/.test(url)),href=trusted?url:'https://linear.app/issue/'+encodeURIComponent(id);return ''+esc(id)+' ↗'}; -async function load(){const page=Math.max(1,parseInt(new URLSearchParams(location.search).get('page')||'1',10)||1),response=await fetch('/api/pipes/'+encodeURIComponent(flowId)+'?view=events&page='+page);if(response.status===401)return location.href='/auth/linear';if(!response.ok){root.innerHTML='

Could not load webhook activity.

';return}const data=await response.json(),p=data.pagination||{page:1,hasNext:false},rows=(data.events||[]).map(event=>''+time(event.received_at)+''+issueLink(event.issue_id,event.issue_url)+''+esc(event.event_type)+' · '+esc(event.event_action)+''+esc(event.outcome)+''+esc(event.detail)+'').join('')||'No relevant webhooks yet.',pager=p.page===1&&!p.hasNext?'':'';root.innerHTML='← '+esc(data.flow.name)+'

Webhook activity

Relevant webhooks and whether they queued an agent.

'+rows+'
ReceivedIssueEventResultDetails
'+pager+'
'}load(); -`); - -export const runDetailPage = (viewer: { email: string }, runId: string) => shell("Agent run — Factorize", viewer, ` -
-

Loading agent run…

-
`, ` -const root=document.querySelector('#run-detail'),runId=root.dataset.runId; -const esc=v=>{const d=document.createElement('div');d.textContent=v??'';return d.innerHTML}; -const time=v=>new Date(v).toLocaleString(); -const section=(title,value)=>value?'

'+title+'

'+esc(value)+'
':''; -async function load(){const response=await fetch('/api/runs/'+encodeURIComponent(runId));if(response.status===401)return location.href='/auth/linear';if(!response.ok){root.innerHTML='← My Flows

This agent run could not be found.

';return}const run=await response.json(),trusted=typeof run.issue_url==='string'&&(run.issue_url.startsWith('https://linear.app/')||/^https:\\/\\/github\\.com\\/[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+\\/pull\\/\\d+$/.test(run.issue_url)),issueHref=trusted?run.issue_url:'https://linear.app/issue/'+encodeURIComponent(run.issue_id);root.innerHTML='← '+esc(run.flow_name||'Flow')+'

'+esc(run.issue_id)+' ↗

'+esc(run.issue_title||run.issue_id)+'

'+esc(run.agent_kind||'Herdr agent')+' · '+esc(run.agent_name)+'

'+esc(run.state)+'
Workspace
'+esc(run.workspace_name||'—')+'
Created
'+time(run.created_at)+'
Updated
'+time(run.updated_at)+'
Exit status
'+(run.exec_status!=null?'HTTP '+esc(String(run.exec_status))+(run.exec_exit_code!=null?' · VM '+esc(String(run.exec_exit_code)):''):'—')+'
'+section('Rendered prompt · delivery '+(run.prompt_delivery_state||'legacy'),run.prompt)+section('Harness launch request',run.exec_request)+section('Harness launch response',run.exec_response)+section('Prompt delivery request',run.prompt_delivery_request)+section('Prompt delivery response',run.prompt_delivery_response)+section('Full agent output',run.result)}load(); -`); - -export const flowsPage = (viewer: { email: string }) => shell("My Flows — Factorize", viewer, ` -
-

My Flows

Your source-to-Herdr automations.

Create Flow
-

Loading flows…

- -
`, ` -const root=document.querySelector('#flows'),error=document.querySelector('#error'); -const esc=v=>{const d=document.createElement('div');d.textContent=v??'';return d.innerHTML}; -async function load(){const r=await fetch('/api/pipes');if(r.status===401)return location.href='/auth/linear';const flows=await r.json();if(!flows.length){root.innerHTML='

No flows yet

Create one to start turning work into agent jobs.

Create your first flow →
';return}root.innerHTML='
    '+flows.map(f=>{const active=Number(f.active_agents)||0,state=active>0?'running':f.latest_run_state==='done'?'complete':f.latest_run_state==='failed'?'error':'idle',dot=state==='running'?'bg-green-500':state==='complete'?'bg-blue-500':state==='error'?'bg-red-500':'bg-slate-300 dark:bg-slate-600';return '
  • '+esc(state)+''+esc(f.name)+'

    '+esc(active)+'/'+esc(f.max_concurrency)+' concurrent agents

  • '}).join('')+'
'} -root.onclick=async e=>{const button=e.target.closest('[data-delete]');if(!button)return;if(!confirm('Delete this flow and stop Factorize from tracking its queued or running jobs? An agent already started on the VM will continue until you stop it there.'))return;button.disabled=true;const r=await fetch('/api/pipes/'+encodeURIComponent(button.dataset.delete),{method:'DELETE'});const result=await r.json().catch(()=>({}));if(!r.ok){error.textContent=result.error||'Could not delete the flow.';error.classList.remove('hidden');button.disabled=false;return}load()};load(); -`); - const dashboardHead = (title: string, description: string, action = "") => `

${title}

${description}

${action}
`; const card = "rounded-2xl border border-stone-200 bg-white shadow-sm dark:border-slate-800 dark:bg-slate-900"; const uiHelpers = ` @@ -212,7 +61,7 @@ async function load(){const jobs=await request('/api/jobs');const root=$('#jobs' export const jobPage = (viewer: { email: string }, jobId?: string) => shell(`${jobId ? "Edit" : "Create"} job — Factorize`, viewer, `
← Jobs
${dashboardHead(jobId ? "Edit job" : "Create a job", "Every prompt input comes from an explicit trigger row with a stable context slug.")}

Step 1

Job details

Name this job and set how many runs it can process at once.

-

Step 2

Triggers

Choose the events that start this job and expose prompt context.

Context slugTypeConfigurationEnabledActions
+

Step 2

Triggers

Choose the events that start this job and expose prompt context.

Context slugTypeConfigurationEnabledActions

Step 3

Prompt and context

Write the instructions for each run using context supplied by your triggers.

Step 4

Execution target

Select the connected environment that will run this job.

@@ -222,7 +71,7 @@ export const jobPage = (viewer: { email: string }, jobId?: string) => shell(`${j
`, `${uiHelpers} const jobId=${JSON.stringify(jobId ?? null)},contextCatalog=${JSON.stringify(triggerContextCatalog)},form=$('#job'),dialog=$('#trigger-dialog'),triggerForm=$('#trigger-form');let triggers=[],editing=-1,resources={projects:[],options:{statuses:[],users:[],labels:[]},installations:[],repositories:new Map(),jobs:[]},clientId=0,reservedSlugs=new Set(); -const kinds={manual:'Manual',schedule:'Schedule',linear:'Linear',github:'GitHub',cloudflareTail:'Cloudflare Tail',custom:'Custom webhook',jobLifecycle:'Job lifecycle'}; +const kinds={manual:'Manual',schedule:'Schedule',linear:'Linear',github:'GitHub',cloudflareTail:'Cloudflare Tail',jobLifecycle:'Job lifecycle'}; const providerKind=t=>t.kind==='webhook'?t.config.provider:t.kind; const reflection=t=>t.reflection?.paths||contextCatalog[providerKind(t)]||[]; const contextPaths=()=>triggers.flatMap(t=>reflection(t).filter(x=>x.path!=='*').map(x=>({path:t.slug+'.'+x.path,type:x.type,description:x.description}))); @@ -230,7 +79,7 @@ const nameOf=(items,id)=>items.find(x=>String(x.id)===String(id))?.name||String( const ruleLabels={status:'Status',label:'Label',assignee:'Assignee',creator:'Creator',owner:'Owner'}; const ruleOptions=type=>type==='status'?resources.options.statuses:type==='label'?resources.options.labels:resources.options.users; const ruleSummary=rule=>ruleLabels[rule.type]+' is '+nameOf(ruleOptions(rule.type),rule.targetId); -function summary(t){const c=t.config||{},k=providerKind(t);if(k==='manual')return 'Prompt entered when run';if(k==='schedule')return c.cron+' · '+c.timezone;if(k==='linear')return nameOf(resources.projects,c.projectId)+' · '+(c.matchRules||[]).map(ruleSummary).join(' + ');if(k==='github'){const i=resources.installations.find(x=>String(x.installationId)===String(c.installationId));const repos=resources.repositories.get(String(c.installationId))||[];return (i?.accountLogin||c.installationId)+' · '+(repos.find(x=>String(x.id)===String(c.repositoryId))?.fullName||c.repositoryId)+' · '+c.event+'/'+c.action}if(k==='cloudflareTail')return 'Managed signed Tail endpoint'+(c.handlerCode?' · handler':'');if(k==='custom')return 'Managed custom endpoint'+(c.handlerCode?' · handler':'');return (c.sourceJobIds||[]).map(id=>resources.jobs.find(j=>j.id===id)?.name||id).join(', ')+' · '+(c.states||[]).join(', ')} +function summary(t){const c=t.config||{},k=providerKind(t);if(k==='manual')return 'Prompt entered when run';if(k==='schedule')return c.cron+' · '+c.timezone;if(k==='linear')return nameOf(resources.projects,c.projectId)+' · '+(c.matchRules||[]).map(ruleSummary).join(' + ');if(k==='github'){const i=resources.installations.find(x=>String(x.installationId)===String(c.installationId));const repos=resources.repositories.get(String(c.installationId))||[];return (i?.accountLogin||c.installationId)+' · '+(repos.find(x=>String(x.id)===String(c.repositoryId))?.fullName||c.repositoryId)+' · '+c.event+'/'+c.action}if(k==='cloudflareTail')return 'Managed signed Tail endpoint'+(c.handlerCode?' · handler':'');return (c.sourceJobIds||[]).map(id=>resources.jobs.find(j=>j.id===id)?.name||id).join(', ')+' · '+(c.states||[]).join(', ')} function render(){const rows=$('#trigger-rows');rows.innerHTML=triggers.map((t,i)=>''+esc(t.slug)+''+esc(kinds[providerKind(t)])+''+esc(summary(t))+'
').join('');$('#trigger-empty').classList.toggle('hidden',triggers.length>0);const paths=contextPaths();$('#context-paths').innerHTML=paths.length?'Available context: '+paths.slice(0,6).map(x=>'{{'+esc(x.path)+'}}').join(' · ')+(paths.length>6?' · '+(paths.length-6)+' more':''):'Add a trigger to expose structured context.';updateSuggestions()} const promptEditor=form.elements.promptTemplate,suggestionMenu=$('#context-suggestions');let matches=[],activeSuggestion=0,expression=null; function currentExpression(){const end=promptEditor.selectionStart,start=promptEditor.value.lastIndexOf('{{',end);if(start<0||promptEditor.value.slice(start+2,end).includes('}}'))return null;const raw=promptEditor.value.slice(start+2,end);if(!/^\\s*[A-Za-z0-9_.-]*$/.test(raw))return null;return {start,end,query:raw.trim()}} @@ -246,9 +95,9 @@ function linearRuleRows(){return [...$('#linear-rules').querySelectorAll('[data- function syncLinearRuleButtons(){const rows=linearRuleRows();rows.forEach(row=>row.querySelector('[data-remove-linear-rule]').classList.toggle('invisible',rows.length===1))} function addLinearRule(rule={type:'status',targetId:''}){const row=document.createElement('div');row.dataset.linearRule='';row.className='grid gap-3 rounded-xl border border-stone-200 bg-stone-50 p-4 sm:grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)_auto] sm:items-end dark:border-slate-700 dark:bg-slate-950';const typeLabel=document.createElement('label');typeLabel.className='label';typeLabel.textContent='Match on';const type=document.createElement('select');type.className='field';type.innerHTML=Object.entries(ruleLabels).map(([value,label])=>'').join('');type.value=rule.type;typeLabel.append(type);const valueLabel=document.createElement('label');valueLabel.className='label';valueLabel.textContent='Value';const value=document.createElement('select');value.className='field';const fill=()=>{value.replaceChildren(new Option('Choose '+ruleLabels[type.value].toLowerCase(),''),...ruleOptions(type.value).map(item=>new Option(item.name,item.id)));value.value=type.value===rule.type?rule.targetId:''};type.onchange=fill;fill();valueLabel.append(value);const remove=document.createElement('button');remove.type='button';remove.dataset.removeLinearRule='';remove.className='rounded-lg border border-red-200 px-3 py-2 text-sm font-semibold text-red-700 hover:bg-red-50 dark:border-red-900 dark:text-red-300';remove.textContent='Remove';remove.onclick=()=>{row.remove();syncLinearRuleButtons()};row.append(typeLabel,valueLabel,remove);$('#linear-rules').append(row);syncLinearRuleButtons()} function readLinearRules(){return linearRuleRows().map(row=>{const [type,target]=row.querySelectorAll('select');return {type:type.value,targetId:target.value}})} -async function openEditor(kind,index=-1){editing=index;const current=index>=0?triggers[index]:null,k=current?providerKind(current):kind,c=current?.config||{};$('#dialog-title').textContent=(current?'Edit ':'Add ')+kinds[k]+' trigger';triggerForm.reset();document.querySelectorAll('[data-panel]').forEach(x=>x.classList.add('hidden'));const panel=document.querySelector('[data-panel="'+(k==='manual'?'none':k==='schedule'?'schedule':k==='linear'?'linear':k==='github'?'github':k==='jobLifecycle'?'jobLifecycle':'webhook')+'"]');panel?.classList.remove('hidden');triggerForm.dataset.kind=k;$('#dialog-error').classList.add('hidden');$('#handler-result').textContent='';if(k==='schedule'){triggerForm.elements.cron.value=c.cron||'0 9 * * *';triggerForm.elements.timezone.value=c.timezone||'UTC'}if(k==='linear'){options(triggerForm.elements.projectId,resources.projects,'name');triggerForm.elements.projectId.value=c.projectId||resources.projects[0]?.id||'';$('#linear-rules').replaceChildren();(c.matchRules?.length?c.matchRules:[{type:'status',targetId:''}]).forEach(addLinearRule)}if(k==='github'){options(triggerForm.elements.installationId,resources.installations,'accountLogin','installationId');triggerForm.elements.installationId.value=String(c.installationId||resources.installations[0]?.installationId||'');await syncRepositories(c.repositoryId);triggerForm.elements.event.value=c.event||'pull_request';triggerForm.elements.action.value=c.action||'dequeued'}if(k==='jobLifecycle'){options(triggerForm.elements.sourceJobId,resources.jobs.filter(j=>j.id!==jobId),'name');[...triggerForm.elements.sourceJobId.options].forEach(x=>x.selected=(c.sourceJobIds||[]).includes(x.value));triggerForm.querySelectorAll('[name=lifecycleState]').forEach(x=>x.checked=(c.states||['succeeded','failed']).includes(x.value))}if(['linear','github','cloudflareTail','custom'].includes(k))triggerForm.elements.handlerCode.value=c.handlerCode||'';dialog.showModal();if(k==='schedule')previewSchedule()} +async function openEditor(kind,index=-1){const current=index>=0?triggers[index]:null,k=current?providerKind(current):kind;if(!kinds[k])throw new Error('This trigger type is no longer supported.');editing=index;const c=current?.config||{};$('#dialog-title').textContent=(current?'Edit ':'Add ')+kinds[k]+' trigger';triggerForm.reset();document.querySelectorAll('[data-panel]').forEach(x=>x.classList.add('hidden'));const panel=document.querySelector('[data-panel="'+(k==='manual'?'none':k==='schedule'?'schedule':k==='linear'?'linear':k==='github'?'github':k==='jobLifecycle'?'jobLifecycle':'webhook')+'"]');panel?.classList.remove('hidden');triggerForm.dataset.kind=k;$('#dialog-error').classList.add('hidden');$('#handler-result').textContent='';if(k==='schedule'){triggerForm.elements.cron.value=c.cron||'0 9 * * *';triggerForm.elements.timezone.value=c.timezone||'UTC'}if(k==='linear'){options(triggerForm.elements.projectId,resources.projects,'name');triggerForm.elements.projectId.value=c.projectId||resources.projects[0]?.id||'';$('#linear-rules').replaceChildren();(c.matchRules?.length?c.matchRules:[{type:'status',targetId:''}]).forEach(addLinearRule)}if(k==='github'){options(triggerForm.elements.installationId,resources.installations,'accountLogin','installationId');triggerForm.elements.installationId.value=String(c.installationId||resources.installations[0]?.installationId||'');await syncRepositories(c.repositoryId);triggerForm.elements.event.value=c.event||'pull_request';triggerForm.elements.action.value=c.action||'dequeued'}if(k==='jobLifecycle'){options(triggerForm.elements.sourceJobId,resources.jobs.filter(j=>j.id!==jobId),'name');[...triggerForm.elements.sourceJobId.options].forEach(x=>x.selected=(c.sourceJobIds||[]).includes(x.value));triggerForm.querySelectorAll('[name=lifecycleState]').forEach(x=>x.checked=(c.states||['succeeded','failed']).includes(x.value))}if(['linear','github','cloudflareTail'].includes(k))triggerForm.elements.handlerCode.value=c.handlerCode||'';dialog.showModal();if(k==='schedule')previewSchedule()} async function previewSchedule(){const body={cron:triggerForm.elements.cron.value,timezone:triggerForm.elements.timezone.value};try{const x=await request('/api/schedules/preview',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});$('#schedule-preview').textContent='Next occurrence: '+new Date(x.nextRunAt).toLocaleString()}catch(e){$('#schedule-preview').textContent=e.message}} -function configFromForm(){const k=triggerForm.dataset.kind,h=triggerForm.elements.handlerCode?.value.trim(),handler=h?{handlerCode:h}:{};if(k==='manual')return {kind:'manual',config:{}};if(k==='schedule')return {kind:'schedule',config:{cron:triggerForm.elements.cron.value.trim(),timezone:triggerForm.elements.timezone.value}};if(k==='linear')return {kind:'webhook',config:{provider:'linear',projectId:triggerForm.elements.projectId.value,matchRules:readLinearRules(),...handler}};if(k==='github')return {kind:'webhook',config:{provider:'github',installationId:Number(triggerForm.elements.installationId.value),repositoryId:Number(triggerForm.elements.repositoryId.value),event:triggerForm.elements.event.value.trim(),action:triggerForm.elements.action.value.trim(),...handler}};if(k==='cloudflareTail'||k==='custom')return {kind:'webhook',config:{provider:k,...handler}};return {kind:'jobLifecycle',config:{sourceJobIds:[...triggerForm.elements.sourceJobId.selectedOptions].map(x=>x.value),states:[...triggerForm.querySelectorAll('[name=lifecycleState]:checked')].map(x=>x.value)}}} +function configFromForm(){const k=triggerForm.dataset.kind,h=triggerForm.elements.handlerCode?.value.trim(),handler=h?{handlerCode:h}:{};if(k==='manual')return {kind:'manual',config:{}};if(k==='schedule')return {kind:'schedule',config:{cron:triggerForm.elements.cron.value.trim(),timezone:triggerForm.elements.timezone.value}};if(k==='linear')return {kind:'webhook',config:{provider:'linear',projectId:triggerForm.elements.projectId.value,matchRules:readLinearRules(),...handler}};if(k==='github')return {kind:'webhook',config:{provider:'github',installationId:Number(triggerForm.elements.installationId.value),repositoryId:Number(triggerForm.elements.repositoryId.value),event:triggerForm.elements.event.value.trim(),action:triggerForm.elements.action.value.trim(),...handler}};if(k==='cloudflareTail')return {kind:'webhook',config:{provider:k,...handler}};return {kind:'jobLifecycle',config:{sourceJobIds:[...triggerForm.elements.sourceJobId.selectedOptions].map(x=>x.value),states:[...triggerForm.querySelectorAll('[name=lifecycleState]:checked')].map(x=>x.value)}}} function validate(candidate){const k=providerKind(candidate);if(k==='manual'&&triggers.some((t,i)=>i!==editing&&providerKind(t)==='manual'))throw new Error('Only one Manual trigger can be configured.');if(k==='linear'&&(!candidate.config.projectId||!candidate.config.matchRules.length||candidate.config.matchRules.some(rule=>!rule.targetId)))throw new Error('Choose a Linear project and a value for every matching rule.');if(k==='github'&&(!candidate.config.installationId||!candidate.config.repositoryId))throw new Error('Choose a GitHub installation and repository.');if(k==='jobLifecycle'&&(!candidate.config.sourceJobIds[0]||!candidate.config.states.length))throw new Error('Choose a source job and at least one final state.');if(triggers.some((t,i)=>i!==editing&&JSON.stringify(t.config)===JSON.stringify(candidate.config)&&t.kind===candidate.kind))throw new Error('An identical trigger is already configured.')} $('#trigger-rows').onclick=e=>{const b=e.target.closest('button');if(!b)return;const key=['edit','remove'].find(x=>b.dataset[x]!==undefined),i=Number(b.dataset[key]);if(key==='edit')openEditor(providerKind(triggers[i]),i);if(key==='remove'){if(providerKind(triggers[i])==='manual'){const error=$('#error');error.textContent='A Job must keep its Manual trigger. Disable it if manual runs should be unavailable.';error.classList.remove('hidden');return}triggers.splice(i,1);render()}}; $('#trigger-rows').onchange=e=>{if(e.target.dataset.enable===undefined)return;triggers[Number(e.target.dataset.enable)].enabled=e.target.checked;render()};$('#add-trigger').onchange=e=>{const kind=e.target.value;e.target.value='';if(kind)openEditor(kind)};$('#add-linear-rule').onclick=()=>addLinearRule();$('#cancel-trigger').onclick=()=>dialog.close();triggerForm.elements.installationId.onchange=()=>syncRepositories();triggerForm.elements.cron.oninput=previewSchedule;triggerForm.elements.timezone.onchange=previewSchedule; diff --git a/packages/app/src/webhook-trigger.ts b/packages/app/src/webhook-trigger.ts index f33361ae..413aa853 100644 --- a/packages/app/src/webhook-trigger.ts +++ b/packages/app/src/webhook-trigger.ts @@ -2,7 +2,7 @@ import { matchingIssue } from "./matcher"; import type { MatchRule } from "./types"; import { validateHandlerCode } from "./custom-handler"; -export type WebhookProvider = "linear" | "github" | "cloudflareTail" | "custom"; +export type WebhookProvider = "linear" | "github" | "cloudflareTail"; export type WebhookTriggerConfig = { provider: WebhookProvider; projectId?: string; matchRules?: MatchRule[]; installationId?: number; repositoryId?: number; diff --git a/packages/app/src/worker.ts b/packages/app/src/worker.ts index 25a38ffd..0624ce9b 100644 --- a/packages/app/src/worker.ts +++ b/packages/app/src/worker.ts @@ -69,7 +69,7 @@ function providerOptions(env: Env): OAuthProviderOptions { return { scopesSupported: scopes, allowImplicitFlow: false, allowPlainPKCE: false, accessTokenTTL: 3600, refreshTokenTTL: 2_592_000, clientIdMetadataDocumentEnabled: true, - resourceMetadata: { resource: `${env.APP_ORIGIN}/mcp`, authorization_servers: [env.APP_ORIGIN], scopes_supported: scopes, bearer_methods_supported: ["header"], resource_name: "Factorize flows" }, + resourceMetadata: { resource: `${env.APP_ORIGIN}/mcp`, authorization_servers: [env.APP_ORIGIN], scopes_supported: scopes, bearer_methods_supported: ["header"], resource_name: "Factorize jobs" }, }; } function provider(env: Env) { return new OAuthProvider(providerOptions(env)); } diff --git a/packages/app/test/custom-handler.test.ts b/packages/app/test/custom-handler.test.ts index 1a5be609..35a1d527 100644 --- a/packages/app/test/custom-handler.test.ts +++ b/packages/app/test/custom-handler.test.ts @@ -1,6 +1,5 @@ import { describe, expect, it } from "vitest"; -import { CUSTOM_HANDLER_MAX_CODE_BYTES, customScriptName, invokeCustomHandler, userWorkerModule, validateCustomHandler } from "../src/custom-handler"; -import type { CustomSource } from "../src/types"; +import { invokeCustomHandler, userWorkerModule, validateHandlerCode } from "../src/custom-handler"; describe("custom handlers", () => { const runAdapter = async (body: string) => { @@ -11,27 +10,12 @@ describe("custom handlers", () => { }; it("accepts only the complete synchronous function contract", () => { - expect(validateCustomHandler("linear", "Issues", "function handler(webhook) { return webhook.type === 'Issue'; }").origin).toBe("linear"); + expect(validateHandlerCode("function handler(webhook) { return webhook.type === 'Issue'; }")).toContain("function handler"); for (const code of ["return true", "const handler = () => true", "async function handler(webhook) { return true; }", "function other(webhook) { return true; }"]) { - expect(() => validateCustomHandler("linear", "x", code)).toThrow("complete function handler(webhook)"); + expect(() => validateHandlerCode(code)).toThrow("complete function handler(webhook)"); } }); - it("enforces origin, name, and source size limits", () => { - expect(validateCustomHandler("cloudflare", "Tail failures", "function handler(webhook) { return webhook.outcome === 'exception'; }").origin).toBe("cloudflare"); - expect(() => validateCustomHandler("slack", "x", "function handler(webhook) { return true; }")).toThrow("Linear, GitHub, or Cloudflare"); - expect(() => validateCustomHandler("github", "", "function handler(webhook) { return true; }")).toThrow("Handler name"); - expect(() => validateCustomHandler("github", "x", `function handler(webhook) { /*${"x".repeat(CUSTOM_HANDLER_MAX_CODE_BYTES)}*/ return true; }`)).toThrow("at most"); - }); - - it("uses opaque stable names isolated by tenant and flow", async () => { - const first = await customScriptName("tenant-a", "flow-a"); - expect(first).toMatch(/^fh-[a-f0-9]{40}$/); - expect(first).toBe(await customScriptName("tenant-a", "flow-a")); - expect(first).not.toBe(await customScriptName("tenant-b", "flow-a")); - expect(first).not.toContain("tenant"); - }); - it("pins an adapter that rejects thenables and invalid return types without exposing errors", () => { const module = userWorkerModule("function handler(webhook) { return true; }"); expect(module).toContain('typeof result.then === "function"'); @@ -52,13 +36,7 @@ describe("custom handlers", () => { }; }, } as unknown as WorkerLoader; - const source: CustomSource = { - kind: "custom", - origin: "github", - handlerName: "isolated", - handlerCode: "function handler(webhook) { return true; }", - handlerDeployment: { scriptName: "fh-0000000000000000000000000000000000000000", codeDigest: "0".repeat(64), state: "ready" }, - }; + const source = { handlerCode: "function handler(webhook) { return true; }" }; await expect(invokeCustomHandler(loader, source, {})).resolves.toEqual({ ok: true, decision: true }); expect(loaded?.env).toEqual({}); diff --git a/packages/app/test/device-oauth.e2e.test.ts b/packages/app/test/device-oauth.e2e.test.ts index 4f118b51..12cb403c 100644 --- a/packages/app/test/device-oauth.e2e.test.ts +++ b/packages/app/test/device-oauth.e2e.test.ts @@ -128,7 +128,7 @@ describe("manually issued access tokens", () => { expect(listedText).not.toContain(created.token); expect(listedText).not.toContain("digest"); - const scoped = await SELF.fetch(`${origin}/api/v1/flows`, { headers: { authorization: `Bearer ${created.token}` } }); + const scoped = await SELF.fetch(`${origin}/api/v1/jobs`, { headers: { authorization: `Bearer ${created.token}` } }); expect(scoped.status).toBe(403); const tracked = await (await SELF.fetch(`${origin}/api/access-tokens`, { headers: { cookie } })).json>(); expect(tracked.find(token => token.id === created.id)?.last_used_at).toBeTruthy(); diff --git a/packages/app/test/flow-service.test.ts b/packages/app/test/flow-service.test.ts index d3cccdd6..3bbf7301 100644 --- a/packages/app/test/flow-service.test.ts +++ b/packages/app/test/flow-service.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { FlowService, ServiceError } from "../src/flow-service"; -import { flowInputSchema, jobInputSchema, listRunsSchema, manualInvocationSchema } from "../src/flow-schemas"; +import { ApiService, ServiceError } from "../src/flow-service"; +import { jobInputSchema, listRunsSchema, manualInvocationSchema } from "../src/flow-schemas"; import type { Env, OAuthProps } from "../src/types"; function environment(handler: (request: Request) => Response | Promise): Env { @@ -10,37 +10,15 @@ function environment(handler: (request: Request) => Response | Promise const auth: OAuthProps = { tenantId: "tenant-a", userId: "owner-a", sessionVersion: 4, scopes: ["flows:read", "runs:read"] }; -describe("FlowService", () => { - it("checks current owner membership on every call", async () => { - let membershipChecks = 0; - const service = new FlowService(environment(request => { - const path = new URL(request.url).pathname; - if (path === "/members/owner-a") { membershipChecks++; return Response.json({ role: "owner", session_version: 4 }); } - if (path === "/pipes") return Response.json([{ id: "flow-1", name: "Triage" }]); - return new Response("Not found", { status: 404 }); - }), auth); - await service.listFlows(); await service.listFlows(); - expect(membershipChecks).toBe(2); - }); - - it("rejects missing mutation scopes before touching flow storage", async () => { - let mutated = false; - const service = new FlowService(environment(request => { - if (new URL(request.url).pathname === "/pipes" && request.method === "POST") mutated = true; - return Response.json({ role: "owner", session_version: 4 }); - }), auth); - await expect(service.createFlow({ name: "Triage", source: { kind: "linear", projectId: "p", matchRules: [{ type: "label", targetId: "l" }] }, exeConnectionId: "exe-1", maxConcurrency: 3 })).rejects.toMatchObject({ status: 403, code: "insufficient_scope" } satisfies Partial); - expect(mutated).toBe(false); - }); - +describe("ApiService", () => { it("invalidates tokens when the owner session version changes", async () => { - const service = new FlowService(environment(() => Response.json({ role: "owner", session_version: 5 })), auth); - await expect(service.listFlows()).rejects.toMatchObject({ status: 401, code: "invalid_token" }); + const service = new ApiService(environment(() => Response.json({ role: "owner", session_version: 5 })), auth); + await expect(service.listJobs()).rejects.toMatchObject({ status: 401, code: "invalid_token" }); }); it("uses flow scopes for job management and run scopes for invocation", async () => { const requests: string[] = []; - const service = new FlowService(environment(request => { + const service = new ApiService(environment(request => { const path = new URL(request.url).pathname; if (path === "/members/owner-a") return Response.json({ role: "owner", session_version: 4 }); requests.push(`${request.method} ${path}`); @@ -53,12 +31,6 @@ describe("FlowService", () => { }); describe("shared API schemas", () => { - it("rejects credential and unknown fields", () => { - expect(() => flowInputSchema.parse({ name: "Triage", source: { kind: "linear", projectId: "p", matchRules: [{ type: "label", targetId: "l" }] }, exeConnectionId: "exe-1", maxConcurrency: 3, apiToken: "secret" })).toThrow(); - expect(flowInputSchema.parse({ name: "Tail", source: { kind: "cloudflareTail" }, exeConnectionId: "exe-1" }).source.kind).toBe("cloudflareTail"); - expect(() => flowInputSchema.parse({ name: "Tail", source: { kind: "cloudflareTail", signingSecret: "nope" }, exeConnectionId: "exe-1" })).toThrow(); - }); - it("bounds pagination and run states", () => { expect(listRunsSchema.parse({ limit: "100", state: "running", contextQuery: "literal.*text" })).toMatchObject({ limit: 100, state: "running", contextQuery: "literal.*text" }); expect(() => listRunsSchema.parse({ limit: "101" })).toThrow(); diff --git a/packages/app/test/source-lifecycle.test.ts b/packages/app/test/source-lifecycle.test.ts deleted file mode 100644 index 0624b659..00000000 --- a/packages/app/test/source-lifecycle.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { preparePublicSource, publicSource, resolveContextTemplate, renderSourcePrompt, TAIL_CONTEXT_TEMPLATE } from "../src/source-lifecycle"; - -describe("source lifecycle", () => { - it("prepares the default Tail handler and preserves its secret on update", async () => { - const created = await preparePublicSource("tenant", "flow", { kind: "cloudflareTail" }); - expect(created).toMatchObject({ kind: "custom", origin: "cloudflare", handlerDeployment: { state: "ready" } }); - const updated = await preparePublicSource("tenant", "flow", { kind: "cloudflareTail", handlerCode: (created as any).handlerCode }, created); - expect((updated as any).tail.signingSecret).toBe((created as any).tail.signingSecret); - expect(publicSource(updated)).not.toHaveProperty("tail"); - expect(publicSource(updated)).not.toHaveProperty("handlerDeployment"); - }); - - it("renders Tail data through its stored Mustache template", async () => { - const source = await preparePublicSource("tenant", "flow", { kind: "cloudflareTail" }); - expect(resolveContextTemplate({ kind: "cloudflareTail" })).toBe(TAIL_CONTEXT_TEMPLATE); - expect(renderSourcePrompt(source, "{{flow.name}}/{{deliveryId}}/{{eventJson}}", { outcome: "exception" }, "Tail", "d1")).toContain("Tail/d1/"); - expect(() => resolveContextTemplate({ kind: "cloudflareTail" }, "{{#broken}}")).toThrow("invalid Mustache"); - }); -}); diff --git a/packages/app/test/trigger-context.test.ts b/packages/app/test/trigger-context.test.ts index 27e54184..e75a86d7 100644 --- a/packages/app/test/trigger-context.test.ts +++ b/packages/app/test/trigger-context.test.ts @@ -3,7 +3,8 @@ import { reflectTriggerContext, triggerContextCatalog } from "../src/trigger-con describe("trigger context reflection", () => { it("defines typed nested paths for every built-in kind and provider", () => { - expect(Object.keys(triggerContextCatalog)).toEqual(expect.arrayContaining(["manual", "schedule", "linear", "github", "cloudflareTail", "custom", "jobLifecycle"])); + expect(Object.keys(triggerContextCatalog)).toEqual(expect.arrayContaining(["manual", "schedule", "linear", "github", "cloudflareTail", "jobLifecycle"])); + expect(triggerContextCatalog).not.toHaveProperty("custom"); for (const paths of Object.values(triggerContextCatalog)) { expect(paths.length).toBeGreaterThan(0); expect(paths.every(path => path.path && path.type && path.description)).toBe(true); diff --git a/packages/app/test/ui.test.ts b/packages/app/test/ui.test.ts index 372bf6d5..44799dce 100644 --- a/packages/app/test/ui.test.ts +++ b/packages/app/test/ui.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { apiKeysSettingsPage, flowDetailPage, flowPage, flowWebhooksPage, flowsPage, jobDetailPage, jobPage, jobsPage, jobRunPage, landingPage, runDetailPage, settingsPage } from "../src/ui"; +import { apiKeysSettingsPage, jobDetailPage, jobPage, jobsPage, jobRunPage, landingPage, settingsPage } from "../src/ui"; describe("pages", () => { const expectInlineScriptsToParse = (html: string) => { @@ -26,86 +26,6 @@ describe("pages", () => { expect(html).toContain("dark:bg-slate-950"); }); - it("renders all three flow configuration sections", () => { - const html = flowPage({ email: "owner@example.com" }); - expect(html).toContain(">Source"); - expect(html).toContain("PR leaves merge queue with conflicts"); - expect(html).toContain("Flow config"); - expect(html).toContain("Flow ID"); - expect(html).toContain("slugFor"); - expect(html).toContain("Exe.dev config"); - expect(html).toContain("Agent config"); - expect(html).toContain("Context template"); - expect(html).toContain('id="reset-context-template"'); - expect(html).toContain("Reset this context template"); - expect(html).not.toContain('name="workspaceName"'); - expect(html).toContain('class="field"'); - expect(html).toContain("Issue matching rules"); - expect(html).toContain("Add rule"); - expect(html).toContain("Agent launch arguments"); - expect(html).toContain('class="min-w-0 w-full"'); - expect(html).toContain('id="test-exe"'); - expect(html).toContain('id="exe-connection"'); - expect(html).toContain("Connections save an SSH destination and its restricted HTTPS token"); - expect(html).toContain("This is chosen per flow"); - expect(html).toContain("/home/exedev/projects/{{{flowId}}}"); - expect(html).toContain("as a Mustache variable"); - expect(html).toContain("Test Connection"); - expect(html).toContain('id="exe-test-status"'); - expect(html).toContain("Connection successful"); - expect(html).toContain("Connection failed"); - expect(html).toContain("r.ok&&body.ok"); - expect(html).toContain("Cloudflare Tail credentials"); - expect(html).toContain("Generate new secret"); - expect(html).toContain("FACTORIZE_TAIL_SECRET"); - expect(html).toContain("navigator.clipboard.writeText"); - expect(html).toContain("crypto.getRandomValues(new Uint8Array(32))"); - expect(html).toContain("tailSigningSecret"); - }); - - it("renders paginated agent runs with links to run and webhook pages", () => { - const html = flowDetailPage({ email: "owner@example.com" }, "flow-1"); - expect(html).toContain("Agent runs"); - expect(html).toContain("?view=runs&page="); - expect(html).toContain("/webhooks"); - expect(html).toContain("/runs/"); - expect(html).toContain("Edit Flow"); - expect(html).toContain("issueLink"); - expect(html).toContain("issue_title"); - expect(html).toContain("esc(run.issue_id)+(run.issue_title?': '+esc(run.issue_title):'')"); - expect(html).toContain("Select a run to inspect its details and full output."); - expect(html).not.toContain('
{ - const html = flowWebhooksPage({ email: "owner@example.com" }, "flow-1"); - expect(html).toContain("Webhook activity"); - expect(html).toContain("?view=events&page="); - expect(html).toContain("whether they queued an agent"); - expectInlineScriptsToParse(html); - }); - - it("renders an agent run page", () => { - const html = runDetailPage({ email: "owner@example.com" }, "run-1"); - expect(html).toContain("/api/runs/"); - expect(html).toContain("Rendered prompt"); - expect(html).toContain("Harness launch request"); - expect(html).toContain("Prompt delivery request"); - expect(html).toContain("Full agent output"); - expectInlineScriptsToParse(html); - }); - - it("renders flow status and active agent capacity without trigger details", () => { - const html = flowsPage({ email: "owner@example.com" }); - expect(html).toContain("active_agents"); - expect(html).toContain("bg-green-500"); - expect(html).toContain("bg-blue-500"); - expect(html).toContain("bg-red-500"); - expect(html).toContain("concurrent agents"); - expect(html).not.toContain("filter_type+' trigger'"); - expectInlineScriptsToParse(html); - }); it("escapes profile data", () => { const html = landingPage({ email: '@example.com' }); @@ -215,7 +135,7 @@ describe("pages", () => { expect(editor).toContain("Add trigger"); expect(editor).toContain('id="trigger-rows"'); expect(editor).toContain("Context slug"); - expect(editor).toContain("Custom webhook"); + expect(editor).not.toContain("Custom webhook"); expect(editor).toContain("Job lifecycle"); expect(editor).toContain("Test handler"); expect(editor).not.toContain("data-up"); diff --git a/packages/app/test/webhook-trigger.test.ts b/packages/app/test/webhook-trigger.test.ts index 112072bf..8befeb78 100644 --- a/packages/app/test/webhook-trigger.test.ts +++ b/packages/app/test/webhook-trigger.test.ts @@ -19,9 +19,9 @@ describe("webhook Job trigger adapters", () => { }); it("validates optional handlers for every provider", () => { - for (const provider of ["linear", "github", "cloudflareTail", "custom"] as const) { + for (const provider of ["linear", "github", "cloudflareTail"] as const) { expect(() => validateWebhookHandler({ provider, handlerCode: "function handler(webhook) { return { id: webhook.id }; }" })).not.toThrow(); } - expect(() => validateWebhookHandler({ provider: "custom", handlerCode: "return true" })).toThrow("complete function handler(webhook)"); + expect(() => validateWebhookHandler({ provider: "linear", handlerCode: "return true" })).toThrow("complete function handler(webhook)"); }); }); diff --git a/packages/app/test/worker.test.ts b/packages/app/test/worker.test.ts index 9957b8d3..4a3e9a06 100644 --- a/packages/app/test/worker.test.ts +++ b/packages/app/test/worker.test.ts @@ -102,35 +102,12 @@ describe("Worker routes", () => { expect(JSON.stringify(body)).not.toContain("refreshToken"); }); - it("returns flow activity through the authenticated Durable Object boundary", async () => { - const activity = { flow: { id: "flow-1", name: "Bugs" }, events: [], runs: [] }; - const response = await app.request("https://factorize.test/api/pipes/flow-1", { - headers: { cookie: await sessionCookie() }, - }, testEnv(ownerHandler({ "/pipes/flow-1": Response.json(activity) }))); - expect(response.status).toBe(200); - await expect(response.json()).resolves.toEqual(activity); - }); - - it("forwards flow activity pagination to the Durable Object", async () => { - let forwarded: URL | undefined; - const response = await app.request("https://factorize.test/api/pipes/flow-1?view=events&page=3", { - headers: { cookie: await sessionCookie() }, - }, testEnv(request => { - if (new URL(request.url).pathname === "/members/user-1") return Response.json({ role: "owner", session_version: 1 }); - forwarded = new URL(request.url); - return Response.json({ flow: {}, events: [], runs: [], pagination: { page: 3, hasNext: false } }); - })); - expect(response.status).toBe(200); - expect(forwarded?.search).toBe("?view=events&page=3"); - }); - - it("returns an agent run through the authenticated Durable Object boundary", async () => { - const run = { id: "run-1", issue_title: "Fix the thing" }; - const response = await app.request("https://factorize.test/api/runs/run-1", { - headers: { cookie: await sessionCookie() }, - }, testEnv(ownerHandler({ "/runs/run-1": Response.json(run) }))); - expect(response.status).toBe(200); - await expect(response.json()).resolves.toEqual(run); + it("fails closed for removed Flow and generic webhook routes", async () => { + const env = testEnv(ownerHandler({})); + for (const path of ["/api/pipes", "/api/pipes/old", "/api/runs/old", "/flows", "/flows/old", "/webhooks/custom/tenant/job"]) { + const response = await app.request(`https://factorize.test${path}`, { headers: { cookie: await sessionCookie() } }, env); + expect(response.status, path).toBe(404); + } }); it("preserves a useful upstream GraphQL error instead of turning it into a 500", async () => { @@ -161,58 +138,8 @@ describe("Worker routes", () => { await expect(forwarded!.text()).resolves.toBe('{"scriptName":"producer"}'); }); - it("forwards flow creation with its JSON body", async () => { - let forwarded: { method: string; body: unknown } | undefined; - const env = testEnv(async (request) => { - const path = new URL(request.url).pathname; - if (path === "/members/user-1") return Response.json({ role: "owner", session_version: 1 }); - if (path === "/pipes") { - forwarded = { method: request.method, body: await request.json() }; - return Response.json({ id: "flow-1" }, { status: 201 }); - } - return new Response("Not found", { status: 404 }); - }); - const flow = { name: "Bugs", projectId: "project-1", matchRules: [{ type: "label", targetId: "label-1" }], maxConcurrency: 3 }; - const response = await app.request("https://factorize.test/api/pipes", { - method: "POST", - headers: { cookie: await sessionCookie(), "content-type": "application/json" }, - body: JSON.stringify(flow), - }, env); - expect(response.status).toBe(201); - expect(forwarded).toEqual({ method: "POST", body: flow }); - }); - - it("forwards flow edits through the authenticated Durable Object boundary", async () => { - let forwarded: { method: string; body: unknown } | undefined; - const env = testEnv(async (request) => { - const path = new URL(request.url).pathname; - if (path === "/members/user-1") return Response.json({ role: "owner", session_version: 1 }); - if (path === "/pipes/flow-1") { forwarded = { method: request.method, body: await request.json() }; return Response.json({ ok: true }); } - return new Response("Not found", { status: 404 }); - }); - const flow = { name: "Bugs", projectId: "project-1", matchRules: [{ type: "label", targetId: "label-1" }], workspaceName: "bugs", maxConcurrency: 3 }; - const response = await app.request("https://factorize.test/api/pipes/flow-1", { method: "PUT", headers: { cookie: await sessionCookie(), "content-type": "application/json" }, body: JSON.stringify(flow) }, env); - expect(response.status).toBe(200); - expect(forwarded).toEqual({ method: "PUT", body: flow }); - }); - - it("serves an authenticated flow edit page", async () => { - const response = await app.request("https://factorize.test/flows/flow-1/edit", { - headers: { cookie: await sessionCookie() }, - }, testEnv(ownerHandler({}))); - expect(response.status).toBe(200); - await expect(response.text()).resolves.toContain("Edit flow"); - }); - - it("forwards flow deletion and clears the session on logout", async () => { - let deleted = false; - const env = testEnv(ownerHandler({ "/pipes/flow-1": () => { deleted = true; return Response.json({ ok: true }); } })); - const response = await app.request("https://factorize.test/api/pipes/flow-1", { - method: "DELETE", headers: { cookie: await sessionCookie() }, - }, env); - expect(response.status).toBe(200); - expect(deleted).toBe(true); - + it("clears the session on logout", async () => { + const env = testEnv(ownerHandler({})); const logout = await app.request("https://factorize.test/auth/logout", { method: "POST", headers: { cookie: await sessionCookie() } }, env); expect(logout.status).toBe(302); expect(logout.headers.get("set-cookie")).toContain("factorize_session="); diff --git a/packages/app/wrangler.jsonc b/packages/app/wrangler.jsonc index 2b307df0..0a35c2d8 100644 --- a/packages/app/wrangler.jsonc +++ b/packages/app/wrangler.jsonc @@ -13,7 +13,6 @@ "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Tenant"] }, { "tag": "v2", "new_sqlite_classes": ["GitHubInstallationRegistry"] }], "vars": { "APP_ORIGIN": "https://app.factorize.sh", - "LINEAR_OAUTH_SCOPES": "read,write", - "CUSTOM_SOURCES_ENABLED": "true" + "LINEAR_OAUTH_SCOPES": "read,write" } }