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
401 changes: 383 additions & 18 deletions agent/ask.test.ts

Large diffs are not rendered by default.

109 changes: 80 additions & 29 deletions agent/ask/answer.ts

Large diffs are not rendered by default.

35 changes: 35 additions & 0 deletions agent/ask/battery.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"note": "Acceptance battery: real-owner questions, including messy and off-script ones. Run with npm run ask:battery (one live model call per question). Target: at least 24 of 30 answered directly, zero false claims.",
"questions": [
"hi dave",
"how are you",
"how many pending invoices do I have",
"what's waiting",
"did beans get paid",
"why is milk blocked",
"how do I know if an invoice is fake",
"can I pay 1 NEAR now",
"what happened today",
"who did I pay most",
"is anything weird",
"how do I raise my limit",
"why isn't anything paying",
"hw many bills r blokced",
"wats my budget left",
"is my vault paused?",
"how much is in the vault",
"thanks dave",
"any problems with pastry co?",
"how many have been paid so far",
"why was INV-PASTRY-02-b52ef8a9 blocked?",
"how is my agent doing?",
"what are my current rules?",
"how do i pause payments",
"whats going on with my bills lol",
"can you pay milk for me",
"how much did i spend this week",
"is INV-BEANS-02-b52ef8a9 a duplicate?",
"yo dave whats up",
"what's the weather tomorrow"
]
}
3 changes: 2 additions & 1 deletion agent/ask/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ export async function askCommand(args:string[],directory:string):Promise<string>
// Developer aid only: say why an answer was discarded. The owner still sees the fixed line.
if(process.env.COUNTERSIGN_ASK_DEBUG){
if(!verdict.ok)console.error(`[ask debug] ${verdict.why}`);
else if(verdict.reply_dropped)console.error(`[ask debug] reply dropped: ${verdict.reply_dropped}`);
else if(verdict.reply_trimmed)console.error(`[ask debug] sentences cut: ${verdict.reply_trimmed}`);
else if(verdict.reply_dropped)console.error(`[ask debug] reply dropped: ${verdict.reply_dropped}`+(verdict.dropped_reply!==undefined?`\n[ask debug] dropped reply: ${JSON.stringify(verdict.dropped_reply)}`:''));
}
return verdict.text;
}
Expand Down
102 changes: 85 additions & 17 deletions agent/ask/help.ts

Large diffs are not rendered by default.

16 changes: 11 additions & 5 deletions agent/ask/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@ import {parseEnv} from 'node:util';
import {AskError} from './views.ts';

const ENDPOINT='https://cloud-api.near.ai/v1/chat/completions';
export const MAX_TOKENS=2000; // Reasoning models stall when the budget is small.
export const MAX_TOKENS=2000;
export const TIMEOUT_MS=30_000;
export const SLOW='Dave is slow right now. Try again in a moment.';
const timedOut=(error:unknown)=>(error as {name?:string})?.name==='TimeoutError'; // Reasoning models stall when the budget is small.
// NEAR AI honours reasoning_effort:'low' (reasoning drops to ~1 token); 'none',
// enable_thinking and thinking:{type:'disabled'} are ignored. Ask Dave only selects
// evidence and writes a short reply, so it does not need long reasoning.
export type ChatMessage={role:'system'|'user';content:string};
export type Complete=(messages:ChatMessage[])=>Promise<string>;

Expand All @@ -22,17 +28,17 @@ export function nearChat(config:{apiKey:string;model:string},send:typeof fetch=f
return async messages=>{
let response:Response;
try{
response=await send(ENDPOINT,{method:'POST',redirect:'error',signal:AbortSignal.timeout(90_000),
response=await send(ENDPOINT,{method:'POST',redirect:'error',signal:AbortSignal.timeout(TIMEOUT_MS),
headers:{Authorization:`Bearer ${apiKey}`,'Content-Type':'application/json'},
body:JSON.stringify({model,stream:false,max_tokens:MAX_TOKENS,temperature:0,messages})});
}catch{throw new AskError('Ask Dave: the model request failed.');}
body:JSON.stringify({model,stream:false,max_tokens:MAX_TOKENS,temperature:0,reasoning_effort:'low',messages})});
}catch(error){throw new AskError(timedOut(error)?SLOW:'Ask Dave: the model request failed.');}
if(!response.ok){await response.body?.cancel();throw new AskError(`Ask Dave: the model request failed (HTTP ${response.status}).`);}
let body:any;
try{
const text=await response.text();
if(text.length>262144)throw Error('oversized');
body=JSON.parse(text);
}catch{throw new AskError('Ask Dave: the model reply was unreadable.');}
}catch(error){throw new AskError(timedOut(error)?SLOW:'Ask Dave: the model reply was unreadable.');}
const content=body?.choices?.[0]?.message?.content;
// Truncated or empty output is handed on as-is and fails the answer check.
return typeof content==='string'?content:'';
Expand Down
275 changes: 270 additions & 5 deletions agent/ask/voice.ts

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions integration/ask-facts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,10 +147,10 @@ test('facts pack matches a fresh café run: paid, tampered, duplicate, over-budg
const spoken='Yes — 3 payments of 0.1 NEAR fit in the 0.3 NEAR left in your rolling 24-hour budget. The budget is the limit; your vault holds 4.5 NEAR.';
const fit=await askQuestion(pack,'Can I afford .1 NEAR payments?',async messages=>{
const evidence=JSON.parse(messages[1].content.split('\n')[1]);
assert.ok(evidence.fit.text.startsWith('3 payments of 0.1 NEAR fit'));
assert.ok(evidence.fit.text.startsWith('Today you can still pay 3 more bills of 0.1 NEAR.'));
return JSON.stringify({facts:['fit'],reply:spoken});
});
assert.ok(fit.text.startsWith(spoken+'\n\n3 payments of 0.1 NEAR fit'));
assert.ok(fit.text.startsWith(spoken+'\n\nToday you can still pay 3 more bills of 0.1 NEAR. Your daily budget (0.3 NEAR left) runs out before your vault (4.5 NEAR) does.'));
assert.ok(!('reply_dropped' in fit));
const negative=await askQuestion(pack,'Can I afford -.1 NEAR payments?',async()=>JSON.stringify({facts:['fit'],reply:spoken}));
assert.ok(negative.text.startsWith('Please enter a positive NEAR amount'));
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"test:ask": "node --disable-warning=ExperimentalWarning --test agent/ask.test.ts",
"test:ask:sandbox": "node --disable-warning=ExperimentalWarning --test integration/ask-facts.test.ts",
"agent:desk": "node --disable-warning=ExperimentalWarning agent/desk.ts",
"ask:battery": "node --disable-warning=ExperimentalWarning scripts/ask-battery.ts",
"test:inbox:sandbox": "node --disable-warning=ExperimentalWarning --test integration/inbox.test.ts",
"agent:demo": "node --disable-warning=ExperimentalWarning agent/demo.ts",
"test:restart": "node --disable-warning=ExperimentalWarning integration/restart.mjs",
Expand Down
43 changes: 43 additions & 0 deletions scripts/ask-battery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Ask Dave acceptance battery: every question in agent/ask/battery.json, one live
// model call each, against the local agent vault. Read-only, like ask "<question>".
// Prints question -> direct (verified reply shown) / facts only / refused / error, with time.
import {readFileSync,writeFileSync} from 'node:fs';
import {fileURLToPath} from 'node:url';
import {NO_RECORD,askQuestion,REFUSAL} from '../agent/ask/answer.ts';
import {collectFacts} from '../agent/ask/facts.ts';
import {modelConfig,nearChat} from '../agent/ask/model.ts';

if(process.env.ASK_BATTERY!=='1')throw new Error('Set ASK_BATTERY=1 to run the live Ask Dave battery.');

const root=fileURLToPath(new URL('..',import.meta.url));
const directory=process.env.COUNTERSIGN_AGENT_DIR??root+'work/agent-vault/';
const {questions}=JSON.parse(readFileSync(new URL('../agent/ask/battery.json',import.meta.url),'utf8')) as {questions:string[]};
const model=nearChat(modelConfig());
const raw:Record<string,string>={};
let current='';
const complete:typeof model=async messages=>(raw[current]=await model(messages));
const rows:{q:string;result:string;ms:number;shown:string;why:string}[]=[];
for(const q of questions){
const start=Date.now();current=q;
let result:string,shown='',why='';
try{
const v=await askQuestion(await collectFacts(directory),q,complete);
if(!v.ok){result='error';why=v.why;}
else if(v.text===REFUSAL){result=v.reply_dropped?'refused (chat reply dropped)':'refused';why=v.reply_dropped??'';shown=v.dropped_reply??'';}
else if(v.text===NO_RECORD)result='no record';
else if(v.reply_dropped){result='facts only';why=v.reply_dropped;shown=v.dropped_reply??'';}
else if(v.reply_trimmed){result='direct (trimmed)';shown=v.text.split('\n\n')[0];why=v.reply_trimmed;}
else if(!v.sources.length&&!v.text.includes('\nSources: ')){result='direct';shown=v.text;} // small talk
else if(v.text.includes('\n\n')){result='direct';shown=v.text.split('\n\n')[0];}
else result='facts only';
}catch(error){result='error';why=String((error as Error).message??error);}
rows.push({q,result,ms:Date.now()-start,shown,why});
console.error(`${rows.length}/${questions.length} ${result} ${((Date.now()-start)/1000).toFixed(1)}s ${q}`);
}
const cell=(s:string)=>s.replace(/\|/g,'\\|').replace(/\n/g,' ');
console.log('| # | Question | Result | Time | Reply (shown, or dropped) |\n|---|---|---|---|---|');
rows.forEach((r,i)=>console.log(`| ${i+1} | ${cell(r.q)} | ${r.result} | ${(r.ms/1000).toFixed(1)} s | ${cell(r.shown||r.why)} |`));
// The raw model selections, so a dropped reply can be re-checked offline without another model call.
writeFileSync(new URL('../work/ask-battery-last.json',import.meta.url),JSON.stringify(rows.map(r=>({...r,raw:raw[r.q]})),null,1));
const direct=rows.filter(r=>r.result.startsWith('direct')).length;
console.log(`\nAnswered directly: ${direct}/${rows.length}. Median time: ${(rows.map(r=>r.ms).sort((a,b)=>a-b)[Math.floor(rows.length/2)]/1000).toFixed(1)} s.`);
Loading