@buoy-gg/agent-core 7.0.62 → 7.0.64
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 +85 -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/historyBudget.js +1 -1
- package/lib/commonjs/engine/idGrounding.js +2 -0
- package/lib/commonjs/engine/planOnlyStop.js +1 -1
- package/lib/commonjs/engine/runAgentTurn.js +9 -8
- package/lib/commonjs/engine/stepBudget.test.js +1 -0
- package/lib/commonjs/engine/systemPrompt.js +5 -2
- package/lib/commonjs/engine/verify.js +2 -2
- package/lib/commonjs/feeds/claude.js +23 -0
- package/lib/commonjs/feeds/gpt.js +5 -0
- package/lib/commonjs/feeds/index.js +1 -0
- 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 -5
- package/lib/commonjs/providers/openai.js +1 -5
- package/lib/commonjs/providers/types.js +1 -1
- package/lib/commonjs/session.js +1 -1
- package/lib/module/blocks/receipts.js +1 -1
- package/lib/module/catalog/catalog.g.js +2 -2
- package/lib/module/catalog/catalog.source.json +85 -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/historyBudget.js +1 -1
- package/lib/module/engine/idGrounding.js +2 -0
- package/lib/module/engine/planOnlyStop.js +1 -1
- package/lib/module/engine/runAgentTurn.js +9 -8
- package/lib/module/engine/stepBudget.test.js +1 -0
- package/lib/module/engine/systemPrompt.js +5 -2
- package/lib/module/engine/verify.js +2 -2
- package/lib/module/feeds/claude.js +23 -0
- package/lib/module/feeds/gpt.js +5 -0
- package/lib/module/feeds/index.js +1 -0
- 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 +1 -5
- package/lib/module/providers/openai.js +1 -5
- package/lib/module/providers/types.js +1 -1
- package/lib/module/session.js +1 -1
- package/lib/typescript/catalog/catalog.g.d.ts +3 -3
- package/lib/typescript/catalog/catalog.types.g.d.ts +4 -3
- package/lib/typescript/engine/emptyTap.test.d.ts +2 -0
- package/lib/typescript/engine/historyBudget.d.ts +1 -1
- package/lib/typescript/engine/idGrounding.d.ts +8 -0
- package/lib/typescript/engine/planOnlyStop.d.ts +2 -2
- package/lib/typescript/engine/runAgentTurn.d.ts +2 -0
- package/lib/typescript/engine/stepBudget.test.d.ts +2 -0
- package/lib/typescript/engine/systemPrompt.d.ts +1 -1
- package/lib/typescript/engine/verify.d.ts +2 -1
- package/lib/typescript/feeds/claude.d.ts +67 -0
- package/lib/typescript/feeds/gpt.d.ts +41 -0
- package/lib/typescript/feeds/index.d.ts +27 -0
- package/lib/typescript/index.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/anthropic.d.ts +4 -0
- package/lib/typescript/providers/openai.d.ts +29 -0
- package/lib/typescript/providers/types.d.ts +32 -1
- package/lib/web/index.mjs +77 -38
- 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.",
|
|
@@ -6748,5 +6760,77 @@
|
|
|
6748
6760
|
}
|
|
6749
6761
|
],
|
|
6750
6762
|
"unavailableWhen": "The native Swift image-overlay adapter is not registered. React Native does not expose these actions."
|
|
6763
|
+
},
|
|
6764
|
+
{
|
|
6765
|
+
"toolId": "three",
|
|
6766
|
+
"title": "Scene",
|
|
6767
|
+
"summary": "Read and edit the 3D scene. Counts are not bytes.",
|
|
6768
|
+
"unavailableWhen": "Needs @buoy-gg/three and a scene in the app.",
|
|
6769
|
+
"actions": [
|
|
6770
|
+
{
|
|
6771
|
+
"action": "getScene",
|
|
6772
|
+
"summary": "Read up to 500 nodes per scene.",
|
|
6773
|
+
"description": "Read up to 500 nodes per scene.",
|
|
6774
|
+
"effect": "read",
|
|
6775
|
+
"release": "works",
|
|
6776
|
+
"params": {
|
|
6777
|
+
"type": "object",
|
|
6778
|
+
"properties": {},
|
|
6779
|
+
"additionalProperties": false
|
|
6780
|
+
}
|
|
6781
|
+
},
|
|
6782
|
+
{
|
|
6783
|
+
"action": "getStats",
|
|
6784
|
+
"summary": "Read the last render counts.",
|
|
6785
|
+
"description": "Read the last render counts.",
|
|
6786
|
+
"effect": "read",
|
|
6787
|
+
"release": "works",
|
|
6788
|
+
"params": {
|
|
6789
|
+
"type": "object",
|
|
6790
|
+
"properties": {},
|
|
6791
|
+
"additionalProperties": false
|
|
6792
|
+
}
|
|
6793
|
+
},
|
|
6794
|
+
{
|
|
6795
|
+
"action": "action",
|
|
6796
|
+
"summary": "Set rendererId and id from getScene. Choose an action. Pass value for edits.",
|
|
6797
|
+
"description": "Use node and scene IDs from getScene. Turn values use radians. Colors use six digit hex.",
|
|
6798
|
+
"effect": "write",
|
|
6799
|
+
"release": "works",
|
|
6800
|
+
"params": {
|
|
6801
|
+
"type": "object",
|
|
6802
|
+
"properties": {
|
|
6803
|
+
"rendererId": {
|
|
6804
|
+
"type": "string",
|
|
6805
|
+
"description": "Scene group ID."
|
|
6806
|
+
},
|
|
6807
|
+
"id": {
|
|
6808
|
+
"type": "string",
|
|
6809
|
+
"description": "Node ID. Omit for clearSelection."
|
|
6810
|
+
},
|
|
6811
|
+
"action": {
|
|
6812
|
+
"type": "string",
|
|
6813
|
+
"enum": [
|
|
6814
|
+
"select",
|
|
6815
|
+
"clearSelection",
|
|
6816
|
+
"visible",
|
|
6817
|
+
"position",
|
|
6818
|
+
"rotation",
|
|
6819
|
+
"scale",
|
|
6820
|
+
"color"
|
|
6821
|
+
]
|
|
6822
|
+
},
|
|
6823
|
+
"value": {
|
|
6824
|
+
"description": "Boolean for visible. Three numbers for a transform. Hex string for color."
|
|
6825
|
+
}
|
|
6826
|
+
},
|
|
6827
|
+
"required": [
|
|
6828
|
+
"rendererId",
|
|
6829
|
+
"action"
|
|
6830
|
+
],
|
|
6831
|
+
"additionalProperties": false
|
|
6832
|
+
}
|
|
6833
|
+
}
|
|
6834
|
+
]
|
|
6751
6835
|
}
|
|
6752
6836
|
]
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CATALOG_ACTIONS=void 0;const CATALOG_ACTIONS=exports.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";Object.defineProperty(exports,"__esModule",{value:true});exports.CATALOG_ACTIONS=void 0;const CATALOG_ACTIONS=exports.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"],"three":["getScene","getStats","action"]};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SNAPSHOT_ACTION=void 0;exports.projectSnapshot=projectSnapshot;var _redact=require("../policy/redact");const SNAPSHOT_ACTION=exports.SNAPSHOT_ACTION="getSnapshot";const SEVERITY={verbose:0,debug:0,trace:0,log:1,info:1,warn:2,warning:2,error:3};function asArray(
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SNAPSHOT_ACTION=void 0;exports.projectSnapshot=projectSnapshot;var _redact=require("../policy/redact");const SNAPSHOT_ACTION=exports.SNAPSHOT_ACTION="getSnapshot";const SEVERITY={verbose:0,debug:0,trace:0,log:1,info:1,warn:2,warning:2,error:3};function asArray(a){return Array.isArray(a)?a:[]}function rec(a){return a&&typeof a==="object"?a:{}}function num(a,t){return typeof a==="number"&&a>0?a:t}function newest(a,t){const s=o=>{const r=rec(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 withinBudget(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 projectConsole(a,t){const s=asArray(rec(a).entries);const o=typeof t.level==="string"?SEVERITY[t.level]??0:0;const r=typeof t.pattern==="string"?t.pattern.toLowerCase():void 0;const u=s.filter(l=>{const e=rec(l);const i=String(e.level??"log");if((SEVERITY[i]??1)<o)return false;if(!r)return true;return String(e.message??"").toLowerCase().includes(r)});const n=newest(u,num(t.limit,40));return{totalCaptured:s.length,shown:n.length,entries:n.map(l=>{const e=rec(l);return{at:e.timestamp,level:e.level,message:e.message}})}}function projectNetwork(a,t){const s=rec(a);const o=asArray(s.events).filter(e=>!(0,_redact.isSelfTraffic)(rec(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=rec(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=newest(n,num(t.limit,25));return{totalCaptured:o.length,shown:l.length,requests:l.map(e=>{const i=rec(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 routeParams(a){const t=Object.entries(rec(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&&!(0,_redact.isSecretKey)(s,"route");return[s.slice(0,48),u?(0,_redact.redact)(o):"(value omitted)"]});return t.length?Object.fromEntries(t):void 0}function flattenRoutes(a,t,s=80){const o=new Map;for(const i of t.slice(0,160)){if(typeof i.pathname!=="string")continue;const c=routeParams(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 f=o.get(i)??{};const p=[...new Set([...Object.keys(f),...asArray(c).filter(m=>typeof m==="string")])].slice(0,6).map(m=>{const g=f[m];return g===void 0||g==="(value omitted)"?m.slice(0,48):`${m}=${String(g)}`});const h=p.every(m=>Object.keys(f).some(g=>m===g||m.startsWith(`${g}=`)))?"params seen":"params";const d=p.length?` (${h}: ${p.join(", ")})`:"";const y=d.length<=n;if(y)n-=d.length;r.push(i+(y?d:""))};const e=(i,c=0)=>{if(c>12)return;for(const f of asArray(i)){if(r.length>=s)break;const p=rec(f);if(p.isInternal!==true&&typeof p.path==="string")l(p.path,p.params);e(p.children,c+1)}};e(a);for(const i of o.keys())l(i);return r}function projectStorage(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=asArray(a).map(rec).map(n=>{const l=rec(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=num(t.limit,20);return{events:r.slice(0,u),total:r.length,returned:Math.min(u,r.length)}}function projectRedux(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=asArray(a).map(rec).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=num(t.limit,20);return{actions:r.slice(0,u),total:r.length,returned:Math.min(u,r.length)}}function projectStoreChanges(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=asArray(rec(a).changes).map(rec).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=num(t.limit,20);return{changes:n.slice(0,l),total:n.length,returned:Math.min(l,n.length)}}function projectRoutes(a,t){const s=rec(a);const o=rec(s.sitemap);const r=asArray(s.stack).map(rec);const u=asArray(s.events).map(rec);const n=r.map(c=>({name:c.name,path:c.pathname,...routeParams(c.params)?{params:routeParams(c.params)}:{},focused:c.isFocused===true?true:void 0}));const l=u.slice(0,num(t.limit,15)).map(c=>({at:c.timestamp,from:c.previousPathname,to:c.pathname,...routeParams(c.params)?{params:routeParams(c.params)}:{}}));const e=r.find(c=>c.isFocused===true)??r[r.length-1];const i=u.length?{path:u[0].pathname,source:"event",...routeParams(u[0].params)?{params:routeParams(u[0].params)}:{}}:typeof e?.pathname==="string"?{path:e.pathname,source:"stack",...routeParams(e.params)?{params:routeParams(e.params)}:{}}:void 0;return{currentRoute:i,stack:n,routes:flattenRoutes(o.routes,[...u.slice(0,80),...r.slice(0,80)]),sitemapSource:o.source,recentNavigations:l}}function projectEnv(a){const t=rec(a);return{env:t.env??t.variables,requiredEnvVars:t.requiredEnvVars,...Array.isArray(t.checks)?{checks:t.checks}:{}}}function projectSentry(a,t){const s=rec(a);const o=asArray(s.envelopes).map(rec);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=asArray(e.items).map(rec);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=withinBudget(newest(n,num(t.limit,10)).map(e=>({id:e.id,at:e.timestamp,origin:e.origin,eventId:e.eventId,totalBytes:e.totalBytes,items:asArray(e.items).slice(0,8).map(i=>{const c=rec(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=rec(s.drops);const i=asArray(e.recent).map(rec);const c=d=>d.category==="span"||d.category==="transaction";const f=[...newest(i.filter(d=>!c(d)),8),...newest(i.filter(c),3)];const p=withinBudget(f.map(d=>({at:d.timestamp,reason:d.reason,category:d.category,quantity:d.quantity,detail:typeof d.detail==="string"?d.detail.slice(0,200):d.detail})),4e3);const h=withinBudget(asArray(e.summary),2e3);return p.length||e.summary?{summary:h,recent:p}: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 projectImpersonate(a){const t=rec(a);const s=o=>{if(o===null||o===void 0)return null;const r=rec(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:asArray(t.history).slice(0,10).map(o=>{const r=rec(o);return{user:s(r.user),lastUsedAt:r.lastUsedAt}})}}function projectSnapshot(a,t,s={}){switch(a){case"console":return projectConsole(t,s);case"network":return projectNetwork(t,s);case"route-events":return projectRoutes(t,s);case"storage":return projectStorage(t,s);case"redux":return projectRedux(t,s);case"zustand":return projectStoreChanges(t,s,"storeName","store");case"jotai":return projectStoreChanges(t,s,"atomLabel","atom");case"env":return projectEnv(t);case"impersonate":return projectImpersonate(t);case"sentry":return projectSentry(t,s);default:return t}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.buildContextDigest=buildContextDigest;exports.buildLiveContext=buildLiveContext;var _snapshotReads=require("../catalog/snapshotReads");var _realNow=require("../realNow");const PROBE_TIMEOUT_MS=2500;const list=t=>Array.isArray(t)?t:Array.isArray(t?.items)?t.items:[];const rec=t=>t&&typeof t==="object"?t:{};const names=(t,e,n=40)=>list(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 DIGEST_STORE_CAP=30;const DIGEST_STORE_KEYS=24;const DIGEST_LISTS_PER_STORE=8;const DIGEST_ITEM_CHARS=240;const DIGEST_SHAPES_TOTAL_CHARS=12e3;const clampText=(t,e)=>t.length<=e?t:`${t.slice(0,e-1)}\u2026`;function topLevelFields(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 STABLE_PROBES=[{key:"routes",toolId:"route-events",action:_snapshotReads.SNAPSHOT_ACTION,shape:t=>list(t?.routes).slice(0,60)},{key:"reduxSlices",toolId:"redux",action:"getState",params:{includeValues:false},shape:t=>{const e=rec(t);if(e.available===false)return void 0;const n=rec(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 list(t?.stores??t).slice(0,DIGEST_STORE_CAP).map(n=>{const s=n??{};const i=typeof s.name==="string"?s.name:s.id;const o=list(s.shape?.lists).map(rec);const u={};const l=[];for(const r of o.slice(0,DIGEST_LISTS_PER_STORE)){const a=typeof r.path==="string"?r.path:void 0;if(!a)continue;if(a.includes("[]."))continue;if(typeof r.item!=="string"){l.push(a);continue}const c=clampText(r.item,DIGEST_ITEM_CHARS);if(e+c.length>DIGEST_SHAPES_TOTAL_CHARS)continue;e+=c.length;u[a]=c}return{name:i,...typeof s.persistName==="string"?{persistsTo:s.persistName}:{},...(()=>{if(!Array.isArray(s.keys)||!s.keys.length)return{};const r=topLevelFields(s.shape?.shape);const a=s.keys.filter(c=>r.get(String(c))!=="function");return a.length?{keys:a.slice(0,DIGEST_STORE_KEYS)}:{}})(),...Object.keys(u).length?{listItemShapes:u}:{},...l.length?{unknownLists:l}:{}}})}},{key:"jotaiAtoms",toolId:"jotai",action:"listAtoms",shape:t=>names(rec(t).atoms??t,["debugLabel","label","id"],40)},{key:"storageKeys",toolId:"storage",action:"async.getAllKeys",shape:t=>list(t).slice(0,60)},{key:"env",toolId:"env",action:_snapshotReads.SNAPSHOT_ACTION,shape:t=>{const e=t?.env;return e&&typeof e==="object"?Object.keys(e).slice(0,40):void 0}}];const LIVE_QUERY_CAP=25;const LIVE_QUERY_SCAN=LIVE_QUERY_CAP*2;const LIVE_REQUEST_CAP=8;const LIVE_PROBES=[{key:"currentRoute",toolId:"route-events",action:"getCurrentRoute",shape:t=>{const e=rec(t);if(typeof e.path!=="string")return void 0;return e.params&&Object.keys(rec(e.params)).length?{path:e.path,params:e.params}:{path:e.path}}},{key:"queries",toolId:"query",action:"listQueries",params:{limit:LIVE_QUERY_SCAN},shape:t=>{const e=list(t?.queries??t).map(rec);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,LIVE_QUERY_CAP)}},{key:"networkCapture",toolId:"network",action:"getCaptureStatus",shape:t=>{const e=rec(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:_snapshotReads.SNAPSHOT_ACTION,params:{limit:LIVE_REQUEST_CAP},shape:t=>list(t?.requests).map(e=>{const n=rec(e);return{id:n.id,method:n.method,url:n.url,status:n.status,...n.overridden?{overridden:true}:{}}})},{key:"appClock",toolId:"clock",action:"getState",shape:t=>{const e=rec(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:_snapshotReads.SNAPSHOT_ACTION,shape:t=>{const e=rec(t);if(e.isActive!==true)return void 0;const n=rec(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=rec(t);if(e.active!==true)return void 0;const n=rec(e.override);const s=rec(e.current);const i=rec(s.fix);const o=rec(n.place);const u=rec(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:u.name??u.id,playing:n.playing===true}:{},...n.signal===false?{signal:false}:{},...n.services===false?{services:false}:{}}}},{key:"appPermissions",toolId:"permissions",action:_snapshotReads.SNAPSHOT_ACTION,shape:t=>{const e=list(rec(t).permissions).map(rec).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=rec(t);const n=list(e.rules).map(rec).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 withTimeout(t,e){return await Promise.race([t.catch(()=>void 0),new Promise(n=>(0,_realNow.realSetTimeout)(()=>n(void 0),e))])}async function runProbes(t,{dispatch:e,readSnapshot:n,availableToolIds:s,availableActions:i}){const o=t.filter(r=>{if(!s.includes(r.toolId))return false;const a=i?.[r.toolId];return!a||a.includes(r.action)});const u=await Promise.all(o.map(async r=>{const a=r.action===_snapshotReads.SNAPSHOT_ACTION?n?Promise.resolve(n(r.toolId)).then(y=>(0,_snapshotReads.projectSnapshot)(r.toolId,y,r.params??{})):Promise.resolve(void 0):Promise.resolve(e(r.toolId,r.action,r.params));const c=await withTimeout(a,PROBE_TIMEOUT_MS);if(c===void 0)return[r.key,void 0];try{return[r.key,r.shape(c)]}catch{return[r.key,void 0]}}));const l={};for(const[r,a]of u){const c=a===void 0||a===null||Array.isArray(a)&&a.length===0;if(!c)l[r]=a}return l}function buildContextDigest(t){return runProbes(STABLE_PROBES,t)}function keyTokens(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?[]:splitTokens(String(typeof n==="object"?JSON.stringify(n):n)))}function splitTokens(t){return t.toLowerCase().split(/[^a-z0-9]+/i).filter(Boolean)}function annotateLikelyScreen(t){const e=t.currentRoute;const n=t.queries;if(!e?.path||!Array.isArray(n))return;const s=Object.values(e.params??{}).map(r=>splitTokens(String(r))).filter(r=>r.length>0);const i=splitTokens(e.path);let o=-1;let u=-1;let l=false;n.forEach((r,a)=>{if(!r.onScreen)return;const c=new Set(keyTokens(r.key));const y=s.filter(d=>d.every(p=>c.has(p))).length;const m=i.filter(d=>c.has(d)||[...c].some(p=>p.includes(d)||d.includes(p))).length;const f=y*3+m;if(f<=0)return;if(f>o){o=f;u=a;l=false}else if(f===o){l=true}});if(u>=0&&!l){n[u].likelyScreen=true;const[r]=n.splice(u,1);n.unshift(r)}}async function buildLiveContext(t){const e=await runProbes(LIVE_PROBES,t);annotateLikelyScreen(e);let n;try{n=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{n=void 0}e.now={iso:new Date((0,_realNow.realNow)()).toISOString(),...n?{timeZone:n}:{}};return e}
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.buildContextDigest=buildContextDigest;exports.buildLiveContext=buildLiveContext;var _snapshotReads=require("../catalog/snapshotReads");var _realNow=require("../realNow");const PROBE_TIMEOUT_MS=2500;const list=t=>Array.isArray(t)?t:Array.isArray(t?.items)?t.items:[];const rec=t=>t&&typeof t==="object"?t:{};const names=(t,e,n=40)=>list(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 DIGEST_STORE_CAP=30;const DIGEST_STORE_KEYS=24;const DIGEST_LISTS_PER_STORE=8;const DIGEST_ITEM_CHARS=240;const DIGEST_SHAPES_TOTAL_CHARS=12e3;const clampText=(t,e)=>t.length<=e?t:`${t.slice(0,e-1)}\u2026`;function topLevelFields(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 STABLE_PROBES=[{key:"routes",toolId:"route-events",action:_snapshotReads.SNAPSHOT_ACTION,shape:t=>list(t?.routes).slice(0,60)},{key:"reduxSlices",toolId:"redux",action:"getState",params:{includeValues:false},shape:t=>{const e=rec(t);if(e.available===false)return void 0;const n=rec(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 list(t?.stores??t).slice(0,DIGEST_STORE_CAP).map(n=>{const s=n??{};const i=typeof s.name==="string"?s.name:s.id;const o=list(s.shape?.lists).map(rec);const u={};const l=[];for(const r of o.slice(0,DIGEST_LISTS_PER_STORE)){const a=typeof r.path==="string"?r.path:void 0;if(!a)continue;if(a.includes("[]."))continue;if(typeof r.item!=="string"){l.push(a);continue}const c=clampText(r.item,DIGEST_ITEM_CHARS);if(e+c.length>DIGEST_SHAPES_TOTAL_CHARS)continue;e+=c.length;u[a]=c}return{name:i,...typeof s.persistName==="string"?{persistsTo:s.persistName}:{},...(()=>{if(!Array.isArray(s.keys)||!s.keys.length)return{};const r=topLevelFields(s.shape?.shape);const a=s.keys.filter(c=>r.get(String(c))!=="function");return a.length?{keys:a.slice(0,DIGEST_STORE_KEYS)}:{}})(),...Object.keys(u).length?{listItemShapes:u}:{},...l.length?{unknownLists:l}:{}}})}},{key:"jotaiAtoms",toolId:"jotai",action:"listAtoms",shape:t=>names(rec(t).atoms??t,["debugLabel","label","id"],40)},{key:"storageKeys",toolId:"storage",action:"async.getAllKeys",shape:t=>list(t).slice(0,60)},{key:"env",toolId:"env",action:_snapshotReads.SNAPSHOT_ACTION,shape:t=>{const e=t?.env;return e&&typeof e==="object"?Object.keys(e).slice(0,40):void 0}}];const LIVE_QUERY_CAP=25;const LIVE_QUERY_SCAN=LIVE_QUERY_CAP*2;const LIVE_REQUEST_CAP=8;function requestAge(t){const e=typeof t==="number"?t:typeof t==="string"?Date.parse(t):NaN;return Number.isFinite(e)?{age:`${Math.max(0,Math.floor(((0,_realNow.realNow)()-e)/1e3))}s ago`}:{}}const LIVE_PROBES=[{key:"currentRoute",toolId:"route-events",action:"getCurrentRoute",shape:t=>{const e=rec(t);if(typeof e.path!=="string")return void 0;return e.params&&Object.keys(rec(e.params)).length?{path:e.path,params:e.params}:{path:e.path}}},{key:"queries",toolId:"query",action:"listQueries",params:{limit:LIVE_QUERY_SCAN},shape:t=>{const e=list(t?.queries??t).map(rec);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,LIVE_QUERY_CAP)}},{key:"networkCapture",toolId:"network",action:"getCaptureStatus",shape:t=>{const e=rec(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:_snapshotReads.SNAPSHOT_ACTION,params:{limit:LIVE_REQUEST_CAP},shape:t=>list(t?.requests).map(e=>{const n=rec(e);return{id:n.id,...n.at!==void 0?{at:n.at}:{},...requestAge(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=rec(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:_snapshotReads.SNAPSHOT_ACTION,shape:t=>{const e=rec(t);if(e.isActive!==true)return void 0;const n=rec(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=rec(t);if(e.active!==true)return void 0;const n=rec(e.override);const s=rec(e.current);const i=rec(s.fix);const o=rec(n.place);const u=rec(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:u.name??u.id,playing:n.playing===true}:{},...n.signal===false?{signal:false}:{},...n.services===false?{services:false}:{}}}},{key:"appPermissions",toolId:"permissions",action:_snapshotReads.SNAPSHOT_ACTION,shape:t=>{const e=list(rec(t).permissions).map(rec).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=rec(t);const n=list(e.rules).map(rec).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 withTimeout(t,e){return await Promise.race([t.catch(()=>void 0),new Promise(n=>(0,_realNow.realSetTimeout)(()=>n(void 0),e))])}async function runProbes(t,{dispatch:e,readSnapshot:n,availableToolIds:s,availableActions:i}){const o=t.filter(r=>{if(!s.includes(r.toolId))return false;const a=i?.[r.toolId];return!a||a.includes(r.action)});const u=await Promise.all(o.map(async r=>{const a=r.action===_snapshotReads.SNAPSHOT_ACTION?n?Promise.resolve(n(r.toolId)).then(y=>(0,_snapshotReads.projectSnapshot)(r.toolId,y,r.params??{})):Promise.resolve(void 0):Promise.resolve(e(r.toolId,r.action,r.params));const c=await withTimeout(a,PROBE_TIMEOUT_MS);if(c===void 0)return[r.key,void 0];try{return[r.key,r.shape(c)]}catch{return[r.key,void 0]}}));const l={};for(const[r,a]of u){const c=a===void 0||a===null||Array.isArray(a)&&a.length===0;if(!c)l[r]=a}return l}function buildContextDigest(t){return runProbes(STABLE_PROBES,t)}function keyTokens(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?[]:splitTokens(String(typeof n==="object"?JSON.stringify(n):n)))}function splitTokens(t){return t.toLowerCase().split(/[^a-z0-9]+/i).filter(Boolean)}function annotateLikelyScreen(t){const e=t.currentRoute;const n=t.queries;if(!e?.path||!Array.isArray(n))return;const s=Object.values(e.params??{}).map(r=>splitTokens(String(r))).filter(r=>r.length>0);const i=splitTokens(e.path);let o=-1;let u=-1;let l=false;n.forEach((r,a)=>{if(!r.onScreen)return;const c=new Set(keyTokens(r.key));const y=s.filter(d=>d.every(p=>c.has(p))).length;const m=i.filter(d=>c.has(d)||[...c].some(p=>p.includes(d)||d.includes(p))).length;const f=y*3+m;if(f<=0)return;if(f>o){o=f;u=a;l=false}else if(f===o){l=true}});if(u>=0&&!l){n[u].likelyScreen=true;const[r]=n.splice(u,1);n.unshift(r)}}async function buildLiveContext(t){const e=await runProbes(LIVE_PROBES,t);annotateLikelyScreen(e);let n;try{n=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{n=void 0}e.now={iso:new Date((0,_realNow.realNow)()).toISOString(),...n?{timeZone:n}:{}};return e}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var _vitest=require("vitest");var _runAgentTurn=require("./runAgentTurn");var _catalog=require("../catalog/catalog.g");var _ledger=require("../effects/ledger");const catalog=[{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 run(e,t,a=false,o=false){const n=new _ledger.EffectLedger;const s=[];let p=0;const d={protocol:"anthropic",async*send(l){s.push(l.messages);if(p++===0)yield{type:"tool-call",call:{id:"tap",name:"buoy_highlight-updates",input:{action:"tapElement",params:e}}};else yield{type:"text",delta:"The screen check is done."};yield{type:"done",outcome:"completed"}}};const r=_vitest.vi.fn(async(l,u)=>u==="describeScreen"?{elements:[{nativeTag:7,label:"Place test order",name:"Pressable"}]}:t);const i=_vitest.vi.fn(async()=>false);const c=[];for await(const l of(0,_runAgentTurn.runAgentTurn)({provider:d,catalog,system:"s",model:"m",maxTokens:100,messages:[{role:"user",text:a?"Why is checkout wrong?":"Tap the button."}],dispatch:r,ledger:n,policy:{requireApproval:o?["write"]:[]},isRelease:false,requestApproval:i}))c.push(l);return{ledger:n,requests:s,dispatch:r,requestApproval:i,events:c}}(0,_vitest.describe)("empty and missed taps",()=>{_vitest.it.each([{},{nativeTag:" ",testID:"",query:""},{testID:"",query:" \n "},{nativeTag:null,testID:" "}])("skips an empty tap: %j",async e=>{for(const t of[false,true]){const a=await run(e,{tapped:true},t,true);(0,_vitest.expect)(a.dispatch).not.toHaveBeenCalled();(0,_vitest.expect)(a.requestApproval).not.toHaveBeenCalled();(0,_vitest.expect)(a.events).toContainEqual(_vitest.expect.objectContaining({type:"tool-end",ok:false,summary:_vitest.expect.stringContaining("tapElement needs")}));(0,_vitest.expect)(JSON.stringify(a.requests)).toContain('\\"ok\\":false');(0,_vitest.expect)(a.ledger.list()).toEqual([]);(0,_vitest.expect)(a.events.some(o=>o.type==="approval-required"||o.type==="tool-verified"||o.type==="block")).toBe(false)}});_vitest.it.each([{query:"Add"},{testID:"add"},{nativeTag:7}])("runs a valid tap: %j",async e=>{const t=await run(e,{tapped:true});(0,_vitest.expect)(t.dispatch).toHaveBeenCalledWith("highlight-updates","tapElement",e);(0,_vitest.expect)(t.events).toContainEqual(_vitest.expect.objectContaining({type:"tool-end",ok:true}));(0,_vitest.expect)(t.ledger.list()).toHaveLength(1)});_vitest.it.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 e=>{const t=await run({query:"Add"},e);(0,_vitest.expect)(t.dispatch).toHaveBeenCalledOnce();(0,_vitest.expect)(t.events).toContainEqual(_vitest.expect.objectContaining({type:"tool-end",ok:false,summary:e.reason}));(0,_vitest.expect)(JSON.stringify(t.requests)).toContain('\\"ok\\":false');(0,_vitest.expect)(t.ledger.list()).toEqual([]);(0,_vitest.expect)(t.events.some(a=>a.type==="tool-verified"||a.type==="block")).toBe(false)});(0,_vitest.it)("keeps the question gate for valid taps",async()=>{const e=await run({query:"Place test order"},{tapped:true},true);(0,_vitest.expect)(e.requestApproval).toHaveBeenCalledOnce();(0,_vitest.expect)(e.dispatch).not.toHaveBeenCalledWith("highlight-updates","tapElement",_vitest.expect.anything());(0,_vitest.expect)(e.ledger.list()).toEqual([])});_vitest.it.each([{},{query:" "},{query:"Add"}])("guards a block button too: %j",async e=>{const t=new _ledger.EffectLedger;const a=_vitest.vi.fn(async()=>({tapped:false,reason:"No match for Add."}));const o=await(0,_runAgentTurn.runGatedAction)({toolId:"highlight-updates",action:"tapElement",params:e,catalog,dispatch:a,ledger:t,policy:{requireApproval:[]},isRelease:false});(0,_vitest.expect)(o).toEqual({ok:false,error:e.query==="Add"?"No match for Add.":"tapElement needs nativeTag, testID or query. Read describeScreen and pass one."});(0,_vitest.expect)(a).toHaveBeenCalledTimes(e.query==="Add"?1:0);(0,_vitest.expect)(t.list()).toEqual([])});_vitest.it.each([{},{query:"Add"}])("does not count a failed tap as plan work: %j",async e=>{let t=0;const a=new _ledger.EffectLedger;const o={protocol:"anthropic",async*send(){const n=t++;if(n===0)yield{type:"tool-call",call:{id:"plan",name:"buoy_ask-buoy",input:{action:"openProcedure",params:{id:"add"}}}};else if(n===1)yield{type:"tool-call",call:{id:"tap",name:"buoy_highlight-updates",input:{action:"tapElement",params:e}}};else yield{type:"text",delta:"The plan is set."};yield{type:"done",outcome:"completed"}}};for await(const n of(0,_runAgentTurn.runAgentTurn)({provider:o,catalog:[...catalog,_catalog.CATALOG.find(s=>s.toolId==="ask-buoy")],system:"s",model:"m",maxTokens:100,messages:[{role:"user",text:"Add the item."}],dispatch:async()=>({tapped:false,reason:"No match."}),ledger:a,policy:{requireApproval:[]},isRelease:false,procedures:[{id:"add",title:"Add an item",summary:"Add one item",body:"Tap Add."}]})){}(0,_vitest.expect)(t).toBe(4);(0,_vitest.expect)(a.list()).toEqual([])});_vitest.it.each([{},{query:"Add"}])("leaves failed taps out of the step-cap list: %j",async e=>{let t=0;const a={protocol:"anthropic",async*send(){if(t++===0)yield{type:"tool-call",call:{id:"tap",name:"buoy_highlight-updates",input:{action:"tapElement",params:e}}};yield{type:"done",outcome:"completed"}}};const o=[];for await(const s of(0,_runAgentTurn.runAgentTurn)({provider:a,catalog,system:"s",model:"m",maxTokens:100,messages:[{role:"user",text:"Tap Add."}],dispatch:async()=>({tapped:false,reason:"No match."}),ledger:new _ledger.EffectLedger,policy:{requireApproval:[],maxSteps:1},isRelease:false}))o.push(s);const n=o.filter(s=>s.type==="text").map(s=>s.delta).join("");(0,_vitest.expect)(n).toContain("The job is not done.");(0,_vitest.expect)(n).not.toContain("These steps ran:")})});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MAX_REQUEST_TOKENS=exports.MAX_REQUEST_CHARS=exports.MAX_HISTORY_TOKENS=exports.MAX_HISTORY_CHARS=void 0;exports.budgetForRequest=budgetForRequest;exports.compressConsumed=compressConsumed;exports.messageSize=messageSize;exports.trimHistory=trimHistory;exports.trimHistoryReport=trimHistoryReport;var _evidence=require("./evidence");var _tokenCalibration=require("./tokenCalibration");const MAX_HISTORY_TOKENS=exports.MAX_HISTORY_TOKENS=37500;const MAX_REQUEST_TOKENS=exports.MAX_REQUEST_TOKENS=1e5;const MAX_HISTORY_CHARS=exports.MAX_HISTORY_CHARS=MAX_HISTORY_TOKENS*_tokenCalibration.DEFAULT_CHARS_PER_TOKEN;const MAX_REQUEST_CHARS=exports.MAX_REQUEST_CHARS=MAX_REQUEST_TOKENS*_tokenCalibration.DEFAULT_CHARS_PER_TOKEN;const MIN_KEEP_MESSAGES=4;const MIN_COMPRESS_CHARS=400;function messageSize(e){try{return JSON.stringify(e).length}catch{return 0}}function compressConsumed(e,c=true){let i=e.length;if(c){i=-1;for(let t=e.length-1;t>=0;t--){if(e[t].role==="tool-results"){i=t;break}}if(i<=0)return e}const
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MAX_REQUEST_TOKENS=exports.MAX_REQUEST_CHARS=exports.MAX_HISTORY_TOKENS=exports.MAX_HISTORY_CHARS=void 0;exports.budgetForRequest=budgetForRequest;exports.compressConsumed=compressConsumed;exports.messageSize=messageSize;exports.trimHistory=trimHistory;exports.trimHistoryReport=trimHistoryReport;var _types=require("../providers/types");var _evidence=require("./evidence");var _tokenCalibration=require("./tokenCalibration");const MAX_HISTORY_TOKENS=exports.MAX_HISTORY_TOKENS=37500;const MAX_REQUEST_TOKENS=exports.MAX_REQUEST_TOKENS=1e5;const MAX_HISTORY_CHARS=exports.MAX_HISTORY_CHARS=MAX_HISTORY_TOKENS*_tokenCalibration.DEFAULT_CHARS_PER_TOKEN;const MAX_REQUEST_CHARS=exports.MAX_REQUEST_CHARS=MAX_REQUEST_TOKENS*_tokenCalibration.DEFAULT_CHARS_PER_TOKEN;const MIN_KEEP_MESSAGES=4;const MIN_COMPRESS_CHARS=400;function messageSize(e){try{return JSON.stringify(e).length}catch{return 0}}function compressConsumed(e,c=true){let i=e.length;if(c){i=-1;for(let t=e.length-1;t>=0;t--){if(e[t].role==="tool-results"){i=t;break}}if(i<=0)return e}const d=new Set;for(let t=0;t<e.length;t++){const u=e[t];if(u.role!=="assistant"||!u.toolCalls?.length)continue;if(!u.toolCalls.some(s=>WRITE_ISH.test(JSON.stringify(s.input??{})+s.name)))continue;for(let s=t-1;s>=0&&s>=t-3;s--){if(e[s].role==="tool-results"){d.add(s);break}}}let o=false;const l=e.map((t,u)=>{if(t.role!=="tool-results"||u>=i||d.has(u))return t;let s=false;const n=t.results.map(r=>{if(r.isError||r.content.length<MIN_COMPRESS_CHARS)return r;if(r.content.startsWith("[earlier result"))return r;s=true;return{...r,content:(0,_evidence.compressedMarker)(r.content.length,r.ref)}});if(!s)return t;o=true;return{...t,results:n}});return o?l:e}const WRITE_ISH=/set|write|dispatch|navigate|tap|override|restore|delete|remove|clear|save|run|impersonat|reload/i;function splitRounds(e,c){const i=[];for(const d of e){if((0,_types.isRealUserMessage)(d)||i.length===0)i.push({messages:[],size:0,pinned:false});const o=i[i.length-1];o.messages.push(d);o.size+=messageSize(d);if(c?.size&&d.role==="assistant"&&d.toolCalls?.some(l=>c.has(l.id)))o.pinned=true}return i}function dropRounds(e,c,i,d){const o=[...e];let l=o.reduce((n,r)=>n+r.size,0);let t=0;let u=0;const s=()=>o.reduce((n,r)=>n+r.messages.length,0);while(o.length>0&&l+i>c&&s()>d){let n=o.findIndex(r=>!r.pinned);if(n<0){n=0;u+=1}l-=o[n].size;o.splice(n,1);t+=1}return{kept:o.flatMap(n=>n.messages),droppedRounds:t,droppedPinned:u}}function trimHistoryReport(e,c=_tokenCalibration.DEFAULT_CHARS_PER_TOKEN,i){const d=Math.floor(MAX_HISTORY_TOKENS*c);let o=0;for(const r of e)o+=messageSize(r);if(o<=d)return{messages:e,droppedRounds:0,droppedPinned:0};const l=compressConsumed(e);let t=0;for(const r of l)t+=messageSize(r);if(t<=d)return{messages:l,droppedRounds:0,droppedPinned:0};const{kept:u,droppedRounds:s,droppedPinned:n}=dropRounds(splitRounds(l,i),d,0,MIN_KEEP_MESSAGES);return{messages:u,droppedRounds:s,droppedPinned:n}}function trimHistory(e){return trimHistoryReport(e).messages}function budgetForRequest(e,c,i=MAX_HISTORY_CHARS,d=_tokenCalibration.DEFAULT_CHARS_PER_TOKEN,o){const l=Math.min(i,Math.floor(MAX_REQUEST_TOKENS*d)-c);let t=0;for(const p of e)t+=messageSize(p);if(t<=l)return{messages:e,droppedRounds:0,droppedPinned:0};let u=-1;for(let p=e.length-1;p>=0;p--){if((0,_types.isRealUserMessage)(e[p])){u=p;break}}if(u<=0){return{messages:compressConsumed(e),droppedRounds:0,droppedPinned:0}}const s=e.slice(0,u);const n=e.slice(u);let r=0;for(const p of n)r+=messageSize(p);const a=compressConsumed(s,false);let f=0;for(const p of a)f+=messageSize(p);if(f+r<=l){return{messages:[...a,...n],droppedRounds:0,droppedPinned:0}}const{kept:_,droppedRounds:R,droppedPinned:S}=dropRounds(splitRounds(a,o),l,r,0);f=_.reduce((p,A)=>p+messageSize(A),0);const E=_.length===0&&f+r>l?compressConsumed(n):n;return{messages:[..._,...E],droppedRounds:R,droppedPinned:S}}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.UNSEEN_ID_ADVICE=void 0;exports.idGrounding=idGrounding;const HISTORY_CHARS=64e3;const HOST_CHARS=32e3;const ID_VALUE=/\b(?:picker_\d+|[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12})\b/gi;const idKey=s=>s==="id"||/Id$/.test(s);const UNSEEN_ID_ADVICE=exports.UNSEEN_ID_ADVICE="Use an id from a read, or search for it.";function idGrounding(s,_){let c="";const d=e=>{c=(c+"\n"+e.replace(/\[Buoy\] Unseen id:[^\n]*/g,"")).slice(-HISTORY_CHARS)};for(const e of s){if(e.role==="user")d(e.text);if(e.role==="tool-results")for(const f of e.results)d(f.content)}const u=_.slice(-HOST_CHARS);return{add:d,trailer(e,f=true){const r=new Set;let g=200;const l=(t,o="",a=0)=>{if(--g<0||a>6||r.size>=8)return;if(typeof t==="string"){if(idKey(o)&&t.length>0&&t.length<=160)r.add(t);for(const n of t.slice(0,2048).match(ID_VALUE)??[])r.add(n);for(const n of t.slice(0,2048).matchAll(/[?&]([^=&]+)=([^&#]*)/g)){try{if(idKey(decodeURIComponent(n[1])))l(decodeURIComponent(n[2]),"id",a+1)}catch{}}}else if(t&&typeof t==="object"){for(const[n,p]of Object.entries(t))l(p,n,a+1)}};l(e);const i=u+"\n"+c;const h=t=>{let o=i.indexOf(t);while(o>=0){if(!/[\w-]/.test(i[o-1]??"")&&!/[\w-]/.test(i[o+t.length]??""))return true;o=i.indexOf(t,o+1)}return false};return[...r].slice(0,8).filter(t=>!h(t)).map(t=>`
|
|
2
|
+
[Buoy] Unseen id: ${t.replace(/[\r\n]/g," ")} was not in any read.${f?` ${UNSEEN_ID_ADVICE}`:""}`).join("")}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SILENT_NUDGE=exports.PLAN_ONLY_NUDGE=void 0;exports.announcesUnstartedWork=announcesUnstartedWork;const PLAN_ONLY_NUDGE=exports.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.]";const SILENT_NUDGE=exports.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 WAITS_ON_USER=/\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 POINTS_AT_MISSING_CONTROL=/\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 ASKS_TO_PICK=/\b(?:pick|choose|select|tell me) (?:what|which)\b/i;const ANNOUNCES=/\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 IN_PROGRESS=/\bi['’]m (?:now )?(?!sorry\b)[a-z]+ing\b/i;function announcesUnstartedWork(n){const t=n.trim();if(POINTS_AT_MISSING_CONTROL.test(t))return true;if(ASKS_TO_PICK.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((i,
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SILENT_NUDGE=exports.PLAN_ONLY_NUDGE=void 0;exports.announcesUnstartedWork=announcesUnstartedWork;const PLAN_ONLY_NUDGE=exports.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.]";const SILENT_NUDGE=exports.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 WAITS_ON_USER=/\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 POINTS_AT_MISSING_CONTROL=/\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 ASKS_TO_PICK=/\b(?:pick|choose|select|tell me) (?:what|which)\b/i;const READY_TO_COMMIT=/\bi(?:['’]m| am) ready to (?:submit|place|refund|continue)\b|\bbefore i (?:submit|place|refund)\b[^.!?]*\bi need to confirm\b/i;const ANNOUNCES=/\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 IN_PROGRESS=/\bi['’]m (?:now )?(?!sorry\b)[a-z]+ing\b/i;function announcesUnstartedWork(n,r=false){const t=n.trim();if(POINTS_AT_MISSING_CONTROL.test(t))return true;if(ASKS_TO_PICK.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((i,u,s)=>!(u===s.length-1&&s.length>1&&/^[“"][^“”"]*[”"]\s*$/.test(i.trim())));const o=e.slice(-2).join(" ");if(r&&READY_TO_COMMIT.test(o))return true;const a=e.length>1&&!/\d/.test(e.at(-1)??"");if((IN_PROGRESS.test(e.at(-1)??"")||a&&IN_PROGRESS.test(e.at(-2)??""))&&!WAITS_ON_USER.test(o))return true;return ANNOUNCES.test(o)&&!WAITS_ON_USER.test(o)}
|
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"digestOf",{enumerable:true,get:function(){return _digest.digestOf}});exports.readTargetDigest=readTargetDigest;exports.runAgentTurn=runAgentTurn;exports.runGatedAction=runGatedAction;var _catalog=require("../catalog/catalog.g");var _validateParams=require("../catalog/validateParams");var _normalizeParams=require("../catalog/normalizeParams");var _toProviderTools=require("../catalog/toProviderTools");var _snapshotReads=require("../catalog/snapshotReads");var _types=require("../providers/types");var _ledger=require("../effects/ledger");var _policy=require("../policy/policy");var _redact=require("../policy/redact");var _effectFor=require("./effectFor");var _digest=require("../effects/digest");var _uiTool=require("../blocks/uiTool");var _receipts=require("../blocks/receipts");var _types2=require("../blocks/types");var _askGate=require("./askGate");var _textToolCalls=require("./textToolCalls");var _planOnlyStop=require("./planOnlyStop");var _compactScreen=require("./compactScreen");var _historyBudget=require("./historyBudget");var _tokenCalibration=require("./tokenCalibration");var _evidence=require("./evidence");var _retrieve=require("./retrieve");var _verify=require("./verify");var _realNow=require("../realNow");const MAX_RESULT_CHARS=24e3;const MAX_TRACE_RESULT_CHARS=2e3;const LOOP_REPEATS=3;function callSignature(t){const o=n=>{if(n===null||typeof n!=="object")return n;if(Array.isArray(n))return n.map(o);const c=n;return Object.keys(c).sort().reduce((u,T)=>(u[T]=o(c[T]),u),{})};return t.map(n=>`${n.name}:${JSON.stringify(o(n.input??{}))}`).join("|")}const LOOP_WARNING="[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 DEFAULT_MAX_STEPS=24;const DEFAULT_TURN_MS=18e4;const THROTTLE_RETRIES=2;const OVERFLOW_RETRIES=1;const RETRY_BASE_MS=1e3;const RETRY_JITTER_MS=250;const RETRY_AFTER_CAP_MS=3e4;function sleep(t,o){return new Promise(n=>{if(o?.aborted)return n();const c=(0,_realNow.realSetTimeout)(u,t);function u(){(0,_realNow.realClearTimeout)(c);o?.removeEventListener("abort",u);n()}o?.addEventListener("abort",u,{once:true})})}function readAnswer(t){if(typeof t==="boolean")return{approved:t,trust:false};const o=t.reason?.trim();return{approved:t.approved,...o?{reason:o}:{},trust:t.trust===true&&t.approved}}function declinedResult(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 findDescriptor(t,o,n){return t.find(c=>c.toolId===o)?.actions.find(c=>c.action===n)}const URL_PROVENANCE_REJECTION="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 droppedImageNote=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 fullText(t){try{return JSON.stringify(t??null)}catch{return String(t)}}function encodeResult(t,o){if(t.length<=MAX_RESULT_CHARS)return t;return`${t.slice(0,MAX_RESULT_CHARS)}${(0,_evidence.truncationMarker)(t.length,o)}`}function summarise(t){if(t===null||t===void 0)return"Done";if(Array.isArray(t))return countOf(t.length);if(typeof t==="boolean")return t?"Done":"Failed";if(typeof t==="object"){const o=t;if(o.ok===false)return typeof o.error==="string"?o.error:"Failed";if(o.found===false)return"Not found";if(o.tapped===false)return"Nothing to tap";if(o.active===false)return"Saved, but inactive in this build";for(const c of["returned","count","total"]){const u=o[c];if(typeof u==="number")return countOf(u)}const n=Object.values(o).filter(Array.isArray);if(n.length===1)return countOf(n[0].length);return"Done"}return String(t).slice(0,80)}function countOf(t){return t===1?"1 item":`${t} items`}function reportsFailure(t){return typeof t==="object"&&t!==null&&t.ok===false}async function*runAgentTurn(t){const{provider:o,catalog:n,system:c,systemVolatile:u,model:T,maxTokens:g,dispatch:d,readSnapshot:y,storeKeyOwners:E,ledger:v,policy:P,isRelease:x,requestApproval:U,signal:$,evidence:D,trusted:A,procedures:j}=t;const B=new Map;const C=t.calibration??new _tokenCalibration.TokenCalibration;const h=[...t.messages];const ne=(0,_toProviderTools.toProviderTools)(n,{availableToolIds:t.availableToolIds,availableActions:t.availableActions,isRelease:x});ne.push((0,_uiTool.uiProviderTool)());const V=P.maxSteps??DEFAULT_MAX_STEPS;const Le=newAskId();const Ue=v.generation;const ge=c.length+(u?.length??0)+ne.reduce((O,q)=>O+q.description.length+JSON.stringify(q.inputSchema).length,0);const be=()=>ge+C.chars(g);let X=(0,_realNow.realNow)()+DEFAULT_TURN_MS;const ie={throttled:0,overflow:0};let Z=_historyBudget.MAX_HISTORY_TOKENS;const se=t.seenUrls??new Set;const De=/https?:\/\/[^\s"'\\)\]}>]+/g;let ke=false;const z=[];let ve=false;const ae=[];let de=false;let we=false;let ee=false;let Te=false;let Se=false;const je=[...h].reverse().find(O=>O.role==="user");const Be=/\?\s*$/.test(je?.text?.trim()??"");for(let O=0;O<V;O++){if($?.aborted){yield{type:"done",stopReason:"stopped"};return h}if((0,_realNow.realNow)()>X){yield{type:"block",block:{id:`cap${(0,_realNow.realNow)()}`,kind:"notice",tone:"warning",text:`This is taking too long \u2014 stopped after ${Math.round(DEFAULT_TURN_MS/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 q=(0,_historyBudget.budgetForRequest)(h,be(),C.chars(Z),C.charsPerToken,v.liveCallIds());if(q.droppedRounds>0){h.length=0;h.push(...q.messages);yield{type:"history-trimmed",droppedRounds:q.droppedRounds,droppedPinned:q.droppedPinned}}else if(q.messages!==h){h.length=0;h.push(...q.messages)}let I="";let Ae=false;const F=e=>{const l=ke&&!Ae;Ae=true;ke=true;return l?{type:"text",delta:e,breakBefore:true}:{type:"text",delta:e}};let w=[];const Re=new Set;let N="";let le=true;let W=[];let te=false;let re;let G;let ce=0;for(;;){ce+=1;I="";w=[];N="";le=true;W=[];te=false;re=void 0;G=void 0;let e;const l=ge+h.reduce((a,p)=>a+(0,_historyBudget.messageSize)(p),0);for await(const a of o.send({messages:h,system:c,systemVolatile:u,tools:ne,model:T,maxTokens:g,signal:$,meta:{askId:Le,round:O+1,attempt:ce}})){if(a.type==="text"){I+=a.delta;if(!le){yield F(a.delta)}else if((0,_textToolCalls.couldBeToolCallEnvelope)(I)){N+=a.delta}else{le=false;N="";yield F(I)}}else if(a.type==="tool-call"){w.push(a.call)}else if(a.type==="meter"){yield{type:"meter",frame:a.frame}}else if(a.type==="thinking"){W.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")&&I===""&&w.length===0&&W.length===0){e={problem:a.problem,message:a.message}}else{yield{type:"error",message:a.message,...a.problem?.hosted?{hosted:a.problem.hosted}:{}};te=true}}else if(a.type==="done"){re=a.outcome;if(a.usage){C.observe(l,(0,_tokenCalibration.promptTokensOf)(a.usage,o.protocol));yield{type:"usage",...a.usage,model:a.model}}}}if(!e)break;const r=e.problem.kind;const i=1+(r==="throttled"?THROTTLE_RETRIES:OVERFLOW_RETRIES);const b=ie[r];let f=r==="throttled"?Math.min(e.problem.retryAfterMs??RETRY_BASE_MS*2**b,RETRY_AFTER_CAP_MS)+Math.floor(Math.random()*RETRY_JITTER_MS):0;let _=b>=i-1||$?.aborted===true||(0,_realNow.realNow)()+f>X;if(e.problem.hosted&&ce>=2)_=true;if(!_&&r==="overflow"){Z=Math.floor(Z/2);const a=h.reduce((J,L)=>J+(0,_historyBudget.messageSize)(L),0);const p=(0,_historyBudget.budgetForRequest)(h,be(),C.chars(Z),C.charsPerToken,v.liveCallIds());const H=p.messages.reduce((J,L)=>J+(0,_historyBudget.messageSize)(L),0);if(H>=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=r==="throttled"?b>0?`The AI endpoint is rate-limiting requests \u2014 tried ${b+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})`};te=true;break}ie[r]+=1;yield{type:"retrying",reason:r,attempt:ie[r]+1,maxAttempts:i,inMs:f};if(f>0)await sleep(f,$);if($?.aborted){yield{type:"done",stopReason:"stopped"};return h}}if(te){if(N)yield F(N);yield{type:"done",stopReason:"error"};return h}if(!G&&re!=="completed"){G={message:re==="output-limited"?w.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(N)yield F(N);if(I.trim())h.push({role:"assistant",text:I});yield{type:"block",block:{id:`cut${(0,_realNow.realNow)()}`,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(N){const e=w.length===0?(0,_textToolCalls.parseTextToolCalls)(N,n):void 0;if(e){for(const l of e.calls){w.push(l);Re.add(l.id)}I=e.reply;if(e.reply)yield F(e.reply)}else{yield F(N)}N=""}h.push({role:"assistant",text:I,toolCalls:w.length?w:void 0,thinking:W.length?W:void 0});if(I.trim())ae.push(I.trim());if(w.length===0&&!ee&&!de&&O<V-1&&((0,_planOnlyStop.announcesUnstartedWork)(I)||Te&&!Se&&!Be)){ee=true;h.push({role:"user",text:_planOnlyStop.PLAN_ONLY_NUDGE});continue}if(w.length===0&&!ee&&ae.length===0&&O<V-1){ee=true;h.push({role:"user",text:_planOnlyStop.SILENT_NUDGE});continue}if(w.length===0){const e=ae.join("\n\n");const l=(0,_askGate.synthesizeShortfallBlock)({text:e,attempted:we});if(l)yield{type:"block",block:l};const r=de||l?null:(0,_askGate.synthesizeAskBlock)(e);if(r){yield{type:"block",block:r};yield{type:"awaiting-user",blockId:r.id}}yield{type:"done",stopReason:r?"awaiting-user":"answered"};return h}const k=[];let Ie=false;const _e=new Map;if(w.length>1){const e=w.every(l=>{if(l.name===_uiTool.UI_TOOL_NAME)return false;const r=(0,_toProviderTools.fromProviderToolName)(l.name,n);if(!r||r==="ask-buoy")return false;const i=l.input?.action;if(typeof i!=="string"||i===_snapshotReads.SNAPSHOT_ACTION)return false;const b=findDescriptor(n,r,i);if(!b||b.effect!=="read")return false;return(0,_policy.decide)({descriptor:b,toolId:r,policy:P,isRelease:x}).verdict==="allow"});if(e){for(const l of w){const r=(0,_toProviderTools.fromProviderToolName)(l.name,n);const i=String(l.input.action);const b={...l.input.params??{}};const f=findDescriptor(n,r,i);const _=(0,_normalizeParams.normalizeParams)(r,i,b);const a=(0,_validateParams.applyDefaults)(_.params,f.params);if(!(0,_validateParams.validateParams)(a,f.params).ok)continue;const p=Promise.resolve(d(r,i,a)).catch(H=>{throw H});p.catch(()=>{});_e.set(l.id,p)}}}let ue=null;const ze=e=>{const l=(0,_toProviderTools.fromProviderToolName)(e.name,n)??e.name;const r=typeof e.input?.action==="string"?e.input.action:"";const i=r?findDescriptor(n,l,r):void 0;const b=e.input?.params??{};return[{type:"tool-start",id:e.id,toolId:l,action:r,label:i?(0,_policy.describeCall)(l,i,b):`${l}.${r}`,description:i?.summary??"",params:b,effect:i?.effect??"read"},{type:"tool-end",id:e.id,ok:false,summary:"stopped",durationMs:0}]};const Ne=w.map(e=>{if(e.name===_uiTool.UI_TOOL_NAME)return void 0;const l=(0,_toProviderTools.fromProviderToolName)(e.name,n);const r=typeof e.input?.action==="string"?e.input.action:void 0;if(!l||!r)return void 0;const i=findDescriptor(n,l,r);if(!i)return void 0;const b=e.input.params??{};const f=(0,_validateParams.applyDefaults)((0,_normalizeParams.normalizeParams)(l,r,b).params,i.params);if(!(0,_validateParams.validateParams)(f,i.params).ok)return void 0;const _=(0,_policy.decide)({descriptor:i,toolId:l,policy:P,isRelease:x});return{call:e,toolId:l,action:r,descriptor:i,params:f,label:(0,_policy.describeCall)(l,i,f),mutates:i.effect!=="read",gated:_.verdict==="needs-approval",reason:_.verdict==="needs-approval"?_.reason:""}});const Fe=Ne.some(e=>e?.gated);const M=new Map;let Ee=false;let $e=false;async function*Ge(){Ee=true;for(const e of Ne){if(!e?.gated||M.has(e.call.id))continue;if(A?.has(`${e.toolId}.${e.action}`)){M.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=(0,_realNow.realNow)();const r=await readTargetDigest({toolId:e.toolId,action:e.action,params:e.params,dispatch:d,catalog:n});const i=readAnswer(A?.has(`${e.toolId}.${e.action}`)?true:U?await U({id:e.call.id,toolId:e.toolId,action:e.action,label:e.label,description:e.descriptor.summary,reason:e.reason,params:e.params,targetDigest:r}):false);X+=(0,_realNow.realNow)()-l;const b=i.approved;M.set(e.call.id,b);if(i.trust)A?.add(`${e.toolId}.${e.action}`);if(i.reason)B.set(e.call.id,i.reason);if(!b){$e=true;return}}}for(const e of w){if($?.aborted){if(e.name!==_uiTool.UI_TOOL_NAME){for(const s of ze(e))yield s}k.push({toolCallId:e.id,content:"Not run \u2014 the user pressed Stop before this call started.",isError:true});continue}const l=e.input?.[_types.UNPARSEABLE_ARGS];if(typeof l==="string"){k.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===_uiTool.UI_TOOL_NAME){const s=(0,_uiTool.buildUiBlock)(e.input);if(!s.ok||!s.block){k.push({toolCallId:e.id,content:`Invalid ${_uiTool.UI_TOOL_NAME} block:
|
|
2
|
-
${
|
|
3
|
-
|
|
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 m=0;if(s.block.kind==="imageGrid"){const S=s.block.images.filter(R=>se.has(R.url));m=s.block.images.length-S.length;if(S.length===0){k.push({toolCallId:e.id,content:URL_PROVENANCE_REJECTION,isError:true});continue}s.block={...s.block,images:S}}if(s.block.kind==="list"){const S=s.block.items.map(R=>{if(!R.image||se.has(R.image))return R;m+=1;return{...R,image:void 0}});s.block={...s.block,items:S}}yield{type:"block",block:s.block,forToolCallId:e.id};if(s.block.kind==="actions"||s.block.kind==="suggestions"||s.block.kind==="plan"&&s.block.pending){de=true}if((0,_types2.isAskBlock)(s.block)){ue=s.block.id;k.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{k.push({toolCallId:e.id,content:"Shown to the user. Don't repeat its contents in text."+(m>0?droppedImageNote(m):"")})}continue}const r=(0,_toProviderTools.fromProviderToolName)(e.name,n);const i=e.input.action;const b=(s,m)=>[{type:"tool-start",id:e.id,toolId:r??e.name,action:i??"",label:s,description:"",params:e.input.params??{},effect:"read"},{type:"tool-end",id:e.id,ok:false,summary:m,durationMs:0}];if(!r){for(const s of b(e.name,"No such tool"))yield s;k.push({toolCallId:e.id,content:`There is no tool called "${e.name}". Use one of the tools you were given.`,isError:true});continue}if(!i){for(const s of b(e.name,"No action given"))yield s;k.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 f=findDescriptor(n,r,i);if(!f){const s=n.find(m=>m.toolId===r)?.actions.map(m=>m.action).join(", ");for(const m of b(`${r}.${i}`,"No such action"))yield m;k.push({toolCallId:e.id,content:`"${i}" is not an action on ${r}.${s?` Valid actions: ${s}.`:""}`,isError:true});continue}const _=e.input.params??{};const a=(0,_normalizeParams.normalizeParams)(r,i,_);const p=(0,_validateParams.applyDefaults)(a.params,f.params);const H=(0,_validateParams.validateParams)(p,f.params);if(!H.ok){k.push({toolCallId:e.id,content:`Invalid parameters for ${r}.${i}:
|
|
5
|
-
${
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"digestOf",{enumerable:true,get:function(){return _digest.digestOf}});exports.readTargetDigest=readTargetDigest;exports.runAgentTurn=runAgentTurn;exports.runGatedAction=runGatedAction;var _catalog=require("../catalog/catalog.g");var _validateParams=require("../catalog/validateParams");var _normalizeParams=require("../catalog/normalizeParams");var _toProviderTools=require("../catalog/toProviderTools");var _snapshotReads=require("../catalog/snapshotReads");var _types=require("../providers/types");var _ledger=require("../effects/ledger");var _turnScope=require("../policy/turnScope");var _policy=require("../policy/policy");var _redact=require("../policy/redact");var _idGrounding=require("./idGrounding");var _effectFor=require("./effectFor");var _digest=require("../effects/digest");var _uiTool=require("../blocks/uiTool");var _receipts=require("../blocks/receipts");var _types2=require("../blocks/types");var _askGate=require("./askGate");var _textToolCalls=require("./textToolCalls");var _planOnlyStop=require("./planOnlyStop");var _compactScreen=require("./compactScreen");var _historyBudget=require("./historyBudget");var _tokenCalibration=require("./tokenCalibration");var _evidence=require("./evidence");var _retrieve=require("./retrieve");var _verify=require("./verify");var _realNow=require("../realNow");const MAX_RESULT_CHARS=24e3;const MAX_TRACE_RESULT_CHARS=2e3;const LOOP_REPEATS=3;function callSignature(t){const n=o=>{if(o===null||typeof o!=="object")return o;if(Array.isArray(o))return o.map(n);const a=o;return Object.keys(a).sort().reduce((d,v)=>(d[v]=n(a[v]),d),{})};return t.map(o=>`${o.name}:${JSON.stringify(n(o.input??{}))}`).join("|")}const LOOP_WARNING="[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 DEFAULT_MAX_STEPS=24;const CONTINUE_SEND="Resume where you left off. Don't redo past changes. Read the past tool results first.";const STEP_CAP_WRAP_UP="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 DEFAULT_TURN_MS=18e4;const THROTTLE_RETRIES=2;const OVERFLOW_RETRIES=1;const RETRY_BASE_MS=1e3;const RETRY_JITTER_MS=250;const RETRY_AFTER_CAP_MS=3e4;function sleep(t,n){return new Promise(o=>{if(n?.aborted)return o();const a=(0,_realNow.realSetTimeout)(d,t);function d(){(0,_realNow.realClearTimeout)(a);n?.removeEventListener("abort",d);o()}n?.addEventListener("abort",d,{once:true})})}function readAnswer(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 declinedResult(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 closeAction(t,n){const o=t.toLowerCase();const a=n.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 findDescriptor(t,n,o){return t.find(a=>a.toolId===n)?.actions.find(a=>a.action===o)}const URL_PROVENANCE_REJECTION="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 droppedImageNote=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 fullText(t){try{return JSON.stringify(t??null)}catch{return String(t)}}function encodeResult(t,n){if(t.length<=MAX_RESULT_CHARS)return t;return`${t.slice(0,MAX_RESULT_CHARS)}${(0,_evidence.truncationMarker)(t.length,n)}`}function summarise(t){if(t===null||t===void 0)return"Done";if(Array.isArray(t))return countOf(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 a of["returned","count","total"]){const d=n[a];if(typeof d==="number")return countOf(d)}const o=Object.values(n).filter(Array.isArray);if(o.length===1)return countOf(o[0].length);return"Done"}return String(t).slice(0,80)}function countOf(t){return t===1?"1 item":`${t} items`}function reportsFailure(t){return typeof t==="object"&&t!==null&&t.ok===false}const EMPTY_TAP_ERROR="tapElement needs nativeTag, testID or query. Read describeScreen and pass one.";function emptyTap(t,n,o){return t==="highlight-updates"&&n==="tapElement"&&![o.nativeTag,o.testID,o.query].some(a=>typeof a==="string"?a.trim().length>0:a!=null)}function tapResult(t,n,o){if(t!=="highlight-updates"||n!=="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."}}async function*runAgentTurn(t){const{provider:n,catalog:o,system:a,systemVolatile:d,model:v,maxTokens:m,dispatch:c,readSnapshot:g,storeKeyOwners:U,ledger:k,policy:x,isRelease:D,requestApproval:J,signal:_,evidence:W,trusted:A,procedures:B}=t;const Y=new Map;const O=t.calibration??new _tokenCalibration.TokenCalibration;const ne=[...t.messages].reverse().find(p=>(0,_types.isRealUserMessage)(p));const M=(0,_turnScope.classifyTurn)(ne?.role==="user"?ne.text:"");const f=[...t.messages];const ue=n.protocol==="anthropic"?t.feedOptions??{}:{};const z=ue.freezeHistory===true;const P=ue.notices==="system-msg";const se=(p,I=false)=>({role:"user",text:p,...n.protocol==="anthropic"?{source:"engine"}:{},...I?{systemNotice:true}:{}});const qe=()=>{const p=f[f.length-1];return P&&(p?.role==="tool-results"||p?.role==="user"&&p.systemNotice===true)};const Ue=(0,_idGrounding.idGrounding)(f,`${t.system}
|
|
2
|
+
${t.systemVolatile??""}${ne?.role==="user"&&ne.liveBlock?`
|
|
3
|
+
${ne.liveBlock.text}`:""}
|
|
4
|
+
${JSON.stringify(B??[])}`);let Q=(0,_toProviderTools.toProviderTools)(o,{availableToolIds:t.availableToolIds,availableActions:t.availableActions,isRelease:D});Q.push((0,_uiTool.uiProviderTool)());if(z)Q=JSON.parse(JSON.stringify(Q));const V=x.maxSteps??DEFAULT_MAX_STEPS;const xe=newAskId();const st=k.generation;const it=new Set(k.list().map(p=>p.id));const De=a.length+(d?.length??0)+Q.reduce((p,I)=>p+I.description.length+JSON.stringify(I.inputSchema).length,0);const fe=()=>De+O.chars(m);let pe=(0,_realNow.realNow)()+DEFAULT_TURN_MS;const ke={throttled:0,overflow:0};let K=_historyBudget.MAX_HISTORY_TOKENS;const ve=t.seenUrls??new Set;const at=/https?:\/\/[^\s"'\\)\]}>]+/g;let we=false;const X=[];let Le=false;const Te=[];let Se=false;let Me=false;let he=false;let je=false;let Be=false;const dt=[...f].reverse().find(_types.isRealUserMessage);const lt=/\?\s*$/.test(dt?.text?.trim()??"");const ze=p=>p.reduce((I,$)=>I+(0,_historyBudget.messageSize)($),0)<=Math.min(O.chars(K),O.chars(_historyBudget.MAX_REQUEST_TOKENS)-fe());const Re="This turn has no room left. Tap Continue to go on.";for(let p=0;p<V;p++){if(_?.aborted){yield{type:"done",stopReason:"stopped"};return f}if((0,_realNow.realNow)()>pe){yield{type:"block",block:{id:`cap${(0,_realNow.realNow)()}`,kind:"notice",tone:"warning",text:`This is taking too long \u2014 stopped after ${Math.round(DEFAULT_TURN_MS/1e3)}s. What it found so far is above.`,actions:[{label:"Continue",primary:true,send:CONTINUE_SEND}]}};yield{type:"done",stopReason:"time-cap"};return f}const I=z&&p>0?{messages:f,droppedRounds:0,droppedPinned:0}:(0,_historyBudget.budgetForRequest)(f,fe(),O.chars(K),O.charsPerToken,k.liveCallIds());if(I.droppedRounds>0){f.length=0;f.push(...I.messages);yield{type:"history-trimmed",droppedRounds:I.droppedRounds,droppedPinned:I.droppedPinned}}else if(I.messages!==f){f.length=0;f.push(...I.messages)}if(V>6&&p===V-6){f.push(se("6 steps left. Finish what the user asked. Skip extra checks. Batch reads that do not depend on each other in one round.",qe()))}if(z&&!ze(f)){yield{type:"block",block:{id:`space${(0,_realNow.realNow)()}`,kind:"notice",tone:"warning",text:Re,actions:[{label:"Continue",primary:true,send:CONTINUE_SEND}]}};yield{type:"done",stopReason:"incomplete"};return f}let $="";let Je=false;const ee=e=>{const l=we&&!Je;Je=true;we=true;return l?{type:"text",delta:e,breakBefore:true}:{type:"text",delta:e}};let S=[];const We=new Set;let q="";let Ie=true;let ae=[];let ye=false;let F;let G;let Ne=0;for(;;){Ne+=1;$="";S=[];q="";Ie=true;ae=[];ye=false;F=void 0;G=void 0;let e;const l=De+f.reduce((u,y)=>u+(0,_historyBudget.messageSize)(y),0);for await(const u of n.send({messages:f,system:a,systemVolatile:d,tools:Q,model:v,maxTokens:m,signal:_,meta:{askId:xe,round:p+1,attempt:Ne}})){if(u.type==="text"){$+=u.delta;if(!Ie){yield ee(u.delta)}else if((0,_textToolCalls.couldBeToolCallEnvelope)($)){q+=u.delta}else{Ie=false;q="";yield ee($)}}else if(u.type==="tool-call"){S.push(u.call)}else if(u.type==="meter"){yield{type:"meter",frame:u.frame}}else if(u.type==="thinking"){ae.push(u.block);if(u.block.type==="thinking"&&u.block.thinking.trim()){yield{type:"reasoning",text:u.block.thinking}}}else if(u.type==="error"){if(u.kind==="truncated"||u.kind==="timeout"){G={message:u.message}}else if(u.problem&&(u.problem.kind==="throttled"||u.problem.kind==="overflow")&&$===""&&S.length===0&&ae.length===0){e={problem:u.problem,message:u.message}}else{yield{type:"error",message:u.message,...u.problem?.hosted?{hosted:u.problem.hosted}:{}};ye=true}}else if(u.type==="done"){F=u.outcome;if(u.usage){O.observe(l,(0,_tokenCalibration.promptTokensOf)(u.usage,n.protocol));yield{type:"usage",...u.usage,model:u.model}}}}if(!e)break;const r=e.problem.kind;if(z&&r==="overflow"){G={message:Re};break}const s=1+(r==="throttled"?THROTTLE_RETRIES:OVERFLOW_RETRIES);const b=ke[r];let h=r==="throttled"?Math.min(e.problem.retryAfterMs??RETRY_BASE_MS*2**b,RETRY_AFTER_CAP_MS)+Math.floor(Math.random()*RETRY_JITTER_MS):0;let C=b>=s-1||_?.aborted===true||(0,_realNow.realNow)()+h>pe;if(e.problem.hosted&&Ne>=2)C=true;if(!C&&r==="overflow"){K=Math.floor(K/2);const u=f.reduce((de,H)=>de+(0,_historyBudget.messageSize)(H),0);const y=(0,_historyBudget.budgetForRequest)(f,fe(),O.chars(K),O.charsPerToken,k.liveCallIds());const te=y.messages.reduce((de,H)=>de+(0,_historyBudget.messageSize)(H),0);if(te>=u){C=true}else{f.length=0;f.push(...y.messages);if(y.droppedRounds>0)yield{type:"history-trimmed",droppedRounds:y.droppedRounds,droppedPinned:y.droppedPinned}}}if(C){const u=r==="throttled"?b>0?`The AI endpoint is rate-limiting requests \u2014 tried ${b+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 y=e.problem.hosted;yield y?{type:"error",message:y.message,hosted:y}:{type:"error",message:`${u} (${e.message})`};ye=true;break}ke[r]+=1;yield{type:"retrying",reason:r,attempt:ke[r]+1,maxAttempts:s,inMs:h};if(h>0)await sleep(h,_);if(_?.aborted){yield{type:"done",stopReason:"stopped"};return f}}if(F==="refused"||F==="context-limited"){yield{type:"error",message:F==="refused"?"Claude could not help with this request.":"Claude ran out of room for this turn. Please send a new message."};yield{type:"done",stopReason:"error"};return f}if(ye){if(q)yield ee(q);yield{type:"done",stopReason:"error"};return f}if(!G&&F!=="completed"){G={message:F==="output-limited"?S.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(q)yield ee(q);if($.trim())f.push({role:"assistant",text:$});yield{type:"block",block:{id:`cut${(0,_realNow.realNow)()}`,kind:"notice",tone:"warning",text:G.message,actions:[{label:"Continue",primary:true,send:CONTINUE_SEND}]}};yield{type:"done",stopReason:"incomplete"};return f}if(q){const e=S.length===0?(0,_textToolCalls.parseTextToolCalls)(q,o):void 0;if(e){for(const l of e.calls){S.push(l);We.add(l.id)}$=e.reply;if(e.reply)yield ee(e.reply)}else{yield ee(q)}q=""}f.push({role:"assistant",text:$,toolCalls:S.length?S:void 0,thinking:ae.length?ae:void 0});if($.trim())Te.push($.trim());if(S.length===0&&!he&&!Se&&p<V-1&&((0,_planOnlyStop.announcesUnstartedWork)($,M==="task")||je&&!Be&&!lt)){he=true;f.push(se(_planOnlyStop.PLAN_ONLY_NUDGE));continue}if(S.length===0&&!he&&Te.length===0&&p<V-1){he=true;f.push(se(_planOnlyStop.SILENT_NUDGE));continue}if(S.length===0){const e=Te.join("\n\n");const l=(0,_askGate.synthesizeShortfallBlock)({text:e,attempted:Me});if(l)yield{type:"block",block:l};const r=Se||l?null:(0,_askGate.synthesizeAskBlock)(e);if(r){yield{type:"block",block:r};yield{type:"awaiting-user",blockId:r.id}}yield{type:"done",stopReason:r?"awaiting-user":"answered"};return f}const w=[];const me=[];const L=e=>{if(!P)return e;me.push(e.trim());return""};let Ye=false;const Qe=new Map;if(S.length>1){const e=S.every(l=>{if(l.name===_uiTool.UI_TOOL_NAME)return false;const r=(0,_toProviderTools.fromProviderToolName)(l.name,o);if(!r||r==="ask-buoy")return false;const s=l.input?.action;if(typeof s!=="string"||s===_snapshotReads.SNAPSHOT_ACTION)return false;const b=findDescriptor(o,r,s);if(!b||b.effect!=="read")return false;return(0,_policy.decide)({descriptor:b,toolId:r,policy:x,isRelease:D}).verdict==="allow"});if(e){for(const l of S){const r=(0,_toProviderTools.fromProviderToolName)(l.name,o);const s=String(l.input.action);const b={...l.input.params??{}};const h=findDescriptor(o,r,s);const C=(0,_normalizeParams.normalizeParams)(r,s,b);const u=(0,_validateParams.applyDefaults)(C.params,h.params);if(!(0,_validateParams.validateParams)(u,h.params).ok)continue;const y=Promise.resolve(c(r,s,u)).catch(te=>{throw te});y.catch(()=>{});Qe.set(l.id,y)}}}let Ae=null;const ut=e=>{const l=(0,_toProviderTools.fromProviderToolName)(e.name,o)??e.name;const r=typeof e.input?.action==="string"?e.input.action:"";const s=r?findDescriptor(o,l,r):void 0;const b=e.input?.params??{};return[{type:"tool-start",id:e.id,toolId:l,action:r,label:s?(0,_policy.describeCall)(l,s,b):`${l}.${r}`,description:s?.summary??"",params:b,effect:s?.effect??"read"},{type:"tool-end",id:e.id,ok:false,summary:"stopped",durationMs:0}]};const ge=new Map;if(M==="question"){for(const e of S){if((0,_toProviderTools.fromProviderToolName)(e.name,o)!=="highlight-updates"||e.input?.action!=="tapElement")continue;const l=(0,_normalizeParams.normalizeParams)("highlight-updates","tapElement",e.input.params??{}).params;if(emptyTap("highlight-updates","tapElement",l))continue;const r=findDescriptor(o,"highlight-updates","describeScreen");const s=findDescriptor(o,"highlight-updates","tapElement");if(_?.aborted||!r||!s||(0,_policy.decide)({descriptor:r,toolId:"highlight-updates",policy:x,isRelease:D}).verdict!=="allow"||(0,_policy.decide)({descriptor:s,toolId:"highlight-updates",policy:x,isRelease:D,turnScope:M,params:l}).verdict==="refuse")continue;const b=await c("highlight-updates","describeScreen",{}).catch(()=>void 0);ge.set(e.id,(0,_turnScope.tapLabels)(b,l))}}const Ve=S.map(e=>{if(e.name===_uiTool.UI_TOOL_NAME)return void 0;const l=(0,_toProviderTools.fromProviderToolName)(e.name,o);const r=typeof e.input?.action==="string"?e.input.action:void 0;if(!l||!r)return void 0;const s=findDescriptor(o,l,r);if(!s)return void 0;const b=e.input.params??{};const h=(0,_validateParams.applyDefaults)((0,_normalizeParams.normalizeParams)(l,r,b).params,s.params);if(emptyTap(l,r,h)||!(0,_validateParams.validateParams)(h,s.params).ok)return void 0;const C=(0,_policy.decide)({descriptor:s,toolId:l,policy:x,isRelease:D,turnScope:M,params:h,tapLabels:ge.get(e.id)});return{call:e,toolId:l,action:r,descriptor:s,params:h,label:(0,_policy.describeCall)(l,s,h),mutates:s.effect!=="read",gated:C.verdict==="needs-approval",turnScoped:C.verdict==="needs-approval"&&C.turnScoped,reason:C.verdict==="needs-approval"?C.reason:""}});const ft=Ve.some(e=>e?.gated);const j=new Map;let Ke=false;let Xe=false;async function*pt(){Ke=true;for(const e of Ve){if(!e?.gated||j.has(e.call.id))continue;if(!e.turnScoped&&A?.has(`${e.toolId}.${e.action}`)){j.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=(0,_realNow.realNow)();const r=await readTargetDigest({toolId:e.toolId,action:e.action,params:e.params,dispatch:c,catalog:o});const s=readAnswer(!e.turnScoped&&A?.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:r}):false);pe+=(0,_realNow.realNow)()-l;const b=s.approved;j.set(e.call.id,b);if(s.trust)A?.add(`${e.toolId}.${e.action}`);if(s.reason)Y.set(e.call.id,s.reason);if(!b){Xe=true;return}}}for(const e of S){if(_?.aborted){if(e.name!==_uiTool.UI_TOOL_NAME){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?.[_types.UNPARSEABLE_ARGS];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===_uiTool.UI_TOOL_NAME){const i=(0,_uiTool.buildUiBlock)(e.input);if(!i.ok||!i.block){w.push({toolCallId:e.id,content:`Invalid ${_uiTool.UI_TOOL_NAME} block:
|
|
5
|
+
${i.errors.join("\n")}`+L("\n\nResend 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 R=0;if(i.block.kind==="imageGrid"){const N=i.block.images.filter(E=>ve.has(E.url));R=i.block.images.length-N.length;if(N.length===0){w.push({toolCallId:e.id,content:P?"Rejected: image URLs were not read from a tool result."+L(URL_PROVENANCE_REJECTION):URL_PROVENANCE_REJECTION,isError:true});continue}i.block={...i.block,images:N}}if(i.block.kind==="list"){const N=i.block.items.map(E=>{if(!E.image||ve.has(E.image))return E;R+=1;return{...E,image:void 0}});i.block={...i.block,items:N}}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){Se=true}if((0,_types2.isAskBlock)(i.block)){Ae=i.block.id;w.push({toolCallId:e.id,content:"Shown. Waiting for the user's answer \u2014 it will arrive as their next message."+L(" Do not guess it.")})}else{w.push({toolCallId:e.id,content:"Shown to the user."+L(" Don't repeat its contents in text.")+(R>0?droppedImageNote(R):"")})}continue}const r=(0,_toProviderTools.fromProviderToolName)(e.name,o);const s=e.input.action;const b=(i,R)=>[{type:"tool-start",id:e.id,toolId:r??e.name,action:s??"",label:i,description:"",params:e.input.params??{},effect:"read"},{type:"tool-end",id:e.id,ok:false,summary:R,durationMs:0}];if(!r){for(const i of b(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 b(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 h=findDescriptor(o,r,s);if(!h){const i=o.find(T=>T.toolId===r)?.actions.map(T=>T.action)??[];const R=o.filter(T=>T.toolId!==r&&T.actions.some(Ce=>Ce.action===s));const N=i.filter(T=>closeAction(T,s));const E=[...R.map(T=>`${T.toolId}.${s}`),...N.map(T=>`${r}.${T}`)].slice(0,3);const re=`${r} has no ${s}.${E.length?` Did you mean ${E.join(" or ")}?`:""}`;for(const T of b(`${r}.${s}`,E.length?re:"No such action"))yield T;w.push({toolCallId:e.id,content:`${re}${i.length?` Valid actions: ${i.join(", ")}.`:""}`,isError:true});continue}const C=e.input.params??{};const u=(0,_normalizeParams.normalizeParams)(r,s,C);const y=(0,_validateParams.applyDefaults)(u.params,h.params);if(emptyTap(r,s,y)){for(const i of b(`${r}.${s}`,EMPTY_TAP_ERROR))yield i;w.push({toolCallId:e.id,content:JSON.stringify({ok:false,error:P?"tapElement needs nativeTag, testID or query."+L("Read describeScreen and pass nativeTag, testID or query."):EMPTY_TAP_ERROR}),isError:true});continue}const te=(0,_validateParams.validateParams)(y,h.params);if(!te.ok){w.push({toolCallId:e.id,content:`Invalid parameters for ${r}.${s}:
|
|
6
|
+
${te.errors.join("\n")}
|
|
6
7
|
|
|
7
8
|
Expected schema:
|
|
8
|
-
${JSON.stringify(
|
|
9
|
+
${JSON.stringify(h.params)}`,isError:true});continue}const de=(0,_normalizeParams.aliasNote)(u.notes);const H=h.effect!=="read"?Ue.trailer(y,!P):"";if(P&&H)L(_idGrounding.UNSEEN_ID_ADVICE);const be=(0,_policy.describeCall)(r,h,y);const oe=(0,_policy.decide)({descriptor:h,toolId:r,policy:x,isRelease:D,turnScope:M,params:y,tapLabels:ge.get(e.id)});const le=i=>[{type:"tool-start",id:e.id,toolId:r,action:s,label:be,description:h.summary,params:y,effect:h.effect},{type:"tool-end",id:e.id,ok:false,summary:i,durationMs:0}];if(oe.verdict==="refuse"){for(const i of le("refused"))yield i;w.push({toolCallId:e.id,content:oe.reason,isError:true});continue}const _e=oe.verdict==="needs-approval";if(ft&&!Ke&&(h.effect!=="read"||_e)){yield*pt()}if(Xe&&(h.effect!=="read"||_e)){for(const i of le("declined"))yield i;w.push({toolCallId:e.id,content:M==="question"?_turnScope.QUESTION_DECLINED:j.get(e.id)===false?declinedResult(Y.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(_e){let i;if(j.has(e.id)){i=j.get(e.id)}else if(!oe.turnScoped&&A?.has(`${r}.${s}`)){i=true;j.set(e.id,true)}else{yield{type:"approval-required",id:e.id,toolId:r,action:s,label:be,description:h.summary,reason:oe.reason};const R=(0,_realNow.realNow)();const N=await readTargetDigest({toolId:r,action:s,params:y,dispatch:c,catalog:o});const E=readAnswer(J?await J({id:e.id,toolId:r,action:s,label:be,description:h.summary,reason:oe.reason,params:y,targetDigest:N}):false);pe+=(0,_realNow.realNow)()-R;i=E.approved;j.set(e.id,i);if(E.trust)A?.add(`${r}.${s}`);if(E.reason)Y.set(e.id,E.reason)}if(!i){for(const R of le("declined"))yield R;w.push({toolCallId:e.id,content:M==="question"?_turnScope.QUESTION_DECLINED:declinedResult(Y.get(e.id)),isError:true});continue}}if(_askGate.ACQUISITION_CALLS.has(`${r}.${s}`))Me=true;if(r==="ask-buoy"&&s==="openProcedure")je=true;yield{type:"tool-start",id:e.id,toolId:r,action:s,label:be,description:h.summary,params:y,effect:h.effect};const Ze=(0,_realNow.realNow)();const et=await captureBefore(h,r,y,c);const $e=await captureStoreState(h,r,y,c);if(_?.aborted){for(const i of le("stopped"))yield i;w.push({toolCallId:e.id,content:"Not run \u2014 the user pressed Stop before this call started.",isError:true});continue}const tt=(0,_policy.decide)({descriptor:h,toolId:r,policy:x,isRelease:D,turnScope:M,params:y,tapLabels:ge.get(e.id)});if(tt.verdict==="refuse"){for(const i of le("refused"))yield i;w.push({toolCallId:e.id,content:tt.reason,isError:true});continue}try{let i=s===_snapshotReads.SNAPSHOT_ACTION?(0,_snapshotReads.projectSnapshot)(r,await requireSnapshot(g,r),y):r==="ask-buoy"?await runAskBuoyAction(s,k,c,W,y,B):await(Qe.get(e.id)??c(r,s,y));i=tapResult(r,s,i);const R=(0,_redact.redact)((0,_redact.stripSelfTraffic)(i));const N=reportsFailure(i);if(h.effect!=="read"&&!N)Be=true;const E=fullText(r==="highlight-updates"&&s==="describeScreen"&&!N?(0,_compactScreen.compactScreen)(R):R);const re=W&&!N&&!(r==="ask-buoy"&&s==="retrieve")?W.stash({toolId:r,action:s,params:y,capturedAt:(0,_realNow.realNow)(),text:E}):void 0;const T=encodeResult(E,re);Ue.add(E);const Ce=T.length>MAX_TRACE_RESULT_CHARS?`${T.slice(0,MAX_TRACE_RESULT_CHARS)}\u2026`:T;yield{type:"tool-end",id:e.id,ok:!N,summary:summarise(i),durationMs:(0,_realNow.realNow)()-Ze,result:Ce};const Oe=$e===void 0||N?void 0:await captureStoreState(h,r,y,c);if(h.effect!=="read"&&r!=="ask-buoy"&&!N){const Pe=k.noteExternalRevert(r,s,y);const rt=(0,_effectFor.effectFor)(r,h,y,i,et,{before:$e,after:Oe});if(rt&&!Pe){const nt=k.record(r,s,rt,st);if(nt)nt.callId=e.id}}const ot=N?void 0:(0,_receipts.projectReceipt)({toolId:r,action:s,params:y,result:R,before:$e??et,after:Oe,effect:h.effect});if(ot)yield{type:"block",block:ot,forToolCallId:e.id};const ce=h.effect!=="read"&&!N?await(0,_verify.verifyOutcome)({toolId:r,action:s,params:y,result:i,dispatch:c,readSnapshot:g,signal:_,after:Oe}):void 0;if(ce)yield{type:"tool-verified",id:e.id,verification:ce};if(P&&ce?.status==="failed")L(_verify.VERIFICATION_REPAIR);for(const Pe of T.match(at)??[])ve.add(Pe);w.push({toolCallId:e.id,content:T+ownedKeyNote(r,h,y,U,P?L:void 0)+de+H+(ce?(0,_verify.verificationTrailer)(ce,!P):"")+(We.has(e.id)?L(_textToolCalls.SALVAGE_NOTE):""),...re?{ref:re}:{}});if(r==="app"&&(s==="reloadApp"||s==="reload")){Ye=true}}catch(i){const R=i instanceof Error?i.message:String(i);yield{type:"tool-end",id:e.id,ok:false,summary:R,durationMs:(0,_realNow.realNow)()-Ze};w.push({toolCallId:e.id,content:`Failed: ${R}${H}`,isError:true})}}if(S.length){X.push(callSignature(S));if(X.length>LOOP_REPEATS)X.shift();const e=!Le&&X.length===LOOP_REPEATS&&X.every(l=>l===X[0]);if(e){Le=true;const l=w[w.length-1];if(P)me.push(LOOP_WARNING);else if(l)l.content=`${l.content}
|
|
9
10
|
|
|
10
|
-
${LOOP_WARNING}`}}
|
|
11
|
+
${LOOP_WARNING}`}}f.push({role:"tool-results",results:w});if(me.length)f.push(se([...new Set(me)].join("\n\n"),true));if(Ae){yield{type:"awaiting-user",blockId:Ae};yield{type:"done",stopReason:"awaiting-user"};return f}if(Ye){yield{type:"done",stopReason:"realm-died"};return f}}if(_?.aborted){yield{type:"done",stopReason:"stopped"};return f}const Z=[];let Fe=false;let Ee=false;const ie=[...f,se(STEP_CAP_WRAP_UP,qe())];const ct=z?{messages:ie}:(0,_historyBudget.budgetForRequest)(ie,fe(),O.chars(K),O.charsPerToken,k.liveCallIds());try{if(z&&!ze(ie))throw new Error(Re);if(z||P||ue.liveBlock==="append"||ue.liveBlock==="system-msg")f.push(ie[ie.length-1]);for await(const p of n.send({messages:ct.messages,system:a,systemVolatile:d,tools:Q,toolChoice:"none",model:v,maxTokens:m,signal:_,meta:{askId:xe,round:V+1,attempt:1}})){if(p.type==="text")Z.push(p.delta);else if(p.type==="tool-call"||p.type==="error")Ee=true;else if(p.type==="meter")yield{type:"meter",frame:p.frame};else if(p.type==="done"){if(p.outcome==="refused"||p.outcome==="context-limited"){yield{type:"error",message:p.outcome==="refused"?"Claude could not help with this request.":"Claude ran out of room for this turn. Please send a new message."};yield{type:"done",stopReason:"error"};return f}Fe=p.outcome==="completed";if(p.usage)yield{type:"usage",...p.usage,model:p.model}}}}catch{Ee=true}if(_?.aborted){yield{type:"done",stopReason:"stopped"};return f}const Ge=Z.join("");if(Ee||!Fe||!Ge.trim()||(0,_textToolCalls.couldBeToolCallEnvelope)(Ge)){const p=k.list().filter(I=>!it.has(I.id));Z.length=0;Z.push(["I ran out of steps. The job is not done.",...p.length?["These steps ran:",...p.map(I=>`- ${I.effect.label}${I.undoneAt?" (since undone)":""}`),"This list does not prove each change worked."]:[]].join("\n"))}let He=true;for(const p of Z){if(!p)continue;yield{type:"text",delta:p,...He&&we?{breakBefore:true}:{}};He=false}f.push({role:"assistant",text:Z.join("")});yield{type:"block",block:{id:`cap${(0,_realNow.realNow)()}`,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:CONTINUE_SEND}]}};yield{type:"done",stopReason:"step-cap"};return f}function ownedKeyNote(t,n,o,a,d){if(t!=="storage"||n.effect==="read")return"";if(!a||typeof o.key!=="string")return"";const v=a[o.key];if(!v)return"";const m=`
|
|
11
12
|
|
|
12
|
-
[Buoy] This wrote to disk, but "${
|
|
13
|
+
[Buoy] This wrote to disk, but "${o.key}" is the saved copy of the live "${v}" store, so nothing on screen has changed \u2014 the app read that key once at startup and has held the state in memory since.`;if(d){d("Use zustand.rehydrate for the store named in the result to load the saved value. Use zustand.setState to change the live store. If the change was for the next app launch, no more work is needed.");return m}return m+` Call zustand.rehydrate({"storeName":"${v}"}) 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.`}async function readTargetDigest(t){const n=findDescriptor(t.catalog??_catalog.CATALOG,t.toolId,t.action);if(!n||n.effect==="read")return void 0;const o=await captureStoreState(n,t.toolId,t.params,t.dispatch);if(o!==void 0)return(0,_digest.digestOf)(o);const a=await captureBefore(n,t.toolId,t.params,t.dispatch);if(a!==void 0)return(0,_digest.digestOf)(a);return void 0}async function runGatedAction(t){const{toolId:n,action:o,dispatch:a,ledger:d,policy:v,isRelease:m}=t;const c=t.catalog??_catalog.CATALOG;const g=findDescriptor(c,n,o);if(!g){return{ok:false,error:`${n}.${o} is not in Buoy's catalog.`}}const U=(0,_normalizeParams.normalizeParams)(n,o,t.params??{});const k=(0,_validateParams.applyDefaults)(U.params,g.params);if(emptyTap(n,o,k))return{ok:false,error:EMPTY_TAP_ERROR};const x=(0,_validateParams.validateParams)(k,g.params);if(!x.ok){return{ok:false,error:x.errors.join("\n")}}const D=(0,_policy.decide)({descriptor:g,toolId:n,policy:v,isRelease:m});if(D.verdict==="refuse"){return{ok:false,error:D.reason}}const J=await captureBefore(g,n,k,a);const _=await captureStoreState(g,n,k,a);const W=(0,_policy.decide)({descriptor:g,toolId:n,policy:v,isRelease:m});if(W.verdict==="refuse"){return{ok:false,error:W.reason}}try{let A=n==="ask-buoy"?await runAskBuoyAction(o,d,a,void 0,k):await a(n,o,k);A=tapResult(n,o,A);if(reportsFailure(A)){const B=A.error;return{ok:false,error:typeof B==="string"?B:"The tool refused this."}}if(g.effect!=="read"&&n!=="ask-buoy"){const B=d.noteExternalRevert(n,o,k);const Y=await captureStoreState(g,n,k,a);const O=(0,_effectFor.effectFor)(n,g,k,A,J,{before:_,after:Y});if(O&&!B)d.record(n,o,O)}return{ok:true,result:A}}catch(A){return{ok:false,error:A instanceof Error?A.message:String(A)}}}async function runAskBuoyAction(t,n,o,a,d,v){if(t==="retrieve"){return(0,_retrieve.retrieveEvidence)(a,d??{})}if(t==="openProcedure"){const m=typeof d?.id==="string"?d.id:"";const c=v?.find(g=>g.id===m);if(!c){const g=(v??[]).map(U=>U.id);return{ok:false,error:g.length?`No procedure "${m}". This app's procedures: ${g.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 m=n.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:(0,_ledger.isReversible)(c.effect)}));return{changes:m,returned:m.length}}if(t==="undoChange"){const m=typeof d?.id==="string"?d.id:"";const c=n.list().find(U=>U.id===m);if(!c){const U=n.list().filter(k=>!k.undoneAt).map(k=>k.id);return{ok:false,error:`No change with id "${m}". Call listChanges for the current ids${U.length?` (${U.join(", ")})`:""}.`}}if(c.undoneAt)return{ok:false,error:`"${c.effect.label}" was already undone.`};if(!(0,_ledger.isReversible)(c.effect)){return{ok:false,error:`"${c.effect.label}" can't be undone automatically \u2014 it is permanent.`}}const g=await n.revertOne(c,o);return g?{ok:false,error:g}:{ok:true,undone:{id:c.id,label:c.effect.label}}}if(t==="undoAll"){const m=await n.revertAll(o);return{ok:m.failed.length===0,...m}}throw new Error(`Unknown ask-buoy action "${t}"`)}async function requireSnapshot(t,n){if(!t){throw new Error(`This app cannot read ${n}'s snapshot \u2014 Buoy's tool registry is not published here.`)}return await t(n)}async function captureStoreState(t,n,o,a){if(n==="zustand"&&t.action==="setState"){if(typeof o.storeName!=="string")return void 0;try{return await a(n,"getStoreState",{storeName:o.storeName})}catch{return void 0}}if(n==="query"&&t.action==="setQueryData"){const d=typeof o.queryHash==="string"?o.queryHash:Array.isArray(o.queryKey)?(0,_normalizeParams.hashQueryKey)(o.queryKey):void 0;if(!d)return void 0;try{return await a(n,"getQueryData",{queryHash:d})}catch{return void 0}}return void 0}async function captureBefore(t,n,o,a){if(t.effect==="read")return void 0;if(n==="network")return captureRuleSwitch(t,o,a);if(n!=="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 v={key:o.key};if(d==="mmkv.get"){if(typeof o.instanceId!=="string")return void 0;v.instanceId=o.instanceId}try{const m=await a(n,d,v);const c=m&&typeof m==="object"?m:void 0;if(c?.found===false)return void 0;const g=c?c.value:m;return{had:g!==void 0&&g!==null,value:g??void 0}}catch{return void 0}}async function captureRuleSwitch(t,n,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(v=>v&&v.id===n.id);if(!d)return void 0;return{had:true,value:String(d.enabled!==false)}}catch{return void 0}}function newAskId(){const t="abcdefghijklmnopqrstuvwxyz0123456789";let n="ask_";for(let o=0;o<20;o++)n+=t[Math.floor(Math.random()*t.length)];return n}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var _vitest=require("vitest");var _runAgentTurn=require("./runAgentTurn");var _systemPrompt=require("./systemPrompt");var _ledger=require("../effects/ledger");const catalog=[{toolId:"sample",title:"Sample",summary:"Test tools",actions:[{action:"read",summary:"Read",effect:"read",release:"works",params:{type:"object",properties:{}}},{action:"write",summary:"Write",effect:"write",release:"works",params:{type:"object",properties:{}}}]}];const note="6 steps left.";async function run(e,t,s=false){const r=[];const n=_vitest.vi.fn(async()=>({value:1}));const i=_vitest.vi.fn(async()=>false);const c=new _ledger.EffectLedger;const p={protocol:"anthropic",async*send(a){r.push(structuredClone(a.messages));const o=r.length;if(o===t||a.toolChoice==="none")yield{type:"text",delta:"The check is done."};else yield{type:"tool-call",call:{id:`call-${o}`,name:"buoy_sample",input:{action:s&&o===19?"write":"read",params:{}}}};yield{type:"done",outcome:"completed"}}};const l=[];for await(const a of(0,_runAgentTurn.runAgentTurn)({provider:p,catalog,system:"s",model:"m",maxTokens:100,messages:[{role:"user",text:s?"Why is the value wrong?":"Check the value."}],dispatch:n,requestApproval:i,ledger:c,policy:{maxSteps:e,requireApproval:[]},isRelease:false}))l.push(a);return{requests:r,dispatch:n,requestApproval:i,ledger:c,events:l}}(0,_vitest.describe)("step budget note",()=>{(0,_vitest.it)("asks for reads with no shared result to share a round",()=>{const e=(0,_systemPrompt.buildSystemPrompt)({catalog:[],isRelease:false,readOnly:false,requireApproval:[]});(0,_vitest.expect)(e).toContain("Batch reads in one round when none needs the other\u2019s result.")});(0,_vitest.it)("adds one note with six rounds left and keeps the cap",async()=>{const e=await run(24,99);(0,_vitest.expect)(e.requests).toHaveLength(25);(0,_vitest.expect)(JSON.stringify(e.requests[17])).not.toContain(note);for(const t of e.requests.slice(18)){(0,_vitest.expect)(t.filter(s=>s.role==="user"&&s.text.startsWith(note))).toHaveLength(1)}(0,_vitest.expect)(e.dispatch).toHaveBeenCalledTimes(24);(0,_vitest.expect)(e.events).toContainEqual({type:"done",stopReason:"step-cap"})});_vitest.it.each([[24,3],[6,99]])("leaves short jobs alone (%i steps)",async(e,t)=>{(0,_vitest.expect)(JSON.stringify((await run(e,t)).requests)).not.toContain(note)});(0,_vitest.it)("keeps question writes behind approval after the note",async()=>{const e=await run(24,20,true);(0,_vitest.expect)(e.requestApproval).toHaveBeenCalledOnce();(0,_vitest.expect)(e.dispatch).not.toHaveBeenCalledWith("sample","write",_vitest.expect.anything());(0,_vitest.expect)(e.ledger.list()).toEqual([])});(0,_vitest.it)("starts a fresh budget for each turn",async()=>{for(let e=0;e<2;e++){const t=await run(8,4);(0,_vitest.expect)(JSON.stringify(t.requests[1])).not.toContain(note);(0,_vitest.expect)(t.requests[2].filter(s=>s.role==="user"&&s.text.startsWith(note))).toHaveLength(1)}})});
|
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
The people who talk to you are usually NOT developers \u2014 QA testers, customer support, product managers. Write like you are talking to a smart colleague who does not read code. Never show raw JSON, stack traces, or internal ids unless they ask. Say what you found and what it means.
|
|
4
4
|
|
|
5
5
|
You can read the app's live state and change it, through the Buoy tools available to you. Prefer looking before acting: read the relevant state first so your change matches how this app actually stores things, rather than guessing at a shape.`);t.push(`HOW TO WORK
|
|
6
|
-
- Chain tools freely to answer one question.
|
|
6
|
+
- Chain tools freely to answer one question. Read what you need.
|
|
7
|
+
- Batch reads in one round when none needs the other\u2019s result.
|
|
7
8
|
- BIG RESULTS ARE KEPT IN FULL. A result over 24,000 characters is cut, and the cut ends with a marker naming a ref (\`[truncated \u2014 \u2026; ref ev_7]\`). Everything past the cut is still here: call ask-buoy.retrieve with that ref \u2014 bare, to see the shape; then with a path ("stats.0.base_stat") or a pattern ("base_stat") to read the part you need. Never tell the user a value is unreadable because it sat past the cut, and never ask them for a narrower slice. The same goes for \`[earlier result \u2014 \u2026; ref ev_3]\`: that result was compressed out of your memory, and retrieve re-reads EXACTLY what you saw at the time \u2014 the value before a write, say \u2014 while calling the tool again gives the app's current value. Choose by which one the question is about.
|
|
8
9
|
- OPENING A SCREEN IS NOT SEEING IT. A navigation proves where the app is, not what the screen shows \u2014 a page can be locked, empty or showing an error. Read it (describeScreen) before you say what is on it. When asked to open a screen for an id that may not exist, open it anyway and report what it shows: how the screen handles that is the test.
|
|
9
10
|
- A DEEP LINK IS TESTED WITH lifecycle.openUrl (the app's own link handling runs). route-events navigate skips it, so never say a link "opened" when you navigated.
|
|
@@ -14,6 +15,8 @@ You can read the app's live state and change it, through the Buoy tools availabl
|
|
|
14
15
|
- 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
16
|
- 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
17
|
- 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.
|
|
18
|
+
- 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.
|
|
19
|
+
- If you place an order or change state to test a fix, say so plainly in your reply.
|
|
17
20
|
- 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
21
|
- 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
22
|
- 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 +56,7 @@ This app has configured you to look but not touch. Answer questions and diagnose
|
|
|
53
56
|
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
57
|
|
|
55
58
|
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.
|
|
59
|
+
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
60
|
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
61
|
- A request could mean two things \u2192 buoy_ui choice. Never guess between real alternatives.
|
|
59
62
|
- 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.
|