@wheatley-ai/cli 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +15 -0
- package/bin/wheatley.js +2 -0
- package/dist/approvals/gate.js +278 -0
- package/dist/approvals/module.js +21 -0
- package/dist/approvals/policy.js +30 -0
- package/dist/approvals/preview.js +17 -0
- package/dist/approvals/prompt.js +98 -0
- package/dist/approvals/rpc.js +16 -0
- package/dist/approvals/store.js +159 -0
- package/dist/cli/ask.js +94 -0
- package/dist/cli/chat.js +180 -0
- package/dist/cli/client.js +104 -0
- package/dist/cli/daemon.js +35 -0
- package/dist/cli/init.js +72 -0
- package/dist/cli/io.js +45 -0
- package/dist/cli/main.js +204 -0
- package/dist/cli/session.js +87 -0
- package/dist/cli/status.js +46 -0
- package/dist/contracts/approval-gate.js +1 -0
- package/dist/contracts/config-store.js +1 -0
- package/dist/contracts/delivery-outbox.js +1 -0
- package/dist/contracts/errors.js +28 -0
- package/dist/contracts/extension-catalog.js +1 -0
- package/dist/contracts/maintenance-runner.js +1 -0
- package/dist/contracts/memory-store.js +1 -0
- package/dist/contracts/module.js +7 -0
- package/dist/contracts/tool-names.js +43 -0
- package/dist/contracts/trigger-runtime.js +1 -0
- package/dist/contracts/webhook-ingress.js +2 -0
- package/dist/core/agent/agent-store.js +300 -0
- package/dist/core/agent/agent.js +1020 -0
- package/dist/core/agent/gated-models.js +89 -0
- package/dist/core/agent/pi-adapter.js +401 -0
- package/dist/core/agent/policy-gate.js +44 -0
- package/dist/core/builtin-catalog.js +20 -0
- package/dist/core/concurrency-gate.js +87 -0
- package/dist/core/config/atomic-file.js +61 -0
- package/dist/core/config/config-store.js +138 -0
- package/dist/core/config/pending-restart.js +53 -0
- package/dist/core/config/secret-references.js +69 -0
- package/dist/core/config/secret-store.js +147 -0
- package/dist/core/config/validate.js +55 -0
- package/dist/core/config/yaml-patch.js +57 -0
- package/dist/core/daemon.js +88 -0
- package/dist/core/deployment.js +347 -0
- package/dist/core/error-message.js +4 -0
- package/dist/core/events.js +25 -0
- package/dist/core/logger.js +81 -0
- package/dist/core/models.js +27 -0
- package/dist/core/module.js +42 -0
- package/dist/core/rpc/agent-handlers.js +82 -0
- package/dist/core/rpc/deployment-handlers.js +63 -0
- package/dist/core/rpc/router.js +95 -0
- package/dist/core/server/connection.js +170 -0
- package/dist/core/server/control-server.js +152 -0
- package/dist/core/server/static-files.js +79 -0
- package/dist/core/supervisor.js +206 -0
- package/dist/core/tool-routing.js +41 -0
- package/dist/dashboard/assets/index-3COz_MZq.css +2 -0
- package/dist/dashboard/assets/index-RnxedkKh.js +11 -0
- package/dist/dashboard/assets/sheet-presentation-U1UUymXc.js +1 -0
- package/dist/dashboard/index.html +13 -0
- package/dist/db/database.js +16 -0
- package/dist/db/migrations.js +184 -0
- package/dist/frontends/discord/approvals.js +199 -0
- package/dist/frontends/discord/attachments.js +115 -0
- package/dist/frontends/discord/binding.js +489 -0
- package/dist/frontends/discord/config.js +107 -0
- package/dist/frontends/discord/discord-runtime.js +52 -0
- package/dist/frontends/discord/errors.js +61 -0
- package/dist/frontends/discord/live-runs.js +189 -0
- package/dist/frontends/discord/module.js +39 -0
- package/dist/frontends/discord/recent-ids.js +20 -0
- package/dist/frontends/slack/approval-blocks.js +98 -0
- package/dist/frontends/slack/attachments.js +102 -0
- package/dist/frontends/slack/background-tasks.js +20 -0
- package/dist/frontends/slack/binding.js +405 -0
- package/dist/frontends/slack/bounded.js +9 -0
- package/dist/frontends/slack/chat-id.js +17 -0
- package/dist/frontends/slack/config.js +80 -0
- package/dist/frontends/slack/delivery-errors.js +81 -0
- package/dist/frontends/slack/inbound.js +76 -0
- package/dist/frontends/slack/live-progress.js +190 -0
- package/dist/frontends/slack/manifest.js +66 -0
- package/dist/frontends/slack/outbound.js +160 -0
- package/dist/frontends/slack/schemas.js +99 -0
- package/dist/frontends/slack/signature.js +30 -0
- package/dist/frontends/slack/slack-client.js +60 -0
- package/dist/frontends/slack/slack-frontend.js +38 -0
- package/dist/frontends/slack/state-store.js +112 -0
- package/dist/frontends/telegram/approvals.js +134 -0
- package/dist/frontends/telegram/attachments.js +126 -0
- package/dist/frontends/telegram/binding.js +144 -0
- package/dist/frontends/telegram/chat-key.js +43 -0
- package/dist/frontends/telegram/client.js +88 -0
- package/dist/frontends/telegram/config.js +93 -0
- package/dist/frontends/telegram/delivery.js +215 -0
- package/dist/frontends/telegram/frontend.js +42 -0
- package/dist/frontends/telegram/grammy-client.js +122 -0
- package/dist/frontends/telegram/http-status.js +6 -0
- package/dist/frontends/telegram/inbound.js +149 -0
- package/dist/frontends/telegram/live.js +182 -0
- package/dist/frontends/telegram/markdown.js +103 -0
- package/dist/frontends/telegram/recent-set.js +18 -0
- package/dist/frontends/telegram/serial-queue.js +23 -0
- package/dist/index.js +7 -0
- package/dist/mcp/content.js +61 -0
- package/dist/mcp/mcp-module.js +35 -0
- package/dist/mcp/mcp-tool-provider.js +93 -0
- package/dist/mcp/server-connection.js +297 -0
- package/dist/memory/consolidation.js +260 -0
- package/dist/memory/format.js +5 -0
- package/dist/memory/migrations.js +76 -0
- package/dist/memory/module.js +69 -0
- package/dist/memory/names.js +20 -0
- package/dist/memory/rows.js +22 -0
- package/dist/memory/rpc.js +49 -0
- package/dist/memory/snapshots.js +12 -0
- package/dist/memory/store.js +281 -0
- package/dist/memory/tools.js +158 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/config.d.ts +252 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/config.js +110 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/domain.d.ts +512 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/domain.js +441 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/duration.d.ts +8 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/duration.js +28 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/events.d.ts +234 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/events.js +124 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/index.d.ts +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/index.js +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.d.ts +81 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.js +157 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json.d.ts +14 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json.js +23 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/limits.d.ts +17 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/limits.js +17 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/methods.d.ts +1107 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/methods.js +201 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.d.ts +45 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.js +44 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/validation.d.ts +20 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/validation.js +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/package.json +14 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.d.ts +11 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.js +162 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/commands.d.ts +48 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/commands.js +39 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.d.ts +29 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.js +27 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.d.ts +236 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/index.d.ts +10 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/index.js +7 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/json.d.ts +9 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/json.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/logger.d.ts +18 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/logger.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.d.ts +48 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.js +5 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/schema.d.ts +69 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/schema.js +3 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/tool.d.ts +69 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/tool.js +3 -0
- package/dist/node_modules/@wheatley-ai/sdk/package.json +11 -0
- package/dist/ops/backup.js +185 -0
- package/dist/ops/cli.js +195 -0
- package/dist/ops/command-runner.js +34 -0
- package/dist/ops/dashboard-assets.js +37 -0
- package/dist/ops/migrate.js +63 -0
- package/dist/ops/module.js +47 -0
- package/dist/ops/paths.js +55 -0
- package/dist/ops/service.js +376 -0
- package/dist/ops/update.js +145 -0
- package/dist/plugins/contributions.js +89 -0
- package/dist/plugins/guards.js +111 -0
- package/dist/plugins/load.js +76 -0
- package/dist/plugins/module.js +31 -0
- package/dist/plugins/provider.js +349 -0
- package/dist/plugins/schema.js +69 -0
- package/dist/skills/disclosure.js +142 -0
- package/dist/skills/discovery.js +120 -0
- package/dist/skills/fs-errors.js +8 -0
- package/dist/skills/read-skill-tool.js +3 -0
- package/dist/skills/skill-file.js +90 -0
- package/dist/skills/skills.js +140 -0
- package/dist/tools/builtin-tools.js +61 -0
- package/dist/tools/input.js +45 -0
- package/dist/tools/paths.js +6 -0
- package/dist/tools/read-file.js +65 -0
- package/dist/tools/shell.js +156 -0
- package/dist/tools/write-file.js +58 -0
- package/dist/triggers/delivery-codec.js +99 -0
- package/dist/triggers/delivery-outbox.js +313 -0
- package/dist/triggers/due-timer.js +14 -0
- package/dist/triggers/errors.js +2 -0
- package/dist/triggers/migrations.js +91 -0
- package/dist/triggers/module.js +104 -0
- package/dist/triggers/rpc.js +35 -0
- package/dist/triggers/schedule.js +52 -0
- package/dist/triggers/sql-row.js +59 -0
- package/dist/triggers/trigger-runtime.js +445 -0
- package/dist/triggers/trigger-tools.js +207 -0
- package/dist/triggers/webhook-ingress.js +216 -0
- package/dist/wiring/agent-services.js +144 -0
- package/dist/wiring/catalog.js +81 -0
- package/dist/wiring/daemon.js +83 -0
- package/dist/wiring/frontend-host.js +268 -0
- package/package.json +50 -3
- package/README.md +0 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as e,c as t,i as n,n as r,o as i,r as a,s as o,t as s}from"./index-RnxedkKh.js";var c=new WeakSet,l=e=>c.has(e);function u(e,t=!1,n){let r=e.defaultView??window,i=e=>n===void 0||!(`pointerId`in e)||e.pointerId===n,a=t=>{i(t)&&(t.preventDefault(),t.stopPropagation(),e.removeEventListener(`click`,a,!0))},o=()=>{e.removeEventListener(`click`,a,!0),e.removeEventListener(`pointerdown`,s,!0),e.removeEventListener(`pointerup`,c,!0),e.removeEventListener(`pointercancel`,c,!0)},s=e=>i(e)&&o(),c=e=>i(e)&&r.setTimeout(o);if(e.addEventListener(`click`,a,!0),e.addEventListener(`pointerdown`,s,!0),!t)return r.setTimeout(o);e.addEventListener(`pointerup`,c,!0),e.addEventListener(`pointercancel`,c,!0)}function d(e){return e.towardMore?!e.atLargest&&e.expandOnScroll?`sheet`:`scroll`:e.scrollAtStart?`sheet`:`scroll`}function f(e,t){return e*t/(1-t)}function p(e){let{extent:t,velocity:n,candidates:r}=e;if(Math.abs(n)<e.minFlingVelocity)return m(r,t);let i=t+f(n,e.rate),a=h(r,t,Math.sign(n)),o=m(r,i);return(n>0?r[o]<=t+.5:r[o]>=t-.5)&&a!==-1&&(o=a),!e.skipSnapPoints&&a!==-1&&(o=n>0?Math.min(o,a):Math.max(o,a)),o}function m(e,t){let n=0;for(let r=1;r<e.length;r++)Math.abs(e[r]-t)<Math.abs(e[n]-t)&&(n=r);return n}function h(e,t,n){if(n>0)return e.findIndex(e=>e>t+.5);for(let n=e.length-1;n>=0;n--)if(e[n]<t-.5)return n;return-1}var g=.55;function _(e,t,n=g){return e<=0?0:(1-1/(e*n/t+1))*t}function v(e,t,n=g){return e<=0?0:(1/(1-Math.min(e/t,.999999))-1)*t/n}function y(e,t,n=g){if(e<=0)return 1;let r=e*n/t+1;return n/(r*r)}function b(e,t,n,r){let i=2*Math.PI/(e*1e3),a=t;return Math.abs(a-1)<1e-6?S(i,n,r):a<1?x(i,a,n,r):C(i,a,n,r)}function x(e,t,n,r){let i=t*e,a=e*Math.sqrt(1-t*t),o=(r+i*n)/a;return{position:e=>Math.exp(-i*e)*(n*Math.cos(a*e)+o*Math.sin(a*e)),velocity:e=>{let t=Math.cos(a*e),r=Math.sin(a*e);return Math.exp(-i*e)*((o*a-i*n)*t-(n*a+i*o)*r)}}}function S(e,t,n){let r=n+e*t;return{position:n=>Math.exp(-e*n)*(t+r*n),velocity:n=>Math.exp(-e*n)*(r-e*(t+r*n))}}function C(e,t,n,r){let i=Math.sqrt(t*t-1),a=-e*(t+i),o=-e*(t-i),s=(r-a*n)/(o-a),c=n-s;return{position:e=>s*Math.exp(o*e)+c*Math.exp(a*e),velocity:e=>s*o*Math.exp(o*e)+c*a*Math.exp(a*e)}}function ee(e,{positionTolerance:t=.5,velocityTolerance:n=.02,step:r=1,limit:i=1e4}={}){for(let a=0;a<=i;a+=r)if(Math.abs(e.position(a))<=t&&Math.abs(e.velocity(a))<=n)return a;return i}function w(e,t,n,r,i=1e3/120){let a=n-t;if(Math.abs(a)<1e-6)return`linear`;let o=[];for(let t=0;t<r;t+=i)o.push(T(1+e.position(t)/a));return o.push(`1`),`linear(${o.join(`, `)})`}function T(e){return String(Math.round(e*1e4)/1e4)}var E=[],D=1;function O(e,t){return{phase:`idle`,extent:e,restingIndex:t}}function k(e,t,n){switch(t.type){case`down`:return j(e,t,n);case`move`:return M(e,t,n);case`up`:return I(e,t,n);case`settled`:return L(e);case`rest`:return R(e,t,n);case`snap-to`:return z(e,t,n);case`nudge`:return B(e,t,n);case`close`:return V(e,n,{targetIndex:-1,motion:A(e,t.time),time:t.time,reason:`imperative`,outcome:{type:`dismiss`,reason:`imperative`}})}}function A(e,t){if(e.phase!==`settling`)return{extent:e.extent,velocity:0};let n=b(e.response,e.dampingRatio,e.from-e.to,e.velocity),r=Math.max(0,t-e.startTime);return{extent:e.to+n.position(r),velocity:n.velocity(r)}}function j(e,t,n){let r=t.pointer===`mouse`?n.physics.mouseSlop:n.physics.touchSlop;if(e.phase===`idle`&&e.restingIndex>=0)return{state:{...e,phase:`pending`,originX:t.x,originY:t.y,slop:r},effects:E};if(e.phase!==`settling`)return{state:e,effects:E};let{extent:i}=A(e,t.time);return{state:{phase:`dragging`,extent:i,restingIndex:e.restingIndex,anchorY:t.y,anchorExtent:U(i,n),lastY:t.y,isScrollingContent:!1},effects:[{type:`move`,extent:i}]}}function M(e,t,n){return e.phase===`pending`?N(e,t,n):e.phase===`scrolling`&&n.contentScroll?n.contentScroll.move(e,t):e.phase===`dragging`?F(e,t,n):{state:e,effects:E}}function N(e,t,n){let r=t.x-e.originX,i=t.y-e.originY;if(Math.max(Math.abs(r),Math.abs(i))<e.slop)return{state:e,effects:E};if(Math.abs(r)>Math.abs(i))return{state:O(e.extent,e.restingIndex),effects:E};let a=n.contentScroll?.claim(e,t,i<0,n);if(a)return{state:a,effects:E};let o={...P(e,e.originY+Math.sign(i)*e.slop),lastY:t.y},s=H(o.anchorExtent+(o.anchorY-t.y),n);return{state:{...o,extent:s},effects:[{type:`move`,extent:s}]}}function P(e,t){return{phase:`dragging`,extent:e.extent,restingIndex:e.restingIndex,anchorY:t,anchorExtent:e.extent,lastY:t,isScrollingContent:!1}}function F(e,t,n){let r=e.lastY-t.y,i=e.isScrollingContent?{anchorY:e.lastY,anchorExtent:e.extent}:e,a=i.anchorExtent+(i.anchorY-t.y),o=n.contentScroll?.drag(e,t,r,a,n);if(o)return o;let s=H(a,n);return{state:{...e,anchorY:i.anchorY,anchorExtent:i.anchorExtent,extent:s,lastY:t.y,isScrollingContent:!1},effects:[{type:`move`,extent:s}]}}function I(e,t,n){if(e.phase===`pending`||e.phase===`scrolling`)return{state:O(e.extent,e.restingIndex),effects:E};if(e.phase!==`dragging`)return{state:e,effects:E};let r=n.contentScroll?.release(e,t,n);if(r)return r;let i=-t.velocity*G(e.extent,n),a=[0,...q(n)],o=n.physics,s={candidates:a,rate:o.projectionRate,minFlingVelocity:o.minFlingVelocity,skipSnapPoints:o.skipSnapPoints},c=p({...s,extent:e.extent,velocity:i}),l={motion:{extent:e.extent,velocity:i},time:t.time,reason:`swipe`};if(n.dismissible)return c>0?V(e,n,{...l,targetIndex:c-1}):V(e,n,{...l,targetIndex:-1,outcome:{type:`dismiss`,reason:`swipe`}});let u=e.anchorExtent+(e.anchorY-e.lastY),d=p({...s,extent:u,velocity:-t.velocity})===0,f=Math.max(0,c-1);return d?V(e,n,{...l,targetIndex:0,outcome:{type:`attempt-dismiss`,reason:`swipe`}}):V(e,n,{...l,targetIndex:f})}function L(e){return e.phase===`settling`?{state:O(e.to,e.targetIndex),effects:E}:{state:e,effects:E}}function R(e,t,n){if(t.extent<1&&n.dismissible)return{state:O(0,-1),effects:[{type:`dismiss`,reason:`swipe`}]};let r=m(q(n),t.extent),i=r===e.restingIndex?[]:[{type:`snap`,id:n.snapPoints[r].id,reason:`swipe`}];return{state:O(t.extent,r),effects:i}}function z(e,t,n){let r=n.snapPoints.findIndex(e=>e.id===t.id);return r===-1||e.phase===`dragging`?{state:e,effects:E}:V(e,n,{targetIndex:r,motion:A(e,t.time),time:t.time,reason:t.reason})}function B(e,t,n){return e.phase!==`idle`||e.restingIndex<0?{state:e,effects:E}:V(e,n,{targetIndex:e.restingIndex,motion:{extent:e.extent,velocity:-D},time:t.time,reason:`imperative`})}function V(e,t,n){let{targetIndex:r,motion:i,time:a,reason:o}=n,s=t.physics,c=r<0?0:t.snapPoints[r].extent,l=Math.abs(i.velocity)>=s.minFlingVelocity?s.momentumDampingRatio:s.dampingRatio,u={phase:`settling`,extent:i.extent,restingIndex:e.restingIndex,targetIndex:r,from:i.extent,to:c,velocity:i.velocity,response:s.response,dampingRatio:l,startTime:a},d=[{type:`settle`,from:i.extent,to:c,velocity:i.velocity,response:s.response,dampingRatio:l}];return r>=0&&r!==e.restingIndex&&d.push({type:`snap`,id:t.snapPoints[r].id,reason:o}),n.outcome&&d.push(n.outcome),{state:u,effects:d}}function H(e,t){let n=K(t),{coefficient:r,dimension:i}=W(t);if(e>n)return n+_(e-n,i,r);if(t.dismissible)return Math.max(0,e);let a=t.snapPoints[0].extent;return e<a?a-_(a-e,i,r):e}function U(e,t){let n=K(t),{coefficient:r,dimension:i}=W(t);if(e>n)return n+v(e-n,i,r);let a=t.snapPoints[0].extent;return!t.dismissible&&e<a?a-v(a-e,i,r):e}function W(e){return{coefficient:e.physics.rubberBand,dimension:e.physics.rubberBandDimension??e.dimension}}function G(e,t){let{coefficient:n,dimension:r}=W(t),i=K(t),a=t.snapPoints[0].extent,o=e>i?e-i:!t.dismissible&&e<a?a-e:0;return o<=0?1:y(v(o,r,n),r,n)}function K(e){return e.snapPoints[e.snapPoints.length-1].extent}function q(e){return e.snapPoints.map(e=>e.extent)}var J=[],te={claim(e,t,n,r){if(t.scroll&&d({towardMore:n,scrollAtStart:t.scroll.atStart,atLargest:e.extent>=K(r)-.5,expandOnScroll:r.expandOnScroll})===`scroll`)return{phase:`scrolling`,extent:e.extent,restingIndex:e.restingIndex,lastY:t.y}},move(e,t){return t.y>e.lastY&&t.scroll?.atStart?{state:P(e,t.y),effects:J}:{state:{...e,lastY:t.y},effects:J}},drag(e,t,n,r,i){let a=t.scroll;if(!a)return;if(e.isScrollingContent&&(n>0?!a.atEnd:!a.atStart)){let r=[{type:`scroll`,delta:n}];return{state:{...e,lastY:t.y},effects:r}}let o=K(i);if(!(n>0&&r>o&&e.extent<=o&&!a.atEnd))return;let s=[{type:`scroll`,delta:r-o}];return e.extent!==o&&s.unshift({type:`move`,extent:o}),{state:{...e,extent:o,anchorY:t.y,anchorExtent:o,lastY:t.y,isScrollingContent:!0},effects:s}},release(e,t,n){if(!e.isScrollingContent)return;let r=n.snapPoints.length-1,i=[{type:`fling-scroll`,velocity:-t.velocity}];return e.restingIndex!==r&&i.push({type:`snap`,id:n.snapPoints[r].id,reason:`swipe`}),{state:O(e.extent,r),effects:i}}},Y={ios:{response:.34,dampingRatio:1,momentumDampingRatio:.88,projectionRate:.99,minFlingVelocity:.5,skipSnapPoints:!0,rubberBand:1.9,rubberBandDimension:24,touchSlop:8,mouseSlop:4,dim:.2,velocityHorizon:70}};function ne(e){return String(e)}function re(e,t){if(typeof e==`number`)return e<=1?e*t.container:e;if(e===`content`)return t.content;let n=parseFloat(e);return e.endsWith(`rem`)?n*t.rootFontSize:e.endsWith(`%`)?n/100*t.container:e.endsWith(`px`)?n:NaN}function X(e,t){let n=e.map((e,n)=>({value:e,index:n,extent:Math.min(re(e,t),t.content)})).filter(e=>e.extent>0).sort((e,t)=>e.extent-t.extent||e.index-t.index),r=[];for(let e of n){let t=ne(e.value),n=r[r.length-1];n&&e.extent-n.extent<1?(n.ids.push(t),e.index>n.index&&Object.assign(n,{id:t,value:e.value,index:e.index}),n.extent=Math.max(n.extent,e.extent)):r.push({id:t,value:e.value,extent:Math.round(e.extent*100)/100,ids:[t],index:e.index})}return r.map(({index:e,...t})=>t)}function Z(e,t){if(t==null)return-1;let n=String(t);return e.findIndex(e=>e.ids.includes(n))}function ie(e,t,n){let r=Z(e,n),i=Z(e,t);return r>=0&&i>=0&&i<=r}function ae(e,t){return r(e,e===`start`||e===`end`?o(t):!1)}var Q=e=>e===`bottom`||e===`top`,oe=e=>e===`bottom`||e===`right`?1:-1;function $(e,t,n,r){let i=Q(e);return r.y=(i?n:t)*oe(e),r.x=i?t:n,r}function se(e,t){let n=`${Math.round(t*oe(e)*100)/100}px`;return Q(e)?`0 ${n}`:`${n} 0`}function ce(e,t){return Q(t)?e.offsetHeight:e.offsetWidth}function le(e,t,n){let r=ue(e,t,n);if(!r)return null;let{start:i,end:a}=fe(r,n);return{atStart:i,atEnd:a,area:r}}function ue(e,t,n){let r=t.ownerDocument.defaultView;if(!r||!(e instanceof Element)||!t.contains(e))return null;let i=Q(n);for(let n=e;n&&n!==t.parentElement;n=n.parentElement){if(!(i?n.scrollHeight>n.clientHeight+1:n.scrollWidth>n.clientWidth+1)||!(n instanceof HTMLElement))continue;let e=i?r.getComputedStyle(n).overflowY:r.getComputedStyle(n).overflowX;if(/auto|scroll/.test(e))return n}return null}function de(e,t){if(Q(t)){let n=e.scrollHeight-e.clientHeight;return{position:t===`bottom`?e.scrollTop:n-e.scrollTop,max:n}}let n=e.scrollWidth-e.clientWidth,r=Math.abs(e.scrollLeft),i=o(e)?n-r:r;return{position:t===`right`?i:n-i,max:n}}function fe(e,t){let{position:n,max:r}=de(e,t);return{start:n<=.5,end:n>=r-1}}function pe(e,t,n){if(Q(t))e.scrollTop+=t===`bottom`?n:-n;else{let r=t===`right`?n:-n;e.scrollLeft+=o(e)?-r:r}}var me=1e3;function he(e,t){e.requestAnimationFrame(()=>e.requestAnimationFrame(t))}function ge(e){return e===`bottom`?-120:-32}function _e(e,t){let n=[];for(let r=0;r<e.duration;r+=1e3/60)n.push(t(e.extentAt(r)));return n.push(t(e.extentAt(e.duration))),n}function ve(e,t){let r=Object.entries(t).map(([t,r])=>n(e,t,r));return()=>r.forEach(e=>e())}var ye=e=>Math.max(0,Math.min(1,e));function be(e,t,n=-1){let r=n<0?0:t[n],i=n<0?t[0]:t[n+1];return i===void 0||i<=r?+(e>r):ye((e-r)/(i-r))}function xe(e,t){let n=t[t.length-1],r=t.length>1?t[t.length-2]:0;return n<=r?+(e>=n):ye((e-r)/(n-r))}function Se(e,t){let n=t[t.length-1];return n>0?ye(e/n):0}var Ce=1e3/60,we=[`--drawer-progress`,`--drawer-dim`,`--drawer-expand`,`--drawer-stack`],Te=new WeakSet;function Ee(e){let t=e.defaultView?.CSS;if(!Te.has(e)&&t?.registerProperty){Te.add(e);for(let e of we)try{t.registerProperty({name:e,syntax:`<number>`,inherits:!1,initialValue:`0`})}catch{}}}function De(){typeof document<`u`&&!Te.has(document)&&a(()=>Ee(document))}var Oe=()=>typeof CSS<`u`&&CSS.supports(`animation-timing-function`,`linear(0, 1)`),ke=e=>Math.round(e*1e4)/1e4;function Ae(e){Ee(e.sheet.ownerDocument);let t=[1],n=-1,r=[],i=new Map,a={dim:0,progress:0,expand:0},o;function s(e){t=e.snapExtents.length?e.snapExtents:[1],n=e.undimmedIndex}function c(e,r=a){return r.dim=ke(be(e,t,n)),r.progress=ke(Se(e,t)),r.expand=ke(xe(e,t)),r}let l=!1;function u(t,{rest:n=!1}={}){if(!l){x(),c(t),d(a.dim),m(e.sheet,a),p(a.progress);for(let t of e.outlets())m(t.el,a),t.keyframes&&h(t,a.expand,n);n&&e.themeColor?.(a.dim)}}function d(t){let n=e.backdrop();n&&(n.style.opacity=String(t));let r=f();r&&(r.currentTime=t*1e3)}function f(){return!e.dimmed||o||(o=e.dimmed.animate({opacity:[0,1]},{...je,duration:1e3,fill:`both`}),o.pause(),o.currentTime=0),o}function p(t){let n=e.ancestors();for(let e=0;e<n.length;e++)n[e].style.setProperty(`--drawer-stack`,String(e+t))}function m(e,{dim:t,progress:n,expand:r}){e.style.setProperty(`--drawer-progress`,String(n)),e.style.setProperty(`--drawer-dim`,String(t)),e.style.setProperty(`--drawer-expand`,String(r))}function h(e,t,n){let r=i.get(e.el);r||(r=e.el.animate(Ne(e.keyframes),{duration:1e3,fill:`both`}),r.pause(),i.set(e.el,r)),r.currentTime=t*1e3,n&&(r.commitStyles?.(),r.cancel(),i.delete(e.el))}function g(t){if(l)return;if(x(),S(),!Oe())return u(t.type===`settle`?t.extentAt(t.duration):0,{rest:!0});let n=y(t);f();let i=t.type===`settle`?{duration:Math.max(1,t.duration),fill:`both`}:{timeline:t.timeline,fill:`both`},a=(e,n,a,o)=>{let s=e.animate(n,{...i,...o,easing:Me(a)});t.type===`settle`&&(s.startTime=t.startTime),r.push(s)},o=e.backdrop();o&&a(o,{opacity:[0,1]},n.dim),e.dimmed&&a(e.dimmed,{opacity:[0,1]},n.dim,je),_(e.sheet,n,a),e.ancestors().forEach((e,t)=>a(e,{"--drawer-stack":[t,t+1]},n.progress));for(let t of e.outlets())_(t.el,n,a),t.keyframes&&a(t.el,Ne(t.keyframes),n.expand);if(t.type!==`settle`)return;v(t.extentAt(t.duration));let s=r;s[0]&&(s[0].onfinish=()=>r===s&&x())}function _(e,t,n){n(e,{"--drawer-progress":[0,1]},t.progress),n(e,{"--drawer-dim":[0,1]},t.dim),n(e,{"--drawer-expand":[0,1]},t.expand)}function v(t){let n=c(t,{dim:0,progress:0,expand:0});d(n.dim),m(e.sheet,n),p(n.progress);for(let t of e.outlets())if(m(t.el,n),t.keyframes)for(let[e,r]of Object.entries(t.keyframes)){let i=r[n.expand>=.5?r.length-1:0];t.el.style.setProperty(Pe(e),String(i))}e.themeColor?.(n.dim)}function y(e){let t={dim:[],progress:[],expand:[]},n={dim:0,progress:0,expand:0},r=e.type===`settle`?Math.max(2,Math.ceil(e.duration/Ce)+1):61;for(let i=0;i<r;i++){let a=i/(r-1);c(e.type===`settle`?e.extentAt(Math.min(e.duration,i*Ce)):e.extentAt(a),n),t.dim.push(n.dim),t.progress.push(n.progress),t.expand.push(n.expand)}return t}function b(e){for(let t of r)t.startTime=e}function x(){if(r.length){for(let e of r)e.cancel();r=[]}}function S(){for(let e of i.values())e.cancel();i.clear()}function C(){l=!0,x(),S(),e.backdrop()?.style.removeProperty(`opacity`),o?.cancel();for(let t of we.slice(0,3))e.sheet.style.removeProperty(t);for(let t of e.outlets()){for(let e of we.slice(0,3))t.el.style.removeProperty(e);for(let e of Object.keys(t.keyframes??{}))t.el.style.removeProperty(Pe(e))}}return{configure:s,compute:c,apply:u,play:g,sync:b,follow:g,stop:x,destroy:C}}var je={pseudoElement:`::backdrop`};function Me(e){return`linear(${e.map(ke).join(`, `)})`}var Ne=e=>e;function Pe(e){return e.startsWith(`--`)?e:e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}var Fe={horizon:70,staleAfter:40,maxSpeed:8,capacity:20};function Ie(e,t,n=0,r=e.length){let i=r-n;if(i<2)return 0;let a=e[r-1];if(i<4)return Le(e,t,n,r);let o=0,s=0,c=0,l=0,u=0,d=0,f=0,p=0;for(let i=n;i<r;i++){let n=e[i]-a,r=t[i],m=n*n;o+=1,s+=n,c+=m,l+=m*n,u+=m*m,d+=r,f+=r*n,p+=r*m}let m=o*(c*u-l*l)-s*(s*u-l*c)+c*(s*l-c*c);return Math.abs(m)<1e-9?Le(e,t,n,r):(o*(f*u-l*p)-d*(s*u-l*c)+c*(s*p-f*c))/m}function Le(e,t,n,r){let i=0,a=0,o=r-n;for(let s=n;s<r;s++)i+=e[s]/o,a+=t[s]/o;let s=0,c=0;for(let o=n;o<r;o++){let n=e[o]-i;s+=n*(t[o]-a),c+=n*n}return c>0?s/c:0}function Re(e={}){let{horizon:t,staleAfter:n,maxSpeed:r,capacity:i}={...Fe,...e},a=new Float64Array(i),o=new Float64Array(i),s=new Float64Array(i),c=new Float64Array(i),l=0,u=-1;function d(e,t){l>0&&e<=a[u]||(u=(u+1)%i,a[u]=e,o[u]=t,l=Math.min(l+1,i))}function f(e){if(l<2)return 0;let d=a[u];if(e-d>n)return 0;let f=0;for(let e=l-1;e>=0;e--){let n=(u-e+i)%i;d-a[n]>t||(s[f]=a[n],c[f]=o[n],f++)}let p=Ie(s,c,0,f);return Math.max(-r,Math.min(r,p))}function p(){l=0,u=-1}return{add:d,velocity:f,reset:p}}var ze=.998,Be=`input, textarea, select, [contenteditable]:not([contenteditable="false"]), [data-drawer-no-drag]`;function Ve(e){let{sheet:n}=e,r=n.ownerDocument,i=r.defaultView??window,a=O(0,-1),o=0,s=null,c=0,f=0,p=null,h=null,g=null,_=null,v=null,y=null,x=null,S=!1,C=!1,T=null,E=null,D=null,A={x:0,y:0},j=Re({horizon:e.config().physics.velocityHorizon}),M=[t(r,`touchstart`,q,{capture:!0,passive:!0}),t(r,`touchmove`,J,{capture:!0,passive:!1}),t(r,`touchend`,Y,{capture:!0,passive:!0}),t(r,`touchcancel`,Y,{capture:!0,passive:!0}),t(n,`pointerdown`,re)],N=!1;function P(t){N||(n.style.translate=se(e.side(),e.size()-t),o=t)}function F(t,n){if(N)return;let r=k(a,t,e.config());a=r.state;let i=`time`in t?t.time:performance.now();for(let e of r.effects)I(e,i,n);let o=a.phase===`dragging`;o!==S&&(S=o,e.onDragChange(S))}function I(t,n,r){switch(t.type){case`move`:p?(B(),P(t.extent),e.onFrame(t.extent)):(s=t.extent,H());return;case`settle`:return L(t,n);case`scroll`:return c+=t.delta,H();case`fling-scroll`:return v&&(_={velocity:t.velocity,startTime:n,startScroll:0,area:v}),H();case`snap`:return E=t.id,e.onSnap(t.id,t.reason,r);case`dismiss`:return t.reason===`swipe`?(g=`swipe`,e.onDismiss(r)):void 0;case`attempt-dismiss`:return e.onDismissAttempt(r)}}function L(t,r){B(),s=null;let i=e.closedExtent(),a=t.from<=0?i:t.from,o=t.to<=0?i:t.to,c=e.reducedMotion()&&(a===i||o===i),l=e.reducedMotion()?z(a,o,c):R(a,o,t);if(P(c?Math.max(o,0):o),Math.abs(o-a)<.5&&t.velocity===0||l.duration===0)return V();let u=e.size(),d=e.side();p=c?n.animate({opacity:a===i?[0,1]:[1,0]},{duration:l.duration,fill:`both`}):Math.abs(o-a)<1||!Oe()?n.animate({translate:_e(l,e=>se(d,u-e))},{duration:l.duration,fill:`backwards`}):n.animate({translate:[se(d,u-a),se(d,u-o)]},{duration:l.duration,easing:l.easing,fill:`backwards`}),c&&(h=p);let f=p;p.onfinish=()=>{p===f&&V()},p.startTime=r,e.onMotion({type:`settle`,extentAt:l.extentAt,startTime:r,duration:l.duration})}function R(e,t,n){let r=b(n.response,n.dampingRatio,e-t,n.velocity),i=ee(r);return{duration:i,easing:w(r,e,t,i),extentAt:e=>t+r.position(e)}}function z(e,t,n){let r=n?150:200,i=e=>1-(1-e)**3;return{duration:r,easing:`cubic-bezier(0.33, 1, 0.68, 1)`,extentAt:n=>e+(t-e)*i(Math.min(1,n/r))}}function B(){p?.cancel(),p=null,h&&=(h.cancel(),null)}function V(){if(B(),F({type:`settled`}),a.phase===`idle`){if(a.restingIndex<0)return g=null,E=null,e.onRest(null);E=e.config().snapPoints[a.restingIndex].id,e.onRest(E)}}function H(){f||=i.requestAnimationFrame(U)}function U(t){f=0,c&&v&&(pe(v,e.side(),c),c=0),_&&W(t),s!==null&&(P(s),s=null,e.onFrame(o))}function W(t){if(!_)return;let n=Math.max(0,t-_.startTime),r=_.velocity*(ze**n-1)/Math.log(ze);pe(_.area,e.side(),r-_.startScroll),_.startScroll=r,Math.abs(_.velocity*ze**n)<.01?_=null:H()}function G(e){return e instanceof Element&&e.closest(Be)!==null}function K(t){let r=le(t,n,e.side());return v=r?.area??null,r&&{atStart:r.atStart,atEnd:r.atEnd}}function q(t){let n=T!==null&&l(T);if(T=null,y||t.touches.length>1||g||n||!e.owns(t.target)||G(t.target))return;let r=t.changedTouches[0];y={id:r.identifier,originX:r.clientX,originY:r.clientY},_=null,j.reset(),$(e.side(),r.clientX,r.clientY,A),j.add(t.timeStamp,A.y),F({type:`down`,time:t.timeStamp,x:A.x,y:A.y,pointer:`touch`},t)}function J(t){let n=ne(t.changedTouches);if(!n)return;$(e.side(),n.clientX,n.clientY,A),j.add(t.timeStamp,A.y);let r=a.phase===`dragging`,i=K(t.target);if(F({type:`move`,time:t.timeStamp,x:A.x,y:A.y,scroll:i},t),a.phase===`pending`)return te(t,n,i);a.phase===`dragging`&&(t.cancelable?t.preventDefault():!r&&v&&(v.style.overscrollBehavior=`none`))}function te(t,n,r){if(!t.cancelable||!y)return;let i=$(e.side(),y.originX,y.originY,{x:0,y:0});if(Math.abs(A.y-i.y)<Math.abs(A.x-i.x))return;let a=e.config().snapPoints.at(-1)?.extent??0;(r?d({towardMore:A.y<i.y,scrollAtStart:r.atStart,atLargest:o>=a-.5,expandOnScroll:e.config().expandOnScroll}):`sheet`)===`sheet`&&t.preventDefault()}function Y(e){if(!ne(e.changedTouches))return;y=null,v&&v.style.removeProperty(`overscroll-behavior`);let t=e.type===`touchcancel`?0:j.velocity(e.timeStamp);F({type:`up`,time:e.timeStamp,velocity:t},e)}function ne(e){if(!y)return null;for(let t=0;t<e.length;t++)if(e[t].identifier===y.id)return e[t];return null}function re(n){if(T=n,n.pointerType===`touch`||n.button!==0||x!==null||g)return;let i=n.target;if(!e.owns(i)||G(i)||!(i instanceof Element)||!e.canMouseDrag(i))return;x=n.pointerId,C=!1,D=a.phase===`settling`&&a.targetIndex>=0?E:null,_=null,j.reset(),$(e.side(),n.clientX,n.clientY,A),j.add(n.timeStamp,A.y),X=[t(r,`pointermove`,Z,{capture:!0}),t(r,`pointerup`,ie,{capture:!0}),t(r,`pointercancel`,ie,{capture:!0})];let o=n.pointerType===`pen`?`pen`:`mouse`;F({type:`down`,time:n.timeStamp,x:A.x,y:A.y,pointer:o},n)}let X=[];function Z(t){if(t.pointerId!==x)return;if(T&&l(T))return ae(t,0,D);let i=t.getCoalescedEvents?.();for(let n of i?.length?i:[t])j.add(n.timeStamp,$(e.side(),n.clientX,n.clientY,A).y);if($(e.side(),t.clientX,t.clientY,A),F({type:`move`,time:t.timeStamp,x:A.x,y:A.y,scroll:K(t.target)},t),!(a.phase!==`dragging`||C)){C=!0,r.getSelection()?.removeAllRanges(),n.style.userSelect=`none`;try{n.setPointerCapture(t.pointerId)}catch{}}}function ie(e){if(e.pointerId===x){if(T&&l(T))return ae(e,0,D);ae(e,e.type===`pointercancel`?0:j.velocity(e.timeStamp))}}function ae(t,i,o=null){x=null,T=null,X.forEach(e=>e()),X=[],n.style.removeProperty(`user-select`);let s=t.timeStamp,c=e.config().snapPoints.findIndex(e=>e.id===o);o!==null&&c>=0?(a=O(a.extent,c),F({type:`snap-to`,time:s,id:o,reason:`imperative`})):F({type:`up`,time:s,velocity:i},t),C&&u(r)}return{open(t,n){g=null,E=t,B();let r=e.config().snapPoints.findIndex(e=>e.id===t);if(!n&&r>=0)return a=O(e.config().snapPoints[r].extent,r),P(a.extent),e.onRest(t);a=O(0,-1),P(e.closedExtent()),F({type:`snap-to`,time:performance.now()+me,id:t,reason:`imperative`});let o=p;o&&he(i,t=>{p===o&&a.phase===`settling`&&(o.startTime=t,a={...a,startTime:t},e.onMotionStart(t))})},close(){let e=g;g=`close`,e||F({type:`close`,time:performance.now()})},snapTo(e,t){g!==`close`&&(g=null,F({type:`snap-to`,time:performance.now(),id:e,reason:t}))},nudge(){!g&&!e.reducedMotion()&&F({type:`nudge`,time:performance.now()})},relayout(t,n){let r=e.config().snapPoints;if(g||E===null||a.phase===`dragging`||a.phase===`pending`)return P(o);let i=r.findIndex(e=>e.id===E),s=r.findIndex(e=>e.id===n),c=i>=0?i:s>=0?s:m(r.map(e=>e.extent),o),{id:l,extent:u}=r[c];if(a.phase===`idle`&&(a=O(o,i),t||Math.abs(u-o)<.5))return a=O(u,c),P(u),t?(l!==E&&I({type:`snap`,id:l,reason:`content-resize`},performance.now()),e.onRest(l)):void 0;F({type:`snap-to`,time:performance.now(),id:l,reason:`content-resize`})},target:()=>g?null:E,isMoving:()=>a.phase!==`idle`,destroy(){N=!0,B(),f&&i.cancelAnimationFrame(f),M.forEach(e=>e()),X.forEach(e=>e()),S&&e.onDragChange(!1);for(let e of[`translate`,`user-select`,`opacity`])n.style.removeProperty(e)}}}var He=120,Ue=24;function We(e){let{sheet:n,host:r}=e,a=n.ownerDocument,o=a.defaultView??window,s=O(0,-1),c=0,l=[],u=null,d=!1,f=!1,p=!1,h=null,g=0,_=0,v=null,y=new Map,x=null,S=ve(r,{inset:`0 0 calc(var(--keyboard-inset, 0px) - 120px) 0`,display:`block`,"overflow-y":`scroll`,"overflow-x":`hidden`,"scroll-snap-type":`y mandatory`,"scrollbar-width":`none`,"overscroll-behavior":`contain`,"pointer-events":`auto`}),C=ve(n,{position:`absolute`,left:`0`,right:`0`}),T=`onscrollend`in r,E=o.ScrollTimeline,D=[t(r,`scroll`,R,{passive:!0}),...T?[t(r,`scrollend`,H)]:[],t(r,`touchstart`,()=>{d=!0,f=!1,u&&!h&&W()},{passive:!0}),t(r,`touchend`,B,{passive:!0}),t(r,`touchcancel`,B,{passive:!0})],A=i()?1:121,j=new IntersectionObserver(U,{root:r,rootMargin:`0px 0px -${A}px 0px`,threshold:0});j.observe(n);let M=()=>e.config().dimension,N=()=>e.config().snapPoints.at(-1)?.extent??0,P=()=>N()+Ue-c,F=()=>Math.min(r.scrollTop+c,N());function I(){let t=e.config();c=t.dismissible?-120:t.snapPoints[0].extent,n.style.top=`${M()-c}px`;for(let e of l)e.remove();let i=t.snapPoints.map(e=>e.extent);l=(t.dismissible?[c,...i]:i).map(e=>L(e-c,`start`)),l.push(L(P()+r.clientHeight-1,`none`)),r.append(...l);for(let e of y.keys())n.contains(e)||y.delete(e);for(let e of Ge(n))y.has(e)||y.set(e,[e.style.getPropertyValue(`overflow-y`),e.style.getPropertyPriority(`overflow-y`)])}function L(e,t){let n=a.createElement(`div`);return n.setAttribute(`aria-hidden`,`true`),n.style.cssText=`position:absolute;left:0;width:1px;height:1px;top:${e}px;scroll-snap-align:${t};pointer-events:none`,n}function R(){u||h||(x&&d&&Math.abs(r.scrollTop-x.offsetTop)>1&&G(),d&&!p&&V(!0),E||(_||=o.requestAnimationFrame(z)),o.clearTimeout(g),!T&&!d&&(g=o.setTimeout(H,He)))}function z(){_=0,e.onFrame(F())}function B(){if(d=!1,V(!1),x){G();let t=e.config().snapPoints;return Y(t[m(t.map(e=>e.extent),F())].id,`swipe`)}!e.config().dismissible&&r.scrollTop<-2&&e.onDismissAttempt(),(f||!T)&&(g=o.setTimeout(H,He)),f=!1}function V(t){p!==t&&(p=t,e.onDragChange(t))}function H(){if(d){f=!0;return}if(u||h)return;let t=e.config(),n=k(s,{type:`rest`,extent:F()},t);s=n.state;for(let t of n.effects)t.type===`snap`&&(v=t.id,e.onSnap(t.id,t.reason));s.restingIndex>=0&&J(t.snapPoints[s.restingIndex].id)}function U(t){t[t.length-1].isIntersecting||u||h||v===null||!e.config().dismissible||(h=`swipe`,v=null,e.onDismiss())}function W(){if(!u)return;let e=Math.max(0,u.extentAt(performance.now()-u.startTime)-c);q(),x=L(e,`start`),r.append(x),r.scrollTop=e,z(),te()}function G(){x?.remove(),x=null}function K(t,i,a,o){q();let s=e.config().physics,l=b(s.response,s.dampingRatio,i-t,0),d=Math.max(1,ee(l)),f=Math.max(c,t);r.scrollTop=f-c;let p=e=>t+l.position(Math.max(0,e)),m=Math.abs(t-i)<.5,h=!m&&!Oe(),g=n.animate({translate:h?_e({duration:d,extentAt:p},e=>`0 ${f-e}px`):[`0 ${f-i}px`,`0 ${f-t}px`]},{duration:d,easing:m||h?`linear`:w(l,i,t,d),fill:`both`});g.startTime=a,u={animation:g,to:t,extentAt:p,startTime:a},e.onMotion({type:`settle`,extentAt:p,startTime:a,duration:d}),g.onfinish=()=>{u?.animation===g&&(u=null,o(),g.cancel())}}function q(){u?.animation.cancel(),u=null}function J(t){let n=e.config(),i=n.snapPoints.findIndex(e=>e.id===t);s=O(n.snapPoints[i].extent,i),v=t,r.style.pointerEvents=e.isInteractive(t)?`none`:`auto`;let a=i===n.snapPoints.length-1;for(let[e,[t,n]]of y)a?e.style.setProperty(`overflow-y`,t,n):e.style.overflowY=`hidden`;e.onRest(t),te()}function te(){if(!E)return;let t=P(),n=new E({source:r,axis:`block`});e.onMotion({type:`timeline`,timeline:n,extentAt:e=>Math.min(N(),e*t+c)})}function Y(t,n){let r=e.config().snapPoints.find(e=>e.id===t);if(!r||h===`close`)return;h=null,t!==v&&(v=t,e.onSnap(t,n));let i=u?u.extentAt(performance.now()-u.startTime):F();K(r.extent,i,performance.now(),()=>J(t))}return{open(t,n){h=null,v=t,I();let i=e.config().snapPoints.find(e=>e.id===t);if(!i)return;if(!n)return r.scrollTop=i.extent-c,J(t);K(i.extent,-120,performance.now()+me,()=>J(t));let a=u;he(o,t=>{a&&u===a&&(a.animation.startTime=t,a.startTime=t,e.onMotionStart(t))})},close(){let t=h;h=`close`,t||(v=null,K(-120,u?u.extentAt(performance.now()-u.startTime):F(),performance.now(),()=>e.onRest(null)))},snapTo:Y,nudge(){if(h||e.reducedMotion()||v===null)return;let t=e.config().snapPoints.find(e=>e.id===v);t&&K(t.extent,t.extent-20,performance.now(),()=>J(t.id))},relayout(t,n){if(h||d)return;let i=e.config().snapPoints,a=i.findIndex(e=>e.id===v),o=i.findIndex(e=>e.id===n),s=a>=0?a:o>=0?o:m(i.map(e=>e.extent),F()),l=c;I();let f=i[s];if(f.id!==v&&(v=f.id,e.onSnap(f.id,`content-resize`)),u){let e=u,t=performance.now();(e.to!==f.extent||c!==l)&&(K(f.extent,e.extentAt(t-e.startTime),Math.max(t,e.startTime),()=>J(f.id)),u=Object.assign(e,u))}else r.scrollTop=f.extent-c,J(f.id)},target:()=>h?null:v,isMoving:()=>!!u||p,destroy(){q(),G(),o.clearTimeout(g),_&&o.cancelAnimationFrame(_),j.disconnect(),D.forEach(e=>e());for(let e of l)e.remove();for(let[e,[t,n]]of y)e.style.setProperty(`overflow-y`,t,n);p&&e.onDragChange(!1),n.style.removeProperty(`top`),C(),S()}}}function Ge(e){let t=e.ownerDocument.defaultView??window;return Array.from(e.querySelectorAll(`*`)).filter(e=>/auto|scroll/.test(t.getComputedStyle(e).overflowY))}function Ke(e){let t=/^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/.exec(e);return t?[t[1],t[2],t[3]].map(Number):null}function qe(e,t){let n=Array.from(e.querySelectorAll(`meta[name="theme-color"]`)),r=n.map(e=>e.content),i=r.map(t=>Ke(Je(e,t))),a=-1;function o(e){let o=Math.round(e*t*100)/100;o!==a&&(a=o,n.forEach((e,t)=>{let n=i[t];n&&(e.content=o?`rgb(${n.map(e=>Math.round(e*(1-o))).join(` `)})`:r[t])}))}function s(){n.forEach((e,t)=>e.content=r[t]),a=-1}return{write:o,restore:s}}function Je(e,t){let n=e.createElement(`span`);n.style.color=t,n.style.display=`none`,e.body.append(n);let r=e.defaultView?.getComputedStyle(n).color??t;return n.remove(),r}var Ye=`a[href], button, label, summary, [role="button"], [role="link"], [role="slider"], [tabindex]:not([tabindex="-1"])`,Xe=e=>!e.closest(Ye),Ze=()=>{};function Qe(e){return{side:()=>`bottom`,snapPoints:()=>[`content`],snapPoint:()=>null,dismissible:()=>!0,modalAbove:()=>void 0,driver:()=>`auto`,expandOnScroll:()=>!0,physics:()=>void 0,backdrop:()=>void 0,hostBackdrop:!1,outlets:()=>[],parent:()=>void 0,themeColor:()=>!1,preventEdgeSwipe:()=>!1,canMouseDrag:Xe,onSnap:Ze,onRest:Ze,onDismissAttempt:Ze,onDragChange:Ze,onLayout:Ze,...$e(e)}}function $e(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}var et=new WeakSet,tt=new WeakMap;function nt(e){for(let t=e.parent;t;t=t.parent){let e=tt.get(t);if(e)return e}}function rt(e){for(let t=e instanceof Element?e:null;t;){if(et.has(t))return t;let e=t.getRootNode();t=t.parentElement??(e instanceof ShadowRoot?e.host:null)}return null}function it(e,t){let n=e.closest(`[popover]`);return!!n&&n!==t&&t.contains(n)}var at=24;function ot(e,t){let n=t.driver();return n===`auto`?t.modalAbove()===void 0&&t.expandOnScroll()&&!!e.matchMedia?.(`(hover: none) and (pointer: coarse)`).matches:n===`scroll-snap`}var st={duration:250,easing:`cubic-bezier(0.38, 0.7, 0.125, 1)`};function ct(e,n){let r=Qe(n),{host:a}=r,o=e.ownerDocument,c=o.defaultView??window,l=c.matchMedia?.(`(prefers-reduced-motion: reduce)`),u=ae(r.side(),e),d=[],f=0,p,m=Y.ios,h,g,_={snapPoints:[],dimension:0,dismissible:!0,expandOnScroll:!0,physics:m,contentScroll:te},v=u===`bottom`&&ot(c,r);et.add(e);let y=[lt(a,u,e),ut(e)],b=[],x=Ae({sheet:e,backdrop:r.backdrop,dimmed:r.hostBackdrop?a:void 0,outlets:r.outlets,ancestors:()=>b,themeColor:e=>h?.write(e)});function S(){let e=r.physics();return e!==p&&(p=e,m=e?{...Y.ios,...e}:Y.ios),_.physics=m,_.dismissible=r.dismissible(),_.expandOnScroll=r.expandOnScroll(),_}let C=!1;function ee(){C=!0;let t=ae(r.side(),e);t!==u&&(u=t,y[0](),y[0]=lt(a,u,e));let n=(Q(u)?a.clientHeight:a.clientWidth)-(v?120:0);M??=c.visualViewport?.height,f=ce(e,u);let i=parseFloat(c.getComputedStyle(o.documentElement).fontSize)||16,s=X(r.snapPoints(),{container:n,content:f,rootFontSize:i});s.length||s.push({id:`content`,value:`content`,extent:f,ids:[`content`]});let l=n!==_.dimension||s.length!==d.length||s.some((e,t)=>e.id!==d[t].id||Math.abs(e.extent-d[t].extent)>=.5);return d=s,_.dimension=n,_.snapPoints=d.map(({id:e,extent:t})=>({id:e,extent:t})),x.configure({snapExtents:_.snapPoints.map(e=>e.extent),undimmedIndex:Z(d,r.modalAbove())}),l&&O(),l}let w=!1,T=e=>e===null?null:d.find(t=>t.id===e)?.value??null,E={sheet:e,host:a,side:()=>u,config:S,size:()=>f,closedExtent:()=>ge(u),reducedMotion:()=>!!l?.matches,owns:t=>rt(t)===e,canMouseDrag:r.canMouseDrag,onSnap:(e,t,n)=>{let i=T(e);i!==null&&r.onSnap(i,t,n)},onRest(e){if(w)return;let t=d.find(t=>t.id===e);x.apply(t?.extent??ge(u),{rest:!0}),r.onRest(T(e)),R&&e!==null&&B(),R=!1},onDismiss:r.onDismiss,onDismissAttempt:r.onDismissAttempt,onDragChange:r.onDragChange,isInteractive:e=>U.isInteractiveAt(T(e)),onFrame:e=>w||x.apply(e),onMotion:e=>w||x.play(e),onMotionStart:e=>w||x.sync(e)},D=!0;function O(){if(!D)return r.onLayout({side:u,snapPoints:d});queueMicrotask(()=>w||r.onLayout({side:u,snapPoints:d}))}S();let k=v?We(E):Ve(E);e.setAttribute(`data-driver`,v?`scroll-snap`:`pointer`),D=!1;let A=new ResizeObserver(()=>{V(!1)});A.observe(e),A.observe(a);let j=0,M,N=null,P=[s(a,{before:()=>j=e.getBoundingClientRect().top,after:F}),...r.preventEdgeSwipe()?[t(o,`touchstart`,I,{capture:!0,passive:!1})]:[],...i()?[t(o,`touchend`,L,{capture:!0,passive:!1})]:[],t(e,`focusin`,z)];function F(){V(!0),B();let t=c.visualViewport?.height;if(t===M)return;M=t,N?.cancel(),N=null;let n=j-e.getBoundingClientRect().top;Math.abs(n)<1||l?.matches||(N=a.animate({translate:[`0 ${n}px`,`0 0`]},st))}function I(e){if(!e.cancelable)return;let t=e.touches[0];if(!t||t.clientX>at&&t.clientX<c.innerWidth-at)return;let n=e.target;n&&(a.contains(n)||r.backdrop()?.contains(n))&&e.preventDefault()}function L(t){let n=t.target;(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement)&&e.contains(n)&&n!==o.activeElement&&!k.isMoving()&&t.cancelable&&(t.preventDefault(),n.focus({preventScroll:!0}))}let R=!1;function z(){k.isMoving()?R=!0:B()}function B(){let t=o.activeElement;if(!(t instanceof HTMLElement)||!e.contains(t)||t===e||it(t,e))return;let n=ue(t,e,`bottom`);if(!n)return;let r=c.visualViewport,i=Math.min(n.getBoundingClientRect().bottom,r?r.offsetTop+r.height:c.innerHeight),{top:a,bottom:s}=t.getBoundingClientRect(),u=n.getBoundingClientRect().top,d=s+16>i?s+16-i:a-16<u?a-16-u:0;d&&n.scrollBy({top:d,behavior:l?.matches?`instant`:`smooth`})}function V(e){let t=!C;ee()&&!t&&k.relayout(e,d[Z(d,r.snapPoint())]?.id)}function H(e){let t=Z(d,e);return d[t>=0?t:0]?.id}let U={element:e,parent:r.parent,open(e){if(w)return;b=[];for(let e=r.parent();e;e=e.parent())b.push(e.element);ee(),S(),r.themeColor()&&(h??=qe(o,m.dim)),e&&x.apply(ge(u)),g?.();let t=r.backdrop();g=t&&ve(t,{"will-change":`opacity`}),k.open(H(r.snapPoint()),e)},close:()=>w||k.close(),snapTo(e,t){let n=Z(d,e);n>=0&&d[n].id!==k.target()&&k.snapTo(d[n].id,t)},nudge:()=>k.nudge(),snapPoints:()=>d,target:()=>T(k.target()),isInteractiveAt:e=>ie(d,e,r.modalAbove()),refresh(){V(!1)},destroy(){w=!0,A.disconnect(),N?.cancel(),P.forEach(e=>e()),k.destroy(),x.destroy(),g?.(),h?.restore(),y.forEach(e=>e()),e.removeAttribute(`data-driver`),et.delete(e)}};return U}function lt(e,t,n){let r=Q(t),i=r?t===`bottom`:t===`right`!=(n.ownerDocument.defaultView?.getComputedStyle(e).direction===`rtl`);return ve(e,{position:`fixed`,inset:`0 0 var(--keyboard-inset, 0px) 0`,width:`auto`,height:`auto`,"max-width":`none`,"max-height":`none`,margin:`0`,padding:`0`,border:`0`,background:`transparent`,color:`inherit`,overflow:`visible`,display:`flex`,"flex-direction":r?`column`:`row`,"justify-content":i?`flex-end`:`flex-start`,"pointer-events":`none`})}function ut(e){return ve(e,{"pointer-events":`auto`,"overscroll-behavior":`contain`,"will-change":`translate`})}function dt(t){let n=t.getAttribute(`data-slot`);n&&e(t.ownerDocument,`ui-sdk-sheet-${n}`,`@layer ui-sdk { :where([data-slot="${n}"])::backdrop { background: var(--sheet-backdrop, rgb(0 0 0 / 0.2)); pointer-events: auto } }`)}function ft(e,t){let r=[],i=e=>{for(let a of Array.from(e.children))t.includes(a)||(t.some(e=>e&&a.contains(e))?i(a):a instanceof HTMLElement&&r.push(n(a,`display`,`none`)))};return i(e),()=>r.forEach(e=>e())}function pt(e,t,r){let i,a=t.bind(e,{...r,position:void 0,inline:!0,onShow(){let[t,n]=r.drillIn();return t&&(i=ft(t,[e,n])),()=>i?.()},onClose(){i?.(),i=n(e,`display`,`none`)}});return()=>{a(),i?.()}}function mt(e,t,n){if(n.drillIn)return pt(e,t,n);let r=e.parentElement;if(!r)return;dt(r);let i;return t.bind(e,{...n,position:void 0,host:()=>r,onShow(a){let o=ht(e,r,t,n,a);return i=o.sheet,()=>{o.hide(),i=void 0}},onClose:()=>i?.close()})}function ht(e,n,r,i,a){let o=null,s=nt(a),c=!i.backdrop?.(),l=ct(e,{host:n,snapPoints:()=>i.snapPoints??[`content`],snapPoint:()=>o,backdrop:i.backdrop,hostBackdrop:c,dismissible:i.dismissible,onDismissAttempt:i.onDismissAttempt,parent:()=>s?.(),onSnap:e=>o=e,onDismiss(e){r.requestClose(`swipe`,e),requestAnimationFrame(()=>{let e=o??l.snapPoints()[0]?.value;a.active()&&e!==void 0&&l.snapTo(e,`imperative`)})}});tt.set(a,()=>l),i.onSheet?.(l);let u=t(e,`focusin`,e=>{let t=l.snapPoints().at(-1);t&&l.snapPoints().length>1&&e.target.matches(`input, textarea`)&&l.snapTo(t.value,`imperative`)}),d=c?getComputedStyle(e).getPropertyValue(`--sheet-backdrop`):`transparent`;return d&&n.style.setProperty(`--sheet-backdrop`,d),a.active()&&l.open(r.opener()!==`initial`),{sheet:l,hide(){u(),tt.delete(a),l.destroy(),i.onSheet?.(void 0),n.style.removeProperty(`--sheet-backdrop`)}}}export{De as prepareVariables,mt as presentSheet};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8" />
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
|
+
<title>Wheatley</title>
|
|
7
|
+
<script type="module" crossorigin src="/assets/index-RnxedkKh.js"></script>
|
|
8
|
+
<link rel="stylesheet" crossorigin href="/assets/index-3COz_MZq.css">
|
|
9
|
+
</head>
|
|
10
|
+
<body>
|
|
11
|
+
<div id="root"></div>
|
|
12
|
+
</body>
|
|
13
|
+
</html>
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { DatabaseSync } from "node:sqlite";
|
|
2
|
+
/** How long a statement waits for a lock held by another connection, for example a backup. */
|
|
3
|
+
const BUSY_TIMEOUT_MS = 5000;
|
|
4
|
+
/**
|
|
5
|
+
* Opens `agent.sqlite` (or `:memory:` in tests) with the settings every Wheatley module relies on: WAL journal,
|
|
6
|
+
* `synchronous = NORMAL`, foreign keys on, and a busy timeout.
|
|
7
|
+
*
|
|
8
|
+
* Only the daemon opens Agent databases (single writer). The caller closes the handle.
|
|
9
|
+
*/
|
|
10
|
+
export const openAgentDatabase = (path) => {
|
|
11
|
+
const db = new DatabaseSync(path, { timeout: BUSY_TIMEOUT_MS });
|
|
12
|
+
db.exec("PRAGMA journal_mode = WAL");
|
|
13
|
+
db.exec("PRAGMA synchronous = NORMAL");
|
|
14
|
+
db.exec("PRAGMA foreign_keys = ON");
|
|
15
|
+
return db;
|
|
16
|
+
};
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { constants } from "node:sqlite";
|
|
2
|
+
/** The error that `planMigrations` and `runMigrations` throw. */
|
|
3
|
+
export class MigrationError extends Error {
|
|
4
|
+
name = "MigrationError";
|
|
5
|
+
code;
|
|
6
|
+
namespace;
|
|
7
|
+
version;
|
|
8
|
+
constructor(code, message, location, cause) {
|
|
9
|
+
super(message, { cause });
|
|
10
|
+
this.code = code;
|
|
11
|
+
this.namespace = location?.namespace;
|
|
12
|
+
this.version = location?.version;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
const NAMESPACE = /^[a-z][a-z0-9_]{0,31}$/u;
|
|
16
|
+
const LEDGER = "wheatley_migrations";
|
|
17
|
+
const isLedgerRow = (row) => typeof row === "object" &&
|
|
18
|
+
row !== null &&
|
|
19
|
+
"namespace" in row &&
|
|
20
|
+
typeof row.namespace === "string" &&
|
|
21
|
+
"version" in row &&
|
|
22
|
+
typeof row.version === "number" &&
|
|
23
|
+
"name" in row &&
|
|
24
|
+
typeof row.name === "string";
|
|
25
|
+
const validateDefinitions = (namespaces) => {
|
|
26
|
+
const seen = new Set();
|
|
27
|
+
for (const { namespace, migrations } of namespaces) {
|
|
28
|
+
if (!NAMESPACE.test(namespace)) {
|
|
29
|
+
throw new MigrationError("invalid_definition", `Invalid migration namespace: ${namespace}`, { namespace });
|
|
30
|
+
}
|
|
31
|
+
if (seen.has(namespace)) {
|
|
32
|
+
throw new MigrationError("invalid_definition", `Duplicate migration namespace: ${namespace}`, { namespace });
|
|
33
|
+
}
|
|
34
|
+
seen.add(namespace);
|
|
35
|
+
for (const [index, migration] of migrations.entries()) {
|
|
36
|
+
if (migration.version !== index + 1) {
|
|
37
|
+
throw new MigrationError("invalid_definition", `Migration ${namespace} #${index + 1} has version ${migration.version}; versions must be 1, 2, 3, ...`, { namespace, version: migration.version });
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
const ledgerExists = (db) => db
|
|
43
|
+
.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = ?")
|
|
44
|
+
.get(LEDGER) !== undefined;
|
|
45
|
+
const readLedger = (db) => {
|
|
46
|
+
if (!ledgerExists(db)) {
|
|
47
|
+
return [];
|
|
48
|
+
}
|
|
49
|
+
return db
|
|
50
|
+
.prepare(`SELECT namespace, version, name FROM ${LEDGER} ORDER BY namespace, version`)
|
|
51
|
+
.all()
|
|
52
|
+
.flatMap((row) => (isLedgerRow(row) ? [row] : []));
|
|
53
|
+
};
|
|
54
|
+
const pendingFor = (namespace, applied) => {
|
|
55
|
+
const declared = namespace.migrations;
|
|
56
|
+
const appliedVersions = new Set();
|
|
57
|
+
for (const row of applied) {
|
|
58
|
+
const migration = declared[row.version - 1];
|
|
59
|
+
if (migration === undefined) {
|
|
60
|
+
throw new MigrationError("newer_schema", `Database has migration ${row.namespace} v${row.version}, which this Wheatley version does not know`, { namespace: row.namespace, version: row.version });
|
|
61
|
+
}
|
|
62
|
+
if (migration.name !== row.name) {
|
|
63
|
+
throw new MigrationError("history_mismatch", `Migration ${row.namespace} v${row.version} is stored as "${row.name}" but declared as "${migration.name}"`, { namespace: row.namespace, version: row.version });
|
|
64
|
+
}
|
|
65
|
+
appliedVersions.add(row.version);
|
|
66
|
+
}
|
|
67
|
+
return declared
|
|
68
|
+
.filter((migration) => !appliedVersions.has(migration.version))
|
|
69
|
+
.map(({ name, version }) => ({
|
|
70
|
+
name,
|
|
71
|
+
namespace: namespace.namespace,
|
|
72
|
+
version,
|
|
73
|
+
}));
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* Lists the migrations that `runMigrations` would apply, in order, without writing to the database.
|
|
77
|
+
*
|
|
78
|
+
* Use it to decide whether to back up the database before migration. Throws a `MigrationError`:
|
|
79
|
+
* - `invalid_definition` for broken definitions.
|
|
80
|
+
* - `newer_schema` if the database has a migration that no definition declares, for example in a namespace of a newer
|
|
81
|
+
* Wheatley version or past the last declared version.
|
|
82
|
+
* - `history_mismatch` if a stored migration name differs from its declaration.
|
|
83
|
+
*/
|
|
84
|
+
export const planMigrations = (db, namespaces) => {
|
|
85
|
+
validateDefinitions(namespaces);
|
|
86
|
+
const applied = readLedger(db);
|
|
87
|
+
const declaredNamespaces = new Set(namespaces.map(({ namespace }) => namespace));
|
|
88
|
+
const unknown = applied.find((row) => !declaredNamespaces.has(row.namespace));
|
|
89
|
+
if (unknown !== undefined) {
|
|
90
|
+
throw new MigrationError("newer_schema", `Database has migrations in namespace ${unknown.namespace}, which this Wheatley version does not know`, { namespace: unknown.namespace, version: unknown.version });
|
|
91
|
+
}
|
|
92
|
+
return namespaces.flatMap((namespace) => pendingFor(namespace, applied.filter((row) => row.namespace === namespace.namespace)));
|
|
93
|
+
};
|
|
94
|
+
const isApplied = (db, planned) => db
|
|
95
|
+
.prepare(`SELECT 1 FROM ${LEDGER} WHERE namespace = ? AND version = ?`)
|
|
96
|
+
.get(planned.namespace, planned.version) !== undefined;
|
|
97
|
+
const foreignKeysOn = (db) => db.prepare("PRAGMA foreign_keys").get()?.foreign_keys === 1;
|
|
98
|
+
/** Denies statements that end the runner's transaction, so a migration cannot commit half of its work. */
|
|
99
|
+
const denyTransactionControl = (actionCode) => actionCode === constants.SQLITE_TRANSACTION
|
|
100
|
+
? constants.SQLITE_DENY
|
|
101
|
+
: constants.SQLITE_OK;
|
|
102
|
+
const runInTransaction = (db, migration, planned, appliedAt) => {
|
|
103
|
+
db.exec("BEGIN IMMEDIATE");
|
|
104
|
+
try {
|
|
105
|
+
// Another connection can apply the migration between the plan and this lock.
|
|
106
|
+
if (isApplied(db, planned)) {
|
|
107
|
+
db.exec("ROLLBACK");
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
db.setAuthorizer(denyTransactionControl);
|
|
111
|
+
try {
|
|
112
|
+
migration.up(db);
|
|
113
|
+
}
|
|
114
|
+
finally {
|
|
115
|
+
db.setAuthorizer(null);
|
|
116
|
+
}
|
|
117
|
+
const violations = db.prepare("PRAGMA foreign_key_check").all();
|
|
118
|
+
if (violations.length > 0) {
|
|
119
|
+
throw new Error(`The migration left ${violations.length} foreign key violations`);
|
|
120
|
+
}
|
|
121
|
+
db.prepare(`INSERT INTO ${LEDGER} (namespace, version, name, applied_at) VALUES (?, ?, ?, ?)`).run(planned.namespace, planned.version, planned.name, appliedAt);
|
|
122
|
+
db.exec("COMMIT");
|
|
123
|
+
return true;
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
if (db.isTransaction) {
|
|
127
|
+
db.exec("ROLLBACK");
|
|
128
|
+
}
|
|
129
|
+
throw new MigrationError("migration_failed", `Migration ${planned.namespace} v${planned.version} (${planned.name}) failed`, { namespace: planned.namespace, version: planned.version }, error);
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
/**
|
|
133
|
+
* Applies one migration with foreign key enforcement off. SQLite ignores `PRAGMA foreign_keys` inside a transaction,
|
|
134
|
+
* so the runner switches it before `BEGIN` and restores it afterward. Resolves `false` if the migration was already
|
|
135
|
+
* applied.
|
|
136
|
+
*/
|
|
137
|
+
const applyOne = (db, migration, planned, appliedAt) => {
|
|
138
|
+
const restoreForeignKeys = foreignKeysOn(db);
|
|
139
|
+
db.exec("PRAGMA foreign_keys = OFF");
|
|
140
|
+
try {
|
|
141
|
+
return runInTransaction(db, migration, planned, appliedAt);
|
|
142
|
+
}
|
|
143
|
+
finally {
|
|
144
|
+
if (restoreForeignKeys) {
|
|
145
|
+
db.exec("PRAGMA foreign_keys = ON");
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
/**
|
|
150
|
+
* Applies every pending migration and returns the applied ones, in order.
|
|
151
|
+
*
|
|
152
|
+
* Order: namespaces in the given order, versions ascending within a namespace. Each migration runs in its own
|
|
153
|
+
* `BEGIN IMMEDIATE` transaction together with its ledger row in `wheatley_migrations`. Thus a failed migration leaves
|
|
154
|
+
* the database at the previous migration. Before it commits, the runner runs `PRAGMA foreign_key_check` and fails the
|
|
155
|
+
* migration on any violation. The runner skips a migration that another connection applied after the plan, and does
|
|
156
|
+
* not return it.
|
|
157
|
+
* A second call applies nothing. Throws the errors of `planMigrations`, and `migration_failed` with the original error
|
|
158
|
+
* as `cause` if a migration fails. Migrations before it stay applied.
|
|
159
|
+
*/
|
|
160
|
+
export const runMigrations = (db, namespaces, now = () => new Date()) => {
|
|
161
|
+
const pending = planMigrations(db, namespaces);
|
|
162
|
+
db.exec(`CREATE TABLE IF NOT EXISTS ${LEDGER} (
|
|
163
|
+
namespace TEXT NOT NULL,
|
|
164
|
+
version INTEGER NOT NULL,
|
|
165
|
+
name TEXT NOT NULL,
|
|
166
|
+
applied_at TEXT NOT NULL,
|
|
167
|
+
PRIMARY KEY (namespace, version)
|
|
168
|
+
) STRICT`);
|
|
169
|
+
const byNamespace = new Map(namespaces.map((namespace) => [namespace.namespace, namespace.migrations]));
|
|
170
|
+
const applied = [];
|
|
171
|
+
for (const planned of pending) {
|
|
172
|
+
const migration = byNamespace.get(planned.namespace)?.[planned.version - 1];
|
|
173
|
+
if (migration === undefined) {
|
|
174
|
+
throw new MigrationError("invalid_definition", `Migration ${planned.namespace} v${planned.version} vanished`, {
|
|
175
|
+
namespace: planned.namespace,
|
|
176
|
+
version: planned.version,
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
if (applyOne(db, migration, planned, now().toISOString())) {
|
|
180
|
+
applied.push(planned);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return applied;
|
|
184
|
+
};
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
/** Discord limits a component `custom_id` to this many characters. */
|
|
5
|
+
const MAX_CUSTOM_ID_LENGTH = 100;
|
|
6
|
+
const CUSTOM_ID_PREFIX = "wheatley-approval";
|
|
7
|
+
const HASHED_KEY_MARKER = "#";
|
|
8
|
+
const HASHED_KEY_LENGTH = 40;
|
|
9
|
+
const MS_PER_SECOND = 1000;
|
|
10
|
+
const STORE_FILE = "approval-prompts.json";
|
|
11
|
+
const STORE_VERSION = 1;
|
|
12
|
+
const DECISION_CODES = {
|
|
13
|
+
allow_always: "a",
|
|
14
|
+
allow_conversation: "c",
|
|
15
|
+
allow_once: "o",
|
|
16
|
+
deny: "d",
|
|
17
|
+
};
|
|
18
|
+
const BUTTON_ORDER = [
|
|
19
|
+
"allow_once",
|
|
20
|
+
"allow_conversation",
|
|
21
|
+
"allow_always",
|
|
22
|
+
"deny",
|
|
23
|
+
];
|
|
24
|
+
const BUTTON_LABELS = {
|
|
25
|
+
allow_always: "Always allow",
|
|
26
|
+
allow_conversation: "Allow in Conversation",
|
|
27
|
+
allow_once: "Allow once",
|
|
28
|
+
deny: "Deny",
|
|
29
|
+
};
|
|
30
|
+
const OUTCOME_TEXT = {
|
|
31
|
+
allow_always: "Always allowed",
|
|
32
|
+
allow_conversation: "Allowed for this Conversation",
|
|
33
|
+
allow_once: "Allowed once",
|
|
34
|
+
cancelled: "Cancelled",
|
|
35
|
+
deny: "Denied",
|
|
36
|
+
timeout: "Timed out",
|
|
37
|
+
};
|
|
38
|
+
/** A `custom_id` is `<prefix>:<decision code>:<key>`: two separators and a one-character decision code. */
|
|
39
|
+
const CUSTOM_ID_OVERHEAD = ":".length * 2 + 1;
|
|
40
|
+
const longestKey = MAX_CUSTOM_ID_LENGTH - CUSTOM_ID_PREFIX.length - CUSTOM_ID_OVERHEAD;
|
|
41
|
+
/** Returns the `custom_id` key for an Approval ID. IDs that do not fit in a `custom_id` become a hash. */
|
|
42
|
+
export const promptKey = (approvalId) => approvalId.length <= longestKey && !approvalId.startsWith(HASHED_KEY_MARKER)
|
|
43
|
+
? approvalId
|
|
44
|
+
: `${HASHED_KEY_MARKER}${createHash("sha256").update(approvalId).digest("base64url").slice(0, HASHED_KEY_LENGTH)}`;
|
|
45
|
+
const customId = (key, decision) => `${CUSTOM_ID_PREFIX}:${DECISION_CODES[decision]}:${key}`;
|
|
46
|
+
/** Parses the `custom_id` of an Approval button, or returns `undefined` for other components. */
|
|
47
|
+
export const parseApprovalCustomId = (value) => {
|
|
48
|
+
const [prefix, code, ...rest] = value.split(":");
|
|
49
|
+
const key = rest.join(":");
|
|
50
|
+
const decision = BUTTON_ORDER.find((candidate) => DECISION_CODES[candidate] === code);
|
|
51
|
+
if (prefix !== CUSTOM_ID_PREFIX || decision === undefined || key === "") {
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
return { decision, key };
|
|
55
|
+
};
|
|
56
|
+
const FENCE = /```/gu;
|
|
57
|
+
/** Builds the prompt text of an `approval_requested` delivery. */
|
|
58
|
+
export const promptContent = (delivery) => {
|
|
59
|
+
const preview = delivery.inputPreview.replaceAll(FENCE, "```");
|
|
60
|
+
const expiry = delivery.expiresAt === null
|
|
61
|
+
? "This request does not time out."
|
|
62
|
+
: `This request times out <t:${Math.floor(Date.parse(delivery.expiresAt) / MS_PER_SECOND)}:R>.`;
|
|
63
|
+
return [
|
|
64
|
+
`**Approval needed** for \`${delivery.toolName}\``,
|
|
65
|
+
`\`\`\`\n${preview}\n\`\`\``,
|
|
66
|
+
expiry,
|
|
67
|
+
].join("\n");
|
|
68
|
+
};
|
|
69
|
+
/** Appends the outcome of an Approval to its prompt text. */
|
|
70
|
+
export const resolvedContent = (content, outcome, resolvedBy, reason) => {
|
|
71
|
+
const by = resolvedBy === undefined ? "" : ` by ${resolvedBy}`;
|
|
72
|
+
const why = reason === undefined ? "" : `: ${reason}`;
|
|
73
|
+
return `${content}\n\n**${OUTCOME_TEXT[outcome]}**${by}${why}`;
|
|
74
|
+
};
|
|
75
|
+
/** Builds the action row with the four Approval buttons. */
|
|
76
|
+
export const approvalButtons = (discord, key, disabled) => {
|
|
77
|
+
const styles = {
|
|
78
|
+
allow_always: discord.ButtonStyle.Secondary,
|
|
79
|
+
allow_conversation: discord.ButtonStyle.Secondary,
|
|
80
|
+
allow_once: discord.ButtonStyle.Primary,
|
|
81
|
+
deny: discord.ButtonStyle.Danger,
|
|
82
|
+
};
|
|
83
|
+
return {
|
|
84
|
+
components: BUTTON_ORDER.map((decision) => ({
|
|
85
|
+
customId: customId(key, decision),
|
|
86
|
+
disabled,
|
|
87
|
+
label: BUTTON_LABELS[decision],
|
|
88
|
+
style: styles[decision],
|
|
89
|
+
type: discord.ComponentType.Button,
|
|
90
|
+
})),
|
|
91
|
+
type: discord.ComponentType.ActionRow,
|
|
92
|
+
};
|
|
93
|
+
};
|
|
94
|
+
const isPromptRecord = (value) => typeof value === "object" &&
|
|
95
|
+
value !== null &&
|
|
96
|
+
"approvalId" in value &&
|
|
97
|
+
typeof value.approvalId === "string" &&
|
|
98
|
+
"key" in value &&
|
|
99
|
+
typeof value.key === "string" &&
|
|
100
|
+
"channelId" in value &&
|
|
101
|
+
typeof value.channelId === "string" &&
|
|
102
|
+
"messageId" in value &&
|
|
103
|
+
typeof value.messageId === "string" &&
|
|
104
|
+
"content" in value &&
|
|
105
|
+
typeof value.content === "string";
|
|
106
|
+
const isStoreFile = (value) => typeof value === "object" &&
|
|
107
|
+
value !== null &&
|
|
108
|
+
"prompts" in value &&
|
|
109
|
+
Array.isArray(value.prompts);
|
|
110
|
+
const isMissingFile = (cause) => cause instanceof Error && "code" in cause && cause.code === "ENOENT";
|
|
111
|
+
const parseStore = (text) => {
|
|
112
|
+
const parsed = JSON.parse(text);
|
|
113
|
+
if (!isStoreFile(parsed)) {
|
|
114
|
+
throw new Error("The Approval prompt file has an unknown format");
|
|
115
|
+
}
|
|
116
|
+
return parsed.prompts.filter(isPromptRecord);
|
|
117
|
+
};
|
|
118
|
+
/**
|
|
119
|
+
* Keeps the platform message of each pending Approval prompt in the binding's `dataDir`, so that an
|
|
120
|
+
* `approval_resolved` delivery after a daemon restart can still disable the buttons.
|
|
121
|
+
*/
|
|
122
|
+
export class PromptStore {
|
|
123
|
+
#path;
|
|
124
|
+
#dataDir;
|
|
125
|
+
#records = new Map();
|
|
126
|
+
#writes = Promise.resolve();
|
|
127
|
+
constructor(dataDir) {
|
|
128
|
+
this.#dataDir = dataDir;
|
|
129
|
+
this.#path = path.join(dataDir, STORE_FILE);
|
|
130
|
+
}
|
|
131
|
+
/** Reads the file. A missing file means no pending prompts. Throws for an unreadable or malformed file. */
|
|
132
|
+
async load() {
|
|
133
|
+
let text;
|
|
134
|
+
try {
|
|
135
|
+
text = await readFile(this.#path, "utf-8");
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
if (isMissingFile(error)) {
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
throw error;
|
|
142
|
+
}
|
|
143
|
+
this.#records.clear();
|
|
144
|
+
for (const record of parseStore(text)) {
|
|
145
|
+
this.#records.set(record.approvalId, record);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
get(approvalId) {
|
|
149
|
+
return this.#records.get(approvalId);
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Resolves a button `custom_id` key to its Approval ID and stored record. An unhashed key is the Approval ID, so it
|
|
153
|
+
* resolves also without a record. A hashed key needs its record, so it returns `undefined` if the record is gone.
|
|
154
|
+
*/
|
|
155
|
+
lookup(key) {
|
|
156
|
+
for (const record of this.#records.values()) {
|
|
157
|
+
if (record.key === key) {
|
|
158
|
+
return { approvalId: record.approvalId, record };
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return key.startsWith(HASHED_KEY_MARKER)
|
|
162
|
+
? undefined
|
|
163
|
+
: { approvalId: key, record: undefined };
|
|
164
|
+
}
|
|
165
|
+
/** Stores a record and resolves once the file holds it. */
|
|
166
|
+
async put(record) {
|
|
167
|
+
this.#records.set(record.approvalId, record);
|
|
168
|
+
await this.#persist();
|
|
169
|
+
}
|
|
170
|
+
/** Removes a record and resolves once the file no longer holds it. */
|
|
171
|
+
async delete(approvalId) {
|
|
172
|
+
if (this.#records.delete(approvalId)) {
|
|
173
|
+
await this.#persist();
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
async #persist() {
|
|
177
|
+
const snapshot = JSON.stringify({
|
|
178
|
+
prompts: [...this.#records.values()],
|
|
179
|
+
version: STORE_VERSION,
|
|
180
|
+
});
|
|
181
|
+
const previous = this.#writes;
|
|
182
|
+
const write = async () => {
|
|
183
|
+
try {
|
|
184
|
+
await previous;
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
// The earlier write already rejected to its own caller. This write replaces the whole file anyway.
|
|
188
|
+
}
|
|
189
|
+
await mkdir(this.#dataDir, { recursive: true });
|
|
190
|
+
const temporary = `${this.#path}.tmp`;
|
|
191
|
+
await writeFile(temporary, snapshot);
|
|
192
|
+
await rename(temporary, this.#path);
|
|
193
|
+
};
|
|
194
|
+
// Writes run one at a time, so a slow earlier write cannot replace a newer snapshot.
|
|
195
|
+
const next = write();
|
|
196
|
+
this.#writes = next;
|
|
197
|
+
await next;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { DeliveryError } from "@wheatley-ai/sdk";
|
|
4
|
+
import { errorText } from "./errors.js";
|
|
5
|
+
/** Discord accepts at most this many files in one message. */
|
|
6
|
+
export const MAX_FILES_PER_MESSAGE = 10;
|
|
7
|
+
const MAX_STAGED_NAME_LENGTH = 100;
|
|
8
|
+
const UNSAFE_FILENAME_CHARACTERS = /[^\w.-]+/gu;
|
|
9
|
+
const DEFAULT_MIME_TYPE = "application/octet-stream";
|
|
10
|
+
const safeName = (name) => {
|
|
11
|
+
const cleaned = name
|
|
12
|
+
.replaceAll(UNSAFE_FILENAME_CHARACTERS, "_")
|
|
13
|
+
.slice(-MAX_STAGED_NAME_LENGTH);
|
|
14
|
+
return cleaned === "" ? "file" : cleaned;
|
|
15
|
+
};
|
|
16
|
+
const readCapped = async (response, maxBytes) => {
|
|
17
|
+
const chunks = [];
|
|
18
|
+
let total = 0;
|
|
19
|
+
if (response.body === null) {
|
|
20
|
+
return new Uint8Array();
|
|
21
|
+
}
|
|
22
|
+
for await (const chunk of response.body) {
|
|
23
|
+
total += chunk.byteLength;
|
|
24
|
+
if (total > maxBytes) {
|
|
25
|
+
await response.body.cancel();
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
chunks.push(chunk);
|
|
29
|
+
}
|
|
30
|
+
return Buffer.concat(chunks);
|
|
31
|
+
};
|
|
32
|
+
const skipped = (file, reason) => ({
|
|
33
|
+
kind: "skipped",
|
|
34
|
+
note: `[Attachment ${file.name} was not received: ${reason}]`,
|
|
35
|
+
});
|
|
36
|
+
const download = async (file, options) => {
|
|
37
|
+
const tooLarge = `it exceeds the ${options.maxBytes}-byte limit`;
|
|
38
|
+
if (file.size > options.maxBytes) {
|
|
39
|
+
return skipped(file, tooLarge);
|
|
40
|
+
}
|
|
41
|
+
const response = await options.fetch(file.url);
|
|
42
|
+
if (!response.ok) {
|
|
43
|
+
return skipped(file, `download failed with HTTP ${response.status}`);
|
|
44
|
+
}
|
|
45
|
+
const data = await readCapped(response, options.maxBytes);
|
|
46
|
+
if (data === undefined) {
|
|
47
|
+
return skipped(file, tooLarge);
|
|
48
|
+
}
|
|
49
|
+
const target = path.join(options.stagingDir, `${options.prefix}-${file.id}-${safeName(file.name)}`);
|
|
50
|
+
await writeFile(target, data);
|
|
51
|
+
return {
|
|
52
|
+
attachment: {
|
|
53
|
+
filename: file.name,
|
|
54
|
+
kind: "file",
|
|
55
|
+
mimeType: file.contentType ?? DEFAULT_MIME_TYPE,
|
|
56
|
+
path: target,
|
|
57
|
+
sizeBytes: data.byteLength,
|
|
58
|
+
},
|
|
59
|
+
kind: "staged",
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
const stageOne = async (file, options) => {
|
|
63
|
+
try {
|
|
64
|
+
return await download(file, options);
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
return skipped(file, `download failed: ${errorText(error)}`);
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* Downloads the files of one inbound message into the staging directory, one file at a time.
|
|
72
|
+
*
|
|
73
|
+
* Skips each file that is larger than `maxBytes`, by its declared size or by the bytes that arrive, and each file that
|
|
74
|
+
* fails to download. It reports skipped files in `notes` instead of throwing, so that the message text still reaches
|
|
75
|
+
* the Agent.
|
|
76
|
+
*/
|
|
77
|
+
export const stageInboundFiles = async (files, options) => {
|
|
78
|
+
const pending = [...files];
|
|
79
|
+
const attachments = [];
|
|
80
|
+
const notes = [];
|
|
81
|
+
if (pending.length === 0) {
|
|
82
|
+
return { attachments, notes };
|
|
83
|
+
}
|
|
84
|
+
await mkdir(options.stagingDir, { recursive: true });
|
|
85
|
+
for (const file of pending) {
|
|
86
|
+
// oxlint-disable-next-line no-await-in-loop -- One download at a time keeps at most one file in memory.
|
|
87
|
+
const result = await stageOne(file, options);
|
|
88
|
+
if (result.kind === "staged") {
|
|
89
|
+
attachments.push(result.attachment);
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
notes.push(result.note);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return { attachments, notes };
|
|
96
|
+
};
|
|
97
|
+
const sizeOf = (attachment) => attachment.kind === "bytes"
|
|
98
|
+
? attachment.data.byteLength
|
|
99
|
+
: attachment.sizeBytes;
|
|
100
|
+
/**
|
|
101
|
+
* Converts outbound attachments into Discord upload payloads.
|
|
102
|
+
*
|
|
103
|
+
* Throws a `permanent` `DeliveryError` if a file is larger than `maxBytes`, because a retry cannot make it fit.
|
|
104
|
+
*/
|
|
105
|
+
export const toUploadPayloads = (attachments, maxBytes) => attachments.map((attachment) => {
|
|
106
|
+
if (sizeOf(attachment) > maxBytes) {
|
|
107
|
+
throw new DeliveryError(`Attachment ${attachment.filename} exceeds the ${maxBytes}-byte limit`, { kind: "permanent" });
|
|
108
|
+
}
|
|
109
|
+
return {
|
|
110
|
+
attachment: attachment.kind === "bytes"
|
|
111
|
+
? Buffer.from(attachment.data)
|
|
112
|
+
: attachment.path,
|
|
113
|
+
name: attachment.filename,
|
|
114
|
+
};
|
|
115
|
+
});
|