From e7b2c871abb6303b94872e9e1a66dd8f8c4d9d76 Mon Sep 17 00:00:00 2001 From: Anthony Ettinger Date: Mon, 30 Nov 2026 14:40:41 +0000 Subject: [PATCH 1/4] cloud: hosted sk33p API + remote MCP with free tier and Pro via CoinPay sk33p.pwa.pit.world. Bun + Hono in front of the release binary: every call runs a fresh 'sk33p mcp' under prlimit in a scratch dir. - /api/v1/{eval,read,write,sheets,convert} (JSON base64 files, or raw upload for convert), /api/v1/{keys,me,upgrade}, remote MCP at /mcp. - Plans per UTC day: no key 10 calls, free key 100 (2 MB), Pro 10,000 (25 MB) at $9 per 30 days; over the limit is a 402 with the next step. - Pro = CoinPay hosted checkout (any coin or PayPal); signed webhook at /hooks/coinpay settles once and extends Pro. - Pages: home with live formula demo + pricing, /docs (+ /docs.md), /key, /upgrade, llms.txt, webring descriptor, webmcp embed, footers. - Docker: ubuntu 24.04 (release glibc), non-root, read-only, HEALTHCHECK. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 4 + cloud/.dockerignore | 5 + cloud/Dockerfile | 25 +++ cloud/bun.lock | 209 +++++++++++++++++++ cloud/compose.yml | 22 ++ cloud/package.json | 15 ++ cloud/src/app.ts | 445 +++++++++++++++++++++++++++++++++++++++++ cloud/src/engine.ts | 100 +++++++++ cloud/src/main.ts | 24 +++ cloud/src/page.ts | 303 ++++++++++++++++++++++++++++ cloud/src/store.ts | 101 ++++++++++ cloud/test/app.test.ts | 167 ++++++++++++++++ 12 files changed, 1420 insertions(+) create mode 100644 cloud/.dockerignore create mode 100644 cloud/Dockerfile create mode 100644 cloud/bun.lock create mode 100644 cloud/compose.yml create mode 100644 cloud/package.json create mode 100644 cloud/src/app.ts create mode 100644 cloud/src/engine.ts create mode 100644 cloud/src/main.ts create mode 100644 cloud/src/page.ts create mode 100644 cloud/src/store.ts create mode 100644 cloud/test/app.test.ts diff --git a/.gitignore b/.gitignore index 2f7896d..6b829d9 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,5 @@ target/ +cloud/node_modules/ +cloud/app.env +cloud/*.db +cloud/*.db-* diff --git a/cloud/.dockerignore b/cloud/.dockerignore new file mode 100644 index 0000000..4b84477 --- /dev/null +++ b/cloud/.dockerignore @@ -0,0 +1,5 @@ +node_modules +test +app.env +*.db +*.db-* diff --git a/cloud/Dockerfile b/cloud/Dockerfile new file mode 100644 index 0000000..96577e3 --- /dev/null +++ b/cloud/Dockerfile @@ -0,0 +1,25 @@ +# sk33p cloud: Bun + Hono in front of the sk33p release binary. +# ubuntu:24.04 because the release binary is built on ubuntu-latest (glibc 2.39). +FROM oven/bun:1.4.4 AS bun + +FROM ubuntu:24.04 +ARG SK33P_VERSION=latest +RUN apt-get update \ + && apt-get install -y --no-install-recommends ca-certificates curl util-linux zlib1g libstdc++6 \ + && rm -rf /var/lib/apt/lists/* +COPY --from=bun /usr/local/bin/bun /usr/local/bin/bun +RUN set -eu; \ + if [ "$SK33P_VERSION" = latest ]; then url=https://github.com/profullstack/sk33p/releases/latest/download/sk33p-linux-x86_64.tar.gz; \ + else url=https://github.com/profullstack/sk33p/releases/download/$SK33P_VERSION/sk33p-linux-x86_64.tar.gz; fi; \ + curl -fsSL "$url" | tar -xz -C /usr/local/bin sk33p && chmod 755 /usr/local/bin/sk33p && /usr/local/bin/sk33p --version +WORKDIR /app +COPY package.json bun.lock ./ +RUN bun install --frozen-lockfile --production +COPY src ./src +# Checkouts can carry owner-only modes; the app runs as a non-root user. +RUN chmod -R a+rX /app && useradd --system --uid 10033 --home /data sk33p && mkdir -p /data && chown sk33p /data +USER sk33p +ENV PORT=8811 HOST=0.0.0.0 DATA_DIR=/data SK33P_BIN=/usr/local/bin/sk33p NODE_ENV=production +EXPOSE 8811 +HEALTHCHECK --interval=30s --timeout=5s --retries=3 CMD curl -fsS http://127.0.0.1:8811/healthz || exit 1 +CMD ["bun", "src/main.ts"] diff --git a/cloud/bun.lock b/cloud/bun.lock new file mode 100644 index 0000000..dbc6ff3 --- /dev/null +++ b/cloud/bun.lock @@ -0,0 +1,209 @@ +{ + "lockfileVersion": 2, + "configVersion": 1, + "workspaces": { + "": { + "name": "sk33p-cloud", + "dependencies": { + "@profullstack/coinpay-onboard": "^0.5.1", + "@profullstack/footer": "^0.7.2", + "hono": "^4.13.23", + }, + }, + }, + "packages": { + "@hono/node-server": ["@hono/node-server@2.1.11", "", { "peerDependencies": { "hono": "^4 || ^5.0.0-0" } }, "sha512-KzKz9vl4vvr1vgLHamj+g5uonbrj5NwAdO3yzOS6cd2HjALVeOgTgeZOyAzNxejbkfOOPIcvuf/Tg8l1pEFLog=="], + + "@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.32.2", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-SWsVtH/0vULSQStoZ6xxH2K09Li8fXYTMC64ZeogCdpZ3XSi1eCPOByV1OpuJxuI3OcmHhosDWYyii07tpPsLw=="], + + "@profullstack/coinpay-onboard": ["@profullstack/coinpay-onboard@0.5.1", "", { "dependencies": { "@modelcontextprotocol/sdk": "^1.32.2", "zod": "^4.6.7" }, "bin": { "coinpay-onboard": "bin/coinpay-onboard" } }, "sha512-vuM/1vYvkXP2E/tBcTBZ8JY4K49qtSPPY1N9XRQvIlcy0Sezr+spOf6vYBkRPhasKcFqda44MRLgxPseG9Kvdg=="], + + "@profullstack/footer": ["@profullstack/footer@0.7.2", "", { "peerDependencies": { "react": ">=18" }, "optionalPeers": ["react"], "bin": { "profullstack-footer": "bin/profullstack-footer.js" } }, "sha512-2Va4LEsVM7PJEGkiNaSn//Zbp3u/EP1jhJff0Q8WfhKZJieUxqXPZZGv0R3qQjy4qiFMNYQATuNXM4ZXNXsVpA=="], + + "accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="], + + "ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], + + "ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="], + + "body-parser": ["body-parser@2.4.0", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^2.1.0", "debug": "^4.4.3", "http-errors": "^2.0.1", "iconv-lite": "^0.7.3", "on-finished": "^2.4.1", "qs": "^6.16.1", "raw-body": "^3.0.2", "type-is": "^2.1.0" } }, "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ=="], + + "bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="], + + "call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="], + + "call-bound": ["call-bound@1.0.4", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="], + + "content-disposition": ["content-disposition@2.0.1", "", {}, "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog=="], + + "content-type": ["content-type@1.0.5", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="], + + "cookie": ["cookie@0.7.2", "", {}, "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w=="], + + "cookie-signature": ["cookie-signature@1.2.2", "", {}, "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg=="], + + "cors": ["cors@2.8.6", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="], + + "cross-spawn": ["cross-spawn@7.1.2", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-8BPK2r+sKWC8sDinRwLwrFMq2lXTBBwzYYEB9LiCznfMurOi4FOvQflq3XOLGG+HPdMSVpe+k/s96+AtDEOgPg=="], + + "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], + + "depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="], + + "dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="], + + "ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="], + + "encodeurl": ["encodeurl@2.0.3", "", {}, "sha512-mIteYONiEfc4xWf2F1WXovh1c8npzS00vNeiUPdwFF+QlVJni+gNvpQltLMQhob8rew/bWWc/bGTuUr0EUGt0w=="], + + "es-define-property": ["es-define-property@1.0.1", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="], + + "es-errors": ["es-errors@1.3.0", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="], + + "es-object-atoms": ["es-object-atoms@1.1.2", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw=="], + + "escape-html": ["escape-html@1.0.3", "", {}, "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="], + + "etag": ["etag@1.8.1", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="], + + "eventsource": ["eventsource@3.0.7", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="], + + "eventsource-parser": ["eventsource-parser@3.1.1", "", {}, "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ=="], + + "express": ["express@5.3.0", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.3.0", "content-disposition": "^2.0.1", "content-type": "^2.0.0", "cookie": "^0.7.1", "cookie-signature": "^1.2.1", "debug": "^4.4.0", "depd": "^2.0.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "finalhandler": "^2.1.0", "fresh": "^2.0.0", "http-errors": "^2.0.0", "merge-descriptors": "^2.0.0", "mime-types": "^3.0.0", "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", "proxy-addr": "^2.0.8", "qs": "^6.16.0", "range-parser": "^1.2.1", "router": "^2.2.0", "send": "^1.1.0", "serve-static": "^2.2.0", "statuses": "^2.0.1", "type-is": "^2.1.0", "vary": "^1.1.2" } }, "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g=="], + + "express-rate-limit": ["express-rate-limit@8.7.5", "", { "dependencies": { "debug": "^4.4.3", "ip-address": "^10.2.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-wi+v38cx2EqD0JnhE/e74o5tFqKWUOAPFJIgyEiqJ8v2MNpoOAA3kI2hXYOI+YM+HE5yqbdAlVxm2GqOIeYOgA=="], + + "fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="], + + "fast-uri": ["fast-uri@3.1.9", "", {}, "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ=="], + + "finalhandler": ["finalhandler@2.1.1", "", { "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "on-finished": "^2.4.1", "parseurl": "^1.3.3", "statuses": "^2.0.1" } }, "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA=="], + + "forwarded": ["forwarded@0.2.0", "", {}, "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow=="], + + "fresh": ["fresh@2.0.0", "", {}, "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A=="], + + "function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="], + + "get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="], + + "get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="], + + "gopd": ["gopd@1.2.0", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="], + + "has-symbols": ["has-symbols@1.1.0", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="], + + "hasown": ["hasown@2.0.4", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="], + + "hono": ["hono@4.13.23", "", {}, "sha512-OS90dj7dcsftEEWCOef8jRbnHE5lbrOq0hNRqjSyPsOnaGZvvfof1KS05hQNb4kUOCfDq1mG3PmHoX37DMnHQg=="], + + "http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="], + + "iconv-lite": ["iconv-lite@0.7.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ=="], + + "inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="], + + "ip-address": ["ip-address@10.7.7", "", {}, "sha512-He15rAs4jip5AEAz7XM9L+S6Y8LBMIDj6YewbYuJfmDnOCKWb+3TLOGnHFBTAIW7wpm5ohtZ+Xyo5PEaG+O2vQ=="], + + "ipaddr.js": ["ipaddr.js@1.9.1", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="], + + "is-promise": ["is-promise@4.0.0", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="], + + "isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], + + "jose": ["jose@6.2.18", "", {}, "sha512-doV4thUwgkrycJH4yLeqwTGIIZphHl+pk7CPReuMIhYhncmgzdko85MaCG4YQFTxqMFr1/oEH32tZuKKovcDEg=="], + + "json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="], + + "json-schema-typed": ["json-schema-typed@8.0.2", "", {}, "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA=="], + + "math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="], + + "media-typer": ["media-typer@1.1.1", "", {}, "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ=="], + + "merge-descriptors": ["merge-descriptors@2.0.0", "", {}, "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g=="], + + "mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="], + + "mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="], + + "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + + "negotiator": ["negotiator@1.1.0", "", { "dependencies": { "content-type": "^2.1.0" } }, "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg=="], + + "object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="], + + "object-inspect": ["object-inspect@1.14.0", "", {}, "sha512-IVgHNlp/jwQX271+Xzoq9LZNTWXxZK+cEOrGBOBxXNbn7fapnZ+Ts6TVMgNOuAezwG2wdtnMX97tTPK6VEnuOQ=="], + + "on-finished": ["on-finished@2.4.2", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ=="], + + "once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="], + + "parseurl": ["parseurl@1.3.3", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="], + + "path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="], + + "path-to-regexp": ["path-to-regexp@8.4.2", "", {}, "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA=="], + + "pkce-challenge": ["pkce-challenge@5.0.2", "", {}, "sha512-vCc54+qyIfKC5e2UN28AZKElwqjLINgiIV3RKI8pDu93TjaAJoB3QrgMzEBouy8yOKsXVXdAinO1QArJf9x5WA=="], + + "proxy-addr": ["proxy-addr@2.0.8", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ=="], + + "qs": ["qs@6.17.1", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA=="], + + "range-parser": ["range-parser@1.3.0", "", {}, "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw=="], + + "raw-body": ["raw-body@3.0.2", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" } }, "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA=="], + + "require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="], + + "router": ["router@2.3.0", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-bpowRfGjEPe8t9R6fJIzhwmyCGAXwKvxBUsgJm+bJukwdcWmUXbMo7p22w7aYmQBPQTUMNqMV39YX0kMou3z8w=="], + + "safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="], + + "send": ["send@1.2.1", "", { "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.1", "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.2" } }, "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ=="], + + "serve-static": ["serve-static@2.2.1", "", { "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "parseurl": "^1.3.3", "send": "^1.2.0" } }, "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw=="], + + "setprototypeof": ["setprototypeof@1.2.0", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="], + + "shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="], + + "shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="], + + "side-channel": ["side-channel@1.1.1", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4", "side-channel-list": "^1.0.1", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" } }, "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ=="], + + "side-channel-list": ["side-channel-list@1.0.1", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4" } }, "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w=="], + + "side-channel-map": ["side-channel-map@1.0.1", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3" } }, "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA=="], + + "side-channel-weakmap": ["side-channel-weakmap@1.0.2", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3", "side-channel-map": "^1.0.1" } }, "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A=="], + + "statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="], + + "toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="], + + "type-is": ["type-is@2.1.0", "", { "dependencies": { "content-type": "^2.0.0", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA=="], + + "unpipe": ["unpipe@1.0.0", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="], + + "vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="], + + "which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], + + "wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="], + + "zod": ["zod@4.6.7", "", {}, "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="], + + "zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="], + + "body-parser/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + + "express/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + + "negotiator/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + + "type-is/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + } +} diff --git a/cloud/compose.yml b/cloud/compose.yml new file mode 100644 index 0000000..a3114c1 --- /dev/null +++ b/cloud/compose.yml @@ -0,0 +1,22 @@ +# docker compose -f cloud/compose.yml --env-file cloud/app.env up -d --build +services: + web: + build: . + image: sk33p-cloud:latest + restart: unless-stopped + env_file: app.env + environment: + ORIGIN: https://sk33p.pwa.pit.world + ports: + - "127.0.0.1:8811:8811" + volumes: + - data:/data + read_only: true + tmpfs: + - /tmp:size=512m + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + mem_limit: 3g + pids_limit: 256 +volumes: + data: diff --git a/cloud/package.json b/cloud/package.json new file mode 100644 index 0000000..0e44050 --- /dev/null +++ b/cloud/package.json @@ -0,0 +1,15 @@ +{ + "name": "sk33p-cloud", + "private": true, + "type": "module", + "description": "sk33p.pwa.pit.world: hosted sk33p API and remote MCP (free tier + Pro via CoinPay)", + "scripts": { + "start": "bun src/main.ts", + "test": "bun test" + }, + "dependencies": { + "@profullstack/coinpay-onboard": "^0.5.1", + "@profullstack/footer": "^0.7.2", + "hono": "^4.13.23" + } +} diff --git a/cloud/src/app.ts b/cloud/src/app.ts new file mode 100644 index 0000000..598fbcb --- /dev/null +++ b/cloud/src/app.ts @@ -0,0 +1,445 @@ +/** + * sk33p cloud: the sk33p engine as an HTTP API and a remote MCP server. + * + * Plans (per day, UTC): + * anon no key, by IP — try it on the homepage + * free free key by email + * pro paid via CoinPay, N days per payment + * Going over answers 402 with the upgrade offer, never a bare 429. + */ +import { Hono, type Context } from 'hono' +import { randomBytes } from 'node:crypto' +import { CoinPay, CoinPayError, readWebhook, verifyWebhook } from '@profullstack/coinpay-onboard' +import { descriptorResponse } from '@profullstack/footer' +import { runTool, safeName, withExt, ToolError, FORMATS, type FileIn } from './engine.ts' +import { Store, type Key, type Plan } from './store.ts' +import { docsMarkdown, docsPage, homePage, keyPage, llmsTxt, messagePage, upgradePage } from './page.ts' + +export type Limits = { calls: number; maxBytes: number } +export type Config = { + origin: string + bin: string + limits: Record + proUsd: number + proDays: number + /** Process limits via prlimit (off only in tests on hosts without it). */ + sandbox: boolean + coinpay: { baseUrl: string; apiKey: string; businessId: string; webhookSecret: string; fetch?: typeof fetch } | null + /** Key mints per IP per day. */ + mintsPerIp: number +} + +export const DEFAULT_LIMITS: Record = { + anon: { calls: 10, maxBytes: 512 * 1024 }, + free: { calls: 100, maxBytes: 2 * 1024 * 1024 }, + pro: { calls: 10_000, maxBytes: 25 * 1024 * 1024 }, +} + +type Caller = { plan: Plan; key: Key | null; subject: string; limits: Limits } +type Env = { Variables: { ip: string } } + +const EMAIL = /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]{2,}$/ + +export function validEmail(v: unknown): string | null { + const s = typeof v === 'string' ? v.trim().toLowerCase() : '' + return s.length <= 200 && EMAIL.test(s) ? s : null +} + +/** The tools, shared by the API and MCP. Each returns JSON plus maybe a file. */ +export const TOOLS = [ + { + name: 'eval', + description: 'Evaluate spreadsheet formulas with SkeeptoEngine (344 Excel-compatible functions: XLOOKUP, LET, FILTER, PMT, IRR, TEXTJOIN...). One result per formula. No ^ operator: use POWER().', + inputSchema: { type: 'object', properties: { formulas: { type: 'array', items: { type: 'string' }, description: 'e.g. ["=PMT(5%/12,360,-300000)", "=SUM(1,2,3)"]' } }, required: ['formulas'] }, + }, + { + name: 'read_range', + description: 'Read computed values (and optionally formulas) from a workbook you send (.xlsx, .sker, .csv, .tsv).', + inputSchema: { + type: 'object', + properties: { file: { $ref: '#/$defs/file' }, range: { type: 'string', description: 'A1 or A1:D20; omit for the used range' }, sheet: { type: 'string' }, formulas: { type: 'boolean' } }, + required: ['file'], + $defs: { file: fileSchema() }, + }, + }, + { + name: 'write_cells', + description: 'Set cells (values or =formulas) in a workbook you send, or in a new one, and get the recomputed values and the saved file back (base64).', + inputSchema: { + type: 'object', + properties: { + file: { $ref: '#/$defs/file' }, + name: { type: 'string', description: 'name for a new workbook, e.g. budget.xlsx (when no file is sent)' }, + cells: { type: 'object', additionalProperties: { type: 'string' }, description: '{"A1": "10", "B1": "=A1*2"}' }, + sheet: { type: 'string' }, + format: { type: 'string', enum: [...FORMATS], description: 'save as this format' }, + }, + required: ['cells'], + $defs: { file: fileSchema() }, + }, + }, + { + name: 'list_sheets', + description: 'List the sheets in a workbook you send, with their used size.', + inputSchema: { type: 'object', properties: { file: { $ref: '#/$defs/file' } }, required: ['file'], $defs: { file: fileSchema() } }, + }, + { + name: 'convert', + description: 'Convert a workbook between .xlsx, .sker, .csv and .tsv; the converted file comes back base64.', + inputSchema: { + type: 'object', + properties: { file: { $ref: '#/$defs/file' }, to: { type: 'string', enum: [...FORMATS] }, sheet: { type: 'string' } }, + required: ['file', 'to'], + $defs: { file: fileSchema() }, + }, + }, +] as const + +function fileSchema() { + return { type: 'object', properties: { name: { type: 'string', description: 'e.g. budget.xlsx' }, data: { type: 'string', description: 'file contents, base64' } }, required: ['name', 'data'] } +} + +const ACCOUNT_TOOLS = [ + { name: 'usage', description: 'Your plan, calls used today and limits.', inputSchema: { type: 'object', properties: {} } }, + { name: 'upgrade', description: 'Start a CoinPay checkout for Pro (any coin or PayPal). Returns a checkout_url for the human to open. Needs an API key.', inputSchema: { type: 'object', properties: {} } }, +] + +function fileArg(v: unknown, label = 'file'): FileIn { + const f = v as { name?: unknown; data?: unknown } | undefined + if (!f || typeof f !== 'object' || typeof f.data !== 'string') throw new ToolError(`${label} must be {"name": "x.xlsx", "data": ""}`) + return { name: safeName(f.name), data: f.data } +} + +/** Run one engine tool with cloud-shaped arguments. */ +export async function callTool(name: string, a: Record, cfg: Config, limits: Limits): Promise> { + const run = { bin: cfg.bin, maxBytes: limits.maxBytes, limits: cfg.sandbox } + const sheet = typeof a.sheet === 'string' && a.sheet ? { sheet: a.sheet.slice(0, 100) } : {} + switch (name) { + case 'eval': { + const fs = Array.isArray(a.formulas) ? a.formulas : typeof a.formula === 'string' ? [a.formula] : null + if (!fs?.length) throw new ToolError('send formulas: ["=SUM(1,2,3)"]') + if (fs.length > 200) throw new ToolError('at most 200 formulas per call') + if (fs.some((f: unknown) => typeof f !== 'string' || f.length > 4000)) throw new ToolError('each formula must be a string under 4000 characters') + const r = await runTool('eval', { formulas: fs }, [], null, run) + return { results: r.result } + } + case 'read_range': { + const f = fileArg(a.file) + const r = await runTool('read_range', { path: f.name, ...(typeof a.range === 'string' ? { range: a.range } : {}), ...sheet, formulas: Boolean(a.formulas) }, [f], null, run) + return { result: r.result } + } + case 'list_sheets': { + const f = fileArg(a.file) + const r = await runTool('list_sheets', { path: f.name }, [f], null, run) + return { sheets: r.result } + } + case 'write_cells': { + if (!a.cells || typeof a.cells !== 'object' || Array.isArray(a.cells)) throw new ToolError('send cells: {"A1": "10", "B1": "=A1*2"}') + const entries = Object.entries(a.cells) + if (!entries.length || entries.length > 5000) throw new ToolError('send between 1 and 5000 cells') + const cells = Object.fromEntries(entries.map(([k, v]) => [k, String(v)])) + const files = a.file ? [fileArg(a.file)] : [] + const name = files[0]?.name ?? safeName(a.name) + const out = typeof a.format === 'string' ? withExt(name, a.format) : name + const r = await runTool('write_cells', { path: name, cells, ...sheet, ...(out !== name ? { out } : {}) }, files, out, run) + return { result: r.result, file: r.file } + } + case 'convert': { + const f = fileArg(a.file) + const to = String(a.to ?? '').toLowerCase().replace(/^\./, '') + let out = withExt(f.name, to) + if (out === f.name) out = out.replace(/(\.[^.]+)$/, '-converted$1') + const r = await runTool('convert', { input: f.name, output: out, ...sheet }, [f], out, run) + if (!r.file) throw new ToolError('the engine wrote no file', 422) + return { file: r.file } + } + } + throw new ToolError(`unknown tool ${name}`, 404) +} + +export function createApp(store: Store, cfg: Config) { + const app = new Hono() + + const keyFrom = (c: Context): string | null => { + const auth = c.req.header('authorization') ?? '' + const m = /^Bearer\s+(\S+)$/i.exec(auth) + return m?.[1] ?? c.req.header('x-api-key') ?? c.req.query('key') ?? null + } + + /** Who is calling: a key's plan, or anonymous by IP. A bad key is an error, not anonymous. */ + const caller = (c: Context): Caller => { + const secret = keyFrom(c) + if (secret) { + const key = store.keyBySecret(secret) + if (!key) throw new ToolError('unknown API key', 401) + const plan: Plan = key.proUntil > Date.now() ? 'pro' : 'free' + return { plan, key, subject: `k:${key.id}`, limits: cfg.limits[plan] } + } + return { plan: 'anon', key: null, subject: `ip:${c.get('ip')}`, limits: cfg.limits.anon } + } + + const offer = (who: Caller) => ({ + plan: who.plan, + limit: who.limits.calls, + used: store.used(who.subject), + resets: 'midnight UTC', + next: + who.plan === 'anon' + ? { step: 'Get a free key (100 calls/day)', web: `${cfg.origin}/key`, api: `POST ${cfg.origin}/api/v1/keys {"email": "you@example.com"}` } + : { step: `Pro: ${cfg.limits.pro.calls} calls/day for $${cfg.proUsd} per ${cfg.proDays} days`, web: `${cfg.origin}/upgrade`, api: `POST ${cfg.origin}/api/v1/upgrade (with your key)`, price_usd: cfg.proUsd, days: cfg.proDays }, + }) + + const usage = (who: Caller) => ({ + plan: who.plan, + email: who.key?.email ?? null, + pro_until: who.key && who.key.proUntil > Date.now() ? new Date(who.key.proUntil).toISOString() : null, + calls_today: store.used(who.subject), + calls_per_day: who.limits.calls, + max_file_bytes: who.limits.maxBytes, + }) + + const fail = (c: Context, e: unknown) => { + if (e instanceof ToolError) return c.json({ error: e.message }, e.status as 400) + console.error(e) + return c.json({ error: 'something went wrong' }, 500) + } + + // Client address: the dev2 edge (Caddy) sets X-Forwarded-For; the first hop is the client. + app.use('*', async (c, next) => { + const xff = (c.req.header('x-forwarded-for') ?? '').split(',')[0]?.trim() + c.set('ip', xff || c.req.header('x-real-ip') || 'local') + await next() + }) + + app.get('/healthz', (c) => c.json({ ok: true })) + + // ---- pages + app.get('/', (c) => c.html(homePage(cfg))) + app.get('/docs', (c) => c.html(docsPage(cfg))) + app.get('/docs.md', (c) => c.text(docsMarkdown(cfg), 200, { 'content-type': 'text/markdown; charset=utf-8' })) + app.get('/llms.txt', (c) => c.text(llmsTxt(cfg))) + app.get('/pricing', (c) => c.redirect('/#pricing')) + app.get('/key', (c) => c.html(keyPage(cfg, {}))) + app.post('/key', async (c) => { + const form = await c.req.parseBody() + const r = mint(c, form.email) + if ('error' in r) return c.html(keyPage(cfg, { error: r.error, email: String(form.email ?? '') }), 400) + return c.html(keyPage(cfg, { key: r.key })) + }) + app.get('/upgrade', (c) => c.html(upgradePage(cfg, { paid: c.req.query('paid') === '1' }))) + app.post('/upgrade', async (c) => { + const form = await c.req.parseBody() + const key = store.keyBySecret(String(form.key ?? '').trim()) + if (!key) return c.html(upgradePage(cfg, { error: 'That key is not one of ours. Get a free key first, then upgrade it.' }), 400) + try { + const s = await checkout(key) + return c.redirect(s.checkout_url, 303) + } catch (e) { + return c.html(upgradePage(cfg, { error: e instanceof ToolError ? e.message : 'CoinPay did not answer; try again in a minute.' }), 502) + } + }) + app.get('/robots.txt', (c) => c.text(`User-agent: *\nAllow: /\nSitemap: ${cfg.origin}/sitemap.xml\n`)) + app.get('/sitemap.xml', (c) => + c.body(`\n${['/', '/docs', '/key', '/upgrade'].map((p) => `${cfg.origin}${p}`).join('')}`, 200, { 'content-type': 'application/xml' }), + ) + app.get('/.well-known/openwebring.json', () => descriptorResponse({ site: `${cfg.origin}/`, name: 'sk33p' })) + + // ---- keys + billing + const mint = (c: Context, emailIn: unknown): { key: string } | { error: string } => { + const email = validEmail(emailIn) + if (!email) return { error: 'Enter a real email: it is where CoinPay sends receipts if you upgrade.' } + if (!store.take(`mint:${c.get('ip')}`, cfg.mintsPerIp)) return { error: 'Too many keys from your address today. Try tomorrow.' } + return { key: store.mintKey(email).key } + } + + const checkout = async (key: Key) => { + const cp = cfg.coinpay + if (!cp) throw new ToolError('Payments are not set up on this server yet.', 503) + const client = new CoinPay({ token: cp.apiKey, base: cp.baseUrl, fetch: cp.fetch ?? fetch }) + const ref = `pp_${randomBytes(9).toString('base64url')}` + let session + try { + session = await client.createCheckoutSession({ + amount: cfg.proUsd, + currency: 'USD', + description: `sk33p Pro: ${cfg.limits.pro.calls} API/MCP calls a day for ${cfg.proDays} days`, + customerEmail: key.email, + accountId: key.id, + property: new URL(cfg.origin).hostname, + metadata: { key_id: key.id, product: 'pro', days: cfg.proDays, payment_ref: ref }, + successUrl: `${cfg.origin}/upgrade?paid=1`, + cancelUrl: `${cfg.origin}/upgrade`, + expiresInMinutes: 60, + }) + } catch (e) { + throw new ToolError(`CoinPay said ${e instanceof CoinPayError ? e.status : 'error'}: ${(e as Error).message.slice(0, 200)}`, 502) + } + if (!session?.id || !session.url) throw new ToolError('CoinPay returned no checkout session', 502) + // Written before the buyer leaves: the webhook can beat the redirect. + store.addPayment({ ref, keyId: key.id, sessionId: session.id, email: key.email, usd: cfg.proUsd, days: cfg.proDays }) + return { checkout_url: session.url, checkout_session_id: session.id, methods: session.methods ?? [], price_usd: cfg.proUsd, days: cfg.proDays } + } + + app.post('/api/v1/keys', async (c) => { + const body = await c.req.json().catch(() => ({})) + const r = mint(c, (body as any).email) + if ('error' in r) return c.json({ error: r.error }, 400) + return c.json({ key: r.key, plan: 'free', calls_per_day: cfg.limits.free.calls, note: 'Shown once: keep it. Send it as Authorization: Bearer .' }, 201) + }) + + app.get('/api/v1/me', (c) => { + try { + return c.json(usage(caller(c))) + } catch (e) { + return fail(c, e) + } + }) + + app.post('/api/v1/upgrade', async (c) => { + try { + const who = caller(c) + if (!who.key) throw new ToolError('send your API key (Authorization: Bearer sk33p_...); get one free at /key', 401) + return c.json(await checkout(who.key)) + } catch (e) { + return fail(c, e) + } + }) + + app.post('/hooks/coinpay', async (c) => { + const raw = await c.req.text() + const cp = cfg.coinpay + const header = c.req.header('x-coinpay-signature') + if (!cp?.webhookSecret || !header || !verifyWebhook(raw, header, cp.webhookSecret, Date.now())) return c.json({ error: 'bad signature' }, 401) + let payload: unknown + try { + payload = JSON.parse(raw) + } catch { + return c.json({ error: 'bad json' }, 400) + } + const ev = readWebhook(payload) + const row = store.payment({ sessionId: ev.checkoutSessionId }) ?? store.payment({ ref: typeof ev.metadata?.payment_ref === 'string' ? ev.metadata.payment_ref : null }) + if (!row) return c.json({ ok: true }) + if (ev.paid) { + if (store.settle(row.ref, ev.paymentId || null)) store.extendPro(row.keyId, row.days) + return c.json({ ok: true, settled: true }) + } + const status = ev.status || ev.type.replace(/^payment\./, '') + if (status) store.setStatus(row.ref, status) + return c.json({ ok: true }) + }) + + // ---- engine API + const metered = async (c: Context, tool: string, args: Record) => { + const who = caller(c) + if (!store.take(who.subject, who.limits.calls)) return c.json({ error: `daily limit reached (${who.limits.calls} calls on ${who.plan})`, ...offer(who) }, 402) + const out = await callTool(tool, args, cfg, who.limits) + c.header('x-sk33p-plan', who.plan) + c.header('x-sk33p-remaining', String(Math.max(0, who.limits.calls - store.used(who.subject)))) + return c.json(out) + } + + const routes: Record = { eval: 'eval', read: 'read_range', write: 'write_cells', sheets: 'list_sheets', convert: 'convert' } + for (const [path, tool] of Object.entries(routes)) { + app.post(`/api/v1/${path}`, async (c) => { + try { + const ct = c.req.header('content-type') ?? '' + // Raw upload: curl --data-binary @budget.xlsx '.../api/v1/convert?name=budget.xlsx&to=csv' + if (!ct.includes('json') && path !== 'eval') { + const buf = Buffer.from(await c.req.arrayBuffer()) + const q = c.req.query() + const args: Record = { ...q, file: { name: q.name ?? 'upload.xlsx', data: buf.toString('base64') } } + if (path === 'write') args.cells = JSON.parse(q.cells ?? '{}') + if (path === 'convert' || (path === 'write' && q.raw === '1')) { + const who = caller(c) + if (!store.take(who.subject, who.limits.calls)) return c.json({ error: `daily limit reached (${who.limits.calls} calls on ${who.plan})`, ...offer(who) }, 402) + const out: any = await callTool(tool, args, cfg, who.limits) + const f = out.file + return c.body(Buffer.from(f.data, 'base64'), 200, { 'content-type': 'application/octet-stream', 'content-disposition': `attachment; filename="${f.name}"`, 'x-sk33p-plan': who.plan }) + } + return await metered(c, tool, args) + } + const body = await c.req.json().catch(() => { + throw new ToolError('send a JSON body') + }) + return await metered(c, tool, body as Record) + } catch (e) { + return fail(c, e) + } + }) + } + + // ---- remote MCP (streamable HTTP, stateless JSON responses) + app.get('/mcp', (c) => c.json({ error: 'POST JSON-RPC here; see /docs#mcp' }, 405)) + app.post('/mcp', async (c) => { + let msg: any + try { + msg = await c.req.json() + } catch { + return c.json({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } }) + } + if (Array.isArray(msg)) return c.json(await Promise.all(msg.map((m) => rpc(c, m)))) + if (msg?.id === undefined || msg?.id === null) return c.body(null, 202) + return c.json(await rpc(c, msg)) + }) + + const rpc = async (c: Context, m: any) => { + const ok = (result: unknown) => ({ jsonrpc: '2.0', id: m.id, result }) + const toolText = (v: unknown, isError = false) => ok({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v) }], ...(isError ? { isError: true } : { structuredContent: v }) }) + switch (m.method) { + case 'initialize': + return ok({ protocolVersion: m.params?.protocolVersion ?? '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'sk33p', version: '0.1.0' }, instructions: `Spreadsheet engine (344 Excel functions, .xlsx in and out). Files go in and out as base64. Free: ${cfg.limits.free.calls} calls/day with a key from ${cfg.origin}/key; Pro via the upgrade tool.` }) + case 'ping': + return ok({}) + case 'tools/list': + return ok({ tools: [...TOOLS, ...ACCOUNT_TOOLS] }) + case 'tools/call': { + const name = m.params?.name + const args = m.params?.arguments ?? {} + try { + const who = caller(c) + if (name === 'usage') return toolText(usage(who)) + if (name === 'upgrade') { + if (!who.key) return toolText(`Get a free key at ${cfg.origin}/key and connect with it first.`, true) + return toolText(await checkout(who.key)) + } + if (!TOOLS.some((t) => t.name === name)) return { jsonrpc: '2.0', id: m.id, error: { code: -32602, message: `unknown tool ${name}` } } + if (!store.take(who.subject, who.limits.calls)) return toolText({ error: `daily limit reached (${who.limits.calls} calls on ${who.plan})`, ...offer(who) }, true) + return toolText(await callTool(name, args, cfg, who.limits)) + } catch (e) { + return toolText(e instanceof ToolError ? e.message : 'something went wrong', true) + } + } + default: + return { jsonrpc: '2.0', id: m.id, error: { code: -32601, message: `method not found: ${m.method}` } } + } + } + + app.notFound((c) => (c.req.path.startsWith('/api/') ? c.json({ error: 'not found' }, 404) : c.html(messagePage(cfg, 'Not found', 'That page does not exist.'), 404))) + app.onError((e, c) => { + console.error(e) + return c.req.path.startsWith('/api/') ? c.json({ error: 'something went wrong' }, 500) : c.html(messagePage(cfg, 'Something went wrong', 'Try again in a moment.'), 500) + }) + return app +} + +export function configFromEnv(env: Record = process.env): Config { + const n = (k: string, d: number) => (env[k] && Number.isFinite(Number(env[k])) ? Number(env[k]) : d) + const coinpay = + env.COINPAY_API_KEY && env.COINPAY_BUSINESS_ID + ? { baseUrl: (env.COINPAY_API_URL ?? 'https://coinpayportal.com').replace(/\/+$/, '').replace(/\/api$/, ''), apiKey: env.COINPAY_API_KEY, businessId: env.COINPAY_BUSINESS_ID, webhookSecret: env.COINPAY_WEBHOOK_SECRET ?? '' } + : null + return { + origin: (env.ORIGIN ?? 'https://sk33p.pwa.pit.world').replace(/\/+$/, ''), + bin: env.SK33P_BIN ?? 'sk33p', + limits: { + anon: { calls: n('ANON_CALLS', DEFAULT_LIMITS.anon.calls), maxBytes: n('ANON_BYTES', DEFAULT_LIMITS.anon.maxBytes) }, + free: { calls: n('FREE_CALLS', DEFAULT_LIMITS.free.calls), maxBytes: n('FREE_BYTES', DEFAULT_LIMITS.free.maxBytes) }, + pro: { calls: n('PRO_CALLS', DEFAULT_LIMITS.pro.calls), maxBytes: n('PRO_BYTES', DEFAULT_LIMITS.pro.maxBytes) }, + }, + proUsd: n('PRO_USD', 9), + proDays: n('PRO_DAYS', 30), + sandbox: env.SANDBOX !== '0', + coinpay, + mintsPerIp: n('MINTS_PER_IP', 5), + } +} diff --git a/cloud/src/engine.ts b/cloud/src/engine.ts new file mode 100644 index 0000000..463daa7 --- /dev/null +++ b/cloud/src/engine.ts @@ -0,0 +1,100 @@ +/** + * Runs one sk33p MCP tool call in a fresh, resource-limited process. + * + * The engine keeps its state in singletons (one workbook per process), so every + * call gets its own `sk33p mcp` in its own scratch directory: input files are + * written there, the tool runs with paths relative to it, any output file is + * read back, and the directory is removed. prlimit caps address space, CPU + * seconds and file size so a hostile workbook cannot take the box down. + */ +import { mkdtemp, readFile, rm, writeFile, stat } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +export type FileIn = { name: string; data: string } +export type FileOut = { name: string; data: string; bytes: number } + +export class ToolError extends Error { + constructor(message: string, readonly status = 400) { + super(message) + } +} + +export const FORMATS = ['xlsx', 'sker', 'csv', 'tsv'] as const +export type Format = (typeof FORMATS)[number] + +/** A file name safe to use inside the scratch dir: plain basename, known extension. */ +export function safeName(name: unknown, fallback = 'workbook.xlsx'): string { + const raw = typeof name === 'string' && name.trim() ? name.trim() : fallback + const base = raw.split(/[\\/]/).pop() ?? '' + const clean = base.replace(/[^A-Za-z0-9._-]/g, '_').replace(/^\.+/, '').slice(0, 80) + const ext = clean.split('.').pop()?.toLowerCase() ?? '' + if (!clean || !(FORMATS as readonly string[]).includes(ext)) throw new ToolError(`file name must end in .${FORMATS.join(', .')}`) + return clean +} + +export function withExt(name: string, to: string): string { + if (!(FORMATS as readonly string[]).includes(to)) throw new ToolError(`format must be one of ${FORMATS.join(', ')}`) + return name.replace(/\.[^.]+$/, '') + '.' + to +} + +export type RunOptions = { + bin: string + timeoutMs?: number + /** Largest file accepted in or produced, bytes. */ + maxBytes: number + /** Use prlimit (Linux). Tests on other hosts can turn it off. */ + limits?: boolean +} + +export type RunResult = { result: unknown; file?: FileOut } + +/** + * Call `tool` with `args`. `files` are written into the scratch dir first; + * `outputName` (if set) is read back after the call. + */ +export async function runTool(tool: string, args: Record, files: FileIn[], outputName: string | null, o: RunOptions): Promise { + const dir = await mkdtemp(join(tmpdir(), 'sk33p-')) + try { + for (const f of files) { + const buf = Buffer.from(f.data, 'base64') + if (buf.length > o.maxBytes) throw new ToolError(`${f.name} is ${buf.length} bytes; your plan allows ${o.maxBytes}`, 413) + await writeFile(join(dir, f.name), buf) + } + const line = JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: tool, arguments: args } }) + '\n' + const cmd = o.limits === false ? [o.bin, 'mcp'] : ['prlimit', '--as=1610612736', '--cpu=20', `--fsize=${Math.max(o.maxBytes * 4, 8 << 20)}`, '--nproc=64', '--', o.bin, 'mcp'] + const proc = Bun.spawn(cmd, { cwd: dir, stdin: 'pipe', stdout: 'pipe', stderr: 'pipe', env: { PATH: '/usr/bin:/bin', HOME: dir, LANG: 'C.UTF-8' } }) + proc.stdin.write(line) + proc.stdin.end() + const timer = setTimeout(() => proc.kill(9), o.timeoutMs ?? 20_000) + const [out, err, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]) + clearTimeout(timer) + const first = out.split('\n').find((l) => l.trim().startsWith('{')) + if (!first) throw new ToolError(code === 137 || code === 9 ? 'the engine ran out of time or memory on that input' : `the engine failed (${code}): ${err.slice(0, 300)}`, 422) + const msg = JSON.parse(first) + if (msg.error) throw new ToolError(String(msg.error.message ?? 'engine error'), 422) + const r = msg.result ?? {} + const text = r.content?.[0]?.text ?? '' + if (r.isError) throw new ToolError(String(text || 'engine error'), 422) + let result: unknown = r.structuredContent?.result ?? r.structuredContent + if (result === undefined) { + try { + result = JSON.parse(text) + } catch { + result = text + } + } + let file: FileOut | undefined + if (outputName) { + const p = join(dir, outputName) + const s = await stat(p).catch(() => null) + if (s) { + if (s.size > o.maxBytes) throw new ToolError(`the result is ${s.size} bytes; your plan allows ${o.maxBytes}`, 413) + file = { name: outputName, data: (await readFile(p)).toString('base64'), bytes: s.size } + } + } + return { result, file } + } finally { + await rm(dir, { recursive: true, force: true }) + } +} diff --git a/cloud/src/main.ts b/cloud/src/main.ts new file mode 100644 index 0000000..6cc3f40 --- /dev/null +++ b/cloud/src/main.ts @@ -0,0 +1,24 @@ +import { footerHtml } from '@profullstack/footer' +import { createApp, configFromEnv } from './app.ts' +import { setFooters } from './page.ts' +import { Store } from './store.ts' + +const cfg = configFromEnv() +const store = new Store(process.env.DB_PATH ?? `${process.env.DATA_DIR ?? '.'}/sk33p-cloud.db`) +const app = createApp(store, cfg) + +// Footers: site footer, Profullstack webring row, pit.world footer last. Refreshed hourly; pages never wait. +const host = new URL(cfg.origin).hostname +const refresh = async () => { + const ring = await footerHtml({ site: `${cfg.origin}/`, links: [{ label: 'Docs', href: '/docs' }, { label: 'Pricing', href: '/#pricing' }, { label: 'GitHub', href: 'https://github.com/profullstack/sk33p' }], since: 2026 }).catch(() => '') + const pit = await fetch(`https://pit.world/snippets/footer.html?site=${encodeURIComponent(host)}`, { signal: AbortSignal.timeout(3000) }) + .then((r) => (r.ok ? r.text() : '')) + .catch(() => '') + setFooters({ ring, pit }) +} +refresh() +setInterval(refresh, 60 * 60_000).unref?.() + +const port = Number(process.env.PORT ?? 8811) +Bun.serve({ port, hostname: process.env.HOST ?? '0.0.0.0', fetch: app.fetch, idleTimeout: 60 }) +console.log(`sk33p cloud on :${port} (${cfg.origin}), payments ${cfg.coinpay ? 'on' : 'OFF'}, sandbox ${cfg.sandbox ? 'prlimit' : 'off'}`) diff --git a/cloud/src/page.ts b/cloud/src/page.ts new file mode 100644 index 0000000..61b3d1f --- /dev/null +++ b/cloud/src/page.ts @@ -0,0 +1,303 @@ +/** Server-rendered pages. One stylesheet, no build step, no client framework. */ +import type { Config } from './app.ts' + +const INSTALL = 'curl -fsSL https://raw.githubusercontent.com/profullstack/sk33p/main/install.sh | sh' +const REPO = 'https://github.com/profullstack/sk33p' + +// Footers are fetched in the background by main.ts and set here; pages never wait on them. +let ringFooter = '' +let pitFooter = '' +export function setFooters(f: { ring?: string; pit?: string }) { + if (typeof f.ring === 'string' && f.ring) ringFooter = f.ring + if (typeof f.pit === 'string' && f.pit.includes('data-pit-footer') && f.pit.length < 64_000) pitFooter = f.pit.trim() +} + +export const esc = (s: unknown) => String(s ?? '').replace(/[&<>"']/g, (ch) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[ch]!) + +const CSS = ` +:root{--bg:#0b0f0c;--panel:#111814;--line:#1f2a23;--fg:#d8e6dc;--dim:#8aa293;--accent:#5cff8d;--accent-ink:#04210f;--warn:#ffcf5c;--err:#ff6b6b;--radius:10px;color-scheme:dark} +@media (prefers-color-scheme: light){:root:not([data-theme="dark"]){--bg:#f6faf7;--panel:#fff;--line:#d9e5dd;--fg:#122018;--dim:#4d6457;--accent:#0f8a3c;--accent-ink:#fff;--warn:#9a6a00;--err:#b42318;color-scheme:light}} +*{box-sizing:border-box}html,body{margin:0} +body{background:var(--bg);color:var(--fg);font:16px/1.6 system-ui,-apple-system,Segoe UI,Roboto,sans-serif} +a{color:var(--accent)}code,pre,kbd,.mono{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace} +.wrap{max-width:1040px;margin:0 auto;padding:0 16px} +header.top{display:flex;align-items:center;gap:16px;padding:18px 0;flex-wrap:wrap} +header.top .brand{font:700 22px ui-monospace,Menlo,monospace;color:var(--fg);text-decoration:none;letter-spacing:.5px} +header.top .brand b{color:var(--accent)} +header.top nav{display:flex;gap:16px;margin-left:auto;flex-wrap:wrap} +header.top nav a{color:var(--dim);text-decoration:none}header.top nav a:hover{color:var(--fg)} +.hero{padding:40px 0 24px} +.hero h1{font-size:clamp(30px,5vw,50px);line-height:1.1;margin:0 0 14px;letter-spacing:-.5px} +.hero h1 em{font-style:normal;color:var(--accent)} +.hero p.lede{font-size:clamp(17px,2.2vw,20px);color:var(--dim);max-width:720px;margin:0 0 22px} +.cmd{display:flex;align-items:center;gap:8px;background:var(--panel);border:1px solid var(--line);border-radius:var(--radius);padding:10px 12px;max-width:100%;overflow-x:auto} +.cmd code{white-space:nowrap;font-size:14px}.cmd .p{color:var(--accent)} +button,.btn{font:600 15px system-ui,sans-serif;border-radius:8px;border:1px solid var(--accent);background:var(--accent);color:var(--accent-ink);padding:10px 16px;cursor:pointer;text-decoration:none;display:inline-block} +.btn.ghost{background:transparent;color:var(--accent)} +.copy{padding:4px 10px;font-size:13px;margin-left:auto;flex:none} +.ctas{display:flex;gap:12px;flex-wrap:wrap;margin-top:18px} +pre.term{background:#050806;color:#c9f5d6;border:1px solid var(--line);border-radius:var(--radius);padding:16px;overflow-x:auto;font-size:13.5px;line-height:1.45;margin:28px 0} +section{padding:34px 0;border-top:1px solid var(--line)} +section h2{font-size:26px;margin:0 0 6px}section .sub{color:var(--dim);margin:0 0 20px} +.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,260px),1fr));gap:16px} +.card{background:var(--panel);border:1px solid var(--line);border-radius:var(--radius);padding:18px} +.card h3{margin:0 0 8px;font-size:18px}.card p{margin:0;color:var(--dim)} +.demo textarea{width:100%;min-height:120px;background:var(--panel);color:var(--fg);border:1px solid var(--line);border-radius:8px;padding:12px;font:14px ui-monospace,Menlo,monospace;resize:vertical} +.demo .row{display:flex;gap:12px;align-items:center;margin-top:10px;flex-wrap:wrap} +.demo table{width:100%;border-collapse:collapse;margin-top:14px;font:14px ui-monospace,Menlo,monospace} +.demo td{border-top:1px solid var(--line);padding:6px 8px;vertical-align:top;word-break:break-word}.demo td.v{color:var(--accent);text-align:right} +.note{color:var(--dim);font-size:14px}.err{color:var(--err)} +.price{display:flex;flex-direction:column;gap:10px} +.price .amt{font:700 32px system-ui,sans-serif}.price .amt small{font-size:15px;color:var(--dim);font-weight:500} +.price ul{margin:0;padding-left:18px;color:var(--dim)}.price .btn{margin-top:auto;text-align:center} +.price.hot{border-color:var(--accent)} +pre.code{background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:14px;overflow-x:auto;font-size:13.5px} +details{border-top:1px solid var(--line);padding:12px 0}summary{cursor:pointer;font-weight:600} +form.stack{display:flex;flex-direction:column;gap:12px;max-width:520px} +input[type=email],input[type=text]{background:var(--panel);color:var(--fg);border:1px solid var(--line);border-radius:8px;padding:11px 12px;font:15px system-ui,sans-serif;width:100%} +.keybox{background:var(--panel);border:1px solid var(--accent);border-radius:8px;padding:14px;font:15px ui-monospace,Menlo,monospace;word-break:break-all} +.doc h2{margin-top:34px}.doc h3{margin-top:24px}.doc table{border-collapse:collapse;width:100%;display:block;overflow-x:auto}.doc td,.doc th{border:1px solid var(--line);padding:6px 10px;text-align:left} +.site-foot{border-top:1px solid var(--line);margin-top:40px;padding:24px 0;color:var(--dim);font-size:14px} +` + +function layout(cfg: Config, o: { title: string; description: string; path: string; body: string }) { + const url = cfg.origin + o.path + return ` +${esc(o.title)} + + + + + + + +
sk33p
+${o.body} + +
+${ringFooter} +${pitFooter} +` +} + +const TERM = `
 sk33p  budget.xlsx [+]    Summary   Jan   Feb
+ C4      │ =SUM(C2:C3)*1.2
+     │      A       │      B       │      C
+   1 │ item         │ qty          │        price
+   2 │ widget       │            4 │        12.50
+   3 │ gadget       │            2 │        40.00
+   4 │ total        │              │       156.00
+ READY                                   ? help  ^S save  ^Q quit
` + +const cmdBox = (text: string, prompt = '$') => `
${prompt}${esc(text)}
` + +const COPY_JS = `` + +export function homePage(cfg: Config): string { + const L = cfg.limits + const curl = `curl -s ${cfg.origin}/api/v1/eval -H 'content-type: application/json' \\\n -d '{"formulas":["=PMT(5%/12,360,-300000)","=XLOOKUP(2,{1,2,3},{\\"a\\",\\"b\\",\\"c\\"})"]}'` + const body = ` +
+

A spreadsheet for the terminal.
And an Excel engine for your agents.

+

sk33p opens, edits and saves real .xlsx files in your terminal, with 344 Excel-compatible functions: XLOOKUP, LET, FILTER, PMT, IRR and the rest. The app is free and open source. The hosted API and remote MCP give scripts and AI agents the same engine with nothing to install.

+ ${cmdBox(INSTALL)} + + ${TERM} +
+ +

Try it now

One formula per line. This runs on the hosted engine (${L.anon.calls} free tries a day without a key).

+
+
No ^ operator in this engine: use POWER().
+ +
+ +

One engine, four ways in

The same calculation core everywhere: people in a terminal, agents over a socket.

+
+

TUI

A full-screen grid: arrows or hjkl, = to type a formula, undo and redo, sheet tabs, :w file.xlsx to save as. Opens .xlsx, .csv, .tsv.

+

CLI

sk33p eval, get, set, cat --csv, convert. Pipe workbooks through shell scripts and CI.

+

API

Evaluate formulas, read ranges, write cells and convert files over HTTPS. Send a workbook, get JSON or the saved file back.

+

MCP

sk33p mcp locally on stdio, or the hosted server at ${esc(cfg.origin)}/mcp for Claude, Cursor and any MCP client.

+
+ +

API in one line

No key needed to try. Add Authorization: Bearer sk33p_... for your plan's limits.

+
${esc(curl)}
+
${esc(`# xlsx in, csv out\ncurl -s --data-binary @budget.xlsx '${cfg.origin}/api/v1/convert?name=budget.xlsx&to=csv' \\\n  -H "authorization: Bearer $SK33P_KEY" -o budget.csv`)}
+
${esc(JSON.stringify({ mcpServers: { sk33p: { type: 'http', url: `${cfg.origin}/mcp`, headers: { Authorization: 'Bearer sk33p_...' } } } }, null, 2))}
+

Every endpoint and MCP tool

+ +

Pricing

The terminal app is free forever. The hosted API and MCP have a free tier; Pro is for real workloads.

+
+

Terminal

$0 forever, MIT
  • TUI, CLI and local MCP
  • Runs on your machine, no limits
  • Linux x86_64 / arm64, macOS arm64
Install
+

Free API

$0 with an email
  • ${L.free.calls} API + MCP calls a day
  • Files up to ${Math.round(L.free.maxBytes / 1048576)} MB
  • All tools: eval, read, write, sheets, convert
Get a free key
+

Pro

$${cfg.proUsd} per ${cfg.proDays} days
  • ${L.pro.calls.toLocaleString('en-US')} calls a day
  • Files up to ${Math.round(L.pro.maxBytes / 1048576)} MB
  • Pay with any coin or PayPal via CoinPay
  • No subscription: buy more days when you want
Go Pro
+
+ +

Questions

+
What is the engine?

SkeeptoEngine, a C++20 calculation core by Stéphane Allez (MIT): 344 worksheet functions including dynamic arrays, XLOOKUP, LET, LAMBDA helpers and financial solvers. sk33p is an independent Rust frontend for it.

+
Do you keep my files?

No. Each call runs in a fresh, sandboxed process in a scratch directory that is deleted when the call ends. We store your key's hash, your email and a daily call count.

+
What happens when I hit the limit?

The API answers 402 with the next step (a free key, or Pro) instead of a bare error. Counts reset at midnight UTC.

+
Anything Excel does that sk33p does not?

No ^ operator (use POWER()), one workbook per process, no charts or macros. Number formats from .xlsx are applied.

+
+${COPY_JS}` + return layout(cfg, { title: 'sk33p: a terminal spreadsheet and Excel engine API', description: 'Open and edit .xlsx in your terminal with 344 Excel-compatible functions. Free TUI and CLI; hosted API and remote MCP for agents, free tier and Pro.', path: '/', body }) +} + +export function keyPage(cfg: Config, o: { key?: string; error?: string; email?: string }): string { + const body = o.key + ? `

Your free key

Shown once. Copy it somewhere safe: we only keep its hash.

+
${esc(o.key)}
+

Use it

${esc(`export SK33P_KEY=${o.key}\ncurl -s ${cfg.origin}/api/v1/me -H "authorization: Bearer $SK33P_KEY"`)}
+

${cfg.limits.free.calls} calls a day. Need more? Go Pro for $${cfg.proUsd} per ${cfg.proDays} days.

${COPY_JS}` + : `

Get a free API key

${cfg.limits.free.calls} API and MCP calls a day, files up to ${Math.round(cfg.limits.free.maxBytes / 1048576)} MB. Your email is where CoinPay sends receipts if you upgrade later.

+
+ +${o.error ? `

${esc(o.error)}

` : ''}
` + return layout(cfg, { title: 'Free API key · sk33p', description: 'A free sk33p API key: the Excel-compatible engine over HTTPS and MCP.', path: '/key', body }) +} + +export function upgradePage(cfg: Config, o: { error?: string; paid?: boolean }): string { + const body = o.paid + ? `

Thanks: Pro is on its way

CoinPay confirms the payment on chain, then your key turns Pro (usually a minute or two). Check with:

+
${esc(`curl -s ${cfg.origin}/api/v1/me -H "authorization: Bearer $SK33P_KEY"`)}
` + : `

sk33p Pro

$${cfg.proUsd} for ${cfg.proDays} days: ${cfg.limits.pro.calls.toLocaleString('en-US')} calls a day and files up to ${Math.round(cfg.limits.pro.maxBytes / 1048576)} MB. Pay with any coin or PayPal through CoinPay. No subscription; each payment adds ${cfg.proDays} days.

+
+${o.error ? `

${esc(o.error)}

` : ''}
+

No key yet? Get a free one first. Agents can call POST /api/v1/upgrade or the MCP upgrade tool and hand you the checkout link.

` + return layout(cfg, { title: 'sk33p Pro', description: `sk33p Pro: ${cfg.limits.pro.calls} Excel-engine API calls a day for $${cfg.proUsd}, paid in crypto or PayPal.`, path: '/upgrade', body }) +} + +export function messagePage(cfg: Config, title: string, message: string): string { + return layout(cfg, { title: `${title} · sk33p`, description: message, path: '/', body: `

${esc(title)}

${esc(message)}

Home
` }) +} + +export function docsMarkdown(cfg: Config): string { + const o = cfg.origin + const L = cfg.limits + return `# sk33p API and MCP + +The sk33p engine (SkeeptoEngine, 344 Excel-compatible functions, reads and writes .xlsx) over HTTPS and MCP. +Base URL: ${o} + +## Auth and limits + +Send your key as \`Authorization: Bearer sk33p_...\` (or \`X-API-Key\`, or \`?key=\` for MCP clients that cannot set headers). +Get a free key at ${o}/key or \`POST /api/v1/keys {"email": "you@example.com"}\`. + +| Plan | Calls a day | Largest file | Price | +| --- | --- | --- | --- | +| No key | ${L.anon.calls} | ${Math.round(L.anon.maxBytes / 1024)} KB | free | +| Free key | ${L.free.calls} | ${Math.round(L.free.maxBytes / 1048576)} MB | free | +| Pro | ${L.pro.calls} | ${Math.round(L.pro.maxBytes / 1048576)} MB | $${cfg.proUsd} per ${cfg.proDays} days | + +Days reset at midnight UTC. Over the limit the API answers **402** with \`next\`: how to get a key or go Pro. +Every engine response carries \`x-sk33p-plan\` and \`x-sk33p-remaining\`. + +Files travel as \`{"name": "budget.xlsx", "data": ""}\`. Formats: .xlsx, .sker, .csv, .tsv. +Each call runs in a fresh sandboxed process; nothing is kept. + +## Endpoints + +### POST /api/v1/eval +\`{"formulas": ["=PMT(5%/12,360,-300000)", "=SUM(1,2,3)"]}\` -> \`{"results": [{"formula": "...", "value": "1610.46486903642"}, ...]}\` +Up to 200 formulas. The engine has no ^ operator: use POWER(). + +### POST /api/v1/read +\`{"file": {...}, "range": "A1:D20", "sheet": "Jan", "formulas": true}\` -> computed values (and formulas). Omit range for the used range. + +### POST /api/v1/write +\`{"file": {...} | omit for a new workbook, "name": "new.xlsx", "cells": {"A1": "10", "B1": "=A1*2"}, "sheet": "Sheet1", "format": "xlsx"}\` +-> \`{"result": ..., "file": {"name", "data", "bytes"}}\` with the saved workbook. + +### POST /api/v1/sheets +\`{"file": {...}}\` -> sheet names and used sizes. + +### POST /api/v1/convert +\`{"file": {...}, "to": "csv"}\` -> \`{"file": {...}}\`. +Raw form: \`curl --data-binary @budget.xlsx '${o}/api/v1/convert?name=budget.xlsx&to=csv' -o budget.csv\` returns the file itself. + +### GET /api/v1/me +Your plan, calls today and limits. + +### POST /api/v1/keys +\`{"email": "you@example.com"}\` -> \`{"key": "sk33p_..."}\` (shown once). + +### POST /api/v1/upgrade +With your key: starts a CoinPay checkout for Pro and returns \`checkout_url\` (any coin or PayPal). Each payment adds ${cfg.proDays} days. + +## MCP + +Remote server (streamable HTTP): \`${o}/mcp\` + +\`\`\`json +{"mcpServers": {"sk33p": {"type": "http", "url": "${o}/mcp", "headers": {"Authorization": "Bearer sk33p_..."}}}} +\`\`\` + +Tools: eval, read_range, write_cells, list_sheets, convert (files as base64), usage, upgrade. + +Local, unlimited, no account: install the app and run \`sk33p mcp\` (stdio; the same tools on file paths). + +## The app + +\`${INSTALL}\` + +Source: ${REPO} (MIT) +` +} + +/** Tiny Markdown renderer for our own docs (headings, code, tables, paragraphs, inline code). */ +function md(src: string): string { + const inline = (s: string) => + esc(s) + .replace(/`([^`]+)`/g, '$1') + .replace(/\*\*([^*]+)\*\*/g, '$1') + .replace(/(https:\/\/[^\s<)]+)/g, '$1') + const out: string[] = [] + const lines = src.split('\n') + for (let i = 0; i < lines.length; i++) { + const l = lines[i]! + if (l.startsWith('```')) { + const buf: string[] = [] + while (++i < lines.length && !lines[i]!.startsWith('```')) buf.push(lines[i]!) + out.push(`
${esc(buf.join('\n'))}
`) + } else if (l.startsWith('|')) { + const rows: string[] = [] + for (; i < lines.length && lines[i]!.startsWith('|'); i++) if (!/^\|\s*-/.test(lines[i]!)) rows.push(lines[i]!) + i-- + out.push(`${rows.map((r, n) => `${r.split('|').slice(1, -1).map((c) => (n ? `` : ``)).join('')}`).join('')}
${inline(c.trim())}${inline(c.trim())}
`) + } else if (/^#{1,3} /.test(l)) { + const n = l.indexOf(' ') + const text = l.slice(n + 1) + const id = text.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') + out.push(`${inline(text)}`) + } else if (l.trim()) out.push(`

${inline(l)}

`) + } + return out.join('\n') +} + +export function docsPage(cfg: Config): string { + return layout(cfg, { title: 'Docs · sk33p API and MCP', description: 'sk33p API and MCP reference: eval, read, write, sheets, convert; limits, keys and Pro.', path: '/docs', body: `
${md(docsMarkdown(cfg))}

This page as Markdown: /docs.md

` }) +} + +export function llmsTxt(cfg: Config): string { + return `# sk33p + +> A terminal spreadsheet (TUI + CLI, MIT) and a hosted Excel-compatible formula engine (API + remote MCP) with 344 functions that reads and writes .xlsx. + +- [Docs (Markdown)](${cfg.origin}/docs.md): every endpoint, MCP tool, limit and price +- [Remote MCP](${cfg.origin}/mcp): streamable HTTP; tools eval, read_range, write_cells, list_sheets, convert, usage, upgrade +- [Free API key](${cfg.origin}/key) +- [Pro](${cfg.origin}/upgrade): $${cfg.proUsd} per ${cfg.proDays} days via CoinPay +- [Source](${REPO}) +` +} diff --git a/cloud/src/store.ts b/cloud/src/store.ts new file mode 100644 index 0000000..bf46458 --- /dev/null +++ b/cloud/src/store.ts @@ -0,0 +1,101 @@ +/** Keys, daily usage and CoinPay payments, in one SQLite file. */ +import { Database } from 'bun:sqlite' +import { createHash, randomBytes } from 'node:crypto' + +export type Plan = 'anon' | 'free' | 'pro' +export type Key = { id: string; email: string; proUntil: number; createdAt: number } +export type Payment = { ref: string; keyId: string; sessionId: string | null; days: number; status: string } + +export const hashKey = (k: string) => createHash('sha256').update(k).digest('hex') +export const day = (now = Date.now()) => new Date(now).toISOString().slice(0, 10) + +export class Store { + readonly db: Database + constructor(path = ':memory:') { + this.db = new Database(path, { create: true }) + this.db.exec('PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;') + this.db.exec(` + CREATE TABLE IF NOT EXISTS keys (id TEXT PRIMARY KEY, hash TEXT UNIQUE NOT NULL, email TEXT NOT NULL, pro_until INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL); + CREATE INDEX IF NOT EXISTS keys_email ON keys(email); + CREATE TABLE IF NOT EXISTS usage (subject TEXT NOT NULL, day TEXT NOT NULL, n INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (subject, day)); + CREATE TABLE IF NOT EXISTS payments (ref TEXT PRIMARY KEY, key_id TEXT NOT NULL, session_id TEXT UNIQUE, email TEXT, usd REAL NOT NULL, days INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'pending', payment_id TEXT, created_at INTEGER NOT NULL, settled_at INTEGER); + `) + } + + /** A new key; the secret is returned once and only its hash is kept. */ + mintKey(email: string, now = Date.now()): { key: string; id: string } { + const key = `sk33p_${randomBytes(24).toString('base64url')}` + const id = `k_${randomBytes(8).toString('base64url')}` + this.db.query('INSERT INTO keys (id, hash, email, created_at) VALUES (?, ?, ?, ?)').run(id, hashKey(key), email, now) + return { key, id } + } + + keyBySecret(secret: string): Key | null { + const r: any = this.db.query('SELECT id, email, pro_until, created_at FROM keys WHERE hash = ?').get(hashKey(secret)) + return r ? { id: r.id, email: r.email, proUntil: r.pro_until, createdAt: r.created_at } : null + } + + keyById(id: string): Key | null { + const r: any = this.db.query('SELECT id, email, pro_until, created_at FROM keys WHERE id = ?').get(id) + return r ? { id: r.id, email: r.email, proUntil: r.pro_until, createdAt: r.created_at } : null + } + + /** Add `days` of Pro, starting from now or from the end of the current Pro period. */ + extendPro(id: string, days: number, now = Date.now()): number { + const k = this.keyById(id) + if (!k) return 0 + const until = Math.max(now, k.proUntil) + days * 86_400_000 + this.db.query('UPDATE keys SET pro_until = ? WHERE id = ?').run(until, id) + return until + } + + used(subject: string, now = Date.now()): number { + const r: any = this.db.query('SELECT n FROM usage WHERE subject = ? AND day = ?').get(subject, day(now)) + return r?.n ?? 0 + } + + /** Count one call if it fits under `limit`; false when the day's quota is spent. */ + take(subject: string, limit: number, now = Date.now()): boolean { + const d = day(now) + return this.db.transaction(() => { + const n = this.used(subject, now) + if (n >= limit) return false + this.db.query('INSERT INTO usage (subject, day, n) VALUES (?, ?, 1) ON CONFLICT(subject, day) DO UPDATE SET n = n + 1').run(subject, d) + return true + })() + } + + addPayment(p: { ref: string; keyId: string; sessionId: string; email: string; usd: number; days: number }, now = Date.now()): void { + this.db.query('INSERT INTO payments (ref, key_id, session_id, email, usd, days, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)').run(p.ref, p.keyId, p.sessionId, p.email, p.usd, p.days, now) + } + + payment(by: { sessionId?: string | null; ref?: string | null }): Payment | null { + const r: any = by.sessionId + ? this.db.query('SELECT * FROM payments WHERE session_id = ?').get(by.sessionId) + : by.ref + ? this.db.query('SELECT * FROM payments WHERE ref = ?').get(by.ref) + : null + return r ? { ref: r.ref, keyId: r.key_id, sessionId: r.session_id, days: r.days, status: r.status } : null + } + + /** Mark paid once; true only for the call that settled it. */ + settle(ref: string, paymentId: string | null, now = Date.now()): boolean { + const r = this.db.query("UPDATE payments SET status = 'paid', settled_at = ?, payment_id = COALESCE(?, payment_id) WHERE ref = ? AND status != 'paid'").run(now, paymentId, ref) + return r.changes === 1 + } + + setStatus(ref: string, status: string): void { + this.db.query("UPDATE payments SET status = ? WHERE ref = ? AND status != 'paid'").run(status, ref) + } + + stats(): { keys: number; pro: number; paid: number; callsToday: number } { + const now = Date.now() + const q = (sql: string, ...a: any[]) => (this.db.query(sql).get(...a) as any)?.n ?? 0 + return { + keys: q('SELECT COUNT(*) n FROM keys'), + pro: q('SELECT COUNT(*) n FROM keys WHERE pro_until > ?', now), + paid: q("SELECT COUNT(*) n FROM payments WHERE status = 'paid'"), + callsToday: q("SELECT COALESCE(SUM(n),0) n FROM usage WHERE day = ? AND subject NOT LIKE 'mint:%'", day(now)), + } + } +} diff --git a/cloud/test/app.test.ts b/cloud/test/app.test.ts new file mode 100644 index 0000000..8e9b23a --- /dev/null +++ b/cloud/test/app.test.ts @@ -0,0 +1,167 @@ +import { describe, expect, test } from 'bun:test' +import { signWebhook } from '@profullstack/coinpay-onboard' +import { createApp, configFromEnv, type Config } from '../src/app.ts' +import { Store } from '../src/store.ts' + +// SK33P_BIN must point at a built sk33p (e.g. a release binary). +const BIN = process.env.SK33P_BIN ?? 'sk33p' +const SECRET = 'whsec_test' + +function setup(over: Partial = {}) { + const sessions: any[] = [] + const fakeFetch = (async (url: string, init: any) => { + const body = JSON.parse(init.body) + sessions.push({ url, body }) + return new Response(JSON.stringify({ session: { id: `cs_${sessions.length}`, url: `https://coinpayportal.com/checkout/cs_${sessions.length}`, methods: ['BTC', 'paypal'] } }), { status: 201, headers: { 'content-type': 'application/json' } }) + }) as unknown as typeof fetch + const cfg: Config = { + ...configFromEnv({ SK33P_BIN: BIN, SANDBOX: process.env.SANDBOX ?? '1', ORIGIN: 'https://sk33p.test' }), + coinpay: { baseUrl: 'https://coinpayportal.com', apiKey: 'cp_test', businessId: 'biz', webhookSecret: SECRET, fetch: fakeFetch }, + ...over, + } + const store = new Store() + const app = createApp(store, cfg) + const req = (path: string, init: RequestInit & { ip?: string; key?: string } = {}) => { + const headers = new Headers(init.headers) + headers.set('x-forwarded-for', init.ip ?? '203.0.113.7') + if (init.key) headers.set('authorization', `Bearer ${init.key}`) + return app.request(path, { ...init, headers }) + } + const json = (path: string, body: unknown, o: { ip?: string; key?: string } = {}) => req(path, { method: 'POST', body: JSON.stringify(body), headers: { 'content-type': 'application/json' }, ...o }) + return { app, store, cfg, req, json, sessions } +} + +describe('engine API', () => { + test('eval works without a key and reports remaining calls', async () => { + const { json } = setup() + const r = await json('/api/v1/eval', { formulas: ['=SUM(1,2,3)', '=PMT(5%/12,360,-300000)', 'POWER(2,10)'] }) + expect(r.status).toBe(200) + expect(r.headers.get('x-sk33p-plan')).toBe('anon') + const j: any = await r.json() + expect(j.results.map((x: any) => x.value)).toEqual(['6', '1610.46486903642', '1024']) + expect(r.headers.get('x-sk33p-remaining')).toBe('9') + }) + + test('anonymous quota answers 402 with the next step', async () => { + const { json, cfg } = setup() + for (let i = 0; i < cfg.limits.anon.calls; i++) expect((await json('/api/v1/eval', { formulas: ['=1'] })).status).toBe(200) + const r = await json('/api/v1/eval', { formulas: ['=1'] }) + expect(r.status).toBe(402) + const j: any = await r.json() + expect(j.next.web).toBe('https://sk33p.test/key') + // Another address still has its own quota. + expect((await json('/api/v1/eval', { formulas: ['=1'] }, { ip: '198.51.100.9' })).status).toBe(200) + }) + + test('write a new xlsx, read it back, list sheets, convert to csv (JSON and raw)', async () => { + const { json, req } = setup() + const { key } = (await (await json('/api/v1/keys', { email: 'a@example.com' })).json()) as any + const w: any = await (await json('/api/v1/write', { name: 'budget.xlsx', cells: { A1: 'qty', B1: 'price', A2: '4', B2: '12.5', C2: '=A2*B2' } }, { key })).json() + expect(w.file.name).toBe('budget.xlsx') + expect(w.file.bytes).toBeGreaterThan(100) + const file = { name: 'budget.xlsx', data: w.file.data } + const rd: any = await (await json('/api/v1/read', { file, range: 'A1:C2' }, { key })).json() + expect(JSON.stringify(rd.result)).toContain('50') + const sh: any = await (await json('/api/v1/sheets', { file }, { key })).json() + expect(JSON.stringify(sh.sheets).length).toBeGreaterThan(2) + const cv: any = await (await json('/api/v1/convert', { file, to: 'csv' }, { key })).json() + expect(cv.file.name).toBe('budget.csv') + expect(Buffer.from(cv.file.data, 'base64').toString()).toContain('qty') + const raw = await req('/api/v1/convert?name=budget.xlsx&to=csv', { method: 'POST', body: Buffer.from(w.file.data, 'base64'), headers: { 'content-type': 'application/octet-stream' }, key }) + expect(raw.status).toBe(200) + expect(raw.headers.get('content-disposition')).toContain('budget.csv') + expect(await raw.text()).toContain('50') + }) + + test('rejects path tricks and unknown keys', async () => { + const { json } = setup() + const bad = await json('/api/v1/read', { file: { name: '../../etc/passwd', data: 'eA==' } }) + expect(bad.status).toBe(400) + const unk = await json('/api/v1/eval', { formulas: ['=1'] }, { key: 'sk33p_nope' }) + expect(unk.status).toBe(401) + }) +}) + +describe('keys and Pro', () => { + test('mint a key, upgrade through CoinPay, webhook turns it Pro', async () => { + const { json, req, sessions, store } = setup() + const mint = await json('/api/v1/keys', { email: 'Buyer@Example.com' }) + expect(mint.status).toBe(201) + const { key } = (await mint.json()) as any + expect(key).toStartWith('sk33p_') + let me: any = await (await req('/api/v1/me', { key })).json() + expect(me.plan).toBe('free') + expect(me.email).toBe('buyer@example.com') + + const up: any = await (await json('/api/v1/upgrade', {}, { key })).json() + expect(up.checkout_url).toContain('coinpayportal.com/checkout/cs_1') + expect(sessions[0].body.amount).toBe(9) + expect(sessions[0].body.customer_email).toBe('buyer@example.com') + + const event = JSON.stringify({ id: 'evt_1', type: 'payment.confirmed', data: { payment_id: 'pay_1', status: 'confirmed', checkout_session_id: up.checkout_session_id, metadata: {} } }) + const forged = await req('/hooks/coinpay', { method: 'POST', body: event, headers: { 'x-coinpay-signature': signWebhook(event, 'wrong') } }) + expect(forged.status).toBe(401) + const ok = await req('/hooks/coinpay', { method: 'POST', body: event, headers: { 'x-coinpay-signature': signWebhook(event, SECRET) } }) + expect(ok.status).toBe(200) + // A replay settles nothing twice. + await req('/hooks/coinpay', { method: 'POST', body: event, headers: { 'x-coinpay-signature': signWebhook(event, SECRET) } }) + me = await (await req('/api/v1/me', { key })).json() + expect(me.plan).toBe('pro') + const days = (Date.parse(me.pro_until) - Date.now()) / 86_400_000 + expect(days).toBeGreaterThan(29.9) + expect(days).toBeLessThan(30.1) + expect(store.stats().paid).toBe(1) + }) + + test('mint limit per address and email validation', async () => { + const { json, cfg } = setup() + expect((await json('/api/v1/keys', { email: 'nope' })).status).toBe(400) + for (let i = 0; i < cfg.mintsPerIp; i++) expect((await json('/api/v1/keys', { email: `u${i}@example.com` })).status).toBe(201) + expect((await json('/api/v1/keys', { email: 'more@example.com' })).status).toBe(400) + }) + + test('web forms: /key shows the key once, /upgrade redirects to CoinPay', async () => { + const { req } = setup() + const page = await req('/key', { method: 'POST', body: new URLSearchParams({ email: 'web@example.com' }), headers: { 'content-type': 'application/x-www-form-urlencoded' } }) + const html = await page.text() + const key = /sk33p_[A-Za-z0-9_-]{32}/.exec(html)?.[0] + expect(key).toBeTruthy() + const up = await req('/upgrade', { method: 'POST', body: new URLSearchParams({ key: key! }), headers: { 'content-type': 'application/x-www-form-urlencoded' } }) + expect(up.status).toBe(303) + expect(up.headers.get('location')).toContain('coinpayportal.com/checkout/') + }) +}) + +describe('MCP', () => { + test('initialize, tools/list, tools/call, usage', async () => { + const { json } = setup() + const rpc = async (method: string, params: unknown = {}, key?: string) => (await (await json('/mcp', { jsonrpc: '2.0', id: 1, method, params }, { key })).json()) as any + expect((await rpc('initialize', { protocolVersion: '2025-06-18' })).result.serverInfo.name).toBe('sk33p') + const names = (await rpc('tools/list')).result.tools.map((t: any) => t.name) + expect(names).toEqual(['eval', 'read_range', 'write_cells', 'list_sheets', 'convert', 'usage', 'upgrade']) + const call = await rpc('tools/call', { name: 'eval', arguments: { formulas: ['=TEXTJOIN("-",TRUE,"a","b")'] } }) + expect(call.result.structuredContent.results[0].value).toBe('a-b') + const usage = await rpc('tools/call', { name: 'usage', arguments: {} }) + expect(usage.result.structuredContent.calls_today).toBe(1) + const up = await rpc('tools/call', { name: 'upgrade', arguments: {} }) + expect(up.result.isError).toBe(true) + const note = await json('/mcp', { jsonrpc: '2.0', method: 'notifications/initialized' }) + expect(note.status).toBe(202) + }) +}) + +describe('pages', () => { + test('home, docs, llms.txt, ring descriptor, healthz', async () => { + const { req } = setup() + const home = await (await req('/')).text() + expect(home).toContain('Pricing') + expect(home).toContain('$9') + expect(home).toContain('data-webmcp') + expect(await (await req('/docs')).text()).toContain('/api/v1/convert') + expect(await (await req('/docs.md')).text()).toContain('## MCP') + expect(await (await req('/llms.txt')).text()).toContain('# sk33p') + expect((await req('/.well-known/openwebring.json')).status).toBe(200) + expect(await (await req('/healthz')).json()).toEqual({ ok: true }) + expect((await req('/nope')).status).toBe(404) + }) +}) From 8e328cbf881e3558aeff69239f4e471fb683ff29 Mon Sep 17 00:00:00 2001 From: Anthony Ettinger Date: Mon, 30 Nov 2026 14:43:15 +0000 Subject: [PATCH 2/4] README: hosted API and MCP at sk33p.pwa.pit.world Co-Authored-By: Claude Opus 5.5 --- README.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/README.md b/README.md index a9242ea..62ba3ed 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,18 @@ TUI keys: arrows or hjkl move, type or `=` to enter, Enter/F2 edit, Tab commit right, Del clear, Ctrl+Z / Ctrl+Y undo and redo, `[` `]` switch sheet, `<` `>` column width, `g` go to, `:w file.xlsx` save as, `:q` quit, `?` all keys. +## Hosted API and MCP + +The same engine over HTTPS and remote MCP at **https://sk33p.pwa.pit.world**: evaluate +formulas, read ranges, write cells and convert workbooks with nothing installed. +Free tier (a key by email, 100 calls a day); Pro is $9 per 30 days via CoinPay. +Docs: https://sk33p.pwa.pit.world/docs. Source in `cloud/`. + +```sh +curl -s https://sk33p.pwa.pit.world/api/v1/eval -H 'content-type: application/json' \ + -d '{"formulas":["=PMT(5%/12,360,-300000)"]}' +``` + ## Engine notes - The formula parser has no `^` operator: write `POWER(A1,2)`. From 8069a392f4b4eb3a8ddd32ccb65bb0340d0aa958 Mon Sep 17 00:00:00 2001 From: Anthony Ettinger Date: Mon, 30 Nov 2026 16:21:30 +0000 Subject: [PATCH 3/4] ci: stop caching target/ (restored engine stamps without their CMake cache) Error: could not load cache on every platform when the cache hit: target/ carries ExternalProject stamps but each sub-build's CMakeCache lives in the engine submodule tree. Cache only the cargo registry and git checkouts. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1993d78..b628949 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -44,11 +44,13 @@ jobs: - uses: dtolnay/rust-toolchain@stable - uses: actions/cache@v4 with: + # Not target/: it holds the engine's ExternalProject stamps, but each + # sub-build's CMakeCache lives in the engine submodule tree, so a + # restored target/ fails with "Error: could not load cache". path: | ~/.cargo/registry ~/.cargo/git - target - key: ${{ matrix.os }}-cargo-${{ hashFiles('Cargo.lock', 'engine', 'shim/**', 'patches/**', 'build.rs') }} + key: ${{ matrix.os }}-cargo-registry-${{ hashFiles('Cargo.lock') }} - name: build run: cargo build --release --all-targets -vv 2>&1 | grep -vE "^\s*$|warning:" | tail -200 env: From db4bd484a9266008eb0966b3c88581ec5143a079 Mon Sep 17 00:00:00 2001 From: Anthony Ettinger Date: Mon, 30 Nov 2026 16:31:02 +0000 Subject: [PATCH 4/4] Ask: plain-language question -> one engine-checked formula, on c0mpute TUI: an [Ask] button and "Ctrl+K ask" hint on the edit line. Ctrl+K on a cell opens the edit line with "?"; Ctrl+K, a click on [Ask], or Enter on a "?question" asks. The call runs on a background thread (status line shows "asking c0mpute... Ns", Esc cancels); the answer lands in the edit line, uncommitted, with its explanation and preview. Enter keeps, Esc drops. Errors (402 with the upgrade link, 422, transport) go to the status line. Context sent: sheet, active cell, used range, edit buffer and up to 30x12 display values around the cell (plus the header row), < 8 KB. CLI: sk33p ask "QUESTION" [FILE] [--cell C4] [--sheet S]. ureq (rustls) client; SK33P_API (default https://sk33p.pwa.pit.world), SK33P_KEY or ~/.config/sk33p/key, 120 s timeout. Cloud: POST /api/v1/ask and an MCP ask tool, metered like every tool. @profullstack/ai-providers built from C0MPUTE_* only with the paid fallback off, so OpenAI/Anthropic are never constructed. Each formula is evaluated by the engine (with the context's cells filled in); an error or error value is fed back for one retry, then 422. blocks stripped. AI call injectable via Config.ai. Docs, homepage line, llms.txt. Bun idleTimeout raised to 255 s so long asks are not cut off. Version 0.2.0. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 511 ++++++++++++++++++++++++++++++++++++++++- Cargo.toml | 3 +- README.md | 38 ++- cloud/bun.lock | 3 + cloud/package.json | 1 + cloud/src/app.ts | 37 ++- cloud/src/ask.ts | 141 ++++++++++++ cloud/src/main.ts | 2 +- cloud/src/page.ts | 34 ++- cloud/test/app.test.ts | 128 ++++++++++- src/ask.rs | 323 ++++++++++++++++++++++++++ src/cli.rs | 4 + src/main.rs | 70 ++++++ src/tui.rs | 294 ++++++++++++++++++++---- 14 files changed, 1523 insertions(+), 66 deletions(-) create mode 100644 cloud/src/ask.ts create mode 100644 src/ask.rs diff --git a/Cargo.lock b/Cargo.lock index f08757e..f738488 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 3 +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "cc" version = "1.12.0" @@ -12,29 +18,209 @@ dependencies = [ "shlex", ] +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "find-msvc-tools" version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "hqtui" version = "0.2.0" source = "git+https://github.com/profullstack/hqtui#8976428b48c78e1bf8d23c319ec0177b98fad101" +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + [[package]] name = "itoa" version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + [[package]] name = "memchr" version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -53,6 +239,55 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom", + "libc", + "untrusted", + "windows-sys", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "serde" version = "1.0.229" @@ -103,13 +338,32 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" [[package]] name = "sk33p" -version = "0.1.0" +version = "0.2.0" dependencies = [ "cc", "hqtui", "serde_json", + "ureq", ] +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "3.0.10" @@ -121,12 +375,267 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "2.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d" +dependencies = [ + "base64", + "log", + "once_cell", + "rustls", + "rustls-pki-types", + "url", + "webpki-roots 0.26.11", +] + +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.12", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index 81e7b87..e08cff0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sk33p" -version = "0.1.0" +version = "0.2.0" edition = "2021" rust-version = "1.75" license = "MIT" @@ -15,6 +15,7 @@ build = "build.rs" [dependencies] serde_json = "1" hqtui = { git = "https://github.com/profullstack/hqtui" } +ureq = { version = "2", default-features = false, features = ["tls"] } [build-dependencies] cc = "1" diff --git a/README.md b/README.md index 62ba3ed..d605be5 100644 --- a/README.md +++ b/README.md @@ -10,13 +10,13 @@ pinned here as a git submodule in `engine/`. ``` sk33p budget.xlsx [+] Summary Jan Feb - C4 │ =SUM(C2:C3)*1.2 + C4 │ =SUM(C2:C3)*1.2 [Ask] │ A │ B │ C 1 │ item │ qty │ price 2 │ widget │ 4 │ 12.50 3 │ gadget │ 2 │ 40.00 4 │ total │ │ 156.00 - READY ? help ^S save ^Q quit + READY ? help ^K ask ^S save ^Q quit ``` ## Use @@ -29,6 +29,7 @@ sk33p get budget.xlsx C4 sk33p set budget.xlsx B2 5 C2 '=B2*2' # writes and saves sk33p cat budget.xlsx A1:C10 --csv sk33p convert budget.xlsx budget.csv +sk33p ask "sum of D2:D6 plus 8% tax" budget.xlsx --cell D12 # a formula from c0mpute sk33p mcp # Model Context Protocol server on stdio ``` @@ -36,10 +37,41 @@ TUI keys: arrows or hjkl move, type or `=` to enter, Enter/F2 edit, Tab commit right, Del clear, Ctrl+Z / Ctrl+Y undo and redo, `[` `]` switch sheet, `<` `>` column width, `g` go to, `:w file.xlsx` save as, `:q` quit, `?` all keys. +## Ask + +Ask for a formula in plain language; models on the [c0mpute](https://c0mpute.com) +network write it and the engine checks it before you see it. + +- **Ctrl+K** on a cell opens the edit line with `?` ready: type the question, press + Enter. While editing, **Ctrl+K** or a click on **[Ask]** (right end of the edit + line) asks with what you typed. Typing `?sum of B2:B9 plus 8% tax` into the edit + line (Enter or F2 first: `?` alone in READY opens help) and pressing Enter asks too: + a `?question` is never stored in a cell. +- The status line shows `asking c0mpute… Ns` (small models take 20-100 s; the grid + keeps drawing); **Esc** cancels. +- The answer lands in the edit line, **not** in the cell, with a one-line explanation + and its preview value. **Enter** keeps it, **Esc** drops it. +- Errors show in the status line: a 402 daily limit comes with the link to a key or Pro. +- Sent with the question: sheet name, active cell, used range, the edit line and up to + 30 rows x 12 columns of displayed values around the cell (plus the header row), + under 8 KB. Nothing else from the file. + +CLI: `sk33p ask "QUESTION" [FILE] [--cell C4] [--sheet S]` prints the formula, +explanation and preview (with FILE it sends the same context). + +| Variable | Default | | +|---|---|---| +| `SK33P_API` | `https://sk33p.pwa.pit.world` | API base | +| `SK33P_KEY` | `~/.config/sk33p/key` if present | API key; without one the anonymous quota (10 calls a day) applies | + +Each ask is one call against your API plan. Get a free key at +https://sk33p.pwa.pit.world/key and save it: `mkdir -p ~/.config/sk33p && echo sk33p_... > ~/.config/sk33p/key`. + ## Hosted API and MCP The same engine over HTTPS and remote MCP at **https://sk33p.pwa.pit.world**: evaluate -formulas, read ranges, write cells and convert workbooks with nothing installed. +formulas, read ranges, write cells, convert workbooks and ask for formulas +(`POST /api/v1/ask`, MCP `ask`) with nothing installed. Free tier (a key by email, 100 calls a day); Pro is $9 per 30 days via CoinPay. Docs: https://sk33p.pwa.pit.world/docs. Source in `cloud/`. diff --git a/cloud/bun.lock b/cloud/bun.lock index dbc6ff3..57c030e 100644 --- a/cloud/bun.lock +++ b/cloud/bun.lock @@ -5,6 +5,7 @@ "": { "name": "sk33p-cloud", "dependencies": { + "@profullstack/ai-providers": "^0.3.3", "@profullstack/coinpay-onboard": "^0.5.1", "@profullstack/footer": "^0.7.2", "hono": "^4.13.23", @@ -16,6 +17,8 @@ "@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.32.2", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-SWsVtH/0vULSQStoZ6xxH2K09Li8fXYTMC64ZeogCdpZ3XSi1eCPOByV1OpuJxuI3OcmHhosDWYyii07tpPsLw=="], + "@profullstack/ai-providers": ["@profullstack/ai-providers@0.3.3", "", { "bin": { "ai-providers": "src/cli.js" } }, "sha512-8nams0QzinxZ6vcycOvQXp2h10pVRTj5dk6Z7sX2xY0RdWwwb1KO+7MhqJsW9WRyNNKOApt0lGd+N2FxO+f6MQ=="], + "@profullstack/coinpay-onboard": ["@profullstack/coinpay-onboard@0.5.1", "", { "dependencies": { "@modelcontextprotocol/sdk": "^1.32.2", "zod": "^4.6.7" }, "bin": { "coinpay-onboard": "bin/coinpay-onboard" } }, "sha512-vuM/1vYvkXP2E/tBcTBZ8JY4K49qtSPPY1N9XRQvIlcy0Sezr+spOf6vYBkRPhasKcFqda44MRLgxPseG9Kvdg=="], "@profullstack/footer": ["@profullstack/footer@0.7.2", "", { "peerDependencies": { "react": ">=18" }, "optionalPeers": ["react"], "bin": { "profullstack-footer": "bin/profullstack-footer.js" } }, "sha512-2Va4LEsVM7PJEGkiNaSn//Zbp3u/EP1jhJff0Q8WfhKZJieUxqXPZZGv0R3qQjy4qiFMNYQATuNXM4ZXNXsVpA=="], diff --git a/cloud/package.json b/cloud/package.json index 0e44050..d361ce3 100644 --- a/cloud/package.json +++ b/cloud/package.json @@ -8,6 +8,7 @@ "test": "bun test" }, "dependencies": { + "@profullstack/ai-providers": "^0.3.3", "@profullstack/coinpay-onboard": "^0.5.1", "@profullstack/footer": "^0.7.2", "hono": "^4.13.23" diff --git a/cloud/src/app.ts b/cloud/src/app.ts index 598fbcb..444521c 100644 --- a/cloud/src/app.ts +++ b/cloud/src/app.ts @@ -13,6 +13,7 @@ import { CoinPay, CoinPayError, readWebhook, verifyWebhook } from '@profullstack import { descriptorResponse } from '@profullstack/footer' import { runTool, safeName, withExt, ToolError, FORMATS, type FileIn } from './engine.ts' import { Store, type Key, type Plan } from './store.ts' +import { ask, c0mputeAi, type AiFn } from './ask.ts' import { docsMarkdown, docsPage, homePage, keyPage, llmsTxt, messagePage, upgradePage } from './page.ts' export type Limits = { calls: number; maxBytes: number } @@ -27,6 +28,8 @@ export type Config = { coinpay: { baseUrl: string; apiKey: string; businessId: string; webhookSecret: string; fetch?: typeof fetch } | null /** Key mints per IP per day. */ mintsPerIp: number + /** The Ask model call (c0mpute only). null turns Ask off. */ + ai: AiFn | null } export const DEFAULT_LIMITS: Record = { @@ -93,6 +96,20 @@ export const TOOLS = [ $defs: { file: fileSchema() }, }, }, + { + name: 'ask', + description: 'Ask in plain language for ONE spreadsheet formula (runs on the c0mpute network). The formula is checked by the engine before it comes back with a one-line explanation and its preview value. Send the cells it should use as context (TSV with column letters and row numbers). Counts as one call.', + inputSchema: { + type: 'object', + properties: { + question: { type: 'string', description: 'e.g. "sum of B2:B9 plus 8% tax"' }, + context: { type: 'string', description: 'optional, under 8 KB: "sheet: S\\nactive cell: C10\\ncells:\\n\\tA\\tB\\n1\\tItem\\tCost\\n2\\tDesk\\t489"' }, + sheet: { type: 'string' }, + cell: { type: 'string', description: 'where the formula will go, e.g. C10' }, + }, + required: ['question'], + }, + }, ] as const function fileSchema() { @@ -153,6 +170,19 @@ export async function callTool(name: string, a: Record, cfg: Config if (!r.file) throw new ToolError('the engine wrote no file', 422) return { file: r.file } } + case 'ask': { + // Checked in the engine: with the context's cells filled in when there are any. + const evaluate = async (formula: string, cells: Record, cell: string | null) => { + if (!Object.keys(cells).length) { + const r = await runTool('eval', { formulas: [formula] }, [], null, run) + return String((r.result as any)?.[0]?.value ?? '') + } + const at = cell ?? (cells.Z999 === undefined ? 'Z999' : 'ZZ9999') + const r = await runTool('write_cells', { path: 'ask.sker', cells: { ...cells, [at]: formula } }, [], null, run) + return String((r.result as any)?.values?.[at] ?? '') + } + return { ...(await ask(a, cfg.ai, evaluate)) } + } } throw new ToolError(`unknown tool ${name}`, 404) } @@ -338,13 +368,13 @@ export function createApp(store: Store, cfg: Config) { return c.json(out) } - const routes: Record = { eval: 'eval', read: 'read_range', write: 'write_cells', sheets: 'list_sheets', convert: 'convert' } + const routes: Record = { eval: 'eval', read: 'read_range', write: 'write_cells', sheets: 'list_sheets', convert: 'convert', ask: 'ask' } for (const [path, tool] of Object.entries(routes)) { app.post(`/api/v1/${path}`, async (c) => { try { const ct = c.req.header('content-type') ?? '' // Raw upload: curl --data-binary @budget.xlsx '.../api/v1/convert?name=budget.xlsx&to=csv' - if (!ct.includes('json') && path !== 'eval') { + if (!ct.includes('json') && path !== 'eval' && path !== 'ask') { const buf = Buffer.from(await c.req.arrayBuffer()) const q = c.req.query() const args: Record = { ...q, file: { name: q.name ?? 'upload.xlsx', data: buf.toString('base64') } } @@ -387,7 +417,7 @@ export function createApp(store: Store, cfg: Config) { const toolText = (v: unknown, isError = false) => ok({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v) }], ...(isError ? { isError: true } : { structuredContent: v }) }) switch (m.method) { case 'initialize': - return ok({ protocolVersion: m.params?.protocolVersion ?? '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'sk33p', version: '0.1.0' }, instructions: `Spreadsheet engine (344 Excel functions, .xlsx in and out). Files go in and out as base64. Free: ${cfg.limits.free.calls} calls/day with a key from ${cfg.origin}/key; Pro via the upgrade tool.` }) + return ok({ protocolVersion: m.params?.protocolVersion ?? '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'sk33p', version: '0.2.0' }, instructions: `Spreadsheet engine (344 Excel functions, .xlsx in and out). ask turns a question into one checked formula (c0mpute). Files go in and out as base64. Free: ${cfg.limits.free.calls} calls/day with a key from ${cfg.origin}/key; Pro via the upgrade tool.` }) case 'ping': return ok({}) case 'tools/list': @@ -441,5 +471,6 @@ export function configFromEnv(env: Record = process. sandbox: env.SANDBOX !== '0', coinpay, mintsPerIp: n('MINTS_PER_IP', 5), + ai: env.ASK_DISABLED === '1' ? null : c0mputeAi(env), } } diff --git a/cloud/src/ask.ts b/cloud/src/ask.ts new file mode 100644 index 0000000..74eaf39 --- /dev/null +++ b/cloud/src/ask.ts @@ -0,0 +1,141 @@ +/** + * Ask: a plain-language question about a sheet in, one checked formula out. + * + * The model runs on the c0mpute network only. The router is built from the + * C0MPUTE_* variables alone with the paid fallback off, so OpenAI and + * Anthropic are never constructed, whatever else is in the environment. + * + * Every formula is run through the engine before it is returned: if it fails + * or evaluates to an error value, the model gets the error and one more try. + */ +import { createAiProviders, extractJson } from '@profullstack/ai-providers' +import { ToolError } from './engine.ts' + +export type AiRequest = { system: string; user: string } +export type AiAnswer = { text: string; model: string; provider: string } +/** The model call. Injected in tests; c0mputeAi() in production. */ +export type AiFn = (req: AiRequest) => Promise +/** Evaluates `formula` at `cell` with the context's cells filled in; returns the display value. */ +export type EvalFn = (formula: string, cells: Record, cell: string | null) => Promise + +export const DEFAULT_MODELS = 'huihui_ai/qwen3.5-abliterated:4b,qwen3:4b' +export const MAX_QUESTION = 2000 +export const MAX_CONTEXT = 12_000 + +export const SYSTEM = `You write ONE spreadsheet formula for SkeeptoEngine, an Excel-compatible engine with 344 functions (SUM, SUMIF(S), XLOOKUP, INDEX/MATCH, LET, FILTER, SORT, UNIQUE, TEXTJOIN, PMT, IRR, ROUND, IF, IFS, DATE, TEXT...). +Rules: +- Use A1 references to the cells shown in the context (column letters across, row numbers down). Never invent data that is not in the context. +- The engine has NO ^ operator: write POWER(x, n) instead. +- One formula only, starting with "=". No charts, macros, VBA, scripts or several steps. +- Do not reference the active cell itself (that would be circular). +Answer with JSON only, no prose and no code fences: +{"formula": "=...", "explanation": "what it does, at most 140 characters"}` + +/** A router that can only ever reach c0mpute. */ +export function c0mputeAi(env: Record): AiFn { + const only: Record = {} + for (const [k, v] of Object.entries(env)) if (k.startsWith('C0MPUTE_') && v) only[k] = v + only.C0MPUTE_MODELS ||= DEFAULT_MODELS + only.C0MPUTE_TIMEOUT_MS ||= '120000' + only.AI_PAID_FALLBACK = 'off' + const router = createAiProviders({ env: only, paidFallback: false }) + const timeoutMs = Number(only.C0MPUTE_TIMEOUT_MS) || 120_000 + return async ({ system, user }) => { + const r = await router.generateText({ system, user, json: true, maxTokens: 1500, temperature: 0.2, feature: 'sk33p-ask', timeoutMs, only: ['c0mpute'] } as any) + if (r.provider !== 'c0mpute') throw new Error(`refusing an answer from ${r.provider}`) + return { text: r.text, model: r.model, provider: r.provider } + } +} + +/** Pull {formula, explanation} out of what a small model wrote. */ +export function parseAnswer(text: string): { formula: string; explanation: string } { + const cleaned = text.replace(/[\s\S]*?<\/think>/gi, '').replace(/[\s\S]*$/i, '').trim() + let obj: any + try { + obj = extractJson(cleaned) + } catch { + // A bare formula is acceptable too. + const m = /`(=[^`\n]+)`/.exec(cleaned) ?? /^\s*(=\S[^\n]*)$/m.exec(cleaned) + if (m) return { formula: tidy(m[1]!), explanation: '' } + throw new Error('the answer was not JSON with a formula') + } + if (Array.isArray(obj)) obj = obj[0] + const f = typeof obj?.formula === 'string' ? obj.formula : '' + if (!f.trim()) throw new Error('the answer had no formula') + const ex = typeof obj?.explanation === 'string' ? obj.explanation.replace(/\s+/g, ' ').trim() : '' + return { formula: tidy(f), explanation: ex.length > 140 ? ex.slice(0, 139) + '…' : ex } +} + +function tidy(f: string): string { + let s = f.trim().replace(/^`+|`+$/g, '').trim() + if (!s.startsWith('=')) s = '=' + s + return s.slice(0, 4000) +} + +const ERR = /^#(NULL!|DIV\/0!|VALUE!|REF!|NAME\?|NUM!|N\/A|SPILL!|CALC!|ERROR!?|FIELD!|BLOCKED!|CONNECT!|BUSY!|UNKNOWN!|GETTING_DATA)/i + +export function isErrorValue(v: string): boolean { + return ERR.test(v.trim()) +} + +const REF = /^[A-Z]{1,3}[1-9][0-9]{0,6}$/ + +/** The cells in the context's TSV block, as {"B2": "12.5"}. */ +export function contextCells(context: string): Record { + const cells: Record = {} + let cols: string[] | null = null + for (const line of context.split('\n')) { + if (line.startsWith('\t')) { + const head = line.split('\t').slice(1) + cols = head.every((c) => /^[A-Z]{1,3}$/.test(c)) ? head : null + continue + } + if (!cols) continue + const parts = line.split('\t') + if (!/^[1-9][0-9]{0,6}$/.test(parts[0] ?? '')) continue + parts.slice(1).forEach((v, i) => { + const col = cols![i] + if (col && v !== '' && Object.keys(cells).length < 1000) cells[`${col}${parts[0]}`] = v.startsWith('=') ? `'${v}` : v + }) + } + return cells +} + +export type AskInput = { question?: unknown; context?: unknown; sheet?: unknown; cell?: unknown } +export type AskResult = { formula: string; explanation: string; preview: string; model: string; provider: string } + +export async function ask(a: AskInput, ai: AiFn | null, evaluate: EvalFn): Promise { + const question = typeof a.question === 'string' ? a.question.trim().replace(/^\?\s*/, '') : '' + if (!question) throw new ToolError('send a question, e.g. {"question": "sum of B2:B9 plus 8% tax"}') + if (question.length > MAX_QUESTION) throw new ToolError(`the question is over ${MAX_QUESTION} characters`) + const context = typeof a.context === 'string' ? a.context : '' + if (context.length > MAX_CONTEXT) throw new ToolError(`context is over ${MAX_CONTEXT} characters; send the rows near the cell, not the whole sheet`) + const sheet = typeof a.sheet === 'string' ? a.sheet.slice(0, 100) : '' + const cellIn = typeof a.cell === 'string' ? a.cell.trim().toUpperCase() : '' + const cell = REF.test(cellIn) ? cellIn : null + if (!ai) throw new ToolError('Ask is not set up on this server yet (no c0mpute route).', 503) + + const cells = contextCells(context) + let user = [sheet && `Sheet: ${sheet}`, cell && `The formula goes in cell ${cell}.`, context && `Context:\n${context}`, `Question: ${question}`].filter(Boolean).join('\n') + let last = '' + for (let attempt = 0; attempt < 2; attempt++) { + let out: AiAnswer + try { + out = await ai({ system: SYSTEM, user }) + } catch (e) { + throw new ToolError(`c0mpute did not answer: ${String((e as Error)?.message ?? e).slice(0, 200)}`, 502) + } + let formula = '' + let explanation = '' + try { + ;({ formula, explanation } = parseAnswer(out.text)) + const preview = await evaluate(formula, cells, cell) + if (isErrorValue(preview)) throw new Error(`it evaluates to ${preview}`) + return { formula, explanation, preview, model: out.model, provider: out.provider } + } catch (e) { + last = `${formula ? formula + ': ' : ''}${String((e as Error)?.message ?? e).slice(0, 300)}` + user += `\n\nYour previous answer did not work (${last}). Fix it and answer with the JSON again.` + } + } + throw new ToolError(`no working formula for that question (${last})`, 422) +} diff --git a/cloud/src/main.ts b/cloud/src/main.ts index 6cc3f40..9d37a5e 100644 --- a/cloud/src/main.ts +++ b/cloud/src/main.ts @@ -20,5 +20,5 @@ refresh() setInterval(refresh, 60 * 60_000).unref?.() const port = Number(process.env.PORT ?? 8811) -Bun.serve({ port, hostname: process.env.HOST ?? '0.0.0.0', fetch: app.fetch, idleTimeout: 60 }) +Bun.serve({ port, hostname: process.env.HOST ?? '0.0.0.0', fetch: app.fetch, idleTimeout: 255 }) // Ask waits up to 120 s on c0mpute; 255 is Bun's max console.log(`sk33p cloud on :${port} (${cfg.origin}), payments ${cfg.coinpay ? 'on' : 'OFF'}, sandbox ${cfg.sandbox ? 'prlimit' : 'off'}`) diff --git a/cloud/src/page.ts b/cloud/src/page.ts index 61b3d1f..b111699 100644 --- a/cloud/src/page.ts +++ b/cloud/src/page.ts @@ -128,7 +128,8 @@ note.textContent=(r.headers.get('x-sk33p-remaining')??'?')+' tries left today.'}

CLI

sk33p eval, get, set, cat --csv, convert. Pipe workbooks through shell scripts and CI.

API

Evaluate formulas, read ranges, write cells and convert files over HTTPS. Send a workbook, get JSON or the saved file back.

MCP

sk33p mcp locally on stdio, or the hosted server at ${esc(cfg.origin)}/mcp for Claude, Cursor and any MCP client.

- + +

Ask: press Ctrl+K or [Ask] on the edit line (or type ?sum of B2:B9 plus 8% tax) and the c0mpute network writes the formula, checked by the engine before you press Enter. Also sk33p ask, POST /api/v1/ask and the MCP ask tool.

API in one line

No key needed to try. Add Authorization: Bearer sk33p_... for your plan's limits.

${esc(curl)}
@@ -139,7 +140,7 @@ note.textContent=(r.headers.get('x-sk33p-remaining')??'?')+' tries left today.'}

Pricing

The terminal app is free forever. The hosted API and MCP have a free tier; Pro is for real workloads.

Terminal

$0 forever, MIT
  • TUI, CLI and local MCP
  • Runs on your machine, no limits
  • Linux x86_64 / arm64, macOS arm64
Install
-

Free API

$0 with an email
  • ${L.free.calls} API + MCP calls a day
  • Files up to ${Math.round(L.free.maxBytes / 1048576)} MB
  • All tools: eval, read, write, sheets, convert
Get a free key
+

Free API

$0 with an email
  • ${L.free.calls} API + MCP calls a day
  • Files up to ${Math.round(L.free.maxBytes / 1048576)} MB
  • All tools: eval, read, write, sheets, convert, ask
Get a free key

Pro

$${cfg.proUsd} per ${cfg.proDays} days
  • ${L.pro.calls.toLocaleString('en-US')} calls a day
  • Files up to ${Math.round(L.pro.maxBytes / 1048576)} MB
  • Pay with any coin or PayPal via CoinPay
  • No subscription: buy more days when you want
Go Pro
@@ -226,6 +227,28 @@ Up to 200 formulas. The engine has no ^ operator: use POWER(). \`{"file": {...}, "to": "csv"}\` -> \`{"file": {...}}\`. Raw form: \`curl --data-binary @budget.xlsx '${o}/api/v1/convert?name=budget.xlsx&to=csv' -o budget.csv\` returns the file itself. +### POST /api/v1/ask +\`{"question": "sum of B2:B9 plus 8% tax", "context": "...", "sheet": "Sheet1", "cell": "B10"}\` +-> \`{"formula": "=SUM(B2:B9)*1.08", "explanation": "Adds B2:B9 and 8% tax", "preview": "3815.75", "model": "qwen3:4b", "provider": "c0mpute"}\` + +Turns a plain-language question into ONE formula. The model runs on the c0mpute network (never OpenAI or Anthropic); answers take 20-100 seconds. +Every formula is run through the engine before it comes back: if it fails or evaluates to an error, the model gets the error and one more try; still bad answers **422** with the reason. +\`preview\` is the formula's value with the context's cells filled in. One call against your plan, like the other tools (402 when over). + +\`context\` (optional, under 8 KB) is what the sheet looks like near the cell; the sk33p app builds it for you. Cells are tab separated with column letters across and row numbers down: + +\`\`\` +sheet: Budget +active cell: B10 +used range: A1:B9 +cells (tab separated; first field is the row number): + A B +1 Item Cost +2 Desk 489 +\`\`\` + +The engine has no ^ operator, so formulas use POWER(). No charts or macros: one formula per question. + ### GET /api/v1/me Your plan, calls today and limits. @@ -243,7 +266,7 @@ Remote server (streamable HTTP): \`${o}/mcp\` {"mcpServers": {"sk33p": {"type": "http", "url": "${o}/mcp", "headers": {"Authorization": "Bearer sk33p_..."}}}} \`\`\` -Tools: eval, read_range, write_cells, list_sheets, convert (files as base64), usage, upgrade. +Tools: eval, read_range, write_cells, list_sheets, convert (files as base64), ask (question -> one checked formula, on c0mpute), usage, upgrade. Local, unlimited, no account: install the app and run \`sk33p mcp\` (stdio; the same tools on file paths). @@ -286,7 +309,7 @@ function md(src: string): string { } export function docsPage(cfg: Config): string { - return layout(cfg, { title: 'Docs · sk33p API and MCP', description: 'sk33p API and MCP reference: eval, read, write, sheets, convert; limits, keys and Pro.', path: '/docs', body: `
${md(docsMarkdown(cfg))}

This page as Markdown: /docs.md

` }) + return layout(cfg, { title: 'Docs · sk33p API and MCP', description: 'sk33p API and MCP reference: eval, read, write, sheets, convert, ask; limits, keys and Pro.', path: '/docs', body: `
${md(docsMarkdown(cfg))}

This page as Markdown: /docs.md

` }) } export function llmsTxt(cfg: Config): string { @@ -295,7 +318,8 @@ export function llmsTxt(cfg: Config): string { > A terminal spreadsheet (TUI + CLI, MIT) and a hosted Excel-compatible formula engine (API + remote MCP) with 344 functions that reads and writes .xlsx. - [Docs (Markdown)](${cfg.origin}/docs.md): every endpoint, MCP tool, limit and price -- [Remote MCP](${cfg.origin}/mcp): streamable HTTP; tools eval, read_range, write_cells, list_sheets, convert, usage, upgrade +- [Remote MCP](${cfg.origin}/mcp): streamable HTTP; tools eval, read_range, write_cells, list_sheets, convert, ask, usage, upgrade +- Ask (\`POST ${cfg.origin}/api/v1/ask\` or the MCP \`ask\` tool): a plain-language question about a sheet becomes one engine-checked formula, written by models on the c0mpute network - [Free API key](${cfg.origin}/key) - [Pro](${cfg.origin}/upgrade): $${cfg.proUsd} per ${cfg.proDays} days via CoinPay - [Source](${REPO}) diff --git a/cloud/test/app.test.ts b/cloud/test/app.test.ts index 8e9b23a..6e5c166 100644 --- a/cloud/test/app.test.ts +++ b/cloud/test/app.test.ts @@ -2,6 +2,7 @@ import { describe, expect, test } from 'bun:test' import { signWebhook } from '@profullstack/coinpay-onboard' import { createApp, configFromEnv, type Config } from '../src/app.ts' import { Store } from '../src/store.ts' +import { contextCells, parseAnswer, type AiFn, type AiRequest } from '../src/ask.ts' // SK33P_BIN must point at a built sk33p (e.g. a release binary). const BIN = process.env.SK33P_BIN ?? 'sk33p' @@ -138,7 +139,7 @@ describe('MCP', () => { const rpc = async (method: string, params: unknown = {}, key?: string) => (await (await json('/mcp', { jsonrpc: '2.0', id: 1, method, params }, { key })).json()) as any expect((await rpc('initialize', { protocolVersion: '2025-06-18' })).result.serverInfo.name).toBe('sk33p') const names = (await rpc('tools/list')).result.tools.map((t: any) => t.name) - expect(names).toEqual(['eval', 'read_range', 'write_cells', 'list_sheets', 'convert', 'usage', 'upgrade']) + expect(names).toEqual(['eval', 'read_range', 'write_cells', 'list_sheets', 'convert', 'ask', 'usage', 'upgrade']) const call = await rpc('tools/call', { name: 'eval', arguments: { formulas: ['=TEXTJOIN("-",TRUE,"a","b")'] } }) expect(call.result.structuredContent.results[0].value).toBe('a-b') const usage = await rpc('tools/call', { name: 'usage', arguments: {} }) @@ -165,3 +166,128 @@ describe('pages', () => { expect((await req('/nope')).status).toBe(404) }) }) + +/** A stand-in for c0mpute: answers from a script, records every prompt. */ +function fakeAi(...answers: string[]) { + const calls: AiRequest[] = [] + const ai: AiFn = async (req) => { + calls.push(req) + const text = answers[Math.min(calls.length - 1, answers.length - 1)]! + return { text, model: 'qwen3:4b', provider: 'c0mpute' } + } + return { ai, calls } +} + +const CONTEXT = 'sheet: Budget\nactive cell: B4\nused range: A1:B3\ncells (tab separated; first field is the row number):\n\tA\tB\n1\tItem\tCost\n2\tDesk\t100\n3\tLamp\t50\n' + +describe('ask', () => { + test('question -> checked formula with a preview from the context cells', async () => { + const { ai, calls } = fakeAi('sum the costs then add tax\n```json\n{"formula": "=SUM(B2:B3)*1.08", "explanation": "Adds the costs plus 8% tax"}\n```') + const { json } = setup({ ai }) + const r = await json('/api/v1/ask', { question: '?total cost plus 8% tax', context: CONTEXT, sheet: 'Budget', cell: 'B4' }) + expect(r.status).toBe(200) + expect(r.headers.get('x-sk33p-plan')).toBe('anon') + expect(r.headers.get('x-sk33p-remaining')).toBe('9') + const j: any = await r.json() + expect(j).toEqual({ formula: '=SUM(B2:B3)*1.08', explanation: 'Adds the costs plus 8% tax', preview: '162', model: 'qwen3:4b', provider: 'c0mpute' }) + expect(calls).toHaveLength(1) + expect(calls[0]!.system).toContain('NO ^ operator') + expect(calls[0]!.user).toContain('Question: total cost plus 8% tax') + expect(calls[0]!.user).toContain('cell B4') + expect(calls[0]!.user).toContain('2\tDesk\t100') + }) + + test('without context the formula is checked with eval', async () => { + const { ai } = fakeAi('{"formula": "POWER(2,10)", "explanation": "two to the tenth"}') + const { json } = setup({ ai }) + const j: any = await (await json('/api/v1/ask', { question: '2 to the power 10' })).json() + expect(j.formula).toBe('=POWER(2,10)') + expect(j.preview).toBe('1024') + }) + + test('an invalid formula is retried once with the error, then 422', async () => { + const bad = fakeAi('{"formula": "=NOSUCHFN(B2:B3)", "explanation": "x"}', '{"formula": "=SUM(B2:B3)", "explanation": "Adds the costs"}') + const a = setup({ ai: bad.ai }) + const ok: any = await (await a.json('/api/v1/ask', { question: 'total', context: CONTEXT, cell: 'B4' })).json() + expect(ok.formula).toBe('=SUM(B2:B3)') + expect(ok.preview).toBe('150') + expect(bad.calls).toHaveLength(2) + expect(bad.calls[1]!.user).toContain('did not work (=NOSUCHFN(B2:B3)') + + const worse = fakeAi('{"formula": "=1/0", "explanation": "x"}', 'I cannot help with that.') + const b = setup({ ai: worse.ai }) + const r = await b.json('/api/v1/ask', { question: 'divide by zero', context: CONTEXT }) + expect(r.status).toBe(422) + expect(((await r.json()) as any).error).toContain('no working formula') + expect(worse.calls).toHaveLength(2) + expect(worse.calls[1]!.user).toContain('#DIV/0!') + }) + + test('metered like every tool: 402 when over, no model call', async () => { + const { ai, calls } = fakeAi('{"formula": "=1+1", "explanation": "two"}') + const { json, cfg } = setup({ ai }) + for (let i = 0; i < cfg.limits.anon.calls; i++) expect((await json('/api/v1/eval', { formulas: ['=1'] })).status).toBe(200) + const r = await json('/api/v1/ask', { question: 'one plus one' }) + expect(r.status).toBe(402) + const j: any = await r.json() + expect(j.next.web).toBe('https://sk33p.test/key') + expect(calls).toHaveLength(0) + }) + + test('no key uses the anonymous quota; a key uses its plan', async () => { + const { ai } = fakeAi('{"formula": "=1+1", "explanation": "two"}') + const { json, req } = setup({ ai }) + const anon = await json('/api/v1/ask', { question: 'one plus one' }) + expect(anon.status).toBe(200) + expect(anon.headers.get('x-sk33p-plan')).toBe('anon') + expect(anon.headers.get('x-sk33p-remaining')).toBe('9') + const { key } = (await (await json('/api/v1/keys', { email: 'asker@example.com' })).json()) as any + const keyed = await json('/api/v1/ask', { question: 'one plus one' }, { key }) + expect(keyed.headers.get('x-sk33p-plan')).toBe('free') + expect(keyed.headers.get('x-sk33p-remaining')).toBe('99') + expect(((await (await req('/api/v1/me', { key })).json()) as any).calls_today).toBe(1) + }) + + test('bad input, model down, Ask off', async () => { + const { json } = setup({ ai: fakeAi('{}').ai }) + expect((await json('/api/v1/ask', { question: '' })).status).toBe(400) + expect((await json('/api/v1/ask', { question: 'x', context: 'y'.repeat(20_000) })).status).toBe(400) + const down = setup({ + ai: async () => { + throw new Error('no free node') + }, + }) + const r = await down.json('/api/v1/ask', { question: 'total' }) + expect(r.status).toBe(502) + expect(((await r.json()) as any).error).toContain('no free node') + const off = setup({ ai: null }) + expect((await off.json('/api/v1/ask', { question: 'total' })).status).toBe(503) + }) + + test('MCP ask tool', async () => { + const { ai } = fakeAi('{"formula": "=SUM(B2:B3)", "explanation": "Adds the costs"}') + const { json } = setup({ ai }) + const r: any = await (await json('/mcp', { jsonrpc: '2.0', id: 7, method: 'tools/call', params: { name: 'ask', arguments: { question: 'total', context: CONTEXT, cell: 'B4' } } })).json() + expect(r.result.isError).toBeUndefined() + expect(r.result.structuredContent).toMatchObject({ formula: '=SUM(B2:B3)', preview: '150', provider: 'c0mpute' }) + const usage: any = await (await json('/mcp', { jsonrpc: '2.0', id: 8, method: 'tools/call', params: { name: 'usage', arguments: {} } })).json() + expect(usage.result.structuredContent.calls_today).toBe(1) + }) + + test('answer and context parsing', () => { + expect(parseAnswer('hmm {"formula": "=WRONG()"}{"formula":"=A1*2","explanation":"double"}')).toEqual({ formula: '=A1*2', explanation: 'double' }) + expect(parseAnswer('Sure! `=SUM(A1:A3)`')).toEqual({ formula: '=SUM(A1:A3)', explanation: '' }) + expect(() => parseAnswer('never closed {"formula": "=1"}')).toThrow() + expect(parseAnswer(`{"formula":"SUM(A1)","explanation":"${'x'.repeat(300)}"}`).explanation.length).toBe(140) + expect(contextCells(CONTEXT)).toEqual({ A1: 'Item', B1: 'Cost', A2: 'Desk', B2: '100', A3: 'Lamp', B3: '50' }) + }) + + test('the production router can only reach c0mpute', async () => { + const cfg = configFromEnv({ SK33P_BIN: BIN, OPENAI_API_KEY: 'sk-not-used', ANTHROPIC_API_KEY: 'sk-ant-not-used', C0MPUTE_DISABLED: '1' }) + expect(cfg.ai).toBeFunction() + // With c0mpute switched off nothing else is tried: the paid keys are never wired in. + await expect(cfg.ai!({ system: 's', user: 'u' })).rejects.toThrow() + const src = await Bun.file(new URL('../src/ask.ts', import.meta.url)).text() + expect(src).not.toMatch(/from ['"](openai|@anthropic-ai\/sdk)['"]/) + }) +}) diff --git a/src/ask.rs b/src/ask.rs new file mode 100644 index 0000000..65193ca --- /dev/null +++ b/src/ask.rs @@ -0,0 +1,323 @@ +//! Ask: turn a plain-language question into one formula, on the c0mpute network. +//! +//! The sk33p cloud (`POST {SK33P_API}/api/v1/ask`) runs the model on c0mpute, +//! checks the formula against the engine and answers +//! `{formula, explanation, preview, model, provider}`. This module builds the +//! small sheet context sent with a question, makes the HTTP call and parses the +//! answer. Nothing here writes a cell: the TUI puts the formula in the edit +//! line and the user presses Enter. +use crate::engine::{cell_name, col_name, parse_ref, Engine}; +use serde_json::{json, Value}; +use std::path::{Path, PathBuf}; +use std::sync::mpsc::{channel, Receiver}; +use std::time::Duration; + +pub const DEFAULT_API: &str = "https://sk33p.pwa.pit.world"; +/// c0mpute's small models take 20-100 s. +const TIMEOUT: Duration = Duration::from_secs(120); +/// The context stays under this many bytes. +pub const MAX_CONTEXT: usize = 8000; +const WINDOW_ROWS: usize = 30; +const WINDOW_COLS: usize = 12; +const MAX_VALUE: usize = 60; + +#[derive(Debug, Clone, PartialEq)] +pub struct Reply { + pub formula: String, + pub explanation: String, + pub preview: String, + pub model: String, + pub provider: String, +} + +/// `?sum of B2:B9 plus 8% tax` typed into a cell is a question, not a value. +/// Returns the question, or None for anything else (including a bare `?`). +pub fn question(input: &str) -> Option<&str> { + let q = input.trim_start().strip_prefix('?')?.trim(); + if q.is_empty() { + None + } else { + Some(q) + } +} + +/// What the sheet looks like near the active cell, for the model: +/// sheet name, active cell, used range, the edit buffer, then up to +/// 30 rows x 12 columns of display values as TSV with A1 column letters and +/// row numbers (plus the header row when the window starts below it). +pub fn context( + sheet: &str, + active: Option<(usize, usize)>, + used: (usize, usize), + buffer: &str, + display: impl Fn(usize, usize) -> String, +) -> String { + let (last_row, last_col) = used; + let (row, col) = active.unwrap_or((1, 1)); + let mut out = format!("sheet: {sheet}\n"); + out.push_str(&format!("active cell: {}\n", active.map(|(r, c)| cell_name(r, c)).unwrap_or_else(|| "none".into()))); + if last_row == 0 || last_col == 0 { + out.push_str("used range: empty\n"); + } else { + out.push_str(&format!("used range: A1:{}\n", cell_name(last_row, last_col))); + } + if !buffer.trim().is_empty() { + out.push_str(&format!("editing: {}\n", clip(buffer, 400))); + } + if last_row == 0 || last_col == 0 { + return out; + } + // A window around the active cell, inside the used range (plus the active cell). + let max_row = last_row.max(row); + let max_col = last_col.max(col); + let r0 = row.saturating_sub(WINDOW_ROWS / 2).max(1).min(max_row.saturating_sub(WINDOW_ROWS - 1).max(1)); + let r1 = (r0 + WINDOW_ROWS - 1).min(max_row); + let c0 = col.saturating_sub(WINDOW_COLS / 2).max(1).min(max_col.saturating_sub(WINDOW_COLS - 1).max(1)); + let c1 = (c0 + WINDOW_COLS - 1).min(max_col); + + out.push_str("cells (tab separated; first field is the row number):\n"); + let mut grid = String::from(""); + for c in c0..=c1 { + grid.push('\t'); + grid.push_str(&col_name(c)); + } + grid.push('\n'); + let line = |r: usize| -> Option { + let vals: Vec = (c0..=c1).map(|c| clip(&display(r, c), MAX_VALUE).replace(['\t', '\n', '\r'], " ")).collect(); + if vals.iter().all(|v| v.is_empty()) { + return None; + } + Some(format!("{r}\t{}\n", vals.join("\t"))) + }; + let mut rows: Vec = vec![]; + if r0 > 1 { + rows.push(1); // header + } + rows.extend(r0..=r1); + for r in rows { + if let Some(l) = line(r) { + if out.len() + grid.len() + l.len() > MAX_CONTEXT { + break; + } + grid.push_str(&l); + } + } + out.push_str(&grid); + out +} + +/// The context for the active sheet of an engine. +pub fn engine_context(e: &Engine, active: Option<(usize, usize)>, buffer: &str) -> String { + context(&e.active_sheet(), active, (e.last_row(), e.last_col()), buffer, |r, c| e.display(r, c)) +} + +fn clip(s: &str, n: usize) -> String { + if s.chars().count() <= n { + s.to_string() + } else { + s.chars().take(n.saturating_sub(1)).collect::() + "…" + } +} + +/// Read the server's answer: a Reply on 200, otherwise the server's message +/// (and, for a 402 daily limit, where to go next). +pub fn parse_reply(status: u16, body: &str) -> Result { + let v: Value = serde_json::from_str(body).map_err(|_| { + let snippet = clip(body.trim(), 160); + if snippet.is_empty() { + format!("the server answered {status} with no body") + } else { + format!("the server answered {status}: {snippet}") + } + })?; + let s = |k: &str| v.get(k).map(|x| x.as_str().map(String::from).unwrap_or_else(|| x.to_string())).unwrap_or_default(); + if status == 200 { + let formula = s("formula"); + if formula.is_empty() { + return Err("the server answered without a formula".into()); + } + return Ok(Reply { formula, explanation: s("explanation"), preview: s("preview"), model: s("model"), provider: s("provider") }); + } + let mut msg = v.get("error").and_then(Value::as_str).map(String::from).unwrap_or_else(|| format!("the server answered {status}")); + if status == 402 { + if let Some(web) = v.pointer("/next/web").and_then(Value::as_str) { + msg.push_str(&format!(": {web}")); + } + } else if status == 401 { + msg.push_str(" (check SK33P_KEY or ~/.config/sk33p/key)"); + } + Err(msg) +} + +/// The API base: $SK33P_API or the hosted server. +pub fn api_base() -> String { + std::env::var("SK33P_API").ok().filter(|s| !s.trim().is_empty()).unwrap_or_else(|| DEFAULT_API.into()).trim_end_matches('/').to_string() +} + +fn key_file() -> Option { + let base = std::env::var_os("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| std::env::var_os("HOME").map(|h| Path::new(&h).join(".config")))?; + Some(base.join("sk33p").join("key")) +} + +/// $SK33P_KEY, else ~/.config/sk33p/key. None means the anonymous quota. +pub fn api_key() -> Option { + if let Some(k) = std::env::var("SK33P_KEY").ok().map(|k| k.trim().to_string()).filter(|k| !k.is_empty()) { + return Some(k); + } + let k = std::fs::read_to_string(key_file()?).ok()?.trim().to_string(); + (!k.is_empty()).then_some(k) +} + +/// One blocking call to the ask endpoint. +pub fn ask(question: &str, context: &str, sheet: Option<&str>, cell: Option<&str>) -> Result { + let url = format!("{}/api/v1/ask", api_base()); + let mut body = json!({"question": question, "context": context}); + if let Some(s) = sheet { + body["sheet"] = json!(s); + } + if let Some(c) = cell { + body["cell"] = json!(c); + } + let agent = ureq::AgentBuilder::new().timeout(TIMEOUT).user_agent(concat!("sk33p/", env!("CARGO_PKG_VERSION"))).build(); + let mut req = agent.post(&url).set("content-type", "application/json"); + if let Some(k) = api_key() { + req = req.set("authorization", &format!("Bearer {k}")); + } + match req.send_string(&body.to_string()) { + Ok(r) => { + let status = r.status(); + let text = r.into_string().map_err(|e| format!("reading the answer: {e}"))?; + parse_reply(status, &text) + } + Err(ureq::Error::Status(status, r)) => parse_reply(status, &r.into_string().unwrap_or_default()), + Err(ureq::Error::Transport(t)) => Err(format!("could not reach {}: {t}", api_base())), + } +} + +/// Ask on a background thread; the answer arrives on the channel. Dropping the +/// receiver cancels as far as the caller is concerned. +pub fn spawn(question: String, context: String, sheet: String, cell: String) -> Receiver> { + let (tx, rx) = channel(); + std::thread::spawn(move || { + let _ = tx.send(ask(&question, &context, Some(&sheet), Some(&cell))); + }); + rx +} + +/// `sk33p ask "question" [FILE] [--cell C4] [--sheet S]` +pub fn cmd(args: &[String]) -> Result<(), String> { + const USAGE: &str = "usage: sk33p ask \"QUESTION\" [FILE] [--cell C4] [--sheet S]"; + let (mut pos, mut cell, mut sheet) = (vec![], None, None); + let mut it = args.iter(); + while let Some(a) = it.next() { + match a.as_str() { + "--cell" | "-c" => cell = Some(it.next().ok_or("--cell needs a reference like C4")?.clone()), + "--sheet" | "-s" => sheet = Some(it.next().ok_or("--sheet needs a name")?.clone()), + _ => pos.push(a.clone()), + } + } + let q = pos.first().ok_or(USAGE)?; + let q = question(q).unwrap_or(q.trim()); + if q.is_empty() || pos.len() > 2 { + return Err(USAGE.into()); + } + let active = match &cell { + Some(c) => Some(parse_ref(c).ok_or(format!("bad cell reference {c:?}"))?), + None => None, + }; + let (ctx, sheet_name) = match pos.get(1) { + Some(file) => { + let mut e = Engine::new()?; + e.load(Path::new(file))?; + if let Some(s) = &sheet { + e.set_active_sheet(s)?; + } + (engine_context(&e, active, ""), Some(e.active_sheet())) + } + None => (String::new(), sheet.clone()), + }; + let cell_ref = active.map(|(r, c)| cell_name(r, c)); + let r = ask(q, &ctx, sheet_name.as_deref(), cell_ref.as_deref())?; + println!("formula: {}", r.formula); + println!("explanation: {}", r.explanation); + println!("preview: {}", r.preview); + if !r.model.is_empty() { + println!("model: {} on {}", r.model, if r.provider.is_empty() { "c0mpute" } else { &r.provider }); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn question_prefix() { + assert_eq!(question("?sum of B2:B9 plus 8% tax"), Some("sum of B2:B9 plus 8% tax")); + assert_eq!(question(" ? total "), Some("total")); + assert_eq!(question("?"), None); + assert_eq!(question("? "), None); + assert_eq!(question("=SUM(A1:A3)"), None); + assert_eq!(question("why?"), None); + assert_eq!(question(""), None); + } + + fn sheet(r: usize, c: usize) -> String { + match (r, c) { + (1, 1) => "Item".into(), + (1, 2) => "Qty".into(), + (1, 3) => "Price".into(), + (r, 1) if r <= 60 => format!("thing {r}"), + (r, 2) if r <= 60 => (r * 2).to_string(), + (r, 3) if r <= 60 => "1.5".into(), + _ => String::new(), + } + } + + #[test] + fn context_small_sheet() { + let ctx = context("Budget", Some((4, 4)), (3, 3), "?total", |r, c| if r <= 3 { sheet(r, c) } else { String::new() }); + assert!(ctx.starts_with("sheet: Budget\nactive cell: D4\nused range: A1:C3\nediting: ?total\n"), "{ctx}"); + assert!(ctx.contains("\tA\tB\tC\tD\n1\tItem\tQty\tPrice\t\n2\tthing 2\t4\t1.5\t\n"), "{ctx}"); + // the empty active row is left out + assert!(!ctx.contains("\n4\t"), "{ctx}"); + } + + #[test] + fn context_window_keeps_header_and_stays_small() { + let ctx = context("S", Some((50, 2)), (60, 3), "", sheet); + assert!(ctx.contains("\n1\tItem\tQty\tPrice\n"), "header row kept: {ctx}"); + assert!(ctx.contains("\n50\tthing 50\t100\t1.5\n"), "{ctx}"); + assert!(!ctx.contains("\n20\t"), "rows far above are left out: {ctx}"); + let data_rows = ctx.lines().filter(|l| l.split('\t').next().is_some_and(|f| f.parse::().is_ok())).count(); + assert_eq!(data_rows, 31, "30-row window plus the header: {ctx}"); + assert!(!ctx.contains("editing:")); + + let wide = |_r: usize, _c: usize| "x".repeat(500); + let big = context("S", Some((100, 100)), (400, 400), "", wide); + assert!(big.len() <= MAX_CONTEXT, "{}", big.len()); + let first = big.lines().find(|l| l.starts_with('\t')).unwrap(); + assert_eq!(first.split('\t').count(), 13, "12 columns: {first}"); + assert!(big.contains("…")); + + let empty = context("S", None, (0, 0), "", |_, _| String::new()); + assert_eq!(empty, "sheet: S\nactive cell: none\nused range: empty\n"); + } + + #[test] + fn reply_parsing() { + let ok = parse_reply(200, r#"{"formula":"=SUM(B2:B9)*1.08","explanation":"Sum plus 8% tax","preview":"108","model":"qwen3:4b","provider":"c0mpute"}"#).unwrap(); + assert_eq!(ok.formula, "=SUM(B2:B9)*1.08"); + assert_eq!(ok.preview, "108"); + assert_eq!(ok.provider, "c0mpute"); + let num = parse_reply(200, r#"{"formula":"=1+1","explanation":"","preview":2}"#).unwrap(); + assert_eq!(num.preview, "2"); + let e = parse_reply(402, r#"{"error":"daily limit reached (10 calls on anon)","next":{"web":"https://sk33p.pwa.pit.world/key"}}"#).unwrap_err(); + assert_eq!(e, "daily limit reached (10 calls on anon): https://sk33p.pwa.pit.world/key"); + let e = parse_reply(422, r#"{"error":"no working formula: #NAME?"}"#).unwrap_err(); + assert_eq!(e, "no working formula: #NAME?"); + assert!(parse_reply(401, r#"{"error":"unknown API key"}"#).unwrap_err().contains("SK33P_KEY")); + assert!(parse_reply(502, "Bad Gateway").unwrap_err().contains("502")); + assert!(parse_reply(200, r#"{"formula":""}"#).is_err()); + } +} diff --git a/src/cli.rs b/src/cli.rs index ecf9845..89f59aa 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -16,6 +16,9 @@ USAGE sk33p sheets FILE list sheet names sk33p convert IN OUT [-s SHEET] convert between .xlsx .sker .csv .tsv sk33p demo [OUT] write a sample workbook (default sk33p-demo.xlsx) + sk33p ask \"QUESTION\" [FILE] [--cell C4] [--sheet S] + ask c0mpute for a formula (via $SK33P_API, key from + $SK33P_KEY or ~/.config/sk33p/key; anonymous quota without) sk33p mcp run a Model Context Protocol server on stdio sk33p --version | --help @@ -23,6 +26,7 @@ TUI KEYS arrows/hjkl move Enter/F2 edit type or = to start Del clear Ctrl+Z/Ctrl+Y undo/redo Ctrl+S save : command (:w :q :e FILE :goto B12 :sheet NAME :addsheet :delsheet :ir :dr :ic :dc) [ ] prev/next sheet < > column width g goto ? help Ctrl+Q quit + Ctrl+K or [Ask] or a cell typed as ?QUESTION: ask c0mpute for a formula; Enter accepts, Esc drops "; struct Args { diff --git a/src/main.rs b/src/main.rs index 09ed9aa..d4e7f82 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,4 @@ +mod ask; mod cli; mod demo; mod engine; @@ -16,6 +17,7 @@ fn main() { Ok(()) } Some("mcp") => mcp::serve(), + Some("ask") => ask::cmd(&args[1..]), Some("snapshot") => tui::snapshot_cmd(&args[1..]), Some("demo") => (|| { let out = args.get(1).cloned().unwrap_or_else(|| "sk33p-demo.xlsx".into()); @@ -115,6 +117,74 @@ mod tests { let r = crate::mcp::handle(&json!({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"read_range","arguments":{"path": book, "range":"A1:A2","formulas":true}}})).unwrap(); let text = r["result"]["content"][0]["text"].as_str().unwrap().to_string(); assert!(text.contains("1024") && text.contains("=POWER(A1,10)"), "{text}"); + + // TUI Ask against a stand-in for the cloud endpoint. + { + let (url, seen) = fake_ask_server(); + std::env::set_var("SK33P_API", &url); + std::env::set_var("SK33P_KEY", "sk33p_test_not_a_real_key"); + let mut e = Engine::new().unwrap(); + e.set(1, 1, "10").unwrap(); + e.set(2, 1, "20").unwrap(); + let _e = crate::tui::ask_flow_for_test(e); + let reqs = seen.lock().unwrap().clone(); + assert!(reqs.len() >= 2, "{reqs:?}"); + let first = &reqs[0]; + assert!(first.starts_with("POST /api/v1/ask "), "{first}"); + assert!(first.to_lowercase().contains("authorization: bearer sk33p_test_not_a_real_key"), "{first}"); + let body: serde_json::Value = serde_json::from_str(first.split("\r\n\r\n").nth(1).unwrap()).unwrap(); + assert_eq!(body["question"], "sum of A1:A2"); + assert_eq!(body["cell"], "A3"); + assert_eq!(body["sheet"], "Sheet1"); + let ctx = body["context"].as_str().unwrap(); + assert!(ctx.contains("active cell: A3") && ctx.contains("1\t10\n2\t20\n"), "{ctx}"); + } let _ = std::fs::remove_dir_all(&dir); } + + /// A one-thread HTTP server that answers like /api/v1/ask: a formula for most + /// questions, a 402 for any question containing "fail". Records each request. + fn fake_ask_server() -> (String, std::sync::Arc>>) { + use std::io::{Read, Write}; + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}", l.local_addr().unwrap()); + let seen = std::sync::Arc::new(std::sync::Mutex::new(vec![])); + let rec = seen.clone(); + std::thread::spawn(move || { + for s in l.incoming() { + let Ok(mut s) = s else { continue }; + let mut buf = vec![]; + let mut chunk = [0u8; 4096]; + // read headers, then content-length bytes + loop { + let n = s.read(&mut chunk).unwrap_or(0); + if n == 0 { + break; + } + buf.extend_from_slice(&chunk[..n]); + let text = String::from_utf8_lossy(&buf).to_string(); + if let Some(i) = text.find("\r\n\r\n") { + let len = text[..i] + .lines() + .find_map(|l| l.to_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::().unwrap_or(0))) + .unwrap_or(0); + if buf.len() >= i + 4 + len { + break; + } + } + } + let req = String::from_utf8_lossy(&buf).to_string(); + rec.lock().unwrap().push(req.clone()); + let (status, body) = if req.contains("fail") { + ("402 Payment Required", r#"{"error":"daily limit reached (10 calls on anon)","next":{"web":"https://sk33p.test/key"}}"#) + } else { + // slow enough that the UI sees the pending state + std::thread::sleep(std::time::Duration::from_millis(150)); + ("200 OK", r#"{"formula":"=SUM(A1:A2)","explanation":"Adds A1 and A2","preview":"30","model":"qwen3:4b","provider":"c0mpute"}"#) + }; + let _ = write!(s, "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", body.len()); + } + }); + (url, seen) + } } diff --git a/src/tui.rs b/src/tui.rs index f81d6db..6f2581d 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -6,6 +6,8 @@ use hqtui::unicode::{fit, string_width}; use hqtui::{MouseAction, MouseButton}; use std::collections::HashMap; use std::path::PathBuf; +use std::sync::mpsc::{Receiver, TryRecvError}; +use std::time::Instant; const DEFAULT_COL_W: usize = 12; const HELP: &[(&str, &str)] = &[ @@ -16,6 +18,9 @@ const HELP: &[(&str, &str)] = &[ ("type, or =", "replace the cell / start a formula"), ("Tab / Shift+Tab", "commit and move right / left"), ("Esc", "cancel the edit"), + ("Ctrl+K / [Ask]", "ask c0mpute for a formula from the edit line"), + ("Enter, ?QUESTION, Enter", "same: a ?question is asked, never stored"), + (" answer", "lands in the edit line: Enter accepts, Esc drops"), ("Del / Backspace", "clear the cell"), ("Ctrl+Z Ctrl+Y", "undo / redo"), ("Ctrl+C Ctrl+V", "copy / paste a cell (terminal paste fills a block)"), @@ -30,6 +35,18 @@ const HELP: &[(&str, &str)] = &[ (":q :q! Ctrl+Q", "quit (:q! discards changes)"), ]; +/// Width of the " [Ask] " button at the right end of the formula bar. +const ASK_BTN: &str = " [Ask] "; +const ASK_HINT: &str = "Ctrl+K ask "; + +/// A question on its way to c0mpute. The answer lands in the edit line, never in a cell. +struct Pending { + rx: Receiver>, + started: Instant, + /// The edit line as it was, restored when the ask is cancelled or fails. + buf: Vec, +} + #[derive(PartialEq)] enum Mode { Normal, @@ -61,6 +78,8 @@ struct State { grid_rows: usize, row_header_w: usize, visible_cols: Vec<(usize, usize, usize)>, // (col, x, width) + width: usize, + asking: Option, } /// Everything one frame needs, captured from the engine before drawing. @@ -81,6 +100,8 @@ struct Snapshot { cols: Vec<(usize, usize, usize)>, cells: Vec>, help: bool, + editing: bool, + asking: bool, } pub fn run(path: Option) -> Result<(), String> { @@ -94,29 +115,7 @@ pub fn run(path: Option) -> Result<(), String> { message = format!("new file {} (Ctrl+S saves)", p.display()); } } - let mut st = State { - engine, - path, - dirty: false, - row: 1, - col: 1, - top: 1, - left: 1, - widths: HashMap::new(), - mode: Mode::Normal, - buf: vec![], - caret: 0, - message, - message_is_error: false, - help: false, - clipboard: None, - quit_armed: false, - quit: false, - grid_y: 3, - grid_rows: 20, - row_header_w: 5, - visible_cols: vec![], - }; + let mut st = new_state(engine, path, message); let mut app = App::with_options(AppOptions { quit_keys: vec![], @@ -130,6 +129,7 @@ pub fn run(path: Option) -> Result<(), String> { for ev in app.poll().map_err(|e| e.to_string())? { handle(&mut st, ev); } + poll_ask(&mut st); if st.quit { break; } @@ -141,12 +141,41 @@ pub fn run(path: Option) -> Result<(), String> { Ok(()) } +fn new_state(engine: Engine, path: Option, message: String) -> State { + State { + engine, + path, + dirty: false, + row: 1, + col: 1, + top: 1, + left: 1, + widths: HashMap::new(), + mode: Mode::Normal, + buf: vec![], + caret: 0, + message, + message_is_error: false, + help: false, + clipboard: None, + quit_armed: false, + quit: false, + grid_y: 3, + grid_rows: 20, + row_header_w: 5, + visible_cols: vec![], + width: 80, + asking: None, + } +} + fn col_w(st: &State, col: usize) -> usize { *st.widths.get(&(st.engine.active_sheet(), col)).unwrap_or(&DEFAULT_COL_W) } /// Keep the cursor on screen and work out which rows and columns fit. fn layout(st: &mut State, width: usize, height: usize) { + st.width = width; st.grid_y = 3; // title, formula bar, column header st.grid_rows = height.saturating_sub(st.grid_y + 1).max(1); if st.row < st.top { @@ -189,6 +218,10 @@ fn snapshot(st: &State) -> Snapshot { let (message, mode_label, is_err) = match st.mode { Mode::Command => (format!(":{}", st.buf.iter().collect::()), "CMD", false), Mode::Goto => (format!("go to: {}", st.buf.iter().collect::()), "GOTO", false), + Mode::Edit if st.asking.is_some() => { + let secs = st.asking.as_ref().map(|p| p.started.elapsed().as_secs()).unwrap_or(0); + (format!("asking c0mpute… {secs}s (Esc cancels)"), "ASK", false) + } Mode::Edit => (st.message.clone(), "EDIT", st.message_is_error), Mode::Normal => (st.message.clone(), "READY", st.message_is_error), }; @@ -215,6 +248,8 @@ fn snapshot(st: &State) -> Snapshot { cols: st.visible_cols.clone(), cells, help: st.help, + editing: st.mode == Mode::Edit, + asking: st.asking.is_some(), } } @@ -246,7 +281,26 @@ fn view(ui: &mut Container<'_>, s: Snapshot) { surface.text(0, 1, &fit(&format!(" {}", s.cell), refw, Align::Left), &TextOptions::new().fg(t.accent).attrs(Attrs::BOLD)); surface.text(refw as isize, 1, "│ ", &TextOptions::new().fg(t.border)); let bx = refw as isize + 2; - let room = width.saturating_sub(bx as usize); + // [Ask] button (and, while editing, its key hint) at the right end. + let btn_x = width.saturating_sub(ASK_BTN.len()); + let mut right = btn_x; + if width >= bx as usize + ASK_BTN.len() + 8 { + let opts = if s.asking { + TextOptions::new().fg(t.background).bg(t.warning).attrs(Attrs::BOLD) + } else if s.editing { + TextOptions::new().fg(t.background).bg(t.accent).attrs(Attrs::BOLD) + } else { + TextOptions::new().fg(t.muted) + }; + surface.text(btn_x as isize, 1, if s.asking { " [ … ] " } else { ASK_BTN }, &opts); + if s.editing && width >= bx as usize + ASK_BTN.len() + ASK_HINT.len() + 16 { + right = btn_x - ASK_HINT.len(); + surface.text(right as isize, 1, ASK_HINT, &TextOptions::new().fg(t.muted)); + } + } else { + right = width; + } + let room = right.saturating_sub(bx as usize + 1); match s.caret { Some(caret) => { let chars: Vec = s.bar.chars().collect(); @@ -325,12 +379,12 @@ fn view(ui: &mut Container<'_>, s: Snapshot) { surface.fill_rect(0, sy, width, 1, &st, ' '.into()); let mx = surface.text(0, sy, &format!(" {} ", s.mode_label), &TextOptions::new().fg(t.background).bg(t.primary).attrs(Attrs::BOLD)); let mfg = if s.message_is_error { t.danger } else { t.foreground }; - surface.text(mx as isize + 1, sy, &s.message, &TextOptions::new().fg(mfg).bg(t.surface).max_width(width.saturating_sub(mx + 30))); - let hint = "? help ^S save ^Q quit "; + surface.text(mx as isize + 1, sy, &s.message, &TextOptions::new().fg(mfg).bg(t.surface).max_width(width.saturating_sub(mx + 38))); + let hint = "? help ^K ask ^S save ^Q quit "; surface.text((width.saturating_sub(hint.len())) as isize, sy, hint, &TextOptions::new().fg(t.muted).bg(t.surface)); if s.help { - let w = 64.min(width.saturating_sub(4)); + let w = 84.min(width.saturating_sub(4)); let h = (HELP.len() + 4).min(height.saturating_sub(2)); let bx = ((width - w) / 2) as isize; let by = ((height - h) / 2) as isize; @@ -338,7 +392,7 @@ fn view(ui: &mut Container<'_>, s: Snapshot) { .sub(bx, by, w, h) .draw_box(&BoxOptions::new().title(" sk33p keys ").footer(" any key closes ").bg(t.surface)); for (i, (k, d)) in HELP.iter().enumerate().take(inner.height()) { - let kw = inner.text(1, i as isize, &fit(k, 20, Align::Left), &TextOptions::new().fg(t.accent).bg(t.surface)); + let kw = inner.text(1, i as isize, &fit(k, 26, Align::Left), &TextOptions::new().fg(t.accent).bg(t.surface)); inner.text(kw as isize + 2, i as isize, d, &TextOptions::new().fg(t.foreground).bg(t.surface)); } } @@ -366,8 +420,58 @@ fn start_edit(st: &mut State, initial: Option) { st.mode = Mode::Edit; } +/// Send the edit line to c0mpute as a question (a leading `?` is dropped). +fn start_ask(st: &mut State) { + if st.asking.is_some() { + return; + } + let text: String = st.buf.iter().collect(); + let q = crate::ask::question(&text).map(String::from).unwrap_or_else(|| text.trim().to_string()); + if q.is_empty() || q == "?" { + if st.buf.is_empty() { + st.buf = vec!['?']; + st.caret = 1; + } + err(st, "type a question after ?, e.g. ?total of column B plus 8% tax, then Enter"); + return; + } + let ctx = crate::ask::engine_context(&st.engine, Some((st.row, st.col)), &text); + let rx = crate::ask::spawn(q, ctx, st.engine.active_sheet(), cell_name(st.row, st.col)); + st.asking = Some(Pending { rx, started: Instant::now(), buf: st.buf.clone() }); +} + +/// Pick up an answer, if one has arrived: the formula goes into the edit line, uncommitted. +fn poll_ask(st: &mut State) { + let Some(p) = &st.asking else { return }; + let got = match p.rx.try_recv() { + Err(TryRecvError::Empty) => return, + Ok(r) => r, + Err(TryRecvError::Disconnected) => Err("the ask stopped without an answer".into()), + }; + let p = st.asking.take().unwrap(); + match got { + Ok(r) => { + st.mode = Mode::Edit; + st.buf = r.formula.chars().collect(); + st.caret = st.buf.len(); + let preview = if r.preview.is_empty() { String::new() } else { format!(" → {}", r.preview) }; + info(st, format!("{}{} [Enter keeps, Esc drops]", r.explanation, preview)); + } + Err(e) => { + st.buf = p.buf; + st.caret = st.buf.len(); + err(st, format!("ask: {e}")); + } + } +} + fn commit(st: &mut State) -> bool { let text: String = st.buf.iter().collect(); + // `?question` is asked, not stored. + if crate::ask::question(&text).is_some() { + start_ask(st); + return false; + } match st.engine.set(st.row, st.col, &text) { Ok(()) => { st.dirty = true; @@ -435,6 +539,20 @@ fn handle(st: &mut State, ev: InputEvent) { } fn mouse(st: &mut State, m: &MouseEvent) { + // The [Ask] button at the right end of the formula bar. + let on_button = m.action == MouseAction::Press + && m.button == MouseButton::Left + && m.y == 1 + && m.x >= st.width.saturating_sub(ASK_BTN.len()) + && m.x < st.width; + if on_button && st.asking.is_none() { + match st.mode { + Mode::Edit => start_ask(st), + Mode::Normal => ask_key_normal(st), + _ => {} + } + return; + } if st.mode != Mode::Normal { return; } @@ -494,8 +612,19 @@ fn key(st: &mut State, k: &KeyEvent) { if k.key != "ctrl+q" { st.quit_armed = false; } + if st.asking.is_some() { + // Only Esc means something while c0mpute is thinking. + if k.key == "escape" { + let p = st.asking.take().unwrap(); + st.buf = p.buf; + st.caret = st.buf.len(); + info(st, "ask cancelled"); + } + return; + } match st.mode { Mode::Edit => match k.key.as_str() { + "ctrl+k" => start_ask(st), "escape" => { st.mode = Mode::Normal; info(st, "edit cancelled"); @@ -562,6 +691,7 @@ fn normal_key(st: &mut State, k: &KeyEvent) { "ctrl+home" => move_to(st, 1, 1), "ctrl+end" => move_to(st, st.engine.last_row().max(1) as isize, st.engine.last_col().max(1) as isize), "enter" | "f2" => start_edit(st, None), + "ctrl+k" => ask_key_normal(st), "delete" | "backspace" => { if let Err(e) = st.engine.set(st.row, st.col, "") { err(st, e); @@ -636,6 +766,12 @@ fn normal_key(st: &mut State, k: &KeyEvent) { } } +/// Ctrl+K (or [Ask]) on a selected cell: open the edit line ready for a question. +fn ask_key_normal(st: &mut State) { + start_edit(st, Some("?".into())); + info(st, "ask c0mpute: type a question, Enter sends it (Esc cancels)"); +} + fn cycle_sheet(st: &mut State, d: isize) { let sheets = st.engine.sheets(); if sheets.len() < 2 { @@ -789,29 +925,9 @@ pub(crate) fn render_headless( row: usize, col: usize, ) -> (hqtui::testing::RenderedScreen, Engine) { - let mut st = State { - engine, - path, - dirty: false, - row, - col, - top: 1, - left: 1, - widths: HashMap::new(), - mode: Mode::Normal, - buf: vec![], - caret: 0, - message: "? for help".into(), - message_is_error: false, - help: false, - clipboard: None, - quit_armed: false, - quit: false, - grid_y: 3, - grid_rows: 20, - row_header_w: 5, - visible_cols: vec![], - }; + let mut st = new_state(engine, path, "? for help".into()); + st.row = row; + st.col = col; for c in 1..=st.engine.last_col() { let w = (1..=st.engine.last_row()).map(|r| string_width(&st.engine.display(r, c))).max().unwrap_or(0); st.widths.insert((st.engine.active_sheet(), c), (w + 1).clamp(6, 28)); @@ -865,3 +981,79 @@ pub(crate) fn render_for_test(engine: Engine, width: usize, height: usize) -> (S let (screen, engine) = render_headless(engine, Some("demo.xlsx".into()), width, height, 3, 1); (screen.text(), engine) } + +/// Drive the TUI's Ask flow headlessly against `SK33P_API` (a test server). +#[cfg(test)] +pub(crate) fn ask_flow_for_test(engine: Engine) -> Engine { + use hqtui::InputParser; + let feed = |st: &mut State, raw: &str| { + for ev in InputParser::new().parse(raw) { + handle(st, ev); + } + }; + let wait = |st: &mut State| { + let t = Instant::now(); + while st.asking.is_some() && t.elapsed().as_secs() < 10 { + std::thread::sleep(std::time::Duration::from_millis(10)); + poll_ask(st); + } + }; + let mut st = new_state(engine, None, String::new()); + st.row = 3; + st.col = 1; + layout(&mut st, 100, 20); + + // `?question` + Enter asks instead of storing the text. + // (`?` alone in READY opens help, so the question is typed in the edit line: Enter/F2 first) + feed(&mut st, "?"); + assert!(st.help && st.mode == Mode::Normal); + feed(&mut st, "q"); // any key closes help + feed(&mut st, "\r"); + feed(&mut st, "?sum of A1:A2"); + feed(&mut st, "\r"); + assert!(st.asking.is_some(), "Enter on ?question starts an ask"); + assert!(st.mode == Mode::Edit); + assert_eq!(snapshot(&st).mode_label, "ASK"); + feed(&mut st, "x"); // ignored while asking + wait(&mut st); + assert_eq!(st.buf.iter().collect::(), "=SUM(A1:A2)"); + assert!(st.mode == Mode::Edit, "the answer waits in the edit line"); + assert_eq!(st.engine.input(3, 1), "", "nothing written before Enter"); + assert!(st.message.contains("Adds A1 and A2") && st.message.contains("→ 30"), "{}", st.message); + let (screen, _) = { + layout(&mut st, 100, 20); + let snap = snapshot(&st); + (hqtui::testing::render_to_screen(100, 20, "dark", move |ui| view(ui, snap)).text(), ()) + }; + assert!(screen.contains("[Ask]") && screen.contains("Ctrl+K ask"), "{screen}"); + feed(&mut st, "\r"); + assert_eq!(st.engine.input(3, 1), "=SUM(A1:A2)"); + assert_eq!(st.engine.display(3, 1), "30"); + assert!(st.mode == Mode::Normal); + + // Ctrl+K on a selected cell opens the edit line with `?`; Ctrl+K asks; Esc cancels. + st.row = 4; + feed(&mut st, "\x0b"); + assert!(st.mode == Mode::Edit); + assert_eq!(st.buf.iter().collect::(), "?"); + feed(&mut st, "double it"); + feed(&mut st, "\x0b"); + assert!(st.asking.is_some()); + // (a lone ESC byte is held by the parser for a possible sequence, so send the key itself) + handle(&mut st, InputEvent::Key(KeyEvent { name: "escape".into(), ctrl: false, alt: false, shift: false, char: None, key: "escape".into(), raw: "\x1b".into() })); + assert!(st.asking.is_none(), "Esc cancels"); + assert_eq!(st.buf.iter().collect::(), "?double it"); + assert_eq!(st.message, "ask cancelled"); + + // Clicking [Ask] asks too; a server error lands in the status line. + st.buf = "?fail please".chars().collect(); + st.caret = st.buf.len(); + let click = MouseEvent { action: MouseAction::Press, button: MouseButton::Left, x: 100 - 3, y: 1, scroll: 0, ctrl: false, alt: false, shift: false }; + handle(&mut st, InputEvent::Mouse(click)); + assert!(st.asking.is_some(), "the [Ask] button asks"); + wait(&mut st); + assert!(st.message_is_error && st.message.contains("daily limit reached") && st.message.contains("/key"), "{}", st.message); + assert_eq!(st.buf.iter().collect::(), "?fail please", "the question is kept after an error"); + assert_eq!(st.engine.input(4, 1), ""); + st.engine +}