gemi 0.230.0 → 0.232.0
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/dist/ai/Agent.d.ts +10 -0
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/AgentController.d.ts.map +1 -1
- package/dist/ai/AgentProvider.d.ts +11 -0
- package/dist/ai/AgentProvider.d.ts.map +1 -1
- package/dist/ai/client/index.js +95 -16
- package/dist/ai/client/index.js.map +1 -1
- package/dist/ai/client/reducer.d.ts +8 -0
- package/dist/ai/client/reducer.d.ts.map +1 -1
- package/dist/ai/index.js +9 -9
- package/dist/ai/index.js.map +4 -4
- package/dist/ai/testing/RecordingProvider.d.ts.map +1 -1
- package/dist/ai/testing/index.d.ts +1 -0
- package/dist/ai/testing/index.d.ts.map +1 -1
- package/dist/ai/testing/index.js +3 -3
- package/dist/ai/testing/index.js.map +6 -5
- package/dist/ai/testing/scriptedProvider.d.ts +146 -0
- package/dist/ai/testing/scriptedProvider.d.ts.map +1 -0
- package/dist/ai/types.d.ts +7 -0
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/useChat.d.ts.map +1 -1
- package/dist/{chunk-sawk9ve0.js → chunk-8640e2g9.js} +2 -2
- package/dist/{chunk-sawk9ve0.js.map → chunk-8640e2g9.js.map} +1 -1
- package/dist/{chunk-enyer84t.js → chunk-8x8pbn1z.js} +2 -2
- package/dist/{chunk-enyer84t.js.map → chunk-8x8pbn1z.js.map} +3 -3
- package/dist/chunk-957arkj0.js +48 -0
- package/dist/{chunk-dn9k026s.js.map → chunk-957arkj0.js.map} +4 -5
- package/dist/{chunk-qgxft2rw.js → chunk-pbdk8w5m.js} +1 -1
- package/dist/{chunk-czbsj144.js → chunk-vwnrha3f.js} +2 -2
- package/dist/{chunk-czbsj144.js.map → chunk-vwnrha3f.js.map} +1 -1
- package/dist/{chunk-66vpxr4g.js → chunk-x35w5kjh.js} +1 -1
- package/dist/chunk-x6fa13e1.js +5 -0
- package/dist/{chunk-kx5gycdv.js.map → chunk-x6fa13e1.js.map} +4 -3
- package/dist/kernel/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/dist/services/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-dn9k026s.js +0 -48
- package/dist/chunk-kx5gycdv.js +0 -5
- /package/dist/{chunk-qgxft2rw.js.map → chunk-pbdk8w5m.js.map} +0 -0
- /package/dist/{chunk-66vpxr4g.js.map → chunk-x35w5kjh.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RecordingProvider.d.ts","sourceRoot":"","sources":["../../../ai/testing/RecordingProvider.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,aAAa,EACb,KAAK,oBAAoB,EACzB,KAAK,aAAa,EAClB,KAAK,oBAAoB,EAE1B,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,KAAK,kBAAkB,EAAE,YAAY,EAAE,KAAK,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAEnG;;;GAGG;AACH,MAAM,MAAM,YAAY,GAAG;IACzB,OAAO,EAAE,eAAe,CAAC;IACzB,MAAM,EAAE,aAAa,EAAE,CAAC;IACxB,2FAA2F;IAC3F,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,+EAA+E;IAC/E,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,4FAA4F;IAC5F,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,eAAe,GAAG;IAC5B,QAAQ,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,OAAO,CAAA;KAAE,EAAE,CAAC;IAC/C,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;CAC1B,CAAC;AAEF,iGAAiG;A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
1
1
|
export { type RecordedCall, type RecordedRequest, type Recording, type RecordingMatch, RecordingMismatchError, RecordingProvider, type RecordingProviderOptions, } from "./RecordingProvider";
|
|
2
2
|
export { type FingerprintOptions, Fingerprints, type RecordingFingerprints } from "./Fingerprints";
|
|
3
3
|
export { pinClock } from "./pinClock";
|
|
4
|
+
export { NO_AGENT, type ScriptedCall, type ScriptedError, ScriptedProvider, ScriptedProviderError, type ScriptedProviderOptions, type ScriptedReply, type ScriptedScripts, type ScriptedStep, type ScriptedTurn, scriptedProvider, turnOf, } from "./scriptedProvider";
|
|
4
5
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../ai/testing/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../ai/testing/index.ts"],"names":[],"mappings":"AAQA,OAAO,EACL,KAAK,YAAY,EACjB,KAAK,eAAe,EACpB,KAAK,SAAS,EACd,KAAK,cAAc,EACnB,sBAAsB,EACtB,iBAAiB,EACjB,KAAK,wBAAwB,GAC9B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,KAAK,kBAAkB,EAAE,YAAY,EAAE,KAAK,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AACnG,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EACL,QAAQ,EACR,KAAK,YAAY,EACjB,KAAK,aAAa,EAClB,gBAAgB,EAChB,qBAAqB,EACrB,KAAK,uBAAuB,EAC5B,KAAK,aAAa,EAClB,KAAK,eAAe,EACpB,KAAK,YAAY,EACjB,KAAK,YAAY,EACjB,gBAAgB,EAChB,MAAM,GACP,MAAM,oBAAoB,CAAC"}
|
package/dist/ai/testing/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{la as
|
|
2
|
+
import{la as b}from"../../chunk-8x8pbn1z.js";import{_d as n}from"../../chunk-x6fa13e1.js";import{Fj as d,Gj as p}from"../../chunk-30zs008n.js";import"../../chunk-m4wagwhr.js";import"../../chunk-6fpjc2eg.js";import"../../chunk-dqb257xv.js";import"../../chunk-x8by5j7p.js";import"../../chunk-30jcs49q.js";import{createHash as QD}from"crypto";import{createHash as x}from"crypto";import{existsSync as o,readdirSync as s,readFileSync as t,statSync as r}from"fs";import{join as E,relative as e,sep as DD}from"path";var M="\u241F",u=6,$D=/\{\{>\s*([^}\s]+)\s*\}\}/g,v=(D)=>D.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function m(D){let $=D.filter((Q)=>Q.length>=u),z=D.filter((Q)=>Q.length<u);return(Q)=>{let V=Q;for(let X of $)if(V.includes(X))V=V.split(X).join(M);for(let X of z)V=V.replace(new RegExp(`${v(X)}\\s*${M}`,"g"),M).replace(new RegExp(`${M}\\s*${v(X)}`,"g"),M);return V.replace(new RegExp(`\\s*${M}[\\s${M}]*`,"g"),M)}}function g(D,$=[]){for(let z of s(D)){if(z==="node_modules")continue;let Q=E(D,z);if(r(Q).isDirectory())g(Q,$);else if(z.endsWith(".md"))$.push(Q)}return $}class H{data;root;options;constructor(D,$={}){this.data=D;this.options=$,this.root=$.root??process.cwd()}static blob(D){return x("sha1").update(`blob ${Buffer.byteLength(D)}\x00`).update(D).digest("hex")}static pieces(D){return D.split(/\{\{[^}]*\}\}/).map(($)=>$.trim()).filter(($)=>$.length>0)}static tool(D){return x("sha256").update(JSON.stringify({description:D.description,parameters:D.parameters})).digest("hex")}static prompts(D={}){let $=D.root??process.cwd(),z=new Map;for(let Q of D.dirs??["app/agents"]){if(!o(E($,Q)))continue;for(let V of g(E($,Q)).sort())z.set(e($,V).split(DD).join("/"),t(V,"utf8"))}return z}static of(D,$,z={}){let Q=[...D].join(`
|
|
3
3
|
\x00
|
|
4
|
-
`),C={};for(let[Y,Q]of W.prompts(z))if(W.pieces(Q).filter((Z)=>Z.length>=12).sort((Z,L)=>L.length-Z.length).slice(0,3).some((Z)=>B.includes(Z)))C[Y]=W.blob(Q);let G=[...$.keys()].sort(),X=z.inputs?.(new Set(G));return new W({prompts:C,tools:Object.fromEntries(G.map((Y)=>[Y,[...$.get(Y)].sort()])),...X&&Object.keys(X).length>0?{inputs:a(X)}:{}},z)}same(D){let $=D instanceof W?D.data:D;return JSON.stringify(this.data)===JSON.stringify($)}changed(){let D=this.options.inputs?.(new Set(Object.keys(this.data.tools)))??{};return[...this.changedPrompts().map(([$])=>$),...Object.entries(this.data.inputs??{}).filter(([$,z])=>D[$]!==z).map(([$])=>`input ${$}`)]}cutters(){let D=W.prompts(this.options),$=this.changedPrompts(),z=new Map,B=new Map;for(let[C,G]of $){let X=this.readBlob(G);if(X===void 0)throw Error(`${C} changed since the recording, and the version it was recorded with (${G}) can't be read back from git`);if(z.set(C,X),D.has(C))B.set(C,D.get(C))}return{changed:$.map(([C])=>C),recorded:R(this.piecesWithPartials(z,(C)=>{let G=this.data.prompts[C];return G&&this.readBlob(G)||D.get(C)})),sent:R(this.piecesWithPartials(B,(C)=>D.get(C)))}}changedPrompts(){let D=W.prompts(this.options);return Object.entries(this.data.prompts).filter(([$,z])=>{let B=D.get($);return B===void 0||W.blob(B)!==z})}readBlob(D){if(this.options.readBlob)return this.options.readBlob(D);let $=Bun.spawnSync(["git","cat-file","blob",D],{cwd:this.root});return $.exitCode===0?$.stdout.toString():void 0}piecesWithPartials(D,$){let z=this.options.dirs??["app/agents"],B=this.options.shared??"prompts",C=[...D];while(C.length>0){let[G,X]=C.pop(),Y=z.find((Q)=>G.startsWith(`${Q}/`));if(Y===void 0)continue;for(let[,Q]of X.matchAll(n)){let V=`${Y}/${Q.includes("/")?Q:`${B}/${Q}`}.md`,Z=D.has(V)?void 0:$(V);if(Z===void 0)continue;D.set(V,Z),C.push([V,Z])}}return[...D.values()].flatMap((G)=>W.pieces(G)).sort((G,X)=>X.length-G.length)}}function a(D){return Object.fromEntries(Object.entries(D).sort(([$],[z])=>$.localeCompare(z)))}class H extends Error{constructor(D){super(`${D} Record again.`);this.name="RecordingMismatchError"}}var o=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g;function T(D,$){if(typeof D==="string")return $(D);if(Array.isArray(D))return D.map((z)=>T(z,$));if(D&&typeof D==="object")return Object.fromEntries(Object.entries(D).map(([z,B])=>[z,T(B,$)]));return D}function f(D){return JSON.parse(JSON.stringify(D,function($,z){if($==="nested")return;if($==="output"&&this.type==="tool-result"&&"modelOutput"in this)return;return z}))}function u(){let D;return{promise:new Promise((z)=>D=z),resolve:D}}var r=(D)=>s("sha256").update(D).digest("hex"),E=(D)=>D.flatMap(($)=>("tools"in $)?$.tools:[$]);function x(D){return D.map(({role:$,content:z})=>({role:$,parts:(Array.isArray(z)?z:[]).flatMap((B)=>{if(B?.type==="tool-call")return[{call:B.name,input:B.input??B.args}];if(B?.type==="tool-result")return[{result:B.name,status:B.status}];if(B?.type==="file")return[{file:!0}];return[]})}))}class M extends g{live;model;capabilities;recordedAt;calls;recordedNested;children=new Map;parent;key;sent=[];uploads;uploadCount=0;read;shared;options;texts=new Set;toolHashes=new Map;toolLists=new Set;recorded;cuts;constructor(D,$,z,B){super();this.live=D;if(this.options={...z,match:z.match??"wording",ids:new RegExp(z.ids??o,"g"),waitMs:z.waitMs??60000},B){let{parent:C}=B;this.parent=C,this.key=B.key,this.model=C.model,this.capabilities=C.capabilities,this.recordedAt=C.recordedAt,this.calls=B.calls,this.recordedNested={},this.uploads=C.uploads,this.shared=C.shared;return}if(this.shared={ids:new Map,stale:new Set,staleCalls:0,started:0,moved:u()},this.uploads=new Map,D){this.model=D.model,this.capabilities=D.capabilities,this.recordedAt=new Date,this.calls=[],this.recordedNested={};return}if(!$||$.version!==1||!Array.isArray($.calls))throw Error("RecordingProvider.replay needs a recording made by RecordingProvider.");if(this.model=$.model,this.capabilities=$.capabilities,this.recordedAt=new Date($.recordedAt),this.calls=structuredClone($.calls),this.recordedNested=structuredClone($.nested??{}),$.fingerprints)this.recorded=new W($.fingerprints,z.fingerprints)}static record(D,$={}){return new M(D,void 0,$)}static replay(D,$={}){return new M(void 0,D,$)}get isRecording(){return this.live!==void 0}get stale(){return this.shared.stale}get staleCalls(){return this.shared.staleCalls}nested(D){if(this.parent)return this.parent.nested(D);let $=this.children.get(D);if(!$){let z=this.recordedNested[D];if(!this.live&&!z)throw new H(`The recording has no sub-run "${D}".`);$=new M(this.live,void 0,this.options,{parent:this,key:D,calls:z??[]}),this.children.set(D,$)}return $}recording(){if(this.parent)return this.parent.recording();if(!this.live)throw Error("Only a recording provider (`record`) has a recording to save.");return{version:1,model:this.model,capabilities:this.capabilities,recordedAt:this.recordedAt.toISOString(),calls:structuredClone(this.calls),...this.options.fingerprints?{fingerprints:this.fingerprints().data}:{},...this.children.size>0?{nested:Object.fromEntries([...this.children].map(([D,$])=>[D,structuredClone($.calls)]))}:{}}}fingerprints(){let D=this.parent??this;return W.of(D.texts,D.toolHashes,this.options.fingerprints)}static changedSince(D,$={}){return D.fingerprints?new W(D.fingerprints,$).changed():[]}replayedInFull(){let D=this.parent??this;return D.calls.length===0&&Object.entries(D.recordedNested).every(([$,z])=>(D.children.get($)?.calls??z).length===0)}async pin(D){if(this.live)return this.read=D,D;let $=this.calls[0]?.read;if($===void 0)return D;return await(this.parent??this).reach($,this.where()),$}async upload(D){let $=++this.uploadCount,z=this.key===void 0?`upload_${$}`:`upload_${this.key}_${$}`;if(this.live)this.uploads.set(z,await this.live.upload(D));return z}async deleteFile(D){let $=this.uploads.get(D);if(this.live&&$!==void 0){if(!this.live.deleteFile)throw Error(`${this.live.constructor.name} cannot delete provider files: it does not implement deleteFile().`);await this.live.deleteFile($),this.uploads.delete(D)}}normalizeError(D){return this.live?this.live.normalizeError(D):super.normalizeError(D)}async*stream(D){let $=this.requestOf(D);if(this.live){yield*this.recordCall(D,$);return}yield*this.replayCall(D,$)}async*recordCall(D,$){let z=this.parent??this,B=z.shared.started++,C=this.read;this.read=void 0;let G=[],X=D.messages.map((Q)=>({...Q,content:Q.content.map((V)=>V.type==="file"&&V.fileId&&this.uploads.has(V.fileId)?{...V,fileId:this.uploads.get(V.fileId)}:V)}));for await(let Q of this.live.stream({...D,messages:X})){let V=G.at(-1);if(Q.type==="tool-call-discard"){let Z=new Set(Q.toolCallIds),L=G.filter((I)=>I.type!=="tool-call-delta"||!Z.has(I.toolCallId));G.splice(0,G.length,...L)}else if(Q.type==="retry");else if(V&&(Q.type==="text-delta"||Q.type==="output-delta")&&V.type===Q.type)V.delta+=Q.delta;else if(V?.type==="tool-call-delta"&&Q.type==="tool-call-delta"&&V.toolCallId===Q.toolCallId)V.argsDelta+=Q.argsDelta;else G.push({...Q});yield Q}let Y=this.options.position?await this.options.position():void 0;this.calls.push({request:$,events:G,at:B,...C!==void 0?{read:C}:{},...Y!==void 0?{ended:Y}:{}})}async*replayCall(D,$){let z=this.parent??this,B=this.where(),C=this.calls[0];if(this.options.ordered&&C?.at!==void 0)await z.turn(C.at,B);let G=this.calls.shift();if(!G)throw new H(`${B}: call ${this.sentCalls} was not recorded (the recording has no more calls).`);let{promptCacheKey:X,...Y}=G.request;if(!z.matches(JSON.stringify(Y),$))z.tolerate(B,{...G,request:Y},$,D.tools??[]);if(G.ended!==void 0)await z.reach(G.ended,B);let Q=z.shared.ids;for(let V of G.events)yield JSON.parse(JSON.stringify(V).replace(this.options.ids,(Z)=>Q.get(Z)??Z))}where(){return this.key===void 0?"the recording":`sub-run "${this.key}"`}sentCalls=0;requestOf(D){this.sentCalls++;let{signal:$,promptCacheKey:z,messages:B,tools:C,...G}=D,X=B.map(({role:L,content:I})=>({role:L,content:f(I)})),Y=this.sent.length>0&&this.sent.length<=X.length&&JSON.stringify(X.slice(0,this.sent.length))===JSON.stringify(this.sent)?this.sent.length:0;this.sent=X;let Q=C&&C.length>0?JSON.stringify(C):void 0,V=this.parent??this,Z=(L)=>{return V.texts.add(L),L};if(T([G,X.slice(Y)],Z),Q&&!V.toolLists.has(Q)){V.toolLists.add(Q);for(let L of E(C)){T(L,Z);let I=V.toolHashes.get(L.name)??new Set;I.add(W.tool(L)),V.toolHashes.set(L.name,I)}}return{...f(G),...Q?{tools:`sha256:${r(Q)}`,toolNames:E(C).map((L)=>L.name).sort()}:{},...Y>0?{after:Y}:{},messages:X.slice(Y)}}matches(D,$){let z=this.options.ids,B=JSON.stringify($),C=D.match(z)??[],G=B.match(z)??[];if(C.length!==G.length)return!1;let X=new Map(this.shared.ids);for(let[Y,Q]of C.entries()){let V=X.get(Q)??G[Y];if(V!==G[Y])return!1;X.set(Q,V)}if(D.replace(z,(Y)=>X.get(Y))!==B)return!1;for(let[Y,Q]of X)this.shared.ids.set(Y,Q);return!0}tolerate(D,$,z,B){let C=this.options.ids,G=this.options.match,X=$.request,Y=(A,K,J)=>{let N=JSON.stringify(A).replace(C,"<id>"),j=JSON.stringify(K).replace(C,"<id>"),_=0;while(_<N.length&&N[_]===j[_])_++;throw new H(`${D}: the request differs from the recorded one${J}. Recorded: \u2026${N.slice(Math.max(0,_-80),_+120)}\u2026 Sent: \u2026${j.slice(Math.max(0,_-80),_+120)}\u2026`)};if(G==="exact")Y(X,z,"");let{tools:Q,toolNames:V,...Z}=X,{tools:L,toolNames:I,...k}=z,w=[];if(!this.matches(JSON.stringify(Z),k))if(G==="wording"){if(!this.recorded)Y(Z,k,", and the recording has no fingerprints to tell a reworded prompt by");try{this.cuts??=this.recorded.cutters()}catch(J){throw new H(`${D}: ${J.message}.`)}let A=T(Z,this.cuts.recorded),K=T(k,this.cuts.sent);if(this.cuts.changed.length===0||!this.matches(JSON.stringify(A),K))Y(A,K,this.cuts.changed.length>0?", beyond the wording of the prompts changed since":"");w.push(...this.cuts.changed.map((J)=>`${J} changed`))}else{if(!((X.after??0)===(z.after??0)&&this.matches(JSON.stringify(x(X.messages)),x(z.messages))))Y(Z,k," in the conversation itself");let{messages:K,...J}=Z,{messages:N,...j}=k;if(!this.matches(JSON.stringify(K),N))w.push("message text changed");let _=new Set([...Object.keys(J),...Object.keys(j)]);for(let U of[..._].sort()){let O=JSON.stringify(J[U]??null);if(!this.matches(O,j[U]??null))w.push(`${U} changed`)}}if(Q!==L){let A=E(B);for(let K of $.events){if(K.type!=="tool-call")continue;let J=A.find((O)=>O.name===K.name);if(!J)throw new H(`${D}: the recorded answer calls ${K.name}, which is not offered any more.`);let N=Object.fromEntries([...JSON.stringify(J.parameters).matchAll(/"format":"([^"]+)"/g)].map(([,O])=>[O,!0])),j;try{j=JSON.parse(K.args||"{}")}catch{j=void 0}let _;try{_=m.fromJSONSchema(J.parameters,{unknownKeys:"error",formats:N})}catch(O){if(!(O instanceof v))throw O}let U=_?.safeParse(j);if(U&&U.ok===!1)throw new H(`${D}: the recorded call of ${K.name} does not fit its schema any more (${U.errors.join("; ")}).`)}if(this.recorded){let K=A.filter((J)=>!this.recorded.data.tools[J.name]?.includes(W.tool(J))).map((J)=>J.name).sort();w.push(K.length>0?`tools changed: ${K.join(", ")}`:"the tools offered changed")}else{let K=new Set(V??[]),J=new Set(I??[]),N=[...J].filter((_)=>!K.has(_)),j=[...K].filter((_)=>!J.has(_));w.push(N.length>0||j.length>0?`tools offered changed (${[...N.map((_)=>`+${_}`),...j.map((_)=>`-${_}`)].join(", ")})`:"the tools offered changed")}}this.shared.staleCalls++;for(let A of w)this.shared.stale.add(A)}async turn(D,$){let z=this.shared;z.pending??=[...this.calls,...Object.values(this.recordedNested).flat()].map((B)=>B.at).filter((B)=>B!==void 0).sort((B,C)=>B-C);while(z.pending[0]!==void 0&&z.pending[0]<D){let B=z.moved.promise;if(!await Promise.race([B.then(()=>!0),new Promise((G)=>setTimeout(()=>G(!1),this.options.waitMs))]))throw new H(`${$}: call ${D} waits for call ${z.pending[0]}, which the replay does not make.`)}z.pending=z.pending.filter((B)=>B!==D),z.moved.resolve(),z.moved=u()}async reach(D,$){let z=this.options.position;if(!z)return;let B=await z(),C=0;while(B<D){await new Promise((X)=>setTimeout(X,25));let G=await z();if(C=G===B?C+25:0,B=G,C>=this.options.waitMs)throw new H(`${$}: a call waits for the app to reach ${D}; it stays at ${B}.`)}}}function t(D){let $=globalThis.Date,z=new $(D).getTime()-$.now();if(!Number.isFinite(z))throw Error(`pinClock: ${String(D)} is not a date.`);class B extends ${constructor(...C){if(C.length===0)super($.now()+z);else super(...C)}static now(){return $.now()+z}}return globalThis.Date=B,()=>{if(globalThis.Date===B)globalThis.Date=$}}export{t as pinClock,M as RecordingProvider,H as RecordingMismatchError,W as Fingerprints};
|
|
4
|
+
`),V={};for(let[J,Z]of H.prompts(z))if(H.pieces(Z).filter((j)=>j.length>=12).sort((j,Y)=>Y.length-j.length).slice(0,3).some((j)=>Q.includes(j)))V[J]=H.blob(Z);let X=[...$.keys()].sort(),K=z.inputs?.(new Set(X));return new H({prompts:V,tools:Object.fromEntries(X.map((J)=>[J,[...$.get(J)].sort()])),...K&&Object.keys(K).length>0?{inputs:zD(K)}:{}},z)}same(D){let $=D instanceof H?D.data:D;return JSON.stringify(this.data)===JSON.stringify($)}changed(){let D=this.options.inputs?.(new Set(Object.keys(this.data.tools)))??{};return[...this.changedPrompts().map(([$])=>$),...Object.entries(this.data.inputs??{}).filter(([$,z])=>D[$]!==z).map(([$])=>`input ${$}`)]}cutters(){let D=H.prompts(this.options),$=this.changedPrompts(),z=new Map,Q=new Map;for(let[V,X]of $){let K=this.readBlob(X);if(K===void 0)throw Error(`${V} changed since the recording, and the version it was recorded with (${X}) can't be read back from git`);if(z.set(V,K),D.has(V))Q.set(V,D.get(V))}return{changed:$.map(([V])=>V),recorded:m(this.piecesWithPartials(z,(V)=>{let X=this.data.prompts[V];return X&&this.readBlob(X)||D.get(V)})),sent:m(this.piecesWithPartials(Q,(V)=>D.get(V)))}}changedPrompts(){let D=H.prompts(this.options);return Object.entries(this.data.prompts).filter(([$,z])=>{let Q=D.get($);return Q===void 0||H.blob(Q)!==z})}readBlob(D){if(this.options.readBlob)return this.options.readBlob(D);let $=Bun.spawnSync(["git","cat-file","blob",D],{cwd:this.root});return $.exitCode===0?$.stdout.toString():void 0}piecesWithPartials(D,$){let z=this.options.dirs??["app/agents"],Q=this.options.shared??"prompts",V=[...D];while(V.length>0){let[X,K]=V.pop(),J=z.find((Z)=>X.startsWith(`${Z}/`));if(J===void 0)continue;for(let[,Z]of K.matchAll($D)){let B=`${J}/${Z.includes("/")?Z:`${Q}/${Z}`}.md`,j=D.has(B)?void 0:$(B);if(j===void 0)continue;D.set(B,j),V.push([B,j])}}return[...D.values()].flatMap((X)=>H.pieces(X)).sort((X,K)=>K.length-X.length)}}function zD(D){return Object.fromEntries(Object.entries(D).sort(([$],[z])=>$.localeCompare(z)))}class w extends Error{constructor(D){super(`${D} Record again.`);this.name="RecordingMismatchError"}}var VD=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g;function T(D,$){if(typeof D==="string")return $(D);if(Array.isArray(D))return D.map((z)=>T(z,$));if(D&&typeof D==="object")return Object.fromEntries(Object.entries(D).map(([z,Q])=>[z,T(Q,$)]));return D}function h(D){return JSON.parse(JSON.stringify(D,function($,z){if($==="nested")return;if($==="output"&&this.type==="tool-result"&&"modelOutput"in this)return;return z}))}function c(){let D;return{promise:new Promise((z)=>D=z),resolve:D}}var XD=(D)=>QD("sha256").update(D).digest("hex"),k=(D)=>D.flatMap(($)=>("tools"in $)?$.tools:[$]);function l(D){return D.map(({role:$,content:z})=>({role:$,parts:(Array.isArray(z)?z:[]).flatMap((Q)=>{if(Q?.type==="tool-call")return[{call:Q.name,input:Q.input??Q.args}];if(Q?.type==="tool-result")return[{result:Q.name,status:Q.status}];if(Q?.type==="file")return[{file:!0}];return[]})}))}class R extends b{live;model;capabilities;recordedAt;calls;recordedNested;children=new Map;parent;key;sent=[];uploads;uploadCount=0;read;shared;options;texts=new Set;toolHashes=new Map;toolLists=new Set;recorded;cuts;constructor(D,$,z,Q){super();this.live=D;if(this.options={...z,match:z.match??"wording",ids:new RegExp(z.ids??VD,"g"),waitMs:z.waitMs??60000},Q){let{parent:V}=Q;this.parent=V,this.key=Q.key,this.model=V.model,this.capabilities=V.capabilities,this.recordedAt=V.recordedAt,this.calls=Q.calls,this.recordedNested={},this.uploads=V.uploads,this.shared=V.shared;return}if(this.shared={ids:new Map,stale:new Set,staleCalls:0,started:0,moved:c()},this.uploads=new Map,D){this.model=D.model,this.capabilities=D.capabilities,this.recordedAt=new Date,this.calls=[],this.recordedNested={};return}if(!$||$.version!==1||!Array.isArray($.calls))throw Error("RecordingProvider.replay needs a recording made by RecordingProvider.");if(this.model=$.model,this.capabilities=$.capabilities,this.recordedAt=new Date($.recordedAt),this.calls=structuredClone($.calls),this.recordedNested=structuredClone($.nested??{}),$.fingerprints)this.recorded=new H($.fingerprints,z.fingerprints)}static record(D,$={}){return new R(D,void 0,$)}static replay(D,$={}){return new R(void 0,D,$)}get isRecording(){return this.live!==void 0}get stale(){return this.shared.stale}get staleCalls(){return this.shared.staleCalls}nested(D){if(this.parent)return this.parent.nested(D);let $=this.children.get(D);if(!$){let z=this.recordedNested[D];if(!this.live&&!z)throw new w(`The recording has no sub-run "${D}".`);$=new R(this.live,void 0,this.options,{parent:this,key:D,calls:z??[]}),this.children.set(D,$)}return $}recording(){if(this.parent)return this.parent.recording();if(!this.live)throw Error("Only a recording provider (`record`) has a recording to save.");return{version:1,model:this.model,capabilities:this.capabilities,recordedAt:this.recordedAt.toISOString(),calls:structuredClone(this.calls),...this.options.fingerprints?{fingerprints:this.fingerprints().data}:{},...this.children.size>0?{nested:Object.fromEntries([...this.children].map(([D,$])=>[D,structuredClone($.calls)]))}:{}}}fingerprints(){let D=this.parent??this;return H.of(D.texts,D.toolHashes,this.options.fingerprints)}static changedSince(D,$={}){return D.fingerprints?new H(D.fingerprints,$).changed():[]}replayedInFull(){let D=this.parent??this;return D.calls.length===0&&Object.entries(D.recordedNested).every(([$,z])=>(D.children.get($)?.calls??z).length===0)}async pin(D){if(this.live)return this.read=D,D;let $=this.calls[0]?.read;if($===void 0)return D;return await(this.parent??this).reach($,this.where()),$}async upload(D){let $=++this.uploadCount,z=this.key===void 0?`upload_${$}`:`upload_${this.key}_${$}`;if(this.live)this.uploads.set(z,await this.live.upload(D));return z}async deleteFile(D){let $=this.uploads.get(D);if(this.live&&$!==void 0){if(!this.live.deleteFile)throw Error(`${this.live.constructor.name} cannot delete provider files: it does not implement deleteFile().`);await this.live.deleteFile($),this.uploads.delete(D)}}normalizeError(D){return this.live?this.live.normalizeError(D):super.normalizeError(D)}async*stream(D){let $=this.requestOf(D);if(this.live){yield*this.recordCall(D,$);return}yield*this.replayCall(D,$)}async*recordCall(D,$){let z=this.parent??this,Q=z.shared.started++,V=this.read;this.read=void 0;let X=[],K=D.messages.map((Z)=>({...Z,content:Z.content.map((B)=>B.type==="file"&&B.fileId&&this.uploads.has(B.fileId)?{...B,fileId:this.uploads.get(B.fileId)}:B)}));for await(let Z of this.live.stream({...D,messages:K})){let B=X.at(-1);if(Z.type==="tool-call-discard"){let j=new Set(Z.toolCallIds),Y=X.filter((_)=>_.type!=="tool-call-delta"||!j.has(_.toolCallId));X.splice(0,X.length,...Y)}else if(Z.type==="retry");else if(B&&(Z.type==="text-delta"||Z.type==="output-delta")&&B.type===Z.type)B.delta+=Z.delta;else if(B?.type==="tool-call-delta"&&Z.type==="tool-call-delta"&&B.toolCallId===Z.toolCallId)B.argsDelta+=Z.argsDelta;else X.push({...Z});yield Z}let J=this.options.position?await this.options.position():void 0;this.calls.push({request:$,events:X,at:Q,...V!==void 0?{read:V}:{},...J!==void 0?{ended:J}:{}})}async*replayCall(D,$){let z=this.parent??this,Q=this.where(),V=this.calls[0];if(this.options.ordered&&V?.at!==void 0)await z.turn(V.at,Q);let X=this.calls.shift();if(!X)throw new w(`${Q}: call ${this.sentCalls} was not recorded (the recording has no more calls).`);let{promptCacheKey:K,...J}=X.request;if(!z.matches(JSON.stringify(J),$))z.tolerate(Q,{...X,request:J},$,D.tools??[]);if(X.ended!==void 0)await z.reach(X.ended,Q);let Z=z.shared.ids;for(let B of X.events)yield JSON.parse(JSON.stringify(B).replace(this.options.ids,(j)=>Z.get(j)??j))}where(){return this.key===void 0?"the recording":`sub-run "${this.key}"`}sentCalls=0;requestOf(D){this.sentCalls++;let{signal:$,promptCacheKey:z,agent:Q,messages:V,tools:X,...K}=D,J=V.map(({role:_,content:I})=>({role:_,content:h(I)})),Z=this.sent.length>0&&this.sent.length<=J.length&&JSON.stringify(J.slice(0,this.sent.length))===JSON.stringify(this.sent)?this.sent.length:0;this.sent=J;let B=X&&X.length>0?JSON.stringify(X):void 0,j=this.parent??this,Y=(_)=>{return j.texts.add(_),_};if(T([K,J.slice(Z)],Y),B&&!j.toolLists.has(B)){j.toolLists.add(B);for(let _ of k(X)){T(_,Y);let I=j.toolHashes.get(_.name)??new Set;I.add(H.tool(_)),j.toolHashes.set(_.name,I)}}return{...h(K),...B?{tools:`sha256:${XD(B)}`,toolNames:k(X).map((_)=>_.name).sort()}:{},...Z>0?{after:Z}:{},messages:J.slice(Z)}}matches(D,$){let z=this.options.ids,Q=JSON.stringify($),V=D.match(z)??[],X=Q.match(z)??[];if(V.length!==X.length)return!1;let K=new Map(this.shared.ids);for(let[J,Z]of V.entries()){let B=K.get(Z)??X[J];if(B!==X[J])return!1;K.set(Z,B)}if(D.replace(z,(J)=>K.get(J))!==Q)return!1;for(let[J,Z]of K)this.shared.ids.set(J,Z);return!0}tolerate(D,$,z,Q){let V=this.options.ids,X=this.options.match,K=$.request,J=(O,G,W)=>{let U=JSON.stringify(O).replace(V,"<id>"),C=JSON.stringify(G).replace(V,"<id>"),L=0;while(L<U.length&&U[L]===C[L])L++;throw new w(`${D}: the request differs from the recorded one${W}. Recorded: \u2026${U.slice(Math.max(0,L-80),L+120)}\u2026 Sent: \u2026${C.slice(Math.max(0,L-80),L+120)}\u2026`)};if(X==="exact")J(K,z,"");let{tools:Z,toolNames:B,...j}=K,{tools:Y,toolNames:_,...I}=z,P=[];if(!this.matches(JSON.stringify(j),I))if(X==="wording"){if(!this.recorded)J(j,I,", and the recording has no fingerprints to tell a reworded prompt by");try{this.cuts??=this.recorded.cutters()}catch(W){throw new w(`${D}: ${W.message}.`)}let O=T(j,this.cuts.recorded),G=T(I,this.cuts.sent);if(this.cuts.changed.length===0||!this.matches(JSON.stringify(O),G))J(O,G,this.cuts.changed.length>0?", beyond the wording of the prompts changed since":"");P.push(...this.cuts.changed.map((W)=>`${W} changed`))}else{if(!((K.after??0)===(z.after??0)&&this.matches(JSON.stringify(l(K.messages)),l(z.messages))))J(j,I," in the conversation itself");let{messages:G,...W}=j,{messages:U,...C}=I;if(!this.matches(JSON.stringify(G),U))P.push("message text changed");let L=new Set([...Object.keys(W),...Object.keys(C)]);for(let q of[...L].sort()){let A=JSON.stringify(W[q]??null);if(!this.matches(A,C[q]??null))P.push(`${q} changed`)}}if(Z!==Y){let O=k(Q);for(let G of $.events){if(G.type!=="tool-call")continue;let W=O.find((A)=>A.name===G.name);if(!W)throw new w(`${D}: the recorded answer calls ${G.name}, which is not offered any more.`);let U=Object.fromEntries([...JSON.stringify(W.parameters).matchAll(/"format":"([^"]+)"/g)].map(([,A])=>[A,!0])),C;try{C=JSON.parse(G.args||"{}")}catch{C=void 0}let L;try{L=p.fromJSONSchema(W.parameters,{unknownKeys:"error",formats:U})}catch(A){if(!(A instanceof d))throw A}let q=L?.safeParse(C);if(q&&q.ok===!1)throw new w(`${D}: the recorded call of ${G.name} does not fit its schema any more (${q.errors.join("; ")}).`)}if(this.recorded){let G=O.filter((W)=>!this.recorded.data.tools[W.name]?.includes(H.tool(W))).map((W)=>W.name).sort();P.push(G.length>0?`tools changed: ${G.join(", ")}`:"the tools offered changed")}else{let G=new Set(B??[]),W=new Set(_??[]),U=[...W].filter((L)=>!G.has(L)),C=[...G].filter((L)=>!W.has(L));P.push(U.length>0||C.length>0?`tools offered changed (${[...U.map((L)=>`+${L}`),...C.map((L)=>`-${L}`)].join(", ")})`:"the tools offered changed")}}this.shared.staleCalls++;for(let O of P)this.shared.stale.add(O)}async turn(D,$){let z=this.shared;z.pending??=[...this.calls,...Object.values(this.recordedNested).flat()].map((Q)=>Q.at).filter((Q)=>Q!==void 0).sort((Q,V)=>Q-V);while(z.pending[0]!==void 0&&z.pending[0]<D){let Q=z.moved.promise;if(!await Promise.race([Q.then(()=>!0),new Promise((X)=>setTimeout(()=>X(!1),this.options.waitMs))]))throw new w(`${$}: call ${D} waits for call ${z.pending[0]}, which the replay does not make.`)}z.pending=z.pending.filter((Q)=>Q!==D),z.moved.resolve(),z.moved=c()}async reach(D,$){let z=this.options.position;if(!z)return;let Q=await z(),V=0;while(Q<D){await new Promise((K)=>setTimeout(K,25));let X=await z();if(V=X===Q?V+25:0,Q=X,V>=this.options.waitMs)throw new w(`${$}: a call waits for the app to reach ${D}; it stays at ${Q}.`)}}}function ZD(D){let $=globalThis.Date,z=new $(D).getTime()-$.now();if(!Number.isFinite(z))throw Error(`pinClock: ${String(D)} is not a date.`);class Q extends ${constructor(...V){if(V.length===0)super($.now()+z);else super(...V)}static now(){return $.now()+z}}return globalThis.Date=Q,()=>{if(globalThis.Date===Q)globalThis.Date=$}}class N extends Error{error;name="ScriptedProviderError";constructor(D,$){super(D);this.error=$}}var F=Symbol("scriptedProvider.NO_AGENT");function a(D){let z=n(D).at(-1),Q=z?.find((X)=>X.role==="user");if(!z||!Q)return;let V=Q.content.map((X)=>X.type==="text"?X.text:"").join("");return{message:Q,text:V,messages:z}}var S=void 0,i=(D)=>D===S?"the script":D===F?"NO_AGENT":`"${D}"`,BD={reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0};class f extends b{options;model="scripted";capabilities=BD;calls=[];uploads=[];steps;used=new Map;constructor(D,$={}){super();this.options=$;this.steps=new Map(Array.isArray(D)?[[S,[...D]]]:[...Object.entries(D).map(([z,Q])=>[z,[...Q]]),...D[F]?[[F,[...D[F]]]]:[]])}callsOf(D){return this.calls.filter(($)=>$.agent===D)}assertDone(){let D=[...this.steps].flatMap(([$,z])=>{let Q=z.length-(this.used.get($)??0);return Q>0?[`${i($)}: ${Q} step(s)`]:[]});if(D.length>0)throw new N(`Steps never used: ${D.join(", ")}.`)}stream(D){let $=D.agent?.name,z=this.steps.has(S)?S:$??F,Q=this.used.get(z)??0,V={agent:$,depth:D.agent?.depth??0,index:this.calls.filter((B)=>B.agent===$).length,messages:D.messages,turn:a(D.messages),params:D};this.calls.push(V);let X=this.steps.get(z),K=X?.[Q];if(X&&K!==void 0)this.used.set(z,Q+1);let J=()=>{let B=$===void 0?"A call no agent made":`Agent "${$}"`,j=V.turn?` (turn: ${JSON.stringify(V.turn.text.slice(0,80))})`:"";if(!X){let Y=[...this.steps.keys()].map(i).join(", ");return`${B} has no script${j}. The scripts are for ${Y}.${$===void 0?" Script it under [NO_AGENT].":""}`}if(z===S){let Y=$===void 0?"":` (${$}'s call ${V.index+1})`;return`The script ran out at step ${Q+1}${Y}: it has ${X.length} step(s)${j}.`}return`${B} made call ${V.index+1}, and its script has ${X.length} step(s)${j}.`},Z=X?this.options.exhausted??"throw":"throw";return async function*(){if(K===void 0){if(Z==="throw")throw new N(J());yield y("stop");return}yield*jD(await KD(K,V),V)}()}async upload(D){return this.uploads.push(D),`file_${this.uploads.length}`}normalizeError(D){if(D instanceof N&&D.error)return{...D.error};return{code:"provider_error",message:D instanceof Error?D.message:String(D),retryable:!1}}}function JD(D,$){return new f(D,$)}async function KD(D,$){let z=D;while(typeof z==="function")z=await z($);return z}var y=(D,$)=>({type:"finish",reason:D,usage:$??{inputTokens:1,outputTokens:1,totalTokens:2}});function jD(D,$){if(typeof D==="string")return[{type:"text-delta",delta:D},y("stop")];if("events"in D)return D.events;if("error"in D){let{error:Q}=D;if(typeof Q==="string")throw new N(Q);if(Q instanceof Error)throw Q;throw new N(Q.message,Q)}let z=[];if(D.reasoning)z.push({type:"reasoning-delta",delta:D.reasoning});for(let Q of typeof D.text==="string"?[D.text]:D.text??[])if(Q)z.push({type:"text-delta",delta:Q});if(D.output!==void 0)z.push({type:"output-delta",delta:JSON.stringify(D.output)});return(D.toolCalls??[]).forEach((Q,V)=>{z.push({type:"tool-call",toolCallId:Q.id??`call_${$.agent??"any"}_${$.index}_${V}`,name:Q.name,args:JSON.stringify(Q.input??{})})}),z.push(y(D.finishReason??"stop",D.usage)),z}export{a as turnOf,JD as scriptedProvider,ZD as pinClock,N as ScriptedProviderError,f as ScriptedProvider,R as RecordingProvider,w as RecordingMismatchError,F as NO_AGENT,H as Fingerprints};
|
|
5
5
|
|
|
6
|
-
//# debugId=
|
|
6
|
+
//# debugId=94903B3902054EDE64756E2164756E21
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../ai/testing/RecordingProvider.ts", "../ai/testing/Fingerprints.ts", "../ai/testing/pinClock.ts"],
|
|
3
|
+
"sources": ["../ai/testing/RecordingProvider.ts", "../ai/testing/Fingerprints.ts", "../ai/testing/pinClock.ts", "../ai/testing/scriptedProvider.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import { createHash } from \"node:crypto\";\n\nimport {\n AgentProvider,\n type ProviderCapabilities,\n type ProviderEvent,\n type ProviderStreamParams,\n type ProviderToolSpec,\n} from \"../AgentProvider\";\nimport { JSONSchemaError, s } from \"../Schema\";\nimport { type FingerprintOptions, Fingerprints, type RecordingFingerprints } from \"./Fingerprints\";\n\n/**\n * One model call, as a recording keeps it: what was sent (normalised, see\n * `RecordingProvider`) and what the model streamed back.\n */\nexport type RecordedCall = {\n request: RecordedRequest;\n events: ProviderEvent[];\n /** When it started among all the calls of the recording, its sub-runs' too (`ordered`). */\n at?: number;\n /** The app's position (`position`) the call's prompt was pinned to (`pin`). */\n read?: number;\n /** The app's position once the call's answer had streamed in full, before its tools ran. */\n ended?: number;\n};\n\n/**\n * A request as recorded. `messages` are the messages new since the call\n * before it (`after` says how many of that call's it resent), each without\n * the parts minted per run; `tools` is a hash of the tool list, and\n * `toolNames` the names it offered.\n */\nexport type RecordedRequest = {\n messages: { role: string; content: unknown }[];\n after?: number;\n tools?: string;\n toolNames?: string[];\n [field: string]: unknown;\n};\n\n/** What a `RecordingProvider` records, and replays from. Plain JSON: write it where you like. */\nexport type Recording = {\n version: 1;\n model: string;\n capabilities: ProviderCapabilities;\n /** When the recording started (ISO). A replay can run at that time: see `pinClock`. */\n recordedAt: string;\n calls: RecordedCall[];\n /** Sub-runs' calls (`nested(key)`), each in its own order. */\n nested?: Record<string, RecordedCall[]>;\n /** What it was made with, when recorded with `fingerprints`. See `Fingerprints`. */\n fingerprints?: RecordingFingerprints;\n};\n\n/** How `replay` matches a request against the recorded one. See `RecordingProviderOptions.match`. */\nexport type RecordingMatch = \"exact\" | \"wording\" | \"shape\";\n\nexport type RecordingProviderOptions = {\n /**\n * What a replayed request may differ in from the recorded one and still\n * replay, counted as `stale` with the reason:\n *\n * - `\"wording\"` (the default): the wording of the prompt files changed since\n * the recording, and nothing else. The static text of those files is cut\n * out of both requests (see `Fingerprints.cutters`), so the messages, the\n * tool calls and results and every value filled into the prompts must\n * still be the same. Needs a recording made with `fingerprints`, and\n * `fingerprints` on the replay to find the files.\n * - `\"shape\"`: anything but the shape of the conversation (its roles, tool\n * calls with their inputs, tool results with their status): instructions,\n * settings and message text. For an app whose prompts are not files.\n * - `\"exact\"`: nothing.\n *\n * In `\"wording\"` and `\"shape\"`, the tools offered may differ too, as long as\n * every tool call the recorded answer makes is to a tool still offered and\n * fits its schema today.\n */\n match?: RecordingMatch;\n /**\n * Fingerprint what the recording is made with (the prompt files its\n * requests carried, its tools' definitions, `inputs`), and, replaying, tell\n * a reworded prompt by them. See `Fingerprints`.\n */\n fingerprints?: FingerprintOptions;\n /**\n * Ids minted per run (a record's id, say), which a replay mints anew. Each\n * recorded id matches the id at its place in the request, the same one\n * wherever it shows, and the recorded answer is given the replay's ids.\n * Default: UUIDs.\n */\n ids?: RegExp;\n /**\n * Replays the calls, the sub-runs' too, in the order they started when\n * recorded (`at`), for runs that go side by side and whose order shows.\n * Off, each run and sub-run replays in its own order, in any interleaving.\n */\n ordered?: boolean;\n /**\n * A position in the app's own state that moves as tools run (an edit log's\n * head, say). Recording, each call keeps where it was; replaying, a call's\n * answer waits until the app gets there again, so tool calls running side by\n * side write in the recorded order. See also `pin`.\n */\n position?: () => number | Promise<number>;\n /** How long a replay waits for `ordered` or `position` before it gives up. Default 60 s. */\n waitMs?: number;\n};\n\n/** A replayed request that is not the recorded one, beyond what `match` tolerates. */\nexport class RecordingMismatchError extends Error {\n constructor(message: string) {\n super(`${message} Record again.`);\n this.name = \"RecordingMismatchError\";\n }\n}\n\nconst UUIDS = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g;\n\n/** `value` with each of its strings passed through `change`. */\nfunction mapStrings(value: unknown, change: (text: string) => string): unknown {\n if (typeof value === \"string\") return change(value);\n if (Array.isArray(value)) return value.map((item) => mapStrings(item, change));\n if (value && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value).map(([key, inner]) => [key, mapStrings(inner, change)]),\n );\n }\n return value;\n}\n\n/**\n * A message's content without what a run mints and the model is not sent: a\n * tool call's sub-run transcript (`nested`, recorded on its own), and the full\n * output of a tool whose model reads a projection (`modelOutput`).\n */\nfunction withoutTranscripts<T>(value: T): T {\n return JSON.parse(\n JSON.stringify(value, function (this: Record<string, unknown>, key, inner) {\n if (key === \"nested\") return undefined;\n if (key === \"output\" && this.type === \"tool-result\" && \"modelOutput\" in this) {\n return undefined;\n }\n return inner;\n }),\n );\n}\n\nfunction resolvers(): { promise: Promise<void>; resolve: () => void } {\n let resolve!: () => void;\n const promise = new Promise<void>((done) => (resolve = done));\n return { promise, resolve };\n}\n\nconst sha256 = (text: string) => createHash(\"sha256\").update(text).digest(\"hex\");\n\nconst flatTools = (tools: NonNullable<ProviderStreamParams[\"tools\"]>): ProviderToolSpec[] =>\n tools.flatMap((tool) => (\"tools\" in tool ? tool.tools : [tool]));\n\n/**\n * The shape of a conversation, which `match: \"shape\"` keeps: each message's\n * role, its tool calls with their inputs and its tool results with their\n * status, but not its text.\n */\nfunction shapeOf(messages: { role: string; content: unknown }[]): unknown {\n return messages.map(({ role, content }) => ({\n role,\n parts: (Array.isArray(content) ? content : []).flatMap((part: any): unknown[] => {\n if (part?.type === \"tool-call\") return [{ call: part.name, input: part.input ?? part.args }];\n if (part?.type === \"tool-result\") return [{ result: part.name, status: part.status }];\n if (part?.type === \"file\") return [{ file: true }];\n return [];\n }),\n }));\n}\n\ntype Shared = {\n ids: Map<string, string>;\n stale: Set<string>;\n staleCalls: number;\n started: number;\n pending?: number[];\n moved: { promise: Promise<void>; resolve: () => void };\n};\n\n/**\n * A provider that records a live provider's calls, and replays them later\n * without one: model-backed tests and evals that run in CI, offline and for\n * free, and stay the same from run to run.\n *\n * // Recording: every call goes to `live`, and is kept.\n * const recorder = RecordingProvider.record(live);\n * await runTheCase(recorder);\n * await Bun.write(file, JSON.stringify(recorder.recording()));\n *\n * // Replaying: each call is answered with what was recorded for it.\n * const replay = RecordingProvider.replay(await Bun.file(file).json());\n * await runTheCase(replay);\n * replay.stale; // why the recording should be made again, if it should\n *\n * WHAT IS MATCHED. The n-th call replays the n-th recorded call (per run and\n * per sub-run, see `nested`), and it has to be the same request:\n *\n * - Messages are compared without ids and times, which differ per run: only\n * `role` and `content` are kept, without sub-run transcripts. A call resends\n * the messages of the one before it, so only the new ones are recorded\n * (`after`), and a recording grows with the run, not with its square.\n * - Ids minted per run (`ids`, UUIDs by default) are matched by place, and the\n * recorded answer is given the replay's ids.\n * - The tool list is compared by its hash.\n *\n * A request that differs is stale rather than a mismatch only as far as\n * `match` allows. With `\"wording\"` (the default) that is the rewording of\n * prompt files changed since the recording: their static text is cut out of\n * both requests and the rest must be the same (see `Fingerprints`). The tools\n * offered may differ too, as long as each tool call the recorded answer makes\n * still exists and fits its schema today: replaying a call that doesn't\n * would test nothing. A stale call replays and is counted in `stale` with the\n * reason. Anything else throws a `RecordingMismatchError` that shows where\n * the two differ.\n *\n * UPLOADS are answered `upload_<n>`, by order, so a file need not be the same\n * bytes on another machine for its call to replay. A sub-run counts its own,\n * `upload_<key>_<n>`, so the ids stay the same however sub-runs interleave.\n * Recording, the file goes to the live provider, and the calls show the model\n * the provider's id.\n *\n * TIME. `recordedAt` is when the recording started. `pinClock(recordedAt)`\n * runs a replay at that time, so dates relative to today come out as recorded.\n */\nexport class RecordingProvider extends AgentProvider {\n readonly model: string;\n readonly capabilities: ProviderCapabilities;\n /** When the recording started. */\n readonly recordedAt: Date;\n private readonly calls: RecordedCall[];\n /** Replaying: the recorded calls of the sub-runs, by key. */\n private readonly recordedNested: Record<string, RecordedCall[]>;\n private readonly children = new Map<string, RecordingProvider>();\n private parent?: RecordingProvider;\n private readonly key?: string;\n /** The messages of the previous call, which the next call's are recorded after. */\n private sent: unknown[] = [];\n /** Recording: the live provider's file id of each upload, by the id answered here. */\n private readonly uploads: Map<string, string>;\n /** Uploads answered so far, counted per run and per sub-run. */\n private uploadCount = 0;\n /** Recording: the position the next call's prompt was pinned to. */\n private read?: number;\n private readonly shared: Shared;\n private readonly options: Required<Pick<RecordingProviderOptions, \"match\" | \"ids\" | \"waitMs\">> &\n RecordingProviderOptions;\n /** What the calls sent, for the fingerprints: every string, and each tool's definition hashes. */\n private readonly texts = new Set<string>();\n private readonly toolHashes = new Map<string, Set<string>>();\n private readonly toolLists = new Set<string>();\n /** Replaying: the recording's fingerprints, and how a differing request is cut by them. */\n private recorded?: Fingerprints;\n private cuts?: ReturnType<Fingerprints[\"cutters\"]>;\n\n private constructor(\n private readonly live: AgentProvider | undefined,\n recording: Recording | undefined,\n options: RecordingProviderOptions,\n child?: { parent: RecordingProvider; key: string; calls: RecordedCall[] },\n ) {\n super();\n this.options = {\n ...options,\n match: options.match ?? \"wording\",\n ids: new RegExp(options.ids ?? UUIDS, \"g\"),\n waitMs: options.waitMs ?? 60_000,\n };\n if (child) {\n const { parent } = child;\n this.parent = parent;\n this.key = child.key;\n this.model = parent.model;\n this.capabilities = parent.capabilities;\n this.recordedAt = parent.recordedAt;\n this.calls = child.calls;\n this.recordedNested = {};\n this.uploads = parent.uploads;\n this.shared = parent.shared;\n return;\n }\n this.shared = {\n ids: new Map(),\n stale: new Set(),\n staleCalls: 0,\n started: 0,\n moved: resolvers(),\n };\n this.uploads = new Map();\n if (live) {\n this.model = live.model;\n this.capabilities = live.capabilities;\n this.recordedAt = new Date();\n this.calls = [];\n this.recordedNested = {};\n return;\n }\n if (!recording || recording.version !== 1 || !Array.isArray(recording.calls)) {\n throw new Error(\"RecordingProvider.replay needs a recording made by RecordingProvider.\");\n }\n this.model = recording.model;\n this.capabilities = recording.capabilities;\n this.recordedAt = new Date(recording.recordedAt);\n this.calls = structuredClone(recording.calls);\n this.recordedNested = structuredClone(recording.nested ?? {});\n if (recording.fingerprints) {\n this.recorded = new Fingerprints(recording.fingerprints, options.fingerprints);\n }\n }\n\n /** Records every call made through it to `live`, which answers it. */\n static record(live: AgentProvider, options: RecordingProviderOptions = {}): RecordingProvider {\n return new RecordingProvider(live, undefined, options);\n }\n\n /** Answers each call with the recorded one. See the class for how calls are matched. */\n static replay(recording: Recording, options: RecordingProviderOptions = {}): RecordingProvider {\n return new RecordingProvider(undefined, recording, options);\n }\n\n /** Whether it records (true) or replays. */\n get isRecording(): boolean {\n return this.live !== undefined;\n }\n\n /**\n * Why the replay should be recorded again: the parts of the requests that\n * differed and were tolerated (`match`). Empty for a replay\n * that matched exactly, and for a recording.\n */\n get stale(): ReadonlySet<string> {\n return this.shared.stale;\n }\n\n /** How many calls replayed stale, the sub-runs' included. */\n get staleCalls(): number {\n return this.shared.staleCalls;\n }\n\n /**\n * The provider of sub-run `key` (a sub-agent's, say), recorded and replayed\n * apart from this one's calls and the other sub-runs', so sub-runs running\n * side by side can replay in any interleaving. The same key answers the same\n * provider, so a sub-run continued later goes on after its calls. Replaying\n * a key the recording does not have throws.\n */\n nested(key: string): RecordingProvider {\n if (this.parent) return this.parent.nested(key);\n let child = this.children.get(key);\n if (!child) {\n const calls = this.recordedNested[key];\n if (!this.live && !calls) {\n throw new RecordingMismatchError(`The recording has no sub-run \"${key}\".`);\n }\n child = new RecordingProvider(this.live, undefined, this.options, {\n parent: this,\n key,\n calls: calls ?? [],\n });\n this.children.set(key, child);\n }\n return child;\n }\n\n /**\n * The recording so far: every call made through this provider and its\n * sub-runs. Write it as JSON. Only for a provider made with `record`.\n */\n recording(): Recording {\n if (this.parent) return this.parent.recording();\n if (!this.live)\n throw new Error(\"Only a recording provider (`record`) has a recording to save.\");\n return {\n version: 1,\n model: this.model,\n capabilities: this.capabilities,\n recordedAt: this.recordedAt.toISOString(),\n calls: structuredClone(this.calls),\n ...(this.options.fingerprints ? { fingerprints: this.fingerprints().data } : {}),\n ...(this.children.size > 0\n ? {\n nested: Object.fromEntries(\n [...this.children].map(([key, child]) => [key, structuredClone(child.calls)]),\n ),\n }\n : {}),\n };\n }\n\n /**\n * The fingerprints of what the calls sent so far, the sub-runs' included:\n * of this recording, or of this replay (compare it with the recording's to\n * tell whether a new recording would differ). Uses the `fingerprints`\n * options for where prompts live.\n */\n fingerprints(): Fingerprints {\n const root = this.parent ?? this;\n return Fingerprints.of(root.texts, root.toolHashes, this.options.fingerprints);\n }\n\n /**\n * What changed since `recording` was made, without replaying it: the prompt\n * files and inputs its fingerprints name that differ today. Empty for a\n * recording without fingerprints. For listing the recordings to make again.\n */\n static changedSince(recording: Recording, options: FingerprintOptions = {}): string[] {\n return recording.fingerprints\n ? new Fingerprints(recording.fingerprints, options).changed()\n : [];\n }\n\n /**\n * Replaying: whether every recorded call was made, the sub-runs' too. A run\n * that took another path and stopped early made fewer.\n */\n replayedInFull(): boolean {\n const root = this.parent ?? this;\n return (\n root.calls.length === 0 &&\n Object.entries(root.recordedNested).every(\n ([key, calls]) => (root.children.get(key)?.calls ?? calls).length === 0,\n )\n );\n }\n\n /**\n * The position (`position`) the next call's prompt should show the app at,\n * given `now`, where it is. Recording, that is `now`, kept with the call.\n * Replaying, it is the recorded position, once the app has got there, so a\n * prompt rendered from the app's state is the one that was recorded,\n * however the other runs were timed.\n */\n async pin(now: number): Promise<number> {\n if (this.live) {\n this.read = now;\n return now;\n }\n const read = this.calls[0]?.read;\n if (read === undefined) return now;\n await (this.parent ?? this).reach(read, this.where());\n return read;\n }\n\n async upload(file: File): Promise<string> {\n const n = ++this.uploadCount;\n const id = this.key === undefined ? `upload_${n}` : `upload_${this.key}_${n}`;\n if (this.live) this.uploads.set(id, await this.live.upload(file));\n return id;\n }\n\n /** Deletes the live copy of a recorded upload; a replay has nothing to delete. */\n override async deleteFile(fileId: string): Promise<void> {\n const live = this.uploads.get(fileId);\n if (this.live && live !== undefined) {\n if (!this.live.deleteFile) {\n throw new Error(`${this.live.constructor.name} cannot delete provider files: it does not implement deleteFile().`);\n }\n await this.live.deleteFile(live);\n this.uploads.delete(fileId);\n }\n }\n\n normalizeError(error: unknown) {\n return this.live ? this.live.normalizeError(error) : super.normalizeError(error);\n }\n\n async *stream(params: ProviderStreamParams): AsyncGenerator<ProviderEvent> {\n const request = this.requestOf(params);\n if (this.live) {\n yield* this.recordCall(params, request);\n return;\n }\n yield* this.replayCall(params, request);\n }\n\n // --- recording ---------------------------------------------------------------\n\n private async *recordCall(\n params: ProviderStreamParams,\n request: RecordedRequest,\n ): AsyncGenerator<ProviderEvent> {\n const root = this.parent ?? this;\n const at = root.shared.started++;\n const read = this.read;\n this.read = undefined;\n const events: ProviderEvent[] = [];\n // The live call shows the model the files it uploaded, by the provider's ids.\n const messages = params.messages.map((message) => ({\n ...message,\n content: message.content.map((part) =>\n part.type === \"file\" && part.fileId && this.uploads.has(part.fileId)\n ? { ...part, fileId: this.uploads.get(part.fileId) }\n : part,\n ),\n }));\n for await (const event of this.live!.stream({ ...params, messages })) {\n const last = events.at(-1);\n if (event.type === \"tool-call-discard\") {\n // The provider asked again: the discarded calls' deltas are void.\n const discarded = new Set(event.toolCallIds);\n const kept = events.filter(\n (e) => e.type !== \"tool-call-delta\" || !discarded.has(e.toolCallId),\n );\n events.splice(0, events.length, ...kept);\n } else if (event.type === \"retry\") {\n // How the live call went, not what it answered.\n } else if (\n last &&\n (event.type === \"text-delta\" || event.type === \"output-delta\") &&\n last.type === event.type\n ) {\n // Consecutive deltas are kept as one, which replays the same text.\n last.delta += event.delta;\n } else if (\n last?.type === \"tool-call-delta\" &&\n event.type === \"tool-call-delta\" &&\n last.toolCallId === event.toolCallId\n ) {\n last.argsDelta += event.argsDelta;\n } else {\n events.push({ ...event });\n }\n yield event;\n }\n const ended = this.options.position ? await this.options.position() : undefined;\n this.calls.push({\n request,\n events,\n at,\n ...(read !== undefined ? { read } : {}),\n ...(ended !== undefined ? { ended } : {}),\n });\n }\n\n // --- replaying ---------------------------------------------------------------\n\n private async *replayCall(\n params: ProviderStreamParams,\n request: RecordedRequest,\n ): AsyncGenerator<ProviderEvent> {\n const root = this.parent ?? this;\n const where = this.where();\n const next = this.calls[0];\n if (this.options.ordered && next?.at !== undefined) await root.turn(next.at, where);\n const call = this.calls.shift();\n if (!call) {\n throw new RecordingMismatchError(\n `${where}: call ${this.sentCalls} was not recorded (the recording has no more calls).`,\n );\n }\n // A recording made with 0.204.0 kept the request's `promptCacheKey`: it is\n // not compared (see `requestOf`).\n const { promptCacheKey: _cacheKey, ...recorded } = call.request;\n if (!root.matches(JSON.stringify(recorded), request)) {\n root.tolerate(\n where,\n { ...call, request: recorded as RecordedRequest },\n request,\n params.tools ?? [],\n );\n }\n if (call.ended !== undefined) await root.reach(call.ended, where);\n const ids = root.shared.ids;\n for (const event of call.events) {\n yield JSON.parse(\n JSON.stringify(event).replace(this.options.ids, (id) => ids.get(id) ?? id),\n ) as ProviderEvent;\n }\n }\n\n private where(): string {\n return this.key === undefined ? \"the recording\" : `sub-run \"${this.key}\"`;\n }\n\n /** How many calls were made through this provider (not its sub-runs). */\n private sentCalls = 0;\n\n /**\n * The request as it is recorded and matched: see the class. Also moves\n * `sent` on, so the next call is recorded after this one.\n */\n private requestOf(params: ProviderStreamParams): RecordedRequest {\n this.sentCalls++;\n // `promptCacheKey` is derived from the prompt and the tools (#1228): it\n // changes whenever they are reworded, and recordings made before it have\n // none. It says nothing the request doesn't already say, so it is neither\n // matched nor fingerprinted (#1231).\n const { signal: _signal, promptCacheKey: _cacheKey, messages, tools, ...rest } = params;\n const sent = messages.map(({ role, content }) => ({\n role,\n content: withoutTranscripts(content),\n }));\n const after =\n this.sent.length > 0 &&\n this.sent.length <= sent.length &&\n JSON.stringify(sent.slice(0, this.sent.length)) === JSON.stringify(this.sent)\n ? this.sent.length\n : 0;\n this.sent = sent;\n const listed = tools && tools.length > 0 ? JSON.stringify(tools) : undefined;\n const root = this.parent ?? this;\n const keep = (text: string) => {\n root.texts.add(text);\n return text;\n };\n mapStrings([rest, sent.slice(after)], keep);\n if (listed && !root.toolLists.has(listed)) {\n root.toolLists.add(listed);\n for (const tool of flatTools(tools!)) {\n mapStrings(tool, keep);\n const hashes = root.toolHashes.get(tool.name) ?? new Set<string>();\n hashes.add(Fingerprints.tool(tool));\n root.toolHashes.set(tool.name, hashes);\n }\n }\n return {\n ...(withoutTranscripts(rest) as Record<string, unknown>),\n ...(listed\n ? {\n tools: `sha256:${sha256(listed)}`,\n toolNames: flatTools(tools!)\n .map((tool) => tool.name)\n .sort(),\n }\n : {}),\n ...(after > 0 ? { after } : {}),\n messages: sent.slice(after),\n };\n }\n\n /**\n * Whether `request` is the recorded one (`recorded`, as JSON), with each\n * recorded id matched to the id at its place in the request, the same one\n * every time it shows (`ids`, shared by the runs and sub-runs).\n */\n private matches(recorded: string, request: unknown): boolean {\n const pattern = this.options.ids;\n const sent = JSON.stringify(request);\n const theirs = recorded.match(pattern) ?? [];\n const ours = sent.match(pattern) ?? [];\n if (theirs.length !== ours.length) return false;\n const ids = new Map(this.shared.ids);\n for (const [index, id] of theirs.entries()) {\n const mapped = ids.get(id) ?? ours[index]!;\n if (mapped !== ours[index]) return false;\n ids.set(id, mapped);\n }\n if (recorded.replace(pattern, (id) => ids.get(id)!) !== sent) return false;\n for (const [id, mapped] of ids) this.shared.ids.set(id, mapped);\n return true;\n }\n\n /**\n * A request that is not the recorded one. It replays, stale, when what\n * differs is what `match` allows (see `RecordingProviderOptions.match`), and\n * every tool call of the recorded answer fits today's tools if those differ.\n * Throws otherwise, showing where the two first differ.\n */\n private tolerate(\n where: string,\n call: RecordedCall,\n request: RecordedRequest,\n tools: NonNullable<ProviderStreamParams[\"tools\"]>,\n ): void {\n const pattern = this.options.ids;\n const match = this.options.match;\n const recorded = call.request;\n const differs = (theirs: unknown, ours: unknown, why: string): never => {\n // Where they first differ, ids aside (they are matched by place).\n const a = JSON.stringify(theirs).replace(pattern, \"<id>\");\n const b = JSON.stringify(ours).replace(pattern, \"<id>\");\n let at = 0;\n while (at < a.length && a[at] === b[at]) at++;\n throw new RecordingMismatchError(\n `${where}: the request differs from the recorded one${why}. Recorded: …${a.slice(Math.max(0, at - 80), at + 120)}… Sent: …${b.slice(Math.max(0, at - 80), at + 120)}…`,\n );\n };\n if (match === \"exact\") differs(recorded, request, \"\");\n\n const { tools: recordedTools, toolNames: recordedNames, ...recordedRest } = recorded;\n const { tools: sentTools, toolNames: sentNames, ...sentRest } = request;\n const reasons: string[] = [];\n\n if (!this.matches(JSON.stringify(recordedRest), sentRest)) {\n if (match === \"wording\") {\n if (!this.recorded) {\n differs(\n recordedRest,\n sentRest,\n \", and the recording has no fingerprints to tell a reworded prompt by\",\n );\n }\n try {\n this.cuts ??= this.recorded!.cutters();\n } catch (error) {\n throw new RecordingMismatchError(`${where}: ${(error as Error).message}.`);\n }\n const theirs = mapStrings(recordedRest, this.cuts.recorded);\n const ours = mapStrings(sentRest, this.cuts.sent);\n if (this.cuts.changed.length === 0 || !this.matches(JSON.stringify(theirs), ours)) {\n differs(\n theirs,\n ours,\n this.cuts.changed.length > 0 ? \", beyond the wording of the prompts changed since\" : \"\",\n );\n }\n reasons.push(...this.cuts.changed.map((path) => `${path} changed`));\n } else {\n // The conversation's shape, ids matched by place as for an exact match.\n const sameShape =\n (recorded.after ?? 0) === (request.after ?? 0) &&\n this.matches(JSON.stringify(shapeOf(recorded.messages)), shapeOf(request.messages));\n if (!sameShape) differs(recordedRest, sentRest, \" in the conversation itself\");\n const { messages: recordedMessages, ...recordedSettings } = recordedRest;\n const { messages: sentMessages, ...sentSettings } = sentRest;\n if (!this.matches(JSON.stringify(recordedMessages), sentMessages)) {\n reasons.push(\"message text changed\");\n }\n const fields = new Set([...Object.keys(recordedSettings), ...Object.keys(sentSettings)]);\n for (const field of [...fields].sort()) {\n const theirs = JSON.stringify(recordedSettings[field] ?? null);\n if (!this.matches(theirs, sentSettings[field] ?? null)) reasons.push(`${field} changed`);\n }\n }\n }\n\n if (recordedTools !== sentTools) {\n const specs = flatTools(tools);\n for (const event of call.events) {\n if (event.type !== \"tool-call\") continue;\n const spec = specs.find((tool) => tool.name === event.name);\n if (!spec) {\n throw new RecordingMismatchError(\n `${where}: the recorded answer calls ${event.name}, which is not offered any more.`,\n );\n }\n // Formats are hints here: the tool checks them itself when the call runs.\n const formats = Object.fromEntries(\n [...JSON.stringify(spec.parameters).matchAll(/\"format\":\"([^\"]+)\"/g)].map(([, f]) => [\n f!,\n true as const,\n ]),\n );\n let input: unknown;\n try {\n input = JSON.parse(event.args || \"{}\");\n } catch {\n input = undefined;\n }\n // A schema `fromJSONSchema` can't model (a free-form part, such as an\n // object value with no type) isn't checked here (#1234): the tool still\n // validates its input when the call runs, as for formats.\n let schema: ReturnType<typeof s.fromJSONSchema> | undefined;\n try {\n schema = s.fromJSONSchema(spec.parameters as never, { unknownKeys: \"error\", formats });\n } catch (error) {\n if (!(error instanceof JSONSchemaError)) throw error;\n }\n const checked = schema?.safeParse(input);\n if (checked && checked.ok === false) {\n throw new RecordingMismatchError(\n `${where}: the recorded call of ${event.name} does not fit its schema any more (${checked.errors.join(\"; \")}).`,\n );\n }\n }\n if (this.recorded) {\n const changed = specs\n .filter(\n (tool) => !this.recorded!.data.tools[tool.name]?.includes(Fingerprints.tool(tool)),\n )\n .map((tool) => tool.name)\n .sort();\n reasons.push(\n changed.length > 0 ? `tools changed: ${changed.join(\", \")}` : \"the tools offered changed\",\n );\n } else {\n const before = new Set(recordedNames ?? []);\n const now = new Set(sentNames ?? []);\n const added = [...now].filter((name) => !before.has(name));\n const removed = [...before].filter((name) => !now.has(name));\n reasons.push(\n added.length > 0 || removed.length > 0\n ? `tools offered changed (${[\n ...added.map((name) => `+${name}`),\n ...removed.map((name) => `-${name}`),\n ].join(\", \")})`\n : \"the tools offered changed\",\n );\n }\n }\n this.shared.staleCalls++;\n for (const reason of reasons) this.shared.stale.add(reason);\n }\n\n /** Waits until every recorded call that started before `at` has started (`ordered`). */\n private async turn(at: number, where: string): Promise<void> {\n const shared = this.shared;\n shared.pending ??= [...this.calls, ...Object.values(this.recordedNested).flat()]\n .map((call) => call.at)\n .filter((started): started is number => started !== undefined)\n .sort((a, b) => a - b);\n while (shared.pending[0] !== undefined && shared.pending[0] < at) {\n const moved = shared.moved.promise;\n const waited = await Promise.race([\n moved.then(() => true),\n new Promise<boolean>((resolve) => setTimeout(() => resolve(false), this.options.waitMs)),\n ]);\n if (!waited) {\n throw new RecordingMismatchError(\n `${where}: call ${at} waits for call ${shared.pending[0]}, which the replay does not make.`,\n );\n }\n }\n shared.pending = shared.pending.filter((started) => started !== at);\n shared.moved.resolve();\n shared.moved = resolvers();\n }\n\n /** Waits until the app's `position` is at `target` or past it. */\n private async reach(target: number, where: string): Promise<void> {\n const position = this.options.position;\n if (!position) return;\n let last = await position();\n let still = 0;\n while (last < target) {\n await new Promise((resolve) => setTimeout(resolve, 25));\n const now = await position();\n still = now === last ? still + 25 : 0;\n last = now;\n if (still >= this.options.waitMs) {\n throw new RecordingMismatchError(\n `${where}: a call waits for the app to reach ${target}; it stays at ${last}.`,\n );\n }\n }\n }\n}\n",
|
|
5
|
+
"import { createHash } from \"node:crypto\";\n\nimport {\n AgentProvider,\n type ProviderCapabilities,\n type ProviderEvent,\n type ProviderStreamParams,\n type ProviderToolSpec,\n} from \"../AgentProvider\";\nimport { JSONSchemaError, s } from \"../Schema\";\nimport { type FingerprintOptions, Fingerprints, type RecordingFingerprints } from \"./Fingerprints\";\n\n/**\n * One model call, as a recording keeps it: what was sent (normalised, see\n * `RecordingProvider`) and what the model streamed back.\n */\nexport type RecordedCall = {\n request: RecordedRequest;\n events: ProviderEvent[];\n /** When it started among all the calls of the recording, its sub-runs' too (`ordered`). */\n at?: number;\n /** The app's position (`position`) the call's prompt was pinned to (`pin`). */\n read?: number;\n /** The app's position once the call's answer had streamed in full, before its tools ran. */\n ended?: number;\n};\n\n/**\n * A request as recorded. `messages` are the messages new since the call\n * before it (`after` says how many of that call's it resent), each without\n * the parts minted per run; `tools` is a hash of the tool list, and\n * `toolNames` the names it offered.\n */\nexport type RecordedRequest = {\n messages: { role: string; content: unknown }[];\n after?: number;\n tools?: string;\n toolNames?: string[];\n [field: string]: unknown;\n};\n\n/** What a `RecordingProvider` records, and replays from. Plain JSON: write it where you like. */\nexport type Recording = {\n version: 1;\n model: string;\n capabilities: ProviderCapabilities;\n /** When the recording started (ISO). A replay can run at that time: see `pinClock`. */\n recordedAt: string;\n calls: RecordedCall[];\n /** Sub-runs' calls (`nested(key)`), each in its own order. */\n nested?: Record<string, RecordedCall[]>;\n /** What it was made with, when recorded with `fingerprints`. See `Fingerprints`. */\n fingerprints?: RecordingFingerprints;\n};\n\n/** How `replay` matches a request against the recorded one. See `RecordingProviderOptions.match`. */\nexport type RecordingMatch = \"exact\" | \"wording\" | \"shape\";\n\nexport type RecordingProviderOptions = {\n /**\n * What a replayed request may differ in from the recorded one and still\n * replay, counted as `stale` with the reason:\n *\n * - `\"wording\"` (the default): the wording of the prompt files changed since\n * the recording, and nothing else. The static text of those files is cut\n * out of both requests (see `Fingerprints.cutters`), so the messages, the\n * tool calls and results and every value filled into the prompts must\n * still be the same. Needs a recording made with `fingerprints`, and\n * `fingerprints` on the replay to find the files.\n * - `\"shape\"`: anything but the shape of the conversation (its roles, tool\n * calls with their inputs, tool results with their status): instructions,\n * settings and message text. For an app whose prompts are not files.\n * - `\"exact\"`: nothing.\n *\n * In `\"wording\"` and `\"shape\"`, the tools offered may differ too, as long as\n * every tool call the recorded answer makes is to a tool still offered and\n * fits its schema today.\n */\n match?: RecordingMatch;\n /**\n * Fingerprint what the recording is made with (the prompt files its\n * requests carried, its tools' definitions, `inputs`), and, replaying, tell\n * a reworded prompt by them. See `Fingerprints`.\n */\n fingerprints?: FingerprintOptions;\n /**\n * Ids minted per run (a record's id, say), which a replay mints anew. Each\n * recorded id matches the id at its place in the request, the same one\n * wherever it shows, and the recorded answer is given the replay's ids.\n * Default: UUIDs.\n */\n ids?: RegExp;\n /**\n * Replays the calls, the sub-runs' too, in the order they started when\n * recorded (`at`), for runs that go side by side and whose order shows.\n * Off, each run and sub-run replays in its own order, in any interleaving.\n */\n ordered?: boolean;\n /**\n * A position in the app's own state that moves as tools run (an edit log's\n * head, say). Recording, each call keeps where it was; replaying, a call's\n * answer waits until the app gets there again, so tool calls running side by\n * side write in the recorded order. See also `pin`.\n */\n position?: () => number | Promise<number>;\n /** How long a replay waits for `ordered` or `position` before it gives up. Default 60 s. */\n waitMs?: number;\n};\n\n/** A replayed request that is not the recorded one, beyond what `match` tolerates. */\nexport class RecordingMismatchError extends Error {\n constructor(message: string) {\n super(`${message} Record again.`);\n this.name = \"RecordingMismatchError\";\n }\n}\n\nconst UUIDS = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g;\n\n/** `value` with each of its strings passed through `change`. */\nfunction mapStrings(value: unknown, change: (text: string) => string): unknown {\n if (typeof value === \"string\") return change(value);\n if (Array.isArray(value)) return value.map((item) => mapStrings(item, change));\n if (value && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value).map(([key, inner]) => [key, mapStrings(inner, change)]),\n );\n }\n return value;\n}\n\n/**\n * A message's content without what a run mints and the model is not sent: a\n * tool call's sub-run transcript (`nested`, recorded on its own), and the full\n * output of a tool whose model reads a projection (`modelOutput`).\n */\nfunction withoutTranscripts<T>(value: T): T {\n return JSON.parse(\n JSON.stringify(value, function (this: Record<string, unknown>, key, inner) {\n if (key === \"nested\") return undefined;\n if (key === \"output\" && this.type === \"tool-result\" && \"modelOutput\" in this) {\n return undefined;\n }\n return inner;\n }),\n );\n}\n\nfunction resolvers(): { promise: Promise<void>; resolve: () => void } {\n let resolve!: () => void;\n const promise = new Promise<void>((done) => (resolve = done));\n return { promise, resolve };\n}\n\nconst sha256 = (text: string) => createHash(\"sha256\").update(text).digest(\"hex\");\n\nconst flatTools = (tools: NonNullable<ProviderStreamParams[\"tools\"]>): ProviderToolSpec[] =>\n tools.flatMap((tool) => (\"tools\" in tool ? tool.tools : [tool]));\n\n/**\n * The shape of a conversation, which `match: \"shape\"` keeps: each message's\n * role, its tool calls with their inputs and its tool results with their\n * status, but not its text.\n */\nfunction shapeOf(messages: { role: string; content: unknown }[]): unknown {\n return messages.map(({ role, content }) => ({\n role,\n parts: (Array.isArray(content) ? content : []).flatMap((part: any): unknown[] => {\n if (part?.type === \"tool-call\") return [{ call: part.name, input: part.input ?? part.args }];\n if (part?.type === \"tool-result\") return [{ result: part.name, status: part.status }];\n if (part?.type === \"file\") return [{ file: true }];\n return [];\n }),\n }));\n}\n\ntype Shared = {\n ids: Map<string, string>;\n stale: Set<string>;\n staleCalls: number;\n started: number;\n pending?: number[];\n moved: { promise: Promise<void>; resolve: () => void };\n};\n\n/**\n * A provider that records a live provider's calls, and replays them later\n * without one: model-backed tests and evals that run in CI, offline and for\n * free, and stay the same from run to run.\n *\n * // Recording: every call goes to `live`, and is kept.\n * const recorder = RecordingProvider.record(live);\n * await runTheCase(recorder);\n * await Bun.write(file, JSON.stringify(recorder.recording()));\n *\n * // Replaying: each call is answered with what was recorded for it.\n * const replay = RecordingProvider.replay(await Bun.file(file).json());\n * await runTheCase(replay);\n * replay.stale; // why the recording should be made again, if it should\n *\n * WHAT IS MATCHED. The n-th call replays the n-th recorded call (per run and\n * per sub-run, see `nested`), and it has to be the same request:\n *\n * - Messages are compared without ids and times, which differ per run: only\n * `role` and `content` are kept, without sub-run transcripts. A call resends\n * the messages of the one before it, so only the new ones are recorded\n * (`after`), and a recording grows with the run, not with its square.\n * - Ids minted per run (`ids`, UUIDs by default) are matched by place, and the\n * recorded answer is given the replay's ids.\n * - The tool list is compared by its hash.\n *\n * A request that differs is stale rather than a mismatch only as far as\n * `match` allows. With `\"wording\"` (the default) that is the rewording of\n * prompt files changed since the recording: their static text is cut out of\n * both requests and the rest must be the same (see `Fingerprints`). The tools\n * offered may differ too, as long as each tool call the recorded answer makes\n * still exists and fits its schema today: replaying a call that doesn't\n * would test nothing. A stale call replays and is counted in `stale` with the\n * reason. Anything else throws a `RecordingMismatchError` that shows where\n * the two differ.\n *\n * UPLOADS are answered `upload_<n>`, by order, so a file need not be the same\n * bytes on another machine for its call to replay. A sub-run counts its own,\n * `upload_<key>_<n>`, so the ids stay the same however sub-runs interleave.\n * Recording, the file goes to the live provider, and the calls show the model\n * the provider's id.\n *\n * TIME. `recordedAt` is when the recording started. `pinClock(recordedAt)`\n * runs a replay at that time, so dates relative to today come out as recorded.\n */\nexport class RecordingProvider extends AgentProvider {\n readonly model: string;\n readonly capabilities: ProviderCapabilities;\n /** When the recording started. */\n readonly recordedAt: Date;\n private readonly calls: RecordedCall[];\n /** Replaying: the recorded calls of the sub-runs, by key. */\n private readonly recordedNested: Record<string, RecordedCall[]>;\n private readonly children = new Map<string, RecordingProvider>();\n private parent?: RecordingProvider;\n private readonly key?: string;\n /** The messages of the previous call, which the next call's are recorded after. */\n private sent: unknown[] = [];\n /** Recording: the live provider's file id of each upload, by the id answered here. */\n private readonly uploads: Map<string, string>;\n /** Uploads answered so far, counted per run and per sub-run. */\n private uploadCount = 0;\n /** Recording: the position the next call's prompt was pinned to. */\n private read?: number;\n private readonly shared: Shared;\n private readonly options: Required<Pick<RecordingProviderOptions, \"match\" | \"ids\" | \"waitMs\">> &\n RecordingProviderOptions;\n /** What the calls sent, for the fingerprints: every string, and each tool's definition hashes. */\n private readonly texts = new Set<string>();\n private readonly toolHashes = new Map<string, Set<string>>();\n private readonly toolLists = new Set<string>();\n /** Replaying: the recording's fingerprints, and how a differing request is cut by them. */\n private recorded?: Fingerprints;\n private cuts?: ReturnType<Fingerprints[\"cutters\"]>;\n\n private constructor(\n private readonly live: AgentProvider | undefined,\n recording: Recording | undefined,\n options: RecordingProviderOptions,\n child?: { parent: RecordingProvider; key: string; calls: RecordedCall[] },\n ) {\n super();\n this.options = {\n ...options,\n match: options.match ?? \"wording\",\n ids: new RegExp(options.ids ?? UUIDS, \"g\"),\n waitMs: options.waitMs ?? 60_000,\n };\n if (child) {\n const { parent } = child;\n this.parent = parent;\n this.key = child.key;\n this.model = parent.model;\n this.capabilities = parent.capabilities;\n this.recordedAt = parent.recordedAt;\n this.calls = child.calls;\n this.recordedNested = {};\n this.uploads = parent.uploads;\n this.shared = parent.shared;\n return;\n }\n this.shared = {\n ids: new Map(),\n stale: new Set(),\n staleCalls: 0,\n started: 0,\n moved: resolvers(),\n };\n this.uploads = new Map();\n if (live) {\n this.model = live.model;\n this.capabilities = live.capabilities;\n this.recordedAt = new Date();\n this.calls = [];\n this.recordedNested = {};\n return;\n }\n if (!recording || recording.version !== 1 || !Array.isArray(recording.calls)) {\n throw new Error(\"RecordingProvider.replay needs a recording made by RecordingProvider.\");\n }\n this.model = recording.model;\n this.capabilities = recording.capabilities;\n this.recordedAt = new Date(recording.recordedAt);\n this.calls = structuredClone(recording.calls);\n this.recordedNested = structuredClone(recording.nested ?? {});\n if (recording.fingerprints) {\n this.recorded = new Fingerprints(recording.fingerprints, options.fingerprints);\n }\n }\n\n /** Records every call made through it to `live`, which answers it. */\n static record(live: AgentProvider, options: RecordingProviderOptions = {}): RecordingProvider {\n return new RecordingProvider(live, undefined, options);\n }\n\n /** Answers each call with the recorded one. See the class for how calls are matched. */\n static replay(recording: Recording, options: RecordingProviderOptions = {}): RecordingProvider {\n return new RecordingProvider(undefined, recording, options);\n }\n\n /** Whether it records (true) or replays. */\n get isRecording(): boolean {\n return this.live !== undefined;\n }\n\n /**\n * Why the replay should be recorded again: the parts of the requests that\n * differed and were tolerated (`match`). Empty for a replay\n * that matched exactly, and for a recording.\n */\n get stale(): ReadonlySet<string> {\n return this.shared.stale;\n }\n\n /** How many calls replayed stale, the sub-runs' included. */\n get staleCalls(): number {\n return this.shared.staleCalls;\n }\n\n /**\n * The provider of sub-run `key` (a sub-agent's, say), recorded and replayed\n * apart from this one's calls and the other sub-runs', so sub-runs running\n * side by side can replay in any interleaving. The same key answers the same\n * provider, so a sub-run continued later goes on after its calls. Replaying\n * a key the recording does not have throws.\n */\n nested(key: string): RecordingProvider {\n if (this.parent) return this.parent.nested(key);\n let child = this.children.get(key);\n if (!child) {\n const calls = this.recordedNested[key];\n if (!this.live && !calls) {\n throw new RecordingMismatchError(`The recording has no sub-run \"${key}\".`);\n }\n child = new RecordingProvider(this.live, undefined, this.options, {\n parent: this,\n key,\n calls: calls ?? [],\n });\n this.children.set(key, child);\n }\n return child;\n }\n\n /**\n * The recording so far: every call made through this provider and its\n * sub-runs. Write it as JSON. Only for a provider made with `record`.\n */\n recording(): Recording {\n if (this.parent) return this.parent.recording();\n if (!this.live)\n throw new Error(\"Only a recording provider (`record`) has a recording to save.\");\n return {\n version: 1,\n model: this.model,\n capabilities: this.capabilities,\n recordedAt: this.recordedAt.toISOString(),\n calls: structuredClone(this.calls),\n ...(this.options.fingerprints ? { fingerprints: this.fingerprints().data } : {}),\n ...(this.children.size > 0\n ? {\n nested: Object.fromEntries(\n [...this.children].map(([key, child]) => [key, structuredClone(child.calls)]),\n ),\n }\n : {}),\n };\n }\n\n /**\n * The fingerprints of what the calls sent so far, the sub-runs' included:\n * of this recording, or of this replay (compare it with the recording's to\n * tell whether a new recording would differ). Uses the `fingerprints`\n * options for where prompts live.\n */\n fingerprints(): Fingerprints {\n const root = this.parent ?? this;\n return Fingerprints.of(root.texts, root.toolHashes, this.options.fingerprints);\n }\n\n /**\n * What changed since `recording` was made, without replaying it: the prompt\n * files and inputs its fingerprints name that differ today. Empty for a\n * recording without fingerprints. For listing the recordings to make again.\n */\n static changedSince(recording: Recording, options: FingerprintOptions = {}): string[] {\n return recording.fingerprints\n ? new Fingerprints(recording.fingerprints, options).changed()\n : [];\n }\n\n /**\n * Replaying: whether every recorded call was made, the sub-runs' too. A run\n * that took another path and stopped early made fewer.\n */\n replayedInFull(): boolean {\n const root = this.parent ?? this;\n return (\n root.calls.length === 0 &&\n Object.entries(root.recordedNested).every(\n ([key, calls]) => (root.children.get(key)?.calls ?? calls).length === 0,\n )\n );\n }\n\n /**\n * The position (`position`) the next call's prompt should show the app at,\n * given `now`, where it is. Recording, that is `now`, kept with the call.\n * Replaying, it is the recorded position, once the app has got there, so a\n * prompt rendered from the app's state is the one that was recorded,\n * however the other runs were timed.\n */\n async pin(now: number): Promise<number> {\n if (this.live) {\n this.read = now;\n return now;\n }\n const read = this.calls[0]?.read;\n if (read === undefined) return now;\n await (this.parent ?? this).reach(read, this.where());\n return read;\n }\n\n async upload(file: File): Promise<string> {\n const n = ++this.uploadCount;\n const id = this.key === undefined ? `upload_${n}` : `upload_${this.key}_${n}`;\n if (this.live) this.uploads.set(id, await this.live.upload(file));\n return id;\n }\n\n /** Deletes the live copy of a recorded upload; a replay has nothing to delete. */\n override async deleteFile(fileId: string): Promise<void> {\n const live = this.uploads.get(fileId);\n if (this.live && live !== undefined) {\n if (!this.live.deleteFile) {\n throw new Error(`${this.live.constructor.name} cannot delete provider files: it does not implement deleteFile().`);\n }\n await this.live.deleteFile(live);\n this.uploads.delete(fileId);\n }\n }\n\n normalizeError(error: unknown) {\n return this.live ? this.live.normalizeError(error) : super.normalizeError(error);\n }\n\n async *stream(params: ProviderStreamParams): AsyncGenerator<ProviderEvent> {\n const request = this.requestOf(params);\n if (this.live) {\n yield* this.recordCall(params, request);\n return;\n }\n yield* this.replayCall(params, request);\n }\n\n // --- recording ---------------------------------------------------------------\n\n private async *recordCall(\n params: ProviderStreamParams,\n request: RecordedRequest,\n ): AsyncGenerator<ProviderEvent> {\n const root = this.parent ?? this;\n const at = root.shared.started++;\n const read = this.read;\n this.read = undefined;\n const events: ProviderEvent[] = [];\n // The live call shows the model the files it uploaded, by the provider's ids.\n const messages = params.messages.map((message) => ({\n ...message,\n content: message.content.map((part) =>\n part.type === \"file\" && part.fileId && this.uploads.has(part.fileId)\n ? { ...part, fileId: this.uploads.get(part.fileId) }\n : part,\n ),\n }));\n for await (const event of this.live!.stream({ ...params, messages })) {\n const last = events.at(-1);\n if (event.type === \"tool-call-discard\") {\n // The provider asked again: the discarded calls' deltas are void.\n const discarded = new Set(event.toolCallIds);\n const kept = events.filter(\n (e) => e.type !== \"tool-call-delta\" || !discarded.has(e.toolCallId),\n );\n events.splice(0, events.length, ...kept);\n } else if (event.type === \"retry\") {\n // How the live call went, not what it answered.\n } else if (\n last &&\n (event.type === \"text-delta\" || event.type === \"output-delta\") &&\n last.type === event.type\n ) {\n // Consecutive deltas are kept as one, which replays the same text.\n last.delta += event.delta;\n } else if (\n last?.type === \"tool-call-delta\" &&\n event.type === \"tool-call-delta\" &&\n last.toolCallId === event.toolCallId\n ) {\n last.argsDelta += event.argsDelta;\n } else {\n events.push({ ...event });\n }\n yield event;\n }\n const ended = this.options.position ? await this.options.position() : undefined;\n this.calls.push({\n request,\n events,\n at,\n ...(read !== undefined ? { read } : {}),\n ...(ended !== undefined ? { ended } : {}),\n });\n }\n\n // --- replaying ---------------------------------------------------------------\n\n private async *replayCall(\n params: ProviderStreamParams,\n request: RecordedRequest,\n ): AsyncGenerator<ProviderEvent> {\n const root = this.parent ?? this;\n const where = this.where();\n const next = this.calls[0];\n if (this.options.ordered && next?.at !== undefined) await root.turn(next.at, where);\n const call = this.calls.shift();\n if (!call) {\n throw new RecordingMismatchError(\n `${where}: call ${this.sentCalls} was not recorded (the recording has no more calls).`,\n );\n }\n // A recording made with 0.204.0 kept the request's `promptCacheKey`: it is\n // not compared (see `requestOf`).\n const { promptCacheKey: _cacheKey, ...recorded } = call.request;\n if (!root.matches(JSON.stringify(recorded), request)) {\n root.tolerate(\n where,\n { ...call, request: recorded as RecordedRequest },\n request,\n params.tools ?? [],\n );\n }\n if (call.ended !== undefined) await root.reach(call.ended, where);\n const ids = root.shared.ids;\n for (const event of call.events) {\n yield JSON.parse(\n JSON.stringify(event).replace(this.options.ids, (id) => ids.get(id) ?? id),\n ) as ProviderEvent;\n }\n }\n\n private where(): string {\n return this.key === undefined ? \"the recording\" : `sub-run \"${this.key}\"`;\n }\n\n /** How many calls were made through this provider (not its sub-runs). */\n private sentCalls = 0;\n\n /**\n * The request as it is recorded and matched: see the class. Also moves\n * `sent` on, so the next call is recorded after this one.\n */\n private requestOf(params: ProviderStreamParams): RecordedRequest {\n this.sentCalls++;\n // `promptCacheKey` is derived from the prompt and the tools (#1228): it\n // changes whenever they are reworded, and recordings made before it have\n // none. It says nothing the request doesn't already say, so it is neither\n // matched nor fingerprinted (#1231). Nor is `agent`, which names who\n // asked rather than what was asked (#1343).\n const {\n signal: _signal,\n promptCacheKey: _cacheKey,\n agent: _agent,\n messages,\n tools,\n ...rest\n } = params;\n const sent = messages.map(({ role, content }) => ({\n role,\n content: withoutTranscripts(content),\n }));\n const after =\n this.sent.length > 0 &&\n this.sent.length <= sent.length &&\n JSON.stringify(sent.slice(0, this.sent.length)) === JSON.stringify(this.sent)\n ? this.sent.length\n : 0;\n this.sent = sent;\n const listed = tools && tools.length > 0 ? JSON.stringify(tools) : undefined;\n const root = this.parent ?? this;\n const keep = (text: string) => {\n root.texts.add(text);\n return text;\n };\n mapStrings([rest, sent.slice(after)], keep);\n if (listed && !root.toolLists.has(listed)) {\n root.toolLists.add(listed);\n for (const tool of flatTools(tools!)) {\n mapStrings(tool, keep);\n const hashes = root.toolHashes.get(tool.name) ?? new Set<string>();\n hashes.add(Fingerprints.tool(tool));\n root.toolHashes.set(tool.name, hashes);\n }\n }\n return {\n ...(withoutTranscripts(rest) as Record<string, unknown>),\n ...(listed\n ? {\n tools: `sha256:${sha256(listed)}`,\n toolNames: flatTools(tools!)\n .map((tool) => tool.name)\n .sort(),\n }\n : {}),\n ...(after > 0 ? { after } : {}),\n messages: sent.slice(after),\n };\n }\n\n /**\n * Whether `request` is the recorded one (`recorded`, as JSON), with each\n * recorded id matched to the id at its place in the request, the same one\n * every time it shows (`ids`, shared by the runs and sub-runs).\n */\n private matches(recorded: string, request: unknown): boolean {\n const pattern = this.options.ids;\n const sent = JSON.stringify(request);\n const theirs = recorded.match(pattern) ?? [];\n const ours = sent.match(pattern) ?? [];\n if (theirs.length !== ours.length) return false;\n const ids = new Map(this.shared.ids);\n for (const [index, id] of theirs.entries()) {\n const mapped = ids.get(id) ?? ours[index]!;\n if (mapped !== ours[index]) return false;\n ids.set(id, mapped);\n }\n if (recorded.replace(pattern, (id) => ids.get(id)!) !== sent) return false;\n for (const [id, mapped] of ids) this.shared.ids.set(id, mapped);\n return true;\n }\n\n /**\n * A request that is not the recorded one. It replays, stale, when what\n * differs is what `match` allows (see `RecordingProviderOptions.match`), and\n * every tool call of the recorded answer fits today's tools if those differ.\n * Throws otherwise, showing where the two first differ.\n */\n private tolerate(\n where: string,\n call: RecordedCall,\n request: RecordedRequest,\n tools: NonNullable<ProviderStreamParams[\"tools\"]>,\n ): void {\n const pattern = this.options.ids;\n const match = this.options.match;\n const recorded = call.request;\n const differs = (theirs: unknown, ours: unknown, why: string): never => {\n // Where they first differ, ids aside (they are matched by place).\n const a = JSON.stringify(theirs).replace(pattern, \"<id>\");\n const b = JSON.stringify(ours).replace(pattern, \"<id>\");\n let at = 0;\n while (at < a.length && a[at] === b[at]) at++;\n throw new RecordingMismatchError(\n `${where}: the request differs from the recorded one${why}. Recorded: …${a.slice(Math.max(0, at - 80), at + 120)}… Sent: …${b.slice(Math.max(0, at - 80), at + 120)}…`,\n );\n };\n if (match === \"exact\") differs(recorded, request, \"\");\n\n const { tools: recordedTools, toolNames: recordedNames, ...recordedRest } = recorded;\n const { tools: sentTools, toolNames: sentNames, ...sentRest } = request;\n const reasons: string[] = [];\n\n if (!this.matches(JSON.stringify(recordedRest), sentRest)) {\n if (match === \"wording\") {\n if (!this.recorded) {\n differs(\n recordedRest,\n sentRest,\n \", and the recording has no fingerprints to tell a reworded prompt by\",\n );\n }\n try {\n this.cuts ??= this.recorded!.cutters();\n } catch (error) {\n throw new RecordingMismatchError(`${where}: ${(error as Error).message}.`);\n }\n const theirs = mapStrings(recordedRest, this.cuts.recorded);\n const ours = mapStrings(sentRest, this.cuts.sent);\n if (this.cuts.changed.length === 0 || !this.matches(JSON.stringify(theirs), ours)) {\n differs(\n theirs,\n ours,\n this.cuts.changed.length > 0 ? \", beyond the wording of the prompts changed since\" : \"\",\n );\n }\n reasons.push(...this.cuts.changed.map((path) => `${path} changed`));\n } else {\n // The conversation's shape, ids matched by place as for an exact match.\n const sameShape =\n (recorded.after ?? 0) === (request.after ?? 0) &&\n this.matches(JSON.stringify(shapeOf(recorded.messages)), shapeOf(request.messages));\n if (!sameShape) differs(recordedRest, sentRest, \" in the conversation itself\");\n const { messages: recordedMessages, ...recordedSettings } = recordedRest;\n const { messages: sentMessages, ...sentSettings } = sentRest;\n if (!this.matches(JSON.stringify(recordedMessages), sentMessages)) {\n reasons.push(\"message text changed\");\n }\n const fields = new Set([...Object.keys(recordedSettings), ...Object.keys(sentSettings)]);\n for (const field of [...fields].sort()) {\n const theirs = JSON.stringify(recordedSettings[field] ?? null);\n if (!this.matches(theirs, sentSettings[field] ?? null)) reasons.push(`${field} changed`);\n }\n }\n }\n\n if (recordedTools !== sentTools) {\n const specs = flatTools(tools);\n for (const event of call.events) {\n if (event.type !== \"tool-call\") continue;\n const spec = specs.find((tool) => tool.name === event.name);\n if (!spec) {\n throw new RecordingMismatchError(\n `${where}: the recorded answer calls ${event.name}, which is not offered any more.`,\n );\n }\n // Formats are hints here: the tool checks them itself when the call runs.\n const formats = Object.fromEntries(\n [...JSON.stringify(spec.parameters).matchAll(/\"format\":\"([^\"]+)\"/g)].map(([, f]) => [\n f!,\n true as const,\n ]),\n );\n let input: unknown;\n try {\n input = JSON.parse(event.args || \"{}\");\n } catch {\n input = undefined;\n }\n // A schema `fromJSONSchema` can't model (a free-form part, such as an\n // object value with no type) isn't checked here (#1234): the tool still\n // validates its input when the call runs, as for formats.\n let schema: ReturnType<typeof s.fromJSONSchema> | undefined;\n try {\n schema = s.fromJSONSchema(spec.parameters as never, { unknownKeys: \"error\", formats });\n } catch (error) {\n if (!(error instanceof JSONSchemaError)) throw error;\n }\n const checked = schema?.safeParse(input);\n if (checked && checked.ok === false) {\n throw new RecordingMismatchError(\n `${where}: the recorded call of ${event.name} does not fit its schema any more (${checked.errors.join(\"; \")}).`,\n );\n }\n }\n if (this.recorded) {\n const changed = specs\n .filter(\n (tool) => !this.recorded!.data.tools[tool.name]?.includes(Fingerprints.tool(tool)),\n )\n .map((tool) => tool.name)\n .sort();\n reasons.push(\n changed.length > 0 ? `tools changed: ${changed.join(\", \")}` : \"the tools offered changed\",\n );\n } else {\n const before = new Set(recordedNames ?? []);\n const now = new Set(sentNames ?? []);\n const added = [...now].filter((name) => !before.has(name));\n const removed = [...before].filter((name) => !now.has(name));\n reasons.push(\n added.length > 0 || removed.length > 0\n ? `tools offered changed (${[\n ...added.map((name) => `+${name}`),\n ...removed.map((name) => `-${name}`),\n ].join(\", \")})`\n : \"the tools offered changed\",\n );\n }\n }\n this.shared.staleCalls++;\n for (const reason of reasons) this.shared.stale.add(reason);\n }\n\n /** Waits until every recorded call that started before `at` has started (`ordered`). */\n private async turn(at: number, where: string): Promise<void> {\n const shared = this.shared;\n shared.pending ??= [...this.calls, ...Object.values(this.recordedNested).flat()]\n .map((call) => call.at)\n .filter((started): started is number => started !== undefined)\n .sort((a, b) => a - b);\n while (shared.pending[0] !== undefined && shared.pending[0] < at) {\n const moved = shared.moved.promise;\n const waited = await Promise.race([\n moved.then(() => true),\n new Promise<boolean>((resolve) => setTimeout(() => resolve(false), this.options.waitMs)),\n ]);\n if (!waited) {\n throw new RecordingMismatchError(\n `${where}: call ${at} waits for call ${shared.pending[0]}, which the replay does not make.`,\n );\n }\n }\n shared.pending = shared.pending.filter((started) => started !== at);\n shared.moved.resolve();\n shared.moved = resolvers();\n }\n\n /** Waits until the app's `position` is at `target` or past it. */\n private async reach(target: number, where: string): Promise<void> {\n const position = this.options.position;\n if (!position) return;\n let last = await position();\n let still = 0;\n while (last < target) {\n await new Promise((resolve) => setTimeout(resolve, 25));\n const now = await position();\n still = now === last ? still + 25 : 0;\n last = now;\n if (still >= this.options.waitMs) {\n throw new RecordingMismatchError(\n `${where}: a call waits for the app to reach ${target}; it stays at ${last}.`,\n );\n }\n }\n }\n}\n",
|
|
6
6
|
"import { createHash } from \"node:crypto\";\nimport { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { join, relative, sep } from \"node:path\";\n\n/**\n * What a recording was made with, kept on it (`Recording.fingerprints`):\n *\n * - `prompts`: each prompt file whose text the requests carried, by its path\n * from `root`, as its git blob id, so the version it was recorded with can\n * be read back from git;\n * - `tools`: each tool the requests offered, by name, as the hashes of its\n * definitions (description and parameters);\n * - `inputs`: anything else the app says the recording depends on\n * (`FingerprintOptions.inputs`), such as the schemas behind generated\n * tools, hashed by name.\n */\nexport type RecordingFingerprints = {\n prompts: Record<string, string>;\n tools: Record<string, string[]>;\n inputs?: Record<string, string>;\n};\n\n/** Where a recording's prompt files are, and how to read their recorded versions back. */\nexport type FingerprintOptions = {\n /** The repository root that paths are relative to, and git runs in. Default the working directory. */\n root?: string;\n /** The folders, relative to `root`, that prompt files (`*.md`) live in. Default `[\"app/agents\"]`, gemi's. */\n dirs?: string[];\n /** The folder under a prompt folder that a bare partial name (`{{> tone}}`) resolves in. Default `prompts`, as `Prompt.render`. */\n shared?: string;\n /**\n * A prompt file's text by its git blob id, for the version a recording was\n * made with. Default `git cat-file blob <id>` in `root`. `undefined` when it\n * can't be found.\n */\n readBlob?: (blob: string) => string | undefined;\n /**\n * Other inputs the recording depends on, hashed by name, given the names of\n * the tools its requests offered: the component schemas behind generated\n * `add_` tools, say. Called when recording, and again to tell what changed.\n */\n inputs?: (tools: ReadonlySet<string>) => Record<string, string>;\n};\n\n/** What a piece of a prompt's static text is replaced with when it is cut out of a request. */\nconst CUT = \"␟\";\n/** Prompt text shorter than this is cut only next to a cut: it could be part of a value as well. */\nconst SHORTEST = 6;\nconst PARTIAL = /\\{\\{>\\s*([^}\\s]+)\\s*\\}\\}/g;\n\nconst escape = (text: string) => text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n/**\n * Cuts `pieces` of prompt text out of a text, leaving a mark (and no\n * whitespace) where each was. A short piece (a full stop between a\n * placeholder and a partial) is cut only where it touches a cut.\n */\nfunction cutOut(pieces: string[]): (text: string) => string {\n const long = pieces.filter((piece) => piece.length >= SHORTEST);\n const short = pieces.filter((piece) => piece.length < SHORTEST);\n return (text) => {\n let left = text;\n for (const piece of long) if (left.includes(piece)) left = left.split(piece).join(CUT);\n for (const piece of short) {\n left = left\n .replace(new RegExp(`${escape(piece)}\\\\s*${CUT}`, \"g\"), CUT)\n .replace(new RegExp(`${CUT}\\\\s*${escape(piece)}`, \"g\"), CUT);\n }\n return left.replace(new RegExp(`\\\\s*${CUT}[\\\\s${CUT}]*`, \"g\"), CUT);\n };\n}\n\nfunction scan(dir: string, out: string[] = []): string[] {\n for (const entry of readdirSync(dir)) {\n if (entry === \"node_modules\") continue;\n const path = join(dir, entry);\n if (statSync(path).isDirectory()) scan(path, out);\n else if (entry.endsWith(\".md\")) out.push(path);\n }\n return out;\n}\n\n/**\n * A recording's fingerprints, and what they tell about it today: which of the\n * prompts, tools and inputs it was made with have changed (`changed`), and how\n * to compare a request across a prompt's rewording (`cutters`).\n *\n * A replayed call whose request differs only in the wording of the prompt\n * files changed since the recording is stale, not a mismatch: the static text\n * of those files is cut out of both sides (the recorded version, read back from\n * git, out of the recorded request; today's out of the replay's), so the\n * messages, the tool calls and results and every value filled into the\n * prompts must still be the same.\n */\nexport class Fingerprints {\n readonly root: string;\n private readonly options: FingerprintOptions;\n\n constructor(\n readonly data: RecordingFingerprints,\n options: FingerprintOptions = {},\n ) {\n this.options = options;\n this.root = options.root ?? process.cwd();\n }\n\n /** A text's git blob id (`git hash-object`). */\n static blob(text: string): string {\n return createHash(\"sha1\")\n .update(`blob ${Buffer.byteLength(text)}\\0`)\n .update(text)\n .digest(\"hex\");\n }\n\n /** A prompt's static text: the pieces between its placeholders and partials. */\n static pieces(text: string): string[] {\n return text\n .split(/\\{\\{[^}]*\\}\\}/)\n .map((piece) => piece.trim())\n .filter((piece) => piece.length > 0);\n }\n\n /** A tool definition's hash, as `tools` keeps it. */\n static tool(tool: { description?: string; parameters?: unknown }): string {\n return createHash(\"sha256\")\n .update(JSON.stringify({ description: tool.description, parameters: tool.parameters }))\n .digest(\"hex\");\n }\n\n /** The prompt files under the configured folders today, by path from `root`. */\n static prompts(options: FingerprintOptions = {}): Map<string, string> {\n const root = options.root ?? process.cwd();\n const prompts = new Map<string, string>();\n for (const dir of options.dirs ?? [\"app/agents\"]) {\n if (!existsSync(join(root, dir))) continue;\n for (const path of scan(join(root, dir)).sort()) {\n prompts.set(relative(root, path).split(sep).join(\"/\"), readFileSync(path, \"utf8\"));\n }\n }\n return prompts;\n }\n\n /**\n * The fingerprints of what requests sent: `texts`, every string they\n * carried, and `tools`, each tool's definition hashes by name. A prompt file\n * counts as sent when one of its three longest pieces of static text (of 12\n * characters or more) is in `texts`.\n */\n static of(\n texts: Iterable<string>,\n tools: ReadonlyMap<string, ReadonlySet<string>>,\n options: FingerprintOptions = {},\n ): Fingerprints {\n const sent = [...texts].join(\"\\n\\0\\n\");\n const prompts: Record<string, string> = {};\n for (const [path, text] of Fingerprints.prompts(options)) {\n const longest = Fingerprints.pieces(text)\n .filter((piece) => piece.length >= 12)\n .sort((a, b) => b.length - a.length)\n .slice(0, 3);\n if (longest.some((piece) => sent.includes(piece))) prompts[path] = Fingerprints.blob(text);\n }\n const names = [...tools.keys()].sort();\n const inputs = options.inputs?.(new Set(names));\n return new Fingerprints(\n {\n prompts,\n tools: Object.fromEntries(names.map((name) => [name, [...tools.get(name)!].sort()])),\n ...(inputs && Object.keys(inputs).length > 0 ? { inputs: sortKeys(inputs) } : {}),\n },\n options,\n );\n }\n\n /** Whether `other` says the same. */\n same(other: Fingerprints | RecordingFingerprints): boolean {\n const data = other instanceof Fingerprints ? other.data : other;\n return JSON.stringify(this.data) === JSON.stringify(data);\n }\n\n /**\n * What differs today from what the recording was made with, without running\n * anything: each prompt file changed or gone (its path) and each input\n * changed or gone (`input <name>`). Tools defined in code are compared by a\n * replay, which offers them.\n */\n changed(): string[] {\n const today = this.options.inputs?.(new Set(Object.keys(this.data.tools))) ?? {};\n return [\n ...this.changedPrompts().map(([path]) => path),\n ...Object.entries(this.data.inputs ?? {})\n .filter(([name, hash]) => today[name] !== hash)\n .map(([name]) => `input ${name}`),\n ];\n }\n\n /**\n * How each side of a differing request is cut before the two are compared:\n * the static text of every prompt file changed since the recording (and of\n * the partials each version of it includes) is cut out, the recorded\n * version's from the recorded request and today's from the replay's.\n * `changed` names those files. Throws when a changed prompt's recorded\n * version can't be read back.\n */\n cutters(): {\n changed: string[];\n recorded: (text: string) => string;\n sent: (text: string) => string;\n } {\n const today = Fingerprints.prompts(this.options);\n const changed = this.changedPrompts();\n const recorded = new Map<string, string>();\n const sent = new Map<string, string>();\n for (const [path, blob] of changed) {\n const text = this.readBlob(blob);\n if (text === undefined) {\n throw new Error(\n `${path} changed since the recording, and the version it was recorded with (${blob}) can't be read back from git`,\n );\n }\n recorded.set(path, text);\n if (today.has(path)) sent.set(path, today.get(path)!);\n }\n return {\n changed: changed.map(([path]) => path),\n recorded: cutOut(\n this.piecesWithPartials(recorded, (path) => {\n const blob = this.data.prompts[path];\n return (blob && this.readBlob(blob)) || today.get(path);\n }),\n ),\n sent: cutOut(this.piecesWithPartials(sent, (path) => today.get(path))),\n };\n }\n\n /** The prompt files that changed or are gone since the recording, with their recorded blob ids. */\n private changedPrompts(): [string, string][] {\n const today = Fingerprints.prompts(this.options);\n return Object.entries(this.data.prompts).filter(([path, blob]) => {\n const text = today.get(path);\n return text === undefined || Fingerprints.blob(text) !== blob;\n });\n }\n\n private readBlob(blob: string): string | undefined {\n if (this.options.readBlob) return this.options.readBlob(blob);\n const git = Bun.spawnSync([\"git\", \"cat-file\", \"blob\", blob], { cwd: this.root });\n return git.exitCode === 0 ? git.stdout.toString() : undefined;\n }\n\n /**\n * The static text of `texts` and of the partials each includes, longest\n * first: moving text into a partial is a change of wording too. Partials\n * resolve as `Prompt.render` resolves them.\n */\n private piecesWithPartials(\n texts: Map<string, string>,\n version: (path: string) => string | undefined,\n ): string[] {\n const dirs = this.options.dirs ?? [\"app/agents\"];\n const shared = this.options.shared ?? \"prompts\";\n const pending = [...texts];\n while (pending.length > 0) {\n const [path, text] = pending.pop()!;\n const dir = dirs.find((d) => path.startsWith(`${d}/`));\n if (dir === undefined) continue;\n for (const [, name] of text.matchAll(PARTIAL)) {\n const partial = `${dir}/${name!.includes(\"/\") ? name : `${shared}/${name}`}.md`;\n const body = texts.has(partial) ? undefined : version(partial);\n if (body === undefined) continue;\n texts.set(partial, body);\n pending.push([partial, body]);\n }\n }\n return [...texts.values()]\n .flatMap((text) => Fingerprints.pieces(text))\n .sort((a, b) => b.length - a.length);\n }\n}\n\nfunction sortKeys(record: Record<string, string>): Record<string, string> {\n return Object.fromEntries(Object.entries(record).sort(([a], [b]) => a.localeCompare(b)));\n}\n",
|
|
7
|
-
"/**\n * Runs the process's clock from `at`: `Date.now()` and `new Date()` answer\n * `at` plus the time since the call, until the returned function puts the real\n * clock back. For replaying a recording (`RecordingProvider.recordedAt`), so\n * dates relative to today (\"in three days\", \"this week\") come out as they were\n * recorded. Timers are not touched: time still passes at its real rate.\n *\n * const restore = pinClock(replay.recordedAt);\n * try {\n * await runTheCase(replay);\n * } finally {\n * restore();\n * }\n *\n * Process-wide, like the clock it replaces: don't run two pinned replays side\n * by side. Inside vitest, `vi.setSystemTime` does the same job.\n */\nexport function pinClock(at: Date | string | number): () => void {\n const RealDate = globalThis.Date;\n const offset = new RealDate(at).getTime() - RealDate.now();\n if (!Number.isFinite(offset)) throw new Error(`pinClock: ${String(at)} is not a date.`);\n\n class PinnedDate extends RealDate {\n constructor(...args: unknown[]) {\n if (args.length === 0) super(RealDate.now() + offset);\n else super(...(args as [string | number | Date]));\n }\n\n static now(): number {\n return RealDate.now() + offset;\n }\n }\n globalThis.Date = PinnedDate as DateConstructor;\n return () => {\n if (globalThis.Date === (PinnedDate as DateConstructor)) globalThis.Date = RealDate;\n };\n}\n"
|
|
7
|
+
"/**\n * Runs the process's clock from `at`: `Date.now()` and `new Date()` answer\n * `at` plus the time since the call, until the returned function puts the real\n * clock back. For replaying a recording (`RecordingProvider.recordedAt`), so\n * dates relative to today (\"in three days\", \"this week\") come out as they were\n * recorded. Timers are not touched: time still passes at its real rate.\n *\n * const restore = pinClock(replay.recordedAt);\n * try {\n * await runTheCase(replay);\n * } finally {\n * restore();\n * }\n *\n * Process-wide, like the clock it replaces: don't run two pinned replays side\n * by side. Inside vitest, `vi.setSystemTime` does the same job.\n */\nexport function pinClock(at: Date | string | number): () => void {\n const RealDate = globalThis.Date;\n const offset = new RealDate(at).getTime() - RealDate.now();\n if (!Number.isFinite(offset)) throw new Error(`pinClock: ${String(at)} is not a date.`);\n\n class PinnedDate extends RealDate {\n constructor(...args: unknown[]) {\n if (args.length === 0) super(RealDate.now() + offset);\n else super(...(args as [string | number | Date]));\n }\n\n static now(): number {\n return RealDate.now() + offset;\n }\n }\n globalThis.Date = PinnedDate as DateConstructor;\n return () => {\n if (globalThis.Date === (PinnedDate as DateConstructor)) globalThis.Date = RealDate;\n };\n}\n",
|
|
8
|
+
"import {\n AgentProvider,\n type ProviderCapabilities,\n type ProviderEvent,\n type ProviderStreamParams,\n} from \"../AgentProvider\";\nimport { splitTurns } from \"../contextWindow\";\nimport type { AgentError, AgentMessage, FinishReason, Usage } from \"../types\";\n\n/**\n * One model call's answer in a `scriptedProvider` script:\n *\n * - a string: a text reply;\n * - `{ text?, reasoning?, output?, toolCalls?, finishReason?, usage? }`: a\n * reply with tool calls, reasoning or structured output (`output` is\n * sent as its JSON; `text` as a list streams one delta per entry);\n * - `{ events }`: the provider events themselves, for what the shorthand\n * does not cover;\n * - `{ error }`: the call fails with it. A string or an `Error` fails as a\n * `provider_error` that is not retryable; a `{ code, message, retryable }`\n * fails as exactly that error, so a `FallbackProvider` (which moves on\n * when `retryable`) or a client's retry message can be tested;\n * - a function of the call (`ScriptedCall`) answering one of these, for an\n * answer that depends on what was sent.\n */\nexport type ScriptedStep =\n | string\n | ScriptedReply\n | { events: ProviderEvent[] }\n | { error: Error | string | ScriptedError }\n | ((call: ScriptedCall) => ScriptedStep | Promise<ScriptedStep>);\n\n/** A step that is not a function: what a function step comes to. */\ntype ResolvedStep = Exclude<ScriptedStep, (call: ScriptedCall) => unknown>;\n\n/** The error a `{ error }` step fails with, as `normalizeError` reports it. */\nexport type ScriptedError = Pick<AgentError, \"code\" | \"message\" | \"retryable\"> & Partial<AgentError>;\n\nexport type ScriptedReply = {\n /** The reply's text: a list streams each entry as its own delta. */\n text?: string | string[];\n reasoning?: string;\n /** Structured output (an agent with `output`), sent as JSON. */\n output?: unknown;\n /** `id` defaults to `call_<agent>_<call>_<n>`; `input` to `{}`. */\n toolCalls?: { name: string; input?: unknown; id?: string }[];\n /** Default `\"stop\"`, tool calls or not: the run goes on to run them. */\n finishReason?: FinishReason;\n /** Default one input and one output token. */\n usage?: Usage;\n};\n\n/** A call a `scriptedProvider` answered, as its steps and `calls` see it. */\nexport type ScriptedCall = {\n /** The agent that made it (`ProviderStreamParams.agent`), `undefined` for a call no agent made. */\n agent: string | undefined;\n /** 0 for a run, 1 for a sub-agent it called, and so on. */\n depth: number;\n /** Which of this agent's calls it is, from 0. */\n index: number;\n /** What the call sent. */\n messages: AgentMessage[];\n /** The user turn the call answers: `turnOf(messages)`. */\n turn: ScriptedTurn | undefined;\n params: ProviderStreamParams;\n};\n\n/** A user turn, as `turnOf` finds it. */\nexport type ScriptedTurn = {\n /** The user message that started the turn. */\n message: AgentMessage;\n /** Its text parts, joined. */\n text: string;\n /** Every message of the turn, the one that started it first. */\n messages: AgentMessage[];\n};\n\nexport type ScriptedProviderOptions = {\n /**\n * What a call does once its script has no step left: `\"throw\"` (the\n * default) fails it with a `ScriptedProviderError` that names the agent,\n * the call and its turn; `\"stop\"` answers an empty reply. A call from an\n * agent the scripts don't name fails either way: a misspelt or renamed\n * agent is never what the test meant.\n */\n exhausted?: \"throw\" | \"stop\";\n};\n\n/** A call a `scriptedProvider` had no step for. The run ends with a `provider_error` carrying its message. */\nexport class ScriptedProviderError extends Error {\n override name = \"ScriptedProviderError\";\n constructor(\n message: string,\n /** What `normalizeError` reports: a `{ error }` step's own, or a `provider_error`. */\n readonly error?: ScriptedError,\n ) {\n super(message);\n }\n}\n\n/**\n * The key of the script for calls no agent makes (`generate()`, a\n * compaction summary through the run's provider), in the per-agent form:\n *\n * scriptedProvider({ writer: [\"Done.\"], [NO_AGENT]: [\"A short summary.\"] });\n */\nexport const NO_AGENT: unique symbol = Symbol(\"scriptedProvider.NO_AGENT\");\n\n/** Scripts by agent name, plus `[NO_AGENT]` for calls no agent makes. */\nexport type ScriptedScripts = Record<string, ScriptedStep[]> & { [NO_AGENT]?: ScriptedStep[] };\n\n/**\n * The user turn the last of `messages` belongs to (#1343): the user message\n * that started it, its text, and the turn's messages. Grouped as\n * `splitTurns` groups (a tool's results and the files it showed are part of\n * the turn that called it; a message that joined a turn goes with it), so a\n * provider reading it does not depend on how a step's messages are laid\n * out. `undefined` when no user message started the last turn.\n */\nexport function turnOf(messages: readonly AgentMessage[]): ScriptedTurn | undefined {\n const turns = splitTurns(messages);\n const last = turns.at(-1);\n const message = last?.find((candidate) => candidate.role === \"user\");\n if (!last || !message) return undefined;\n const text = message.content\n .map((part) => (part.type === \"text\" ? part.text : \"\"))\n .join(\"\");\n return { message, text, messages: last };\n}\n\n/** The key of a script for every call. */\nconst ANY = undefined;\ntype Key = string | typeof NO_AGENT | typeof ANY;\nconst keyName = (key: Key) => (key === ANY ? \"the script\" : key === NO_AGENT ? \"NO_AGENT\" : `\"${key}\"`);\n\nconst CAPABILITIES: ProviderCapabilities = {\n reasoning: true,\n structuredOutput: true,\n fileInput: true,\n parallelToolCalls: true,\n toolSearch: true,\n};\n\n/**\n * A provider for tests that answers each call from a script (#1343).\n *\n * Give it one script per agent, by name, and each agent's calls take the\n * next step of its own script, whatever order the agents call in:\n *\n * const provider = scriptedProvider({\n * planner: [{ toolCalls: [{ name: \"research\", input: { topic: \"tea\" } }] }, \"Here is the plan.\"],\n * researcher: [\"Green tea has less caffeine.\"],\n * });\n *\n * Or one list for every call, whichever agent makes it:\n *\n * scriptedProvider([\"Hello!\", \"Goodbye.\"]);\n *\n * A call with no step left fails with a `ScriptedProviderError` (see\n * `exhausted`), as does one from an agent the scripts do not name. Calls no\n * agent makes take the `[NO_AGENT]` script. `calls` keeps every call;\n * `assertDone()` throws when a step was never used.\n */\nexport class ScriptedProvider extends AgentProvider {\n readonly model = \"scripted\";\n readonly capabilities = CAPABILITIES;\n /** Every call, in the order they were made. */\n readonly calls: ScriptedCall[] = [];\n /** Every upload, in order: each gets the id `file_<n>`. */\n readonly uploads: File[] = [];\n\n private readonly steps: Map<Key, ScriptedStep[]>;\n private readonly used = new Map<Key, number>();\n\n constructor(\n script: ScriptedStep[] | ScriptedScripts,\n private readonly options: ScriptedProviderOptions = {},\n ) {\n super();\n this.steps = new Map<Key, ScriptedStep[]>(\n Array.isArray(script)\n ? [[ANY, [...script]]]\n : [\n ...Object.entries(script).map(([name, steps]): [Key, ScriptedStep[]] => [name, [...steps]]),\n ...(script[NO_AGENT] ? [[NO_AGENT, [...script[NO_AGENT]]] as [Key, ScriptedStep[]]] : []),\n ],\n );\n }\n\n /** The calls `agent` made. */\n callsOf(agent: string): ScriptedCall[] {\n return this.calls.filter((call) => call.agent === agent);\n }\n\n /** Throws when a script has a step no call took. */\n assertDone(): void {\n const left = [...this.steps].flatMap(([key, steps]) => {\n const unused = steps.length - (this.used.get(key) ?? 0);\n return unused > 0 ? [`${keyName(key)}: ${unused} step(s)`] : [];\n });\n if (left.length > 0) throw new ScriptedProviderError(`Steps never used: ${left.join(\", \")}.`);\n }\n\n stream(params: ProviderStreamParams) {\n const agent = params.agent?.name;\n const key: Key = this.steps.has(ANY) ? ANY : (agent ?? NO_AGENT);\n const index = this.used.get(key) ?? 0;\n const call: ScriptedCall = {\n agent,\n depth: params.agent?.depth ?? 0,\n index: this.calls.filter((other) => other.agent === agent).length,\n messages: params.messages,\n turn: turnOf(params.messages),\n params,\n };\n this.calls.push(call);\n const steps = this.steps.get(key);\n const step = steps?.[index];\n if (steps && step !== undefined) this.used.set(key, index + 1);\n const missing = () => {\n const who = agent === undefined ? \"A call no agent made\" : `Agent \"${agent}\"`;\n const turn = call.turn ? ` (turn: ${JSON.stringify(call.turn.text.slice(0, 80))})` : \"\";\n if (!steps) {\n const named = [...this.steps.keys()].map(keyName).join(\", \");\n const hint = agent === undefined ? \" Script it under [NO_AGENT].\" : \"\";\n return `${who} has no script${turn}. The scripts are for ${named}.${hint}`;\n }\n if (key === ANY) {\n const own = agent === undefined ? \"\" : ` (${agent}'s call ${call.index + 1})`;\n return `The script ran out at step ${index + 1}${own}: it has ${steps.length} step(s)${turn}.`;\n }\n return `${who} made call ${call.index + 1}, and its script has ${steps.length} step(s)${turn}.`;\n };\n const exhausted = steps ? (this.options.exhausted ?? \"throw\") : \"throw\";\n return (async function* (): AsyncGenerator<ProviderEvent> {\n if (step === undefined) {\n if (exhausted === \"throw\") throw new ScriptedProviderError(missing());\n yield finish(\"stop\");\n return;\n }\n yield* eventsOf(await resolve(step, call), call);\n })();\n }\n\n async upload(file: File) {\n this.uploads.push(file);\n return `file_${this.uploads.length}`;\n }\n\n override normalizeError(error: unknown): AgentError {\n if (error instanceof ScriptedProviderError && error.error) return { ...error.error };\n return {\n code: \"provider_error\",\n message: error instanceof Error ? error.message : String(error),\n retryable: false,\n };\n }\n}\n\n/** A `ScriptedProvider` (see there): one script for every call, or one per agent, by name. */\nexport function scriptedProvider(\n script: ScriptedStep[] | ScriptedScripts,\n options?: ScriptedProviderOptions,\n): ScriptedProvider {\n return new ScriptedProvider(script, options);\n}\n\nasync function resolve(step: ScriptedStep, call: ScriptedCall): Promise<ResolvedStep> {\n let current = step;\n while (typeof current === \"function\") current = await current(call);\n return current;\n}\n\nconst finish = (reason: FinishReason, usage?: Usage): ProviderEvent => ({\n type: \"finish\",\n reason,\n usage: usage ?? { inputTokens: 1, outputTokens: 1, totalTokens: 2 },\n});\n\nfunction eventsOf(step: ResolvedStep, call: ScriptedCall): ProviderEvent[] {\n if (typeof step === \"string\") return [{ type: \"text-delta\", delta: step }, finish(\"stop\")];\n if (\"events\" in step) return step.events;\n if (\"error\" in step) {\n const { error } = step;\n if (typeof error === \"string\") throw new ScriptedProviderError(error);\n if (error instanceof Error) throw error;\n throw new ScriptedProviderError(error.message, error);\n }\n const events: ProviderEvent[] = [];\n if (step.reasoning) events.push({ type: \"reasoning-delta\", delta: step.reasoning });\n for (const delta of typeof step.text === \"string\" ? [step.text] : (step.text ?? [])) {\n if (delta) events.push({ type: \"text-delta\", delta });\n }\n if (step.output !== undefined) events.push({ type: \"output-delta\", delta: JSON.stringify(step.output) });\n (step.toolCalls ?? []).forEach((toolCall, n) => {\n events.push({\n type: \"tool-call\",\n toolCallId: toolCall.id ?? `call_${call.agent ?? \"any\"}_${call.index}_${n}`,\n name: toolCall.name,\n args: JSON.stringify(toolCall.input ?? {}),\n });\n });\n events.push(finish(step.finishReason ?? \"stop\", step.usage));\n return events;\n}\n"
|
|
8
9
|
],
|
|
9
|
-
"mappings": ";gTAAA,mBAAS,aCAT,mBAAS,aACT,mBAAS,eAAY,gBAAa,cAAc,WA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E,CACpE,GAEA,SAAS,EAAQ,CAAC,EAAoB,EAAqC,CACzE,GAAI,OAAO,IAAS,SAAU,MAAO,CAAC,CAAE,KAAM,aAAc,MAAO,CAAK,EAAG,EAAO,MAAM,CAAC,EACzF,GAAI,WAAY,EAAM,OAAO,EAAK,OAClC,GAAI,UAAW,EAAM,CACnB,IAAQ,SAAU,EAClB,GAAI,OAAO,IAAU,SAAU,MAAM,IAAI,EAAsB,CAAK,EACpE,GAAI,aAAiB,MAAO,MAAM,EAClC,MAAM,IAAI,EAAsB,EAAM,QAAS,CAAK,EAEtD,IAAM,EAA0B,CAAC,EACjC,GAAI,EAAK,UAAW,EAAO,KAAK,CAAE,KAAM,kBAAmB,MAAO,EAAK,SAAU,CAAC,EAClF,QAAW,KAAS,OAAO,EAAK,OAAS,SAAW,CAAC,EAAK,IAAI,EAAK,EAAK,MAAQ,CAAC,EAC/E,GAAI,EAAO,EAAO,KAAK,CAAE,KAAM,aAAc,OAAM,CAAC,EAEtD,GAAI,EAAK,SAAW,OAAW,EAAO,KAAK,CAAE,KAAM,eAAgB,MAAO,KAAK,UAAU,EAAK,MAAM,CAAE,CAAC,EAUvG,OATC,EAAK,WAAa,CAAC,GAAG,QAAQ,CAAC,EAAU,IAAM,CAC9C,EAAO,KAAK,CACV,KAAM,YACN,WAAY,EAAS,IAAM,QAAQ,EAAK,OAAS,SAAS,EAAK,SAAS,IACxE,KAAM,EAAS,KACf,KAAM,KAAK,UAAU,EAAS,OAAS,CAAC,CAAC,CAC3C,CAAC,EACF,EACD,EAAO,KAAK,EAAO,EAAK,cAAgB,OAAQ,EAAK,KAAK,CAAC,EACpD",
|
|
11
|
+
"debugId": "94903B3902054EDE64756E2164756E21",
|
|
11
12
|
"names": []
|
|
12
13
|
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { AgentProvider, type ProviderCapabilities, type ProviderEvent, type ProviderStreamParams } from "../AgentProvider";
|
|
2
|
+
import type { AgentError, AgentMessage, FinishReason, Usage } from "../types";
|
|
3
|
+
/**
|
|
4
|
+
* One model call's answer in a `scriptedProvider` script:
|
|
5
|
+
*
|
|
6
|
+
* - a string: a text reply;
|
|
7
|
+
* - `{ text?, reasoning?, output?, toolCalls?, finishReason?, usage? }`: a
|
|
8
|
+
* reply with tool calls, reasoning or structured output (`output` is
|
|
9
|
+
* sent as its JSON; `text` as a list streams one delta per entry);
|
|
10
|
+
* - `{ events }`: the provider events themselves, for what the shorthand
|
|
11
|
+
* does not cover;
|
|
12
|
+
* - `{ error }`: the call fails with it. A string or an `Error` fails as a
|
|
13
|
+
* `provider_error` that is not retryable; a `{ code, message, retryable }`
|
|
14
|
+
* fails as exactly that error, so a `FallbackProvider` (which moves on
|
|
15
|
+
* when `retryable`) or a client's retry message can be tested;
|
|
16
|
+
* - a function of the call (`ScriptedCall`) answering one of these, for an
|
|
17
|
+
* answer that depends on what was sent.
|
|
18
|
+
*/
|
|
19
|
+
export type ScriptedStep = string | ScriptedReply | {
|
|
20
|
+
events: ProviderEvent[];
|
|
21
|
+
} | {
|
|
22
|
+
error: Error | string | ScriptedError;
|
|
23
|
+
} | ((call: ScriptedCall) => ScriptedStep | Promise<ScriptedStep>);
|
|
24
|
+
/** The error a `{ error }` step fails with, as `normalizeError` reports it. */
|
|
25
|
+
export type ScriptedError = Pick<AgentError, "code" | "message" | "retryable"> & Partial<AgentError>;
|
|
26
|
+
export type ScriptedReply = {
|
|
27
|
+
/** The reply's text: a list streams each entry as its own delta. */
|
|
28
|
+
text?: string | string[];
|
|
29
|
+
reasoning?: string;
|
|
30
|
+
/** Structured output (an agent with `output`), sent as JSON. */
|
|
31
|
+
output?: unknown;
|
|
32
|
+
/** `id` defaults to `call_<agent>_<call>_<n>`; `input` to `{}`. */
|
|
33
|
+
toolCalls?: {
|
|
34
|
+
name: string;
|
|
35
|
+
input?: unknown;
|
|
36
|
+
id?: string;
|
|
37
|
+
}[];
|
|
38
|
+
/** Default `"stop"`, tool calls or not: the run goes on to run them. */
|
|
39
|
+
finishReason?: FinishReason;
|
|
40
|
+
/** Default one input and one output token. */
|
|
41
|
+
usage?: Usage;
|
|
42
|
+
};
|
|
43
|
+
/** A call a `scriptedProvider` answered, as its steps and `calls` see it. */
|
|
44
|
+
export type ScriptedCall = {
|
|
45
|
+
/** The agent that made it (`ProviderStreamParams.agent`), `undefined` for a call no agent made. */
|
|
46
|
+
agent: string | undefined;
|
|
47
|
+
/** 0 for a run, 1 for a sub-agent it called, and so on. */
|
|
48
|
+
depth: number;
|
|
49
|
+
/** Which of this agent's calls it is, from 0. */
|
|
50
|
+
index: number;
|
|
51
|
+
/** What the call sent. */
|
|
52
|
+
messages: AgentMessage[];
|
|
53
|
+
/** The user turn the call answers: `turnOf(messages)`. */
|
|
54
|
+
turn: ScriptedTurn | undefined;
|
|
55
|
+
params: ProviderStreamParams;
|
|
56
|
+
};
|
|
57
|
+
/** A user turn, as `turnOf` finds it. */
|
|
58
|
+
export type ScriptedTurn = {
|
|
59
|
+
/** The user message that started the turn. */
|
|
60
|
+
message: AgentMessage;
|
|
61
|
+
/** Its text parts, joined. */
|
|
62
|
+
text: string;
|
|
63
|
+
/** Every message of the turn, the one that started it first. */
|
|
64
|
+
messages: AgentMessage[];
|
|
65
|
+
};
|
|
66
|
+
export type ScriptedProviderOptions = {
|
|
67
|
+
/**
|
|
68
|
+
* What a call does once its script has no step left: `"throw"` (the
|
|
69
|
+
* default) fails it with a `ScriptedProviderError` that names the agent,
|
|
70
|
+
* the call and its turn; `"stop"` answers an empty reply. A call from an
|
|
71
|
+
* agent the scripts don't name fails either way: a misspelt or renamed
|
|
72
|
+
* agent is never what the test meant.
|
|
73
|
+
*/
|
|
74
|
+
exhausted?: "throw" | "stop";
|
|
75
|
+
};
|
|
76
|
+
/** A call a `scriptedProvider` had no step for. The run ends with a `provider_error` carrying its message. */
|
|
77
|
+
export declare class ScriptedProviderError extends Error {
|
|
78
|
+
/** What `normalizeError` reports: a `{ error }` step's own, or a `provider_error`. */
|
|
79
|
+
readonly error?: ScriptedError;
|
|
80
|
+
name: string;
|
|
81
|
+
constructor(message: string,
|
|
82
|
+
/** What `normalizeError` reports: a `{ error }` step's own, or a `provider_error`. */
|
|
83
|
+
error?: ScriptedError);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* The key of the script for calls no agent makes (`generate()`, a
|
|
87
|
+
* compaction summary through the run's provider), in the per-agent form:
|
|
88
|
+
*
|
|
89
|
+
* scriptedProvider({ writer: ["Done."], [NO_AGENT]: ["A short summary."] });
|
|
90
|
+
*/
|
|
91
|
+
export declare const NO_AGENT: unique symbol;
|
|
92
|
+
/** Scripts by agent name, plus `[NO_AGENT]` for calls no agent makes. */
|
|
93
|
+
export type ScriptedScripts = Record<string, ScriptedStep[]> & {
|
|
94
|
+
[NO_AGENT]?: ScriptedStep[];
|
|
95
|
+
};
|
|
96
|
+
/**
|
|
97
|
+
* The user turn the last of `messages` belongs to (#1343): the user message
|
|
98
|
+
* that started it, its text, and the turn's messages. Grouped as
|
|
99
|
+
* `splitTurns` groups (a tool's results and the files it showed are part of
|
|
100
|
+
* the turn that called it; a message that joined a turn goes with it), so a
|
|
101
|
+
* provider reading it does not depend on how a step's messages are laid
|
|
102
|
+
* out. `undefined` when no user message started the last turn.
|
|
103
|
+
*/
|
|
104
|
+
export declare function turnOf(messages: readonly AgentMessage[]): ScriptedTurn | undefined;
|
|
105
|
+
/**
|
|
106
|
+
* A provider for tests that answers each call from a script (#1343).
|
|
107
|
+
*
|
|
108
|
+
* Give it one script per agent, by name, and each agent's calls take the
|
|
109
|
+
* next step of its own script, whatever order the agents call in:
|
|
110
|
+
*
|
|
111
|
+
* const provider = scriptedProvider({
|
|
112
|
+
* planner: [{ toolCalls: [{ name: "research", input: { topic: "tea" } }] }, "Here is the plan."],
|
|
113
|
+
* researcher: ["Green tea has less caffeine."],
|
|
114
|
+
* });
|
|
115
|
+
*
|
|
116
|
+
* Or one list for every call, whichever agent makes it:
|
|
117
|
+
*
|
|
118
|
+
* scriptedProvider(["Hello!", "Goodbye."]);
|
|
119
|
+
*
|
|
120
|
+
* A call with no step left fails with a `ScriptedProviderError` (see
|
|
121
|
+
* `exhausted`), as does one from an agent the scripts do not name. Calls no
|
|
122
|
+
* agent makes take the `[NO_AGENT]` script. `calls` keeps every call;
|
|
123
|
+
* `assertDone()` throws when a step was never used.
|
|
124
|
+
*/
|
|
125
|
+
export declare class ScriptedProvider extends AgentProvider {
|
|
126
|
+
private readonly options;
|
|
127
|
+
readonly model = "scripted";
|
|
128
|
+
readonly capabilities: ProviderCapabilities;
|
|
129
|
+
/** Every call, in the order they were made. */
|
|
130
|
+
readonly calls: ScriptedCall[];
|
|
131
|
+
/** Every upload, in order: each gets the id `file_<n>`. */
|
|
132
|
+
readonly uploads: File[];
|
|
133
|
+
private readonly steps;
|
|
134
|
+
private readonly used;
|
|
135
|
+
constructor(script: ScriptedStep[] | ScriptedScripts, options?: ScriptedProviderOptions);
|
|
136
|
+
/** The calls `agent` made. */
|
|
137
|
+
callsOf(agent: string): ScriptedCall[];
|
|
138
|
+
/** Throws when a script has a step no call took. */
|
|
139
|
+
assertDone(): void;
|
|
140
|
+
stream(params: ProviderStreamParams): AsyncGenerator<ProviderEvent, any, any>;
|
|
141
|
+
upload(file: File): Promise<string>;
|
|
142
|
+
normalizeError(error: unknown): AgentError;
|
|
143
|
+
}
|
|
144
|
+
/** A `ScriptedProvider` (see there): one script for every call, or one per agent, by name. */
|
|
145
|
+
export declare function scriptedProvider(script: ScriptedStep[] | ScriptedScripts, options?: ScriptedProviderOptions): ScriptedProvider;
|
|
146
|
+
//# sourceMappingURL=scriptedProvider.d.ts.map
|