Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 106 additions & 9 deletions cloud/src/page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ section h2{font-size:26px;margin:0 0 6px}section .sub{color:var(--dim);margin:0
.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)}
.ask{display:flex;gap:10px;margin:6px 0 4px;flex-wrap:wrap}.ask input{flex:1;min-width:min(100%,260px)}
.gallery{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,300px),1fr));gap:14px;margin-top:22px}
.ex h3{margin:0 0 8px;font-size:15px;color:var(--dim);font-weight:600}.chips{display:flex;flex-wrap:wrap;gap:6px}
.chip{background:var(--panel);color:var(--fg);border:1px solid var(--line);font:500 13px system-ui,sans-serif;padding:5px 10px;border-radius:999px}
.chip:hover{border-color:var(--accent);color:var(--accent)}
.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}
Expand Down Expand Up @@ -89,6 +94,91 @@ const TERM = `<pre class="term" aria-label="sk33p in a terminal"> sk33p budget.
4 │ total │ │ 156.00
READY ? help ^S save ^Q quit</pre>`

/**
* The showcase. Every formula here is evaluated in test/app.test.ts against the real
* engine and must not return an error, so a broken example cannot ship.
* Lists written with ; are columns (what SORT/UNIQUE/TAKE expect, as in Excel).
*/
export const EXAMPLES: { group: string; items: [formula: string, label: string][] }[] = [
{ group: 'Finance', items: [
['=ROUND(PMT(6%/12,360,-300000),2)', 'mortgage payment'],
['=ROUND(FV(5%/12,120,-200),2)', '$200/month for 10 years'],
['=ROUND(IRR({-1000;300;400;500}),4)', 'IRR of cash flows'],
['=ROUND(NPV(8%,300,400,500)-1000,2)', 'net present value'],
['=ROUND(RATE(36,-300,10000)*12,4)', 'loan APR'],
['=ROUND(NPER(5%/12,-500,20000),1)', 'months to pay off'],
['=ROUND(EFFECT(6%,12),5)', 'effective annual rate'],
['=ROUND(DB(30000,5000,5,1),2)', 'depreciation'],
] },
{ group: 'Lookup', items: [
['=XLOOKUP("gold",{"bronze";"silver";"gold"},{10;20;50})', 'XLOOKUP'],
['=VLOOKUP(2,{1,"apple";2,"banana";3,"cherry"},2,FALSE)', 'VLOOKUP'],
['=HLOOKUP("Q2",{"Q1","Q2","Q3";120,145,160},2,FALSE)', 'HLOOKUP'],
['=INDEX({"F";"C";"B";"A"},MATCH(84,{0;60;80;90},1))', 'grade from score'],
] },
{ group: 'Dynamic arrays', items: [
['=TEXTJOIN(", ",TRUE,SORT({"pear";"apple";"fig"}))', 'SORT'],
['=TEXTJOIN(", ",TRUE,UNIQUE({"a";"b";"a";"c";"b"}))', 'UNIQUE'],
['=TEXTJOIN(", ",TRUE,FILTER({12;45;7;88;30},{12;45;7;88;30}>25))', 'FILTER'],
['=TEXTJOIN(", ",TRUE,SORTBY({"x";"y";"z"},{3;1;2}))', 'SORTBY'],
['=TEXTJOIN(", ",TRUE,SEQUENCE(5,1,0,25))', 'SEQUENCE'],
['=TEXTJOIN(", ",TRUE,TAKE(SORT({4;9;1;7;3},1,-1),3))', 'top 3'],
] },
{ group: 'LET and LAMBDA', items: [
['=LET(rate,6%/12,n,360,loan,300000,ROUND(PMT(rate,n,-loan),2))', 'LET'],
['=SUM(MAP({1;2;3;4},LAMBDA(x,x*x)))', 'MAP'],
['=REDUCE(1,{1;2;3;4;5},LAMBDA(acc,x,acc*x))', 'REDUCE (5!)'],
['=TEXTJOIN(", ",TRUE,BYROW({1,2;3,4;5,6},LAMBDA(r,SUM(r))))', 'BYROW'],
['=LAMBDA(c,ROUND(c*9/5+32,1))(37)', 'inline LAMBDA'],
] },
{ group: 'Text', items: [
['=TEXTBEFORE("jane.doe@example.com","@")', 'TEXTBEFORE'],
['=TEXTAFTER("jane.doe@example.com","@")', 'TEXTAFTER'],
['=PROPER("the quick brown fox")', 'PROPER'],
['=TEXT(1234567.891,"#,##0.00")', 'number format'],
['=TEXT(0.256,"0.0%")', 'percent format'],
['=REGEXEXTRACT("order #4821 shipped","[0-9]+")', 'REGEXEXTRACT'],
['=TEXTJOIN(" | ",TRUE,TEXTSPLIT("red,green,blue",","))', 'TEXTSPLIT'],
] },
{ group: 'Dates', items: [
['=TEXT(DATE(2026,11,30),"dddd, mmmm d, yyyy")', 'date format'],
['=NETWORKDAYS(DATE(2026,12,1),DATE(2026,12,31))', 'working days'],
['=TEXT(EOMONTH(DATE(2026,2,10),0),"yyyy-mm-dd")', 'end of month'],
['=TEXT(EDATE(DATE(2026,1,31),1),"yyyy-mm-dd")', 'add a month'],
['=DATEDIF(DATE(1990,6,15),DATE(2026,11,30),"Y")', 'age in years'],
] },
{ group: 'Statistics', items: [
['=MEDIAN({3;8;1;9;4})', 'MEDIAN'],
['=ROUND(STDEV({2;4;4;4;5;5;7;9}),4)', 'STDEV'],
['=ROUND(CORREL({1;2;3;4},{2;4;5;8}),4)', 'CORREL'],
['=COUNTIF({"yes";"no";"yes";"yes"},"yes")', 'COUNTIF'],
['=AVERAGEIFS({10;20;30;40},{"a";"b";"a";"b"},"a")', 'AVERAGEIFS'],
['=SUMPRODUCT({2;3;5},{10;20;30})', 'SUMPRODUCT'],
] },
{ group: 'Logic', items: [
['=IFS(84>=90,"A",84>=80,"B",TRUE,"C")', 'IFS'],
['=SWITCH(WEEKDAY(DATE(2026,11,30)),1,"Sun",2,"Mon",3,"Tue","later")', 'SWITCH'],
['=IFERROR(1/0,"divide by zero caught")', 'IFERROR'],
] },
{ group: 'Math and engineering', items: [
['=POWER(2,10)', 'powers (no ^)'],
['=GCD(48,180)', 'GCD'],
['=DEC2HEX(48879)', 'hex'],
['=BIN2DEC("101010")', 'binary'],
['=ROMAN(2026)', 'roman numerals'],
['=BASE(255,2)', 'any base'],
] },
]

const DEMO_DEFAULT = [
'=ROUND(PMT(6%/12,360,-300000),2)',
'=XLOOKUP("gold",{"bronze";"silver";"gold"},{10;20;50})',
'=TEXTJOIN(", ",TRUE,SORT({"pear";"apple";"fig"}))',
'=LET(rate,6%/12,n,360,loan,300000,ROUND(PMT(rate,n,-loan),2))',
'=ROUND(IRR({-1000;300;400;500}),4)',
'=TEXT(DATE(2026,11,30),"dddd, mmmm d, yyyy")',
].join('\n')

const cmdBox = (text: string, prompt = '$') => `<div class="cmd"><span class="p mono">${prompt}</span><code>${esc(text)}</code><button class="copy" type="button" data-copy="${esc(text)}">Copy</button></div>`

const COPY_JS = `<script>document.addEventListener('click',e=>{const b=e.target.closest('[data-copy]');if(!b)return;navigator.clipboard.writeText(b.dataset.copy).then(()=>{const t=b.textContent;b.textContent='Copied';setTimeout(()=>b.textContent=t,1200)})})</script>`
Expand All @@ -105,21 +195,28 @@ export function homePage(cfg: Config): string {
${TERM}
</div>

<section id="demo" class="demo"><h2>Try it now</h2><p class="sub">One formula per line. This runs on the hosted engine (${L.anon.calls} free tries a day without a key).</p>
<form id="evalf"><textarea id="formulas" spellcheck="false" aria-label="Formulas">=PMT(5%/12,360,-300000)
=TEXTJOIN(", ",TRUE,"alpha","beta","gamma")
=XLOOKUP(3,{1,2,3},{"one","two","three"})
=ROUND(FV(5%/12,120,-200),2)
=POWER(2,10)</textarea>
<section id="demo" class="demo"><h2>Try it now</h2><p class="sub">One formula per line, or pick from the examples below. This runs on the hosted engine (${L.anon.calls} free tries a day without a key).</p>
<form id="askf" class="ask" toolname="sk33p_ask" tooldescription="Ask the sk33p AI for a spreadsheet formula"><input id="question" type="text" placeholder="Ask AI: monthly payment on a $300,000 loan at 6% for 30 years" aria-label="Ask AI for a formula" autocomplete="off"><button type="submit">Ask AI</button></form>
<p id="asknote" class="note">Ask writes the formula on the c0mpute network and checks it on the engine; it lands in the box below. Each ask is one call.</p>
<form id="evalf"><textarea id="formulas" spellcheck="false" aria-label="Formulas">${esc(DEMO_DEFAULT)}</textarea>
<div class="row"><button type="submit">Evaluate</button><span id="evalnote" class="note">No ^ operator in this engine: use POWER().</span></div></form>
<table id="evalout" hidden><tbody></tbody></table>
<div class="gallery">${EXAMPLES.map((g) => `<div class="ex"><h3>${esc(g.group)}</h3><div class="chips">${g.items.map(([f, label]) => `<button type="button" class="chip" data-f="${esc(f)}" title="${esc(f)}">${esc(label)}</button>`).join('')}</div></div>`).join('')}</div>
<script>
document.getElementById('evalf').addEventListener('submit',async e=>{e.preventDefault();const note=document.getElementById('evalnote'),t=document.getElementById('evalout'),tb=t.querySelector('tbody');
const fs=document.getElementById('formulas').value.split('\\n').map(s=>s.trim()).filter(Boolean);note.textContent='Running...';note.className='note';
const box=document.getElementById('formulas'),evalf=document.getElementById('evalf');
async function run(){const note=document.getElementById('evalnote'),t=document.getElementById('evalout'),tb=t.querySelector('tbody');
const fs=box.value.split('\\n').map(s=>s.trim()).filter(Boolean);note.textContent='Running...';note.className='note';
try{const r=await fetch('/api/v1/eval',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({formulas:fs})});const j=await r.json();
if(!r.ok){note.textContent=j.error+(j.next?' '+j.next.step+': '+j.next.web:'');note.className='note err';return}
tb.replaceChildren(...j.results.map(x=>{const tr=document.createElement('tr');const a=document.createElement('td');a.textContent=x.formula;const b=document.createElement('td');b.className='v';b.textContent=x.value;tr.append(a,b);return tr}));t.hidden=false;
note.textContent=(r.headers.get('x-sk33p-remaining')??'?')+' tries left today.'}catch(err){note.textContent='Could not reach the engine.';note.className='note err'}})
note.textContent=(r.headers.get('x-sk33p-remaining')??'?')+' tries left today.'}catch(err){note.textContent='Could not reach the engine.';note.className='note err'}}
evalf.addEventListener('submit',e=>{e.preventDefault();run()});
document.querySelectorAll('.chip').forEach(c=>c.addEventListener('click',()=>{box.value=c.dataset.f;run();box.scrollIntoView({behavior:'smooth',block:'center'})}));
document.getElementById('askf').addEventListener('submit',async e=>{e.preventDefault();const q=document.getElementById('question').value.trim(),note=document.getElementById('asknote');if(!q)return;
note.textContent='Asking c0mpute... (usually 20-60 seconds)';note.className='note';
try{const r=await fetch('/api/v1/ask',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({question:q})});const j=await r.json();
if(!r.ok){note.textContent=j.error+(j.next?' '+j.next.step+': '+j.next.web:'');note.className='note err';return}
box.value=j.formula+'\\n'+box.value;note.textContent=j.explanation+' = '+j.preview;run()}catch(err){note.textContent='Could not reach the engine.';note.className='note err'}});
</script></section>

<section><h2>One engine, four ways in</h2><p class="sub">The same calculation core everywhere: people in a terminal, agents over a socket.</p>
Expand Down
14 changes: 13 additions & 1 deletion cloud/test/app.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { describe, expect, test } from 'bun:test'
import { signWebhook } from '@profullstack/coinpay-onboard'
import { createApp, configFromEnv, type Config } from '../src/app.ts'
import { createApp, configFromEnv, callTool, DEFAULT_LIMITS, type Config } from '../src/app.ts'
import { EXAMPLES } from '../src/page.ts'
import { Store } from '../src/store.ts'
import { contextCells, parseAnswer, type AiFn, type AiRequest } from '../src/ask.ts'

Expand Down Expand Up @@ -151,6 +152,17 @@ describe('MCP', () => {
})
})

describe('showcase', () => {
test('every homepage example evaluates without an error', async () => {
const cfg = configFromEnv({ SK33P_BIN: BIN, SANDBOX: process.env.SANDBOX ?? '1' })
const formulas = EXAMPLES.flatMap((g) => g.items.map(([f]) => f))
expect(formulas.length).toBeGreaterThan(40)
const out: any = await callTool('eval', { formulas }, cfg, DEFAULT_LIMITS.pro)
const bad = out.results.filter((r: any) => !r.value || String(r.value).startsWith('#'))
expect(bad).toEqual([])
})
})

describe('pages', () => {
test('home, docs, llms.txt, ring descriptor, healthz', async () => {
const { req } = setup()
Expand Down
66 changes: 66 additions & 0 deletions patches/0002-match-index-excel-semantics.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
diff --git a/Libraries/SkSpreadSheet/source/SkFunctionSpreadSheet.cpp b/Libraries/SkSpreadSheet/source/SkFunctionSpreadSheet.cpp
index bd3d176..886a0c8 100644
--- a/Libraries/SkSpreadSheet/source/SkFunctionSpreadSheet.cpp
+++ b/Libraries/SkSpreadSheet/source/SkFunctionSpreadSheet.cpp
@@ -1166,6 +1166,11 @@ namespace SkSpreadSheet {
StackElemToIndex(wArgRow, wRow);
if (wArgRange.Type() == tStackType::t_Range) {
wRange=wArgRange.Range();
+ // Excel: on a single-row range the one index picks the column (sk33p patch 0003).
+ if (wRange!=nullptr && wRange->TopIndex()==wRange->IterateBottom() && wRange->IterateRight()>wRange->LeftIndex()) {
+ wCol=wRow;
+ wRow=1;
+ }
}
}
else {
@@ -1916,38 +1921,20 @@ namespace SkSpreadSheet {
}
}
} else if (wMatchTypeInt == 1) {
- // Greater or equal (ascending order)
- tIndex wSearchCol=wRange->LeftIndex();
+ // Excel: the largest value <= lookup_value in an ascending list (sk33p patch 0002).
+ // Scan along the range's long side: a single row is searched across its columns.
+ const tBool wHorizontal = wRange->TopIndex() == wRange->IterateBottom() && wRange->IterateRight() > wRange->LeftIndex();
+ const tIndex wCount = wHorizontal ? wRange->IterateRight() - wRange->LeftIndex() + 1 : wRange->IterateBottom() - wRange->TopIndex() + 1;
tIndex wLastMatch = 0;
- for(tIndex wRow=wRange->TopIndex();wRow<=wRange->IterateBottom();wRow++) {
- tCell* wCell=wColRowCellRange->Cell(wRow,wSearchCol);
- if (wCell!=nullptr) {
- tVariant wCellValue = wCell->Value();
- if (wCellValue >= wSearch) {
- wPosition = wRow - wRange->TopIndex() + 1; // 1-based position
- // Clean up arguments before returning
- return(tStackElem(tVariant(wPosition)));
- }
- wLastMatch = wRow - wRange->TopIndex() + 1;
- }
- }
- // Check columns if range is horizontal
- tIndex wSearchRow=wRange->TopIndex();
- for(tIndex wCol=wRange->LeftIndex();wCol<=wRange->IterateRight();wCol++) {
- tCell* wCell=wColRowCellRange->Cell(wSearchRow,wCol);
- if (wCell!=nullptr) {
- tVariant wCellValue = wCell->Value();
- if (wCellValue >= wSearch) {
- wPosition = wCol - wRange->LeftIndex() + 1; // 1-based position
- // Clean up arguments before returning
- return(tStackElem(tVariant(wPosition)));
- }
- wLastMatch = wCol - wRange->LeftIndex() + 1;
- }
+ for (tIndex wI = 0; wI < wCount; wI++) {
+ tCell* wCell = wHorizontal ? wColRowCellRange->Cell(wRange->TopIndex(), wRange->LeftIndex() + wI)
+ : wColRowCellRange->Cell(wRange->TopIndex() + wI, wRange->LeftIndex());
+ if (wCell == nullptr) continue;
+ tVariant wCellValue = wCell->Value();
+ if (wCellValue > wSearch) break; // ascending: nothing later can be <= lookup_value
+ wLastMatch = wI + 1; // 1-based position
}
- // Return last position if no exact match found
if (wLastMatch > 0) {
- // Clean up arguments before returning
return(tStackElem(tVariant(wLastMatch)));
}
} else if (wMatchTypeInt == -1) {
Loading
Loading