@buoy-gg/agent-core 7.0.64 → 7.0.66
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/catalog/catalog.g.js +2 -2
- package/lib/commonjs/catalog/catalog.source.json +10 -6
- package/lib/commonjs/catalog/validateParams.js +1 -1
- package/lib/commonjs/engine/runAgentTurn.js +6 -6
- package/lib/module/catalog/catalog.g.js +2 -2
- package/lib/module/catalog/catalog.source.json +10 -6
- package/lib/module/catalog/validateParams.js +1 -1
- package/lib/module/engine/runAgentTurn.js +6 -6
- package/lib/web/index.mjs +32 -32
- package/package.json +1 -1
|
@@ -328,6 +328,10 @@
|
|
|
328
328
|
"replace": {
|
|
329
329
|
"type": "boolean",
|
|
330
330
|
"description": "Replace the current screen instead of pushing it on top. Default false. Use true when resetting the app to a base route."
|
|
331
|
+
},
|
|
332
|
+
"reset": {
|
|
333
|
+
"type": "boolean",
|
|
334
|
+
"description": "Clear the old screens, then go to this path. This ignores replace when true. Default false."
|
|
331
335
|
}
|
|
332
336
|
},
|
|
333
337
|
"required": [
|
|
@@ -1391,7 +1395,7 @@
|
|
|
1391
1395
|
{
|
|
1392
1396
|
"toolId": "events",
|
|
1393
1397
|
"title": "Events",
|
|
1394
|
-
"summary": "The cross-tool activity timeline: one chronological ring buffer (max 200, newest-first) that aggregates events from every other installed Buoy tool \u2014 network requests, redux/zustand/jotai state changes, react-query query/mutation updates, AsyncStorage/MMKV writes, route navigations, and component renders. Reach for it first for any \"what just happened in the app?\" question, before drilling into a single-tool reader. It exposes 3 actions: exportEvents (formatted read), setEnabledSources (choose what the device records), clearEvents (wipe the timeline). CRITICAL: it only records while something is watching \u2014 a cold exportEvents on a freshly connected session usually returns 0 events because nothing has ever armed capture, which is NOT the same as \"the app did nothing\". Swift captures network, storage-async, storage-mmkv, and route. React state and render sources are unavailable. Native export accepts format, includeEventData, includeSource, includeStatus, includeTitle, includeSubtitle, includeSummaryHeader, filterMode, filterSources, dataSizeThreshold, and timestampFormat; other settings are rejected. Native detail inherits source snapshot payload limits.",
|
|
1398
|
+
"summary": "For a request to record new events, call setEnabledSources before the app action. Then read exportEvents. A storage snapshot shows past writes; it does not start event capture. The cross-tool activity timeline: one chronological ring buffer (max 200, newest-first) that aggregates events from every other installed Buoy tool \u2014 network requests, redux/zustand/jotai state changes, react-query query/mutation updates, AsyncStorage/MMKV writes, route navigations, and component renders. Reach for it first for any \"what just happened in the app?\" question, before drilling into a single-tool reader. It exposes 3 actions: exportEvents (formatted read), setEnabledSources (choose what the device records), clearEvents (wipe the timeline). CRITICAL: it only records while something is watching \u2014 a cold exportEvents on a freshly connected session usually returns 0 events because nothing has ever armed capture, which is NOT the same as \"the app did nothing\". Swift captures network, storage-async, storage-mmkv, and route. React state and render sources are unavailable. Native export accepts format, includeEventData, includeSource, includeStatus, includeTitle, includeSubtitle, includeSummaryHeader, filterMode, filterSources, dataSizeThreshold, and timestampFormat; other settings are rejected. Native detail inherits source snapshot payload limits.",
|
|
1395
1399
|
"actions": [
|
|
1396
1400
|
{
|
|
1397
1401
|
"action": "exportEvents",
|
|
@@ -2273,7 +2277,7 @@
|
|
|
2273
2277
|
{
|
|
2274
2278
|
"toolId": "time-machine",
|
|
2275
2279
|
"title": "Time Machine",
|
|
2276
|
-
"summary": "Save and restore the app's entire client-side state (device storage, redux, zustand, jotai, react-query) as named snapshots (\"restore points\"), plus the route it was captured on. Reach for it to put the app back into a known state before re-running a flow, to preview exactly what a restore would change before committing, or to wipe the app to fresh-install state. Snapshot payloads stay on-device \u2014 `list` returns metadata only; use `inspect` for one source's actual captured data and `preview` for item-level diffs. Swift supports live restore of registered providers, with UserDefaults and MMKV supplied by default. Keychain
|
|
2280
|
+
"summary": "Save and restore the app's entire client-side state (device storage, redux, zustand, jotai, react-query) as named snapshots (\"restore points\"), plus the route it was captured on. Reach for it to put the app back into a known state before re-running a flow, to preview exactly what a restore would change before committing, or to wipe the app to fresh-install state. Snapshot payloads stay on-device \u2014 `list` returns metadata only; use `inspect` for one source's actual captured data and `preview` for item-level diffs. Swift supports live restore of registered providers, with UserDefaults and MMKV supplied by default. RN saves SecureStore keys you register. It can put them back. Swift does this for Keychain keys you register. Both skip keys that need a face or fingerprint check. They also skip Buoy keys. Read provider detail and restoreModes. Swift has captureBaseline and wipeAll. It also accepts mode reload. Reload runs if the app has a reload hook. Read willReload to see if one was queued. A restore from the bar saves a safety copy. This does not reset the whole app process.",
|
|
2277
2281
|
"actions": [
|
|
2278
2282
|
{
|
|
2279
2283
|
"action": "list",
|
|
@@ -2285,7 +2289,7 @@
|
|
|
2285
2289
|
},
|
|
2286
2290
|
"effect": "read",
|
|
2287
2291
|
"release": "works",
|
|
2288
|
-
"description": "Same payload as the tool's synced snapshot. Returns { snapshots, busy, lastOutcome, providers, route }. `snapshots[]` = { id (e.g. \"snap_m1x2y3_4\"), name, createdAt, sizeBytes, baseline?, route?:{pathname,href}, restoreRoute?, scope?, excludedKeys?, sources:{ [sourceId]: { warnings:string[] } } } \u2014 METADATA ONLY, no captured values. `providers[]` = { id, label, canCapture, canRestore, detail } for the registered sources: \"storage\", \"redux\", \"zustand\", \"jotai\", \"query\" (plus any custom ones the app registered). Read `detail` before reporting a source as broken \u2014 e.g. redux says \"Auto-instrumented store cannot be restored\" when the app didn't wrap its root reducer. `route.available` is false on apps without expo-router (those snapshots record no route). `lastOutcome` is the previous restore's per-source result. Call this first \u2014 every other action needs an `id` from here. Swift supports live restore of registered providers, with UserDefaults and MMKV supplied by default. Keychain
|
|
2292
|
+
"description": "Same payload as the tool's synced snapshot. Returns { snapshots, busy, lastOutcome, providers, route }. `snapshots[]` = { id (e.g. \"snap_m1x2y3_4\"), name, createdAt, sizeBytes, baseline?, route?:{pathname,href}, restoreRoute?, scope?, excludedKeys?, sources:{ [sourceId]: { warnings:string[] } } } \u2014 METADATA ONLY, no captured values. `providers[]` = { id, label, canCapture, canRestore, detail } for the registered sources: \"storage\", \"redux\", \"zustand\", \"jotai\", \"query\" (plus any custom ones the app registered). Read `detail` before reporting a source as broken \u2014 e.g. redux says \"Auto-instrumented store cannot be restored\" when the app didn't wrap its root reducer. `route.available` is false on apps without expo-router (those snapshots record no route). `lastOutcome` is the previous restore's per-source result. Call this first \u2014 every other action needs an `id` from here. Swift supports live restore of registered providers, with UserDefaults and MMKV supplied by default. RN saves SecureStore keys you register. It can put them back. Swift does this for Keychain keys you register. Both skip keys that need a face or fingerprint check. They also skip Buoy keys. Read provider detail and restoreModes. Swift has captureBaseline and wipeAll. It also accepts mode reload. Reload runs if the app has a reload hook. Read willReload to see if one was queued. A restore from the bar saves a safety copy. This does not reset the whole app process.",
|
|
2289
2293
|
"requires": [
|
|
2290
2294
|
"@buoy-gg/time-machine registered in FloatingDevTools"
|
|
2291
2295
|
]
|
|
@@ -2385,7 +2389,7 @@
|
|
|
2385
2389
|
},
|
|
2386
2390
|
"effect": "destructive",
|
|
2387
2391
|
"release": "works",
|
|
2388
|
-
"description": "Requires `id` (throws \"restore requires a snapshot `id`\" without it). mode \"live\" (default) replaces state in place source by source in a fixed order (storage \u2192 redux \u2192 zustand \u2192 jotai \u2192 query); mode \"reload\" restores ONLY persisted storage and then reloads the JS bundle so in-memory stores rebuild themselves. A baseline snapshot ALWAYS takes the clear+reload path regardless of mode. Storage restore is a diff \u2014 app keys missing from the snapshot are DELETED. Returns a RestoreOutcome: read `results[sourceId].applied` / `.skipped[].reason` / `.warnings` rather than assuming success (a source with canRestore:false comes back skipped with a reason, not an error), and read `willReload` and `route.status` (\"navigated\" | \"deferred\" | \"failed\" | \"unavailable\"). TWO GOTCHAS: (1) omitting `excludeKeys` makes the snapshot's own SAVED excludedKeys apply, and a saved `scope` narrows the restore to only the scoped items \u2014 passing an explicit `excludeKeys` array disables that saved scope. (2) omitting `restoreRoute` does NOT mean false: it falls back to the snapshot's own setting, which is ON whenever the snapshot captured a route. Pass restoreRoute:false to keep the app on the current screen. Swift supports live restore of registered providers, with UserDefaults and MMKV supplied by default. Keychain
|
|
2392
|
+
"description": "Requires `id` (throws \"restore requires a snapshot `id`\" without it). mode \"live\" (default) replaces state in place source by source in a fixed order (storage \u2192 redux \u2192 zustand \u2192 jotai \u2192 query); mode \"reload\" restores ONLY persisted storage and then reloads the JS bundle so in-memory stores rebuild themselves. A baseline snapshot ALWAYS takes the clear+reload path regardless of mode. Storage restore is a diff \u2014 app keys missing from the snapshot are DELETED. Returns a RestoreOutcome: read `results[sourceId].applied` / `.skipped[].reason` / `.warnings` rather than assuming success (a source with canRestore:false comes back skipped with a reason, not an error), and read `willReload` and `route.status` (\"navigated\" | \"deferred\" | \"failed\" | \"unavailable\"). TWO GOTCHAS: (1) omitting `excludeKeys` makes the snapshot's own SAVED excludedKeys apply, and a saved `scope` narrows the restore to only the scoped items \u2014 passing an explicit `excludeKeys` array disables that saved scope. (2) omitting `restoreRoute` does NOT mean false: it falls back to the snapshot's own setting, which is ON whenever the snapshot captured a route. Pass restoreRoute:false to keep the app on the current screen. Swift supports live restore of registered providers, with UserDefaults and MMKV supplied by default. RN saves SecureStore keys you register. It can put them back. Swift does this for Keychain keys you register. Both skip keys that need a face or fingerprint check. They also skip Buoy keys. Read provider detail and restoreModes. Swift has captureBaseline and wipeAll. It also accepts mode reload. Reload runs if the app has a reload hook. Read willReload to see if one was queued. A restore from the bar saves a safety copy. This does not reset the whole app process.",
|
|
2389
2393
|
"requires": [
|
|
2390
2394
|
"a source's provider must report canRestore:true or that source is skipped with a reason",
|
|
2391
2395
|
"expo-router for the route leg",
|
|
@@ -3094,7 +3098,7 @@
|
|
|
3094
3098
|
},
|
|
3095
3099
|
{
|
|
3096
3100
|
"action": "runRecipe",
|
|
3097
|
-
"summary": "Run the
|
|
3101
|
+
"summary": "Run the fixed recipe named by `id`: phone-call (20s), quick-switch (5s), away-31m, overnight, low-memory, dying-battery or relaunch. If the user gives a call length, use interrupt with duration.",
|
|
3098
3102
|
"description": "Each recipe is a short sequence of the actions above; getState lists them with `unavailable` when a dependency is missing (away-31m and overnight need @buoy-gg/clock, dying-battery needs a battery library). Returns the new state.",
|
|
3099
3103
|
"effect": "write",
|
|
3100
3104
|
"release": "works",
|
|
@@ -3709,7 +3713,7 @@
|
|
|
3709
3713
|
{
|
|
3710
3714
|
"toolId": "storage",
|
|
3711
3715
|
"title": "Storage",
|
|
3712
|
-
"summary": "Read and write the app's persisted state across all three backends \u2014 AsyncStorage, every registered MMKV instance, and registered Expo SecureStore keys \u2014 plus a recorded timeline of storage writes with per-event undo/jump. Reach for this first when a value is wrong, stale, missing, or only broken after a restart/upgrade: the bad value is usually sitting in storage. Buoy's own devtool keys (@react_buoy*, @buoy*, buoy-*) are stripped from every read path, so results are app data only. Nothing here is __DEV__-gated \u2014 every action really runs in a release build. When a saved value looks wrong, compare it with getRequiredKeys: a key written by an older app version shows up there with the wrong type (a bare \"1856\" where the app expects an object). The storage write timeline is this tool's getSnapshot (newest events, each with its key, value and the value it replaced) \u2014 read it for \"what changed in storage?\" and to find the event to undo. Do not use the Events tool for that: it records a source only after setEnabledSources, so earlier writes are not there.",
|
|
3716
|
+
"summary": "Read and write the app's persisted state across all three backends \u2014 AsyncStorage, every registered MMKV instance, and registered Expo SecureStore keys \u2014 plus a recorded timeline of storage writes with per-event undo/jump. Reach for this first when a value is wrong, stale, missing, or only broken after a restart/upgrade: the bad value is usually sitting in storage. Buoy's own devtool keys (@react_buoy*, @buoy*, buoy-*) are stripped from every read path, so results are app data only. Nothing here is __DEV__-gated \u2014 every action really runs in a release build. When a saved value looks wrong, compare it with getRequiredKeys: a key written by an older app version shows up there with the wrong type (a bare \"1856\" where the app expects an object). The storage write timeline is this tool's getSnapshot (newest events, each with its key, value and the value it replaced) \u2014 read it for \"what changed in storage?\" and to find the event to undo. Do not use the Events tool for that: it records a source only after setEnabledSources, so earlier writes are not there. When asked to record a new write, call events.setEnabledSources first. Then write once and read events.exportEvents. A storage snapshot does not start Events capture.",
|
|
3713
3717
|
"actions": [
|
|
3714
3718
|
{
|
|
3715
3719
|
"action": "getSnapshot",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";function
|
|
1
|
+
"use strict";function y(n){if(n===null)return"null";if(Array.isArray(n))return"array";return typeof n}function d(n,t){if(Array.isArray(t))return t.some(e=>d(n,e));switch(t){case"integer":return typeof n==="number"&&Number.isInteger(n);case"number":return typeof n==="number"&&Number.isFinite(n);case"null":return n===null;case"array":return Array.isArray(n);case"object":return y(n)==="object";default:return typeof n===t}}function s(n,t,e,r){if(t.anyOf?.length){const f=t.anyOf.some(i=>{const o=[];s(n,i,e,o);return o.length===0});if(!f){const i=t.anyOf.map(o=>o.type??"?").join(" | ");r.push(`${e}: expected ${i}, got ${y(n)}`)}return}if(t.type&&!d(n,t.type)){r.push(`${e}: expected ${t.type}, got ${y(n)}`);return}if(t.enum&&!t.enum.includes(n)){r.push(`${e}: expected one of ${t.enum.map(f=>JSON.stringify(f)).join(", ")}, got ${JSON.stringify(n)}`);return}const u=Array.isArray(t.type)?t.type:[t.type];if(u.includes("array")&&Array.isArray(n)){if(t.minItems!==void 0&&n.length<t.minItems){r.push(`${e}: expected at least ${t.minItems} item(s), got ${n.length}`)}if(t.maxItems!==void 0&&n.length>t.maxItems){r.push(`${e}: expected at most ${t.maxItems} item(s), got ${n.length}`)}if(t.items){n.forEach((f,i)=>s(f,t.items,`${e}[${i}]`,r))}return}if(u.includes("object")&&y(n)==="object"){const f=n;for(const i of t.required??[]){if(f[i]===void 0)r.push(`${e}.${i}: required`)}if(t.properties){for(const[i,o]of Object.entries(t.properties)){if(f[i]!==void 0)s(f[i],o,`${e}.${i}`,r)}if(t.additionalProperties===false){const i=new Set(Object.keys(t.properties));for(const o of Object.keys(f)){if(!i.has(o))r.push(`${e}.${o}: unexpected property`)}}}}}export function validateParams(n,t){const e=[];const r=t.type&&d(null,t.type);const u=n===void 0||n===null&&!r?{}:n;s(u,t,"params",e);return{ok:e.length===0,errors:e}}export function applyDefaults(n,t){const e=y(n)==="object"?{...n}:{};for(const[r,u]of Object.entries(t.properties??{})){if(e[r]===void 0&&u.default!==void 0)e[r]=u.default}return e}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
"use strict";import{CATALOG as
|
|
1
|
+
"use strict";import{CATALOG as St}from"../catalog/catalog.g";import{applyDefaults as Ee,validateParams as Ae}from"../catalog/validateParams";import{normalizeParams as me,aliasNote as Kt}from"../catalog/normalizeParams";import{fromProviderToolName as ae,toProviderTools as Qt}from"../catalog/toProviderTools";import{hashQueryKey as Xt}from"../catalog/normalizeParams";import{projectSnapshot as Zt,SNAPSHOT_ACTION as Tt}from"../catalog/snapshotReads";import{UNPARSEABLE_ARGS as eo,isRealUserMessage as It}from"../providers/types";import{isReversible as Et}from"../effects/ledger";import{classifyTurn as to,QUESTION_DECLINED as At,tapLabels as oo}from"../policy/turnScope";import{describeCall as We,decide as z}from"../policy/policy";import{redact as no,stripSelfTraffic as ro}from"../policy/redact";import{idGrounding as so,UNSEEN_ID_ADVICE as io}from"./idGrounding";import{effectFor as $t}from"./effectFor";import{digestOf as Ge}from"../effects/digest";import{buildUiBlock as ao,UI_TOOL_NAME as ye,uiProviderTool as lo}from"../blocks/uiTool";import{projectReceipt as co}from"../blocks/receipts";import{isAskBlock as uo}from"../blocks/types";import{ACQUISITION_CALLS as fo,synthesizeAskBlock as po,synthesizeShortfallBlock as ho}from"./askGate";import{couldBeToolCallEnvelope as Nt,parseTextToolCalls as mo,SALVAGE_NOTE as yo}from"./textToolCalls";import{announcesUnstartedWork as go,PLAN_ONLY_NUDGE as bo,SILENT_NUDGE as ko}from"./planOnlyStop";import{compactScreen as wo}from"./compactScreen";import{budgetForRequest as Ye,MAX_HISTORY_TOKENS as vo,MAX_REQUEST_TOKENS as Ro,messageSize as $e}from"./historyBudget";import{promptTokensOf as So,TokenCalibration as To}from"./tokenCalibration";import{truncationMarker as Io}from"./evidence";import{retrieveEvidence as Eo}from"./retrieve";import{VERIFICATION_REPAIR as Ao,verificationTrailer as $o,verifyOutcome as No}from"./verify";import{realClearTimeout as Co,realNow as N,realSetTimeout as _o}from"../realNow";const Ct=24e3;const _t=2e3;const Ot=3;function Oo(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,w)=>(d[w]=n(a[w]),d),{})};return t.map(o=>`${o.name}:${JSON.stringify(n(o.input??{}))}`).join("|")}const xt="[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 xo=24;const Ne="Resume where you left off. Don't redo past changes. Read the past tool results first.";const Uo="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 Ut=18e4;const Po=2;const Do=1;const Lo=1e3;const Mo=250;const qo=3e4;function jo(t,n){return new Promise(o=>{if(n?.aborted)return o();const a=_o(d,t);function d(){Co(a);n?.removeEventListener("abort",d);o()}n?.addEventListener("abort",d,{once:true})})}function Pt(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 Dt(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 Bo(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 j(t,n,o){return t.find(a=>a.toolId===n)?.actions.find(a=>a.action===o)}const Lt="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 Fo=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 zo(t){try{return JSON.stringify(t??null)}catch{return String(t)}}function Ho(t,n){if(t.length<=Ct)return t;return`${t.slice(0,Ct)}${Io(t.length,n)}`}function Jo(t){if(t===null||t===void 0)return"Done";if(Array.isArray(t))return Ve(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&&typeof n.inactiveReason==="string"&&n.inactiveReason.length>0){return"Saved, but inactive in this build"}for(const a of["returned","count","total"]){const d=n[a];if(typeof d==="number")return Ve(d)}const o=Object.values(n).filter(Array.isArray);if(o.length===1)return Ve(o[0].length);return"Done"}return String(t).slice(0,80)}function Ve(t){return t===1?"1 item":`${t} items`}function Mt(t){return typeof t==="object"&&t!==null&&t.ok===false}const Ke="tapElement needs nativeTag, testID or query. Read describeScreen and pass one.";function Ce(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 qt(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."}}export async function*runAgentTurn(t){const{provider:n,catalog:o,system:a,systemVolatile:d,model:w,maxTokens:y,dispatch:c,readSnapshot:g,storeKeyOwners:D,ledger:k,policy:L,isRelease:M,requestApproval:V,signal:C,evidence:K,trusted:$,procedures:H}=t;const Q=new Map;const x=t.calibration??new To;const de=[...t.messages].reverse().find(p=>It(p));const B=to(de?.role==="user"?de.text:"");const f=[...t.messages];const be=n.protocol==="anthropic"?t.feedOptions??{}:{};const J=be.freezeHistory===true;const U=be.notices==="system-msg";const le=(p,E=false)=>({role:"user",text:p,...n.protocol==="anthropic"?{source:"engine"}:{},...E?{systemNotice:true}:{}});const Xe=()=>{const p=f[f.length-1];return U&&(p?.role==="tool-results"||p?.role==="user"&&p.systemNotice===true)};const Ze=so(f,`${t.system}
|
|
2
2
|
${t.systemVolatile??""}${de?.role==="user"&&de.liveBlock?`
|
|
3
3
|
${de.liveBlock.text}`:""}
|
|
4
|
-
${JSON.stringify(H??[])}`);let X=Qt(o,{availableToolIds:t.availableToolIds,availableActions:t.availableActions,isRelease:M});X.push(lo());if(J)X=JSON.parse(JSON.stringify(X));const Z=L.maxSteps??xo;const et=Vo();const Bt=k.generation;const Ft=new Set(k.list().map(p=>p.id));const tt=a.length+(d?.length??0)+X.reduce((p,E)=>p+E.description.length+JSON.stringify(E.inputSchema).length,0);const ke=()=>tt+x.chars(y);let we=N()+Ut;const _e={throttled:0,overflow:0};let ee=vo;const Oe=t.seenUrls??new Set;const zt=/https?:\/\/[^\s"'\\)\]}>]+/g;let xe=false;const te=[];let ot=false;const Ue=[];let Pe=false;let nt=false;let ve=false;let rt=false;let st=false;const Ht=[...f].reverse().find(It);const Jt=/\?\s*$/.test(Ht?.text?.trim()??"");const it=p=>p.reduce((E,_)=>E+$e(_),0)<=Math.min(x.chars(ee),x.chars(
|
|
5
|
-
${i.errors.join("\n")}`+q("\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 T=0;if(i.block.kind==="imageGrid"){const A=i.block.images.filter(I=>Oe.has(I.url));T=i.block.images.length-A.length;if(A.length===0){v.push({toolCallId:e.id,content:U?"Rejected: image URLs were not read from a tool result."+q(Lt):Lt,isError:true});continue}i.block={...i.block,images:A}}if(i.block.kind==="list"){const A=i.block.items.map(I=>{if(!I.image||Oe.has(I.image))return I;T+=1;return{...I,image:void 0}});i.block={...i.block,items:A}}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){Pe=true}if(uo(i.block)){je=i.block.id;v.push({toolCallId:e.id,content:"Shown. Waiting for the user's answer \u2014 it will arrive as their next message."+q(" Do not guess it.")})}else{v.push({toolCallId:e.id,content:"Shown to the user."+q(" Don't repeat its contents in text.")+(T>0?Fo(T):"")})}continue}const
|
|
4
|
+
${JSON.stringify(H??[])}`);let X=Qt(o,{availableToolIds:t.availableToolIds,availableActions:t.availableActions,isRelease:M});X.push(lo());if(J)X=JSON.parse(JSON.stringify(X));const Z=L.maxSteps??xo;const et=Vo();const Bt=k.generation;const Ft=new Set(k.list().map(p=>p.id));const tt=a.length+(d?.length??0)+X.reduce((p,E)=>p+E.description.length+JSON.stringify(E.inputSchema).length,0);const ke=()=>tt+x.chars(y);let we=N()+Ut;const _e={throttled:0,overflow:0};let ee=vo;const Oe=t.seenUrls??new Set;const zt=/https?:\/\/[^\s"'\\)\]}>]+/g;let xe=false;const te=[];let ot=false;const Ue=[];let Pe=false;let nt=false;let ve=false;let rt=false;let st=false;const Ht=[...f].reverse().find(It);const Jt=/\?\s*$/.test(Ht?.text?.trim()??"");const it=p=>p.reduce((E,_)=>E+$e(_),0)<=Math.min(x.chars(ee),x.chars(Ro)-ke());const De="This turn has no room left. Tap Continue to go on.";for(let p=0;p<Z;p++){if(C?.aborted){yield{type:"done",stopReason:"stopped"};return f}if(N()>we){yield{type:"block",block:{id:`cap${N()}`,kind:"notice",tone:"warning",text:`This is taking too long \u2014 stopped after ${Math.round(Ut/1e3)}s. What it found so far is above.`,actions:[{label:"Continue",primary:true,send:Ne}]}};yield{type:"done",stopReason:"time-cap"};return f}const E=J&&p>0?{messages:f,droppedRounds:0,droppedPinned:0}:Ye(f,ke(),x.chars(ee),x.charsPerToken,k.liveCallIds());if(E.droppedRounds>0){f.length=0;f.push(...E.messages);yield{type:"history-trimmed",droppedRounds:E.droppedRounds,droppedPinned:E.droppedPinned}}else if(E.messages!==f){f.length=0;f.push(...E.messages)}if(Z>6&&p===Z-6){f.push(le("6 steps left. Finish what the user asked. Skip extra checks. Batch reads that do not depend on each other in one round.",Xe()))}if(J&&!it(f)){yield{type:"block",block:{id:`space${N()}`,kind:"notice",tone:"warning",text:De,actions:[{label:"Continue",primary:true,send:Ne}]}};yield{type:"done",stopReason:"incomplete"};return f}let _="";let ct=false;const ne=e=>{const l=xe&&!ct;ct=true;xe=true;return l?{type:"text",delta:e,breakBefore:true}:{type:"text",delta:e}};let S=[];const ut=new Set;let P="";let Me=true;let ue=[];let Re=false;let W;let G;let qe=0;for(;;){qe+=1;_="";S=[];P="";Me=true;ue=[];Re=false;W=void 0;G=void 0;let e;const l=tt+f.reduce((u,m)=>u+$e(m),0);for await(const u of n.send({messages:f,system:a,systemVolatile:d,tools:X,model:w,maxTokens:y,signal:C,meta:{askId:et,round:p+1,attempt:qe}})){if(u.type==="text"){_+=u.delta;if(!Me){yield ne(u.delta)}else if(Nt(_)){P+=u.delta}else{Me=false;P="";yield ne(_)}}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"){ue.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&&ue.length===0){e={problem:u.problem,message:u.message}}else{yield{type:"error",message:u.message,...u.problem?.hosted?{hosted:u.problem.hosted}:{}};Re=true}}else if(u.type==="done"){W=u.outcome;if(u.usage){x.observe(l,So(u.usage,n.protocol));yield{type:"usage",...u.usage,model:u.model}}}}if(!e)break;const r=e.problem.kind;if(J&&r==="overflow"){G={message:De};break}const s=1+(r==="throttled"?Po:Do);const b=_e[r];let h=r==="throttled"?Math.min(e.problem.retryAfterMs??Lo*2**b,qo)+Math.floor(Math.random()*Mo):0;let O=b>=s-1||C?.aborted===true||N()+h>we;if(e.problem.hosted&&qe>=2)O=true;if(!O&&r==="overflow"){ee=Math.floor(ee/2);const u=f.reduce((fe,Y)=>fe+$e(Y),0);const m=Ye(f,ke(),x.chars(ee),x.charsPerToken,k.liveCallIds());const re=m.messages.reduce((fe,Y)=>fe+$e(Y),0);if(re>=u){O=true}else{f.length=0;f.push(...m.messages);if(m.droppedRounds>0)yield{type:"history-trimmed",droppedRounds:m.droppedRounds,droppedPinned:m.droppedPinned}}}if(O){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 m=e.problem.hosted;yield m?{type:"error",message:m.message,hosted:m}:{type:"error",message:`${u} (${e.message})`};Re=true;break}_e[r]+=1;yield{type:"retrying",reason:r,attempt:_e[r]+1,maxAttempts:s,inMs:h};if(h>0)await jo(h,C);if(C?.aborted){yield{type:"done",stopReason:"stopped"};return f}}if(W==="refused"||W==="context-limited"){yield{type:"error",message:W==="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(Re){if(P)yield ne(P);yield{type:"done",stopReason:"error"};return f}if(!G&&W!=="completed"){G={message:W==="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(P)yield ne(P);if(_.trim())f.push({role:"assistant",text:_});yield{type:"block",block:{id:`cut${N()}`,kind:"notice",tone:"warning",text:G.message,actions:[{label:"Continue",primary:true,send:Ne}]}};yield{type:"done",stopReason:"incomplete"};return f}if(P){const e=S.length===0?mo(P,o):void 0;if(e){for(const l of e.calls){S.push(l);ut.add(l.id)}_=e.reply;if(e.reply)yield ne(e.reply)}else{yield ne(P)}P=""}f.push({role:"assistant",text:_,toolCalls:S.length?S:void 0,thinking:ue.length?ue:void 0});if(_.trim())Ue.push(_.trim());if(S.length===0&&!ve&&!Pe&&p<Z-1&&(go(_,B==="task")||rt&&!st&&!Jt)){ve=true;f.push(le(bo));continue}if(S.length===0&&!ve&&Ue.length===0&&p<Z-1){ve=true;f.push(le(ko));continue}if(S.length===0){const e=Ue.join("\n\n");const l=ho({text:e,attempted:nt});if(l)yield{type:"block",block:l};const r=Pe||l?null:po(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 v=[];const Se=[];const q=e=>{if(!U)return e;Se.push(e.trim());return""};let ft=false;const pt=new Map;if(S.length>1){const e=S.every(l=>{if(l.name===ye)return false;const r=ae(l.name,o);if(!r||r==="ask-buoy")return false;const s=l.input?.action;if(typeof s!=="string"||s===Tt)return false;const b=j(o,r,s);if(!b||b.effect!=="read")return false;return z({descriptor:b,toolId:r,policy:L,isRelease:M}).verdict==="allow"});if(e){for(const l of S){const r=ae(l.name,o);const s=String(l.input.action);const b={...l.input.params??{}};const h=j(o,r,s);const O=me(r,s,b);const u=Ee(O.params,h.params);if(!Ae(u,h.params).ok)continue;const m=Promise.resolve(c(r,s,u)).catch(re=>{throw re});m.catch(()=>{});pt.set(l.id,m)}}}let je=null;const Gt=e=>{const l=ae(e.name,o)??e.name;const r=typeof e.input?.action==="string"?e.input.action:"";const s=r?j(o,l,r):void 0;const b=e.input?.params??{};return[{type:"tool-start",id:e.id,toolId:l,action:r,label:s?We(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 Te=new Map;if(B==="question"){for(const e of S){if(ae(e.name,o)!=="highlight-updates"||e.input?.action!=="tapElement")continue;const l=me("highlight-updates","tapElement",e.input.params??{}).params;if(Ce("highlight-updates","tapElement",l))continue;const r=j(o,"highlight-updates","describeScreen");const s=j(o,"highlight-updates","tapElement");if(C?.aborted||!r||!s||z({descriptor:r,toolId:"highlight-updates",policy:L,isRelease:M}).verdict!=="allow"||z({descriptor:s,toolId:"highlight-updates",policy:L,isRelease:M,turnScope:B,params:l}).verdict==="refuse")continue;const b=await c("highlight-updates","describeScreen",{}).catch(()=>void 0);Te.set(e.id,oo(b,l))}}const ht=S.map(e=>{if(e.name===ye)return void 0;const l=ae(e.name,o);const r=typeof e.input?.action==="string"?e.input.action:void 0;if(!l||!r)return void 0;const s=j(o,l,r);if(!s)return void 0;const b=e.input.params??{};const h=Ee(me(l,r,b).params,s.params);if(Ce(l,r,h)||!Ae(h,s.params).ok)return void 0;const O=z({descriptor:s,toolId:l,policy:L,isRelease:M,turnScope:B,params:h,tapLabels:Te.get(e.id)});return{call:e,toolId:l,action:r,descriptor:s,params:h,label:We(l,s,h),mutates:s.effect!=="read",gated:O.verdict==="needs-approval",turnScoped:O.verdict==="needs-approval"&&O.turnScoped,reason:O.verdict==="needs-approval"?O.reason:""}});const Yt=ht.some(e=>e?.gated);const F=new Map;let mt=false;let yt=false;async function*Vt(){mt=true;for(const e of ht){if(!e?.gated||F.has(e.call.id))continue;if(!e.turnScoped&&$?.has(`${e.toolId}.${e.action}`)){F.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=N();const r=await readTargetDigest({toolId:e.toolId,action:e.action,params:e.params,dispatch:c,catalog:o});const s=Pt(!e.turnScoped&&$?.has(`${e.toolId}.${e.action}`)?true:V?await V({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);we+=N()-l;const b=s.approved;F.set(e.call.id,b);if(s.trust)$?.add(`${e.toolId}.${e.action}`);if(s.reason)Q.set(e.call.id,s.reason);if(!b){yt=true;return}}}for(const e of S){if(C?.aborted){if(e.name!==ye){for(const i of Gt(e))yield i}v.push({toolCallId:e.id,content:"Not run \u2014 the user pressed Stop before this call started.",isError:true});continue}const l=e.input?.[eo];if(typeof l==="string"){v.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===ye){const i=ao(e.input);if(!i.ok||!i.block){v.push({toolCallId:e.id,content:`Invalid ${ye} block:
|
|
5
|
+
${i.errors.join("\n")}`+q("\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 T=0;if(i.block.kind==="imageGrid"){const A=i.block.images.filter(I=>Oe.has(I.url));T=i.block.images.length-A.length;if(A.length===0){v.push({toolCallId:e.id,content:U?"Rejected: image URLs were not read from a tool result."+q(Lt):Lt,isError:true});continue}i.block={...i.block,images:A}}if(i.block.kind==="list"){const A=i.block.items.map(I=>{if(!I.image||Oe.has(I.image))return I;T+=1;return{...I,image:void 0}});i.block={...i.block,items:A}}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){Pe=true}if(uo(i.block)){je=i.block.id;v.push({toolCallId:e.id,content:"Shown. Waiting for the user's answer \u2014 it will arrive as their next message."+q(" Do not guess it.")})}else{v.push({toolCallId:e.id,content:"Shown to the user."+q(" Don't repeat its contents in text.")+(T>0?Fo(T):"")})}continue}const r=ae(e.name,o);const s=e.input.action;const b=(i,T)=>[{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:T,durationMs:0}];if(!r){for(const i of b(e.name,"No such tool"))yield i;v.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;v.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=j(o,r,s);if(!h){const i=o.find(R=>R.toolId===r)?.actions.map(R=>R.action)??[];const T=o.filter(R=>R.toolId!==r&&R.actions.some(ze=>ze.action===s));const A=i.filter(R=>Bo(R,s));const I=[...T.map(R=>`${R.toolId}.${s}`),...A.map(R=>`${r}.${R}`)].slice(0,3);const ie=`${r} has no ${s}.${I.length?` Did you mean ${I.join(" or ")}?`:""}`;for(const R of b(`${r}.${s}`,I.length?ie:"No such action"))yield R;v.push({toolCallId:e.id,content:`${ie}${i.length?` Valid actions: ${i.join(", ")}.`:""}`,isError:true});continue}const O=e.input.params??{};const u=me(r,s,O);const m=Ee(u.params,h.params);if(Ce(r,s,m)){for(const i of b(`${r}.${s}`,Ke))yield i;v.push({toolCallId:e.id,content:JSON.stringify({ok:false,error:U?"tapElement needs nativeTag, testID or query."+q("Read describeScreen and pass nativeTag, testID or query."):Ke}),isError:true});continue}const re=Ae(m,h.params);if(!re.ok){v.push({toolCallId:e.id,content:`Invalid parameters for ${r}.${s}:
|
|
6
6
|
${re.errors.join("\n")}
|
|
7
7
|
|
|
8
8
|
Expected schema:
|
|
9
|
-
${JSON.stringify(h.params)}`,isError:true});continue}const fe=Kt(u.notes);const Y=h.effect!=="read"?Ze.trailer(m,!U):"";if(U&&Y)q(io);const Ie=We(
|
|
9
|
+
${JSON.stringify(h.params)}`,isError:true});continue}const fe=Kt(u.notes);const Y=h.effect!=="read"?Ze.trailer(m,!U):"";if(U&&Y)q(io);const Ie=We(r,h,m);const se=z({descriptor:h,toolId:r,policy:L,isRelease:M,turnScope:B,params:m,tapLabels:Te.get(e.id)});const pe=i=>[{type:"tool-start",id:e.id,toolId:r,action:s,label:Ie,description:h.summary,params:m,effect:h.effect},{type:"tool-end",id:e.id,ok:false,summary:i,durationMs:0}];if(se.verdict==="refuse"){for(const i of pe("refused"))yield i;v.push({toolCallId:e.id,content:se.reason,isError:true});continue}const Be=se.verdict==="needs-approval";if(Yt&&!mt&&(h.effect!=="read"||Be)){yield*Vt()}if(yt&&(h.effect!=="read"||Be)){for(const i of pe("declined"))yield i;v.push({toolCallId:e.id,content:B==="question"?At:F.get(e.id)===false?Dt(Q.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(Be){let i;if(F.has(e.id)){i=F.get(e.id)}else if(!se.turnScoped&&$?.has(`${r}.${s}`)){i=true;F.set(e.id,true)}else{yield{type:"approval-required",id:e.id,toolId:r,action:s,label:Ie,description:h.summary,reason:se.reason};const T=N();const A=await readTargetDigest({toolId:r,action:s,params:m,dispatch:c,catalog:o});const I=Pt(V?await V({id:e.id,toolId:r,action:s,label:Ie,description:h.summary,reason:se.reason,params:m,targetDigest:A}):false);we+=N()-T;i=I.approved;F.set(e.id,i);if(I.trust)$?.add(`${r}.${s}`);if(I.reason)Q.set(e.id,I.reason)}if(!i){for(const T of pe("declined"))yield T;v.push({toolCallId:e.id,content:B==="question"?At:Dt(Q.get(e.id)),isError:true});continue}}if(fo.has(`${r}.${s}`))nt=true;if(r==="ask-buoy"&&s==="openProcedure")rt=true;yield{type:"tool-start",id:e.id,toolId:r,action:s,label:Ie,description:h.summary,params:m,effect:h.effect};const gt=N();const bt=await Qe(h,r,m,c);const Fe=await ge(h,r,m,c);if(C?.aborted){for(const i of pe("stopped"))yield i;v.push({toolCallId:e.id,content:"Not run \u2014 the user pressed Stop before this call started.",isError:true});continue}const kt=z({descriptor:h,toolId:r,policy:L,isRelease:M,turnScope:B,params:m,tapLabels:Te.get(e.id)});if(kt.verdict==="refuse"){for(const i of pe("refused"))yield i;v.push({toolCallId:e.id,content:kt.reason,isError:true});continue}try{let i=s===Tt?Zt(r,await Go(g,r),m):r==="ask-buoy"?await jt(s,k,c,K,m,H):await(pt.get(e.id)??c(r,s,m));i=qt(r,s,i);const T=no(ro(i));const A=Mt(i);if(h.effect!=="read"&&!A)st=true;const I=zo(r==="highlight-updates"&&s==="describeScreen"&&!A?wo(T):T);const ie=K&&!A&&!(r==="ask-buoy"&&s==="retrieve")?K.stash({toolId:r,action:s,params:m,capturedAt:N(),text:I}):void 0;const R=Ho(I,ie);Ze.add(I);const ze=R.length>_t?`${R.slice(0,_t)}\u2026`:R;yield{type:"tool-end",id:e.id,ok:!A,summary:Jo(i),durationMs:N()-gt,result:ze};const He=Fe===void 0||A?void 0:await ge(h,r,m,c);if(h.effect!=="read"&&r!=="ask-buoy"&&!A){const Je=k.noteExternalRevert(r,s,m);const vt=$t(r,h,m,i,bt,{before:Fe,after:He});if(vt&&!Je){const Rt=k.record(r,s,vt,Bt);if(Rt)Rt.callId=e.id}}const wt=A?void 0:co({toolId:r,action:s,params:m,result:T,before:Fe??bt,after:He,effect:h.effect});if(wt)yield{type:"block",block:wt,forToolCallId:e.id};const he=h.effect!=="read"&&!A?await No({toolId:r,action:s,params:m,result:i,dispatch:c,readSnapshot:g,signal:C,after:He}):void 0;if(he)yield{type:"tool-verified",id:e.id,verification:he};if(U&&he?.status==="failed")q(Ao);for(const Je of R.match(zt)??[])Oe.add(Je);v.push({toolCallId:e.id,content:R+Wo(r,h,m,D,U?q:void 0)+fe+Y+(he?$o(he,!U):"")+(ut.has(e.id)?q(yo):""),...ie?{ref:ie}:{}});if(r==="app"&&(s==="reloadApp"||s==="reload")){ft=true}}catch(i){const T=i instanceof Error?i.message:String(i);yield{type:"tool-end",id:e.id,ok:false,summary:T,durationMs:N()-gt};v.push({toolCallId:e.id,content:`Failed: ${T}${Y}`,isError:true})}}if(S.length){te.push(Oo(S));if(te.length>Ot)te.shift();const e=!ot&&te.length===Ot&&te.every(l=>l===te[0]);if(e){ot=true;const l=v[v.length-1];if(U)Se.push(xt);else if(l)l.content=`${l.content}
|
|
10
10
|
|
|
11
|
-
${xt}`}}f.push({role:"tool-results",results:v});if(
|
|
11
|
+
${xt}`}}f.push({role:"tool-results",results:v});if(Se.length)f.push(le([...new Set(Se)].join("\n\n"),true));if(je){yield{type:"awaiting-user",blockId:je};yield{type:"done",stopReason:"awaiting-user"};return f}if(ft){yield{type:"done",stopReason:"realm-died"};return f}}if(C?.aborted){yield{type:"done",stopReason:"stopped"};return f}const oe=[];let at=false;let Le=false;const ce=[...f,le(Uo,Xe())];const Wt=J?{messages:ce}:Ye(ce,ke(),x.chars(ee),x.charsPerToken,k.liveCallIds());try{if(J&&!it(ce))throw new Error(De);if(J||U||be.liveBlock==="append"||be.liveBlock==="system-msg")f.push(ce[ce.length-1]);for await(const p of n.send({messages:Wt.messages,system:a,systemVolatile:d,tools:X,toolChoice:"none",model:w,maxTokens:y,signal:C,meta:{askId:et,round:Z+1,attempt:1}})){if(p.type==="text")oe.push(p.delta);else if(p.type==="tool-call"||p.type==="error")Le=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}at=p.outcome==="completed";if(p.usage)yield{type:"usage",...p.usage,model:p.model}}}}catch{Le=true}if(C?.aborted){yield{type:"done",stopReason:"stopped"};return f}const dt=oe.join("");if(Le||!at||!dt.trim()||Nt(dt)){const p=k.list().filter(E=>!Ft.has(E.id));oe.length=0;oe.push(["I ran out of steps. The job is not done.",...p.length?["These steps ran:",...p.map(E=>`- ${E.effect.label}${E.undoneAt?" (since undone)":""}`),"This list does not prove each change worked."]:[]].join("\n"))}let lt=true;for(const p of oe){if(!p)continue;yield{type:"text",delta:p,...lt&&xe?{breakBefore:true}:{}};lt=false}f.push({role:"assistant",text:oe.join("")});yield{type:"block",block:{id:`cap${N()}`,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:Ne}]}};yield{type:"done",stopReason:"step-cap"};return f}function Wo(t,n,o,a,d){if(t!=="storage"||n.effect==="read")return"";if(!a||typeof o.key!=="string")return"";const w=a[o.key];if(!w)return"";const y=`
|
|
12
12
|
|
|
13
|
-
[Buoy] This wrote to disk, but "${o.key}" is the saved copy of the live "${w}" 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 y}return y+` Call zustand.rehydrate({"storeName":"${w}"}) to make the app pick this up, or use zustand.setState next time to change the store directly. If you meant to set the value for the app's next launch, this is already done and no further action is needed.`}export{Ge as digestOf};export async function readTargetDigest(t){const
|
|
13
|
+
[Buoy] This wrote to disk, but "${o.key}" is the saved copy of the live "${w}" 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 y}return y+` Call zustand.rehydrate({"storeName":"${w}"}) to make the app pick this up, or use zustand.setState next time to change the store directly. If you meant to set the value for the app's next launch, this is already done and no further action is needed.`}export{Ge as digestOf};export async function readTargetDigest(t){const n=j(t.catalog??St,t.toolId,t.action);if(!n||n.effect==="read")return void 0;const o=await ge(n,t.toolId,t.params,t.dispatch);if(o!==void 0)return Ge(o);const a=await Qe(n,t.toolId,t.params,t.dispatch);if(a!==void 0)return Ge(a);return void 0}export async function runGatedAction(t){const{toolId:n,action:o,dispatch:a,ledger:d,policy:w,isRelease:y}=t;const c=t.catalog??St;const g=j(c,n,o);if(!g){return{ok:false,error:`${n}.${o} is not in Buoy's catalog.`}}const D=me(n,o,t.params??{});const k=Ee(D.params,g.params);if(Ce(n,o,k))return{ok:false,error:Ke};const L=Ae(k,g.params);if(!L.ok){return{ok:false,error:L.errors.join("\n")}}const M=z({descriptor:g,toolId:n,policy:w,isRelease:y});if(M.verdict==="refuse"){return{ok:false,error:M.reason}}const V=await Qe(g,n,k,a);const C=await ge(g,n,k,a);const K=z({descriptor:g,toolId:n,policy:w,isRelease:y});if(K.verdict==="refuse"){return{ok:false,error:K.reason}}try{let $=n==="ask-buoy"?await jt(o,d,a,void 0,k):await a(n,o,k);$=qt(n,o,$);if(Mt($)){const H=$.error;return{ok:false,error:typeof H==="string"?H:"The tool refused this."}}if(g.effect!=="read"&&n!=="ask-buoy"){const H=d.noteExternalRevert(n,o,k);const Q=await ge(g,n,k,a);const x=$t(n,g,k,$,V,{before:C,after:Q});if(x&&!H)d.record(n,o,x)}return{ok:true,result:$}}catch($){return{ok:false,error:$ instanceof Error?$.message:String($)}}}async function jt(t,n,o,a,d,w){if(t==="retrieve"){return Eo(a,d??{})}if(t==="openProcedure"){const y=typeof d?.id==="string"?d.id:"";const c=w?.find(g=>g.id===y);if(!c){const g=(w??[]).map(D=>D.id);return{ok:false,error:g.length?`No procedure "${y}". 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 y=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:Et(c.effect)}));return{changes:y,returned:y.length}}if(t==="undoChange"){const y=typeof d?.id==="string"?d.id:"";const c=n.list().find(D=>D.id===y);if(!c){const D=n.list().filter(k=>!k.undoneAt).map(k=>k.id);return{ok:false,error:`No change with id "${y}". Call listChanges for the current ids${D.length?` (${D.join(", ")})`:""}.`}}if(c.undoneAt)return{ok:false,error:`"${c.effect.label}" was already undone.`};if(!Et(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 y=await n.revertAll(o);return{ok:y.failed.length===0,...y}}throw new Error(`Unknown ask-buoy action "${t}"`)}async function Go(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 ge(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)?Xt(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 Qe(t,n,o,a){if(t.effect==="read")return void 0;if(n==="network")return Yo(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 w={key:o.key};if(d==="mmkv.get"){if(typeof o.instanceId!=="string")return void 0;w.instanceId=o.instanceId}try{const y=await a(n,d,w);const c=y&&typeof y==="object"?y:void 0;if(c?.found===false)return void 0;const g=c?c.value:y;return{had:g!==void 0&&g!==null,value:g??void 0}}catch{return void 0}}async function Yo(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(w=>w&&w.id===n.id);if(!d)return void 0;return{had:true,value:String(d.enabled!==false)}}catch{return void 0}}function Vo(){const t="abcdefghijklmnopqrstuvwxyz0123456789";let n="ask_";for(let o=0;o<20;o++)n+=t[Math.floor(Math.random()*t.length)];return n}
|