@buoy-gg/agent-core 7.0.61 → 7.0.63
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/commonjs/blocks/receipts.js +1 -1
- package/lib/commonjs/catalog/catalog.g.js +2 -2
- package/lib/commonjs/catalog/catalog.source.json +13 -1
- package/lib/commonjs/catalog/catalog.types.g.js +1 -1
- package/lib/commonjs/catalog/snapshotReads.js +1 -1
- package/lib/commonjs/context/buildContextPack.js +1 -1
- package/lib/commonjs/engine/emptyTap.test.js +1 -0
- package/lib/commonjs/engine/idGrounding.js +2 -0
- package/lib/commonjs/engine/planOnlyStop.js +1 -1
- package/lib/commonjs/engine/runAgentTurn.js +9 -7
- package/lib/commonjs/engine/systemPrompt.js +3 -1
- package/lib/commonjs/engine/verify.js +1 -1
- package/lib/commonjs/policy/policy.js +1 -1
- package/lib/commonjs/policy/redact.js +1 -1
- package/lib/commonjs/policy/turnScope.js +1 -0
- package/lib/commonjs/providers/anthropic.js +1 -1
- package/lib/commonjs/providers/openai.js +3 -3
- package/lib/module/blocks/receipts.js +1 -1
- package/lib/module/catalog/catalog.g.js +2 -2
- package/lib/module/catalog/catalog.source.json +13 -1
- package/lib/module/catalog/catalog.types.g.js +1 -1
- package/lib/module/catalog/snapshotReads.js +1 -1
- package/lib/module/context/buildContextPack.js +1 -1
- package/lib/module/engine/emptyTap.test.js +1 -0
- package/lib/module/engine/idGrounding.js +2 -0
- package/lib/module/engine/planOnlyStop.js +1 -1
- package/lib/module/engine/runAgentTurn.js +9 -7
- package/lib/module/engine/systemPrompt.js +3 -1
- package/lib/module/engine/verify.js +1 -1
- package/lib/module/policy/policy.js +1 -1
- package/lib/module/policy/redact.js +1 -1
- package/lib/module/policy/turnScope.js +1 -0
- package/lib/module/providers/anthropic.js +2 -2
- package/lib/module/providers/openai.js +3 -3
- package/lib/typescript/catalog/catalog.g.d.ts +2 -2
- package/lib/typescript/catalog/catalog.types.g.d.ts +2 -2
- package/lib/typescript/engine/emptyTap.test.d.ts +2 -0
- package/lib/typescript/engine/idGrounding.d.ts +7 -0
- package/lib/typescript/engine/planOnlyStop.d.ts +2 -2
- package/lib/typescript/engine/systemPrompt.d.ts +1 -1
- package/lib/typescript/policy/policy.d.ts +8 -3
- package/lib/typescript/policy/redact.d.ts +1 -0
- package/lib/typescript/policy/turnScope.d.ts +13 -0
- package/lib/typescript/providers/types.d.ts +1 -0
- package/lib/web/index.mjs +44 -36
- package/package.json +1 -1
|
@@ -831,8 +831,20 @@
|
|
|
831
831
|
{
|
|
832
832
|
"toolId": "impersonate",
|
|
833
833
|
"title": "Impersonate",
|
|
834
|
-
"summary": "Become another user inside the running app without logging out: it injects an impersonation header (default `x-impersonate-user-id: <user.id>`) into every outgoing globalThis.fetch and XMLHttpRequest, so the backend returns that user's data. Reach for it to reproduce a specific customer's bug (\"show me what account 8812 sees\"), then stop/pause to return to the real login.
|
|
834
|
+
"summary": "Become another user inside the running app without logging out: it injects an impersonation header (default `x-impersonate-user-id: <user.id>`) into every outgoing globalThis.fetch and XMLHttpRequest, so the backend returns that user's data. Reach for it to reproduce a specific customer's bug (\"show me what account 8812 sees\"), then stop/pause to return to the real login. Read impersonate.getSnapshot to check the switch. It shows isActive, isPaused, currentUser, and history. Note that switching or stopping also CLEARS app caches per dataNukeSettings (react-query + redux on by default), so it is not a passive read-only view.",
|
|
835
835
|
"actions": [
|
|
836
|
+
{
|
|
837
|
+
"action": "getSnapshot",
|
|
838
|
+
"summary": "Read the user, pause state, and past users. Read settings too.",
|
|
839
|
+
"description": "Returns isActive, isPaused, currentUser, headerKey, ignorePatterns, dataNukeSettings, showBanner, and history. Users have id, displayName, and email. Each history row has user and lastUsedAt. Settings show what should clear, not proof it cleared.",
|
|
840
|
+
"params": {
|
|
841
|
+
"type": "object",
|
|
842
|
+
"properties": {},
|
|
843
|
+
"additionalProperties": false
|
|
844
|
+
},
|
|
845
|
+
"effect": "read",
|
|
846
|
+
"release": "works"
|
|
847
|
+
},
|
|
836
848
|
{
|
|
837
849
|
"action": "searchUsers",
|
|
838
850
|
"summary": "Search the app's own user directory and get back User objects you can feed to startImpersonation.",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";export const CATALOG_ACTIONS={"env":["getSnapshot"],"console":["getSnapshot","clearEntries"],"sentry":["getSnapshot","clearEnvelopes"],"jotai":["getSnapshot","listAtoms","getAtomValue","getChangeDetail","setAtom","clearEvents"],"route-events":["getSnapshot","getCurrentRoute","navigate","stackGoBack","stackNavigateToIndex","stackPopToIndex","stackPopToTop","clearEvents"],"debug-borders":["cycleMode","setMode"],"zustand":["getSnapshot","listStores","getStoreState","getChangeDetail","setState","rehydrate","clearEvents"],"redux":["getSnapshot","getState","getActionDetail","dispatch","setState","clearEvents"],"impersonate":["searchUsers","startImpersonation","stopImpersonation","pauseImpersonation","resumeImpersonation","updateSettings","removeFromHistory","clearHistory"],"query":["listQueries","getQueryData","refetch","invalidate","reset","remove","setQueryData","triggerError","restoreError","triggerLoading","restoreLoading","clearQueryCache","clearMutationCache","setOnline"],"events":["exportEvents","setEnabledSources","clearEvents"],"network":["getSnapshot","getCaptureStatus","getEventBody","setPinned","setSaved","removeSavedRecord","clearSavedRequests","clearPinnedRequests","clearEvents","listOverrideRules","getOverrideRuleBody","debugOverrides","upsertOverrideRule","setOverrideRuleEnabled","setOverridesEnabled","deleteOverrideRule","clearOverrideRules","getNetworkConditions","setNetworkConditions"],"js-top":["sample","getOriginDetail","setEnabled","pause","resume","clear"],"app":["ping","reloadApp"],"time-machine":["list","capture","captureBaseline","wipeAll","restore","preview","inspect","delete","rename","duplicate","setExclusions","setScope","setRestoreRoute"],"clock":["getState","setTime","shift","freeze","resume","setRate","reset","updateSettings","jumpToTokenExpiry","failNextRequest","stopTokenCheck"],"lifecycle":["getState","background","interrupt","returnToApp","memoryWarning","openUrl","pressBack","setColorScheme","setPower","resetPower","relaunch","runRecipe","clearReport","reset"],"location":["getState","setLocation","startRoute","pauseRoute","resumeRoute","stopRoute","seekRoute","setSpeed","enterRegion","exitRegion","setConditions","setSignal","setServices","tune","useRealLocation","reset","updateSettings","clearLog"],"permissions":["getState","setOverride","clearOverride","resetAll","requestReal","updateSettings","simulateReturnFromSettings","clearLog"],"storage":["getSnapshot","getRequiredKeys","async.getAllKeys","async.multiGet","async.getItem","async.setItem","async.removeItem","async.multiRemove","async.multiSet","async.clear","clearAppStorage","getEventDetail","clearEvents","timeTravel.undo","timeTravel.jump","mmkv.snapshot","mmkv.get","mmkv.set","mmkv.remove","secure.keys","secure.snapshot","secure.get","secure.set","secure.delete"],"highlight-updates":["describeScreen","tapElement","waitFor","beginMeasurement","endMeasurement","locateComponent","getRenderDetail","setEnabled","toggle","setSilentTracking","toggleFreeze","setSpotlight","clearRenderCounts","startTouchCapture","stopTouchCapture","clearTouchCapture","readTouchCapture"],"scenarios":["listScenarios","getScenario","save","acceptDraft","discardDraft","preview","run","deactivate","delete","setFolder","listFolders","getActive","export"],"perf-monitor":["setEnabled","startRecording","stopRecording","savePending","discardPending","mark","startAutomation","cancelAutomation","acknowledgeAutomation","refreshIndex","getAutomationConfig","setAutomationConfig","loadReport","deleteReport","deleteBatch","clearAll"],"assets":["list","getDetail","rescan","measureSizes","saveBaseline","clearBaseline","getDiff","clearRecords","getScanStatus"],"tv-remote":["arm","getEventsSince","setMenuCapture","disarm","clear"],"focus-inspector":["rescan","focusElement","setTracking","clearHistory"],"images":["list","getDetail","getCaptureStatus","retry","flash","proveSavings","setOverride","clearOverride","setNetworkMode","setBlankImages","hardReload","evictDisk","massAction","clearRecords","clearExpoCaches"],"ask-buoy":["listChanges","undoChange","undoAll","retrieve","openProcedure"],"push-notifications":["getSnapshot","getCapabilities","getEvent","getPermissions","listPresented","refreshToken","setCaptureSession","clearCapturedEvents","scheduleLocal"],"image-overlay":["getSnapshot","listTargets","selectTarget","loadImage","setSettings","fitToScreen","resetSettings","remove"]};
|
|
1
|
+
"use strict";export const CATALOG_ACTIONS={"env":["getSnapshot"],"console":["getSnapshot","clearEntries"],"sentry":["getSnapshot","clearEnvelopes"],"jotai":["getSnapshot","listAtoms","getAtomValue","getChangeDetail","setAtom","clearEvents"],"route-events":["getSnapshot","getCurrentRoute","navigate","stackGoBack","stackNavigateToIndex","stackPopToIndex","stackPopToTop","clearEvents"],"debug-borders":["cycleMode","setMode"],"zustand":["getSnapshot","listStores","getStoreState","getChangeDetail","setState","rehydrate","clearEvents"],"redux":["getSnapshot","getState","getActionDetail","dispatch","setState","clearEvents"],"impersonate":["getSnapshot","searchUsers","startImpersonation","stopImpersonation","pauseImpersonation","resumeImpersonation","updateSettings","removeFromHistory","clearHistory"],"query":["listQueries","getQueryData","refetch","invalidate","reset","remove","setQueryData","triggerError","restoreError","triggerLoading","restoreLoading","clearQueryCache","clearMutationCache","setOnline"],"events":["exportEvents","setEnabledSources","clearEvents"],"network":["getSnapshot","getCaptureStatus","getEventBody","setPinned","setSaved","removeSavedRecord","clearSavedRequests","clearPinnedRequests","clearEvents","listOverrideRules","getOverrideRuleBody","debugOverrides","upsertOverrideRule","setOverrideRuleEnabled","setOverridesEnabled","deleteOverrideRule","clearOverrideRules","getNetworkConditions","setNetworkConditions"],"js-top":["sample","getOriginDetail","setEnabled","pause","resume","clear"],"app":["ping","reloadApp"],"time-machine":["list","capture","captureBaseline","wipeAll","restore","preview","inspect","delete","rename","duplicate","setExclusions","setScope","setRestoreRoute"],"clock":["getState","setTime","shift","freeze","resume","setRate","reset","updateSettings","jumpToTokenExpiry","failNextRequest","stopTokenCheck"],"lifecycle":["getState","background","interrupt","returnToApp","memoryWarning","openUrl","pressBack","setColorScheme","setPower","resetPower","relaunch","runRecipe","clearReport","reset"],"location":["getState","setLocation","startRoute","pauseRoute","resumeRoute","stopRoute","seekRoute","setSpeed","enterRegion","exitRegion","setConditions","setSignal","setServices","tune","useRealLocation","reset","updateSettings","clearLog"],"permissions":["getState","setOverride","clearOverride","resetAll","requestReal","updateSettings","simulateReturnFromSettings","clearLog"],"storage":["getSnapshot","getRequiredKeys","async.getAllKeys","async.multiGet","async.getItem","async.setItem","async.removeItem","async.multiRemove","async.multiSet","async.clear","clearAppStorage","getEventDetail","clearEvents","timeTravel.undo","timeTravel.jump","mmkv.snapshot","mmkv.get","mmkv.set","mmkv.remove","secure.keys","secure.snapshot","secure.get","secure.set","secure.delete"],"highlight-updates":["describeScreen","tapElement","waitFor","beginMeasurement","endMeasurement","locateComponent","getRenderDetail","setEnabled","toggle","setSilentTracking","toggleFreeze","setSpotlight","clearRenderCounts","startTouchCapture","stopTouchCapture","clearTouchCapture","readTouchCapture"],"scenarios":["listScenarios","getScenario","save","acceptDraft","discardDraft","preview","run","deactivate","delete","setFolder","listFolders","getActive","export"],"perf-monitor":["setEnabled","startRecording","stopRecording","savePending","discardPending","mark","startAutomation","cancelAutomation","acknowledgeAutomation","refreshIndex","getAutomationConfig","setAutomationConfig","loadReport","deleteReport","deleteBatch","clearAll"],"assets":["list","getDetail","rescan","measureSizes","saveBaseline","clearBaseline","getDiff","clearRecords","getScanStatus"],"tv-remote":["arm","getEventsSince","setMenuCapture","disarm","clear"],"focus-inspector":["rescan","focusElement","setTracking","clearHistory"],"images":["list","getDetail","getCaptureStatus","retry","flash","proveSavings","setOverride","clearOverride","setNetworkMode","setBlankImages","hardReload","evictDisk","massAction","clearRecords","clearExpoCaches"],"ask-buoy":["listChanges","undoChange","undoAll","retrieve","openProcedure"],"push-notifications":["getSnapshot","getCapabilities","getEvent","getPermissions","listPresented","refreshToken","setCaptureSession","clearCapturedEvents","scheduleLocal"],"image-overlay":["getSnapshot","listTargets","selectTarget","loadImage","setSettings","fitToScreen","resetSettings","remove"]};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{isSelfTraffic as
|
|
1
|
+
"use strict";import{isSecretKey as L,isSelfTraffic as A,redact as O}from"../policy/redact";export const SNAPSHOT_ACTION="getSnapshot";const C={verbose:0,debug:0,trace:0,log:1,info:1,warn:2,warning:2,error:3};function p(a){return Array.isArray(a)?a:[]}function d(a){return a&&typeof a==="object"?a:{}}function w(a,t){return typeof a==="number"&&a>0?a:t}function v(a,t){const s=o=>{const r=d(o).timestamp;const u=typeof r==="number"?r:typeof r==="string"?Date.parse(r):NaN;return Number.isFinite(u)?u:0};return[...a].sort((o,r)=>s(r)-s(o)).slice(0,t)}function k(a,t){const s=[];for(const o of a){const r=JSON.stringify(o).length+1;if(r>t)continue;s.push(o);t-=r}return s}function P(a,t){const s=p(d(a).entries);const o=typeof t.level==="string"?C[t.level]??0:0;const r=typeof t.pattern==="string"?t.pattern.toLowerCase():void 0;const u=s.filter(l=>{const e=d(l);const i=String(e.level??"log");if((C[i]??1)<o)return false;if(!r)return true;return String(e.message??"").toLowerCase().includes(r)});const n=v(u,w(t.limit,40));return{totalCaptured:s.length,shown:n.length,entries:n.map(l=>{const e=d(l);return{at:e.timestamp,level:e.level,message:e.message}})}}function R(a,t){const s=d(a);const o=p(s.events).filter(e=>!A(d(e).url));const r=t.failedOnly===true;const u=typeof t.pattern==="string"?t.pattern.toLowerCase():void 0;const n=o.filter(e=>{const i=d(e);const c=typeof i.status==="number"?i.status:void 0;if(r&&!(i.error||c!==void 0&&c>=400))return false;if(!u)return true;return String(i.url??"").toLowerCase().includes(u)});const l=v(n,w(t.limit,25));return{totalCaptured:o.length,shown:l.length,requests:l.map(e=>{const i=d(e);return{id:i.id,at:i.timestamp,method:i.method,url:i.url,status:i.status,durationMs:i.duration,error:i.error,overridden:i.override?true:void 0}}),hint:"Read one response with network.getEventBody({ id })."}}function g(a){const t=Object.entries(d(a)).slice(0,6).map(([s,o])=>{const r=typeof o==="string"||typeof o==="number"||typeof o==="boolean";const u=r&&String(o).length<=48&&!L(s,"route");return[s.slice(0,48),u?O(o):"(value omitted)"]});return t.length?Object.fromEntries(t):void 0}function $(a,t,s=80){const o=new Map;for(const i of t.slice(0,160)){if(typeof i.pathname!=="string")continue;const c=g(i.params);if(c)o.set(i.pathname,{...c,...o.get(i.pathname)})}const r=[];const u=new Set;let n=3e3;const l=(i,c=[])=>{if(r.length>=s||u.has(i))return;u.add(i);const y=o.get(i)??{};const f=[...new Set([...Object.keys(y),...p(c).filter(h=>typeof h==="string")])].slice(0,6).map(h=>{const S=y[h];return S===void 0||S==="(value omitted)"?h.slice(0,48):`${h}=${String(S)}`});const b=f.every(h=>Object.keys(y).some(S=>h===S||h.startsWith(`${S}=`)))?"params seen":"params";const m=f.length?` (${b}: ${f.join(", ")})`:"";const N=m.length<=n;if(N)n-=m.length;r.push(i+(N?m:""))};const e=(i,c=0)=>{if(c>12)return;for(const y of p(i)){if(r.length>=s)break;const f=d(y);if(f.isInternal!==true&&typeof f.path==="string")l(f.path,f.params);e(f.children,c+1)}};e(a);for(const i of o.keys())l(i);return r}function B(a,t){const s=n=>typeof n==="string"&&n.length>300?`${n.slice(0,300)}\u2026`:n;const o=typeof t.key==="string"?t.key.toLowerCase():void 0;const r=p(a).map(d).map(n=>{const l=d(n.data);return{id:n.id,at:n.timestamp,action:n.action,storage:n.storageType,key:l.key??l.keys,value:s(l.value),prevValue:s(l.prevValue)}}).filter(n=>!o||JSON.stringify(n.key??"").toLowerCase().includes(o)).sort((n,l)=>String(l.at).localeCompare(String(n.at)));const u=w(t.limit,20);return{events:r.slice(0,u),total:r.length,returned:Math.min(u,r.length)}}function E(a,t){const s=n=>{if(n===void 0)return void 0;const l=typeof n==="string"?n:JSON.stringify(n);return l&&l.length>400?`${l.slice(0,400)}\u2026`:n};const o=typeof t.type==="string"?t.type.toLowerCase():void 0;const r=p(a).map(d).filter(n=>n.category!=="internal").map(n=>({id:n.id,at:n.timestamp,type:n.type,payload:s(n.payload),meta:s(n.meta),error:s(n.error),changed:n.diffSummary||void 0})).filter(n=>!o||String(n.type).toLowerCase().includes(o)).sort((n,l)=>Number(l.at)-Number(n.at));const u=w(t.limit,20);return{actions:r.slice(0,u),total:r.length,returned:Math.min(u,r.length)}}function j(a,t,s,o){const r=e=>{if(e===void 0)return void 0;const i=typeof e==="string"?e:JSON.stringify(e);return i&&i.length>400?`${i.slice(0,400)}\u2026`:e};const u=typeof t[o]==="string"?String(t[o]).toLowerCase():void 0;const n=p(d(a).changes).map(d).map(e=>({id:e.id,at:e.timestamp,[o]:e[s],changed:e.changedKeys,summary:e.diffSummary||void 0,...s==="storeName"?{partial:r(e.partial)}:{value:r(e.valuePreview)}})).filter(e=>!u||String(e[o]??"").toLowerCase().includes(u)).sort((e,i)=>Number(i.at)-Number(e.at));const l=w(t.limit,20);return{changes:n.slice(0,l),total:n.length,returned:Math.min(l,n.length)}}function x(a,t){const s=d(a);const o=d(s.sitemap);const r=p(s.stack).map(d);const u=p(s.events).map(d);const n=r.map(c=>({name:c.name,path:c.pathname,...g(c.params)?{params:g(c.params)}:{},focused:c.isFocused===true?true:void 0}));const l=u.slice(0,w(t.limit,15)).map(c=>({at:c.timestamp,from:c.previousPathname,to:c.pathname,...g(c.params)?{params:g(c.params)}:{}}));const e=r.find(c=>c.isFocused===true)??r[r.length-1];const i=u.length?{path:u[0].pathname,source:"event",...g(u[0].params)?{params:g(u[0].params)}:{}}:typeof e?.pathname==="string"?{path:e.pathname,source:"stack",...g(e.params)?{params:g(e.params)}:{}}:void 0;return{currentRoute:i,stack:n,routes:$(o.routes,[...u.slice(0,80),...r.slice(0,80)]),sitemapSource:o.source,recentNavigations:l}}function F(a){const t=d(a);return{env:t.env??t.variables,requiredEnvVars:t.requiredEnvVars,...Array.isArray(t.checks)?{checks:t.checks}:{}}}function I(a,t){const s=d(a);const o=p(s.envelopes).map(d);const r=typeof t.type==="string"?t.type:void 0;const u=typeof t.pattern==="string"?t.pattern.toLowerCase():void 0;const n=o.filter(e=>{const i=p(e.items).map(d);if(r&&!i.some(c=>c.type===r))return false;if(!u)return true;return i.some(c=>String(c.summary??"").toLowerCase().includes(u))});const l=k(v(n,w(t.limit,10)).map(e=>({id:e.id,at:e.timestamp,origin:e.origin,eventId:e.eventId,totalBytes:e.totalBytes,items:p(e.items).slice(0,8).map(i=>{const c=d(i);return{type:c.type,summary:typeof c.summary==="string"?c.summary.slice(0,300):c.summary,spanCount:c.spanCount,bytes:c.bytes}})})),12e3);return{status:s.status,totalCaptured:o.length,shown:l.length,envelopes:l,drops:(()=>{const e=d(s.drops);const i=p(e.recent).map(d);const c=m=>m.category==="span"||m.category==="transaction";const y=[...v(i.filter(m=>!c(m)),8),...v(i.filter(c),3)];const f=k(y.map(m=>({at:m.timestamp,reason:m.reason,category:m.category,quantity:m.quantity,detail:typeof m.detail==="string"?m.detail.slice(0,200):m.detail})),4e3);const b=k(p(e.summary),2e3);return f.length||e.summary?{summary:b,recent:f}:void 0})(),hint:"For crash stack traces, console's [FATAL] entries carry the component stacks. `drops` lists events the SDK discarded before sending, with the reason."}}function T(a){const t=d(a);const s=o=>{if(o===null||o===void 0)return null;const r=d(o);return{id:r.id,displayName:r.displayName,email:r.email}};return{isActive:t.isActive,isPaused:t.isPaused,currentUser:s(t.currentUser),headerKey:t.headerKey,ignorePatterns:t.ignorePatterns,dataNukeSettings:t.dataNukeSettings,showBanner:t.showBanner,history:p(t.history).slice(0,10).map(o=>{const r=d(o);return{user:s(r.user),lastUsedAt:r.lastUsedAt}})}}export function projectSnapshot(a,t,s={}){switch(a){case"console":return P(t,s);case"network":return R(t,s);case"route-events":return x(t,s);case"storage":return B(t,s);case"redux":return E(t,s);case"zustand":return j(t,s,"storeName","store");case"jotai":return j(t,s,"atomLabel","atom");case"env":return F(t);case"impersonate":return T(t);case"sentry":return I(t,s);default:return t}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{projectSnapshot as
|
|
1
|
+
"use strict";import{projectSnapshot as b,SNAPSHOT_ACTION as p}from"../catalog/snapshotReads";import{realNow as k,realSetTimeout as E}from"../realNow";const T=2500;const f=t=>Array.isArray(t)?t:Array.isArray(t?.items)?t.items:[];const a=t=>t&&typeof t==="object"?t:{};const _=(t,e,n=40)=>f(t).slice(0,n).map(s=>{if(!s||typeof s!=="object")return s;const i=s;for(const o of e){if(i[o]!==void 0)return i[o]}return i.id??i.name??i.key});const w=30;const O=24;const P=8;const R=240;const C=12e3;const L=(t,e)=>t.length<=e?t:`${t.slice(0,e-1)}\u2026`;function j(t){const e=new Map;if(typeof t!=="string"||!t.startsWith("{"))return e;let n=0;let s="";const i=()=>{const o=s.indexOf(":");if(o>0)e.set(s.slice(0,o).trim(),s.slice(o+1).trim());s=""};for(const o of t.slice(1,-1)){if(o==="{"||o==="["||o==="(")n++;else if(o==="}"||o==="]"||o===")")n--;if(o===","&&n===0)i();else s+=o}i();return e}const N=[{key:"routes",toolId:"route-events",action:p,shape:t=>f(t?.routes).slice(0,60)},{key:"reduxSlices",toolId:"redux",action:"getState",params:{includeValues:false},shape:t=>{const e=a(t);if(e.available===false)return void 0;const n=a(e.sliceFields);if(Array.isArray(e.slices))return e.slices.slice(0,40).map(s=>Array.isArray(n[String(s)])&&n[String(s)].length?`${String(s)}: ${n[String(s)].join(", ")}`:s);return e.state&&typeof e.state==="object"?Object.keys(e.state).slice(0,40):void 0}},{key:"zustandStores",toolId:"zustand",action:"listStores",shape:t=>{let e=0;return f(t?.stores??t).slice(0,w).map(n=>{const s=n??{};const i=typeof s.name==="string"?s.name:s.id;const o=f(s.shape?.lists).map(a);const l={};const d=[];for(const r of o.slice(0,P)){const c=typeof r.path==="string"?r.path:void 0;if(!c)continue;if(c.includes("[]."))continue;if(typeof r.item!=="string"){d.push(c);continue}const u=L(r.item,R);if(e+u.length>C)continue;e+=u.length;l[c]=u}return{name:i,...typeof s.persistName==="string"?{persistsTo:s.persistName}:{},...(()=>{if(!Array.isArray(s.keys)||!s.keys.length)return{};const r=j(s.shape?.shape);const c=s.keys.filter(u=>r.get(String(u))!=="function");return c.length?{keys:c.slice(0,O)}:{}})(),...Object.keys(l).length?{listItemShapes:l}:{},...d.length?{unknownLists:d}:{}}})}},{key:"jotaiAtoms",toolId:"jotai",action:"listAtoms",shape:t=>_(a(t).atoms??t,["debugLabel","label","id"],40)},{key:"storageKeys",toolId:"storage",action:"async.getAllKeys",shape:t=>f(t).slice(0,60)},{key:"env",toolId:"env",action:p,shape:t=>{const e=t?.env;return e&&typeof e==="object"?Object.keys(e).slice(0,40):void 0}}];const I=25;const x=I*2;const D=8;function M(t){const e=typeof t==="number"?t:typeof t==="string"?Date.parse(t):NaN;return Number.isFinite(e)?{age:`${Math.max(0,Math.floor((k()-e)/1e3))}s ago`}:{}}const B=[{key:"currentRoute",toolId:"route-events",action:"getCurrentRoute",shape:t=>{const e=a(t);if(typeof e.path!=="string")return void 0;return e.params&&Object.keys(a(e.params)).length?{path:e.path,params:e.params}:{path:e.path}}},{key:"queries",toolId:"query",action:"listQueries",params:{limit:x},shape:t=>{const e=f(t?.queries??t).map(a);const n=e.map(s=>{const i=typeof s.observers==="number"?s.observers:0;return{key:s.queryKey??s.queryHash,status:s.status,...i>0?{onScreen:true,observers:i}:{}}});n.sort((s,i)=>Number(Boolean(i.onScreen))-Number(Boolean(s.onScreen)));return n.slice(0,I)}},{key:"networkCapture",toolId:"network",action:"getCaptureStatus",shape:t=>{const e=a(t);if(typeof e.capturing!=="boolean")return void 0;return{recording:e.capturing,...e.interceptorLive===false?{interceptorLive:false}:{},captured:typeof e.eventCount==="number"?e.eventCount:void 0}}},{key:"recentRequests",toolId:"network",action:p,params:{limit:D},shape:t=>f(t?.requests).map(e=>{const n=a(e);return{id:n.id,...n.at!==void 0?{at:n.at}:{},...M(n.at),method:n.method,url:n.url,status:n.status,...n.overridden?{overridden:true}:{}}})},{key:"appClock",toolId:"clock",action:"getState",shape:t=>{const e=a(t);if(e.active!==true||typeof e.virtualIso!=="string")return void 0;return{appTime:e.virtualIso,mode:e.mode,...typeof e.rate==="number"&&e.rate!==1?{rate:e.rate}:{},offsetMs:e.offsetMs}}},{key:"impersonating",toolId:"impersonate",action:p,shape:t=>{const e=a(t);if(e.isActive!==true)return void 0;const n=a(e.currentUser);return{user:typeof n.displayName==="string"?n.displayName:n.id,id:n.id,...e.isPaused===true?{paused:true}:{},header:e.headerKey}}},{key:"appLocation",toolId:"location",action:"getState",shape:t=>{const e=a(t);if(e.active!==true)return void 0;const n=a(e.override);const s=a(e.current);const i=a(s.fix);const o=a(n.place);const l=a(n.route);return{mode:n.mode,...typeof i.latitude==="number"?{latitude:i.latitude,longitude:i.longitude,accuracy:i.accuracy}:{noFix:s.reason},...n.mode==="fixed"&&typeof o.label==="string"?{place:o.label}:{},...n.mode==="route"?{route:l.name??l.id,playing:n.playing===true}:{},...n.signal===false?{signal:false}:{},...n.services===false?{services:false}:{}}}},{key:"appPermissions",toolId:"permissions",action:p,shape:t=>{const e=f(a(t).permissions).map(a).filter(n=>typeof n.override==="string");if(!e.length)return void 0;return Object.fromEntries(e.map(n=>[String(n.id),n.real&&n.real!==n.override?`${n.override} (system: ${n.real})`:n.override]))}},{key:"networkOverrides",toolId:"network",action:"listOverrideRules",shape:t=>{const e=a(t);const n=f(e.rules).map(a).filter(s=>s.enabled!==false).slice(0,10).map(s=>({id:s.id,urlPattern:s.urlPattern,kind:s.kind,status:s.status}));if(!n.length)return void 0;return{enabled:e.enabled===true,rules:n}}}];async function H(t,e){return await Promise.race([t.catch(()=>void 0),new Promise(n=>E(()=>n(void 0),e))])}async function A(t,{dispatch:e,readSnapshot:n,availableToolIds:s,availableActions:i}){const o=t.filter(r=>{if(!s.includes(r.toolId))return false;const c=i?.[r.toolId];return!c||c.includes(r.action)});const l=await Promise.all(o.map(async r=>{const c=r.action===p?n?Promise.resolve(n(r.toolId)).then(g=>b(r.toolId,g,r.params??{})):Promise.resolve(void 0):Promise.resolve(e(r.toolId,r.action,r.params));const u=await H(c,T);if(u===void 0)return[r.key,void 0];try{return[r.key,r.shape(u)]}catch{return[r.key,void 0]}}));const d={};for(const[r,c]of l){const u=c===void 0||c===null||Array.isArray(c)&&c.length===0;if(!u)d[r]=c}return d}export function buildContextDigest(t){return A(N,t)}function K(t){const e=Array.isArray(t)?t:typeof t==="string"?(()=>{try{const n=JSON.parse(t);return Array.isArray(n)?n:[t]}catch{return[t]}})():[t];return e.flatMap(n=>n===null||n===void 0?[]:S(String(typeof n==="object"?JSON.stringify(n):n)))}function S(t){return t.toLowerCase().split(/[^a-z0-9]+/i).filter(Boolean)}function $(t){const e=t.currentRoute;const n=t.queries;if(!e?.path||!Array.isArray(n))return;const s=Object.values(e.params??{}).map(r=>S(String(r))).filter(r=>r.length>0);const i=S(e.path);let o=-1;let l=-1;let d=false;n.forEach((r,c)=>{if(!r.onScreen)return;const u=new Set(K(r.key));const g=s.filter(y=>y.every(h=>u.has(h))).length;const v=i.filter(y=>u.has(y)||[...u].some(h=>h.includes(y)||y.includes(h))).length;const m=g*3+v;if(m<=0)return;if(m>o){o=m;l=c;d=false}else if(m===o){d=true}});if(l>=0&&!d){n[l].likelyScreen=true;const[r]=n.splice(l,1);n.unshift(r)}}export async function buildLiveContext(t){const e=await A(B,t);$(e);let n;try{n=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{n=void 0}e.now={iso:new Date(k()).toISOString(),...n?{timeZone:n}:{}};return e}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";import{describe as A,expect as e,it as r,vi as u}from"vitest";import{runAgentTurn as y,runGatedAction as b}from"./runAgentTurn";import{CATALOG as k}from"../catalog/catalog.g";import{EffectLedger as d}from"../effects/ledger";const p=[{toolId:"highlight-updates",title:"Screen",summary:"Screen tools",actions:[{action:"tapElement",summary:"Tap a control",effect:"write",release:"works",params:{type:"object",properties:{nativeTag:{type:"number"},testID:{type:"string"},query:{type:"string"}}}},{action:"describeScreen",summary:"Read the screen",effect:"read",release:"works",params:{type:"object",properties:{}}}]}];async function c(t,a,o=false,s=false){const l=new d;const n=[];let g=0;const v={protocol:"anthropic",async*send(i){n.push(i.messages);if(g++===0)yield{type:"tool-call",call:{id:"tap",name:"buoy_highlight-updates",input:{action:"tapElement",params:t}}};else yield{type:"text",delta:"The screen check is done."};yield{type:"done",outcome:"completed"}}};const m=u.fn(async(i,q)=>q==="describeScreen"?{elements:[{nativeTag:7,label:"Place test order",name:"Pressable"}]}:a);const h=u.fn(async()=>false);const f=[];for await(const i of y({provider:v,catalog:p,system:"s",model:"m",maxTokens:100,messages:[{role:"user",text:o?"Why is checkout wrong?":"Tap the button."}],dispatch:m,ledger:l,policy:{requireApproval:s?["write"]:[]},isRelease:false,requestApproval:h}))f.push(i);return{ledger:l,requests:n,dispatch:m,requestApproval:h,events:f}}A("empty and missed taps",()=>{r.each([{},{nativeTag:" ",testID:"",query:""},{testID:"",query:" \n "},{nativeTag:null,testID:" "}])("skips an empty tap: %j",async t=>{for(const a of[false,true]){const o=await c(t,{tapped:true},a,true);e(o.dispatch).not.toHaveBeenCalled();e(o.requestApproval).not.toHaveBeenCalled();e(o.events).toContainEqual(e.objectContaining({type:"tool-end",ok:false,summary:e.stringContaining("tapElement needs")}));e(JSON.stringify(o.requests)).toContain('\\"ok\\":false');e(o.ledger.list()).toEqual([]);e(o.events.some(s=>s.type==="approval-required"||s.type==="tool-verified"||s.type==="block")).toBe(false)}});r.each([{query:"Add"},{testID:"add"},{nativeTag:7}])("runs a valid tap: %j",async t=>{const a=await c(t,{tapped:true});e(a.dispatch).toHaveBeenCalledWith("highlight-updates","tapElement",t);e(a.events).toContainEqual(e.objectContaining({type:"tool-end",ok:true}));e(a.ledger.list()).toHaveLength(1)});r.each([{tapped:false,reason:"No match for Add."},{ok:true,tapped:false,reason:"No match for Add."}])("keeps a missed tap out of the ledger: %j",async t=>{const a=await c({query:"Add"},t);e(a.dispatch).toHaveBeenCalledOnce();e(a.events).toContainEqual(e.objectContaining({type:"tool-end",ok:false,summary:t.reason}));e(JSON.stringify(a.requests)).toContain('\\"ok\\":false');e(a.ledger.list()).toEqual([]);e(a.events.some(o=>o.type==="tool-verified"||o.type==="block")).toBe(false)});r("keeps the question gate for valid taps",async()=>{const t=await c({query:"Place test order"},{tapped:true},true);e(t.requestApproval).toHaveBeenCalledOnce();e(t.dispatch).not.toHaveBeenCalledWith("highlight-updates","tapElement",e.anything());e(t.ledger.list()).toEqual([])});r.each([{},{query:" "},{query:"Add"}])("guards a block button too: %j",async t=>{const a=new d;const o=u.fn(async()=>({tapped:false,reason:"No match for Add."}));const s=await b({toolId:"highlight-updates",action:"tapElement",params:t,catalog:p,dispatch:o,ledger:a,policy:{requireApproval:[]},isRelease:false});e(s).toEqual({ok:false,error:t.query==="Add"?"No match for Add.":"tapElement needs nativeTag, testID or query. Read describeScreen and pass one."});e(o).toHaveBeenCalledTimes(t.query==="Add"?1:0);e(a.list()).toEqual([])});r.each([{},{query:"Add"}])("does not count a failed tap as plan work: %j",async t=>{let a=0;const o=new d;const s={protocol:"anthropic",async*send(){const l=a++;if(l===0)yield{type:"tool-call",call:{id:"plan",name:"buoy_ask-buoy",input:{action:"openProcedure",params:{id:"add"}}}};else if(l===1)yield{type:"tool-call",call:{id:"tap",name:"buoy_highlight-updates",input:{action:"tapElement",params:t}}};else yield{type:"text",delta:"The plan is set."};yield{type:"done",outcome:"completed"}}};for await(const l of y({provider:s,catalog:[...p,k.find(n=>n.toolId==="ask-buoy")],system:"s",model:"m",maxTokens:100,messages:[{role:"user",text:"Add the item."}],dispatch:async()=>({tapped:false,reason:"No match."}),ledger:o,policy:{requireApproval:[]},isRelease:false,procedures:[{id:"add",title:"Add an item",summary:"Add one item",body:"Tap Add."}]})){}e(a).toBe(4);e(o.list()).toEqual([])});r.each([{},{query:"Add"}])("leaves failed taps out of the step-cap list: %j",async t=>{let a=0;const o={protocol:"anthropic",async*send(){if(a++===0)yield{type:"tool-call",call:{id:"tap",name:"buoy_highlight-updates",input:{action:"tapElement",params:t}}};yield{type:"done",outcome:"completed"}}};const s=[];for await(const n of y({provider:o,catalog:p,system:"s",model:"m",maxTokens:100,messages:[{role:"user",text:"Tap Add."}],dispatch:async()=>({tapped:false,reason:"No match."}),ledger:new d,policy:{requireApproval:[],maxSteps:1},isRelease:false}))s.push(n);const l=s.filter(n=>n.type==="text").map(n=>n.delta).join("");e(l).toContain("The job is not done.");e(l).not.toContain("These steps ran:")})});
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";const p=64e3;const U=32e3;const _=/\b(?:picker_\d+|[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12})\b/gi;const a=r=>r==="id"||/Id$/.test(r);export function idGrounding(r,g){let i="";const f=e=>{i=(i+"\n"+e.replace(/\[Buoy\] Unseen id:[^\n]*/g,"")).slice(-p)};for(const e of r){if(e.role==="user")f(e.text);if(e.role==="tool-results")for(const o of e.results)f(o.content)}const h=g.slice(-U);return{add:f,trailer(e){const o=new Set;let m=200;const d=(t,n="",l=0)=>{if(--m<0||l>6||o.size>=8)return;if(typeof t==="string"){if(a(n)&&t.length>0&&t.length<=160)o.add(t);for(const s of t.slice(0,2048).match(_)??[])o.add(s);for(const s of t.slice(0,2048).matchAll(/[?&]([^=&]+)=([^&#]*)/g)){try{if(a(decodeURIComponent(s[1])))d(decodeURIComponent(s[2]),"id",l+1)}catch{}}}else if(t&&typeof t==="object"){for(const[s,y]of Object.entries(t))d(y,s,l+1)}};d(e);const c=h+"\n"+i;const u=t=>{let n=c.indexOf(t);while(n>=0){if(!/[\w-]/.test(c[n-1]??"")&&!/[\w-]/.test(c[n+t.length]??""))return true;n=c.indexOf(t,n+1)}return false};return[...o].slice(0,8).filter(t=>!u(t)).map(t=>`
|
|
2
|
+
[Buoy] Unseen id: ${t.replace(/[\r\n]/g," ")} was not in any read. Use an id from a read, or search for it.`).join("")}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";export const PLAN_ONLY_NUDGE="[Buoy, not the user: your last message said what you would do next but called no tool, so nothing ran and the turn would end there. If the task is not finished, make the next call now. If you are done, say so. If the user has to pick or answer, send the buoy_ui block (choice, confirm or input) now \u2014 text alone gives them nothing to tap.]";export const SILENT_NUDGE="[Buoy, not the user: you ended the turn without a word to the user. Tell them in a sentence or two what you found or did \u2014 a card alone does not say it.]";const s=/\b(if you|once you|when you|after you|only if|let me know|would you like|do you want|shall i|should i|tap|choose|approve)\b/i;const
|
|
1
|
+
"use strict";export const PLAN_ONLY_NUDGE="[Buoy, not the user: your last message said what you would do next but called no tool, so nothing ran and the turn would end there. If the task is not finished, make the next call now. If the user asked for this change, do it and check it. Do not ask them to grant that same step again. Still obey tool approval checks. If you are done, say so. If the user has to pick or answer, send the buoy_ui block (choice, confirm or input) now \u2014 text alone gives them nothing to tap.]";export const SILENT_NUDGE="[Buoy, not the user: you ended the turn without a word to the user. Tell them in a sentence or two what you found or did \u2014 a card alone does not say it.]";const s=/\b(if you|once you|when you|after you|only if|let me know|would you like|do you want|shall i|should i|tap|choose|approve)\b/i;const h=/\b(?:tap|press|click|choose|select)\s+\**["“]?(?:go|approve|yes|continue|start|confirm)\b|ready for your (?:approval|go-ahead|ok)|(?:plan|steps|card|options?) (?:above|below)\b|approve the plan|for your (?:approval|go-ahead)|here['’]s the (?:plan|flow|steps)\b|\b(?:choose|pick|select) (?:what|which|one|from)\b[^.?!]*:/i;const d=/\b(?:pick|choose|select|tell me) (?:what|which)\b/i;const p=/\bi(?:['’]m| am) ready to (?:submit|place|refund|continue)\b|\bbefore i (?:submit|place|refund)\b[^.!?]*\bi need to confirm\b/i;const b=/\b(i['’]ll|i will|let me|i['’]m going to|i am going to|next,? i|now i['’]ll|i['’]m about to)\b/i;const r=/\bi['’]m (?:now )?(?!sorry\b)[a-z]+ing\b/i;export function announcesUnstartedWork(a,i=false){const t=a.trim();if(h.test(t))return true;if(d.test(t))return true;if(/:\s*$/.test(t))return true;if(!t||/\?\s*$/.test(t))return false;const e=t.split(/(?<=[.!*])\s*(?=[A-Z“"])/).filter((l,c,n)=>!(c===n.length-1&&n.length>1&&/^[“"][^“”"]*[”"]\s*$/.test(l.trim())));const o=e.slice(-2).join(" ");if(i&&p.test(o))return true;const u=e.length>1&&!/\d/.test(e.at(-1)??"");if((r.test(e.at(-1)??"")||u&&r.test(e.at(-2)??""))&&!s.test(o))return true;return b.test(o)&&!s.test(o)}
|
|
@@ -1,12 +1,14 @@
|
|
|
1
|
-
"use strict";import{CATALOG as Ve}from"../catalog/catalog.g";import{applyDefaults as ce,validateParams as fe}from"../catalog/validateParams";import{normalizeParams as ue,aliasNote as bt}from"../catalog/normalizeParams";import{fromProviderToolName as ee,toProviderTools as wt}from"../catalog/toProviderTools";import{hashQueryKey as vt}from"../catalog/normalizeParams";import{projectSnapshot as Rt,SNAPSHOT_ACTION as Xe}from"../catalog/snapshotReads";import{UNPARSEABLE_ARGS as St}from"../providers/types";import{isReversible as Ze}from"../effects/ledger";import{describeCall as Ae,decide as Y}from"../policy/policy";import{redact as Tt,stripSelfTraffic as It}from"../policy/redact";import{effectFor as et}from"./effectFor";import{digestOf as Ee}from"../effects/digest";import{buildUiBlock as At,UI_TOOL_NAME as te,uiProviderTool as Et}from"../blocks/uiTool";import{projectReceipt as $t}from"../blocks/receipts";import{isAskBlock as Ct}from"../blocks/types";import{ACQUISITION_CALLS as Nt,synthesizeAskBlock as _t,synthesizeShortfallBlock as Ot}from"./askGate";import{couldBeToolCallEnvelope as xt,parseTextToolCalls as Mt,SALVAGE_NOTE as Lt}from"./textToolCalls";import{announcesUnstartedWork as Pt,PLAN_ONLY_NUDGE as Ut,SILENT_NUDGE as Dt}from"./planOnlyStop";import{compactScreen as qt}from"./compactScreen";import{budgetForRequest as tt,MAX_HISTORY_TOKENS as jt,messageSize as $e}from"./historyBudget";import{promptTokensOf as Bt,TokenCalibration as Ft}from"./tokenCalibration";import{truncationMarker as zt}from"./evidence";import{retrieveEvidence as Ht}from"./retrieve";import{verificationTrailer as Wt,verifyOutcome as Gt}from"./verify";import{realClearTimeout as Jt,realNow as A,realSetTimeout as Yt}from"../realNow";const ot=24e3;const nt=2e3;const rt=3;function Kt(t){const n=r=>{if(r===null||typeof r!=="object")return r;if(Array.isArray(r))return r.map(n);const c=r;return Object.keys(c).sort().reduce((f,R)=>(f[R]=n(c[R]),f),{})};return t.map(r=>`${r.name}:${JSON.stringify(n(r.input??{}))}`).join("|")}const Qt="[Buoy] You have now made this exact call three times in a row and gotten the same thing back. Repeating it again will not change the answer. Read the result you already have, then either try a different tool or different arguments, or tell the user plainly what you could not get and what you tried.";const Vt=24;const it=18e4;const Xt=2;const Zt=1;const eo=1e3;const to=250;const oo=3e4;function no(t,n){return new Promise(r=>{if(n?.aborted)return r();const c=Yt(f,t);function f(){Jt(c);n?.removeEventListener("abort",f);r()}n?.addEventListener("abort",f,{once:true})})}function st(t){if(typeof t==="boolean")return{approved:t,trust:false};const n=t.reason?.trim();return{approved:t.approved,...n?{reason:n}:{},trust:t.trust===true&&t.approved}}function at(t){return t?`The user declined this change and said: "${t}". Do not retry it as proposed; take their note into account and, if a different change would fit, propose that instead.`:"The user declined this change. Do not retry it; ask what they would prefer."}function q(t,n,r){return t.find(c=>c.toolId===n)?.actions.find(c=>c.action===r)}const ro="Rejected: every image URL must be one you read from a tool result in THIS conversation (images.list, a storage value, a response body). Never invent or remember URLs \u2014 read them first, then show them.";const io=t=>` NOTE: ${t} image ${t===1?"URL was":"URLs were"} dropped \u2014 they were not read from a tool result in this conversation, so the card the user is looking at has no picture there. Do not tell them it does; read the URLs and show it again, or say the artwork is missing.`;function so(t){try{return JSON.stringify(t??null)}catch{return String(t)}}function ao(t,n){if(t.length<=ot)return t;return`${t.slice(0,ot)}${zt(t.length,n)}`}function lo(t){if(t===null||t===void 0)return"Done";if(Array.isArray(t))return Ce(t.length);if(typeof t==="boolean")return t?"Done":"Failed";if(typeof t==="object"){const n=t;if(n.ok===false)return typeof n.error==="string"?n.error:"Failed";if(n.found===false)return"Not found";if(n.tapped===false)return"Nothing to tap";if(n.active===false)return"Saved, but inactive in this build";for(const c of["returned","count","total"]){const f=n[c];if(typeof f==="number")return Ce(f)}const r=Object.values(n).filter(Array.isArray);if(r.length===1)return Ce(r[0].length);return"Done"}return String(t).slice(0,80)}function Ce(t){return t===1?"1 item":`${t} items`}function dt(t){return typeof t==="object"&&t!==null&&t.ok===false}export async function*runAgentTurn(t){const{provider:n,catalog:r,system:c,systemVolatile:f,model:R,maxTokens:g,dispatch:d,readSnapshot:m,storeKeyOwners:N,ledger:w,policy:L,isRelease:P,requestApproval:j,signal:_,evidence:B,trusted:T,procedures:F}=t;const z=new Map;const O=t.calibration??new Ft;const h=[...t.messages];const pe=wt(r,{availableToolIds:t.availableToolIds,availableActions:t.availableActions,isRelease:P});pe.push(Et());const ne=L.maxSteps??Vt;const ct=po();const ft=w.generation;const _e=c.length+(f?.length??0)+pe.reduce((x,M)=>x+M.description.length+JSON.stringify(M.inputSchema).length,0);const Oe=()=>_e+O.chars(g);let re=A()+it;const he={throttled:0,overflow:0};let ie=jt;const me=t.seenUrls??new Set;const ut=/https?:\/\/[^\s"'\\)\]}>]+/g;let xe=false;const H=[];let Me=false;const ye=[];let ge=false;let Le=false;let se=false;let Pe=false;let Ue=false;const pt=[...h].reverse().find(x=>x.role==="user");const ht=/\?\s*$/.test(pt?.text?.trim()??"");for(let x=0;x<ne;x++){if(_?.aborted){yield{type:"done",stopReason:"stopped"};return h}if(A()>re){yield{type:"block",block:{id:`cap${A()}`,kind:"notice",tone:"warning",text:`This is taking too long \u2014 stopped after ${Math.round(it/1e3)}s. What it found so far is above.`,actions:[{label:"Continue",primary:true,send:"Continue where you left off."}]}};yield{type:"done",stopReason:"time-cap"};return h}const M=tt(h,Oe(),O.chars(ie),O.charsPerToken,w.liveCallIds());if(M.droppedRounds>0){h.length=0;h.push(...M.messages);yield{type:"history-trimmed",droppedRounds:M.droppedRounds,droppedPinned:M.droppedPinned}}else if(M.messages!==h){h.length=0;h.push(...M.messages)}let E="";let De=false;const W=e=>{const l=xe&&!De;De=true;xe=true;return l?{type:"text",delta:e,breakBefore:true}:{type:"text",delta:e}};let v=[];const qe=new Set;let C="";let ke=true;let K=[];let ae=false;let de;let G;let be=0;for(;;){be+=1;E="";v=[];C="";ke=true;K=[];ae=false;de=void 0;G=void 0;let e;const l=_e+h.reduce((a,p)=>a+$e(p),0);for await(const a of n.send({messages:h,system:c,systemVolatile:f,tools:pe,model:R,maxTokens:g,signal:_,meta:{askId:ct,round:x+1,attempt:be}})){if(a.type==="text"){E+=a.delta;if(!ke){yield W(a.delta)}else if(xt(E)){C+=a.delta}else{ke=false;C="";yield W(E)}}else if(a.type==="tool-call"){v.push(a.call)}else if(a.type==="meter"){yield{type:"meter",frame:a.frame}}else if(a.type==="thinking"){K.push(a.block);if(a.block.type==="thinking"&&a.block.thinking.trim()){yield{type:"reasoning",text:a.block.thinking}}}else if(a.type==="error"){if(a.kind==="truncated"||a.kind==="timeout"){G={message:a.message}}else if(a.problem&&(a.problem.kind==="throttled"||a.problem.kind==="overflow")&&E===""&&v.length===0&&K.length===0){e={problem:a.problem,message:a.message}}else{yield{type:"error",message:a.message,...a.problem?.hosted?{hosted:a.problem.hosted}:{}};ae=true}}else if(a.type==="done"){de=a.outcome;if(a.usage){O.observe(l,Bt(a.usage,n.protocol));yield{type:"usage",...a.usage,model:a.model}}}}if(!e)break;const o=e.problem.kind;const i=1+(o==="throttled"?Xt:Zt);const k=he[o];let u=o==="throttled"?Math.min(e.problem.retryAfterMs??eo*2**k,oo)+Math.floor(Math.random()*to):0;let $=k>=i-1||_?.aborted===true||A()+u>re;if(e.problem.hosted&&be>=2)$=true;if(!$&&o==="overflow"){ie=Math.floor(ie/2);const a=h.reduce((Q,D)=>Q+$e(D),0);const p=tt(h,Oe(),O.chars(ie),O.charsPerToken,w.liveCallIds());const J=p.messages.reduce((Q,D)=>Q+$e(D),0);if(J>=a){$=true}else{h.length=0;h.push(...p.messages);if(p.droppedRounds>0)yield{type:"history-trimmed",droppedRounds:p.droppedRounds,droppedPinned:p.droppedPinned}}}if($){const a=o==="throttled"?k>0?`The AI endpoint is rate-limiting requests \u2014 tried ${k+1} times.`:"The AI endpoint is rate-limiting requests.":"This conversation is too large for the AI endpoint and there was nothing older to trim. Start a new conversation, or ask a shorter question.";const p=e.problem.hosted;yield p?{type:"error",message:p.message,hosted:p}:{type:"error",message:`${a} (${e.message})`};ae=true;break}he[o]+=1;yield{type:"retrying",reason:o,attempt:he[o]+1,maxAttempts:i,inMs:u};if(u>0)await no(u,_);if(_?.aborted){yield{type:"done",stopReason:"stopped"};return h}}if(ae){if(C)yield W(C);yield{type:"done",stopReason:"error"};return h}if(!G&&de!=="completed"){G={message:de==="output-limited"?v.length?"The model ran out of room mid-plan, so nothing was run. What it found so far is above.":"The model ran out of room before finishing this answer.":"The answer ended before the endpoint said it was finished, so nothing was run."}}if(G){if(C)yield W(C);if(E.trim())h.push({role:"assistant",text:E});yield{type:"block",block:{id:`cut${A()}`,kind:"notice",tone:"warning",text:G.message,actions:[{label:"Continue",primary:true,send:"Continue where you left off."}]}};yield{type:"done",stopReason:"incomplete"};return h}if(C){const e=v.length===0?Mt(C,r):void 0;if(e){for(const l of e.calls){v.push(l);qe.add(l.id)}E=e.reply;if(e.reply)yield W(e.reply)}else{yield W(C)}C=""}h.push({role:"assistant",text:E,toolCalls:v.length?v:void 0,thinking:K.length?K:void 0});if(E.trim())ye.push(E.trim());if(v.length===0&&!se&&!ge&&x<ne-1&&(Pt(E)||Pe&&!Ue&&!ht)){se=true;h.push({role:"user",text:Ut});continue}if(v.length===0&&!se&&ye.length===0&&x<ne-1){se=true;h.push({role:"user",text:Dt});continue}if(v.length===0){const e=ye.join("\n\n");const l=Ot({text:e,attempted:Le});if(l)yield{type:"block",block:l};const o=ge||l?null:_t(e);if(o){yield{type:"block",block:o};yield{type:"awaiting-user",blockId:o.id}}yield{type:"done",stopReason:o?"awaiting-user":"answered"};return h}const b=[];let je=false;const Be=new Map;if(v.length>1){const e=v.every(l=>{if(l.name===te)return false;const o=ee(l.name,r);if(!o||o==="ask-buoy")return false;const i=l.input?.action;if(typeof i!=="string"||i===Xe)return false;const k=q(r,o,i);if(!k||k.effect!=="read")return false;return Y({descriptor:k,toolId:o,policy:L,isRelease:P}).verdict==="allow"});if(e){for(const l of v){const o=ee(l.name,r);const i=String(l.input.action);const k={...l.input.params??{}};const u=q(r,o,i);const $=ue(o,i,k);const a=ce($.params,u.params);if(!fe(a,u.params).ok)continue;const p=Promise.resolve(d(o,i,a)).catch(J=>{throw J});p.catch(()=>{});Be.set(l.id,p)}}}let we=null;const mt=e=>{const l=ee(e.name,r)??e.name;const o=typeof e.input?.action==="string"?e.input.action:"";const i=o?q(r,l,o):void 0;const k=e.input?.params??{};return[{type:"tool-start",id:e.id,toolId:l,action:o,label:i?Ae(l,i,k):`${l}.${o}`,description:i?.summary??"",params:k,effect:i?.effect??"read"},{type:"tool-end",id:e.id,ok:false,summary:"stopped",durationMs:0}]};const Fe=v.map(e=>{if(e.name===te)return void 0;const l=ee(e.name,r);const o=typeof e.input?.action==="string"?e.input.action:void 0;if(!l||!o)return void 0;const i=q(r,l,o);if(!i)return void 0;const k=e.input.params??{};const u=ce(ue(l,o,k).params,i.params);if(!fe(u,i.params).ok)return void 0;const $=Y({descriptor:i,toolId:l,policy:L,isRelease:P});return{call:e,toolId:l,action:o,descriptor:i,params:u,label:Ae(l,i,u),mutates:i.effect!=="read",gated:$.verdict==="needs-approval",reason:$.verdict==="needs-approval"?$.reason:""}});const yt=Fe.some(e=>e?.gated);const U=new Map;let ze=false;let He=false;async function*gt(){ze=true;for(const e of Fe){if(!e?.gated||U.has(e.call.id))continue;if(T?.has(`${e.toolId}.${e.action}`)){U.set(e.call.id,true);continue}yield{type:"approval-required",id:e.call.id,toolId:e.toolId,action:e.action,label:e.label,description:e.descriptor.summary,reason:e.reason};const l=A();const o=await readTargetDigest({toolId:e.toolId,action:e.action,params:e.params,dispatch:d,catalog:r});const i=st(T?.has(`${e.toolId}.${e.action}`)?true:j?await j({id:e.call.id,toolId:e.toolId,action:e.action,label:e.label,description:e.descriptor.summary,reason:e.reason,params:e.params,targetDigest:o}):false);re+=A()-l;const k=i.approved;U.set(e.call.id,k);if(i.trust)T?.add(`${e.toolId}.${e.action}`);if(i.reason)z.set(e.call.id,i.reason);if(!k){He=true;return}}}for(const e of v){if(_?.aborted){if(e.name!==te){for(const s of mt(e))yield s}b.push({toolCallId:e.id,content:"Not run \u2014 the user pressed Stop before this call started.",isError:true});continue}const l=e.input?.[St];if(typeof l==="string"){b.push({toolCallId:e.id,content:`Not run \u2014 this call's arguments were not valid JSON, so nothing changed (${l.slice(0,120)}). Send the call again with compact JSON: {"action": "...", "params": {...}}.`,isError:true});continue}if(e.name===te){const s=At(e.input);if(!s.ok||!s.block){b.push({toolCallId:e.id,content:`Invalid ${te} block:
|
|
2
|
-
${
|
|
1
|
+
"use strict";import{CATALOG as pt}from"../catalog/catalog.g";import{applyDefaults as ge,validateParams as be}from"../catalog/validateParams";import{normalizeParams as se,aliasNote as Mt}from"../catalog/normalizeParams";import{fromProviderToolName as ee,toProviderTools as jt}from"../catalog/toProviderTools";import{hashQueryKey as qt}from"../catalog/normalizeParams";import{projectSnapshot as Bt,SNAPSHOT_ACTION as ht}from"../catalog/snapshotReads";import{UNPARSEABLE_ARGS as Ft}from"../providers/types";import{isReversible as mt}from"../effects/ledger";import{classifyTurn as Wt,QUESTION_DECLINED as yt,tapLabels as zt}from"../policy/turnScope";import{describeCall as Ue,decide as B}from"../policy/policy";import{redact as Gt,stripSelfTraffic as Ht}from"../policy/redact";import{idGrounding as Jt}from"./idGrounding";import{effectFor as gt}from"./effectFor";import{digestOf as Pe}from"../effects/digest";import{buildUiBlock as Yt,UI_TOOL_NAME as ie,uiProviderTool as Kt}from"../blocks/uiTool";import{projectReceipt as Qt}from"../blocks/receipts";import{isAskBlock as Vt}from"../blocks/types";import{ACQUISITION_CALLS as Xt,synthesizeAskBlock as Zt,synthesizeShortfallBlock as eo}from"./askGate";import{couldBeToolCallEnvelope as bt,parseTextToolCalls as to,SALVAGE_NOTE as oo}from"./textToolCalls";import{announcesUnstartedWork as no,PLAN_ONLY_NUDGE as ro,SILENT_NUDGE as so}from"./planOnlyStop";import{compactScreen as io}from"./compactScreen";import{budgetForRequest as De,MAX_HISTORY_TOKENS as ao,messageSize as Me}from"./historyBudget";import{promptTokensOf as lo,TokenCalibration as co}from"./tokenCalibration";import{truncationMarker as fo}from"./evidence";import{retrieveEvidence as uo}from"./retrieve";import{verificationTrailer as po,verifyOutcome as ho}from"./verify";import{realClearTimeout as mo,realNow as _,realSetTimeout as yo}from"../realNow";const kt=24e3;const wt=2e3;const vt=3;function go(t){const r=o=>{if(o===null||typeof o!=="object")return o;if(Array.isArray(o))return o.map(r);const a=o;return Object.keys(a).sort().reduce((d,E)=>(d[E]=r(a[E]),d),{})};return t.map(o=>`${o.name}:${JSON.stringify(r(o.input??{}))}`).join("|")}const bo="[Buoy] You have now made this exact call three times in a row and gotten the same thing back. Repeating it again will not change the answer. Read the result you already have, then either try a different tool or different arguments, or tell the user plainly what you could not get and what you tried.";const ko=24;const je="Resume where you left off. Don't redo past changes. Read the past tool results first.";const wo="You are out of steps. No more tools may run. Reply in the user's language with plain words. Name every write that ran, what you found, and what is still not done. Use the tool results as proof. A tap alone does not prove a save or an order worked. Do not claim the job is done if you have not checked it. Keep the reply short.";const Tt=18e4;const vo=2;const To=1;const So=1e3;const Io=250;const Ro=3e4;function Eo(t,r){return new Promise(o=>{if(r?.aborted)return o();const a=yo(d,t);function d(){mo(a);r?.removeEventListener("abort",d);o()}r?.addEventListener("abort",d,{once:true})})}function St(t){if(typeof t==="boolean")return{approved:t,trust:false};const r=t.reason?.trim();return{approved:t.approved,...r?{reason:r}:{},trust:t.trust===true&&t.approved}}function It(t){return t?`The user declined this change and said: "${t}". Do not retry it as proposed; take their note into account and, if a different change would fit, propose that instead.`:"The user declined this change. Do not retry it; ask what they would prefer."}function $o(t,r){const o=t.toLowerCase();const a=r.toLowerCase();if(Math.abs(o.length-a.length)>1)return false;let d=0;while(d<o.length&&o[d]===a[d])d++;return o===a||o.slice(d+1)===a.slice(d+1)||o.slice(d+1)===a.slice(d)||o.slice(d)===a.slice(d+1)}function M(t,r,o){return t.find(a=>a.toolId===r)?.actions.find(a=>a.action===o)}const Ao="Rejected: every image URL must be one you read from a tool result in THIS conversation (images.list, a storage value, a response body). Never invent or remember URLs \u2014 read them first, then show them.";const Co=t=>` NOTE: ${t} image ${t===1?"URL was":"URLs were"} dropped \u2014 they were not read from a tool result in this conversation, so the card the user is looking at has no picture there. Do not tell them it does; read the URLs and show it again, or say the artwork is missing.`;function No(t){try{return JSON.stringify(t??null)}catch{return String(t)}}function _o(t,r){if(t.length<=kt)return t;return`${t.slice(0,kt)}${fo(t.length,r)}`}function Oo(t){if(t===null||t===void 0)return"Done";if(Array.isArray(t))return qe(t.length);if(typeof t==="boolean")return t?"Done":"Failed";if(typeof t==="object"){const r=t;if(r.ok===false)return typeof r.error==="string"?r.error:"Failed";if(r.found===false)return"Not found";if(r.tapped===false)return"Nothing to tap";if(r.active===false)return"Saved, but inactive in this build";for(const a of["returned","count","total"]){const d=r[a];if(typeof d==="number")return qe(d)}const o=Object.values(r).filter(Array.isArray);if(o.length===1)return qe(o[0].length);return"Done"}return String(t).slice(0,80)}function qe(t){return t===1?"1 item":`${t} items`}function Rt(t){return typeof t==="object"&&t!==null&&t.ok===false}const Be="tapElement needs nativeTag, testID or query. Read describeScreen and pass one.";function ke(t,r,o){return t==="highlight-updates"&&r==="tapElement"&&![o.nativeTag,o.testID,o.query].some(a=>typeof a==="string"?a.trim().length>0:a!=null)}function Et(t,r,o){if(t!=="highlight-updates"||r!=="tapElement"||!o||typeof o!=="object")return o;const a=o;if(a.tapped!==false)return o;return{...a,ok:false,error:typeof a.reason==="string"?a.reason:typeof a.error==="string"?a.error:"Nothing was tapped. Read describeScreen and try again."}}export async function*runAgentTurn(t){const{provider:r,catalog:o,system:a,systemVolatile:d,model:E,maxTokens:b,dispatch:c,readSnapshot:y,storeKeyOwners:U,ledger:k,policy:P,isRelease:D,requestApproval:W,signal:A,evidence:z,trusted:$,procedures:F}=t;const G=new Map;const x=t.calibration??new co;const We=[...t.messages].reverse().find(m=>m.role==="user");const j=Wt(We?.role==="user"?We.text:"");const h=[...t.messages];const ze=Jt(h,`${t.system}
|
|
2
|
+
${t.systemVolatile??""}
|
|
3
|
+
${JSON.stringify(F??[])}`);const de=jt(o,{availableToolIds:t.availableToolIds,availableActions:t.availableActions,isRelease:D});de.push(Kt());const le=P.maxSteps??ko;const Ge=Po();const At=k.generation;const Ct=new Set(k.list().map(m=>m.id));const He=a.length+(d?.length??0)+de.reduce((m,C)=>m+C.description.length+JSON.stringify(C.inputSchema).length,0);const we=()=>He+x.chars(b);let ce=_()+Tt;const ve={throttled:0,overflow:0};let te=ao;const Te=t.seenUrls??new Set;const Nt=/https?:\/\/[^\s"'\\)\]}>]+/g;let Se=false;const H=[];let Je=false;const Ie=[];let Re=false;let Ye=false;let fe=false;let Ke=false;let Qe=false;const _t=[...h].reverse().find(m=>m.role==="user");const Ot=/\?\s*$/.test(_t?.text?.trim()??"");for(let m=0;m<le;m++){if(A?.aborted){yield{type:"done",stopReason:"stopped"};return h}if(_()>ce){yield{type:"block",block:{id:`cap${_()}`,kind:"notice",tone:"warning",text:`This is taking too long \u2014 stopped after ${Math.round(Tt/1e3)}s. What it found so far is above.`,actions:[{label:"Continue",primary:true,send:je}]}};yield{type:"done",stopReason:"time-cap"};return h}const C=De(h,we(),x.chars(te),x.charsPerToken,k.liveCallIds());if(C.droppedRounds>0){h.length=0;h.push(...C.messages);yield{type:"history-trimmed",droppedRounds:C.droppedRounds,droppedPinned:C.droppedPinned}}else if(C.messages!==h){h.length=0;h.push(...C.messages)}let O="";let et=false;const Y=e=>{const l=Se&&!et;et=true;Se=true;return l?{type:"text",delta:e,breakBefore:true}:{type:"text",delta:e}};let T=[];const tt=new Set;let L="";let $e=true;let oe=[];let ue=false;let pe;let K;let Ae=0;for(;;){Ae+=1;O="";T=[];L="";$e=true;oe=[];ue=false;pe=void 0;K=void 0;let e;const l=He+h.reduce((f,p)=>f+Me(p),0);for await(const f of r.send({messages:h,system:a,systemVolatile:d,tools:de,model:E,maxTokens:b,signal:A,meta:{askId:Ge,round:m+1,attempt:Ae}})){if(f.type==="text"){O+=f.delta;if(!$e){yield Y(f.delta)}else if(bt(O)){L+=f.delta}else{$e=false;L="";yield Y(O)}}else if(f.type==="tool-call"){T.push(f.call)}else if(f.type==="meter"){yield{type:"meter",frame:f.frame}}else if(f.type==="thinking"){oe.push(f.block);if(f.block.type==="thinking"&&f.block.thinking.trim()){yield{type:"reasoning",text:f.block.thinking}}}else if(f.type==="error"){if(f.kind==="truncated"||f.kind==="timeout"){K={message:f.message}}else if(f.problem&&(f.problem.kind==="throttled"||f.problem.kind==="overflow")&&O===""&&T.length===0&&oe.length===0){e={problem:f.problem,message:f.message}}else{yield{type:"error",message:f.message,...f.problem?.hosted?{hosted:f.problem.hosted}:{}};ue=true}}else if(f.type==="done"){pe=f.outcome;if(f.usage){x.observe(l,lo(f.usage,r.protocol));yield{type:"usage",...f.usage,model:f.model}}}}if(!e)break;const n=e.problem.kind;const s=1+(n==="throttled"?vo:To);const g=ve[n];let u=n==="throttled"?Math.min(e.problem.retryAfterMs??So*2**g,Ro)+Math.floor(Math.random()*Io):0;let N=g>=s-1||A?.aborted===true||_()+u>ce;if(e.problem.hosted&&Ae>=2)N=true;if(!N&&n==="overflow"){te=Math.floor(te/2);const f=h.reduce((ne,V)=>ne+Me(V),0);const p=De(h,we(),x.chars(te),x.charsPerToken,k.liveCallIds());const Q=p.messages.reduce((ne,V)=>ne+Me(V),0);if(Q>=f){N=true}else{h.length=0;h.push(...p.messages);if(p.droppedRounds>0)yield{type:"history-trimmed",droppedRounds:p.droppedRounds,droppedPinned:p.droppedPinned}}}if(N){const f=n==="throttled"?g>0?`The AI endpoint is rate-limiting requests \u2014 tried ${g+1} times.`:"The AI endpoint is rate-limiting requests.":"This conversation is too large for the AI endpoint and there was nothing older to trim. Start a new conversation, or ask a shorter question.";const p=e.problem.hosted;yield p?{type:"error",message:p.message,hosted:p}:{type:"error",message:`${f} (${e.message})`};ue=true;break}ve[n]+=1;yield{type:"retrying",reason:n,attempt:ve[n]+1,maxAttempts:s,inMs:u};if(u>0)await Eo(u,A);if(A?.aborted){yield{type:"done",stopReason:"stopped"};return h}}if(ue){if(L)yield Y(L);yield{type:"done",stopReason:"error"};return h}if(!K&&pe!=="completed"){K={message:pe==="output-limited"?T.length?"The model ran out of room mid-plan, so nothing was run. What it found so far is above.":"The model ran out of room before finishing this answer.":"The answer ended before the endpoint said it was finished, so nothing was run."}}if(K){if(L)yield Y(L);if(O.trim())h.push({role:"assistant",text:O});yield{type:"block",block:{id:`cut${_()}`,kind:"notice",tone:"warning",text:K.message,actions:[{label:"Continue",primary:true,send:je}]}};yield{type:"done",stopReason:"incomplete"};return h}if(L){const e=T.length===0?to(L,o):void 0;if(e){for(const l of e.calls){T.push(l);tt.add(l.id)}O=e.reply;if(e.reply)yield Y(e.reply)}else{yield Y(L)}L=""}h.push({role:"assistant",text:O,toolCalls:T.length?T:void 0,thinking:oe.length?oe:void 0});if(O.trim())Ie.push(O.trim());if(T.length===0&&!fe&&!Re&&m<le-1&&(no(O,j==="task")||Ke&&!Qe&&!Ot)){fe=true;h.push({role:"user",text:ro});continue}if(T.length===0&&!fe&&Ie.length===0&&m<le-1){fe=true;h.push({role:"user",text:so});continue}if(T.length===0){const e=Ie.join("\n\n");const l=eo({text:e,attempted:Ye});if(l)yield{type:"block",block:l};const n=Re||l?null:Zt(e);if(n){yield{type:"block",block:n};yield{type:"awaiting-user",blockId:n.id}}yield{type:"done",stopReason:n?"awaiting-user":"answered"};return h}const w=[];let ot=false;const nt=new Map;if(T.length>1){const e=T.every(l=>{if(l.name===ie)return false;const n=ee(l.name,o);if(!n||n==="ask-buoy")return false;const s=l.input?.action;if(typeof s!=="string"||s===ht)return false;const g=M(o,n,s);if(!g||g.effect!=="read")return false;return B({descriptor:g,toolId:n,policy:P,isRelease:D}).verdict==="allow"});if(e){for(const l of T){const n=ee(l.name,o);const s=String(l.input.action);const g={...l.input.params??{}};const u=M(o,n,s);const N=se(n,s,g);const f=ge(N.params,u.params);if(!be(f,u.params).ok)continue;const p=Promise.resolve(c(n,s,f)).catch(Q=>{throw Q});p.catch(()=>{});nt.set(l.id,p)}}}let Ce=null;const Ut=e=>{const l=ee(e.name,o)??e.name;const n=typeof e.input?.action==="string"?e.input.action:"";const s=n?M(o,l,n):void 0;const g=e.input?.params??{};return[{type:"tool-start",id:e.id,toolId:l,action:n,label:s?Ue(l,s,g):`${l}.${n}`,description:s?.summary??"",params:g,effect:s?.effect??"read"},{type:"tool-end",id:e.id,ok:false,summary:"stopped",durationMs:0}]};const he=new Map;if(j==="question"){for(const e of T){if(ee(e.name,o)!=="highlight-updates"||e.input?.action!=="tapElement")continue;const l=se("highlight-updates","tapElement",e.input.params??{}).params;if(ke("highlight-updates","tapElement",l))continue;const n=M(o,"highlight-updates","describeScreen");const s=M(o,"highlight-updates","tapElement");if(A?.aborted||!n||!s||B({descriptor:n,toolId:"highlight-updates",policy:P,isRelease:D}).verdict!=="allow"||B({descriptor:s,toolId:"highlight-updates",policy:P,isRelease:D,turnScope:j,params:l}).verdict==="refuse")continue;const g=await c("highlight-updates","describeScreen",{}).catch(()=>void 0);he.set(e.id,zt(g,l))}}const rt=T.map(e=>{if(e.name===ie)return void 0;const l=ee(e.name,o);const n=typeof e.input?.action==="string"?e.input.action:void 0;if(!l||!n)return void 0;const s=M(o,l,n);if(!s)return void 0;const g=e.input.params??{};const u=ge(se(l,n,g).params,s.params);if(ke(l,n,u)||!be(u,s.params).ok)return void 0;const N=B({descriptor:s,toolId:l,policy:P,isRelease:D,turnScope:j,params:u,tapLabels:he.get(e.id)});return{call:e,toolId:l,action:n,descriptor:s,params:u,label:Ue(l,s,u),mutates:s.effect!=="read",gated:N.verdict==="needs-approval",turnScoped:N.verdict==="needs-approval"&&N.turnScoped,reason:N.verdict==="needs-approval"?N.reason:""}});const Pt=rt.some(e=>e?.gated);const q=new Map;let st=false;let it=false;async function*Dt(){st=true;for(const e of rt){if(!e?.gated||q.has(e.call.id))continue;if(!e.turnScoped&&$?.has(`${e.toolId}.${e.action}`)){q.set(e.call.id,true);continue}yield{type:"approval-required",id:e.call.id,toolId:e.toolId,action:e.action,label:e.label,description:e.descriptor.summary,reason:e.reason};const l=_();const n=await readTargetDigest({toolId:e.toolId,action:e.action,params:e.params,dispatch:c,catalog:o});const s=St(!e.turnScoped&&$?.has(`${e.toolId}.${e.action}`)?true:W?await W({id:e.call.id,toolId:e.toolId,action:e.action,label:e.label,description:e.descriptor.summary,reason:e.reason,params:e.params,targetDigest:n}):false);ce+=_()-l;const g=s.approved;q.set(e.call.id,g);if(s.trust)$?.add(`${e.toolId}.${e.action}`);if(s.reason)G.set(e.call.id,s.reason);if(!g){it=true;return}}}for(const e of T){if(A?.aborted){if(e.name!==ie){for(const i of Ut(e))yield i}w.push({toolCallId:e.id,content:"Not run \u2014 the user pressed Stop before this call started.",isError:true});continue}const l=e.input?.[Ft];if(typeof l==="string"){w.push({toolCallId:e.id,content:`Not run \u2014 this call's arguments were not valid JSON, so nothing changed (${l.slice(0,120)}). Send the call again with compact JSON: {"action": "...", "params": {...}}.`,isError:true});continue}if(e.name===ie){const i=Yt(e.input);if(!i.ok||!i.block){w.push({toolCallId:e.id,content:`Invalid ${ie} block:
|
|
4
|
+
${i.errors.join("\n")}
|
|
3
5
|
|
|
4
|
-
Resend ONLY the corrected block. Do not rewrite your answer \u2014 whatever you already said this turn has been shown to the user, and saying it again repeats it on their screen.`,isError:true});continue}let
|
|
5
|
-
${
|
|
6
|
+
Resend ONLY the corrected block. Do not rewrite your answer \u2014 whatever you already said this turn has been shown to the user, and saying it again repeats it on their screen.`,isError:true});continue}let S=0;if(i.block.kind==="imageGrid"){const R=i.block.images.filter(I=>Te.has(I.url));S=i.block.images.length-R.length;if(R.length===0){w.push({toolCallId:e.id,content:Ao,isError:true});continue}i.block={...i.block,images:R}}if(i.block.kind==="list"){const R=i.block.items.map(I=>{if(!I.image||Te.has(I.image))return I;S+=1;return{...I,image:void 0}});i.block={...i.block,items:R}}yield{type:"block",block:i.block,forToolCallId:e.id};if(i.block.kind==="actions"||i.block.kind==="suggestions"||i.block.kind==="plan"&&i.block.pending){Re=true}if(Vt(i.block)){Ce=i.block.id;w.push({toolCallId:e.id,content:"Shown. Waiting for the user's answer \u2014 it will arrive as their next message. Do not guess it."})}else{w.push({toolCallId:e.id,content:"Shown to the user. Don't repeat its contents in text."+(S>0?Co(S):"")})}continue}const n=ee(e.name,o);const s=e.input.action;const g=(i,S)=>[{type:"tool-start",id:e.id,toolId:n??e.name,action:s??"",label:i,description:"",params:e.input.params??{},effect:"read"},{type:"tool-end",id:e.id,ok:false,summary:S,durationMs:0}];if(!n){for(const i of g(e.name,"No such tool"))yield i;w.push({toolCallId:e.id,content:`There is no tool called "${e.name}". Use one of the tools you were given.`,isError:true});continue}if(!s){for(const i of g(e.name,"No action given"))yield i;w.push({toolCallId:e.id,content:`"${e.name}" needs an "action" \u2014 it is required, and it names which of this tool's actions to run. See the action list in the tool's description.`,isError:true});continue}const u=M(o,n,s);if(!u){const i=o.find(v=>v.toolId===n)?.actions.map(v=>v.action)??[];const S=o.filter(v=>v.toolId!==n&&v.actions.some(Oe=>Oe.action===s));const R=i.filter(v=>$o(v,s));const I=[...S.map(v=>`${v.toolId}.${s}`),...R.map(v=>`${n}.${v}`)].slice(0,3);const Z=`${n} has no ${s}.${I.length?` Did you mean ${I.join(" or ")}?`:""}`;for(const v of g(`${n}.${s}`,I.length?Z:"No such action"))yield v;w.push({toolCallId:e.id,content:`${Z}${i.length?` Valid actions: ${i.join(", ")}.`:""}`,isError:true});continue}const N=e.input.params??{};const f=se(n,s,N);const p=ge(f.params,u.params);if(ke(n,s,p)){for(const i of g(`${n}.${s}`,Be))yield i;w.push({toolCallId:e.id,content:JSON.stringify({ok:false,error:Be}),isError:true});continue}const Q=be(p,u.params);if(!Q.ok){w.push({toolCallId:e.id,content:`Invalid parameters for ${n}.${s}:
|
|
7
|
+
${Q.errors.join("\n")}
|
|
6
8
|
|
|
7
9
|
Expected schema:
|
|
8
|
-
${JSON.stringify(u.params)}`,isError:true});continue}const
|
|
10
|
+
${JSON.stringify(u.params)}`,isError:true});continue}const ne=Mt(f.notes);const V=u.effect!=="read"?ze.trailer(p):"";const me=Ue(n,u,p);const X=B({descriptor:u,toolId:n,policy:P,isRelease:D,turnScope:j,params:p,tapLabels:he.get(e.id)});const re=i=>[{type:"tool-start",id:e.id,toolId:n,action:s,label:me,description:u.summary,params:p,effect:u.effect},{type:"tool-end",id:e.id,ok:false,summary:i,durationMs:0}];if(X.verdict==="refuse"){for(const i of re("refused"))yield i;w.push({toolCallId:e.id,content:X.reason,isError:true});continue}const Ne=X.verdict==="needs-approval";if(Pt&&!st&&(u.effect!=="read"||Ne)){yield*Dt()}if(it&&(u.effect!=="read"||Ne)){for(const i of re("declined"))yield i;w.push({toolCallId:e.id,content:j==="question"?yt:q.get(e.id)===false?It(G.get(e.id)):"Not run \u2014 the user declined another change in this same batch, so none of it was applied. Ask what they would prefer before proposing it again.",isError:true});continue}if(Ne){let i;if(q.has(e.id)){i=q.get(e.id)}else if(!X.turnScoped&&$?.has(`${n}.${s}`)){i=true;q.set(e.id,true)}else{yield{type:"approval-required",id:e.id,toolId:n,action:s,label:me,description:u.summary,reason:X.reason};const S=_();const R=await readTargetDigest({toolId:n,action:s,params:p,dispatch:c,catalog:o});const I=St(W?await W({id:e.id,toolId:n,action:s,label:me,description:u.summary,reason:X.reason,params:p,targetDigest:R}):false);ce+=_()-S;i=I.approved;q.set(e.id,i);if(I.trust)$?.add(`${n}.${s}`);if(I.reason)G.set(e.id,I.reason)}if(!i){for(const S of re("declined"))yield S;w.push({toolCallId:e.id,content:j==="question"?yt:It(G.get(e.id)),isError:true});continue}}if(Xt.has(`${n}.${s}`))Ye=true;if(n==="ask-buoy"&&s==="openProcedure")Ke=true;yield{type:"tool-start",id:e.id,toolId:n,action:s,label:me,description:u.summary,params:p,effect:u.effect};const at=_();const dt=await Fe(u,n,p,c);const _e=await ae(u,n,p,c);if(A?.aborted){for(const i of re("stopped"))yield i;w.push({toolCallId:e.id,content:"Not run \u2014 the user pressed Stop before this call started.",isError:true});continue}const lt=B({descriptor:u,toolId:n,policy:P,isRelease:D,turnScope:j,params:p,tapLabels:he.get(e.id)});if(lt.verdict==="refuse"){for(const i of re("refused"))yield i;w.push({toolCallId:e.id,content:lt.reason,isError:true});continue}try{let i=s===ht?Bt(n,await Lo(y,n),p):n==="ask-buoy"?await $t(s,k,c,z,p,F):await(nt.get(e.id)??c(n,s,p));i=Et(n,s,i);const S=Gt(Ht(i));const R=Rt(i);if(u.effect!=="read"&&!R)Qe=true;const I=No(n==="highlight-updates"&&s==="describeScreen"&&!R?io(S):S);const Z=z&&!R&&!(n==="ask-buoy"&&s==="retrieve")?z.stash({toolId:n,action:s,params:p,capturedAt:_(),text:I}):void 0;const v=_o(I,Z);ze.add(I);const Oe=v.length>wt?`${v.slice(0,wt)}\u2026`:v;yield{type:"tool-end",id:e.id,ok:!R,summary:Oo(i),durationMs:_()-at,result:Oe};const xe=_e===void 0||R?void 0:await ae(u,n,p,c);if(u.effect!=="read"&&n!=="ask-buoy"&&!R){const Le=k.noteExternalRevert(n,s,p);const ft=gt(n,u,p,i,dt,{before:_e,after:xe});if(ft&&!Le){const ut=k.record(n,s,ft,At);if(ut)ut.callId=e.id}}const ct=R?void 0:Qt({toolId:n,action:s,params:p,result:S,before:_e??dt,after:xe,effect:u.effect});if(ct)yield{type:"block",block:ct,forToolCallId:e.id};const ye=u.effect!=="read"&&!R?await ho({toolId:n,action:s,params:p,result:i,dispatch:c,readSnapshot:y,signal:A,after:xe}):void 0;if(ye)yield{type:"tool-verified",id:e.id,verification:ye};for(const Le of v.match(Nt)??[])Te.add(Le);w.push({toolCallId:e.id,content:v+xo(n,u,p,U)+ne+V+(ye?po(ye):"")+(tt.has(e.id)?oo:""),...Z?{ref:Z}:{}});if(n==="app"&&(s==="reloadApp"||s==="reload")){ot=true}}catch(i){const S=i instanceof Error?i.message:String(i);yield{type:"tool-end",id:e.id,ok:false,summary:S,durationMs:_()-at};w.push({toolCallId:e.id,content:`Failed: ${S}${V}`,isError:true})}}if(T.length){H.push(go(T));if(H.length>vt)H.shift();const e=!Je&&H.length===vt&&H.every(l=>l===H[0]);if(e){Je=true;const l=w[w.length-1];if(l)l.content=`${l.content}
|
|
9
11
|
|
|
10
|
-
${
|
|
12
|
+
${bo}`}}h.push({role:"tool-results",results:w});if(Ce){yield{type:"awaiting-user",blockId:Ce};yield{type:"done",stopReason:"awaiting-user"};return h}if(ot){yield{type:"done",stopReason:"realm-died"};return h}}if(A?.aborted){yield{type:"done",stopReason:"stopped"};return h}const J=[];let Ve=false;let Ee=false;const xt=[...h,{role:"user",text:wo}];const Lt=De(xt,we(),x.chars(te),x.charsPerToken,k.liveCallIds());try{for await(const m of r.send({messages:Lt.messages,system:a,systemVolatile:d,tools:de,toolChoice:"none",model:E,maxTokens:b,signal:A,meta:{askId:Ge,round:le+1,attempt:1}})){if(m.type==="text")J.push(m.delta);else if(m.type==="tool-call"||m.type==="error")Ee=true;else if(m.type==="meter")yield{type:"meter",frame:m.frame};else if(m.type==="done"){Ve=m.outcome==="completed";if(m.usage)yield{type:"usage",...m.usage,model:m.model}}}}catch{Ee=true}if(A?.aborted){yield{type:"done",stopReason:"stopped"};return h}const Xe=J.join("");if(Ee||!Ve||!Xe.trim()||bt(Xe)){const m=k.list().filter(C=>!Ct.has(C.id));J.length=0;J.push(["I ran out of steps. The job is not done.",...m.length?["These steps ran:",...m.map(C=>`- ${C.effect.label}${C.undoneAt?" (since undone)":""}`),"This list does not prove each change worked."]:[]].join("\n"))}let Ze=true;for(const m of J){if(!m)continue;yield{type:"text",delta:m,...Ze&&Se?{breakBefore:true}:{}};Ze=false}h.push({role:"assistant",text:J.join("")});yield{type:"block",block:{id:`cap${_()}`,kind:"notice",tone:"warning",text:"I ran out of steps. The job is not done. Tap Continue to go on.",actions:[{label:"Continue",primary:true,send:je}]}};yield{type:"done",stopReason:"step-cap"};return h}function xo(t,r,o,a){if(t!=="storage"||r.effect==="read")return"";if(!a||typeof o.key!=="string")return"";const d=a[o.key];if(!d)return"";return`
|
|
11
13
|
|
|
12
|
-
[Buoy] This wrote to disk, but "${
|
|
14
|
+
[Buoy] This wrote to disk, but "${o.key}" is the saved copy of the live "${d}" store, so nothing on screen has changed \u2014 the app read that key once at startup and has held the state in memory since. Call zustand.rehydrate({"storeName":"${d}"}) to make the app pick this up, or use zustand.setState next time to change the store directly. If you meant to set the value for the app's next launch, this is already done and no further action is needed.`}export{Pe as digestOf};export async function readTargetDigest(t){const r=M(t.catalog??pt,t.toolId,t.action);if(!r||r.effect==="read")return void 0;const o=await ae(r,t.toolId,t.params,t.dispatch);if(o!==void 0)return Pe(o);const a=await Fe(r,t.toolId,t.params,t.dispatch);if(a!==void 0)return Pe(a);return void 0}export async function runGatedAction(t){const{toolId:r,action:o,dispatch:a,ledger:d,policy:E,isRelease:b}=t;const c=t.catalog??pt;const y=M(c,r,o);if(!y){return{ok:false,error:`${r}.${o} is not in Buoy's catalog.`}}const U=se(r,o,t.params??{});const k=ge(U.params,y.params);if(ke(r,o,k))return{ok:false,error:Be};const P=be(k,y.params);if(!P.ok){return{ok:false,error:P.errors.join("\n")}}const D=B({descriptor:y,toolId:r,policy:E,isRelease:b});if(D.verdict==="refuse"){return{ok:false,error:D.reason}}const W=await Fe(y,r,k,a);const A=await ae(y,r,k,a);const z=B({descriptor:y,toolId:r,policy:E,isRelease:b});if(z.verdict==="refuse"){return{ok:false,error:z.reason}}try{let $=r==="ask-buoy"?await $t(o,d,a,void 0,k):await a(r,o,k);$=Et(r,o,$);if(Rt($)){const F=$.error;return{ok:false,error:typeof F==="string"?F:"The tool refused this."}}if(y.effect!=="read"&&r!=="ask-buoy"){const F=d.noteExternalRevert(r,o,k);const G=await ae(y,r,k,a);const x=gt(r,y,k,$,W,{before:A,after:G});if(x&&!F)d.record(r,o,x)}return{ok:true,result:$}}catch($){return{ok:false,error:$ instanceof Error?$.message:String($)}}}async function $t(t,r,o,a,d,E){if(t==="retrieve"){return uo(a,d??{})}if(t==="openProcedure"){const b=typeof d?.id==="string"?d.id:"";const c=E?.find(y=>y.id===b);if(!c){const y=(E??[]).map(U=>U.id);return{ok:false,error:y.length?`No procedure "${b}". This app's procedures: ${y.join(", ")}.`:"This app has no procedures written for it."}}return{id:c.id,title:c.title,...c.version?{version:c.version}:{},...c.requires?.length?{requires:c.requires}:{},body:c.body,note:"Follow these steps with the ordinary tools. Every write still goes through the same policy, approval and undo as any other call; a step that is refused stays refused."}}if(t==="listChanges"){const b=r.list().filter(c=>!c.undoneAt).map(c=>({id:c.id,toolId:c.toolId,action:c.action,kind:c.effect.kind,label:c.effect.label,reversible:mt(c.effect)}));return{changes:b,returned:b.length}}if(t==="undoChange"){const b=typeof d?.id==="string"?d.id:"";const c=r.list().find(U=>U.id===b);if(!c){const U=r.list().filter(k=>!k.undoneAt).map(k=>k.id);return{ok:false,error:`No change with id "${b}". Call listChanges for the current ids${U.length?` (${U.join(", ")})`:""}.`}}if(c.undoneAt)return{ok:false,error:`"${c.effect.label}" was already undone.`};if(!mt(c.effect)){return{ok:false,error:`"${c.effect.label}" can't be undone automatically \u2014 it is permanent.`}}const y=await r.revertOne(c,o);return y?{ok:false,error:y}:{ok:true,undone:{id:c.id,label:c.effect.label}}}if(t==="undoAll"){const b=await r.revertAll(o);return{ok:b.failed.length===0,...b}}throw new Error(`Unknown ask-buoy action "${t}"`)}async function Lo(t,r){if(!t){throw new Error(`This app cannot read ${r}'s snapshot \u2014 Buoy's tool registry is not published here.`)}return await t(r)}async function ae(t,r,o,a){if(r==="zustand"&&t.action==="setState"){if(typeof o.storeName!=="string")return void 0;try{return await a(r,"getStoreState",{storeName:o.storeName})}catch{return void 0}}if(r==="query"&&t.action==="setQueryData"){const d=typeof o.queryHash==="string"?o.queryHash:Array.isArray(o.queryKey)?qt(o.queryKey):void 0;if(!d)return void 0;try{return await a(r,"getQueryData",{queryHash:d})}catch{return void 0}}return void 0}async function Fe(t,r,o,a){if(t.effect==="read")return void 0;if(r==="network")return Uo(t,o,a);if(r!=="storage"||typeof o.key!=="string")return void 0;const d=t.action.startsWith("async.")?"async.getItem":t.action.startsWith("mmkv.")?"mmkv.get":void 0;if(!d)return void 0;const E={key:o.key};if(d==="mmkv.get"){if(typeof o.instanceId!=="string")return void 0;E.instanceId=o.instanceId}try{const b=await a(r,d,E);const c=b&&typeof b==="object"?b:void 0;if(c?.found===false)return void 0;const y=c?c.value:b;return{had:y!==void 0&&y!==null,value:y??void 0}}catch{return void 0}}async function Uo(t,r,o){if(t.action!=="setOverrideRuleEnabled"&&t.action!=="setOverridesEnabled"){return void 0}try{const a=await o("network","listOverrideRules",{});if(!a||typeof a!=="object")return void 0;if(t.action==="setOverridesEnabled"){return{had:true,value:String(a.enabled!==false)}}const d=(a.rules??[]).find(E=>E&&E.id===r.id);if(!d)return void 0;return{had:true,value:String(d.enabled!==false)}}catch{return void 0}}function Po(){const t="abcdefghijklmnopqrstuvwxyz0123456789";let r="ask_";for(let o=0;o<20;o++)r+=t[Math.floor(Math.random()*t.length)];return r}
|
|
@@ -14,6 +14,8 @@ You can read the app's live state and change it, through the Buoy tools availabl
|
|
|
14
14
|
- When you change something, say plainly what you changed, in the user's language ("I put the double burger out of stock at store 100"), not in tool terms.
|
|
15
15
|
- A WRITE'S RESULT IS CHECKED, AND THE CHECK TELLS YOU WHAT ACTUALLY HAPPENED. Some writes come back with a trailer: \`[Buoy] Verified: \u2026\` means the app was read back and shows the requested state \u2014 say it plainly. \`[Buoy] Unverified: \u2026\` means the write landed but the outcome is not visible yet (an override installed that no request has used) \u2014 do the thing the trailer names (a refetch, a visit to the screen) before saying the screen shows it, or say honestly that it will show on the next load. \`[Buoy] Check FAILED: \u2026\` means the app does NOT hold what you wrote: read the current state, work out why, and correct ONCE with a different, targeted change \u2014 never repeat the same write, never report the outcome as done.
|
|
16
16
|
- If a tool returns an empty list, check whether the tool needed to be recording first. Several Buoy tools only capture while something is watching them, so an empty result often means "nothing was recording", not "nothing happened". Say which one it is.
|
|
17
|
+
- An old error can show where to look. It does not prove this try failed. For a vague "it is broken, fix it" with no steps, read first. Find the fault now, then ask which step fails. Do not place an order or change test settings for that vague ask. If the user asked you to place an order, refund it, or make a change, do it and check the result. Do not ask them to grant that same step again. Still obey tool approval checks.
|
|
18
|
+
- If you place an order or change state to test a fix, say so plainly in your reply.
|
|
17
19
|
- A COUNT IS NOT A BUG UNTIL YOU HAVE CHECKED THE CLOCK. recentRequests and the events timeline accumulate for as long as the app has been open, so "23 calls to /orders/pending" is a polling interval times minutes, not one screen load, until the timestamps say otherwise. Before you call anything a bug, run the one check that would make it NOT one \u2014 the timestamps across the window, the query's refetchInterval, whether capture was on the whole time, whether the screen actually shows the wrong thing \u2014 and say in the finding what you checked. A finding you did not check is a guess wearing a card, and the person reading it cannot tell the two apart.
|
|
18
20
|
- WHAT YOU READ IS A RECORD OF WHAT HAS ALREADY HAPPENED, never a list of what this app has. The query cache holds what the app has already fetched THIS SESSION; recentRequests what it has already called; console, events, images and assets only what was recording or has already rendered. So a SHORT list means "nobody has been there yet", not "that is all there is" \u2014 and you have to work out which, exactly as you would for an empty one. Four of something is not the answer to "show me all of them". It is four of them, and a gap.
|
|
19
21
|
- GETTING DATA THAT ISN'T LOADED YET. You are inside the running app and you can drive it, so a gap is a job, not an answer. In order, cheapest first:
|
|
@@ -53,7 +55,7 @@ This app has configured you to look but not touch. Answer questions and diagnose
|
|
|
53
55
|
Actions classed as ${i.join(" and ")} need the user to tap Approve before they run. Buoy shows that card itself the moment you call one \u2014 so CALL THE ACTION rather than asking for permission in words or with a confirm block first. If the result says the user declined, respect it and ask what they would prefer instead.
|
|
54
56
|
|
|
55
57
|
Say what you are ABOUT to do, never what you have done, until the result is back. "Setting the Lugia line to 3" is right; "Bumped the Lugia line to 3" before the tap is a claim you cannot make \u2014 the user may decline, and then your own answer contradicts itself in the same breath.`)}else if(h){t.push(`APPROVALS ARE OFF
|
|
56
|
-
The user has turned approval prompts off on this device.
|
|
58
|
+
The user has turned approval prompts off on this device. Task writes can run at once, even wipes and resets. A question still needs a tap before a data change. So: do only what was actually asked, one change at a time; never run a destructive action speculatively, in bulk, or to find out what it does; and read the current state before you overwrite it. Say what you are about to change in the same message you change it, then report what happened. If a request is ambiguous and one reading is destructive, ask with buoy_ui choice instead of guessing \u2014 a broad "reset everything" always is.`)}t.push(`SHOWING THINGS
|
|
57
59
|
You have a \`buoy_ui\` tool. Use it instead of prose whenever the answer is a set of things, a picture, a comparison, a number, or a decision the user has to make:
|
|
58
60
|
- A request could mean two things \u2192 buoy_ui choice. Never guess between real alternatives.
|
|
59
61
|
- You are about to write APP STATE in a shape you did not read (a store, a cache entry), or act as a user you invented \u2192 buoy_ui confirm first. A mock response the user described ("200 with an error in the body", "a 503 with a maintenance message") is not a guess: write it \u2014 for an endpoint you have not seen, a plain {"error": "...", "message": "..."} body \u2014 and say what you sent. Do NOT pre-confirm destructive tool actions: just call them. Buoy shows the user its own approval card and runs the action only if they tap Approve, so asking first makes them answer twice.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";import{realClearTimeout as S,realNow as w,realSetTimeout as A}from"../realNow";const u=e=>e&&typeof e==="object"&&!Array.isArray(e)?e:void 0;function g(e,n){return new Promise(r=>{if(n?.aborted)return r();const t=A(i,e);function i(){S(t);n?.removeEventListener("abort",i);r()}n?.addEventListener("abort",i,{once:true})})}async function y(e,n,r,t,i){const a=w()+r;for(;;){const o=await e();if(n(o))return{value:o,satisfied:true};if(i?.aborted||w()+t>a)return{value:o,satisfied:false};await g(t,i)}}export function isSubset(e,n){if(e===null||typeof e!=="object"||Array.isArray(e))return JSON.stringify(e)===JSON.stringify(n);const r=u(n);if(!r)return false;for(const[t,i]of Object.entries(e)){if(!(t in r))return false;if(!isSubset(i,r[t]))return false}return true}export function atPath(e,n){const r=n.replace(/^\/+/,"").match(/\[[^\]]*\]|[^.[\]/]+/g)??[];let t=e;for(const i of r){if(t===null||typeof t!=="object")return void 0;if(i.startsWith("[")){const a=i.slice(1,-1).trim();if(!Array.isArray(t))return void 0;const o=a.indexOf("=");if(o<0){t=t[Number(a)]}else{const s=a.slice(0,o).trim();const d=a.slice(o+1).trim().replace(/^["']|["']$/g,"");t=t.find(c=>c&&typeof c==="object"&&String(c[s])===d)}}else{t=t[i]}}return t}const l=e=>{const n=JSON.stringify(e);return n===void 0?"undefined":n.length>80?`${n.slice(0,77)}\u2026`:n};const m=async({params:e,dispatch:n})=>{if(typeof e.key!=="string")return void 0;const r=await n("storage","async.getItem",{key:e.key});const t=typeof r==="string"?r:u(r)?.value;const i=typeof e.value==="string"?e.value:JSON.stringify(e.value);if(t===i)return{status:"verified",detail:`Read back: "${e.key}" now holds the written value.`};return{status:"failed",detail:`Read back after the write: "${e.key}" holds ${l(t)}, not what was written. The write did not take.`}};function N(e){if(typeof e.path==="string"){const t=e.path.split(".").pop()?.replace(/\[.*\]$/,"")??"";return t?[[t,e.value]]:[]}const n=[];const r=(t,i,a)=>{const o=u(t);if(o&&a<4)for(const[s,d]of Object.entries(o))r(d,s,a+1);else if(i&&(typeof t==="number"||typeof t==="string"||typeof t==="boolean"))n.push([i,t])};r(e.state,"",0);return n}function v(e,n,r,t=0){const i=u(e);if(!i||t>4)return[];const a=[];for(const[o,s]of Object.entries(i)){if(o===n&&(typeof s==="number"||typeof s==="string"||typeof s==="boolean")&&JSON.stringify(s)!==JSON.stringify(r))a.push(s);else if(u(s))a.push(...v(s,n,r,t+1))}return a}const O=new Set(["id","key","type","name","title","status","value","label"]);async function R(e,n){const r=N(e).filter(([a])=>a.length>2&&!O.has(a));if(!r.length)return void 0;const t=u(await n("query","listQueries",{limit:25}).catch(()=>void 0));const i=(Array.isArray(t?.queries)?t.queries:[]).map(u).filter(a=>!!a&&Number(a.observers)>0&&typeof a.queryHash==="string").slice(0,5);for(const a of i){const o=u(await n("query","getQueryData",{queryHash:a.queryHash}).catch(()=>void 0));if(!o||o.found===false)continue;for(const[s,d]of r){const c=v(o.data,s,d);if(c.length)return`The query ${a.queryHash} on screen also has ${s} = ${l(c[0])}. If the screen reads that query, it still shows ${l(c[0])}: check the screen, and change the query (setQueryData) if so.`}}return void 0}const T=async({params:e,dispatch:n,after:r})=>{const t=await _({params:e,dispatch:n,after:r});if(t?.status!=="verified")return t;const i=await R(e,n).catch(()=>void 0);return i?{status:"unverified",detail:`${t.detail.replace(/\.$/,"")}, but that is the store, not the screen. ${i}`}:t};const _=async({params:e,dispatch:n,after:r})=>{if(typeof e.storeName!=="string")return void 0;const t=u(r!==void 0?r:await n("zustand","getStoreState",{storeName:e.storeName}));if(!t||t.found===false)return{status:"failed",detail:`Read back: store "${e.storeName}" could not be read after the write.`};const i=t.currentState;if(typeof e.path==="string"){const s=atPath(i,e.path);if(JSON.stringify(s)===JSON.stringify(e.value))return{status:"verified",detail:`Read back: ${e.storeName}.${e.path} is now ${l(s)}.`};return{status:"failed",detail:`Read back: ${e.storeName}.${e.path} is ${l(s)}, not ${l(e.value)}. The store did not take the write.`}}const a=u(e.state);if(!a)return void 0;if(isSubset(a,i))return{status:"verified",detail:`Read back: "${e.storeName}" now holds the written fields (${Object.keys(a).join(", ")}).`};const o=Object.keys(a).filter(s=>!isSubset(a[s],u(i)?.[s]));return{status:"failed",detail:`Read back: "${e.storeName}" does not hold the written value for ${o.join(", ")}. The store did not take the write \u2014 read it before deciding what to do.`}};const E=async({params:e,dispatch:n,after:r,signal:t})=>{const i=e.queryHash!==void 0?{queryHash:e.queryHash}:e.queryKey!==void 0?{queryKey:e.queryKey}:void 0;if(!i)return void 0;const a=u(r!==void 0?r:await n("query","getQueryData",i));if(!a||a.found===false)return{status:"failed",detail:"Read back: the query could not be read after the write."};const o=a.data;if(typeof e.path==="string"){const s=atPath(o,e.path);if(JSON.stringify(s)===JSON.stringify(e.value))return b(e,n,`Read back: the cached ${e.path} is now ${l(s)}.`,t);return{status:"failed",detail:`Read back: the cached ${e.path} is ${l(s)}, not ${l(e.value)}. The cache did not take the write \u2014 the app may have refetched over it.`}}if(e.data===void 0)return void 0;if(isSubset(e.data,o))return b(e,n,"Read back: the cache now holds the written data.",t);return{status:"failed",detail:"Read back: the cache does not hold the written data \u2014 the app may have refetched over it, or the shape differed."}};async function b(e,n,r,t){const i=typeof e.queryHash==="string"?e.queryHash:Array.isArray(e.queryKey)?JSON.stringify(e.queryKey):void 0;const a=i?await $(n,i).catch(()=>void 0):void 0;const o=typeof a?.refetchEveryMs==="number"?a.refetchEveryMs:void 0;if(!i||!o||o>1e4)return{status:"verified",detail:r};await g(o+750,t);if(t?.aborted)return{status:"verified",detail:r};const s=u(await n("query","getQueryData",{queryHash:i}).catch(()=>void 0));if(!s||s.found===false)return{status:"verified",detail:r};const d=typeof e.path==="string"?JSON.stringify(atPath(s.data,e.path))===JSON.stringify(e.value):e.data!==void 0&&isSubset(e.data,s.data);if(d)return{status:"verified",detail:`${r} It is still there after the screen's ${o} ms refetch.`};return{status:"failed",detail:`${r} But this screen refetches every ${o} ms, and it already has: the server's data replaced the edit. For a change that stays, override the API response \u2014 network.upsertOverrideRule (fromRequestId + bodyPatch, or a full body), then query.invalidate.`}}const I=async({params:e,dispatch:n,signal:r})=>{if(typeof e.path!=="string")return void 0;const t=e.path.split("?")[0];const{value:i,satisfied:a}=await y(async()=>u(await n("route-events","getCurrentRoute",{})),s=>typeof s?.path==="string"&&(s.path===t||s.path.split("?")[0]===t),2e3,250,r);if(a)return{status:"verified",detail:`The app is now on ${t}.`};const o=typeof i?.path==="string"?i.path:"an unknown route";return{status:"failed",detail:`Two seconds after navigating, the app is on ${o}, not ${t}. Do not navigate again blindly \u2014 check the route exists (the sitemap) and whether something redirected.`}};const j=async({params:e,result:n,dispatch:r,signal:t})=>{const i=u(u(n)?.rule)?.id??u(e.rule)?.id;if(typeof i!=="string")return void 0;const a=async()=>{const d=u(await r("network","listOverrideRules",{}));const c=Array.isArray(d?.rules)?d.rules:[];return c.map(u).find(p=>p?.id===i)};const{value:o,satisfied:s}=await y(a,d=>typeof d?.hits==="number"&&d.hits>0,3e3,500,t);if(!o)return{status:"failed",detail:"The rule is not in the override list after the write. It did not install."};if(o.enabled===false)return{status:"failed",detail:"The rule is installed but disabled, so it will not fire."};if(s)return{status:"verified",detail:`The rule has matched ${o.hits} request${o.hits===1?"":"s"} \u2014 the app has already received the overridden response.`};return{status:"unverified",detail:"The rule is installed, but no request has matched it yet \u2014 the app is still showing whatever it loaded before. A refetch or a visit to the screen that fetches this will exercise it; until then, do not say the screen shows the override."}};async function $(e,n){const r=u(await e("query","listQueries",{limit:100}));const t=Array.isArray(r?.queries)?r.queries:[];return t.map(u).find(i=>i?.queryHash===n)}function k(e,n,r){return async({params:t,dispatch:i,signal:a})=>{if(typeof t.queryHash!=="string")return void 0;const o=async()=>{const c=await $(i,t.queryHash);return typeof c?.status==="string"?c.status:void 0};const{value:s,satisfied:d}=await y(o,c=>c!==void 0&&!e(c),3e3,500,a);if(s===void 0)return void 0;if(!d)return{status:"verified",detail:`Still ${n} three seconds later.`};return{status:"failed",detail:`Within three seconds the app refetched and the query is "${s}" again: this screen polls, so a cache ${n} pin cannot last. ${r}`}}}const x=k(e=>e==="error","error","For an error that stays, make the API fail instead \u2014 network.upsertOverrideRule with status 500 for this endpoint, then query.invalidate \u2014 and restoreError this query.");const D=k(e=>e==="fetching"||e==="pending"||e==="loading","loading","To keep it loading, delay the API instead \u2014 network.upsertOverrideRule with a long delayMs (60000) for this endpoint, then query.invalidate \u2014 and restoreLoading this query.");const H=async({dispatch:e,signal:n})=>{await g(2e3,n);const{satisfied:r}=await y(async()=>{try{return u(await e("app","ping",{}))?.ok===true}catch{return false}},t=>t,4e4,1500,n);return r?{status:"verified",detail:"The app reloaded and is answering again \u2014 read its screen or state now."}:{status:"failed",detail:"The app has not answered for 40 seconds after the relaunch. It may have crashed on start: check the console, then reload_app."}};const J={"phone-call":2e4,"quick-switch":5e3,"low-memory":1e4};const q=async({action:e,params:n,dispatch:r,signal:t})=>{let i;if(e==="runRecipe")i=J[String(n.id)];else if(e==="background"&&n.duration!==void 0&&n.skipWait!==true){const f=n.duration;const h=/^(\d+(?:\.\d+)?)\s*(ms|s|m)$/.exec(String(f));i=typeof f==="number"?f:h?Number(h[1])*(h[2]==="ms"?1:h[2]==="s"?1e3:6e4):void 0}if(!i||i>12e4)return void 0;const{satisfied:a}=await y(async()=>u(await r("lifecycle","getState",{}).catch(()=>void 0)),f=>!!f&&(f.away===null||f.away===void 0)&&f.realAppState!=="background",i+8e3,1e3,t);if(!a)return{status:"unverified",detail:`The app has not come back yet (expected about ${Math.round(i/1e3)} s). Do not report the result until it has.`};const o=await y(async()=>u(u(await r("lifecycle","getState",{}).catch(()=>void 0))?.report),f=>!f||f.collectingUntil===null||f.collectingUntil===void 0,8e3,1e3,t);const s=o.value;const d=u(s?.counts);const c=d&&Object.keys(d).length?` Seen during it: ${Object.entries(d).map(([f,h])=>`${f} ${h}`).join(", ")}.`:" Nothing was recorded during it.";const p=typeof s?.finding==="string"?` ${s.finding}`:"";return{status:"verified",detail:`The interruption is over and the app is active again.${s?`${p}${c}`:""}`}};const C=async({readSnapshot:e,signal:n})=>{if(!e)return void 0;const r=w();await g(1500,n);const t=u(await Promise.resolve(e("console")).catch(()=>void 0));const i=(Array.isArray(t?.entries)?t.entries:Array.isArray(t)?t:[]).map(u).filter(a=>!!a&&Number(a.timestamp??a.at??0)>=r-250).slice(-6).map(a=>`${String(a.level??a.type??"log")}: ${String(a.message??(Array.isArray(a.args)?a.args.join(" "):"")).slice(0,160)}`);if(!i.length)return{status:"unverified",detail:"Delivered. The app logged nothing in the next 1.5 s; check the screen or report for its reaction."};return{status:"verified",detail:`Delivered. The app logged right after: ${i.join(" | ")}`}};const L=/^\s*(save|submit|update|apply|done|confirm)\b/i;const P=async({result:e,dispatch:n})=>{const r=u(u(e)?.matched);const t=typeof r?.via==="string"?r.via:"";if(t!=="onValueChange"&&t!=="onChangeText")return void 0;const i=u(await n("highlight-updates","describeScreen",{}).catch(()=>void 0));const a=Array.isArray(i?.elements)?i.elements.map(u):[];const o=a.find(d=>!!d&&d.interactive===true&&L.test(String(d.label??d.text??""))&&d.nativeTag!==r?.nativeTag);if(!o)return void 0;const s=String(o.label??o.text).trim();return{status:"unverified",detail:`Changed on screen only. This screen has a "${s}" button: the change isn't saved until it's pressed. Press it, then check the result.`}};export const VERIFIERS={"highlight-updates.tapElement":P,"lifecycle.memoryWarning":C,"lifecycle.relaunch":H,"lifecycle.runRecipe":q,"lifecycle.background":q,"query.triggerError":x,"query.triggerLoading":D,"storage.async.setItem":m,"zustand.setState":T,"query.setQueryData":E,"route-events.navigate":I,"network.upsertOverrideRule":j};export async function verifyOutcome(e){const n=VERIFIERS[`${e.toolId}.${e.action}`];if(!n)return void 0;try{return await n(e)}catch{return void 0}}export function verificationTrailer(e){switch(e.status){case"verified":return`
|
|
1
|
+
"use strict";import{realClearTimeout as N,realNow as w,realSetTimeout as O}from"../realNow";const u=e=>e&&typeof e==="object"&&!Array.isArray(e)?e:void 0;function v(e,n){return new Promise(r=>{if(n?.aborted)return r();const t=O(i,e);function i(){N(t);n?.removeEventListener("abort",i);r()}n?.addEventListener("abort",i,{once:true})})}async function g(e,n,r,t,i){const a=w()+r;for(;;){const o=await e();if(n(o))return{value:o,satisfied:true};if(i?.aborted||w()+t>a)return{value:o,satisfied:false};await v(t,i)}}export function isSubset(e,n){if(e===null||typeof e!=="object"||Array.isArray(e))return JSON.stringify(e)===JSON.stringify(n);const r=u(n);if(!r)return false;for(const[t,i]of Object.entries(e)){if(!(t in r))return false;if(!isSubset(i,r[t]))return false}return true}export function atPath(e,n){const r=n.replace(/^\/+/,"").match(/\[[^\]]*\]|[^.[\]/]+/g)??[];let t=e;for(const i of r){if(t===null||typeof t!=="object")return void 0;if(i.startsWith("[")){const a=i.slice(1,-1).trim();if(!Array.isArray(t))return void 0;const o=a.indexOf("=");if(o<0){t=t[Number(a)]}else{const s=a.slice(0,o).trim();const d=a.slice(o+1).trim().replace(/^["']|["']$/g,"");t=t.find(c=>c&&typeof c==="object"&&String(c[s])===d)}}else{t=t[i]}}return t}const h=e=>{const n=JSON.stringify(e);return n===void 0?"undefined":n.length>80?`${n.slice(0,77)}\u2026`:n};const R=async({params:e,dispatch:n})=>{if(typeof e.key!=="string")return void 0;const r=await n("storage","async.getItem",{key:e.key});const t=typeof r==="string"?r:u(r)?.value;const i=typeof e.value==="string"?e.value:JSON.stringify(e.value);if(t===i)return{status:"verified",detail:`Read back: "${e.key}" now holds the written value.`};return{status:"failed",detail:`Read back after the write: "${e.key}" holds ${h(t)}, not what was written. The write did not take.`}};function T(e){if(typeof e.path==="string"){const t=e.path.split(".").pop()?.replace(/\[.*\]$/,"")??"";return t?[[t,e.value]]:[]}const n=[];const r=(t,i,a)=>{const o=u(t);if(o&&a<4)for(const[s,d]of Object.entries(o))r(d,s,a+1);else if(i&&(typeof t==="number"||typeof t==="string"||typeof t==="boolean"))n.push([i,t])};r(e.state,"",0);return n}function $(e,n,r,t=0){const i=u(e);if(!i||t>4)return[];const a=[];for(const[o,s]of Object.entries(i)){if(o===n&&(typeof s==="number"||typeof s==="string"||typeof s==="boolean")&&JSON.stringify(s)!==JSON.stringify(r))a.push(s);else if(u(s))a.push(...$(s,n,r,t+1))}return a}const _=new Set(["id","key","type","name","title","status","value","label"]);async function E(e,n){const r=T(e).filter(([a])=>a.length>2&&!_.has(a));if(!r.length)return void 0;const t=u(await n("query","listQueries",{limit:25}).catch(()=>void 0));const i=(Array.isArray(t?.queries)?t.queries:[]).map(u).filter(a=>!!a&&Number(a.observers)>0&&typeof a.queryHash==="string").slice(0,5);for(const a of i){const o=u(await n("query","getQueryData",{queryHash:a.queryHash}).catch(()=>void 0));if(!o||o.found===false)continue;for(const[s,d]of r){const c=$(o.data,s,d);if(c.length)return`The query ${a.queryHash} on screen also has ${s} = ${h(c[0])}. If the screen reads that query, it still shows ${h(c[0])}: check the screen, and change the query (setQueryData) if so.`}}return void 0}const j=async({params:e,dispatch:n,after:r})=>{const t=await I({params:e,dispatch:n,after:r});if(t?.status!=="verified")return t;const i=await E(e,n).catch(()=>void 0);return i?{status:"unverified",detail:`${t.detail.replace(/\.$/,"")}, but that is the store, not the screen. ${i}`}:t};const I=async({params:e,dispatch:n,after:r})=>{if(typeof e.storeName!=="string")return void 0;const t=u(r!==void 0?r:await n("zustand","getStoreState",{storeName:e.storeName}));if(!t||t.found===false)return{status:"failed",detail:`Read back: store "${e.storeName}" could not be read after the write.`};const i=t.currentState;if(typeof e.path==="string"){const s=atPath(i,e.path);if(JSON.stringify(s)===JSON.stringify(e.value))return{status:"verified",detail:`Read back: ${e.storeName}.${e.path} is now ${h(s)}.`};return{status:"failed",detail:`Read back: ${e.storeName}.${e.path} is ${h(s)}, not ${h(e.value)}. The store did not take the write.`}}const a=u(e.state);if(!a)return void 0;if(isSubset(a,i))return{status:"verified",detail:`Read back: "${e.storeName}" now holds the written fields (${Object.keys(a).join(", ")}).`};const o=Object.keys(a).filter(s=>!isSubset(a[s],u(i)?.[s]));return{status:"failed",detail:`Read back: "${e.storeName}" does not hold the written value for ${o.join(", ")}. The store did not take the write \u2014 read it before deciding what to do.`}};const x=async({params:e,dispatch:n,after:r,signal:t})=>{const i=e.queryHash!==void 0?{queryHash:e.queryHash}:e.queryKey!==void 0?{queryKey:e.queryKey}:void 0;if(!i)return void 0;const a=u(r!==void 0?r:await n("query","getQueryData",i));if(!a||a.found===false)return{status:"failed",detail:"Read back: the query could not be read after the write."};const o=a.data;if(typeof e.path==="string"){const s=atPath(o,e.path);if(JSON.stringify(s)===JSON.stringify(e.value))return k(e,n,`Read back: the cached ${e.path} is now ${h(s)}.`,t);return{status:"failed",detail:`Read back: the cached ${e.path} is ${h(s)}, not ${h(e.value)}. The cache did not take the write \u2014 the app may have refetched over it.`}}if(e.data===void 0)return void 0;if(isSubset(e.data,o))return k(e,n,"Read back: the cache now holds the written data.",t);return{status:"failed",detail:"Read back: the cache does not hold the written data \u2014 the app may have refetched over it, or the shape differed."}};async function k(e,n,r,t){const i=typeof e.queryHash==="string"?e.queryHash:Array.isArray(e.queryKey)?JSON.stringify(e.queryKey):void 0;const a=i?await q(n,i).catch(()=>void 0):void 0;const o=typeof a?.refetchEveryMs==="number"?a.refetchEveryMs:void 0;if(!i||!o||o>1e4)return{status:"verified",detail:r};await v(o+750,t);if(t?.aborted)return{status:"verified",detail:r};const s=u(await n("query","getQueryData",{queryHash:i}).catch(()=>void 0));if(!s||s.found===false)return{status:"verified",detail:r};const d=typeof e.path==="string"?JSON.stringify(atPath(s.data,e.path))===JSON.stringify(e.value):e.data!==void 0&&isSubset(e.data,s.data);if(d)return{status:"verified",detail:`${r} It is still there after the screen's ${o} ms refetch.`};return{status:"failed",detail:`${r} But this screen refetches every ${o} ms, and it already has: the server's data replaced the edit. For a change that stays, override the API response \u2014 network.upsertOverrideRule (fromRequestId + bodyPatch, or a full body), then query.invalidate.`}}const J=async({params:e,dispatch:n,signal:r})=>{if(typeof e.path!=="string")return void 0;const t=e.path.split("?")[0];const i=new URLSearchParams(e.path.split("?").slice(1).join("?").split("#")[0]);const a=l=>{const f=u(l?.params);const y=Array.from(new Set(Array.from(i.keys())));return y.filter(b=>{const p=f?.[b];const A=Array.isArray(p)?p.map(String):p===void 0||p===null?[]:[String(p)];return JSON.stringify(i.getAll(b))!==JSON.stringify(A)})};const o=l=>typeof l?.path==="string"&&l.path.split("?")[0]===t;const{value:s,satisfied:d}=await g(async()=>u(await n("route-events","getCurrentRoute",{})),l=>o(l)&&a(l).length===0,2e3,250,r);if(d)return{status:"verified",detail:`The app is now on ${t}.`};if(o(s))return{status:"unverified",detail:`The app is on ${t}. These route params are missing or do not match: ${a(s).join(", ")}.`};const c=typeof s?.path==="string"?s.path:"an unknown route";return{status:"failed",detail:`Two seconds after navigating, the app is on ${c}, not ${t}. Do not navigate again blindly \u2014 check the route exists (the sitemap) and whether something redirected.`}};const D=async({params:e,result:n,dispatch:r,signal:t})=>{const i=u(u(n)?.rule)?.id??u(e.rule)?.id;if(typeof i!=="string")return void 0;const a=async()=>{const d=u(await r("network","listOverrideRules",{}));const c=Array.isArray(d?.rules)?d.rules:[];return c.map(u).find(l=>l?.id===i)};const{value:o,satisfied:s}=await g(a,d=>typeof d?.hits==="number"&&d.hits>0,3e3,500,t);if(!o)return{status:"failed",detail:"The rule is not in the override list after the write. It did not install."};if(o.enabled===false)return{status:"failed",detail:"The rule is installed but disabled, so it will not fire."};if(s)return{status:"verified",detail:`The rule has matched ${o.hits} request${o.hits===1?"":"s"} \u2014 the app has already received the overridden response.`};return{status:"unverified",detail:"The rule is installed, but no request has matched it yet \u2014 the app is still showing whatever it loaded before. A refetch or a visit to the screen that fetches this will exercise it; until then, do not say the screen shows the override."}};async function q(e,n){const r=u(await e("query","listQueries",{limit:100}));const t=Array.isArray(r?.queries)?r.queries:[];return t.map(u).find(i=>i?.queryHash===n)}function S(e,n,r){return async({params:t,dispatch:i,signal:a})=>{if(typeof t.queryHash!=="string")return void 0;const o=async()=>{const c=await q(i,t.queryHash);return typeof c?.status==="string"?c.status:void 0};const{value:s,satisfied:d}=await g(o,c=>c!==void 0&&!e(c),3e3,500,a);if(s===void 0)return void 0;if(!d)return{status:"verified",detail:`Still ${n} three seconds later.`};return{status:"failed",detail:`Within three seconds the app refetched and the query is "${s}" again: this screen polls, so a cache ${n} pin cannot last. ${r}`}}}const H=S(e=>e==="error","error","For an error that stays, make the API fail instead \u2014 network.upsertOverrideRule with status 500 for this endpoint, then query.invalidate \u2014 and restoreError this query.");const L=S(e=>e==="fetching"||e==="pending"||e==="loading","loading","To keep it loading, delay the API instead \u2014 network.upsertOverrideRule with a long delayMs (60000) for this endpoint, then query.invalidate \u2014 and restoreLoading this query.");const P=async({dispatch:e,signal:n})=>{await v(2e3,n);const{satisfied:r}=await g(async()=>{try{return u(await e("app","ping",{}))?.ok===true}catch{return false}},t=>t,4e4,1500,n);return r?{status:"verified",detail:"The app reloaded and is answering again \u2014 read its screen or state now."}:{status:"failed",detail:"The app has not answered for 40 seconds after the relaunch. It may have crashed on start: check the console, then reload_app."}};const C={"phone-call":2e4,"quick-switch":5e3,"low-memory":1e4};const m=async({action:e,params:n,dispatch:r,signal:t})=>{let i;if(e==="runRecipe")i=C[String(n.id)];else if(e==="background"&&n.duration!==void 0&&n.skipWait!==true){const f=n.duration;const y=/^(\d+(?:\.\d+)?)\s*(ms|s|m)$/.exec(String(f));i=typeof f==="number"?f:y?Number(y[1])*(y[2]==="ms"?1:y[2]==="s"?1e3:6e4):void 0}if(!i||i>12e4)return void 0;const{satisfied:a}=await g(async()=>u(await r("lifecycle","getState",{}).catch(()=>void 0)),f=>!!f&&(f.away===null||f.away===void 0)&&f.realAppState!=="background",i+8e3,1e3,t);if(!a)return{status:"unverified",detail:`The app has not come back yet (expected about ${Math.round(i/1e3)} s). Do not report the result until it has.`};const o=await g(async()=>u(u(await r("lifecycle","getState",{}).catch(()=>void 0))?.report),f=>!f||f.collectingUntil===null||f.collectingUntil===void 0,8e3,1e3,t);const s=o.value;const d=u(s?.counts);const c=d&&Object.keys(d).length?` Seen during it: ${Object.entries(d).map(([f,y])=>`${f} ${y}`).join(", ")}.`:" Nothing was recorded during it.";const l=typeof s?.finding==="string"?` ${s.finding}`:"";return{status:"verified",detail:`The interruption is over and the app is active again.${s?`${l}${c}`:""}`}};const Q=async({readSnapshot:e,signal:n})=>{if(!e)return void 0;const r=w();await v(1500,n);const t=u(await Promise.resolve(e("console")).catch(()=>void 0));const i=(Array.isArray(t?.entries)?t.entries:Array.isArray(t)?t:[]).map(u).filter(a=>!!a&&Number(a.timestamp??a.at??0)>=r-250).slice(-6).map(a=>`${String(a.level??a.type??"log")}: ${String(a.message??(Array.isArray(a.args)?a.args.join(" "):"")).slice(0,160)}`);if(!i.length)return{status:"unverified",detail:"Delivered. The app logged nothing in the next 1.5 s; check the screen or report for its reaction."};return{status:"verified",detail:`Delivered. The app logged right after: ${i.join(" | ")}`}};const B=/^\s*(save|submit|update|apply|done|confirm)\b/i;const M=async({result:e,dispatch:n})=>{const r=u(u(e)?.matched);const t=typeof r?.via==="string"?r.via:"";if(t!=="onValueChange"&&t!=="onChangeText")return void 0;const i=u(await n("highlight-updates","describeScreen",{}).catch(()=>void 0));const a=Array.isArray(i?.elements)?i.elements.map(u):[];const o=a.find(d=>!!d&&d.interactive===true&&B.test(String(d.label??d.text??""))&&d.nativeTag!==r?.nativeTag);if(!o)return void 0;const s=String(o.label??o.text).trim();return{status:"unverified",detail:`Changed on screen only. This screen has a "${s}" button: the change isn't saved until it's pressed. Press it, then check the result.`}};export const VERIFIERS={"highlight-updates.tapElement":M,"lifecycle.memoryWarning":Q,"lifecycle.relaunch":P,"lifecycle.runRecipe":m,"lifecycle.background":m,"query.triggerError":H,"query.triggerLoading":L,"storage.async.setItem":R,"zustand.setState":j,"query.setQueryData":x,"route-events.navigate":J,"network.upsertOverrideRule":D};export async function verifyOutcome(e){const n=VERIFIERS[`${e.toolId}.${e.action}`];if(!n)return void 0;try{return await n(e)}catch{return void 0}}export function verificationTrailer(e){switch(e.status){case"verified":return`
|
|
2
2
|
|
|
3
3
|
[Buoy] Verified: ${e.detail}`;case"unverified":return`
|
|
4
4
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{titleCall as
|
|
1
|
+
"use strict";import{isQuestionLookup as c}from"./turnScope";import{titleCall as l}from"./labels";export const DEFAULT_REQUIRE_APPROVAL=["destructive"];export function resolveRequireApproval(e){return e.requireApproval??DEFAULT_REQUIRE_APPROVAL}const d=new Set(["secure.get","secure.snapshot"]);export function decide({descriptor:e,toolId:t,policy:n,isRelease:s,turnScope:i,tapLabels:o,params:u={}}){for(const a of n.deny??[]){if(a.toolId===t&&(!a.action||a.action===e.action)){return{verdict:"refuse",reason:"This action is disabled in this app."}}}if(s&&e.release!=="works"){return{verdict:"refuse",reason:f(e)}}if(n.allow){const a=n.allow.some(r=>(r.toolId===void 0||r.toolId===t)&&(r.action===void 0||r.action===e.action)&&(r.effect===void 0||r.effect===e.effect));if(!a){return{verdict:"refuse",reason:"This action isn't on Ask Buoy's allow list in this app."}}}if(t==="storage"&&d.has(e.action)&&n.secureReads!==true){return{verdict:"refuse",reason:"Reading SecureStore values is off by default \u2014 they are credentials, and they would be sent to the configured model endpoint. Key names are still readable via secure.keys; the app can opt in with policy.secureReads: true."}}if(e.effect!=="read"&&n.readOnly){return{verdict:"refuse",reason:"Ask Buoy is in read-only mode in this app, so it can look at state but not change it."}}if(i==="question"&&e.effect!=="read"&&!c(t,e.action,u,o)){const a=t==="impersonate"?"who the app acts as or their settings":t==="storage"?"saved app data":t==="highlight-updates"?"the app with this tap":"the app's state";return{verdict:"needs-approval",turnScoped:true,reason:`You asked a question. This would change ${a}. Go ahead?`}}for(const a of n.requireApprovalFor??[]){if(a.toolId===t&&(!a.action||a.action===e.action)){return{verdict:"needs-approval",reason:"This app asks for a tap before this particular action runs."}}}if(e.effect==="read")return{verdict:"allow"};if(resolveRequireApproval(n).includes(e.effect)){return{verdict:"needs-approval",reason:e.effect==="destructive"?"Buoy can't undo this one \u2014 that's why it's asking.":"This will change the app's state."}}return{verdict:"allow"}}function f(e){const t=`\`${e.action}\` does not work in this build (a release build).`;switch(e.release){case"noop":return`${t} It would report success and change nothing, so Buoy refused to run it rather than let you be told it worked. ${e.releaseNote??""}`.trim();case"empty":return`${t} It relies on React's developer hook, which React Native only installs in development builds, so it can only ever return empty results here. ${e.releaseNote??""}`.trim();case"throws":return`${t} It is explicitly disabled outside development. ${e.releaseNote??""}`.trim();default:return`${t} Buoy could not confirm it behaves correctly outside development, so it refused rather than guess.`}}export function describeCall(e,t,n){return l(e,t.action,n)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const a=["authorization","cookie","setcookie","apikey","proxyauthorization","authtoken","accesstoken","refreshtoken","idtoken","sessiontoken","bearertoken","licensekey","licencekey","buoykey","privatekey","secret","password","passwd","credential"];const f="[redacted by Buoy]";const l=[{re:/\bBearer\s+[A-Za-z0-9._~+/-]{12,}=*/gi,label:"[bearer token removed]"},{re:/\beyJ[A-Za-z0-9._-]{20,}/g,label:"[jwt removed]"},{re:/\bsk-[A-Za-z0-9_-]{16,}/g,label:"[api key removed]"},{re:/\bBUOY-[A-Z0-9-]{8,}/g,label:"[license key removed]"},{re:/\b[A-F0-9]{6}(?:-[A-F0-9]{6}){4}-V\d\b/g,label:"[license key removed]"},{re:/("|')?[A-Za-z0-9_-]*(authorization|api[_-]?key|password|passwd|secret|access[_-]?token|refresh[_-]?token|auth[_-]?token|session[_-]?token|license[_-]?key|licence[_-]?key|buoy[_-]?key|private[_-]?key)\1?\s*[:=]\s*("|')?(?!(?:authorization|bearer|cookie|header)\b)[^\s"',}]{6,}/gi,label:"[credential removed]"}];function
|
|
1
|
+
"use strict";const a=["authorization","cookie","setcookie","apikey","proxyauthorization","authtoken","accesstoken","refreshtoken","idtoken","sessiontoken","bearertoken","licensekey","licencekey","buoykey","privatekey","secret","password","passwd","credential"];const f="[redacted by Buoy]";const l=[{re:/\bBearer\s+[A-Za-z0-9._~+/-]{12,}=*/gi,label:"[bearer token removed]"},{re:/\beyJ[A-Za-z0-9._-]{20,}/g,label:"[jwt removed]"},{re:/\bsk-[A-Za-z0-9_-]{16,}/g,label:"[api key removed]"},{re:/\bBUOY-[A-Z0-9-]{8,}/g,label:"[license key removed]"},{re:/\b[A-F0-9]{6}(?:-[A-F0-9]{6}){4}-V\d\b/g,label:"[license key removed]"},{re:/("|')?[A-Za-z0-9_-]*(authorization|api[_-]?key|password|passwd|secret|access[_-]?token|refresh[_-]?token|auth[_-]?token|session[_-]?token|license[_-]?key|licence[_-]?key|buoy[_-]?key|private[_-]?key)\1?\s*[:=]\s*("|')?(?!(?:authorization|bearer|cookie|header)\b)[^\s"',}]{6,}/gi,label:"[credential removed]"}];function k(e){let t=e;for(const{re:o,label:r}of l){t=t.replace(o,r)}return t}export function isSecretKey(e,t="tool"){const o=e.toLowerCase().replace(/[-_.\s]/g,"");return a.some(r=>o.includes(r))||t==="route"&&/token|code|key|auth|session|signature|otp|email|phone/.test(o)}export function redact(e,t=0){if(typeof e==="string")return k(e);if(t>12||e===null||typeof e!=="object")return e;if(Array.isArray(e)){return e.map(r=>redact(r,t+1))}const o={};for(const[r,n]of Object.entries(e)){o[r]=isSecretKey(r)?f:redact(n,t+1)}return o}const i=new Set;const c="__BUOY_INTERNAL_HOSTS__";export function registerSelfEndpoint(e){try{const t=/^[a-z]+:\/\/([^/?#]+)/i.exec(e);if(!t?.[1])return;const o=t[1].toLowerCase();i.add(o);const r=globalThis;const n=r[c];const s=n instanceof Set?n:new Set;s.add(o);r[c]=s}catch{}}export function isSelfTraffic(e){if(typeof e!=="string")return false;const t=e.toLowerCase();for(const o of i){if(t.includes(o))return true}return false}function u(e){if(!e||typeof e!=="object")return false;const t=e;return isSelfTraffic(t.url??t.uri??t.href)}export function stripSelfTraffic(e,t=0){if(t>6||e===null||typeof e!=="object")return e;if(Array.isArray(e)){return e.filter(r=>!u(r)).map(r=>stripSelfTraffic(r,t+1))}const o={};for(const[r,n]of Object.entries(e)){o[r]=stripSelfTraffic(n,t+1)}return o}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const c=/(?:^|[.!?;,]\s*|\b(?:please|and|then|now|instead|actually)\s+|\b(?:can|could|would|will)\s+you\s+|\bi\s+(?:want|need)\s+you\s+to\s+)(?:please\s+)?(?:add|make|set|turn|fix|place|order|undo|clear|switch|save|delete|remove|reset|wipe|change|update|put|give|enable|disable|start|stop|pause|resume|refund|redeem|pay|submit|confirm|charge|run|try|test|act|pick|send|log\s+in|pretend|cut|sort|toggle|select|choose|replace|fill|type|enter|simulate|throttle|force|pin|hide|move|block|unblock|inject|reload|restart|restore|retry|apply|accept|create|edit)\b/i;const l=/(?:^|[.!?;,]\s*|\b(?:please|and|then|now|just)\s+)(?:why|what|can|could|is|are|does|do|did|how|which|where|when|check|find out|tell me|explain|read|show me|look|write test steps)\b/i;export function classifyTurn(s){const e=s.replace(/\b(?:do not|don't|never)\b[^.!?;]*/gi,"");if(/\b(?:do the same|show (?:me )?what .+ looks like when|show .*(?:made-up|fake))\b/i.test(e)||c.test(e))return"task";return l.test(e)?"question":"task"}export const QUESTION_DECLINED="The user asked a question; this change was not made. Answer from what you can read.";const d=/\b(?:place|pay|submit|save|confirm|delete|redeem|refund|order)\b/i;function h(s,e){const n=[e.role,e.name].filter(Boolean).map(i=>i.toLowerCase());const o=e.via==="onValueChange"||n.some(i=>/^(switch|toggle|slider|adjustable|checkbox)$/.test(i));const t=e.via==="onChangeText"||n.some(i=>/^(textinput|textbox|input|textarea|searchbox)$/.test(i));const r=e.via==="onPress"||n.some(i=>/^(button|pressable|touchableopacity|touchablehighlight|touchablewithoutfeedback|text|statictext)$/.test(i));const a=!o&&!t&&!r;const u=typeof s.text==="string"?!!s.text.trim():s.text!==void 0;return u&&(t||a)||s.value!==void 0&&(o||t||a)}export function isQuestionLookup(s,e,n,o){if(s==="route-events"){return["navigate","stackGoBack","stackNavigateToIndex","stackPopToIndex","stackPopToTop"].includes(e)}if(s==="query")return e==="refetch"||e==="invalidate";if(s!=="highlight-updates")return false;if(["describeScreen","waitFor","scroll"].includes(e))return true;if(e!=="tapElement"||n.longPress)return false;return!!o?.length&&o.every(t=>{const r=[t.label,t.text].filter(Boolean).join(" ");return r.trim()&&!d.test(r)&&!h(n,t)})}export function tapLabels(s,e){const n=s?.elements;if(!Array.isArray(n))return[];const o=typeof e.query==="string"?e.query.toLowerCase():"";return n.filter(t=>{if(e.nativeTag!==void 0)return t.nativeTag===e.nativeTag;if(e.testID)return t.testID===e.testID;return o&&[t.label,t.text,t.testID,t.name].some(r=>r?.toLowerCase().includes(o))}).map(({label:t,text:r,name:a,role:u})=>({label:t,text:r,name:a,role:u}))}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";import{truncatedMessage as w,unparseableMessage as v}from"./sse";import{createStreamTimer as j}from"./streamTimer";import{createTransport as S}from"./transport";import{classifyProblem as M}from"./problem";const V="2023-06-01";function E(a){const i=a[a.length-1];const
|
|
1
|
+
"use strict";import{truncatedMessage as w,unparseableMessage as v}from"./sse";import{createStreamTimer as j}from"./streamTimer";import{createTransport as S}from"./transport";import{classifyProblem as M}from"./problem";const V="2023-06-01";function E(a){const i=a[a.length-1];const n=i?.content[i.content.length-1];if(n){n.cache_control={type:"ephemeral"}}return a}function k(a){const i=[];for(const n of a){if(n.role==="user"){i.push({role:"user",content:[{type:"text",text:n.text}]})}else if(n.role==="assistant"){const o=[];for(const r of n.thinking??[])o.push(r);if(n.text)o.push({type:"text",text:n.text});for(const r of n.toolCalls??[]){o.push({type:"tool_use",id:r.id,name:r.name,input:r.input})}if(o.length)i.push({role:"assistant",content:o})}else{i.push({role:"user",content:n.results.map(o=>({type:"tool_result",tool_use_id:o.toolCallId,content:o.content,...o.isError?{is_error:true}:{}}))})}}return i}export function createAnthropicProvider(a){const i=S(a);return{protocol:"anthropic",async*send(n){const o=j(n.signal,a);const r={truncated:false};try{const l={"content-type":"application/json","anthropic-version":a.anthropicVersion??V,...await(a.headers?.(n.meta)??{})};if(a.apiKey&&!l["x-api-key"]&&!l.Authorization){l["x-api-key"]=a.apiKey;l["anthropic-dangerous-direct-browser-access"]="true"}const p=await i.open({headers:l,signal:o.signal,body:JSON.stringify({model:n.model,max_tokens:n.maxTokens,stream:true,system:a.cache===false?n.systemVolatile?`${n.system}
|
|
2
2
|
|
|
3
3
|
---
|
|
4
4
|
|
|
5
|
-
${
|
|
5
|
+
${n.systemVolatile}`:n.system:[{type:"text",text:n.system,cache_control:{type:"ephemeral"}},...n.systemVolatile?[{type:"text",text:n.systemVolatile}]:[]],tools:n.tools.map(c=>({name:c.name,description:c.description,input_schema:c.inputSchema,...c.inputExamples?.length?{input_examples:c.inputExamples}:{}})),messages:a.cache===false?k(n.messages):E(k(n.messages)),...n.toolChoice!==void 0?{tool_choice:{type:n.toolChoice}}:{},...a.requestOverrides})});o.connected();if(p.problem){yield{type:"error",message:p.problem,kind:"provider",problem:p.problemInfo};return}const m=new Map;const d=new Map;let y;let u;let g;let h=false;for await(const c of p.frames({status:r,onFrame:o.activity,signal:o.signal})){let s;try{s=JSON.parse(c.data)}catch{continue}const x=s.type??c.event;switch(x){case"content_block_start":{const e=s.content_block;if(e?.type==="thinking"){d.set(s.index,{thinking:e.thinking??"",signature:e.signature??""})}else if(e?.type==="redacted_thinking"){yield{type:"thinking",block:{type:"redacted_thinking",data:e.data}}}else if(e?.type==="tool_use"){m.set(s.index,{id:e.id,name:e.name,json:""})}break}case"content_block_delta":{const e=s.delta;if(e?.type==="text_delta"){yield{type:"text",delta:e.text}}else if(e?.type==="input_json_delta"){const t=m.get(s.index);if(t)t.json+=e.partial_json??""}else if(e?.type==="thinking_delta"){const t=d.get(s.index);if(t)t.thinking+=e.thinking??""}else if(e?.type==="signature_delta"){const t=d.get(s.index);if(t)t.signature+=e.signature??""}break}case"content_block_stop":{const e=d.get(s.index);if(e){d.delete(s.index);yield{type:"thinking",block:{type:"thinking",...e}}}const t=m.get(s.index);if(t){m.delete(s.index);let f={};try{f=t.json?JSON.parse(t.json):{}}catch{yield{type:"error",kind:"provider",message:v(t.name,t.json)};break}const b={id:t.id,name:t.name,input:f};yield{type:"tool-call",call:b}}break}case"message_start":{const e=s.message;if(typeof e?.model==="string"&&e.model)g=e.model;const t=e?.usage;if(t){u={input:t.input_tokens??0,output:t.output_tokens??0,...t.cache_read_input_tokens!==void 0?{cacheRead:t.cache_read_input_tokens}:{},...t.cache_creation_input_tokens!==void 0?{cacheWrite:t.cache_creation_input_tokens}:{}}}break}case"message_delta":{const e=s.delta;if(e?.stop_reason)y=e.stop_reason;const t=s.usage;if(t){u={...u,input:t.input_tokens??u?.input??0,output:t.output_tokens??0}}break}case"error":{const e=s.error;const t=e?.message??"Provider error";yield{type:"error",message:t,kind:"provider",problem:M({type:typeof e?.type==="string"?e.type:void 0,message:t})};return}case"message_stop":h=true;break;default:break}if(h)break}const _=h||y!==void 0;if(!_){yield{type:"error",message:w(r.truncated),kind:"truncated"};return}yield{type:"done",outcome:y==="max_tokens"?"output-limited":"completed",stopReason:y,usage:u,model:g}}catch(l){if(n.signal?.aborted)throw l;const p=o.message();if(p){yield{type:"error",message:p,kind:"timeout"};return}throw l}finally{o.dispose()}}}}
|