@pydantic/logfire-ai-sdk-code-mode 0.0.0-stage → 0.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 - present Pydantic Services inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,45 @@
1
- # Temporary Holding Version
1
+ # Logfire AI SDK Code Mode
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Let [Vercel AI SDK](https://ai-sdk.dev) agents write one Python program that calls their tools, instead of calling them
4
+ one model turn at a time. The program runs in a [Logfire Agent Sandbox](https://pydantic.dev/logfire), and your tools
5
+ stay in your Node.js process.
6
+
7
+ ```bash
8
+ npm install @pydantic/logfire-ai-sdk-code-mode @pydantic/monty@^1.5.0 ai zod
9
+ ```
10
+
11
+ Create a Logfire project API key with the **Run code in this project's agent sandboxes** permission
12
+ (`project:execute_agent_sandboxes`) and set it as `LOGFIRE_API_KEY`. The key also selects your data region.
13
+
14
+ ```ts
15
+ import type { LanguageModel } from 'ai'
16
+
17
+ import { codeMode } from '@pydantic/logfire-ai-sdk-code-mode'
18
+ import { generateText, stepCountIs, tool } from 'ai'
19
+ import { z } from 'zod'
20
+
21
+ const getWeather = tool({
22
+ description: 'Get the weather for a city.',
23
+ inputSchema: z.object({ city: z.string() }),
24
+ outputSchema: z.object({ city: z.string(), forecast: z.string() }),
25
+ execute: async ({ city }) => ({ city, forecast: 'Sunny' }),
26
+ })
27
+
28
+ export async function askAgent(model: LanguageModel, prompt: string): Promise<string> {
29
+ await using code = codeMode({ tools: { get_weather: getWeather } })
30
+ const { text } = await generateText({
31
+ model,
32
+ prompt,
33
+ tools: code.tools,
34
+ stopWhen: stepCountIs(10),
35
+ })
36
+ return text
37
+ }
38
+ ```
39
+
40
+ `codeMode()` turns your tools into typed async Python functions and gives the model one `run_code` tool to call them
41
+ from. Create one `codeMode()` object per agent run: it is one sandbox session, kept like a REPL for every `run_code`
42
+ call in that run.
43
+
44
+ See the [Agent Sandboxes docs](https://github.com/pydantic/logfire-js/blob/main/docs/agent-sandboxes.md#use-with-the-vercel-ai-sdk)
45
+ for streaming, approval, tool context, limits, and error handling.
package/dist/index.cjs ADDED
@@ -0,0 +1,28 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));let c=require("@opentelemetry/api"),l=require("@pydantic/logfire-agent-sandboxes"),u=require("@pydantic/monty"),d=require("ai"),f=require("logfire");f=s(f,1);let p=require("node:timers/promises");async function ee(e,{tools:t,toolsContext:n,runtimeContext:r},i){if(e===void 0)return{approved:!0};let a;if(typeof e==`function`){let{tool:o}=i;a=await e({toolCall:{type:`tool-call`,toolCallId:i.toolCallId,toolName:i.toolName,input:i.input,...o.metadata===void 0||o.metadata===null?{}:{toolMetadata:o.metadata},...o.type===`dynamic`?{dynamic:!0}:{},title:o.title},tools:t,toolsContext:n,runtimeContext:r,messages:i.messages})}else{let t=Object.hasOwn(e,i.toolName)?e[i.toolName]:void 0;a=typeof t==`function`?await t(i.input,{toolCallId:i.toolCallId,messages:i.messages,toolContext:i.toolContext,runtimeContext:r}):t}let o=typeof a==`object`?a.type:a,s=typeof a==`object`?a.reason:void 0;return o===void 0||o===`not-applicable`||o===`approved`?{approved:!0}:{approved:!1,reason:s,needsUser:o===`user-approval`}}const m={timeout:3e4,toolCalls:100,concurrentToolCalls:8,outputBytes:64e3,codeBytes:1e5,toolInputBytes:1e6,toolOutputBytes:1e7,memory:268435456,suspensions:1e4},h=/* @__PURE__ */ new Set([`toolCalls`,`concurrentToolCalls`,`memory`,`suspensions`]);function g(e={}){let t={...m};for(let[n,r]of Object.entries(e)){if(!(n in m))throw TypeError(`Unknown code mode limit "${n}". The limits are: ${Object.keys(m).join(`, `)}.`);if(r!==void 0){if(!(typeof r==`number`&&r>0&&Number.isFinite(r)&&(!h.has(n)||Number.isSafeInteger(r)))){let e=h.has(n)?`a positive integer`:`a positive number`;throw RangeError(`The code mode limit "${n}" must be ${e}, not ${JSON.stringify(r)}.`)}t[n]=r}}return t}const _=/* @__PURE__ */ new Set(/* @__PURE__ */ `False.None.True.and.as.assert.async.await.break.class.continue.def.del.elif.else.except.finally.for.from.global.if.import.in.is.lambda.nonlocal.not.or.pass.raise.return.try.while.with.yield`.split(`.`));function v(e){return _.has(e)}const y=/* @__PURE__ */ new Set(/* @__PURE__ */ `ArithmeticError.AssertionError.AttributeError.BaseException.BaseExceptionGroup.BlockingIOError.BrokenPipeError.BufferError.BytesWarning.ChildProcessError.ConnectionAbortedError.ConnectionError.ConnectionRefusedError.ConnectionResetError.DeprecationWarning.EOFError.Ellipsis.EncodingWarning.EnvironmentError.Exception.ExceptionGroup.False.FileExistsError.FileNotFoundError.FloatingPointError.FutureWarning.GeneratorExit.IOError.ImportError.ImportWarning.IndentationError.IndexError.InterruptedError.IsADirectoryError.KeyError.KeyboardInterrupt.LookupError.MemoryError.ModuleNotFoundError.NameError.None.NotADirectoryError.NotImplemented.NotImplementedError.OSError.OverflowError.PendingDeprecationWarning.PermissionError.ProcessLookupError.PythonFinalizationError.RecursionError.ReferenceError.ResourceWarning.RuntimeError.RuntimeWarning.StopAsyncIteration.StopIteration.SyntaxError.SyntaxWarning.SystemError.SystemExit.TabError.TimeoutError.True.TypeError.UnboundLocalError.UnicodeDecodeError.UnicodeEncodeError.UnicodeError.UnicodeTranslateError.UnicodeWarning.UserWarning.ValueError.Warning.ZeroDivisionError.abs.aiter.all.anext.any.ascii.bin.bool.breakpoint.bytearray.bytes.callable.chr.classmethod.compile.complex.copyright.credits.delattr.dict.dir.divmod.enumerate.eval.exec.exit.filter.float.format.frozenset.getattr.globals.hasattr.hash.help.hex.id.input.int.isinstance.issubclass.iter.len.license.list.locals.map.max.memoryview.min.next.object.oct.open.ord.pow.print.property.quit.range.repr.reversed.round.set.setattr.slice.sorted.staticmethod.str.sum.super.tuple.type.vars.zip`.split(`.`));function te(e){return y.has(e)}function b(e){return/^[\p{XID_Start}_]\p{XID_Continue}*$/u.test(e)}function x(e){return b(e)&&!v(e)}function S(e){return e==null?`None`:typeof e==`boolean`?e?`True`:`False`:typeof e==`number`?ne(e):typeof e==`string`?ie(e):Array.isArray(e)?`[${e.map(S).join(`, `)}]`:typeof e==`object`?`{${Object.entries(e).map(([e,t])=>`${ie(e)}: ${S(t)}`).join(`, `)}}`:typeof e==`bigint`?e.toString():`None`}function ne(e){let t=JSON.stringify(e);if(/^-?\d+$/u.test(t))return t;let[n=``,r=`0`]=e.toExponential().split(`e`),i=Number(r),a=n.startsWith(`-`),o=n.replace(/[-.]/gu,``),s=a?`-`:``;if(i<-4||i>=16){let e=o.length>1?`.${o.slice(1)}`:``,t=i<0?`-`:`+`;return`${s}${o[0]??``}${e}e${t}${String(Math.abs(i)).padStart(2,`0`)}`}return i<0?`${s}0.${`0`.repeat(-i-1)}${o}`:`${s}${o.slice(0,i+1).padEnd(i+1,`0`)}.${o.slice(i+1)||`0`}`}const re=/[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Cn}\p{Zl}\p{Zp}\p{Zs}]/u;function ie(e){let t=e.includes(`'`)&&!e.includes(`"`)?`"`:`'`,n=t;for(let r of e)if(r===t||r===`\\`)n+=`\\${r}`;else if(r===` `)n+=`\\t`;else if(r===`
2
+ `)n+=`\\n`;else if(r===`\r`)n+=`\\r`;else if(r!==` `&&re.test(r)){let e=r.codePointAt(0)??0;n+=e<256?`\\x${e.toString(16).padStart(2,`0`)}`:e<65536?`\\u${e.toString(16).padStart(4,`0`)}`:`\\U${e.toString(16).padStart(8,`0`)}`}else n+=r;return n+t}const ae='Write and run Python code in a sandboxed environment.\n\nThe sandbox uses Monty, a subset of Python. Key restrictions:\n- **No third-party libraries**: only the standard library modules listed below can be used\n- **Importable standard library modules**: `sys`, `typing`, `asyncio`, `math`, `json`, `re`, `unicodedata`, `datetime`, `time`, `random`, `os`, `pathlib`, `collections`, `itertools`, `functools`, `dataclasses`, `copy`, `base64`, `binascii`, `bisect`, `csv`, `decimal`, `fnmatch`, `hashlib`, `os.path`, `tomllib`, `annotationlib`. These must be imported before use, just like in regular Python.\n- **No filesystem, environment, or clock**: `pathlib.Path` I/O, `os.getenv`/`os.environ`, `datetime.datetime.now()`, `datetime.date.today()`, and `time.time()` are unavailable here (no filesystem mount or OS handler is configured). `os` and `pathlib` import successfully, but their I/O operations are not supported in this configuration. `time.sleep` and `asyncio.sleep` really wait.\n- **No `import *`**: wildcard imports are not supported\n\nState is preserved between calls (REPL-style). Set `restart: true` to reset state.\n\nThe last expression\'s value is automatically captured as the return value -- you do **not** need to `print()` it. End the snippet with the value to return as a bare expression. A final assignment stores the value but does not return it. A final expression that evaluates to `None` is treated as no result. Without a non-`None` final expression or print output, `run_code` returns `{}`. For example:\n\n```python\nresult = some_expression\nresult\n```\n\nAvoid `print()` for return values as it produces Python string representations, not structured data. Use `print()` only for supplementary logging or debug output.\n\nReturns a non-`None` last expression\'s value directly when nothing is printed. With `print()` output and no non-`None` final expression, returns `{"output": "<printed text>"}`. With `print()` output and a plain, non-`None` final expression, returns `{"output": "<printed text>", "result": <last expression>}`. With `print()` output and a multimodal final expression, returns a list with the printed text followed by the native content.';function oe(e,t){if(t.length===0)return ae;let n=["\nThe following functions are available inside the sandbox. These functions are already defined in the sandbox; call them by name without redefining or importing them. All parameters are keyword-only. All tool functions are async: invoke them with `await`, e.g. `await tool_name(arg=value)`. Calling without `await` returns an unresolved future, not the value.\n\nTo run calls concurrently, first `import asyncio`, then use `await asyncio.gather(...)` with positional awaitables. Monty does not support `asyncio.gather` keyword arguments or other task creation and wait APIs."];return e.length>0&&n.push("```python\n"+e.join(`
3
+
4
+ `)+"\n```"),n.push("```python\n"+t.join(`
5
+
6
+ `)+"\n```"),`${ae}\n\n${n.join(`
7
+
8
+ `)}`}let C,w=/* @__PURE__ */ new Set;var T=class{kind=`simple`;name;constructor(e){this.name=e}toString(){return this.name}},se=class{kind=`literal`;values;constructor(e){this.values=e}toString(){return`Literal[${this.values.map(S).join(`, `)}]`}},E=class{kind=`generic`;base;args;constructor(e,t){this.base=e,this.args=t}toString(){return`${this.base}[${this.args.map(String).join(`, `)}]`}},D=class{kind=`union`;members;constructor(e){this.members=e}toString(){return this.members.map(String).join(` | `)}};const ce=` `;function le(e){return e.replace(/[\\\0"]/gu,e=>e===`\\`?`\\\\`:e===`\0`?`\\x00`:`\\"`)}const ue=`\\s\\x1c-\\x1f\\x85`,de=RegExp(`^[${ue}]+|[${ue}]+$`,`gu`),fe=/\r\n|[\n\r\v\f\x1c-\x1e\x85\u2028\u2029]/u,pe=RegExp(`[${ue}]+$`,`u`);function O(e){return e.replace(de,``)}function me(e){return e.replace(pe,``)}function k(e){if(e===``)return[];let t=e.split(fe);return t.at(-1)===``&&fe.test(e.at(-1)??``)&&t.pop(),t}function A(e){return e!==void 0&&e!==``}function j(e,t=``){let n=le(O(e)),r=k(n);return r.length>1?[`${t}"""`,...r.map(e=>O(e)?`${t}${e}`:``),`${t}"""`]:[`${t}"""${n}"""`]}function he(e){let t=e.replace(/[^a-zA-Z0-9_]/gu,`_`);return/^[0-9]/u.test(t)&&(t=`_${t}`),v(t)&&(t=`${t}_`),t||`_`}function ge(e,t=``){return k(O(e).replace(/\0/gu,`\\x00`)).map(e=>me(`${t}# ${e}`))}var _e=class{kind=`field`;name;type;required;description;constructor(e,t,n=!1,r){this.name=e,this.type=t,this.required=n,this.description=r}toString(){let e=[` ${this.name}: ${ve(this)}`];return A(this.description)&&e.push(...j(this.description,` `)),e.join(`
9
+ `)}};function ve(e){let t=String(e.type);return e.required?t:`NotRequired[${t}]`}function ye(e){let t=A(e.description)?ge(e.description,` `):[];return t.push(` ${S(e.name)}: ${ve(e)},`),t.join(`
10
+ `)}var M=class{kind=`type`;name;description;fields;constructor(e,t,n=/* @__PURE__ */ new Map){this.name=e,this.description=t,this.fields=n}get displayName(){if(C===void 0||!C.conflicting.has(this.name))return this.name;let e=C.typeNames.get(this);if(e!==void 0)return e;let t=C.fallbackOwner;return A(t)?`${t}_${this.name}`:this.name}toString(){return this.displayName}renderDefinition(e,t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Map){return Ce({conflicting:t,typeNames:n,fallbackOwner:e},()=>this.renderDefinitionBody())}renderDefinitionBody(){if(![...this.fields.keys()].every(x))return this.renderFunctionalDefinition();let e=[`class ${this.displayName}(TypedDict):`];if(A(this.description)&&e.push(...j(this.description,` `)),this.fields.size===0)A(this.description)||e.push(` pass`);else for(let t of this.fields.values())e.push(String(t));return e.join(`
11
+ `)}renderFunctionalDefinition(){let e=A(this.description)?ge(this.description):[];return e.push(`${this.displayName} = TypedDict(${S(this.displayName)}, {`),e.push(...[...this.fields.values()].map(ye)),e.push(`})`),e.join(`
12
+ `)}structurallyEqual(e){return be(this,e,/* @__PURE__ */ new Map)}};function be(e,t,n){if(e===t||n.get(e)?.has(t)===!0)return!0;if(n.set(e,/* @__PURE__ */ new Set([...n.get(e)??[],t])),e.fields.size!==t.fields.size)return!1;for(let[r,i]of e.fields){let e=t.fields.get(r);if(e===void 0||i.required!==e.required||!xe(i.type,e.type,n))return!1}return!0}function xe(e,t,n){return e instanceof M&&t instanceof M?e.name===t.name&&be(e,t,n):e instanceof E&&t instanceof E?e.base===t.base&&Se(e.args,t.args,n):e instanceof D&&t instanceof D?Se(e.members,t.members,n):e.kind===t.kind&&String(e)===String(t)}function Se(e,t,n){return e.length===t.length&&e.every((e,r)=>{let i=t[r];return i!==void 0&&xe(e,i,n)})}var N=class{kind=`param`;name;type;defaultValue;description;constructor(e,t,n,r){this.name=e,this.type=t,this.defaultValue=n,this.description=r}toString(){let e=String(this.type);return this.defaultValue===void 0?`${this.name}: ${e}`:`${this.name}: ${e} = ${this.defaultValue}`}},P=class e{kind=`function`;name;params;returnType;referencedTypes;description;isAsync;constructor(e,t,n,r,i,a=!1){this.name=e,this.params=t,this.returnType=n,this.referencedTypes=r,this.description=i,this.isAsync=a}render(e,t={}){let n=t.name!==void 0&&t.name!==``?t.name:this.name,r=t.description??this.description;return Ce({conflicting:t.conflictingTypeNames??/* @__PURE__ */ new Set,typeNames:t.typeNames??/* @__PURE__ */ new Map,fallbackOwner:n},()=>this.renderBody(e,n,r,t.isAsync))}renderBody(e,t,n,r){let i=r??this.isAsync?`async def`:`def`,a=[...this.params.values()].map(String).join(`, `),o=String(this.returnType),s=[a?`${i} ${t}(*, ${a}) -> ${o}:`:`${i} ${t}() -> ${o}:`],c=A(n)?[n]:[],l=[];for(let e of this.params.values()){let[t,...n]=k(O(e.description??``));t!==void 0&&(l.push(`${ce}${e.name}: ${t}`),l.push(...n.map(e=>`${ce}${ce}${e}`)))}l.length>0&&c.push([`Args:`,...l].join(`
13
+ `));let u=c.join(`
14
+
15
+ `);return u!==``&&s.push(...j(u,` `)),s.push(` ${e}`),s.join(`
16
+ `)}static fromSchema(t,n,r){let i=De(n),a=/* @__PURE__ */ new Map;Ae(i,a,t);let o=je(n,i,a,t),s=F,c=/* @__PURE__ */ new Map;if(r!==void 0){let e=De(r);Ae(e,c,t),s=U(r,e,c,t,`Return`)}let l=[...a.values()],u=/* @__PURE__ */ new Map;for(let e of c.values()){let t=a.get(e.name);if(t?.structurallyEqual(e)===!0){u.set(e,t);continue}l.push(e)}s=G(s,u);for(let e of l)for(let t of e.fields.values())t.type=G(t.type,u);return new e(t,o,s,l)}static getConflictingTypeNames(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Set;for(let r of e){let e=[];for(let i of r.referencedTypes){let a=t.get(i.name);a===void 0?(t.set(i.name,i),e.push(i)):a.structurallyEqual(i)?(Ue(r,i,a),e.push(a)):(n.add(i.name),e.push(i))}r.referencedTypes=e}return n}static collectUniqueReferencedTypes(e){let t=/* @__PURE__ */ new Set,n=[];for(let r of e)for(let e of r.referencedTypes)t.has(e)||(t.add(e),n.push(e));return n}static prefixedTypeNames(t,n){let r=/* @__PURE__ */ new Set;for(let i of e.collectUniqueReferencedTypes(t))n.has(i.name)||r.add(i.name);let i=/* @__PURE__ */ new Map;for(let e of t)for(let t of e.referencedTypes){if(!n.has(t.name)||i.has(t))continue;let a=`${e.name}_${t.name}`,o=a;for(let e=2;r.has(o);e++)o=`${a}_${String(e)}`;r.add(o),i.set(t,o)}return i}static renderTypeDefinitions(t,n){let r=e.collectUniqueReferencedTypes(t),i=e.prefixedTypeNames(t,n);return r.map(e=>e.renderDefinition(void 0,n,i))}};function Ce(e,t){let n=C;C=e;try{return t()}finally{C=n}}const F=new T(`Any`),I=new T(`None`),we=/* @__PURE__ */ new Map([[`string`,`str`],[`integer`,`int`],[`number`,`float`],[`boolean`,`bool`],[`null`,`None`]]);function Te(e){return new T(we.get(e)??`Any`)}function Ee(e){return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}function L(e){let t=e.replace(/[^a-zA-Z0-9]/gu,`_`).split(`_`).filter(Boolean).map(Ee).join(``);return/^[0-9]/u.test(t)?`_${t}`:t}function R(e,t){return[e,...t.split(`.`).filter(Boolean)].map(L).join(``)}function z(e){return typeof e==`string`&&e!==``?e:void 0}function B(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function V(e){return B(e)?e:{}}function De(e){let t=e.$defs;return B(t)?t:{}}function H(e){let t=e.properties;return B(t)?t:{}}function Oe(e){let t=e.required;return new Set(Array.isArray(t)?t:[])}function ke(e){return e.type===`object`&&`properties`in e}function Ae(e,t,n){for(let[r,i]of Object.entries(e)){let a=V(i);ke(a)&&!t.has(r)&&W(r,a,e,t,n,r)}}function je(e,t,n,r){let i=Oe(e),a=H(e),o=Me(Object.keys(a)),s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Map;for(let[e,l]of Object.entries(a)){let a=V(l),u=U(a,t,n,r,e),d=z(a.description),f=o.get(e)??e;`default`in a?c.set(e,new N(f,u,S(a.default),d)):i.has(e)?s.set(e,new N(f,u,void 0,d)):Ne(a)?c.set(e,new N(f,u,`None`,d)):c.set(e,new N(f,new D([u,I]),`None`,d))}return new Map([...s,...c])}function Me(e){let t=[...e],n=new Set(t.filter(x)),r=/* @__PURE__ */ new Map;for(let e of t){if(x(e)){r.set(e,e);continue}let t=he(e),i=t;for(let e=2;n.has(i);e++)i=`${t}_${String(e)}`;n.add(i),r.set(e,i)}return r}function Ne(e){let t=e.type;if(Array.isArray(t)&&t.includes(`null`))return!0;for(let t of[`anyOf`,`oneOf`])if(t in e){let n=e[t];return Array.isArray(n)&&n.some(e=>V(e).type===`null`)}return!1}function U(e,t,n,r,i){let a=V(e);if(`$ref`in a){let e=String(a.$ref).split(`/`).at(-1)??``;if(Object.hasOwn(t,e)&&!n.has(e)){let a=V(t[e]);if(ke(a))W(e,a,t,n,r,i);else{if(w.has(e))return F;let o=w;w=/* @__PURE__ */ new Set([...o,e]);try{return U(a,t,n,r,i)}finally{w=o}}}return n.get(e)??new M(e)}if(`anyOf`in a)return Le(a.anyOf,t,n,r,i);if(`oneOf`in a)return Le(a.oneOf,t,n,r,i);if(`allOf`in a){let e=a.allOf;return e.length===1?U(e[0],t,n,r,i):F}return`const`in a?new se([a.const]):`enum`in a?new se(a.enum):Pe(a.type,a,t,n,r,i)}function Pe(e,t,n,r,i,a){let o=we.get(e);if(o!==void 0)return new T(o);if(e===`array`){let e=t.items??{};return Fe(e)?Array.isArray(e)?new E(`tuple`,e.map((e,t)=>U(e,n,r,i,`${a}.${String(t)}`))):new E(`list`,[U(e,n,r,i,`${a}Item`)]):new E(`list`,[F])}if(e===`object`){if(`properties`in t){let e=t.title,o=typeof e==`string`&&e!==``&&b(e)?e:R(i,a),s=Object.hasOwn(n,o)?V(n[o]):void 0;return s!==void 0&&ke(s)&&!r.has(o)&&W(o,s,n,r,i,o),r.has(o)?Ve(o,t,n,r,i,a):W(o,t,n,r,i,a)}if(`additionalProperties`in t){let e=t.additionalProperties;if(e===!0)return new E(`dict`,[new T(`str`),F]);if(B(e)){let t=U(e,n,r,i,`${a}Value`);return new E(`dict`,[new T(`str`),t])}}return new E(`dict`,[new T(`str`),F])}return Array.isArray(e)?Ie(e,t,n,r,i,a):F}function Fe(e){return Array.isArray(e)?e.length>0:B(e)?Object.keys(e).length>0:!!e}function Ie(e,t,n,r,i,a){if(e.includes(`object`)&&`properties`in t){let o=Pe(`object`,t,n,r,i,a);return e.includes(`null`)?new D([o,I]):o}let o=e.map(Te),s=o.find(e=>String(e)!==`None`);if(o.length===2&&s!==void 0&&o.some(e=>String(e)===`None`))return new D([s,I]);let[c,...l]=o;return c===void 0?F:l.length>0?new D(o):c}function Le(e,t,n,r,i){let a=e.map(V),o=Re(a,i),s=[],c=!1;for(let e of a)e.type===`null`?c=!0:s.push(U(e,t,n,r,o.get(e)??i));let l=/* @__PURE__ */ new Set,u=[];for(let e of s){let t=String(e);l.has(t)||(l.add(t),u.push(e))}c&&u.push(I);let[d,...f]=u;return d!==void 0&&f.length===0?d:new D(u)}function Re(e,t){let n=e.filter(e=>e.type===`object`&&`properties`in e&&!ze(e)),r=/* @__PURE__ */ new Map;if(n.length<2)return r;let i=n.map(Be),a=i.every(e=>e!==void 0)&&new Set(i.map(e=>L(e))).size===i.length;return n.forEach((e,n)=>{r.set(e,`${t}.${a?i[n]??``:String(n+1)}`)}),r}function ze(e){let t=e.title;return typeof t==`string`&&t!==``&&b(t)}function Be(e){for(let t of Object.values(H(e))){let e=V(t).const;if(typeof e==`string`&&L(e)!==``)return e}}function Ve(e,t,n,r,i,a){let o=He(e,t,n,r,i,a);for(let t=1;;t++){let n=t===1?e:`${e}_${String(t)}`,i=r.get(n);if(i===void 0){let e=new M(n,o.description,o.fields);return r.set(n,e),e}if(i.structurallyEqual(o))return i}}function W(e,t,n,r,i,a){let o=new M(e);r.set(e,o);let s=He(e,t,n,r,i,a);return o.fields=s.fields,o.description=s.description,o}function He(e,t,n,r,i,a){let o=Oe(t),s=/* @__PURE__ */ new Map;for(let[e,c]of Object.entries(H(t))){let t=V(c),l=U(t,n,r,i,a?`${a}.${e}`:e),u=z(t.description);s.set(e,new _e(e,l,o.has(e),u))}return new M(e,z(t.description),s)}function G(e,t){if(e instanceof M)return t.get(e)??e;if(e instanceof E){let n=e.args.map(e=>G(e,t));n.some((t,n)=>t!==e.args[n])&&(e.args=n)}else if(e instanceof D){let n=e.members.map(e=>G(e,t));n.some((t,n)=>t!==e.members[n])&&(e.members=n)}return e}function Ue(e,t,n){let r=/* @__PURE__ */ new Map([[t,n]]);for(let t of e.params.values())t.type=G(t.type,r);e.returnType=G(e.returnType,r);for(let t of e.referencedTypes)for(let e of t.fields.values())e.type=G(e.type,r)}function We(e,t,n){let r=structuredClone(e),i=Ge(r,t);if(delete r.$schema,n===`parameters`&&typeof r.$ref==`string`)throw Error(`Tool "${t}" has a parameters schema that is only a reference, which code mode cannot read`);let a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Set,s=(e,n)=>{if(o.has(n))throw Error(`Tool "${t}" has two schema definitions that both become the Python type "${n}"`);o.add(n),a.set(e,n)},c;Ke([r,...Object.values(i)],`#`)&&(c=Ye(r.title,void 0,()=>R(t,n===`return`?`Return`:``)),o.add(c));let l=Qe(r,i,n);for(let[e,n]of Object.entries(i))s(e,Ye(K(n)?n.title:void 0,e,()=>R(t,l.get(e)??e)));let u=e=>J(e,t,a,c),d=u(r),f={};for(let[e,t]of a)f[t]=u(i[e]);if(c!==void 0){let e={...d};delete e.$defs,f[c]=e}return Object.keys(f).length>0&&(d.$defs=f),d}function K(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ge(e,t){let n={},r=[e.definitions,e.$defs];delete e.definitions,delete e.$defs;for(let e of r)if(K(e))for(let[r,i]of Object.entries(e)){if(Object.hasOwn(n,r))throw Error(`Tool "${t}" defines "${r}" in both "definitions" and "$defs"`);n[r]=i}return n}function Ke(e,t){return Array.isArray(e)?e.some(e=>Ke(e,t)):K(e)?e.$ref===t||Object.entries(e).some(([e,n])=>!Xe.has(e)&&Ke(n,t)):!1}const qe=/^__schema\d+$/u,Je=/* @__PURE__ */ new Set([`asyncio`,`Any`,`TypedDict`,`NotRequired`,`Literal`,`str`,`int`,`float`,`bool`,`list`,`dict`,`tuple`]);function q(e){return x(e)&&!Je.has(e)}function Ye(e,t,n){if(t!==void 0&&q(t)&&!qe.test(t))return t;if(typeof e==`string`&&q(e))return e;if(t!==void 0&&!qe.test(t)){let e=L(t);if(q(e))return e}return n()}const Xe=/* @__PURE__ */ new Set([`default`,`const`,`enum`,`examples`]),Ze=/* @__PURE__ */ new Set([`properties`,`patternProperties`,`$defs`,`definitions`]);function Qe(e,t,n){let r=/* @__PURE__ */ new Map,i=(e,n)=>{if(Array.isArray(e)){for(let t of e)i(t,n);return}if(!K(e))return;let a=e.$ref;if(typeof a==`string`){let e=$e(a);e!==void 0&&Object.hasOwn(t,e)&&!r.has(e)&&(r.set(e,n),i(t[e],n))}let o=e.properties;if(K(o))for(let[e,t]of Object.entries(o))i(t,n?`${n}.${e}`:e);let s=e.items;Array.isArray(s)?s.forEach((e,t)=>{i(e,`${n}.${String(t)}`)}):i(s,`${n}Item`),i(e.additionalProperties,`${n}Value`);for(let t of[`anyOf`,`oneOf`,`allOf`])i(e[t],n)};return i(e,n===`return`?`Return`:``),r}function $e(e){return/^#\/(?:definitions|\$defs)\/([^/]+)$/u.exec(e)?.[1]?.replace(/~1/gu,`/`).replace(/~0/gu,`~`)}function J(e,t,n,r){if(Array.isArray(e))return e.map(e=>J(e,t,n,r));if(!K(e))return e;let i={};for(let[a,o]of Object.entries(e))if(Ze.has(a)&&K(o))i[a]=Object.fromEntries(Object.entries(o).map(([e,i])=>[e,J(i,t,n,r)]));else if(Xe.has(a))i[a]=o;else if(a===`$ref`&&typeof o==`string`)i[a]=et(o,t,n,r);else if(a===`title`&&typeof o==`string`&&!q(o))continue;else i[a]=J(o,t,n,r);return i}function et(e,t,n,r){if(e===`#`&&r!==void 0)return`#/$defs/${r}`;let i=$e(e),a=i===void 0?void 0:n.get(i);if(a===void 0)throw Error(`Tool "${t}" has a schema reference "${e}" that code mode cannot resolve`);return`#/$defs/${a}`}const tt=`import asyncio
17
+ from typing import Any, TypedDict, NotRequired, Literal`,nt=new Set(tt.split(`
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:P.fromSchema(e.name,e.parametersSchema,e.returnSchema)})),n=t.map(({sig:e})=>e),r=P.getConflictingTypeNames(n),i=P.prefixedTypeNames(n,r),a=P.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
+
20
+ `)}}function ot(e){return he(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 S(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`?S(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 Rt(e)}function Z(e,t){let n=Error(t);return n.name=e,n}function xt(e){return e instanceof Error?e.message:String(e)}const St=2e3;function Ct(e){let t=xt(e);return t.length>St?`${t.slice(0,St)} ... (${String(t.length)} chars total)`:t}function wt(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`,Et(e,n)):t}}function Tt(e,t){return t===void 0?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[t.get(e)??e,n]))}function Et(e,t){return`The arguments to ${e}() are more than ${String(t)} bytes of JSON, over the limit for one call.`}function Dt(){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 Ot(e){let t=JSON.stringify(e??null,Dt());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 kt(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 At(e){return e.aborted?`stopped`:new Promise(t=>{e.addEventListener(`abort`,()=>{t(`stopped`)},{once:!0})})}var jt=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()}},Mt=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 $(e){return String(e.timeout/1e3)}var Nt=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 Mt(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 ${$(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 Pt=/^suspension limit [0-9]+ exceeded$/u,Ft=[`time limit exceeded`,`memory limit exceeded`,`suspension limit `];function It(e){return e.traceback().length===0&&e.display(`msg`).includes(`time limit exceeded`)}function Lt(e){return e.exception.typeName===`MemoryError`&&e.display(`msg`).startsWith(`memory limit exceeded`)}var Rt=class{tools;limits;idleTimeout;pythonNames;schemaArgNames;typeCheckStubs;queue=Promise.resolve();poolPromise;sessionPromise;passedTypeCheck=!1;expired=!1;idleTimer;current;closing;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=g(e.limits),this.slots=new jt(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(te(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:oe(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)=>this.enqueue(e,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){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();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 Nt(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 feed(e,t,n){let r;try{r=await this.session()}catch(e){throw t.stopped===void 0?Error(this.describeFailure(e,t).message,{cause:e}):this.stoppedError(t,!1)}if(t.stopped!==void 0)throw this.stoppedError(t,!1);let i,a,o=!1,s=!1;t.start();let c=this.options.typeCheck===`off`||this.options.typeCheck!==`every-snippet`&&this.passedTypeCheck,l=r.feedRun(e,{externalLookup:this.externalLookup(t,n),printCallback:t.printed.write,os:this.osCallback(t),skipTypeCheck:c}).then(e=>({ok:!0,result:e}),e=>({ok:!1,error:e})),d=await Promise.race([l,At(t.signal)]);d===`stopped`?(s=!0,this.abandonSession(r,l)):d.ok?(i=d.result,o=!0,this.passedTypeCheck=!0):(a=d.error,this.passedTypeCheck||=!(a instanceof u.MontyTypingError||a instanceof u.MontySyntaxError));let f=t.reason();if(f===`closed`||f===`aborted`)throw this.stoppedError(t,!0);if(f===`deadline`){s||await this.releaseSession();let e=a instanceof u.MontyRuntimeError?`Runtime error:\n${t.printed.prependTo(this.cut(a.display(`traceback`)))}\n\n`:``;throw Error(`${e}The code ran longer than its ${$(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.`+t.startedCalls())}if(!o){let e=this.describeFailure(a,t);throw e.reset&&await this.releaseSession(),Error(e.message,{cause:a})}return this.shapeResult(i,t)}shapeResult(e,t){let{outputBytes:n}=this.limits,r=/* @__PURE__ */ Error(`The result is more than ${String(n)} 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.`),i;try{i=gt(ht(e,n))}catch(e){throw e instanceof mt?r:e}if(Y(JSON.stringify(i??null))>n)throw r;let a=t.printed.output;return a===``?i??{}:i==null?{output:a}:{output:a,result:i}}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||Ft.some(e=>i.includes(e)))&&(r+=t.startedCalls());let a=It(e),o=Lt(e);a&&(r+=`
22
+
23
+ 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.`),o&&(r+=`
24
+
25
+ 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`&&Pt.test(i)&&(r+=`
26
+
27
+ If this reports the sandbox session's suspension limit, its cumulative host-interaction budget is exhausted. Further tool calls, OS callbacks, name lookups and future resolutions need a fresh session; revising the snippet does not replenish this budget. Pure Python using existing state may still work. Pass \`restart: true\` to start a fresh session; that discards all REPL variables, imports and definitions. Check the calls already started before continuing, and do not replay completed side effects.`),{message:r,reset:s}}if(e instanceof u.MontyCrashedError)return{message:`The code crashed the sandbox worker and the session was reset. Revise the code and try again.${t.startedCalls()}`,reset:!0};let r=e instanceof Error?`${e.name}: ${e.message}`:String(e);return{message:`Code execution failed and the session was reset. Re-run any imports, recreate any state you need, and try again.
28
+ ${n.prependTo(this.cut(r))}${t.startedCalls()}`,reset:!0}}osCallback(e){return async(t,n)=>{if(t!==`time.sleep`&&t!==`asyncio.sleep`)return u.NOT_HANDLED;let r=Number(n[0]),i=Math.max(0,(e.deadline-Date.now())/1e3);if(e.stopped!==void 0||r>i)throw Z(`TimeoutError`,`sleeping ${String(r)}s would exceed the ${$(this.limits)}s this code may run; ${i.toFixed(1)}s left`);return await Q((0,p.setTimeout)(r*1e3,void 0,{ref:!1}),e.signal),null}}externalLookup(e,t){return Object.fromEntries(Object.keys(this.options.tools).map(n=>{let r=this.pythonNames.get(n)??n;return[r,async(...i)=>this.callTool(n,r,i,e,t)]}))}async callTool(e,t,n,r,i){let{limits:a}=this,o=this.options.tools[e];if(r.stopped!==void 0)throw r.signal.reason;if(r.callCount>=a.toolCalls)throw r.budgetExhausted=!0,Z(`RuntimeError`,`Code mode allows ${String(a.toolCalls)} nested tool calls per \`run_code\` call and this snippet asked for more. Call fewer tools, for example by filtering the inputs first, or split the work across several \`run_code\` calls.`);r.callCount+=1;let s=`${r.id}__${String(r.callCount)}`,c=Tt(wt(t,n,a.toolInputBytes),this.schemaArgNames.get(t));if(Y(JSON.stringify(c))>a.toolInputBytes)throw Z(`ValueError`,Et(t,a.toolInputBytes));let l=await Q(Promise.resolve((0,d.asSchema)(o.inputSchema).validate?.(c)),r.signal);if(l!==void 0&&!l.success)throw Z(`ValueError`,`Invalid arguments for ${t}(): ${Ct(l.error)}`);let u=l===void 0?c:l.value,p=this.options.context,m=p!==void 0&&Object.hasOwn(p,e)?p[e]:void 0;if(o.contextSchema!==void 0){let t=await Q(Promise.resolve((0,d.asSchema)(o.contextSchema).validate?.(m)),r.signal);if(t!==void 0&&!t.success)throw Z(`ValueError`,`Invalid context for tool "${e}": ${Ct(t.error)}`);m=t===void 0?m:t.value}let h={toolName:e,inputPreview:X(u),status:`running`},g=await Q(ee(this.options.approval,{tools:this.options.tools,toolsContext:this.options.context??{},runtimeContext:this.options.runtimeContext},{toolName:e,toolCallId:s,input:u,messages:i.messages,toolContext:m,tool:o}),r.signal);if(!g.approved){h.status=`denied`,r.calls.push(h);let t=g.reason===void 0?``:` ${g.reason}`;throw Z(`RuntimeError`,g.needsUser?`Tool '${e}' needs a person to approve it, and code mode cannot ask for approval from inside the sandbox.${t}`:`Tool '${e}' call denied:${t===``?` denied by the approval policy`:t}`)}await this.slots.acquire(r.signal);let _=!1,v=()=>{_||(_=!0,this.slots.release())},y={};r.calls.push(h);try{return await f.span(`run_code called {tool_name}`,{tool_name:e,tool_call_id:s,arguments:u},{},async()=>{let n;try{r.signal.throwIfAborted();let e=this.execute(o,u,{...i,toolCallId:s,context:m,abortSignal:r.signal});y.running=e,e.then(v,v),n=await Q(e,r.signal)}catch(t){throw h.status=`failed`,r.stopped===void 0?this.replaceToolError(t,{toolName:e,toolCallId:s,input:u}):t}h.status=`returned`;let c;try{c=Ot(n)}catch(e){let n=e instanceof RangeError?`it is nested too deeply or contains itself`:xt(e);throw h.outputPreview=`<not JSON>`,Z(`ValueError`,`${t}() returned a value that cannot be sent to the sandbox as JSON: ${n}. The call ran, so do not repeat it to get the same result.`)}let l=Y(c);if(l>a.toolOutputBytes)throw h.outputPreview=`<${String(l)} bytes, over the limit>`,Z(`ValueError`,`${t}() returned ${String(l)} bytes of JSON, over the ${String(a.toolOutputBytes)}-byte limit for one call. The call ran, so do not repeat it to get the same result.`);let d=JSON.parse(c);return h.outputPreview=X(d),d})}finally{y.running===void 0&&v()}}async execute(e,t,n){let r=e.execute,i=r(t,n);if(kt(i)){let e;for await(let t of i)e=t;return e}return await i}replaceToolError(e,t){let n=this.options.onToolError?.(e,t);return n instanceof Error?n:typeof n==`string`?Error(n):e instanceof Error?e:Error(String(e))}async pool(){let{sandboxes:e}=this.options;this.poolPromise??=e===void 0?(0,l.agentSandboxes)({requestTimeout:this.limits.timeout/1e3+10}):Promise.resolve(e);try{return await this.poolPromise}catch(e){throw this.poolPromise=void 0,e}}async session(){this.sessionPromise??=this.checkout();try{return await this.sessionPromise}catch(e){throw this.sessionPromise=void 0,e}}async checkout(){let e=this.options.typeCheck!==`off`;return c.context.with(this.traceContext,async()=>(await this.pool()).checkout({ephemeral:!0,scriptName:`run_code.py`,typeCheck:e,...e?{typeCheckStubs:this.typeCheckStubs}:{},limits:{maxFeedDurationSecs:this.limits.timeout/1e3,maxMemory:this.limits.memory,maxSuspensions:this.limits.suspensions},osPolicy:{datetime:`call_host`,sleep:`call_host`,randomStart:`call_host`}}))}abandonSession(e,t){this.sessionPromise=void 0,this.passedTypeCheck=!1,t.then(async()=>e.close()).catch(()=>void 0)}async releaseSession(){let e=this.sessionPromise;if(this.sessionPromise=void 0,this.passedTypeCheck=!1,e!==void 0)try{await(await e).close()}catch{}}startIdleTimer(){this.closing===void 0&&this.sessionPromise!==void 0&&Number.isFinite(this.idleTimeout)&&(this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.current===void 0&&this.closing===void 0&&(this.expired=!0,this.releaseSession().catch(()=>void 0))},Math.min(this.idleTimeout,2**31-1)),this.idleTimer.unref())}clearIdleTimer(){clearTimeout(this.idleTimer),this.idleTimer=void 0}};exports.codeMode=bt;
@@ -0,0 +1,133 @@
1
+ import { MontySession, RemoteCheckoutOptions } from "@pydantic/monty";
2
+ import { Tool, ToolApprovalConfiguration, ToolApprovalStatus, ToolSet } from "ai";
3
+ //#region src/approval.d.ts
4
+ type AnyFunction = (...args: never[]) => unknown;
5
+ /** The AI SDK's statuses without `'user-approval'`: nothing in the sandbox can wait for a person. */
6
+ type CodeModeApprovalStatus = Exclude<ToolApprovalStatus, "user-approval" | {
7
+ type: "user-approval";
8
+ }>;
9
+ type NarrowedEntry<ENTRY> = ENTRY extends ((...args: infer ARGS) => unknown) ? (...args: ARGS) => CodeModeApprovalStatus | PromiseLike<CodeModeApprovalStatus> : Extract<ENTRY, CodeModeApprovalStatus>;
10
+ type ApprovalMap<TOOLS extends ToolSet, RUNTIME_CONTEXT> = Exclude<ToolApprovalConfiguration<TOOLS, RUNTIME_CONTEXT>, AnyFunction>;
11
+ /**
12
+ * generateText's `toolApproval`, narrowed so that `'user-approval'` does not compile. Accepting it today would mean
13
+ * "fail the call", and the same config would change meaning if code mode ever supports pausing for a person. Leaving
14
+ * it out means real approval can be added by widening this type.
15
+ */
16
+ type CodeModeApproval<TOOLS extends ToolSet, RUNTIME_CONTEXT> = NarrowedEntry<Extract<ToolApprovalConfiguration<TOOLS, RUNTIME_CONTEXT>, AnyFunction>> | { [NAME in keyof ApprovalMap<TOOLS, RUNTIME_CONTEXT>]: NarrowedEntry<ApprovalMap<TOOLS, RUNTIME_CONTEXT>[NAME]>; };
17
+ //#endregion
18
+ //#region src/limits.d.ts
19
+ /** Caps on what one `codeMode()` instance lets sandbox code do. Every field is optional. */
20
+ interface CodeModeLimits {
21
+ /**
22
+ * Milliseconds of wall-clock time per snippet, including time spent waiting on tools and sleeping (default 30,000).
23
+ * Also Monty's execution-time limit for the snippet's own code.
24
+ */
25
+ timeout?: number;
26
+ /** Nested tool calls per snippet (default 100). Calls past the budget fail without reaching the tool. */
27
+ toolCalls?: number;
28
+ /** Tool calls running on the host at the same time (default 8). More calls wait for a free slot. */
29
+ concurrentToolCalls?: number;
30
+ /**
31
+ * Bytes of JSON result sent to the model per snippet, and separately bytes of printed output (default 64,000).
32
+ * A larger result fails with a message asking for a smaller one; printed output is cut.
33
+ */
34
+ outputBytes?: number;
35
+ /** Bytes of source per snippet (default 100,000). */
36
+ codeBytes?: number;
37
+ /** Bytes of JSON arguments per nested call (default 1,000,000). */
38
+ toolInputBytes?: number;
39
+ /** Bytes of JSON result per nested call (default 10,000,000). */
40
+ toolOutputBytes?: number;
41
+ /** Bytes of sandbox heap (default 256 MiB). */
42
+ memory?: number;
43
+ /**
44
+ * Host interactions per session, which every tool call, sleep and future resolution uses (default 10,000).
45
+ * Monty's own default of 1,000 would end a long agent run partway through.
46
+ */
47
+ suspensions?: number;
48
+ }
49
+ //#endregion
50
+ //#region src/codeMode.d.ts
51
+ /** Where code runs: a pool such as `agentSandboxes()`, `MontyRemote.create()` or `Monty.create()`. */
52
+ interface Sandboxes {
53
+ checkout(options?: RemoteCheckoutOptions): Promise<MontySession>;
54
+ close(): Promise<void>;
55
+ }
56
+ interface ToolErrorCall {
57
+ toolName: string;
58
+ toolCallId: string;
59
+ input: unknown;
60
+ }
61
+ interface CodeModeOptions<TOOLS extends ToolSet, RUNTIME_CONTEXT = unknown> {
62
+ /** The tools sandbox code can call, as typed async Python functions. Do not also pass them to generateText. */
63
+ tools: TOOLS;
64
+ /**
65
+ * Where the code runs. Omitted, code mode creates `agentSandboxes()` on the first `run_code` call and closes it
66
+ * in `close()`. A pool you pass is yours to close. Its `requestTimeout`, which Monty takes in seconds, must be above `limits.timeout`, or a long
67
+ * snippet fails with a transport error instead of the time-limit message.
68
+ */
69
+ sandboxes?: Sandboxes;
70
+ /** Context for each tool, keyed by tool name, as generateText's `toolsContext`. */
71
+ context?: { [NAME in keyof TOOLS]?: unknown; };
72
+ /**
73
+ * Which nested calls may run, in the shape of generateText's `toolApproval`, without `'user-approval'`: nothing in
74
+ * the sandbox can wait for a person. An async function can ask one itself and return `'approved'` or `'denied'`,
75
+ * within `limits.timeout`. From untyped code, a `'user-approval'` status fails the call.
76
+ */
77
+ approval?: CodeModeApproval<TOOLS, RUNTIME_CONTEXT>;
78
+ /** Passed to `approval` functions; tool execution does not see generateText's `runtimeContext`. */
79
+ runtimeContext?: RUNTIME_CONTEXT;
80
+ limits?: CodeModeLimits;
81
+ /**
82
+ * Which snippets Monty's type checker sees (default `'first-snippet'`, as pydantic-ai). Monty's checker rejects
83
+ * some valid code, such as a None check on an indexed value, and a model can spend every step trying to satisfy
84
+ * it, so later snippets are not checked once one has passed.
85
+ */
86
+ typeCheck?: "every-snippet" | "first-snippet" | "off";
87
+ /**
88
+ * Milliseconds without a `run_code` call before the session is released (default 300,000; `Infinity` disables). It ends
89
+ * sessions of runs that stopped without `close()`, such as a stream cancelled without an abort signal. A later
90
+ * call gets a fresh session, and the model is told that earlier state is gone.
91
+ */
92
+ idleTimeout?: number;
93
+ /**
94
+ * Replaces the error the sandbox, the model and the trace see when a tool throws. Return a string or an error to
95
+ * replace it, or `undefined` to keep it. Messages pass through unchanged by default, as in pydantic-ai. A result
96
+ * that has no JSON form, such as a bigint or a cycle, is not a tool error, so this is not called for it.
97
+ */
98
+ onToolError?: (error: unknown, call: ToolErrorCall) => Error | string | undefined;
99
+ }
100
+ interface RunCodeInput {
101
+ code: string;
102
+ restart?: boolean | undefined;
103
+ }
104
+ interface CodeMode extends AsyncDisposable {
105
+ /** `{ run_code }`, to spread into generateText's or streamText's `tools`. */
106
+ readonly tools: {
107
+ run_code: Tool<RunCodeInput, unknown>;
108
+ };
109
+ /** Ends the session and, if code mode created it, the sandbox pool. Safe to call more than once. */
110
+ close(): Promise<void>;
111
+ /** Closes code mode once a streamText result settles, including on error and abort. */
112
+ closeWhenDone(result: {
113
+ finishReason: PromiseLike<unknown>;
114
+ }): Promise<void>;
115
+ }
116
+ /**
117
+ * Gives an AI SDK agent one `run_code` tool. The model writes Python, the code runs in one sandbox session for the
118
+ * life of this object, and `tools` become typed async functions inside it, so one model step can make many tool
119
+ * calls and keep their results in the sandbox instead of the model's context.
120
+ *
121
+ * Nothing starts here: the session is checked out on the first `run_code` call. Close it when the run ends, with
122
+ * `close()` or with `await using`, which awaits the same cleanup when the enclosing block exits:
123
+ *
124
+ * ```ts
125
+ * await using code = codeMode({ tools })
126
+ * const { text } = await generateText({ model, prompt, tools: code.tools, stopWhen: stepCountIs(10) })
127
+ * ```
128
+ *
129
+ * With `streamText`, use `closeWhenDone(result)` instead, because the block exits before the stream is read.
130
+ */
131
+ export declare function codeMode<TOOLS extends ToolSet, RUNTIME_CONTEXT = unknown>(options: CodeModeOptions<TOOLS, RUNTIME_CONTEXT>): CodeMode;
132
+ //#endregion
133
+ export type { CodeMode, CodeModeOptions };
@@ -0,0 +1,133 @@
1
+ import { MontySession, RemoteCheckoutOptions } from "@pydantic/monty";
2
+ import { Tool, ToolApprovalConfiguration, ToolApprovalStatus, ToolSet } from "ai";
3
+ //#region src/approval.d.ts
4
+ type AnyFunction = (...args: never[]) => unknown;
5
+ /** The AI SDK's statuses without `'user-approval'`: nothing in the sandbox can wait for a person. */
6
+ type CodeModeApprovalStatus = Exclude<ToolApprovalStatus, "user-approval" | {
7
+ type: "user-approval";
8
+ }>;
9
+ type NarrowedEntry<ENTRY> = ENTRY extends ((...args: infer ARGS) => unknown) ? (...args: ARGS) => CodeModeApprovalStatus | PromiseLike<CodeModeApprovalStatus> : Extract<ENTRY, CodeModeApprovalStatus>;
10
+ type ApprovalMap<TOOLS extends ToolSet, RUNTIME_CONTEXT> = Exclude<ToolApprovalConfiguration<TOOLS, RUNTIME_CONTEXT>, AnyFunction>;
11
+ /**
12
+ * generateText's `toolApproval`, narrowed so that `'user-approval'` does not compile. Accepting it today would mean
13
+ * "fail the call", and the same config would change meaning if code mode ever supports pausing for a person. Leaving
14
+ * it out means real approval can be added by widening this type.
15
+ */
16
+ type CodeModeApproval<TOOLS extends ToolSet, RUNTIME_CONTEXT> = NarrowedEntry<Extract<ToolApprovalConfiguration<TOOLS, RUNTIME_CONTEXT>, AnyFunction>> | { [NAME in keyof ApprovalMap<TOOLS, RUNTIME_CONTEXT>]: NarrowedEntry<ApprovalMap<TOOLS, RUNTIME_CONTEXT>[NAME]>; };
17
+ //#endregion
18
+ //#region src/limits.d.ts
19
+ /** Caps on what one `codeMode()` instance lets sandbox code do. Every field is optional. */
20
+ interface CodeModeLimits {
21
+ /**
22
+ * Milliseconds of wall-clock time per snippet, including time spent waiting on tools and sleeping (default 30,000).
23
+ * Also Monty's execution-time limit for the snippet's own code.
24
+ */
25
+ timeout?: number;
26
+ /** Nested tool calls per snippet (default 100). Calls past the budget fail without reaching the tool. */
27
+ toolCalls?: number;
28
+ /** Tool calls running on the host at the same time (default 8). More calls wait for a free slot. */
29
+ concurrentToolCalls?: number;
30
+ /**
31
+ * Bytes of JSON result sent to the model per snippet, and separately bytes of printed output (default 64,000).
32
+ * A larger result fails with a message asking for a smaller one; printed output is cut.
33
+ */
34
+ outputBytes?: number;
35
+ /** Bytes of source per snippet (default 100,000). */
36
+ codeBytes?: number;
37
+ /** Bytes of JSON arguments per nested call (default 1,000,000). */
38
+ toolInputBytes?: number;
39
+ /** Bytes of JSON result per nested call (default 10,000,000). */
40
+ toolOutputBytes?: number;
41
+ /** Bytes of sandbox heap (default 256 MiB). */
42
+ memory?: number;
43
+ /**
44
+ * Host interactions per session, which every tool call, sleep and future resolution uses (default 10,000).
45
+ * Monty's own default of 1,000 would end a long agent run partway through.
46
+ */
47
+ suspensions?: number;
48
+ }
49
+ //#endregion
50
+ //#region src/codeMode.d.ts
51
+ /** Where code runs: a pool such as `agentSandboxes()`, `MontyRemote.create()` or `Monty.create()`. */
52
+ interface Sandboxes {
53
+ checkout(options?: RemoteCheckoutOptions): Promise<MontySession>;
54
+ close(): Promise<void>;
55
+ }
56
+ interface ToolErrorCall {
57
+ toolName: string;
58
+ toolCallId: string;
59
+ input: unknown;
60
+ }
61
+ interface CodeModeOptions<TOOLS extends ToolSet, RUNTIME_CONTEXT = unknown> {
62
+ /** The tools sandbox code can call, as typed async Python functions. Do not also pass them to generateText. */
63
+ tools: TOOLS;
64
+ /**
65
+ * Where the code runs. Omitted, code mode creates `agentSandboxes()` on the first `run_code` call and closes it
66
+ * in `close()`. A pool you pass is yours to close. Its `requestTimeout`, which Monty takes in seconds, must be above `limits.timeout`, or a long
67
+ * snippet fails with a transport error instead of the time-limit message.
68
+ */
69
+ sandboxes?: Sandboxes;
70
+ /** Context for each tool, keyed by tool name, as generateText's `toolsContext`. */
71
+ context?: { [NAME in keyof TOOLS]?: unknown; };
72
+ /**
73
+ * Which nested calls may run, in the shape of generateText's `toolApproval`, without `'user-approval'`: nothing in
74
+ * the sandbox can wait for a person. An async function can ask one itself and return `'approved'` or `'denied'`,
75
+ * within `limits.timeout`. From untyped code, a `'user-approval'` status fails the call.
76
+ */
77
+ approval?: CodeModeApproval<TOOLS, RUNTIME_CONTEXT>;
78
+ /** Passed to `approval` functions; tool execution does not see generateText's `runtimeContext`. */
79
+ runtimeContext?: RUNTIME_CONTEXT;
80
+ limits?: CodeModeLimits;
81
+ /**
82
+ * Which snippets Monty's type checker sees (default `'first-snippet'`, as pydantic-ai). Monty's checker rejects
83
+ * some valid code, such as a None check on an indexed value, and a model can spend every step trying to satisfy
84
+ * it, so later snippets are not checked once one has passed.
85
+ */
86
+ typeCheck?: "every-snippet" | "first-snippet" | "off";
87
+ /**
88
+ * Milliseconds without a `run_code` call before the session is released (default 300,000; `Infinity` disables). It ends
89
+ * sessions of runs that stopped without `close()`, such as a stream cancelled without an abort signal. A later
90
+ * call gets a fresh session, and the model is told that earlier state is gone.
91
+ */
92
+ idleTimeout?: number;
93
+ /**
94
+ * Replaces the error the sandbox, the model and the trace see when a tool throws. Return a string or an error to
95
+ * replace it, or `undefined` to keep it. Messages pass through unchanged by default, as in pydantic-ai. A result
96
+ * that has no JSON form, such as a bigint or a cycle, is not a tool error, so this is not called for it.
97
+ */
98
+ onToolError?: (error: unknown, call: ToolErrorCall) => Error | string | undefined;
99
+ }
100
+ interface RunCodeInput {
101
+ code: string;
102
+ restart?: boolean | undefined;
103
+ }
104
+ interface CodeMode extends AsyncDisposable {
105
+ /** `{ run_code }`, to spread into generateText's or streamText's `tools`. */
106
+ readonly tools: {
107
+ run_code: Tool<RunCodeInput, unknown>;
108
+ };
109
+ /** Ends the session and, if code mode created it, the sandbox pool. Safe to call more than once. */
110
+ close(): Promise<void>;
111
+ /** Closes code mode once a streamText result settles, including on error and abort. */
112
+ closeWhenDone(result: {
113
+ finishReason: PromiseLike<unknown>;
114
+ }): Promise<void>;
115
+ }
116
+ /**
117
+ * Gives an AI SDK agent one `run_code` tool. The model writes Python, the code runs in one sandbox session for the
118
+ * life of this object, and `tools` become typed async functions inside it, so one model step can make many tool
119
+ * calls and keep their results in the sandbox instead of the model's context.
120
+ *
121
+ * Nothing starts here: the session is checked out on the first `run_code` call. Close it when the run ends, with
122
+ * `close()` or with `await using`, which awaits the same cleanup when the enclosing block exits:
123
+ *
124
+ * ```ts
125
+ * await using code = codeMode({ tools })
126
+ * const { text } = await generateText({ model, prompt, tools: code.tools, stopWhen: stepCountIs(10) })
127
+ * ```
128
+ *
129
+ * With `streamText`, use `closeWhenDone(result)` instead, because the block exits before the stream is read.
130
+ */
131
+ export declare function codeMode<TOOLS extends ToolSet, RUNTIME_CONTEXT = unknown>(options: CodeModeOptions<TOOLS, RUNTIME_CONTEXT>): CodeMode;
132
+ //#endregion
133
+ export type { CodeMode, CodeModeOptions };
package/dist/index.js ADDED
@@ -0,0 +1,28 @@
1
+ import{context as e}from"@opentelemetry/api";import{agentSandboxes as t}from"@pydantic/logfire-agent-sandboxes";import{MontyCrashedError as n,MontyRuntimeError as r,MontySyntaxError as i,MontyTypingError as a,NOT_HANDLED as o}from"@pydantic/monty";import{asSchema as s,jsonSchema as c,tool as l}from"ai";import*as u from"logfire";import{setTimeout as d}from"node:timers/promises";async function f(e,{tools:t,toolsContext:n,runtimeContext:r},i){if(e===void 0)return{approved:!0};let a;if(typeof e==`function`){let{tool:o}=i;a=await e({toolCall:{type:`tool-call`,toolCallId:i.toolCallId,toolName:i.toolName,input:i.input,...o.metadata===void 0||o.metadata===null?{}:{toolMetadata:o.metadata},...o.type===`dynamic`?{dynamic:!0}:{},title:o.title},tools:t,toolsContext:n,runtimeContext:r,messages:i.messages})}else{let t=Object.hasOwn(e,i.toolName)?e[i.toolName]:void 0;a=typeof t==`function`?await t(i.input,{toolCallId:i.toolCallId,messages:i.messages,toolContext:i.toolContext,runtimeContext:r}):t}let o=typeof a==`object`?a.type:a,s=typeof a==`object`?a.reason:void 0;return o===void 0||o===`not-applicable`||o===`approved`?{approved:!0}:{approved:!1,reason:s,needsUser:o===`user-approval`}}const p={timeout:3e4,toolCalls:100,concurrentToolCalls:8,outputBytes:64e3,codeBytes:1e5,toolInputBytes:1e6,toolOutputBytes:1e7,memory:268435456,suspensions:1e4},m=/* @__PURE__ */ new Set([`toolCalls`,`concurrentToolCalls`,`memory`,`suspensions`]);function h(e={}){let t={...p};for(let[n,r]of Object.entries(e)){if(!(n in p))throw TypeError(`Unknown code mode limit "${n}". The limits are: ${Object.keys(p).join(`, `)}.`);if(r!==void 0){if(!(typeof r==`number`&&r>0&&Number.isFinite(r)&&(!m.has(n)||Number.isSafeInteger(r)))){let e=m.has(n)?`a positive integer`:`a positive number`;throw RangeError(`The code mode limit "${n}" must be ${e}, not ${JSON.stringify(r)}.`)}t[n]=r}}return t}const g=/* @__PURE__ */ new Set(/* @__PURE__ */ `False.None.True.and.as.assert.async.await.break.class.continue.def.del.elif.else.except.finally.for.from.global.if.import.in.is.lambda.nonlocal.not.or.pass.raise.return.try.while.with.yield`.split(`.`));function _(e){return g.has(e)}const v=/* @__PURE__ */ new Set(/* @__PURE__ */ `ArithmeticError.AssertionError.AttributeError.BaseException.BaseExceptionGroup.BlockingIOError.BrokenPipeError.BufferError.BytesWarning.ChildProcessError.ConnectionAbortedError.ConnectionError.ConnectionRefusedError.ConnectionResetError.DeprecationWarning.EOFError.Ellipsis.EncodingWarning.EnvironmentError.Exception.ExceptionGroup.False.FileExistsError.FileNotFoundError.FloatingPointError.FutureWarning.GeneratorExit.IOError.ImportError.ImportWarning.IndentationError.IndexError.InterruptedError.IsADirectoryError.KeyError.KeyboardInterrupt.LookupError.MemoryError.ModuleNotFoundError.NameError.None.NotADirectoryError.NotImplemented.NotImplementedError.OSError.OverflowError.PendingDeprecationWarning.PermissionError.ProcessLookupError.PythonFinalizationError.RecursionError.ReferenceError.ResourceWarning.RuntimeError.RuntimeWarning.StopAsyncIteration.StopIteration.SyntaxError.SyntaxWarning.SystemError.SystemExit.TabError.TimeoutError.True.TypeError.UnboundLocalError.UnicodeDecodeError.UnicodeEncodeError.UnicodeError.UnicodeTranslateError.UnicodeWarning.UserWarning.ValueError.Warning.ZeroDivisionError.abs.aiter.all.anext.any.ascii.bin.bool.breakpoint.bytearray.bytes.callable.chr.classmethod.compile.complex.copyright.credits.delattr.dict.dir.divmod.enumerate.eval.exec.exit.filter.float.format.frozenset.getattr.globals.hasattr.hash.help.hex.id.input.int.isinstance.issubclass.iter.len.license.list.locals.map.max.memoryview.min.next.object.oct.open.ord.pow.print.property.quit.range.repr.reversed.round.set.setattr.slice.sorted.staticmethod.str.sum.super.tuple.type.vars.zip`.split(`.`));function y(e){return v.has(e)}function b(e){return/^[\p{XID_Start}_]\p{XID_Continue}*$/u.test(e)}function x(e){return b(e)&&!_(e)}function S(e){return e==null?`None`:typeof e==`boolean`?e?`True`:`False`:typeof e==`number`?ee(e):typeof e==`string`?ne(e):Array.isArray(e)?`[${e.map(S).join(`, `)}]`:typeof e==`object`?`{${Object.entries(e).map(([e,t])=>`${ne(e)}: ${S(t)}`).join(`, `)}}`:typeof e==`bigint`?e.toString():`None`}function ee(e){let t=JSON.stringify(e);if(/^-?\d+$/u.test(t))return t;let[n=``,r=`0`]=e.toExponential().split(`e`),i=Number(r),a=n.startsWith(`-`),o=n.replace(/[-.]/gu,``),s=a?`-`:``;if(i<-4||i>=16){let e=o.length>1?`.${o.slice(1)}`:``,t=i<0?`-`:`+`;return`${s}${o[0]??``}${e}e${t}${String(Math.abs(i)).padStart(2,`0`)}`}return i<0?`${s}0.${`0`.repeat(-i-1)}${o}`:`${s}${o.slice(0,i+1).padEnd(i+1,`0`)}.${o.slice(i+1)||`0`}`}const te=/[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Cn}\p{Zl}\p{Zp}\p{Zs}]/u;function ne(e){let t=e.includes(`'`)&&!e.includes(`"`)?`"`:`'`,n=t;for(let r of e)if(r===t||r===`\\`)n+=`\\${r}`;else if(r===` `)n+=`\\t`;else if(r===`
2
+ `)n+=`\\n`;else if(r===`\r`)n+=`\\r`;else if(r!==` `&&te.test(r)){let e=r.codePointAt(0)??0;n+=e<256?`\\x${e.toString(16).padStart(2,`0`)}`:e<65536?`\\u${e.toString(16).padStart(4,`0`)}`:`\\U${e.toString(16).padStart(8,`0`)}`}else n+=r;return n+t}const re='Write and run Python code in a sandboxed environment.\n\nThe sandbox uses Monty, a subset of Python. Key restrictions:\n- **No third-party libraries**: only the standard library modules listed below can be used\n- **Importable standard library modules**: `sys`, `typing`, `asyncio`, `math`, `json`, `re`, `unicodedata`, `datetime`, `time`, `random`, `os`, `pathlib`, `collections`, `itertools`, `functools`, `dataclasses`, `copy`, `base64`, `binascii`, `bisect`, `csv`, `decimal`, `fnmatch`, `hashlib`, `os.path`, `tomllib`, `annotationlib`. These must be imported before use, just like in regular Python.\n- **No filesystem, environment, or clock**: `pathlib.Path` I/O, `os.getenv`/`os.environ`, `datetime.datetime.now()`, `datetime.date.today()`, and `time.time()` are unavailable here (no filesystem mount or OS handler is configured). `os` and `pathlib` import successfully, but their I/O operations are not supported in this configuration. `time.sleep` and `asyncio.sleep` really wait.\n- **No `import *`**: wildcard imports are not supported\n\nState is preserved between calls (REPL-style). Set `restart: true` to reset state.\n\nThe last expression\'s value is automatically captured as the return value -- you do **not** need to `print()` it. End the snippet with the value to return as a bare expression. A final assignment stores the value but does not return it. A final expression that evaluates to `None` is treated as no result. Without a non-`None` final expression or print output, `run_code` returns `{}`. For example:\n\n```python\nresult = some_expression\nresult\n```\n\nAvoid `print()` for return values as it produces Python string representations, not structured data. Use `print()` only for supplementary logging or debug output.\n\nReturns a non-`None` last expression\'s value directly when nothing is printed. With `print()` output and no non-`None` final expression, returns `{"output": "<printed text>"}`. With `print()` output and a plain, non-`None` final expression, returns `{"output": "<printed text>", "result": <last expression>}`. With `print()` output and a multimodal final expression, returns a list with the printed text followed by the native content.';function ie(e,t){if(t.length===0)return re;let n=["\nThe following functions are available inside the sandbox. These functions are already defined in the sandbox; call them by name without redefining or importing them. All parameters are keyword-only. All tool functions are async: invoke them with `await`, e.g. `await tool_name(arg=value)`. Calling without `await` returns an unresolved future, not the value.\n\nTo run calls concurrently, first `import asyncio`, then use `await asyncio.gather(...)` with positional awaitables. Monty does not support `asyncio.gather` keyword arguments or other task creation and wait APIs."];return e.length>0&&n.push("```python\n"+e.join(`
3
+
4
+ `)+"\n```"),n.push("```python\n"+t.join(`
5
+
6
+ `)+"\n```"),`${re}\n\n${n.join(`
7
+
8
+ `)}`}let C,w=/* @__PURE__ */ new Set;var T=class{kind=`simple`;name;constructor(e){this.name=e}toString(){return this.name}},ae=class{kind=`literal`;values;constructor(e){this.values=e}toString(){return`Literal[${this.values.map(S).join(`, `)}]`}},E=class{kind=`generic`;base;args;constructor(e,t){this.base=e,this.args=t}toString(){return`${this.base}[${this.args.map(String).join(`, `)}]`}},D=class{kind=`union`;members;constructor(e){this.members=e}toString(){return this.members.map(String).join(` | `)}};const oe=` `;function se(e){return e.replace(/[\\\0"]/gu,e=>e===`\\`?`\\\\`:e===`\0`?`\\x00`:`\\"`)}const ce=`\\s\\x1c-\\x1f\\x85`,le=RegExp(`^[${ce}]+|[${ce}]+$`,`gu`),ue=/\r\n|[\n\r\v\f\x1c-\x1e\x85\u2028\u2029]/u,de=RegExp(`[${ce}]+$`,`u`);function O(e){return e.replace(le,``)}function fe(e){return e.replace(de,``)}function k(e){if(e===``)return[];let t=e.split(ue);return t.at(-1)===``&&ue.test(e.at(-1)??``)&&t.pop(),t}function A(e){return e!==void 0&&e!==``}function pe(e,t=``){let n=se(O(e)),r=k(n);return r.length>1?[`${t}"""`,...r.map(e=>O(e)?`${t}${e}`:``),`${t}"""`]:[`${t}"""${n}"""`]}function me(e){let t=e.replace(/[^a-zA-Z0-9_]/gu,`_`);return/^[0-9]/u.test(t)&&(t=`_${t}`),_(t)&&(t=`${t}_`),t||`_`}function he(e,t=``){return k(O(e).replace(/\0/gu,`\\x00`)).map(e=>fe(`${t}# ${e}`))}var ge=class{kind=`field`;name;type;required;description;constructor(e,t,n=!1,r){this.name=e,this.type=t,this.required=n,this.description=r}toString(){let e=[` ${this.name}: ${_e(this)}`];return A(this.description)&&e.push(...pe(this.description,` `)),e.join(`
9
+ `)}};function _e(e){let t=String(e.type);return e.required?t:`NotRequired[${t}]`}function ve(e){let t=A(e.description)?he(e.description,` `):[];return t.push(` ${S(e.name)}: ${_e(e)},`),t.join(`
10
+ `)}var j=class{kind=`type`;name;description;fields;constructor(e,t,n=/* @__PURE__ */ new Map){this.name=e,this.description=t,this.fields=n}get displayName(){if(C===void 0||!C.conflicting.has(this.name))return this.name;let e=C.typeNames.get(this);if(e!==void 0)return e;let t=C.fallbackOwner;return A(t)?`${t}_${this.name}`:this.name}toString(){return this.displayName}renderDefinition(e,t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Map){return Se({conflicting:t,typeNames:n,fallbackOwner:e},()=>this.renderDefinitionBody())}renderDefinitionBody(){if(![...this.fields.keys()].every(x))return this.renderFunctionalDefinition();let e=[`class ${this.displayName}(TypedDict):`];if(A(this.description)&&e.push(...pe(this.description,` `)),this.fields.size===0)A(this.description)||e.push(` pass`);else for(let t of this.fields.values())e.push(String(t));return e.join(`
11
+ `)}renderFunctionalDefinition(){let e=A(this.description)?he(this.description):[];return e.push(`${this.displayName} = TypedDict(${S(this.displayName)}, {`),e.push(...[...this.fields.values()].map(ve)),e.push(`})`),e.join(`
12
+ `)}structurallyEqual(e){return ye(this,e,/* @__PURE__ */ new Map)}};function ye(e,t,n){if(e===t||n.get(e)?.has(t)===!0)return!0;if(n.set(e,/* @__PURE__ */ new Set([...n.get(e)??[],t])),e.fields.size!==t.fields.size)return!1;for(let[r,i]of e.fields){let e=t.fields.get(r);if(e===void 0||i.required!==e.required||!be(i.type,e.type,n))return!1}return!0}function be(e,t,n){return e instanceof j&&t instanceof j?e.name===t.name&&ye(e,t,n):e instanceof E&&t instanceof E?e.base===t.base&&xe(e.args,t.args,n):e instanceof D&&t instanceof D?xe(e.members,t.members,n):e.kind===t.kind&&String(e)===String(t)}function xe(e,t,n){return e.length===t.length&&e.every((e,r)=>{let i=t[r];return i!==void 0&&be(e,i,n)})}var M=class{kind=`param`;name;type;defaultValue;description;constructor(e,t,n,r){this.name=e,this.type=t,this.defaultValue=n,this.description=r}toString(){let e=String(this.type);return this.defaultValue===void 0?`${this.name}: ${e}`:`${this.name}: ${e} = ${this.defaultValue}`}},N=class e{kind=`function`;name;params;returnType;referencedTypes;description;isAsync;constructor(e,t,n,r,i,a=!1){this.name=e,this.params=t,this.returnType=n,this.referencedTypes=r,this.description=i,this.isAsync=a}render(e,t={}){let n=t.name!==void 0&&t.name!==``?t.name:this.name,r=t.description??this.description;return Se({conflicting:t.conflictingTypeNames??/* @__PURE__ */ new Set,typeNames:t.typeNames??/* @__PURE__ */ new Map,fallbackOwner:n},()=>this.renderBody(e,n,r,t.isAsync))}renderBody(e,t,n,r){let i=r??this.isAsync?`async def`:`def`,a=[...this.params.values()].map(String).join(`, `),o=String(this.returnType),s=[a?`${i} ${t}(*, ${a}) -> ${o}:`:`${i} ${t}() -> ${o}:`],c=A(n)?[n]:[],l=[];for(let e of this.params.values()){let[t,...n]=k(O(e.description??``));t!==void 0&&(l.push(`${oe}${e.name}: ${t}`),l.push(...n.map(e=>`${oe}${oe}${e}`)))}l.length>0&&c.push([`Args:`,...l].join(`
13
+ `));let u=c.join(`
14
+
15
+ `);return u!==``&&s.push(...pe(u,` `)),s.push(` ${e}`),s.join(`
16
+ `)}static fromSchema(t,n,r){let i=Ee(n),a=/* @__PURE__ */ new Map;Ae(i,a,t);let o=je(n,i,a,t),s=P,c=/* @__PURE__ */ new Map;if(r!==void 0){let e=Ee(r);Ae(e,c,t),s=V(r,e,c,t,`Return`)}let l=[...a.values()],u=/* @__PURE__ */ new Map;for(let e of c.values()){let t=a.get(e.name);if(t?.structurallyEqual(e)===!0){u.set(e,t);continue}l.push(e)}s=U(s,u);for(let e of l)for(let t of e.fields.values())t.type=U(t.type,u);return new e(t,o,s,l)}static getConflictingTypeNames(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Set;for(let r of e){let e=[];for(let i of r.referencedTypes){let a=t.get(i.name);a===void 0?(t.set(i.name,i),e.push(i)):a.structurallyEqual(i)?(Ue(r,i,a),e.push(a)):(n.add(i.name),e.push(i))}r.referencedTypes=e}return n}static collectUniqueReferencedTypes(e){let t=/* @__PURE__ */ new Set,n=[];for(let r of e)for(let e of r.referencedTypes)t.has(e)||(t.add(e),n.push(e));return n}static prefixedTypeNames(t,n){let r=/* @__PURE__ */ new Set;for(let i of e.collectUniqueReferencedTypes(t))n.has(i.name)||r.add(i.name);let i=/* @__PURE__ */ new Map;for(let e of t)for(let t of e.referencedTypes){if(!n.has(t.name)||i.has(t))continue;let a=`${e.name}_${t.name}`,o=a;for(let e=2;r.has(o);e++)o=`${a}_${String(e)}`;r.add(o),i.set(t,o)}return i}static renderTypeDefinitions(t,n){let r=e.collectUniqueReferencedTypes(t),i=e.prefixedTypeNames(t,n);return r.map(e=>e.renderDefinition(void 0,n,i))}};function Se(e,t){let n=C;C=e;try{return t()}finally{C=n}}const P=new T(`Any`),F=new T(`None`),Ce=/* @__PURE__ */ new Map([[`string`,`str`],[`integer`,`int`],[`number`,`float`],[`boolean`,`bool`],[`null`,`None`]]);function we(e){return new T(Ce.get(e)??`Any`)}function Te(e){return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}function I(e){let t=e.replace(/[^a-zA-Z0-9]/gu,`_`).split(`_`).filter(Boolean).map(Te).join(``);return/^[0-9]/u.test(t)?`_${t}`:t}function L(e,t){return[e,...t.split(`.`).filter(Boolean)].map(I).join(``)}function R(e){return typeof e==`string`&&e!==``?e:void 0}function z(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function B(e){return z(e)?e:{}}function Ee(e){let t=e.$defs;return z(t)?t:{}}function De(e){let t=e.properties;return z(t)?t:{}}function Oe(e){let t=e.required;return new Set(Array.isArray(t)?t:[])}function ke(e){return e.type===`object`&&`properties`in e}function Ae(e,t,n){for(let[r,i]of Object.entries(e)){let a=B(i);ke(a)&&!t.has(r)&&H(r,a,e,t,n,r)}}function je(e,t,n,r){let i=Oe(e),a=De(e),o=Me(Object.keys(a)),s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Map;for(let[e,l]of Object.entries(a)){let a=B(l),u=V(a,t,n,r,e),d=R(a.description),f=o.get(e)??e;`default`in a?c.set(e,new M(f,u,S(a.default),d)):i.has(e)?s.set(e,new M(f,u,void 0,d)):Ne(a)?c.set(e,new M(f,u,`None`,d)):c.set(e,new M(f,new D([u,F]),`None`,d))}return new Map([...s,...c])}function Me(e){let t=[...e],n=new Set(t.filter(x)),r=/* @__PURE__ */ new Map;for(let e of t){if(x(e)){r.set(e,e);continue}let t=me(e),i=t;for(let e=2;n.has(i);e++)i=`${t}_${String(e)}`;n.add(i),r.set(e,i)}return r}function Ne(e){let t=e.type;if(Array.isArray(t)&&t.includes(`null`))return!0;for(let t of[`anyOf`,`oneOf`])if(t in e){let n=e[t];return Array.isArray(n)&&n.some(e=>B(e).type===`null`)}return!1}function V(e,t,n,r,i){let a=B(e);if(`$ref`in a){let e=String(a.$ref).split(`/`).at(-1)??``;if(Object.hasOwn(t,e)&&!n.has(e)){let a=B(t[e]);if(ke(a))H(e,a,t,n,r,i);else{if(w.has(e))return P;let o=w;w=/* @__PURE__ */ new Set([...o,e]);try{return V(a,t,n,r,i)}finally{w=o}}}return n.get(e)??new j(e)}if(`anyOf`in a)return Le(a.anyOf,t,n,r,i);if(`oneOf`in a)return Le(a.oneOf,t,n,r,i);if(`allOf`in a){let e=a.allOf;return e.length===1?V(e[0],t,n,r,i):P}return`const`in a?new ae([a.const]):`enum`in a?new ae(a.enum):Pe(a.type,a,t,n,r,i)}function Pe(e,t,n,r,i,a){let o=Ce.get(e);if(o!==void 0)return new T(o);if(e===`array`){let e=t.items??{};return Fe(e)?Array.isArray(e)?new E(`tuple`,e.map((e,t)=>V(e,n,r,i,`${a}.${String(t)}`))):new E(`list`,[V(e,n,r,i,`${a}Item`)]):new E(`list`,[P])}if(e===`object`){if(`properties`in t){let e=t.title,o=typeof e==`string`&&e!==``&&b(e)?e:L(i,a),s=Object.hasOwn(n,o)?B(n[o]):void 0;return s!==void 0&&ke(s)&&!r.has(o)&&H(o,s,n,r,i,o),r.has(o)?Ve(o,t,n,r,i,a):H(o,t,n,r,i,a)}if(`additionalProperties`in t){let e=t.additionalProperties;if(e===!0)return new E(`dict`,[new T(`str`),P]);if(z(e)){let t=V(e,n,r,i,`${a}Value`);return new E(`dict`,[new T(`str`),t])}}return new E(`dict`,[new T(`str`),P])}return Array.isArray(e)?Ie(e,t,n,r,i,a):P}function Fe(e){return Array.isArray(e)?e.length>0:z(e)?Object.keys(e).length>0:!!e}function Ie(e,t,n,r,i,a){if(e.includes(`object`)&&`properties`in t){let o=Pe(`object`,t,n,r,i,a);return e.includes(`null`)?new D([o,F]):o}let o=e.map(we),s=o.find(e=>String(e)!==`None`);if(o.length===2&&s!==void 0&&o.some(e=>String(e)===`None`))return new D([s,F]);let[c,...l]=o;return c===void 0?P:l.length>0?new D(o):c}function Le(e,t,n,r,i){let a=e.map(B),o=Re(a,i),s=[],c=!1;for(let e of a)e.type===`null`?c=!0:s.push(V(e,t,n,r,o.get(e)??i));let l=/* @__PURE__ */ new Set,u=[];for(let e of s){let t=String(e);l.has(t)||(l.add(t),u.push(e))}c&&u.push(F);let[d,...f]=u;return d!==void 0&&f.length===0?d:new D(u)}function Re(e,t){let n=e.filter(e=>e.type===`object`&&`properties`in e&&!ze(e)),r=/* @__PURE__ */ new Map;if(n.length<2)return r;let i=n.map(Be),a=i.every(e=>e!==void 0)&&new Set(i.map(e=>I(e))).size===i.length;return n.forEach((e,n)=>{r.set(e,`${t}.${a?i[n]??``:String(n+1)}`)}),r}function ze(e){let t=e.title;return typeof t==`string`&&t!==``&&b(t)}function Be(e){for(let t of Object.values(De(e))){let e=B(t).const;if(typeof e==`string`&&I(e)!==``)return e}}function Ve(e,t,n,r,i,a){let o=He(e,t,n,r,i,a);for(let t=1;;t++){let n=t===1?e:`${e}_${String(t)}`,i=r.get(n);if(i===void 0){let e=new j(n,o.description,o.fields);return r.set(n,e),e}if(i.structurallyEqual(o))return i}}function H(e,t,n,r,i,a){let o=new j(e);r.set(e,o);let s=He(e,t,n,r,i,a);return o.fields=s.fields,o.description=s.description,o}function He(e,t,n,r,i,a){let o=Oe(t),s=/* @__PURE__ */ new Map;for(let[e,c]of Object.entries(De(t))){let t=B(c),l=V(t,n,r,i,a?`${a}.${e}`:e),u=R(t.description);s.set(e,new ge(e,l,o.has(e),u))}return new j(e,R(t.description),s)}function U(e,t){if(e instanceof j)return t.get(e)??e;if(e instanceof E){let n=e.args.map(e=>U(e,t));n.some((t,n)=>t!==e.args[n])&&(e.args=n)}else if(e instanceof D){let n=e.members.map(e=>U(e,t));n.some((t,n)=>t!==e.members[n])&&(e.members=n)}return e}function Ue(e,t,n){let r=/* @__PURE__ */ new Map([[t,n]]);for(let t of e.params.values())t.type=U(t.type,r);e.returnType=U(e.returnType,r);for(let t of e.referencedTypes)for(let e of t.fields.values())e.type=U(e.type,r)}function We(e,t,n){let r=structuredClone(e),i=Ge(r,t);if(delete r.$schema,n===`parameters`&&typeof r.$ref==`string`)throw Error(`Tool "${t}" has a parameters schema that is only a reference, which code mode cannot read`);let a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Set,s=(e,n)=>{if(o.has(n))throw Error(`Tool "${t}" has two schema definitions that both become the Python type "${n}"`);o.add(n),a.set(e,n)},c;G([r,...Object.values(i)],`#`)&&(c=Je(r.title,void 0,()=>L(t,n===`return`?`Return`:``)),o.add(c));let l=Ze(r,i,n);for(let[e,n]of Object.entries(i))s(e,Je(W(n)?n.title:void 0,e,()=>L(t,l.get(e)??e)));let u=e=>q(e,t,a,c),d=u(r),f={};for(let[e,t]of a)f[t]=u(i[e]);if(c!==void 0){let e={...d};delete e.$defs,f[c]=e}return Object.keys(f).length>0&&(d.$defs=f),d}function W(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ge(e,t){let n={},r=[e.definitions,e.$defs];delete e.definitions,delete e.$defs;for(let e of r)if(W(e))for(let[r,i]of Object.entries(e)){if(Object.hasOwn(n,r))throw Error(`Tool "${t}" defines "${r}" in both "definitions" and "$defs"`);n[r]=i}return n}function G(e,t){return Array.isArray(e)?e.some(e=>G(e,t)):W(e)?e.$ref===t||Object.entries(e).some(([e,n])=>!Ye.has(e)&&G(n,t)):!1}const Ke=/^__schema\d+$/u,qe=/* @__PURE__ */ new Set([`asyncio`,`Any`,`TypedDict`,`NotRequired`,`Literal`,`str`,`int`,`float`,`bool`,`list`,`dict`,`tuple`]);function K(e){return x(e)&&!qe.has(e)}function Je(e,t,n){if(t!==void 0&&K(t)&&!Ke.test(t))return t;if(typeof e==`string`&&K(e))return e;if(t!==void 0&&!Ke.test(t)){let e=I(t);if(K(e))return e}return n()}const Ye=/* @__PURE__ */ new Set([`default`,`const`,`enum`,`examples`]),Xe=/* @__PURE__ */ new Set([`properties`,`patternProperties`,`$defs`,`definitions`]);function Ze(e,t,n){let r=/* @__PURE__ */ new Map,i=(e,n)=>{if(Array.isArray(e)){for(let t of e)i(t,n);return}if(!W(e))return;let a=e.$ref;if(typeof a==`string`){let e=Qe(a);e!==void 0&&Object.hasOwn(t,e)&&!r.has(e)&&(r.set(e,n),i(t[e],n))}let o=e.properties;if(W(o))for(let[e,t]of Object.entries(o))i(t,n?`${n}.${e}`:e);let s=e.items;Array.isArray(s)?s.forEach((e,t)=>{i(e,`${n}.${String(t)}`)}):i(s,`${n}Item`),i(e.additionalProperties,`${n}Value`);for(let t of[`anyOf`,`oneOf`,`allOf`])i(e[t],n)};return i(e,n===`return`?`Return`:``),r}function Qe(e){return/^#\/(?:definitions|\$defs)\/([^/]+)$/u.exec(e)?.[1]?.replace(/~1/gu,`/`).replace(/~0/gu,`~`)}function q(e,t,n,r){if(Array.isArray(e))return e.map(e=>q(e,t,n,r));if(!W(e))return e;let i={};for(let[a,o]of Object.entries(e))if(Xe.has(a)&&W(o))i[a]=Object.fromEntries(Object.entries(o).map(([e,i])=>[e,q(i,t,n,r)]));else if(Ye.has(a))i[a]=o;else if(a===`$ref`&&typeof o==`string`)i[a]=$e(o,t,n,r);else if(a===`title`&&typeof o==`string`&&!K(o))continue;else i[a]=q(o,t,n,r);return i}function $e(e,t,n,r){if(e===`#`&&r!==void 0)return`#/$defs/${r}`;let i=Qe(e),a=i===void 0?void 0:n.get(i);if(a===void 0)throw Error(`Tool "${t}" has a schema reference "${e}" that code mode cannot resolve`);return`#/$defs/${a}`}const et=`import asyncio
17
+ from typing import Any, TypedDict, NotRequired, Literal`,tt=new Set(et.split(`
18
+ `).flatMap(e=>e.replace(/^(?:from \S+ )?import /u,``).split(`, `)));function nt(e){let{functions:t,toolNames:n}=rt(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{...it(t),toolNames:n,schemaArgNames:r}}function rt(e){let t=[],n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map;for(let[i,a]of Object.entries(e)){let e=at(i);if(e===`run_code`)throw Error(`Tool "${i}" becomes the Python function "${e}", which code mode reserves for itself. Rename the tool.`);if(tt.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:ct(i,a);if(s===void 0&&dt(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(ot(i,a),e,`parameters`),returnSchema:s===void 0?void 0:We(s,e,`return`)})}return{functions:t,toolNames:n}}function it(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:[et,...a,...o(`raise NotImplementedError()`)].join(`
19
+
20
+ `)}}function at(e){return me(e)}function ot(e,t){return J(e,s(t.inputSchema).jsonSchema)}function st(e){let t=(e?.[`~standard`])?.jsonSchema?.output;return typeof t==`function`?t:void 0}function ct(e,t){let n=st(t.outputSchema);return n===void 0?J(e,s(t.outputSchema).jsonSchema):J(e,n({target:`draft-07`}))}function lt(e){return typeof e.then==`function`}function J(e,t){if(lt(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 ut=/* @__PURE__ */ new WeakSet;function dt(e,t){ut.has(t)||(ut.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 ft(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 pt(e){return typeof e==`number`&&!Number.isFinite(e)?Number.isNaN(e)?`nan`:e>0?`inf`:`-inf`:Array.isArray(e)?e.map(pt):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,pt(t)])):e}function mt(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 ht(e,t,n){return e>t?` ... (${String(e)} ${n} total)`:``}function Z(e,t=!1){if(typeof e==`string`)return S(e.slice(0,120))+ht(e.length,120,`chars`);if(Array.isArray(e))return t?`[${String(e.length)} items]`:`[${e.slice(0,5).map(e=>Z(e,!0)).join(`, `)}]`+ht(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(`, `)}}`+ht(n.length,5,`items`)}return e==null||typeof e==`boolean`||typeof e==`number`?S(e):`<object>`}function gt(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 _t(e){return new It(e)}function Q(e,t){let n=Error(t);return n.name=e,n}function vt(e){return e instanceof Error?e.message:String(e)}const yt=2e3;function bt(e){let t=vt(e);return t.length>yt?`${t.slice(0,yt)} ... (${String(t.length)} chars total)`:t}function xt(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 ft(r,n)}catch(t){throw t instanceof Y?Q(`ValueError`,Ct(e,n)):t}}function St(e,t){return t===void 0?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[t.get(e)??e,n]))}function Ct(e,t){return`The arguments to ${e}() are more than ${String(t)} bytes of JSON, over the limit for one call.`}function wt(){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 Tt(e){let t=JSON.stringify(e??null,wt());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 Et(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 Dt(e){return e.aborted?`stopped`:new Promise(t=>{e.addEventListener(`abort`,()=>{t(`stopped`)},{once:!0})})}var Ot=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()}},kt=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 At(e){return String(e.timeout/1e3)}var jt=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 kt(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 ${At(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${gt(this.calls)}`}};const Mt=/^suspension limit [0-9]+ exceeded$/u,Nt=[`time limit exceeded`,`memory limit exceeded`,`suspension limit `];function Pt(e){return e.traceback().length===0&&e.display(`msg`).includes(`time limit exceeded`)}function Ft(e){return e.exception.typeName===`MemoryError`&&e.display(`msg`).startsWith(`memory limit exceeded`)}var It=class{tools;limits;idleTimeout;pythonNames;schemaArgNames;typeCheckStubs;queue=Promise.resolve();poolPromise;sessionPromise;passedTypeCheck=!1;expired=!1;idleTimer;current;closing;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=h(t.limits),this.slots=new Ot(this.limits.concurrentToolCalls),this.idleTimeout=i;let a=nt(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(y(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:l({description:ie(a.typeDefinitions,a.functions),inputSchema:c({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)=>this.enqueue(e,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){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();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 jt(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 feed(e,t,n){let o;try{o=await this.session()}catch(e){throw t.stopped===void 0?Error(this.describeFailure(e,t).message,{cause:e}):this.stoppedError(t,!1)}if(t.stopped!==void 0)throw this.stoppedError(t,!1);let s,c,l=!1,u=!1;t.start();let d=this.options.typeCheck===`off`||this.options.typeCheck!==`every-snippet`&&this.passedTypeCheck,f=o.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,Dt(t.signal)]);p===`stopped`?(u=!0,this.abandonSession(o,f)):p.ok?(s=p.result,l=!0,this.passedTypeCheck=!0):(c=p.error,this.passedTypeCheck||=!(c instanceof a||c instanceof i));let m=t.reason();if(m===`closed`||m===`aborted`)throw this.stoppedError(t,!0);if(m===`deadline`){u||await this.releaseSession();let e=c instanceof r?`Runtime error:\n${t.printed.prependTo(this.cut(c.display(`traceback`)))}\n\n`:``;throw Error(`${e}The code ran longer than its ${At(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.`+t.startedCalls())}if(!l){let e=this.describeFailure(c,t);throw e.reset&&await this.releaseSession(),Error(e.message,{cause:c})}return this.shapeResult(s,t)}shapeResult(e,t){let{outputBytes:n}=this.limits,r=/* @__PURE__ */ Error(`The result is more than ${String(n)} 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.`),i;try{i=pt(ft(e,n))}catch(e){throw e instanceof Y?r:e}if(X(JSON.stringify(i??null))>n)throw r;let a=t.printed.output;return a===``?i??{}:i==null?{output:a}:{output:a,result:i}}cut(e){return mt(e,this.limits.outputBytes)}describeFailure(e,t){let{printed:o}=t;if(e instanceof i)return{message:`Syntax error in code:\n${o.prependTo(this.cut(e.display(`traceback`)))}`,reset:!1};if(e instanceof a)return{message:`Type error in code:\n${o.prependTo(this.cut(e.display()))}`,reset:!1};if(e instanceof r){let n=`Runtime error:\n${o.prependTo(this.cut(e.display(`traceback`)))}`,r=e.display(`msg`);(t.budgetExhausted||Nt.some(e=>r.includes(e)))&&(n+=t.startedCalls());let i=Pt(e),a=Ft(e);i&&(n+=`
22
+
23
+ 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.`),a&&(n+=`
24
+
25
+ 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=i||a;return e.exception.typeName===`RuntimeError`&&Mt.test(r)&&(n+=`
26
+
27
+ If this reports the sandbox session's suspension limit, its cumulative host-interaction budget is exhausted. Further tool calls, OS callbacks, name lookups and future resolutions need a fresh session; revising the snippet does not replenish this budget. Pure Python using existing state may still work. Pass \`restart: true\` to start a fresh session; that discards all REPL variables, imports and definitions. Check the calls already started before continuing, and do not replay completed side effects.`),{message:n,reset:s}}if(e instanceof n)return{message:`The code crashed the sandbox worker and the session was reset. Revise the code and try again.${t.startedCalls()}`,reset:!0};let s=e instanceof Error?`${e.name}: ${e.message}`:String(e);return{message:`Code execution failed and the session was reset. Re-run any imports, recreate any state you need, and try again.
28
+ ${o.prependTo(this.cut(s))}${t.startedCalls()}`,reset:!0}}osCallback(e){return async(t,n)=>{if(t!==`time.sleep`&&t!==`asyncio.sleep`)return o;let r=Number(n[0]),i=Math.max(0,(e.deadline-Date.now())/1e3);if(e.stopped!==void 0||r>i)throw Q(`TimeoutError`,`sleeping ${String(r)}s would exceed the ${At(this.limits)}s this code may run; ${i.toFixed(1)}s left`);return await $(d(r*1e3,void 0,{ref:!1}),e.signal),null}}externalLookup(e,t){return Object.fromEntries(Object.keys(this.options.tools).map(n=>{let r=this.pythonNames.get(n)??n;return[r,async(...i)=>this.callTool(n,r,i,e,t)]}))}async callTool(e,t,n,r,i){let{limits:a}=this,o=this.options.tools[e];if(r.stopped!==void 0)throw r.signal.reason;if(r.callCount>=a.toolCalls)throw r.budgetExhausted=!0,Q(`RuntimeError`,`Code mode allows ${String(a.toolCalls)} nested tool calls per \`run_code\` call and this snippet asked for more. Call fewer tools, for example by filtering the inputs first, or split the work across several \`run_code\` calls.`);r.callCount+=1;let c=`${r.id}__${String(r.callCount)}`,l=St(xt(t,n,a.toolInputBytes),this.schemaArgNames.get(t));if(X(JSON.stringify(l))>a.toolInputBytes)throw Q(`ValueError`,Ct(t,a.toolInputBytes));let d=await $(Promise.resolve(s(o.inputSchema).validate?.(l)),r.signal);if(d!==void 0&&!d.success)throw Q(`ValueError`,`Invalid arguments for ${t}(): ${bt(d.error)}`);let p=d===void 0?l:d.value,m=this.options.context,h=m!==void 0&&Object.hasOwn(m,e)?m[e]:void 0;if(o.contextSchema!==void 0){let t=await $(Promise.resolve(s(o.contextSchema).validate?.(h)),r.signal);if(t!==void 0&&!t.success)throw Q(`ValueError`,`Invalid context for tool "${e}": ${bt(t.error)}`);h=t===void 0?h:t.value}let g={toolName:e,inputPreview:Z(p),status:`running`},_=await $(f(this.options.approval,{tools:this.options.tools,toolsContext:this.options.context??{},runtimeContext:this.options.runtimeContext},{toolName:e,toolCallId:c,input:p,messages:i.messages,toolContext:h,tool:o}),r.signal);if(!_.approved){g.status=`denied`,r.calls.push(g);let t=_.reason===void 0?``:` ${_.reason}`;throw Q(`RuntimeError`,_.needsUser?`Tool '${e}' needs a person to approve it, and code mode cannot ask for approval from inside the sandbox.${t}`:`Tool '${e}' call denied:${t===``?` denied by the approval policy`:t}`)}await this.slots.acquire(r.signal);let v=!1,y=()=>{v||(v=!0,this.slots.release())},b={};r.calls.push(g);try{return await u.span(`run_code called {tool_name}`,{tool_name:e,tool_call_id:c,arguments:p},{},async()=>{let n;try{r.signal.throwIfAborted();let e=this.execute(o,p,{...i,toolCallId:c,context:h,abortSignal:r.signal});b.running=e,e.then(y,y),n=await $(e,r.signal)}catch(t){throw g.status=`failed`,r.stopped===void 0?this.replaceToolError(t,{toolName:e,toolCallId:c,input:p}):t}g.status=`returned`;let s;try{s=Tt(n)}catch(e){let n=e instanceof RangeError?`it is nested too deeply or contains itself`:vt(e);throw g.outputPreview=`<not JSON>`,Q(`ValueError`,`${t}() returned a value that cannot be sent to the sandbox as JSON: ${n}. The call ran, so do not repeat it to get the same result.`)}let l=X(s);if(l>a.toolOutputBytes)throw g.outputPreview=`<${String(l)} bytes, over the limit>`,Q(`ValueError`,`${t}() returned ${String(l)} bytes of JSON, over the ${String(a.toolOutputBytes)}-byte limit for one call. The call ran, so do not repeat it to get the same result.`);let u=JSON.parse(s);return g.outputPreview=Z(u),u})}finally{b.running===void 0&&y()}}async execute(e,t,n){let r=e.execute,i=r(t,n);if(Et(i)){let e;for await(let t of i)e=t;return e}return await i}replaceToolError(e,t){let n=this.options.onToolError?.(e,t);return n instanceof Error?n:typeof n==`string`?Error(n):e instanceof Error?e:Error(String(e))}async pool(){let{sandboxes:e}=this.options;this.poolPromise??=e===void 0?t({requestTimeout:this.limits.timeout/1e3+10}):Promise.resolve(e);try{return await this.poolPromise}catch(e){throw this.poolPromise=void 0,e}}async session(){this.sessionPromise??=this.checkout();try{return await this.sessionPromise}catch(e){throw this.sessionPromise=void 0,e}}async checkout(){let t=this.options.typeCheck!==`off`;return e.with(this.traceContext,async()=>(await this.pool()).checkout({ephemeral:!0,scriptName:`run_code.py`,typeCheck:t,...t?{typeCheckStubs:this.typeCheckStubs}:{},limits:{maxFeedDurationSecs:this.limits.timeout/1e3,maxMemory:this.limits.memory,maxSuspensions:this.limits.suspensions},osPolicy:{datetime:`call_host`,sleep:`call_host`,randomStart:`call_host`}}))}abandonSession(e,t){this.sessionPromise=void 0,this.passedTypeCheck=!1,t.then(async()=>e.close()).catch(()=>void 0)}async releaseSession(){let e=this.sessionPromise;if(this.sessionPromise=void 0,this.passedTypeCheck=!1,e!==void 0)try{await(await e).close()}catch{}}startIdleTimer(){this.closing===void 0&&this.sessionPromise!==void 0&&Number.isFinite(this.idleTimeout)&&(this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.current===void 0&&this.closing===void 0&&(this.expired=!0,this.releaseSession().catch(()=>void 0))},Math.min(this.idleTimeout,2**31-1)),this.idleTimer.unref())}clearIdleTimer(){clearTimeout(this.idleTimer),this.idleTimer=void 0}};export{_t as codeMode};
package/package.json CHANGED
@@ -1,6 +1,78 @@
1
1
  {
2
2
  "name": "@pydantic/logfire-ai-sdk-code-mode",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "description": "Let Vercel AI SDK agents call their tools from Python running in Logfire Agent Sandboxes - https://pydantic.dev/logfire",
4
+ "author": {
5
+ "name": "The Pydantic Team",
6
+ "email": "engineering@pydantic.dev",
7
+ "url": "https://pydantic.dev"
8
+ },
9
+ "repository": {
10
+ "url": "https://github.com/pydantic/logfire-js",
11
+ "directory": "packages/logfire-ai-sdk-code-mode"
12
+ },
13
+ "sideEffects": false,
14
+ "homepage": "https://pydantic.dev/logfire",
15
+ "license": "MIT",
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "keywords": [
20
+ "logfire",
21
+ "monty",
22
+ "sandbox",
23
+ "agents",
24
+ "ai-sdk",
25
+ "code-mode",
26
+ "python"
27
+ ],
28
+ "version": "0.0.0",
29
+ "type": "module",
30
+ "main": "./dist/index.cjs",
31
+ "module": "./dist/index.js",
32
+ "types": "./dist/index.d.ts",
33
+ "exports": {
34
+ ".": {
35
+ "import": {
36
+ "types": "./dist/index.d.ts",
37
+ "default": "./dist/index.js"
38
+ },
39
+ "require": {
40
+ "types": "./dist/index.d.cts",
41
+ "default": "./dist/index.cjs"
42
+ }
43
+ }
44
+ },
45
+ "dependencies": {
46
+ "@pydantic/logfire-agent-sandboxes": "0.2.0",
47
+ "logfire": "0.25.1"
48
+ },
49
+ "peerDependencies": {
50
+ "@opentelemetry/api": ">=1.9.1 <1.10.0",
51
+ "@pydantic/monty": "^1.5.0",
52
+ "ai": "^7.0.0"
53
+ },
54
+ "devDependencies": {
55
+ "@grpc/grpc-js": "^1.14.5",
56
+ "@opentelemetry/api": ">=1.9.1 <1.10.0",
57
+ "@opentelemetry/context-async-hooks": "^2.8.0",
58
+ "@opentelemetry/sdk-trace-base": "^2.8.0",
59
+ "@pydantic/monty": "^1.5.0",
60
+ "@types/node": "^22.5.1",
61
+ "ai": "^7.0.0",
62
+ "vitest": "5.0.1",
63
+ "zod": "^4.6.6"
64
+ },
65
+ "files": [
66
+ "dist",
67
+ "LICENSE"
68
+ ],
69
+ "scripts": {
70
+ "dev": "vp pack --watch",
71
+ "build": "vp pack",
72
+ "lint": "vp lint",
73
+ "preview": "vp preview",
74
+ "typecheck": "tsc",
75
+ "test": "vp test",
76
+ "render-fixtures": "uv run --no-project --script scripts/render-fixtures.py"
77
+ }
6
78
  }