@pydantic/logfire-ai-sdk-code-mode 0.1.3 → 0.1.5
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/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -18,7 +18,7 @@ from typing import Any, TypedDict, NotRequired, Literal`,nt=new Set(tt.split(`
|
|
|
18
18
|
`).flatMap(e=>e.replace(/^(?:from \S+ )?import /u,``).split(`, `)));function rt(e){let{functions:t,toolNames:n}=it(e),r=/* @__PURE__ */ new Map;for(let e of t){let t=e.parametersSchema.properties,n=typeof t==`object`&&t&&!Array.isArray(t)?Object.keys(t):[],i=new Map([...Me(n)].filter(([e,t])=>t!==e).map(([e,t])=>[t,e]));i.size>0&&r.set(e.name,i)}return{...at(t),toolNames:n,schemaArgNames:r}}function it(e){let t=[],n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map;for(let[i,a]of Object.entries(e)){let e=ot(i);if(e===`run_code`)throw Error(`Tool "${i}" becomes the Python function "${e}", which code mode reserves for itself. Rename the tool.`);if(nt.has(e))throw Error(`Tool "${i}" becomes the Python function "${e}", which the type-check stubs import, so the function would replace that import. Rename the tool.`);let o=r.get(e);if(o!==void 0)throw Error(`Tools "${o}" and "${i}" both become the Python function "${e}". Rename one of them.`);r.set(e,i),e!==i&&n.set(e,i);let s=a.outputSchema===void 0?void 0:lt(i,a);if(s===void 0&&pt(i,a),typeof a.description==`function`)throw Error(`Tool "${i}" has a description that depends on its context, which code mode cannot render yet`);t.push({name:e,description:a.description,parametersSchema:We(st(i,a),e,`parameters`),returnSchema:s===void 0?void 0:We(s,e,`return`)})}return{functions:t,toolNames:n}}function at(e){let t=e.map(e=>({f:e,sig:N.fromSchema(e.name,e.parametersSchema,e.returnSchema)})),n=t.map(({sig:e})=>e),r=N.getConflictingTypeNames(n),i=N.prefixedTypeNames(n,r),a=N.renderTypeDefinitions(n,r),o=e=>t.map(({f:t,sig:n})=>n.render(e,{name:t.name,description:t.description,isAsync:!0,conflictingTypeNames:r,typeNames:i}));return{typeDefinitions:a,functions:o(`...`),typeCheckStubs:[tt,...a,...o(`raise NotImplementedError()`)].join(`
|
|
19
19
|
|
|
20
20
|
`)}}function ot(e){return ge(e)}function st(e,t){return dt(e,(0,d.asSchema)(t.inputSchema).jsonSchema)}function ct(e){let t=(e?.[`~standard`])?.jsonSchema?.output;return typeof t==`function`?t:void 0}function lt(e,t){let n=ct(t.outputSchema);return n===void 0?dt(e,(0,d.asSchema)(t.outputSchema).jsonSchema):dt(e,n({target:`draft-07`}))}function ut(e){return typeof e.then==`function`}function dt(e,t){if(ut(t))throw Promise.resolve(t).catch(()=>void 0),Error(`Tool "${e}" has a schema that converts to JSON Schema asynchronously, which code mode does not support`);return t}const ft=/* @__PURE__ */ new WeakSet;function pt(e,t){ft.has(t)||(ft.add(t),console.warn(`Tool "${e}" has no outputSchema, so code mode shows its return type as Any. Add an outputSchema so that the model knows the shape of its result.`))}var mt=class extends Error{maxBytes;constructor(e){super(`The value is more than ${String(e)} bytes of JSON.`),this.maxBytes=e}};function ht(e,t){let n=t,r=e=>{if(n-=e,n<0)throw new mt(t)},i=e=>{r(2);let t={};for(let[n,i]of e){let e=String(n);r(Y(e)+4),Object.defineProperty(t,e,{value:a(i),enumerable:!0,writable:!0,configurable:!0})}return t},a=e=>{if(e instanceof Map)return i(e);if(e instanceof Set||Array.isArray(e)){r(2);let t=[];for(let n of e)r(1),t.push(a(n));return t}if(typeof e==`bigint`){let t=e.toString();return r(t.length),Number.isSafeInteger(Number(e))?Number(e):t}return e instanceof Uint8Array?(r(e.length+2),Buffer.from(e).toString(`latin1`)):typeof e==`string`?(r(Y(e)+2),e):typeof e==`object`&&e?i(Object.entries(e)):(r(typeof e==`number`?String(e).length:5),e)};return a(e)}function gt(e){return typeof e==`number`&&!Number.isFinite(e)?Number.isNaN(e)?`nan`:e>0?`inf`:`-inf`:Array.isArray(e)?e.map(gt):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,gt(t)])):e}function _t(e,t){let n=Y(e);if(n<=t)return e;let r=Buffer.from(e),i=Math.floor(t/2),a=r.subarray(0,i).toString().replace(/\uFFFD$/u,``),o=r.subarray(n-i).toString().replace(/^\uFFFD/u,``);return`${a}\n... (${String(n-2*i)} of ${String(n)} bytes cut) ...\n${o}`}function Y(e){return Buffer.byteLength(e,`utf8`)}function vt(e,t,n){return e>t?` ... (${String(e)} ${n} total)`:``}function X(e,t=!1){if(typeof e==`string`)return C(e.slice(0,120))+vt(e.length,120,`chars`);if(Array.isArray(e))return t?`[${String(e.length)} items]`:`[${e.slice(0,5).map(e=>X(e,!0)).join(`, `)}]`+vt(e.length,5,`items`);if(typeof e==`object`&&e){let n=Object.entries(e);return t?`{${String(n.length)} items}`:`{${n.slice(0,5).map(([e,t])=>`${X(e,!0)}: ${X(t,!0)}`).join(`, `)}}`+vt(n.length,5,`items`)}return e==null||typeof e==`boolean`||typeof e==`number`?C(e):`<object>`}function yt(e){let t=[],n=0;for(let r of e){let i=r.status===`returned`?`returned ${r.outputPreview??`None`}`:r.status===`denied`?`was denied and did not run`:`did not finish, so it may have applied a partial change`,a=`- ${r.toolName}(${r.inputPreview}) ${i}`;if(n+a.length>2e3){t.push(`- ... and ${String(e.length-t.length)} more not shown`);break}t.push(a),n+=a.length}let r=String(e.length);return`${r} nested tool calls started before execution stopped:\n`+t.join(`
|
|
21
|
-
`)+`\nAccount for all ${r} before retrying; repeating a call repeats whatever it already did.`}function bt(e){return new Ht(e)}var xt=class{sandboxFailure=!0;#e;constructor(e){this.#e=e}get error(){return this.#e}};function Z(e,t){let n=Error(t);return n.name=e,n}function St(e){return e instanceof Error?e.message:String(e)}function Ct(e){let t=e;for(let e=0;e<8&&t instanceof Error;e+=1){if(t instanceof u.MontyError)return t;t=t.cause}}const wt=2e3;function Tt(e){let t=St(e);return t.length>wt?`${t.slice(0,wt)} ... (${String(t.length)} chars total)`:t}function Et(e,t,n){let r=t.at(-1),i=typeof r==`object`&&!!r&&Object.getPrototypeOf(r)===null;if(t.length>+!!i)throw Z(`TypeError`,`${e}() does not accept positional arguments; use keyword arguments`);if(!i)return{};try{return ht(r,n)}catch(t){throw t instanceof mt?Z(`ValueError`,Ot(e,n)):t}}function Dt(e,t){return t===void 0?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[t.get(e)??e,n]))}function Ot(e,t){return`The arguments to ${e}() are more than ${String(t)} bytes of JSON, over the limit for one call.`}function kt(){let e=/* @__PURE__ */ new Map;return(t,n)=>{if(!(n instanceof Map||n instanceof Set))return n;let r=e.get(n);return r===void 0&&(r=n instanceof Map?Object.fromEntries([...n].map(([e,t])=>[String(e),t])):[...n],e.set(n,r)),r}}function At(e){let t=JSON.stringify(e??null,kt());if(t===void 0)throw TypeError(`the result, a ${typeof e==`object`?`value whose toJSON() returns undefined`:typeof e}, has no JSON form`);return t}function jt(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e}async function Q(e,t){if(t.aborted)throw e.catch(()=>void 0),t.reason;return new Promise((n,r)=>{let i=()=>{r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})})}async function Mt(e){return e.aborted?`stopped`:new Promise(t=>{e.addEventListener(`abort`,()=>{t(`stopped`)},{once:!0})})}var Nt=class{free;waiting=[];constructor(e){this.free=e}async acquire(e){if(e.throwIfAborted(),this.free>0){--this.free;return}let t=()=>void 0,n=new Promise(e=>{t=e});this.waiting.push(t);try{await Q(n,e)}catch(e){let n=this.waiting.indexOf(t);throw n===-1?this.release():this.waiting.splice(n,1),e}}release(){let e=this.waiting.shift();e===void 0?this.free+=1:e()}},Pt=class{text=``;bytes=0;truncated=!1;maxBytes;constructor(e){this.maxBytes=e}write=(e,t)=>{if(this.truncated)return;let n=Y(t);if(this.bytes+n<=this.maxBytes){this.text+=t,this.bytes+=n;return}this.text+=Buffer.from(t).subarray(0,this.maxBytes-this.bytes).toString().replace(/�$/u,``),this.truncated=!0};get output(){return this.truncated?`${this.text}\n[printed output cut at ${String(this.maxBytes)} bytes]\n`:this.text}prependTo(e){let t=this.output.replace(/\n+$/u,``);return t===``?e:`[stdout before error]\n${t}\n[/stdout before error]\n${e}`}};function Ft(e){return String(e.timeout/1e3)}var It=class{calls=[];printed;deadline=1/0;callCount=0;budgetExhausted=!1;stopped;controller=new AbortController;timer;id;limits;constructor(e,t){this.id=e,this.limits=t,this.printed=new Pt(t.outputBytes)}start(){this.deadline=Date.now()+this.limits.timeout,this.timer=setTimeout(()=>{this.stop(`deadline`)},this.limits.timeout)}get signal(){return this.controller.signal}stop(e){if(clearTimeout(this.timer),this.stopped!==void 0)return;this.stopped=e;let t=e===`deadline`?`the code passed its ${Ft(this.limits)}-second time limit`:e===`aborted`?`the agent run was aborted`:e===`closed`?`code mode was closed`:`the code had already finished`;this.controller.abort(Z(`TimeoutError`,`Stopped because ${t}.`))}reason(){return this.stopped}startedCalls(){return this.calls.length===0?``:`\n\n${yt(this.calls)}`}};const Lt=/^suspension limit [0-9]+ exceeded$/u,Rt=[`time limit exceeded`,`memory limit exceeded`,`suspension limit `],zt=`The code ran longer than its time limit and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and make the code do less work per call.`,$=`The sandbox session was replaced. Variables, imports and definitions from earlier calls are gone. Recreate any state you need, but do not replay completed side effects.`;function Bt(e){return e.traceback().length===0&&e.display(`msg`).includes(`time limit exceeded`)}function Vt(e){return e.exception.typeName===`MemoryError`&&e.display(`msg`).startsWith(`memory limit exceeded`)}var Ht=class{tools;limits;idleTimeout;pythonNames;schemaArgNames;typeCheckStubs;queue=Promise.resolve();poolPromise;sessionPromise;passedTypeCheck=!1;expired=!1;idleTimer;current;closing;failure;options;traceContext;slots;constructor(e){this.options=e,this.traceContext=c.context.active();let{tools:t,sandboxes:n,idleTimeout:r=3e5}=e;for(let[e,n]of Object.entries(t)){if(typeof n.execute!=`function`)throw Error(`Tool "${e}" has no execute function, so sandbox code cannot call it. Pass it to generateText as a direct tool instead.`);if(n.needsApproval!==void 0)throw Error(`Tool "${e}" sets needsApproval, which code mode cannot enforce. Use the approval option of codeMode() instead.`);if(n.toModelOutput!==void 0)throw Error(`Tool "${e}" sets toModelOutput, which code mode cannot apply: sandbox code receives the result that execute returns. Return only what the model may see from execute, or pass the tool to generateText as a direct tool.`)}if(n===void 0&&[void 0,``].includes(process.env.LOGFIRE_API_KEY))throw Error("Agent sandboxes require a Logfire API key with the `project:execute_agent_sandboxes` scope. Set the LOGFIRE_API_KEY environment variable, or pass `sandboxes` to codeMode().");if(!(r>0))throw RangeError(`idleTimeout must be a positive number of milliseconds or Infinity, not ${String(r)}.`);this.limits=_(e.limits),this.slots=new Nt(this.limits.concurrentToolCalls),this.idleTimeout=r;let i=rt(t);this.typeCheckStubs=i.typeCheckStubs,this.schemaArgNames=i.schemaArgNames,this.pythonNames=new Map(Object.keys(t).map(e=>[e,e]));for(let[e,t]of i.toolNames)this.pythonNames.set(t,e);for(let[e,t]of this.pythonNames)if(ee(t))throw Error(`Tool "${e}" becomes the Python function "${t}", which is a Python builtin, so sandbox code would call the builtin instead. Rename the tool.`);this.tools={run_code:(0,d.tool)({description:ae(i.typeDefinitions,i.functions),inputSchema:(0,d.jsonSchema)({type:`object`,properties:{code:{type:`string`,description:`The Python code to execute in the sandbox.`},restart:{type:`boolean`,description:`Set to true to reset REPL state. When false (default), state is preserved between calls.`}},required:[`code`],additionalProperties:!1},{validate:e=>{let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&(t.restart===void 0||typeof t.restart==`boolean`)?{success:!0,value:{code:t.code,restart:t.restart}}:{success:!1,error:/* @__PURE__ */ TypeError("run_code takes a string `code` and an optional boolean `restart`.")}}}),execute:async(e,t)=>{let n=await this.enqueue(e,t);return n instanceof xt?n:{result:n}},toModelOutput:({output:e})=>{if(e instanceof xt)throw e.error;if(typeof e==`object`&&e&&Object.keys(e).length===1&&`sandboxFailure`in e&&e.sandboxFailure===!0)return{type:`text`,value:`Agent Sandboxes infrastructure failed. This call did not complete; a developer must fix the sandbox before a new run.`};let{result:t}=e;return typeof t==`string`?{type:`text`,value:t}:{type:`json`,value:t}}})}}async close(){return this.closing??=this.shutDown(),this.closing}async closeWhenDone(e){return Promise.resolve(e.finishReason).then(async()=>this.close(),async()=>this.close())}async[Symbol.asyncDispose](){return this.close()}async shutDown(){this.clearIdleTimer(),this.current?.stop(`closed`),await this.queue,await this.releaseSession();let e=this.options.sandboxes===void 0?this.poolPromise:void 0;this.poolPromise=void 0,e!==void 0&&await(await e).close()}async enqueue(e,t){let n=this.queue.then(async()=>this.run(e,t));return this.queue=n.catch(()=>void 0),n}closedError(){return/* @__PURE__ */ Error(`Code mode is closed, so this code did not run.`)}stoppedError(e,t){if(e.stopped===`deadline`)return/* @__PURE__ */ Error(`The code ran longer than its ${Ft(this.limits)}-second time limit, counting time spent waiting on tools, and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and make the code do less work per call.`+e.startedCalls());let n=e.stopped===`aborted`?`The agent run was aborted`:`Code mode was closed`;return t?/* @__PURE__ */ Error(`${n} while this code ran, so tool calls it had not started were stopped.${e.startedCalls()}`):e.stopped===`aborted`?/* @__PURE__ */ Error(`${n}, so this code did not run.`):this.closedError()}async run({code:e,restart:t},n){if(this.closing!==void 0)throw this.closedError();if(this.failure!==void 0)return this.failure;n.abortSignal?.throwIfAborted();let r=Y(e);if(r>this.limits.codeBytes)throw Error(`The code is ${String(r)} bytes, over the ${String(this.limits.codeBytes)}-byte limit for one snippet. Send less code per call; variables and functions from earlier calls are still defined.`);let i=new It(n.toolCallId,this.limits);this.current=i;let a=()=>{i.stop(`aborted`)};n.abortSignal?.addEventListener(`abort`,a,{once:!0}),this.clearIdleTimer();let o=this.expired;this.expired=!1;try{return t===!0&&await this.releaseSession(),await this.feed(e,i,n)}catch(e){throw o&&e instanceof Error?/* @__PURE__ */ Error(`${e.message}\n\nThe sandbox session had no run_code call for ${String(this.idleTimeout/1e3)} seconds and was replaced, so variables, imports and definitions from earlier calls are gone.`):e}finally{i.stop(`finished`),n.abortSignal?.removeEventListener(`abort`,a),this.current=void 0,this.startIdleTimer()}}async failSandbox(e){this.failure=new xt(e);try{await this.options.onError?.({error:e})}catch{return this.failure}return this.failure}async feed(e,t,n,r=!1){let i;try{i=await this.session(t.signal)}catch(e){if(t.stopped!==void 0)throw this.stoppedError(t,!1);return this.failSandbox(e)}if(t.stopped!==void 0)throw t.stopped===`deadline`&&await this.releaseSession(),this.stoppedError(t,!1);let a,o,s,c=!1,l=!1;r||t.start();let d=this.options.typeCheck===`off`||this.options.typeCheck!==`every-snippet`&&this.passedTypeCheck,f=i.feedRun(e,{externalLookup:this.externalLookup(t,n),printCallback:t.printed.write,os:this.osCallback(t),skipTypeCheck:d}).then(e=>({ok:!0,result:e}),e=>({ok:!1,error:e})),p=await Promise.race([f,Mt(t.signal)]);p===`stopped`?(l=!0,this.abandonSession(i,f)):p.ok?(a=p.result,c=!0,this.passedTypeCheck=!0):(o=p.error,s=Ct(o),this.passedTypeCheck||=!(s instanceof u.MontyTypingError||s instanceof u.MontySyntaxError));let m=t.reason();if(m===`closed`||m===`aborted`)throw this.stoppedError(t,!0);if(m===`deadline`){l||await this.releaseSession();let e=s instanceof u.MontyRuntimeError?`Runtime error:\n${t.printed.prependTo(this.cut(s.display(`traceback`)))}\n\n`:``;throw Error(e+this.stoppedError(t,!0).message)}if(!c){if(s instanceof u.MontyShutdown&&!r&&t.callCount===0)return await this.releaseSession(),t.printed=new Pt(this.limits.outputBytes),this.feed(e,t,n,!0);t.stop(`finished`);let i=this.describeFailure(s,t);if((i===void 0||i.reset)&&await this.releaseSession(),i===void 0)return this.failSandbox(o);throw Error(i.message+(r?`\n\n${$}`:``),{cause:o})}let h=this.shapeResult(a,t,r);return r?{result:h,sessionReset:$}:h}shapeResult(e,t,n){let{outputBytes:r}=this.limits,i=/* @__PURE__ */ Error(`The result is more than ${String(r)} bytes of JSON, over the limit for what one snippet returns. The code ran and its variables are still defined, so return a smaller value from them, such as a summary or fewer fields.`+(n?`\n\n${$}`:``)),a;try{a=gt(ht(e,r))}catch(e){throw e instanceof mt?i:e}if(Y(JSON.stringify(a??null))>r)throw i;let o=t.printed.output;return o===``?a??{}:a==null?{output:o}:{output:o,result:a}}cut(e){return _t(e,this.limits.outputBytes)}describeFailure(e,t){let{printed:n}=t;if(e instanceof u.MontySyntaxError)return{message:`Syntax error in code:\n${n.prependTo(this.cut(e.display(`traceback`)))}`,reset:!1};if(e instanceof u.MontyTypingError)return{message:`Type error in code:\n${n.prependTo(this.cut(e.display()))}`,reset:!1};if(e instanceof u.MontyRuntimeError){let r=`Runtime error:\n${n.prependTo(this.cut(e.display(`traceback`)))}`,i=e.display(`msg`);(t.budgetExhausted||Rt.some(e=>i.includes(e)))&&(r+=t.startedCalls());let a=Bt(e),o=Vt(e);a&&(r+=`\n\n${zt}`),o&&(r+=`
|
|
21
|
+
`)+`\nAccount for all ${r} before retrying; repeating a call repeats whatever it already did.`}function bt(e){return new Ht(e)}var xt=class{sandboxFailure=!0;#e;constructor(e){this.#e=e}get error(){return this.#e}};function Z(e,t){let n=Error(t);return n.name=e,n}function St(e){return e instanceof Error?e.message:String(e)}function Ct(e){let t=e;for(let e=0;e<8&&t instanceof Error;e+=1){if(t instanceof u.MontyError)return t;t=t.cause}}const wt=2e3;function Tt(e){let t=St(e);return t.length>wt?`${t.slice(0,wt)} ... (${String(t.length)} chars total)`:t}function Et(e,t,n){let r=t.at(-1),i=typeof r==`object`&&!!r&&Object.getPrototypeOf(r)===null;if(t.length>+!!i)throw Z(`TypeError`,`${e}() does not accept positional arguments; use keyword arguments`);if(!i)return{};try{return ht(r,n)}catch(t){throw t instanceof mt?Z(`ValueError`,Ot(e,n)):t}}function Dt(e,t){return t===void 0?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[t.get(e)??e,n]))}function Ot(e,t){return`The arguments to ${e}() are more than ${String(t)} bytes of JSON, over the limit for one call.`}function kt(){let e=/* @__PURE__ */ new Map;return(t,n)=>{if(!(n instanceof Map||n instanceof Set))return n;let r=e.get(n);return r===void 0&&(r=n instanceof Map?Object.fromEntries([...n].map(([e,t])=>[String(e),t])):[...n],e.set(n,r)),r}}function At(e){let t=JSON.stringify(e??null,kt());if(t===void 0)throw TypeError(`the result, a ${typeof e==`object`?`value whose toJSON() returns undefined`:typeof e}, has no JSON form`);return t}function jt(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e}async function Q(e,t){if(t.aborted)throw e.catch(()=>void 0),t.reason;return new Promise((n,r)=>{let i=()=>{r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})})}async function Mt(e){return e.aborted?`stopped`:new Promise(t=>{e.addEventListener(`abort`,()=>{t(`stopped`)},{once:!0})})}var Nt=class{free;waiting=[];constructor(e){this.free=e}async acquire(e){if(e.throwIfAborted(),this.free>0){--this.free;return}let t=()=>void 0,n=new Promise(e=>{t=e});this.waiting.push(t);try{await Q(n,e)}catch(e){let n=this.waiting.indexOf(t);throw n===-1?this.release():this.waiting.splice(n,1),e}}release(){let e=this.waiting.shift();e===void 0?this.free+=1:e()}},Pt=class{text=``;bytes=0;truncated=!1;maxBytes;constructor(e){this.maxBytes=e}write=(e,t)=>{if(this.truncated)return;let n=Y(t);if(this.bytes+n<=this.maxBytes){this.text+=t,this.bytes+=n;return}this.text+=Buffer.from(t).subarray(0,this.maxBytes-this.bytes).toString().replace(/�$/u,``),this.truncated=!0};get output(){return this.truncated?`${this.text}\n[printed output cut at ${String(this.maxBytes)} bytes]\n`:this.text}prependTo(e){let t=this.output.replace(/\n+$/u,``);return t===``?e:`[stdout before error]\n${t}\n[/stdout before error]\n${e}`}};function Ft(e){return String(e.timeout/1e3)}var It=class{calls=[];printed;deadline=1/0;callCount=0;budgetExhausted=!1;stopped;controller=new AbortController;timer;id;limits;constructor(e,t){this.id=e,this.limits=t,this.printed=new Pt(t.outputBytes)}start(){this.deadline=Date.now()+this.limits.timeout,this.timer=setTimeout(()=>{this.stop(`deadline`)},this.limits.timeout)}get signal(){return this.controller.signal}stop(e){if(clearTimeout(this.timer),this.stopped!==void 0)return;this.stopped=e;let t=e===`deadline`?`the code passed its ${Ft(this.limits)}-second time limit`:e===`aborted`?`the agent run was aborted`:e===`closed`?`code mode was closed`:`the code had already finished`;this.controller.abort(Z(`TimeoutError`,`Stopped because ${t}.`))}reason(){return this.stopped}startedCalls(){return this.calls.length===0?``:`\n\n${yt(this.calls)}`}};const Lt=/^suspension limit [0-9]+ exceeded$/u,Rt=[`time limit exceeded`,`memory limit exceeded`,`suspension limit `],zt=`The code ran longer than its time limit and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and make the code do less work per call.`,$=`The sandbox session was replaced. Variables, imports and definitions from earlier calls are gone. Recreate any state you need, but do not replay completed side effects.`;function Bt(e){return e.traceback().length===0&&e.display(`msg`).includes(`time limit exceeded`)}function Vt(e){return e.exception.typeName===`MemoryError`&&e.display(`msg`).startsWith(`memory limit exceeded`)}var Ht=class{tools;limits;idleTimeout;pythonNames;schemaArgNames;typeCheckStubs;queue=Promise.resolve();poolPromise;sessionPromise;passedTypeCheck=!1;expired=!1;idleTimer;current;closing;failure;options;traceContext;slots;constructor(e){this.options=e,this.traceContext=c.context.active();let{tools:t,sandboxes:n,idleTimeout:r=3e5}=e;for(let[e,n]of Object.entries(t)){if(typeof n.execute!=`function`)throw Error(`Tool "${e}" has no execute function, so sandbox code cannot call it. Pass it to generateText as a direct tool instead.`);if(n.needsApproval!==void 0)throw Error(`Tool "${e}" sets needsApproval, which code mode cannot enforce. Use the approval option of codeMode() instead.`);if(n.toModelOutput!==void 0)throw Error(`Tool "${e}" sets toModelOutput, which code mode cannot apply: sandbox code receives the result that execute returns. Return only what the model may see from execute, or pass the tool to generateText as a direct tool.`)}if(n===void 0&&[void 0,``].includes(process.env.LOGFIRE_API_KEY))throw Error("Agent sandboxes require a Logfire API key with the `project:execute_agent_sandboxes` scope. Set the LOGFIRE_API_KEY environment variable, or pass `sandboxes` to codeMode().");if(!(r>0))throw RangeError(`idleTimeout must be a positive number of milliseconds or Infinity, not ${String(r)}.`);this.limits=_(e.limits),this.slots=new Nt(this.limits.concurrentToolCalls),this.idleTimeout=r;let i=rt(t);this.typeCheckStubs=i.typeCheckStubs,this.schemaArgNames=i.schemaArgNames,this.pythonNames=new Map(Object.keys(t).map(e=>[e,e]));for(let[e,t]of i.toolNames)this.pythonNames.set(t,e);for(let[e,t]of this.pythonNames)if(ee(t))throw Error(`Tool "${e}" becomes the Python function "${t}", which is a Python builtin, so sandbox code would call the builtin instead. Rename the tool.`);this.tools={run_code:(0,d.tool)({description:ae(i.typeDefinitions,i.functions),inputSchema:(0,d.jsonSchema)({type:`object`,properties:{code:{type:`string`,description:`The Python code to execute in the sandbox.`},restart:{type:`boolean`,description:`Set to true to reset REPL state. When false (default), state is preserved between calls.`}},required:[`code`],additionalProperties:!1},{validate:e=>{let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&(t.restart===void 0||typeof t.restart==`boolean`)?{success:!0,value:{code:t.code,restart:t.restart}}:{success:!1,error:/* @__PURE__ */ TypeError("run_code takes a string `code` and an optional boolean `restart`.")}}}),execute:async(e,t)=>{let n=await this.enqueue(e,t);return n instanceof xt?n:{result:n}},toModelOutput:({output:e})=>{if(e instanceof xt)throw e.error;if(typeof e==`object`&&e&&Object.keys(e).length===1&&`sandboxFailure`in e&&e.sandboxFailure===!0)return{type:`text`,value:`Agent Sandboxes infrastructure failed. This call did not complete; a developer must fix the sandbox before a new run.`};let t=typeof e==`object`&&e&&!Array.isArray(e)&&Reflect.ownKeys(e).length===1&&Object.hasOwn(e,`result`)?e.result:e;return typeof t==`string`?{type:`text`,value:t}:{type:`json`,value:t}}})}}async close(){return this.closing??=this.shutDown(),this.closing}async closeWhenDone(e){return Promise.resolve(e.finishReason).then(async()=>this.close(),async()=>this.close())}async[Symbol.asyncDispose](){return this.close()}async shutDown(){this.clearIdleTimer(),this.current?.stop(`closed`),await this.queue,await this.releaseSession();let e=this.options.sandboxes===void 0?this.poolPromise:void 0;this.poolPromise=void 0,e!==void 0&&await(await e).close()}async enqueue(e,t){let n=this.queue.then(async()=>this.run(e,t));return this.queue=n.catch(()=>void 0),n}closedError(){return/* @__PURE__ */ Error(`Code mode is closed, so this code did not run.`)}stoppedError(e,t){if(e.stopped===`deadline`)return/* @__PURE__ */ Error(`The code ran longer than its ${Ft(this.limits)}-second time limit, counting time spent waiting on tools, and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and make the code do less work per call.`+e.startedCalls());let n=e.stopped===`aborted`?`The agent run was aborted`:`Code mode was closed`;return t?/* @__PURE__ */ Error(`${n} while this code ran, so tool calls it had not started were stopped.${e.startedCalls()}`):e.stopped===`aborted`?/* @__PURE__ */ Error(`${n}, so this code did not run.`):this.closedError()}async run({code:e,restart:t},n){if(this.closing!==void 0)throw this.closedError();if(this.failure!==void 0)return this.failure;n.abortSignal?.throwIfAborted();let r=Y(e);if(r>this.limits.codeBytes)throw Error(`The code is ${String(r)} bytes, over the ${String(this.limits.codeBytes)}-byte limit for one snippet. Send less code per call; variables and functions from earlier calls are still defined.`);let i=new It(n.toolCallId,this.limits);this.current=i;let a=()=>{i.stop(`aborted`)};n.abortSignal?.addEventListener(`abort`,a,{once:!0}),this.clearIdleTimer();let o=this.expired;this.expired=!1;try{return t===!0&&await this.releaseSession(),await this.feed(e,i,n)}catch(e){throw o&&e instanceof Error?/* @__PURE__ */ Error(`${e.message}\n\nThe sandbox session had no run_code call for ${String(this.idleTimeout/1e3)} seconds and was replaced, so variables, imports and definitions from earlier calls are gone.`):e}finally{i.stop(`finished`),n.abortSignal?.removeEventListener(`abort`,a),this.current=void 0,this.startIdleTimer()}}async failSandbox(e){this.failure=new xt(e);try{await this.options.onError?.({error:e})}catch{return this.failure}return this.failure}async feed(e,t,n,r=!1){let i;try{i=await this.session(t.signal)}catch(e){if(t.stopped!==void 0)throw this.stoppedError(t,!1);return this.failSandbox(e)}if(t.stopped!==void 0)throw t.stopped===`deadline`&&await this.releaseSession(),this.stoppedError(t,!1);let a,o,s,c=!1,l=!1;r||t.start();let d=this.options.typeCheck===`off`||this.options.typeCheck!==`every-snippet`&&this.passedTypeCheck,f=i.feedRun(e,{externalLookup:this.externalLookup(t,n),printCallback:t.printed.write,os:this.osCallback(t),skipTypeCheck:d}).then(e=>({ok:!0,result:e}),e=>({ok:!1,error:e})),p=await Promise.race([f,Mt(t.signal)]);p===`stopped`?(l=!0,this.abandonSession(i,f)):p.ok?(a=p.result,c=!0,this.passedTypeCheck=!0):(o=p.error,s=Ct(o),this.passedTypeCheck||=!(s instanceof u.MontyTypingError||s instanceof u.MontySyntaxError));let m=t.reason();if(m===`closed`||m===`aborted`)throw this.stoppedError(t,!0);if(m===`deadline`){l||await this.releaseSession();let e=s instanceof u.MontyRuntimeError?`Runtime error:\n${t.printed.prependTo(this.cut(s.display(`traceback`)))}\n\n`:``;throw Error(e+this.stoppedError(t,!0).message)}if(!c){if(s instanceof u.MontyShutdown&&!r&&t.callCount===0)return await this.releaseSession(),t.printed=new Pt(this.limits.outputBytes),this.feed(e,t,n,!0);t.stop(`finished`);let i=this.describeFailure(s,t);if((i===void 0||i.reset)&&await this.releaseSession(),i===void 0)return this.failSandbox(o);throw Error(i.message+(r?`\n\n${$}`:``),{cause:o})}let h=this.shapeResult(a,t,r);return r?{result:h,sessionReset:$}:h}shapeResult(e,t,n){let{outputBytes:r}=this.limits,i=/* @__PURE__ */ Error(`The result is more than ${String(r)} bytes of JSON, over the limit for what one snippet returns. The code ran and its variables are still defined, so return a smaller value from them, such as a summary or fewer fields.`+(n?`\n\n${$}`:``)),a;try{a=gt(ht(e,r))}catch(e){throw e instanceof mt?i:e}if(Y(JSON.stringify(a??null))>r)throw i;let o=t.printed.output;return o===``?a??{}:a==null?{output:o}:{output:o,result:a}}cut(e){return _t(e,this.limits.outputBytes)}describeFailure(e,t){let{printed:n}=t;if(e instanceof u.MontySyntaxError)return{message:`Syntax error in code:\n${n.prependTo(this.cut(e.display(`traceback`)))}`,reset:!1};if(e instanceof u.MontyTypingError)return{message:`Type error in code:\n${n.prependTo(this.cut(e.display()))}`,reset:!1};if(e instanceof u.MontyRuntimeError){let r=`Runtime error:\n${n.prependTo(this.cut(e.display(`traceback`)))}`,i=e.display(`msg`);(t.budgetExhausted||Rt.some(e=>i.includes(e)))&&(r+=t.startedCalls());let a=Bt(e),o=Vt(e);a&&(r+=`\n\n${zt}`),o&&(r+=`
|
|
22
22
|
|
|
23
23
|
The code ran out of memory and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and keep less data in memory at once.`);let s=a||o;return e.exception.typeName===`RuntimeError`&&Lt.test(i)&&(r+=`
|
|
24
24
|
|
package/dist/index.js
CHANGED
|
@@ -18,7 +18,7 @@ from typing import Any, TypedDict, NotRequired, Literal`,at=new Set(it.split(`
|
|
|
18
18
|
`).flatMap(e=>e.replace(/^(?:from \S+ )?import /u,``).split(`, `)));function ot(e){let{functions:t,toolNames:n}=st(e),r=/* @__PURE__ */ new Map;for(let e of t){let t=e.parametersSchema.properties,n=typeof t==`object`&&t&&!Array.isArray(t)?Object.keys(t):[],i=new Map([...Ie(n)].filter(([e,t])=>t!==e).map(([e,t])=>[t,e]));i.size>0&&r.set(e.name,i)}return{...ct(t),toolNames:n,schemaArgNames:r}}function st(e){let t=[],n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map;for(let[i,a]of Object.entries(e)){let e=lt(i);if(e===`run_code`)throw Error(`Tool "${i}" becomes the Python function "${e}", which code mode reserves for itself. Rename the tool.`);if(at.has(e))throw Error(`Tool "${i}" becomes the Python function "${e}", which the type-check stubs import, so the function would replace that import. Rename the tool.`);let o=r.get(e);if(o!==void 0)throw Error(`Tools "${o}" and "${i}" both become the Python function "${e}". Rename one of them.`);r.set(e,i),e!==i&&n.set(e,i);let s=a.outputSchema===void 0?void 0:ft(i,a);if(s===void 0&&ht(i,a),typeof a.description==`function`)throw Error(`Tool "${i}" has a description that depends on its context, which code mode cannot render yet`);t.push({name:e,description:a.description,parametersSchema:Je(ut(i,a),e,`parameters`),returnSchema:s===void 0?void 0:Je(s,e,`return`)})}return{functions:t,toolNames:n}}function ct(e){let t=e.map(e=>({f:e,sig:N.fromSchema(e.name,e.parametersSchema,e.returnSchema)})),n=t.map(({sig:e})=>e),r=N.getConflictingTypeNames(n),i=N.prefixedTypeNames(n,r),a=N.renderTypeDefinitions(n,r),o=e=>t.map(({f:t,sig:n})=>n.render(e,{name:t.name,description:t.description,isAsync:!0,conflictingTypeNames:r,typeNames:i}));return{typeDefinitions:a,functions:o(`...`),typeCheckStubs:[it,...a,...o(`raise NotImplementedError()`)].join(`
|
|
19
19
|
|
|
20
20
|
`)}}function lt(e){return ve(e)}function ut(e,t){return J(e,d(t.inputSchema).jsonSchema)}function dt(e){let t=(e?.[`~standard`])?.jsonSchema?.output;return typeof t==`function`?t:void 0}function ft(e,t){let n=dt(t.outputSchema);return n===void 0?J(e,d(t.outputSchema).jsonSchema):J(e,n({target:`draft-07`}))}function pt(e){return typeof e.then==`function`}function J(e,t){if(pt(t))throw Promise.resolve(t).catch(()=>void 0),Error(`Tool "${e}" has a schema that converts to JSON Schema asynchronously, which code mode does not support`);return t}const mt=/* @__PURE__ */ new WeakSet;function ht(e,t){mt.has(t)||(mt.add(t),console.warn(`Tool "${e}" has no outputSchema, so code mode shows its return type as Any. Add an outputSchema so that the model knows the shape of its result.`))}var Y=class extends Error{maxBytes;constructor(e){super(`The value is more than ${String(e)} bytes of JSON.`),this.maxBytes=e}};function gt(e,t){let n=t,r=e=>{if(n-=e,n<0)throw new Y(t)},i=e=>{r(2);let t={};for(let[n,i]of e){let e=String(n);r(X(e)+4),Object.defineProperty(t,e,{value:a(i),enumerable:!0,writable:!0,configurable:!0})}return t},a=e=>{if(e instanceof Map)return i(e);if(e instanceof Set||Array.isArray(e)){r(2);let t=[];for(let n of e)r(1),t.push(a(n));return t}if(typeof e==`bigint`){let t=e.toString();return r(t.length),Number.isSafeInteger(Number(e))?Number(e):t}return e instanceof Uint8Array?(r(e.length+2),Buffer.from(e).toString(`latin1`)):typeof e==`string`?(r(X(e)+2),e):typeof e==`object`&&e?i(Object.entries(e)):(r(typeof e==`number`?String(e).length:5),e)};return a(e)}function _t(e){return typeof e==`number`&&!Number.isFinite(e)?Number.isNaN(e)?`nan`:e>0?`inf`:`-inf`:Array.isArray(e)?e.map(_t):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,_t(t)])):e}function vt(e,t){let n=X(e);if(n<=t)return e;let r=Buffer.from(e),i=Math.floor(t/2),a=r.subarray(0,i).toString().replace(/\uFFFD$/u,``),o=r.subarray(n-i).toString().replace(/^\uFFFD/u,``);return`${a}\n... (${String(n-2*i)} of ${String(n)} bytes cut) ...\n${o}`}function X(e){return Buffer.byteLength(e,`utf8`)}function yt(e,t,n){return e>t?` ... (${String(e)} ${n} total)`:``}function Z(e,t=!1){if(typeof e==`string`)return x(e.slice(0,120))+yt(e.length,120,`chars`);if(Array.isArray(e))return t?`[${String(e.length)} items]`:`[${e.slice(0,5).map(e=>Z(e,!0)).join(`, `)}]`+yt(e.length,5,`items`);if(typeof e==`object`&&e){let n=Object.entries(e);return t?`{${String(n.length)} items}`:`{${n.slice(0,5).map(([e,t])=>`${Z(e,!0)}: ${Z(t,!0)}`).join(`, `)}}`+yt(n.length,5,`items`)}return e==null||typeof e==`boolean`||typeof e==`number`?x(e):`<object>`}function bt(e){let t=[],n=0;for(let r of e){let i=r.status===`returned`?`returned ${r.outputPreview??`None`}`:r.status===`denied`?`was denied and did not run`:`did not finish, so it may have applied a partial change`,a=`- ${r.toolName}(${r.inputPreview}) ${i}`;if(n+a.length>2e3){t.push(`- ... and ${String(e.length-t.length)} more not shown`);break}t.push(a),n+=a.length}let r=String(e.length);return`${r} nested tool calls started before execution stopped:\n`+t.join(`
|
|
21
|
-
`)+`\nAccount for all ${r} before retrying; repeating a call repeats whatever it already did.`}function xt(e){return new Wt(e)}var St=class{sandboxFailure=!0;#e;constructor(e){this.#e=e}get error(){return this.#e}};function Q(e,t){let n=Error(t);return n.name=e,n}function Ct(e){return e instanceof Error?e.message:String(e)}function wt(e){let t=e;for(let e=0;e<8&&t instanceof Error;e+=1){if(t instanceof i)return t;t=t.cause}}const Tt=2e3;function Et(e){let t=Ct(e);return t.length>Tt?`${t.slice(0,Tt)} ... (${String(t.length)} chars total)`:t}function Dt(e,t,n){let r=t.at(-1),i=typeof r==`object`&&!!r&&Object.getPrototypeOf(r)===null;if(t.length>+!!i)throw Q(`TypeError`,`${e}() does not accept positional arguments; use keyword arguments`);if(!i)return{};try{return gt(r,n)}catch(t){throw t instanceof Y?Q(`ValueError`,kt(e,n)):t}}function Ot(e,t){return t===void 0?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[t.get(e)??e,n]))}function kt(e,t){return`The arguments to ${e}() are more than ${String(t)} bytes of JSON, over the limit for one call.`}function At(){let e=/* @__PURE__ */ new Map;return(t,n)=>{if(!(n instanceof Map||n instanceof Set))return n;let r=e.get(n);return r===void 0&&(r=n instanceof Map?Object.fromEntries([...n].map(([e,t])=>[String(e),t])):[...n],e.set(n,r)),r}}function jt(e){let t=JSON.stringify(e??null,At());if(t===void 0)throw TypeError(`the result, a ${typeof e==`object`?`value whose toJSON() returns undefined`:typeof e}, has no JSON form`);return t}function Mt(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e}async function $(e,t){if(t.aborted)throw e.catch(()=>void 0),t.reason;return new Promise((n,r)=>{let i=()=>{r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})})}async function Nt(e){return e.aborted?`stopped`:new Promise(t=>{e.addEventListener(`abort`,()=>{t(`stopped`)},{once:!0})})}var Pt=class{free;waiting=[];constructor(e){this.free=e}async acquire(e){if(e.throwIfAborted(),this.free>0){--this.free;return}let t=()=>void 0,n=new Promise(e=>{t=e});this.waiting.push(t);try{await $(n,e)}catch(e){let n=this.waiting.indexOf(t);throw n===-1?this.release():this.waiting.splice(n,1),e}}release(){let e=this.waiting.shift();e===void 0?this.free+=1:e()}},Ft=class{text=``;bytes=0;truncated=!1;maxBytes;constructor(e){this.maxBytes=e}write=(e,t)=>{if(this.truncated)return;let n=X(t);if(this.bytes+n<=this.maxBytes){this.text+=t,this.bytes+=n;return}this.text+=Buffer.from(t).subarray(0,this.maxBytes-this.bytes).toString().replace(/�$/u,``),this.truncated=!0};get output(){return this.truncated?`${this.text}\n[printed output cut at ${String(this.maxBytes)} bytes]\n`:this.text}prependTo(e){let t=this.output.replace(/\n+$/u,``);return t===``?e:`[stdout before error]\n${t}\n[/stdout before error]\n${e}`}};function It(e){return String(e.timeout/1e3)}var Lt=class{calls=[];printed;deadline=1/0;callCount=0;budgetExhausted=!1;stopped;controller=new AbortController;timer;id;limits;constructor(e,t){this.id=e,this.limits=t,this.printed=new Ft(t.outputBytes)}start(){this.deadline=Date.now()+this.limits.timeout,this.timer=setTimeout(()=>{this.stop(`deadline`)},this.limits.timeout)}get signal(){return this.controller.signal}stop(e){if(clearTimeout(this.timer),this.stopped!==void 0)return;this.stopped=e;let t=e===`deadline`?`the code passed its ${It(this.limits)}-second time limit`:e===`aborted`?`the agent run was aborted`:e===`closed`?`code mode was closed`:`the code had already finished`;this.controller.abort(Q(`TimeoutError`,`Stopped because ${t}.`))}reason(){return this.stopped}startedCalls(){return this.calls.length===0?``:`\n\n${bt(this.calls)}`}};const Rt=/^suspension limit [0-9]+ exceeded$/u,zt=[`time limit exceeded`,`memory limit exceeded`,`suspension limit `],Bt=`The code ran longer than its time limit and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and make the code do less work per call.`,Vt=`The sandbox session was replaced. Variables, imports and definitions from earlier calls are gone. Recreate any state you need, but do not replay completed side effects.`;function Ht(e){return e.traceback().length===0&&e.display(`msg`).includes(`time limit exceeded`)}function Ut(e){return e.exception.typeName===`MemoryError`&&e.display(`msg`).startsWith(`memory limit exceeded`)}var Wt=class{tools;limits;idleTimeout;pythonNames;schemaArgNames;typeCheckStubs;queue=Promise.resolve();poolPromise;sessionPromise;passedTypeCheck=!1;expired=!1;idleTimer;current;closing;failure;options;traceContext;slots;constructor(t){this.options=t,this.traceContext=e.active();let{tools:n,sandboxes:r,idleTimeout:i=3e5}=t;for(let[e,t]of Object.entries(n)){if(typeof t.execute!=`function`)throw Error(`Tool "${e}" has no execute function, so sandbox code cannot call it. Pass it to generateText as a direct tool instead.`);if(t.needsApproval!==void 0)throw Error(`Tool "${e}" sets needsApproval, which code mode cannot enforce. Use the approval option of codeMode() instead.`);if(t.toModelOutput!==void 0)throw Error(`Tool "${e}" sets toModelOutput, which code mode cannot apply: sandbox code receives the result that execute returns. Return only what the model may see from execute, or pass the tool to generateText as a direct tool.`)}if(r===void 0&&[void 0,``].includes(process.env.LOGFIRE_API_KEY))throw Error("Agent sandboxes require a Logfire API key with the `project:execute_agent_sandboxes` scope. Set the LOGFIRE_API_KEY environment variable, or pass `sandboxes` to codeMode().");if(!(i>0))throw RangeError(`idleTimeout must be a positive number of milliseconds or Infinity, not ${String(i)}.`);this.limits=v(t.limits),this.slots=new Pt(this.limits.concurrentToolCalls),this.idleTimeout=i;let a=ot(n);this.typeCheckStubs=a.typeCheckStubs,this.schemaArgNames=a.schemaArgNames,this.pythonNames=new Map(Object.keys(n).map(e=>[e,e]));for(let[e,t]of a.toolNames)this.pythonNames.set(t,e);for(let[e,t]of this.pythonNames)if(ie(t))throw Error(`Tool "${e}" becomes the Python function "${t}", which is a Python builtin, so sandbox code would call the builtin instead. Rename the tool.`);this.tools={run_code:p({description:le(a.typeDefinitions,a.functions),inputSchema:f({type:`object`,properties:{code:{type:`string`,description:`The Python code to execute in the sandbox.`},restart:{type:`boolean`,description:`Set to true to reset REPL state. When false (default), state is preserved between calls.`}},required:[`code`],additionalProperties:!1},{validate:e=>{let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&(t.restart===void 0||typeof t.restart==`boolean`)?{success:!0,value:{code:t.code,restart:t.restart}}:{success:!1,error:/* @__PURE__ */ TypeError("run_code takes a string `code` and an optional boolean `restart`.")}}}),execute:async(e,t)=>{let n=await this.enqueue(e,t);return n instanceof St?n:{result:n}},toModelOutput:({output:e})=>{if(e instanceof St)throw e.error;if(typeof e==`object`&&e&&Object.keys(e).length===1&&`sandboxFailure`in e&&e.sandboxFailure===!0)return{type:`text`,value:`Agent Sandboxes infrastructure failed. This call did not complete; a developer must fix the sandbox before a new run.`};let{result:t}=e;return typeof t==`string`?{type:`text`,value:t}:{type:`json`,value:t}}})}}async close(){return this.closing??=this.shutDown(),this.closing}async closeWhenDone(e){return Promise.resolve(e.finishReason).then(async()=>this.close(),async()=>this.close())}async[Symbol.asyncDispose](){return this.close()}async shutDown(){this.clearIdleTimer(),this.current?.stop(`closed`),await this.queue,await this.releaseSession();let e=this.options.sandboxes===void 0?this.poolPromise:void 0;this.poolPromise=void 0,e!==void 0&&await(await e).close()}async enqueue(e,t){let n=this.queue.then(async()=>this.run(e,t));return this.queue=n.catch(()=>void 0),n}closedError(){return/* @__PURE__ */ Error(`Code mode is closed, so this code did not run.`)}stoppedError(e,t){if(e.stopped===`deadline`)return/* @__PURE__ */ Error(`The code ran longer than its ${It(this.limits)}-second time limit, counting time spent waiting on tools, and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and make the code do less work per call.`+e.startedCalls());let n=e.stopped===`aborted`?`The agent run was aborted`:`Code mode was closed`;return t?/* @__PURE__ */ Error(`${n} while this code ran, so tool calls it had not started were stopped.${e.startedCalls()}`):e.stopped===`aborted`?/* @__PURE__ */ Error(`${n}, so this code did not run.`):this.closedError()}async run({code:e,restart:t},n){if(this.closing!==void 0)throw this.closedError();if(this.failure!==void 0)return this.failure;n.abortSignal?.throwIfAborted();let r=X(e);if(r>this.limits.codeBytes)throw Error(`The code is ${String(r)} bytes, over the ${String(this.limits.codeBytes)}-byte limit for one snippet. Send less code per call; variables and functions from earlier calls are still defined.`);let i=new Lt(n.toolCallId,this.limits);this.current=i;let a=()=>{i.stop(`aborted`)};n.abortSignal?.addEventListener(`abort`,a,{once:!0}),this.clearIdleTimer();let o=this.expired;this.expired=!1;try{return t===!0&&await this.releaseSession(),await this.feed(e,i,n)}catch(e){throw o&&e instanceof Error?/* @__PURE__ */ Error(`${e.message}\n\nThe sandbox session had no run_code call for ${String(this.idleTimeout/1e3)} seconds and was replaced, so variables, imports and definitions from earlier calls are gone.`):e}finally{i.stop(`finished`),n.abortSignal?.removeEventListener(`abort`,a),this.current=void 0,this.startIdleTimer()}}async failSandbox(e){this.failure=new St(e);try{await this.options.onError?.({error:e})}catch{return this.failure}return this.failure}async feed(e,t,n,r=!1){let i;try{i=await this.session(t.signal)}catch(e){if(t.stopped!==void 0)throw this.stoppedError(t,!1);return this.failSandbox(e)}if(t.stopped!==void 0)throw t.stopped===`deadline`&&await this.releaseSession(),this.stoppedError(t,!1);let a,u,d,f=!1,p=!1;r||t.start();let ee=this.options.typeCheck===`off`||this.options.typeCheck!==`every-snippet`&&this.passedTypeCheck,m=i.feedRun(e,{externalLookup:this.externalLookup(t,n),printCallback:t.printed.write,os:this.osCallback(t),skipTypeCheck:ee}).then(e=>({ok:!0,result:e}),e=>({ok:!1,error:e})),h=await Promise.race([m,Nt(t.signal)]);h===`stopped`?(p=!0,this.abandonSession(i,m)):h.ok?(a=h.result,f=!0,this.passedTypeCheck=!0):(u=h.error,d=wt(u),this.passedTypeCheck||=!(d instanceof l||d instanceof c));let g=t.reason();if(g===`closed`||g===`aborted`)throw this.stoppedError(t,!0);if(g===`deadline`){p||await this.releaseSession();let e=d instanceof o?`Runtime error:\n${t.printed.prependTo(this.cut(d.display(`traceback`)))}\n\n`:``;throw Error(e+this.stoppedError(t,!0).message)}if(!f){if(d instanceof s&&!r&&t.callCount===0)return await this.releaseSession(),t.printed=new Ft(this.limits.outputBytes),this.feed(e,t,n,!0);t.stop(`finished`);let i=this.describeFailure(d,t);if((i===void 0||i.reset)&&await this.releaseSession(),i===void 0)return this.failSandbox(u);throw Error(i.message+(r?`\n\n${Vt}`:``),{cause:u})}let _=this.shapeResult(a,t,r);return r?{result:_,sessionReset:Vt}:_}shapeResult(e,t,n){let{outputBytes:r}=this.limits,i=/* @__PURE__ */ Error(`The result is more than ${String(r)} bytes of JSON, over the limit for what one snippet returns. The code ran and its variables are still defined, so return a smaller value from them, such as a summary or fewer fields.`+(n?`\n\n${Vt}`:``)),a;try{a=_t(gt(e,r))}catch(e){throw e instanceof Y?i:e}if(X(JSON.stringify(a??null))>r)throw i;let o=t.printed.output;return o===``?a??{}:a==null?{output:o}:{output:o,result:a}}cut(e){return vt(e,this.limits.outputBytes)}describeFailure(e,t){let{printed:i}=t;if(e instanceof c)return{message:`Syntax error in code:\n${i.prependTo(this.cut(e.display(`traceback`)))}`,reset:!1};if(e instanceof l)return{message:`Type error in code:\n${i.prependTo(this.cut(e.display()))}`,reset:!1};if(e instanceof o){let n=`Runtime error:\n${i.prependTo(this.cut(e.display(`traceback`)))}`,r=e.display(`msg`);(t.budgetExhausted||zt.some(e=>r.includes(e)))&&(n+=t.startedCalls());let a=Ht(e),o=Ut(e);a&&(n+=`\n\n${Bt}`),o&&(n+=`
|
|
21
|
+
`)+`\nAccount for all ${r} before retrying; repeating a call repeats whatever it already did.`}function xt(e){return new Wt(e)}var St=class{sandboxFailure=!0;#e;constructor(e){this.#e=e}get error(){return this.#e}};function Q(e,t){let n=Error(t);return n.name=e,n}function Ct(e){return e instanceof Error?e.message:String(e)}function wt(e){let t=e;for(let e=0;e<8&&t instanceof Error;e+=1){if(t instanceof i)return t;t=t.cause}}const Tt=2e3;function Et(e){let t=Ct(e);return t.length>Tt?`${t.slice(0,Tt)} ... (${String(t.length)} chars total)`:t}function Dt(e,t,n){let r=t.at(-1),i=typeof r==`object`&&!!r&&Object.getPrototypeOf(r)===null;if(t.length>+!!i)throw Q(`TypeError`,`${e}() does not accept positional arguments; use keyword arguments`);if(!i)return{};try{return gt(r,n)}catch(t){throw t instanceof Y?Q(`ValueError`,kt(e,n)):t}}function Ot(e,t){return t===void 0?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[t.get(e)??e,n]))}function kt(e,t){return`The arguments to ${e}() are more than ${String(t)} bytes of JSON, over the limit for one call.`}function At(){let e=/* @__PURE__ */ new Map;return(t,n)=>{if(!(n instanceof Map||n instanceof Set))return n;let r=e.get(n);return r===void 0&&(r=n instanceof Map?Object.fromEntries([...n].map(([e,t])=>[String(e),t])):[...n],e.set(n,r)),r}}function jt(e){let t=JSON.stringify(e??null,At());if(t===void 0)throw TypeError(`the result, a ${typeof e==`object`?`value whose toJSON() returns undefined`:typeof e}, has no JSON form`);return t}function Mt(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e}async function $(e,t){if(t.aborted)throw e.catch(()=>void 0),t.reason;return new Promise((n,r)=>{let i=()=>{r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})})}async function Nt(e){return e.aborted?`stopped`:new Promise(t=>{e.addEventListener(`abort`,()=>{t(`stopped`)},{once:!0})})}var Pt=class{free;waiting=[];constructor(e){this.free=e}async acquire(e){if(e.throwIfAborted(),this.free>0){--this.free;return}let t=()=>void 0,n=new Promise(e=>{t=e});this.waiting.push(t);try{await $(n,e)}catch(e){let n=this.waiting.indexOf(t);throw n===-1?this.release():this.waiting.splice(n,1),e}}release(){let e=this.waiting.shift();e===void 0?this.free+=1:e()}},Ft=class{text=``;bytes=0;truncated=!1;maxBytes;constructor(e){this.maxBytes=e}write=(e,t)=>{if(this.truncated)return;let n=X(t);if(this.bytes+n<=this.maxBytes){this.text+=t,this.bytes+=n;return}this.text+=Buffer.from(t).subarray(0,this.maxBytes-this.bytes).toString().replace(/�$/u,``),this.truncated=!0};get output(){return this.truncated?`${this.text}\n[printed output cut at ${String(this.maxBytes)} bytes]\n`:this.text}prependTo(e){let t=this.output.replace(/\n+$/u,``);return t===``?e:`[stdout before error]\n${t}\n[/stdout before error]\n${e}`}};function It(e){return String(e.timeout/1e3)}var Lt=class{calls=[];printed;deadline=1/0;callCount=0;budgetExhausted=!1;stopped;controller=new AbortController;timer;id;limits;constructor(e,t){this.id=e,this.limits=t,this.printed=new Ft(t.outputBytes)}start(){this.deadline=Date.now()+this.limits.timeout,this.timer=setTimeout(()=>{this.stop(`deadline`)},this.limits.timeout)}get signal(){return this.controller.signal}stop(e){if(clearTimeout(this.timer),this.stopped!==void 0)return;this.stopped=e;let t=e===`deadline`?`the code passed its ${It(this.limits)}-second time limit`:e===`aborted`?`the agent run was aborted`:e===`closed`?`code mode was closed`:`the code had already finished`;this.controller.abort(Q(`TimeoutError`,`Stopped because ${t}.`))}reason(){return this.stopped}startedCalls(){return this.calls.length===0?``:`\n\n${bt(this.calls)}`}};const Rt=/^suspension limit [0-9]+ exceeded$/u,zt=[`time limit exceeded`,`memory limit exceeded`,`suspension limit `],Bt=`The code ran longer than its time limit and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and make the code do less work per call.`,Vt=`The sandbox session was replaced. Variables, imports and definitions from earlier calls are gone. Recreate any state you need, but do not replay completed side effects.`;function Ht(e){return e.traceback().length===0&&e.display(`msg`).includes(`time limit exceeded`)}function Ut(e){return e.exception.typeName===`MemoryError`&&e.display(`msg`).startsWith(`memory limit exceeded`)}var Wt=class{tools;limits;idleTimeout;pythonNames;schemaArgNames;typeCheckStubs;queue=Promise.resolve();poolPromise;sessionPromise;passedTypeCheck=!1;expired=!1;idleTimer;current;closing;failure;options;traceContext;slots;constructor(t){this.options=t,this.traceContext=e.active();let{tools:n,sandboxes:r,idleTimeout:i=3e5}=t;for(let[e,t]of Object.entries(n)){if(typeof t.execute!=`function`)throw Error(`Tool "${e}" has no execute function, so sandbox code cannot call it. Pass it to generateText as a direct tool instead.`);if(t.needsApproval!==void 0)throw Error(`Tool "${e}" sets needsApproval, which code mode cannot enforce. Use the approval option of codeMode() instead.`);if(t.toModelOutput!==void 0)throw Error(`Tool "${e}" sets toModelOutput, which code mode cannot apply: sandbox code receives the result that execute returns. Return only what the model may see from execute, or pass the tool to generateText as a direct tool.`)}if(r===void 0&&[void 0,``].includes(process.env.LOGFIRE_API_KEY))throw Error("Agent sandboxes require a Logfire API key with the `project:execute_agent_sandboxes` scope. Set the LOGFIRE_API_KEY environment variable, or pass `sandboxes` to codeMode().");if(!(i>0))throw RangeError(`idleTimeout must be a positive number of milliseconds or Infinity, not ${String(i)}.`);this.limits=v(t.limits),this.slots=new Pt(this.limits.concurrentToolCalls),this.idleTimeout=i;let a=ot(n);this.typeCheckStubs=a.typeCheckStubs,this.schemaArgNames=a.schemaArgNames,this.pythonNames=new Map(Object.keys(n).map(e=>[e,e]));for(let[e,t]of a.toolNames)this.pythonNames.set(t,e);for(let[e,t]of this.pythonNames)if(ie(t))throw Error(`Tool "${e}" becomes the Python function "${t}", which is a Python builtin, so sandbox code would call the builtin instead. Rename the tool.`);this.tools={run_code:p({description:le(a.typeDefinitions,a.functions),inputSchema:f({type:`object`,properties:{code:{type:`string`,description:`The Python code to execute in the sandbox.`},restart:{type:`boolean`,description:`Set to true to reset REPL state. When false (default), state is preserved between calls.`}},required:[`code`],additionalProperties:!1},{validate:e=>{let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&(t.restart===void 0||typeof t.restart==`boolean`)?{success:!0,value:{code:t.code,restart:t.restart}}:{success:!1,error:/* @__PURE__ */ TypeError("run_code takes a string `code` and an optional boolean `restart`.")}}}),execute:async(e,t)=>{let n=await this.enqueue(e,t);return n instanceof St?n:{result:n}},toModelOutput:({output:e})=>{if(e instanceof St)throw e.error;if(typeof e==`object`&&e&&Object.keys(e).length===1&&`sandboxFailure`in e&&e.sandboxFailure===!0)return{type:`text`,value:`Agent Sandboxes infrastructure failed. This call did not complete; a developer must fix the sandbox before a new run.`};let t=typeof e==`object`&&e&&!Array.isArray(e)&&Reflect.ownKeys(e).length===1&&Object.hasOwn(e,`result`)?e.result:e;return typeof t==`string`?{type:`text`,value:t}:{type:`json`,value:t}}})}}async close(){return this.closing??=this.shutDown(),this.closing}async closeWhenDone(e){return Promise.resolve(e.finishReason).then(async()=>this.close(),async()=>this.close())}async[Symbol.asyncDispose](){return this.close()}async shutDown(){this.clearIdleTimer(),this.current?.stop(`closed`),await this.queue,await this.releaseSession();let e=this.options.sandboxes===void 0?this.poolPromise:void 0;this.poolPromise=void 0,e!==void 0&&await(await e).close()}async enqueue(e,t){let n=this.queue.then(async()=>this.run(e,t));return this.queue=n.catch(()=>void 0),n}closedError(){return/* @__PURE__ */ Error(`Code mode is closed, so this code did not run.`)}stoppedError(e,t){if(e.stopped===`deadline`)return/* @__PURE__ */ Error(`The code ran longer than its ${It(this.limits)}-second time limit, counting time spent waiting on tools, and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and make the code do less work per call.`+e.startedCalls());let n=e.stopped===`aborted`?`The agent run was aborted`:`Code mode was closed`;return t?/* @__PURE__ */ Error(`${n} while this code ran, so tool calls it had not started were stopped.${e.startedCalls()}`):e.stopped===`aborted`?/* @__PURE__ */ Error(`${n}, so this code did not run.`):this.closedError()}async run({code:e,restart:t},n){if(this.closing!==void 0)throw this.closedError();if(this.failure!==void 0)return this.failure;n.abortSignal?.throwIfAborted();let r=X(e);if(r>this.limits.codeBytes)throw Error(`The code is ${String(r)} bytes, over the ${String(this.limits.codeBytes)}-byte limit for one snippet. Send less code per call; variables and functions from earlier calls are still defined.`);let i=new Lt(n.toolCallId,this.limits);this.current=i;let a=()=>{i.stop(`aborted`)};n.abortSignal?.addEventListener(`abort`,a,{once:!0}),this.clearIdleTimer();let o=this.expired;this.expired=!1;try{return t===!0&&await this.releaseSession(),await this.feed(e,i,n)}catch(e){throw o&&e instanceof Error?/* @__PURE__ */ Error(`${e.message}\n\nThe sandbox session had no run_code call for ${String(this.idleTimeout/1e3)} seconds and was replaced, so variables, imports and definitions from earlier calls are gone.`):e}finally{i.stop(`finished`),n.abortSignal?.removeEventListener(`abort`,a),this.current=void 0,this.startIdleTimer()}}async failSandbox(e){this.failure=new St(e);try{await this.options.onError?.({error:e})}catch{return this.failure}return this.failure}async feed(e,t,n,r=!1){let i;try{i=await this.session(t.signal)}catch(e){if(t.stopped!==void 0)throw this.stoppedError(t,!1);return this.failSandbox(e)}if(t.stopped!==void 0)throw t.stopped===`deadline`&&await this.releaseSession(),this.stoppedError(t,!1);let a,u,d,f=!1,p=!1;r||t.start();let ee=this.options.typeCheck===`off`||this.options.typeCheck!==`every-snippet`&&this.passedTypeCheck,m=i.feedRun(e,{externalLookup:this.externalLookup(t,n),printCallback:t.printed.write,os:this.osCallback(t),skipTypeCheck:ee}).then(e=>({ok:!0,result:e}),e=>({ok:!1,error:e})),h=await Promise.race([m,Nt(t.signal)]);h===`stopped`?(p=!0,this.abandonSession(i,m)):h.ok?(a=h.result,f=!0,this.passedTypeCheck=!0):(u=h.error,d=wt(u),this.passedTypeCheck||=!(d instanceof l||d instanceof c));let g=t.reason();if(g===`closed`||g===`aborted`)throw this.stoppedError(t,!0);if(g===`deadline`){p||await this.releaseSession();let e=d instanceof o?`Runtime error:\n${t.printed.prependTo(this.cut(d.display(`traceback`)))}\n\n`:``;throw Error(e+this.stoppedError(t,!0).message)}if(!f){if(d instanceof s&&!r&&t.callCount===0)return await this.releaseSession(),t.printed=new Ft(this.limits.outputBytes),this.feed(e,t,n,!0);t.stop(`finished`);let i=this.describeFailure(d,t);if((i===void 0||i.reset)&&await this.releaseSession(),i===void 0)return this.failSandbox(u);throw Error(i.message+(r?`\n\n${Vt}`:``),{cause:u})}let _=this.shapeResult(a,t,r);return r?{result:_,sessionReset:Vt}:_}shapeResult(e,t,n){let{outputBytes:r}=this.limits,i=/* @__PURE__ */ Error(`The result is more than ${String(r)} bytes of JSON, over the limit for what one snippet returns. The code ran and its variables are still defined, so return a smaller value from them, such as a summary or fewer fields.`+(n?`\n\n${Vt}`:``)),a;try{a=_t(gt(e,r))}catch(e){throw e instanceof Y?i:e}if(X(JSON.stringify(a??null))>r)throw i;let o=t.printed.output;return o===``?a??{}:a==null?{output:o}:{output:o,result:a}}cut(e){return vt(e,this.limits.outputBytes)}describeFailure(e,t){let{printed:i}=t;if(e instanceof c)return{message:`Syntax error in code:\n${i.prependTo(this.cut(e.display(`traceback`)))}`,reset:!1};if(e instanceof l)return{message:`Type error in code:\n${i.prependTo(this.cut(e.display()))}`,reset:!1};if(e instanceof o){let n=`Runtime error:\n${i.prependTo(this.cut(e.display(`traceback`)))}`,r=e.display(`msg`);(t.budgetExhausted||zt.some(e=>r.includes(e)))&&(n+=t.startedCalls());let a=Ht(e),o=Ut(e);a&&(n+=`\n\n${Bt}`),o&&(n+=`
|
|
22
22
|
|
|
23
23
|
The code ran out of memory and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and keep less data in memory at once.`);let s=a||o;return e.exception.typeName===`RuntimeError`&&Rt.test(r)&&(n+=`
|
|
24
24
|
|
package/package.json
CHANGED
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
"code-mode",
|
|
26
26
|
"python"
|
|
27
27
|
],
|
|
28
|
-
"version": "0.1.
|
|
28
|
+
"version": "0.1.5",
|
|
29
29
|
"type": "module",
|
|
30
30
|
"main": "./dist/index.cjs",
|
|
31
31
|
"module": "./dist/index.js",
|
|
@@ -43,8 +43,8 @@
|
|
|
43
43
|
}
|
|
44
44
|
},
|
|
45
45
|
"dependencies": {
|
|
46
|
-
"@pydantic/logfire-agent-sandboxes": "0.2.
|
|
47
|
-
"logfire": "0.26.
|
|
46
|
+
"@pydantic/logfire-agent-sandboxes": "0.2.3",
|
|
47
|
+
"logfire": "0.26.1"
|
|
48
48
|
},
|
|
49
49
|
"peerDependencies": {
|
|
50
50
|
"@opentelemetry/api": ">=1.9.1 <1.10.0",
|