@pydantic/logfire-ai-sdk-code-mode 0.1.5 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,25 +1,42 @@
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 m(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 h={timeout:3e4,toolCalls:100,concurrentToolCalls:8,outputBytes:64e3,codeBytes:1e5,toolInputBytes:1e6,toolOutputBytes:1e7,memory:268435456,suspensions:1e4},g=/* @__PURE__ */ new Set([`toolCalls`,`concurrentToolCalls`,`memory`,`suspensions`]);function _(e={}){let t={...h};for(let[n,r]of Object.entries(e)){if(!(n in h))throw TypeError(`Unknown code mode limit "${n}". The limits are: ${Object.keys(h).join(`, `)}.`);if(r!==void 0){if(!(typeof r==`number`&&r>0&&Number.isFinite(r)&&(!g.has(n)||Number.isSafeInteger(r)))){let e=g.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 v=/* @__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 y(e){return v.has(e)}const b=/* @__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 ee(e){return b.has(e)}function x(e){return/^[\p{XID_Start}_]\p{XID_Continue}*$/u.test(e)}function S(e){return x(e)&&!y(e)}function C(e){return e==null?`None`:typeof e==`boolean`?e?`True`:`False`:typeof e==`number`?te(e):typeof e==`string`?re(e):Array.isArray(e)?`[${e.map(C).join(`, `)}]`:typeof e==`object`?`{${Object.entries(e).map(([e,t])=>`${re(e)}: ${C(t)}`).join(`, `)}}`:typeof e==`bigint`?e.toString():`None`}function te(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 ne=/[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Cn}\p{Zl}\p{Zp}\p{Zs}]/u;function re(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!==` `&&ne.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 ie='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 ae(e,t){if(t.length===0)return ie;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(`
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 m(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 h={timeout:3e4,toolCalls:100,concurrentToolCalls:8,outputBytes:64e3,codeBytes:1e5,toolInputBytes:1e6,toolOutputBytes:1e7,memory:268435456,suspensions:1e4},g=/* @__PURE__ */ new Set([`toolCalls`,`concurrentToolCalls`,`memory`,`suspensions`]);function _(e={}){let t={...h};for(let[n,r]of Object.entries(e)){if(!(n in h))throw TypeError(`Unknown code mode limit "${n}". The limits are: ${Object.keys(h).join(`, `)}.`);if(r!==void 0){if(!(typeof r==`number`&&r>0&&Number.isFinite(r)&&(!g.has(n)||Number.isSafeInteger(r)))){let e=g.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 v=/* @__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 y(e){return v.has(e)}const ee=/* @__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 ee.has(e)}function ne(e){return/^[\p{XID_Start}_]\p{XID_Continue}*$/u.test(e)}function b(e){return ne(e)&&!y(e)}function x(e){return e==null?`None`:typeof e==`boolean`?e?`True`:`False`:typeof e==`number`?re(e):typeof e==`string`?ae(e):Array.isArray(e)?`[${e.map(x).join(`, `)}]`:typeof e==`object`?`{${Object.entries(e).map(([e,t])=>`${ae(e)}: ${x(t)}`).join(`, `)}}`:typeof e==`bigint`?e.toString():`None`}function re(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 ie=/[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Cn}\p{Zl}\p{Zp}\p{Zs}]/u;function ae(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!==` `&&ie.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}function oe(e){return`- **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. ${e}`}function se(e){return`- **No filesystem or environment**: \`pathlib.Path\` I/O and \`os.getenv\`/\`os.environ\` 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. \`datetime.datetime.now()\`, \`datetime.date.today()\`, and \`time.time()\` read the clock configured for this sandbox. ${e}`}function ce(e){let t=e.sleep===`zero`?"`time.sleep` and `asyncio.sleep` return at once without waiting.":"`time.sleep` and `asyncio.sleep` really wait.";return e.datetime===void 0||e.datetime===`call_host`?oe(t):se(t)}function le(e,t,n=ce({})){let r=`Write and run Python code in a sandboxed environment.
3
3
 
4
- `)+"\n```"),n.push("```python\n"+t.join(`
4
+ The sandbox uses Monty, a subset of Python. Key restrictions:
5
+ - **No third-party libraries**: only the standard library modules listed below can be used
6
+ - **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${n}\n- **No \`import *\`**: wildcard imports are not supported
5
7
 
6
- `)+"\n```"),`${ie}\n\n${n.join(`
8
+ State is preserved between calls (REPL-style). Set \`restart: true\` to reset state.
7
9
 
8
- `)}`}let w,T=/* @__PURE__ */ new Set;var E=class{kind=`simple`;name;constructor(e){this.name=e}toString(){return this.name}},oe=class{kind=`literal`;values;constructor(e){this.values=e}toString(){return`Literal[${this.values.map(C).join(`, `)}]`}},D=class{kind=`generic`;base;args;constructor(e,t){this.base=e,this.args=t}toString(){return`${this.base}[${this.args.map(String).join(`, `)}]`}},O=class{kind=`union`;members;constructor(e){this.members=e}toString(){return this.members.map(String).join(` | `)}};const se=` `;function ce(e){return e.replace(/[\\\0"]/gu,e=>e===`\\`?`\\\\`:e===`\0`?`\\x00`:`\\"`)}const le=`\\s\\x1c-\\x1f\\x85`,ue=RegExp(`^[${le}]+|[${le}]+$`,`gu`),de=/\r\n|[\n\r\v\f\x1c-\x1e\x85\u2028\u2029]/u,fe=RegExp(`[${le}]+$`,`u`);function k(e){return e.replace(ue,``)}function pe(e){return e.replace(fe,``)}function me(e){if(e===``)return[];let t=e.split(de);return t.at(-1)===``&&de.test(e.at(-1)??``)&&t.pop(),t}function A(e){return e!==void 0&&e!==``}function he(e,t=``){let n=ce(k(e)),r=me(n);return r.length>1?[`${t}"""`,...r.map(e=>k(e)?`${t}${e}`:``),`${t}"""`]:[`${t}"""${n}"""`]}function ge(e){let t=e.replace(/[^a-zA-Z0-9_]/gu,`_`);return/^[0-9]/u.test(t)&&(t=`_${t}`),y(t)&&(t=`${t}_`),t||`_`}function _e(e,t=``){return me(k(e).replace(/\0/gu,`\\x00`)).map(e=>pe(`${t}# ${e}`))}var ve=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}: ${ye(this)}`];return A(this.description)&&e.push(...he(this.description,` `)),e.join(`
9
- `)}};function ye(e){let t=String(e.type);return e.required?t:`NotRequired[${t}]`}function be(e){let t=A(e.description)?_e(e.description,` `):[];return t.push(` ${C(e.name)}: ${ye(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(w===void 0||!w.conflicting.has(this.name))return this.name;let e=w.typeNames.get(this);if(e!==void 0)return e;let t=w.fallbackOwner;return A(t)?`${t}_${this.name}`:this.name}toString(){return this.displayName}renderDefinition(e,t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Map){return we({conflicting:t,typeNames:n,fallbackOwner:e},()=>this.renderDefinitionBody())}renderDefinitionBody(){if(![...this.fields.keys()].every(S))return this.renderFunctionalDefinition();let e=[`class ${this.displayName}(TypedDict):`];if(A(this.description)&&e.push(...he(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)?_e(this.description):[];return e.push(`${this.displayName} = TypedDict(${C(this.displayName)}, {`),e.push(...[...this.fields.values()].map(be)),e.push(`})`),e.join(`
12
- `)}structurallyEqual(e){return xe(this,e,/* @__PURE__ */ new Map)}};function xe(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||!Se(i.type,e.type,n))return!1}return!0}function Se(e,t,n){return e instanceof j&&t instanceof j?e.name===t.name&&xe(e,t,n):e instanceof D&&t instanceof D?e.base===t.base&&Ce(e.args,t.args,n):e instanceof O&&t instanceof O?Ce(e.members,t.members,n):e.kind===t.kind&&String(e)===String(t)}function Ce(e,t,n){return e.length===t.length&&e.every((e,r)=>{let i=t[r];return i!==void 0&&Se(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 we({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]=me(k(e.description??``));t!==void 0&&(l.push(`${se}${e.name}: ${t}`),l.push(...n.map(e=>`${se}${se}${e}`)))}l.length>0&&c.push([`Args:`,...l].join(`
10
+ The 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:
11
+
12
+ \`\`\`python
13
+ result = some_expression
14
+ result
15
+ \`\`\`
16
+
17
+ Avoid \`print()\` for return values as it produces Python string representations, not structured data. Use \`print()\` only for supplementary logging or debug output.
18
+
19
+ Returns 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.`;if(t.length===0)return r;let i=["\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&&i.push("```python\n"+e.join(`
20
+
21
+ `)+"\n```"),i.push("```python\n"+t.join(`
22
+
23
+ `)+"\n```"),`${r}\n\n${i.join(`
24
+
25
+ `)}`}let S,C=/* @__PURE__ */ new Set;var w=class{kind=`simple`;name;constructor(e){this.name=e}toString(){return this.name}},ue=class{kind=`literal`;values;constructor(e){this.values=e}toString(){return`Literal[${this.values.map(x).join(`, `)}]`}},T=class{kind=`generic`;base;args;constructor(e,t){this.base=e,this.args=t}toString(){return`${this.base}[${this.args.map(String).join(`, `)}]`}},E=class{kind=`union`;members;constructor(e){this.members=e}toString(){return this.members.map(String).join(` | `)}};const D=` `;function de(e){return e.replace(/[\\\0"]/gu,e=>e===`\\`?`\\\\`:e===`\0`?`\\x00`:`\\"`)}const O=`\\s\\x1c-\\x1f\\x85`,fe=RegExp(`^[${O}]+|[${O}]+$`,`gu`),pe=/\r\n|[\n\r\v\f\x1c-\x1e\x85\u2028\u2029]/u,me=RegExp(`[${O}]+$`,`u`);function k(e){return e.replace(fe,``)}function he(e){return e.replace(me,``)}function ge(e){if(e===``)return[];let t=e.split(pe);return t.at(-1)===``&&pe.test(e.at(-1)??``)&&t.pop(),t}function A(e){return e!==void 0&&e!==``}function j(e,t=``){let n=de(k(e)),r=ge(n);return r.length>1?[`${t}"""`,...r.map(e=>k(e)?`${t}${e}`:``),`${t}"""`]:[`${t}"""${n}"""`]}function _e(e){let t=e.replace(/[^a-zA-Z0-9_]/gu,`_`);return/^[0-9]/u.test(t)&&(t=`_${t}`),y(t)&&(t=`${t}_`),t||`_`}function ve(e,t=``){return ge(k(e).replace(/\0/gu,`\\x00`)).map(e=>he(`${t}# ${e}`))}var ye=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}: ${be(this)}`];return A(this.description)&&e.push(...j(this.description,` `)),e.join(`
26
+ `)}};function be(e){let t=String(e.type);return e.required?t:`NotRequired[${t}]`}function xe(e){let t=A(e.description)?ve(e.description,` `):[];return t.push(` ${x(e.name)}: ${be(e)},`),t.join(`
27
+ `)}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(S===void 0||!S.conflicting.has(this.name))return this.name;let e=S.typeNames.get(this);if(e!==void 0)return e;let t=S.fallbackOwner;return A(t)?`${t}_${this.name}`:this.name}toString(){return this.displayName}renderDefinition(e,t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Map){return Te({conflicting:t,typeNames:n,fallbackOwner:e},()=>this.renderDefinitionBody())}renderDefinitionBody(){if(![...this.fields.keys()].every(b))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(`
28
+ `)}renderFunctionalDefinition(){let e=A(this.description)?ve(this.description):[];return e.push(`${this.displayName} = TypedDict(${x(this.displayName)}, {`),e.push(...[...this.fields.values()].map(xe)),e.push(`})`),e.join(`
29
+ `)}structurallyEqual(e){return Se(this,e,/* @__PURE__ */ new Map)}};function Se(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||!Ce(i.type,e.type,n))return!1}return!0}function Ce(e,t,n){return e instanceof M&&t instanceof M?e.name===t.name&&Se(e,t,n):e instanceof T&&t instanceof T?e.base===t.base&&we(e.args,t.args,n):e instanceof E&&t instanceof E?we(e.members,t.members,n):e.kind===t.kind&&String(e)===String(t)}function we(e,t,n){return e.length===t.length&&e.every((e,r)=>{let i=t[r];return i!==void 0&&Ce(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 Te({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]=ge(k(e.description??``));t!==void 0&&(l.push(`${D}${e.name}: ${t}`),l.push(...n.map(e=>`${D}${D}${e}`)))}l.length>0&&c.push([`Args:`,...l].join(`
13
30
  `));let u=c.join(`
14
31
 
15
- `);return u!==``&&s.push(...he(u,` `)),s.push(` ${e}`),s.join(`
16
- `)}static fromSchema(t,n,r){let i=Oe(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=Oe(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 we(e,t){let n=w;w=e;try{return t()}finally{w=n}}const P=new E(`Any`),F=new E(`None`),Te=/* @__PURE__ */ new Map([[`string`,`str`],[`integer`,`int`],[`number`,`float`],[`boolean`,`bool`],[`null`,`None`]]);function Ee(e){return new E(Te.get(e)??`Any`)}function De(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(De).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 Oe(e){let t=e.$defs;return z(t)?t:{}}function V(e){let t=e.properties;return z(t)?t:{}}function ke(e){let t=e.required;return new Set(Array.isArray(t)?t:[])}function H(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);H(a)&&!t.has(r)&&W(r,a,e,t,n,r)}}function je(e,t,n,r){let i=ke(e),a=V(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=U(a,t,n,r,e),d=R(a.description),f=o.get(e)??e;`default`in a?c.set(e,new M(f,u,C(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 O([u,F]),`None`,d))}return new Map([...s,...c])}function Me(e){let t=[...e],n=new Set(t.filter(S)),r=/* @__PURE__ */ new Map;for(let e of t){if(S(e)){r.set(e,e);continue}let t=ge(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 U(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(H(a))W(e,a,t,n,r,i);else{if(T.has(e))return P;let o=T;T=/* @__PURE__ */ new Set([...o,e]);try{return U(a,t,n,r,i)}finally{T=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?U(e[0],t,n,r,i):P}return`const`in a?new oe([a.const]):`enum`in a?new oe(a.enum):Pe(a.type,a,t,n,r,i)}function Pe(e,t,n,r,i,a){let o=Te.get(e);if(o!==void 0)return new E(o);if(e===`array`){let e=t.items??{};return Fe(e)?Array.isArray(e)?new D(`tuple`,e.map((e,t)=>U(e,n,r,i,`${a}.${String(t)}`))):new D(`list`,[U(e,n,r,i,`${a}Item`)]):new D(`list`,[P])}if(e===`object`){if(`properties`in t){let e=t.title,o=typeof e==`string`&&e!==``&&x(e)?e:L(i,a),s=Object.hasOwn(n,o)?B(n[o]):void 0;return s!==void 0&&H(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 D(`dict`,[new E(`str`),P]);if(z(e)){let t=U(e,n,r,i,`${a}Value`);return new D(`dict`,[new E(`str`),t])}}return new D(`dict`,[new E(`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 O([o,F]):o}let o=e.map(Ee),s=o.find(e=>String(e)!==`None`);if(o.length===2&&s!==void 0&&o.some(e=>String(e)===`None`))return new O([s,F]);let[c,...l]=o;return c===void 0?P:l.length>0?new O(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(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(F);let[d,...f]=u;return d!==void 0&&f.length===0?d:new O(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!==``&&x(t)}function Be(e){for(let t of Object.values(V(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 W(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=ke(t),s=/* @__PURE__ */ new Map;for(let[e,c]of Object.entries(V(t))){let t=B(c),l=U(t,n,r,i,a?`${a}.${e}`:e),u=R(t.description);s.set(e,new ve(e,l,o.has(e),u))}return new j(e,R(t.description),s)}function G(e,t){if(e instanceof j)return t.get(e)??e;if(e instanceof D){let n=e.args.map(e=>G(e,t));n.some((t,n)=>t!==e.args[n])&&(e.args=n)}else if(e instanceof O){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,()=>L(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,()=>L(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 S(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=I(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:N.fromSchema(e.name,e.parametersSchema,e.returnSchema)})),n=t.map(({sig:e})=>e),r=N.getConflictingTypeNames(n),i=N.prefixedTypeNames(n,r),a=N.renderTypeDefinitions(n,r),o=e=>t.map(({f:t,sig:n})=>n.render(e,{name:t.name,description:t.description,isAsync:!0,conflictingTypeNames:r,typeNames:i}));return{typeDefinitions:a,functions:o(`...`),typeCheckStubs:[tt,...a,...o(`raise NotImplementedError()`)].join(`
32
+ `);return u!==``&&s.push(...j(u,` `)),s.push(` ${e}`),s.join(`
33
+ `)}static fromSchema(t,n,r){let i=ke(n),a=/* @__PURE__ */ new Map;je(i,a,t);let o=Me(n,i,a,t),s=F,c=/* @__PURE__ */ new Map;if(r!==void 0){let e=ke(r);je(e,c,t),s=W(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=K(s,u);for(let e of l)for(let t of e.fields.values())t.type=K(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)?(We(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 Te(e,t){let n=S;S=e;try{return t()}finally{S=n}}const F=new w(`Any`),I=new w(`None`),Ee=/* @__PURE__ */ new Map([[`string`,`str`],[`integer`,`int`],[`number`,`float`],[`boolean`,`bool`],[`null`,`None`]]);function De(e){return new w(Ee.get(e)??`Any`)}function Oe(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(Oe).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 ke(e){let t=e.$defs;return B(t)?t:{}}function H(e){let t=e.properties;return B(t)?t:{}}function Ae(e){let t=e.required;return new Set(Array.isArray(t)?t:[])}function U(e){return e.type===`object`&&`properties`in e}function je(e,t,n){for(let[r,i]of Object.entries(e)){let a=V(i);U(a)&&!t.has(r)&&G(r,a,e,t,n,r)}}function Me(e,t,n,r){let i=Ae(e),a=H(e),o=Ne(Object.keys(a)),s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Map;for(let[e,l]of Object.entries(a)){let a=V(l),u=W(a,t,n,r,e),d=z(a.description),f=o.get(e)??e;`default`in a?c.set(e,new N(f,u,x(a.default),d)):i.has(e)?s.set(e,new N(f,u,void 0,d)):Pe(a)?c.set(e,new N(f,u,`None`,d)):c.set(e,new N(f,new E([u,I]),`None`,d))}return new Map([...s,...c])}function Ne(e){let t=[...e],n=new Set(t.filter(b)),r=/* @__PURE__ */ new Map;for(let e of t){if(b(e)){r.set(e,e);continue}let t=_e(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 Pe(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 W(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(U(a))G(e,a,t,n,r,i);else{if(C.has(e))return F;let o=C;C=/* @__PURE__ */ new Set([...o,e]);try{return W(a,t,n,r,i)}finally{C=o}}}return n.get(e)??new M(e)}if(`anyOf`in a)return Re(a.anyOf,t,n,r,i);if(`oneOf`in a)return Re(a.oneOf,t,n,r,i);if(`allOf`in a){let e=a.allOf;return e.length===1?W(e[0],t,n,r,i):F}return`const`in a?new ue([a.const]):`enum`in a?new ue(a.enum):Fe(a.type,a,t,n,r,i)}function Fe(e,t,n,r,i,a){let o=Ee.get(e);if(o!==void 0)return new w(o);if(e===`array`){let e=t.items??{};return Ie(e)?Array.isArray(e)?new T(`tuple`,e.map((e,t)=>W(e,n,r,i,`${a}.${String(t)}`))):new T(`list`,[W(e,n,r,i,`${a}Item`)]):new T(`list`,[F])}if(e===`object`){if(`properties`in t){let e=t.title,o=typeof e==`string`&&e!==``&&ne(e)?e:R(i,a),s=Object.hasOwn(n,o)?V(n[o]):void 0;return s!==void 0&&U(s)&&!r.has(o)&&G(o,s,n,r,i,o),r.has(o)?He(o,t,n,r,i,a):G(o,t,n,r,i,a)}if(`additionalProperties`in t){let e=t.additionalProperties;if(e===!0)return new T(`dict`,[new w(`str`),F]);if(B(e)){let t=W(e,n,r,i,`${a}Value`);return new T(`dict`,[new w(`str`),t])}}return new T(`dict`,[new w(`str`),F])}return Array.isArray(e)?Le(e,t,n,r,i,a):F}function Ie(e){return Array.isArray(e)?e.length>0:B(e)?Object.keys(e).length>0:!!e}function Le(e,t,n,r,i,a){if(e.includes(`object`)&&`properties`in t){let o=Fe(`object`,t,n,r,i,a);return e.includes(`null`)?new E([o,I]):o}let o=e.map(De),s=o.find(e=>String(e)!==`None`);if(o.length===2&&s!==void 0&&o.some(e=>String(e)===`None`))return new E([s,I]);let[c,...l]=o;return c===void 0?F:l.length>0?new E(o):c}function Re(e,t,n,r,i){let a=e.map(V),o=ze(a,i),s=[],c=!1;for(let e of a)e.type===`null`?c=!0:s.push(W(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 E(u)}function ze(e,t){let n=e.filter(e=>e.type===`object`&&`properties`in e&&!Be(e)),r=/* @__PURE__ */ new Map;if(n.length<2)return r;let i=n.map(Ve),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 Be(e){let t=e.title;return typeof t==`string`&&t!==``&&ne(t)}function Ve(e){for(let t of Object.values(H(e))){let e=V(t).const;if(typeof e==`string`&&L(e)!==``)return e}}function He(e,t,n,r,i,a){let o=Ue(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 G(e,t,n,r,i,a){let o=new M(e);r.set(e,o);let s=Ue(e,t,n,r,i,a);return o.fields=s.fields,o.description=s.description,o}function Ue(e,t,n,r,i,a){let o=Ae(t),s=/* @__PURE__ */ new Map;for(let[e,c]of Object.entries(H(t))){let t=V(c),l=W(t,n,r,i,a?`${a}.${e}`:e),u=z(t.description);s.set(e,new ye(e,l,o.has(e),u))}return new M(e,z(t.description),s)}function K(e,t){if(e instanceof M)return t.get(e)??e;if(e instanceof T){let n=e.args.map(e=>K(e,t));n.some((t,n)=>t!==e.args[n])&&(e.args=n)}else if(e instanceof E){let n=e.members.map(e=>K(e,t));n.some((t,n)=>t!==e.members[n])&&(e.members=n)}return e}function We(e,t,n){let r=/* @__PURE__ */ new Map([[t,n]]);for(let t of e.params.values())t.type=K(t.type,r);e.returnType=K(e.returnType,r);for(let t of e.referencedTypes)for(let e of t.fields.values())e.type=K(e.type,r)}function Ge(e,t,n){let r=structuredClone(e),i=Ke(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;qe([r,...Object.values(i)],`#`)&&(c=Xe(r.title,void 0,()=>R(t,n===`return`?`Return`:``)),o.add(c));let l=$e(r,i,n);for(let[e,n]of Object.entries(i))s(e,Xe(q(n)?n.title:void 0,e,()=>R(t,l.get(e)??e)));let u=e=>Y(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 q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ke(e,t){let n={},r=[e.definitions,e.$defs];delete e.definitions,delete e.$defs;for(let e of r)if(q(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 qe(e,t){return Array.isArray(e)?e.some(e=>qe(e,t)):q(e)?e.$ref===t||Object.entries(e).some(([e,n])=>!Ze.has(e)&&qe(n,t)):!1}const Je=/^__schema\d+$/u,Ye=/* @__PURE__ */ new Set([`asyncio`,`Any`,`TypedDict`,`NotRequired`,`Literal`,`str`,`int`,`float`,`bool`,`list`,`dict`,`tuple`]);function J(e){return b(e)&&!Ye.has(e)}function Xe(e,t,n){if(t!==void 0&&J(t)&&!Je.test(t))return t;if(typeof e==`string`&&J(e))return e;if(t!==void 0&&!Je.test(t)){let e=L(t);if(J(e))return e}return n()}const Ze=/* @__PURE__ */ new Set([`default`,`const`,`enum`,`examples`]),Qe=/* @__PURE__ */ new Set([`properties`,`patternProperties`,`$defs`,`definitions`]);function $e(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(!q(e))return;let a=e.$ref;if(typeof a==`string`){let e=et(a);e!==void 0&&Object.hasOwn(t,e)&&!r.has(e)&&(r.set(e,n),i(t[e],n))}let o=e.properties;if(q(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 et(e){return/^#\/(?:definitions|\$defs)\/([^/]+)$/u.exec(e)?.[1]?.replace(/~1/gu,`/`).replace(/~0/gu,`~`)}function Y(e,t,n,r){if(Array.isArray(e))return e.map(e=>Y(e,t,n,r));if(!q(e))return e;let i={};for(let[a,o]of Object.entries(e))if(Qe.has(a)&&q(o))i[a]=Object.fromEntries(Object.entries(o).map(([e,i])=>[e,Y(i,t,n,r)]));else if(Ze.has(a))i[a]=o;else if(a===`$ref`&&typeof o==`string`)i[a]=tt(o,t,n,r);else if(a===`title`&&typeof o==`string`&&!J(o))continue;else i[a]=Y(o,t,n,r);return i}function tt(e,t,n,r){if(e===`#`&&r!==void 0)return`#/$defs/${r}`;let i=et(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 nt=`import asyncio
34
+ from typing import Any, TypedDict, NotRequired, Literal`,rt=new Set(nt.split(`
35
+ `).flatMap(e=>e.replace(/^(?:from \S+ )?import /u,``).split(`, `)));function it(e){let{functions:t,toolNames:n}=at(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([...Ne(n)].filter(([e,t])=>t!==e).map(([e,t])=>[t,e]));i.size>0&&r.set(e.name,i)}return{...ot(t),toolNames:n,schemaArgNames:r}}function at(e){let t=[],n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map;for(let[i,a]of Object.entries(e)){let e=st(i);if(e===`run_code`)throw Error(`Tool "${i}" becomes the Python function "${e}", which code mode reserves for itself. Rename the tool.`);if(rt.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:ut(i,a);if(s===void 0&&mt(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:Ge(ct(i,a),e,`parameters`),returnSchema:s===void 0?void 0:Ge(s,e,`return`)})}return{functions:t,toolNames:n}}function ot(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:[nt,...a,...o(`raise NotImplementedError()`)].join(`
19
36
 
20
- `)}}function ot(e){return ge(e)}function st(e,t){return dt(e,(0,d.asSchema)(t.inputSchema).jsonSchema)}function ct(e){let t=(e?.[`~standard`])?.jsonSchema?.output;return typeof t==`function`?t:void 0}function lt(e,t){let n=ct(t.outputSchema);return n===void 0?dt(e,(0,d.asSchema)(t.outputSchema).jsonSchema):dt(e,n({target:`draft-07`}))}function ut(e){return typeof e.then==`function`}function dt(e,t){if(ut(t))throw Promise.resolve(t).catch(()=>void 0),Error(`Tool "${e}" has a schema that converts to JSON Schema asynchronously, which code mode does not support`);return t}const ft=/* @__PURE__ */ new WeakSet;function pt(e,t){ft.has(t)||(ft.add(t),console.warn(`Tool "${e}" has no outputSchema, so code mode shows its return type as Any. Add an outputSchema so that the model knows the shape of its result.`))}var mt=class extends Error{maxBytes;constructor(e){super(`The value is more than ${String(e)} bytes of JSON.`),this.maxBytes=e}};function ht(e,t){let n=t,r=e=>{if(n-=e,n<0)throw new mt(t)},i=e=>{r(2);let t={};for(let[n,i]of e){let e=String(n);r(Y(e)+4),Object.defineProperty(t,e,{value:a(i),enumerable:!0,writable:!0,configurable:!0})}return t},a=e=>{if(e instanceof Map)return i(e);if(e instanceof Set||Array.isArray(e)){r(2);let t=[];for(let n of e)r(1),t.push(a(n));return t}if(typeof e==`bigint`){let t=e.toString();return r(t.length),Number.isSafeInteger(Number(e))?Number(e):t}return e instanceof Uint8Array?(r(e.length+2),Buffer.from(e).toString(`latin1`)):typeof e==`string`?(r(Y(e)+2),e):typeof e==`object`&&e?i(Object.entries(e)):(r(typeof e==`number`?String(e).length:5),e)};return a(e)}function gt(e){return typeof e==`number`&&!Number.isFinite(e)?Number.isNaN(e)?`nan`:e>0?`inf`:`-inf`:Array.isArray(e)?e.map(gt):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,gt(t)])):e}function _t(e,t){let n=Y(e);if(n<=t)return e;let r=Buffer.from(e),i=Math.floor(t/2),a=r.subarray(0,i).toString().replace(/\uFFFD$/u,``),o=r.subarray(n-i).toString().replace(/^\uFFFD/u,``);return`${a}\n... (${String(n-2*i)} of ${String(n)} bytes cut) ...\n${o}`}function Y(e){return Buffer.byteLength(e,`utf8`)}function vt(e,t,n){return e>t?` ... (${String(e)} ${n} total)`:``}function X(e,t=!1){if(typeof e==`string`)return C(e.slice(0,120))+vt(e.length,120,`chars`);if(Array.isArray(e))return t?`[${String(e.length)} items]`:`[${e.slice(0,5).map(e=>X(e,!0)).join(`, `)}]`+vt(e.length,5,`items`);if(typeof e==`object`&&e){let n=Object.entries(e);return t?`{${String(n.length)} items}`:`{${n.slice(0,5).map(([e,t])=>`${X(e,!0)}: ${X(t,!0)}`).join(`, `)}}`+vt(n.length,5,`items`)}return e==null||typeof e==`boolean`||typeof e==`number`?C(e):`<object>`}function yt(e){let t=[],n=0;for(let r of e){let i=r.status===`returned`?`returned ${r.outputPreview??`None`}`:r.status===`denied`?`was denied and did not run`:`did not finish, so it may have applied a partial change`,a=`- ${r.toolName}(${r.inputPreview}) ${i}`;if(n+a.length>2e3){t.push(`- ... and ${String(e.length-t.length)} more not shown`);break}t.push(a),n+=a.length}let r=String(e.length);return`${r} nested tool calls started before execution stopped:\n`+t.join(`
21
- `)+`\nAccount for all ${r} before retrying; repeating a call repeats whatever it already did.`}function bt(e){return new Ht(e)}var xt=class{sandboxFailure=!0;#e;constructor(e){this.#e=e}get error(){return this.#e}};function Z(e,t){let n=Error(t);return n.name=e,n}function St(e){return e instanceof Error?e.message:String(e)}function Ct(e){let t=e;for(let e=0;e<8&&t instanceof Error;e+=1){if(t instanceof u.MontyError)return t;t=t.cause}}const wt=2e3;function Tt(e){let t=St(e);return t.length>wt?`${t.slice(0,wt)} ... (${String(t.length)} chars total)`:t}function Et(e,t,n){let r=t.at(-1),i=typeof r==`object`&&!!r&&Object.getPrototypeOf(r)===null;if(t.length>+!!i)throw Z(`TypeError`,`${e}() does not accept positional arguments; use keyword arguments`);if(!i)return{};try{return ht(r,n)}catch(t){throw t instanceof mt?Z(`ValueError`,Ot(e,n)):t}}function Dt(e,t){return t===void 0?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[t.get(e)??e,n]))}function Ot(e,t){return`The arguments to ${e}() are more than ${String(t)} bytes of JSON, over the limit for one call.`}function kt(){let e=/* @__PURE__ */ new Map;return(t,n)=>{if(!(n instanceof Map||n instanceof Set))return n;let r=e.get(n);return r===void 0&&(r=n instanceof Map?Object.fromEntries([...n].map(([e,t])=>[String(e),t])):[...n],e.set(n,r)),r}}function At(e){let t=JSON.stringify(e??null,kt());if(t===void 0)throw TypeError(`the result, a ${typeof e==`object`?`value whose toJSON() returns undefined`:typeof e}, has no JSON form`);return t}function jt(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e}async function Q(e,t){if(t.aborted)throw e.catch(()=>void 0),t.reason;return new Promise((n,r)=>{let i=()=>{r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})})}async function Mt(e){return e.aborted?`stopped`:new Promise(t=>{e.addEventListener(`abort`,()=>{t(`stopped`)},{once:!0})})}var Nt=class{free;waiting=[];constructor(e){this.free=e}async acquire(e){if(e.throwIfAborted(),this.free>0){--this.free;return}let t=()=>void 0,n=new Promise(e=>{t=e});this.waiting.push(t);try{await Q(n,e)}catch(e){let n=this.waiting.indexOf(t);throw n===-1?this.release():this.waiting.splice(n,1),e}}release(){let e=this.waiting.shift();e===void 0?this.free+=1:e()}},Pt=class{text=``;bytes=0;truncated=!1;maxBytes;constructor(e){this.maxBytes=e}write=(e,t)=>{if(this.truncated)return;let n=Y(t);if(this.bytes+n<=this.maxBytes){this.text+=t,this.bytes+=n;return}this.text+=Buffer.from(t).subarray(0,this.maxBytes-this.bytes).toString().replace(/�$/u,``),this.truncated=!0};get output(){return this.truncated?`${this.text}\n[printed output cut at ${String(this.maxBytes)} bytes]\n`:this.text}prependTo(e){let t=this.output.replace(/\n+$/u,``);return t===``?e:`[stdout before error]\n${t}\n[/stdout before error]\n${e}`}};function Ft(e){return String(e.timeout/1e3)}var It=class{calls=[];printed;deadline=1/0;callCount=0;budgetExhausted=!1;stopped;controller=new AbortController;timer;id;limits;constructor(e,t){this.id=e,this.limits=t,this.printed=new Pt(t.outputBytes)}start(){this.deadline=Date.now()+this.limits.timeout,this.timer=setTimeout(()=>{this.stop(`deadline`)},this.limits.timeout)}get signal(){return this.controller.signal}stop(e){if(clearTimeout(this.timer),this.stopped!==void 0)return;this.stopped=e;let t=e===`deadline`?`the code passed its ${Ft(this.limits)}-second time limit`:e===`aborted`?`the agent run was aborted`:e===`closed`?`code mode was closed`:`the code had already finished`;this.controller.abort(Z(`TimeoutError`,`Stopped because ${t}.`))}reason(){return this.stopped}startedCalls(){return this.calls.length===0?``:`\n\n${yt(this.calls)}`}};const Lt=/^suspension limit [0-9]+ exceeded$/u,Rt=[`time limit exceeded`,`memory limit exceeded`,`suspension limit `],zt=`The code ran longer than its time limit and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and make the code do less work per call.`,$=`The sandbox session was replaced. Variables, imports and definitions from earlier calls are gone. Recreate any state you need, but do not replay completed side effects.`;function Bt(e){return e.traceback().length===0&&e.display(`msg`).includes(`time limit exceeded`)}function Vt(e){return e.exception.typeName===`MemoryError`&&e.display(`msg`).startsWith(`memory limit exceeded`)}var Ht=class{tools;limits;idleTimeout;pythonNames;schemaArgNames;typeCheckStubs;queue=Promise.resolve();poolPromise;sessionPromise;passedTypeCheck=!1;expired=!1;idleTimer;current;closing;failure;options;traceContext;slots;constructor(e){this.options=e,this.traceContext=c.context.active();let{tools:t,sandboxes:n,idleTimeout:r=3e5}=e;for(let[e,n]of Object.entries(t)){if(typeof n.execute!=`function`)throw Error(`Tool "${e}" has no execute function, so sandbox code cannot call it. Pass it to generateText as a direct tool instead.`);if(n.needsApproval!==void 0)throw Error(`Tool "${e}" sets needsApproval, which code mode cannot enforce. Use the approval option of codeMode() instead.`);if(n.toModelOutput!==void 0)throw Error(`Tool "${e}" sets toModelOutput, which code mode cannot apply: sandbox code receives the result that execute returns. Return only what the model may see from execute, or pass the tool to generateText as a direct tool.`)}if(n===void 0&&[void 0,``].includes(process.env.LOGFIRE_API_KEY))throw Error("Agent sandboxes require a Logfire API key with the `project:execute_agent_sandboxes` scope. Set the LOGFIRE_API_KEY environment variable, or pass `sandboxes` to codeMode().");if(!(r>0))throw RangeError(`idleTimeout must be a positive number of milliseconds or Infinity, not ${String(r)}.`);this.limits=_(e.limits),this.slots=new Nt(this.limits.concurrentToolCalls),this.idleTimeout=r;let i=rt(t);this.typeCheckStubs=i.typeCheckStubs,this.schemaArgNames=i.schemaArgNames,this.pythonNames=new Map(Object.keys(t).map(e=>[e,e]));for(let[e,t]of i.toolNames)this.pythonNames.set(t,e);for(let[e,t]of this.pythonNames)if(ee(t))throw Error(`Tool "${e}" becomes the Python function "${t}", which is a Python builtin, so sandbox code would call the builtin instead. Rename the tool.`);this.tools={run_code:(0,d.tool)({description:ae(i.typeDefinitions,i.functions),inputSchema:(0,d.jsonSchema)({type:`object`,properties:{code:{type:`string`,description:`The Python code to execute in the sandbox.`},restart:{type:`boolean`,description:`Set to true to reset REPL state. When false (default), state is preserved between calls.`}},required:[`code`],additionalProperties:!1},{validate:e=>{let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&(t.restart===void 0||typeof t.restart==`boolean`)?{success:!0,value:{code:t.code,restart:t.restart}}:{success:!1,error:/* @__PURE__ */ TypeError("run_code takes a string `code` and an optional boolean `restart`.")}}}),execute:async(e,t)=>{let n=await this.enqueue(e,t);return n instanceof xt?n:{result:n}},toModelOutput:({output:e})=>{if(e instanceof xt)throw e.error;if(typeof e==`object`&&e&&Object.keys(e).length===1&&`sandboxFailure`in e&&e.sandboxFailure===!0)return{type:`text`,value:`Agent Sandboxes infrastructure failed. This call did not complete; a developer must fix the sandbox before a new run.`};let t=typeof e==`object`&&e&&!Array.isArray(e)&&Reflect.ownKeys(e).length===1&&Object.hasOwn(e,`result`)?e.result:e;return typeof t==`string`?{type:`text`,value:t}:{type:`json`,value:t}}})}}async close(){return this.closing??=this.shutDown(),this.closing}async closeWhenDone(e){return Promise.resolve(e.finishReason).then(async()=>this.close(),async()=>this.close())}async[Symbol.asyncDispose](){return this.close()}async shutDown(){this.clearIdleTimer(),this.current?.stop(`closed`),await this.queue,await this.releaseSession();let e=this.options.sandboxes===void 0?this.poolPromise:void 0;this.poolPromise=void 0,e!==void 0&&await(await e).close()}async enqueue(e,t){let n=this.queue.then(async()=>this.run(e,t));return this.queue=n.catch(()=>void 0),n}closedError(){return/* @__PURE__ */ Error(`Code mode is closed, so this code did not run.`)}stoppedError(e,t){if(e.stopped===`deadline`)return/* @__PURE__ */ Error(`The code ran longer than its ${Ft(this.limits)}-second time limit, counting time spent waiting on tools, and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and make the code do less work per call.`+e.startedCalls());let n=e.stopped===`aborted`?`The agent run was aborted`:`Code mode was closed`;return t?/* @__PURE__ */ Error(`${n} while this code ran, so tool calls it had not started were stopped.${e.startedCalls()}`):e.stopped===`aborted`?/* @__PURE__ */ Error(`${n}, so this code did not run.`):this.closedError()}async run({code:e,restart:t},n){if(this.closing!==void 0)throw this.closedError();if(this.failure!==void 0)return this.failure;n.abortSignal?.throwIfAborted();let r=Y(e);if(r>this.limits.codeBytes)throw Error(`The code is ${String(r)} bytes, over the ${String(this.limits.codeBytes)}-byte limit for one snippet. Send less code per call; variables and functions from earlier calls are still defined.`);let i=new It(n.toolCallId,this.limits);this.current=i;let a=()=>{i.stop(`aborted`)};n.abortSignal?.addEventListener(`abort`,a,{once:!0}),this.clearIdleTimer();let o=this.expired;this.expired=!1;try{return t===!0&&await this.releaseSession(),await this.feed(e,i,n)}catch(e){throw o&&e instanceof Error?/* @__PURE__ */ Error(`${e.message}\n\nThe sandbox session had no run_code call for ${String(this.idleTimeout/1e3)} seconds and was replaced, so variables, imports and definitions from earlier calls are gone.`):e}finally{i.stop(`finished`),n.abortSignal?.removeEventListener(`abort`,a),this.current=void 0,this.startIdleTimer()}}async failSandbox(e){this.failure=new xt(e);try{await this.options.onError?.({error:e})}catch{return this.failure}return this.failure}async feed(e,t,n,r=!1){let i;try{i=await this.session(t.signal)}catch(e){if(t.stopped!==void 0)throw this.stoppedError(t,!1);return this.failSandbox(e)}if(t.stopped!==void 0)throw t.stopped===`deadline`&&await this.releaseSession(),this.stoppedError(t,!1);let a,o,s,c=!1,l=!1;r||t.start();let d=this.options.typeCheck===`off`||this.options.typeCheck!==`every-snippet`&&this.passedTypeCheck,f=i.feedRun(e,{externalLookup:this.externalLookup(t,n),printCallback:t.printed.write,os:this.osCallback(t),skipTypeCheck:d}).then(e=>({ok:!0,result:e}),e=>({ok:!1,error:e})),p=await Promise.race([f,Mt(t.signal)]);p===`stopped`?(l=!0,this.abandonSession(i,f)):p.ok?(a=p.result,c=!0,this.passedTypeCheck=!0):(o=p.error,s=Ct(o),this.passedTypeCheck||=!(s instanceof u.MontyTypingError||s instanceof u.MontySyntaxError));let m=t.reason();if(m===`closed`||m===`aborted`)throw this.stoppedError(t,!0);if(m===`deadline`){l||await this.releaseSession();let e=s instanceof u.MontyRuntimeError?`Runtime error:\n${t.printed.prependTo(this.cut(s.display(`traceback`)))}\n\n`:``;throw Error(e+this.stoppedError(t,!0).message)}if(!c){if(s instanceof u.MontyShutdown&&!r&&t.callCount===0)return await this.releaseSession(),t.printed=new Pt(this.limits.outputBytes),this.feed(e,t,n,!0);t.stop(`finished`);let i=this.describeFailure(s,t);if((i===void 0||i.reset)&&await this.releaseSession(),i===void 0)return this.failSandbox(o);throw Error(i.message+(r?`\n\n${$}`:``),{cause:o})}let h=this.shapeResult(a,t,r);return r?{result:h,sessionReset:$}:h}shapeResult(e,t,n){let{outputBytes:r}=this.limits,i=/* @__PURE__ */ Error(`The result is more than ${String(r)} bytes of JSON, over the limit for what one snippet returns. The code ran and its variables are still defined, so return a smaller value from them, such as a summary or fewer fields.`+(n?`\n\n${$}`:``)),a;try{a=gt(ht(e,r))}catch(e){throw e instanceof mt?i:e}if(Y(JSON.stringify(a??null))>r)throw i;let o=t.printed.output;return o===``?a??{}:a==null?{output:o}:{output:o,result:a}}cut(e){return _t(e,this.limits.outputBytes)}describeFailure(e,t){let{printed:n}=t;if(e instanceof u.MontySyntaxError)return{message:`Syntax error in code:\n${n.prependTo(this.cut(e.display(`traceback`)))}`,reset:!1};if(e instanceof u.MontyTypingError)return{message:`Type error in code:\n${n.prependTo(this.cut(e.display()))}`,reset:!1};if(e instanceof u.MontyRuntimeError){let r=`Runtime error:\n${n.prependTo(this.cut(e.display(`traceback`)))}`,i=e.display(`msg`);(t.budgetExhausted||Rt.some(e=>i.includes(e)))&&(r+=t.startedCalls());let a=Bt(e),o=Vt(e);a&&(r+=`\n\n${zt}`),o&&(r+=`
37
+ `)}}function st(e){return _e(e)}function ct(e,t){return ft(e,(0,d.asSchema)(t.inputSchema).jsonSchema)}function lt(e){let t=(e?.[`~standard`])?.jsonSchema?.output;return typeof t==`function`?t:void 0}function ut(e,t){let n=lt(t.outputSchema);return n===void 0?ft(e,(0,d.asSchema)(t.outputSchema).jsonSchema):ft(e,n({target:`draft-07`}))}function dt(e){return typeof e.then==`function`}function ft(e,t){if(dt(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 pt=/* @__PURE__ */ new WeakSet;function mt(e,t){pt.has(t)||(pt.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 ht=class extends Error{maxBytes;constructor(e){super(`The value is more than ${String(e)} bytes of JSON.`),this.maxBytes=e}};function gt(e,t){let n=t,r=e=>{if(n-=e,n<0)throw new ht(t)},i=e=>{r(2);let t={};for(let[n,i]of e){let e=String(n);r(X(e)+4),Object.defineProperty(t,e,{value:a(i),enumerable:!0,writable:!0,configurable:!0})}return t},a=e=>{if(e instanceof Map)return i(e);if(e instanceof Set||Array.isArray(e)){r(2);let t=[];for(let n of e)r(1),t.push(a(n));return t}if(typeof e==`bigint`){let t=e.toString();return r(t.length),Number.isSafeInteger(Number(e))?Number(e):t}return e instanceof Uint8Array?(r(e.length+2),Buffer.from(e).toString(`latin1`)):typeof e==`string`?(r(X(e)+2),e):typeof e==`object`&&e?i(Object.entries(e)):(r(typeof e==`number`?String(e).length:5),e)};return a(e)}function _t(e){return typeof e==`number`&&!Number.isFinite(e)?Number.isNaN(e)?`nan`:e>0?`inf`:`-inf`:Array.isArray(e)?e.map(_t):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,_t(t)])):e}function vt(e,t){let n=X(e);if(n<=t)return e;let r=Buffer.from(e),i=Math.floor(t/2),a=r.subarray(0,i).toString().replace(/\uFFFD$/u,``),o=r.subarray(n-i).toString().replace(/^\uFFFD/u,``);return`${a}\n... (${String(n-2*i)} of ${String(n)} bytes cut) ...\n${o}`}function X(e){return Buffer.byteLength(e,`utf8`)}function yt(e,t,n){return e>t?` ... (${String(e)} ${n} total)`:``}function Z(e,t=!1){if(typeof e==`string`)return x(e.slice(0,120))+yt(e.length,120,`chars`);if(Array.isArray(e))return t?`[${String(e.length)} items]`:`[${e.slice(0,5).map(e=>Z(e,!0)).join(`, `)}]`+yt(e.length,5,`items`);if(typeof e==`object`&&e){let n=Object.entries(e);return t?`{${String(n.length)} items}`:`{${n.slice(0,5).map(([e,t])=>`${Z(e,!0)}: ${Z(t,!0)}`).join(`, `)}}`+yt(n.length,5,`items`)}return e==null||typeof e==`boolean`||typeof e==`number`?x(e):`<object>`}function bt(e){let t=[],n=0;for(let r of e){let i=r.status===`returned`?`returned ${r.outputPreview??`None`}`:r.status===`denied`?`was denied and did not run`:`did not finish, so it may have applied a partial change`,a=`- ${r.toolName}(${r.inputPreview}) ${i}`;if(n+a.length>2e3){t.push(`- ... and ${String(e.length-t.length)} more not shown`);break}t.push(a),n+=a.length}let r=String(e.length);return`${r} nested tool calls started before execution stopped:\n`+t.join(`
38
+ `)+`\nAccount for all ${r} before retrying; repeating a call repeats whatever it already did.`}function xt(e){return new Gt(e)}var St=class{sandboxFailure=!0;#e;constructor(e){this.#e=e}get error(){return this.#e}};function Q(e,t){let n=Error(t);return n.name=e,n}function Ct(e){return e instanceof Error?e.message:String(e)}function wt(e){let t=e;for(let e=0;e<8&&t instanceof Error;e+=1){if(t instanceof u.MontyError)return t;t=t.cause}}const Tt=2e3;function Et(e){let t=Ct(e);return t.length>Tt?`${t.slice(0,Tt)} ... (${String(t.length)} chars total)`:t}function Dt(e,t,n){let r=t.at(-1),i=typeof r==`object`&&!!r&&Object.getPrototypeOf(r)===null;if(t.length>+!!i)throw Q(`TypeError`,`${e}() does not accept positional arguments; use keyword arguments`);if(!i)return{};try{return gt(r,n)}catch(t){throw t instanceof ht?Q(`ValueError`,kt(e,n)):t}}function Ot(e,t){return t===void 0?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[t.get(e)??e,n]))}function kt(e,t){return`The arguments to ${e}() are more than ${String(t)} bytes of JSON, over the limit for one call.`}function At(){let e=/* @__PURE__ */ new Map;return(t,n)=>{if(!(n instanceof Map||n instanceof Set))return n;let r=e.get(n);return r===void 0&&(r=n instanceof Map?Object.fromEntries([...n].map(([e,t])=>[String(e),t])):[...n],e.set(n,r)),r}}function jt(e){let t=JSON.stringify(e??null,At());if(t===void 0)throw TypeError(`the result, a ${typeof e==`object`?`value whose toJSON() returns undefined`:typeof e}, has no JSON form`);return t}function Mt(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e}async function $(e,t){if(t.aborted)throw e.catch(()=>void 0),t.reason;return new Promise((n,r)=>{let i=()=>{r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})})}async function Nt(e){return e.aborted?`stopped`:new Promise(t=>{e.addEventListener(`abort`,()=>{t(`stopped`)},{once:!0})})}var Pt=class{free;waiting=[];constructor(e){this.free=e}async acquire(e){if(e.throwIfAborted(),this.free>0){--this.free;return}let t=()=>void 0,n=new Promise(e=>{t=e});this.waiting.push(t);try{await $(n,e)}catch(e){let n=this.waiting.indexOf(t);throw n===-1?this.release():this.waiting.splice(n,1),e}}release(){let e=this.waiting.shift();e===void 0?this.free+=1:e()}},Ft=class{text=``;bytes=0;truncated=!1;maxBytes;constructor(e){this.maxBytes=e}write=(e,t)=>{if(this.truncated)return;let n=X(t);if(this.bytes+n<=this.maxBytes){this.text+=t,this.bytes+=n;return}this.text+=Buffer.from(t).subarray(0,this.maxBytes-this.bytes).toString().replace(/�$/u,``),this.truncated=!0};get output(){return this.truncated?`${this.text}\n[printed output cut at ${String(this.maxBytes)} bytes]\n`:this.text}prependTo(e){let t=this.output.replace(/\n+$/u,``);return t===``?e:`[stdout before error]\n${t}\n[/stdout before error]\n${e}`}};function It(e){return String(e.timeout/1e3)}var Lt=class{calls=[];printed;deadline=1/0;callCount=0;budgetExhausted=!1;stopped;controller=new AbortController;timer;id;limits;constructor(e,t){this.id=e,this.limits=t,this.printed=new Ft(t.outputBytes)}start(){this.deadline=Date.now()+this.limits.timeout,this.timer=setTimeout(()=>{this.stop(`deadline`)},this.limits.timeout)}get signal(){return this.controller.signal}stop(e){if(clearTimeout(this.timer),this.stopped!==void 0)return;this.stopped=e;let t=e===`deadline`?`the code passed its ${It(this.limits)}-second time limit`:e===`aborted`?`the agent run was aborted`:e===`closed`?`code mode was closed`:`the code had already finished`;this.controller.abort(Q(`TimeoutError`,`Stopped because ${t}.`))}reason(){return this.stopped}startedCalls(){return this.calls.length===0?``:`\n\n${bt(this.calls)}`}};const Rt={datetime:`call_host`,sleep:`call_host`,randomStart:`call_host`},zt=/^suspension limit [0-9]+ exceeded$/u,Bt=[`time limit exceeded`,`memory limit exceeded`,`suspension limit `],Vt=`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.`,Ht=`The sandbox session was replaced. Variables, imports and definitions from earlier calls are gone. Recreate any state you need, but do not replay completed side effects.`;function Ut(e){return e.traceback().length===0&&e.display(`msg`).includes(`time limit exceeded`)}function Wt(e){return e.exception.typeName===`MemoryError`&&e.display(`msg`).startsWith(`memory limit exceeded`)}var Gt=class{tools;limits;idleTimeout;pythonNames;schemaArgNames;typeCheckStubs;osPolicy;queue=Promise.resolve();poolPromise;sessionPromise;passedTypeCheck=!1;expired=!1;idleTimer;current;closing;failure;options;traceContext;slots;constructor(e){this.options=e,this.traceContext=c.context.active();let{tools:t,sandboxes:n,idleTimeout:r=3e5}=e;for(let[e,n]of Object.entries(t)){if(typeof n.execute!=`function`)throw Error(`Tool "${e}" has no execute function, so sandbox code cannot call it. Pass it to generateText as a direct tool instead.`);if(n.needsApproval!==void 0)throw Error(`Tool "${e}" sets needsApproval, which code mode cannot enforce. Use the approval option of codeMode() instead.`);if(n.toModelOutput!==void 0)throw Error(`Tool "${e}" sets toModelOutput, which code mode cannot apply: sandbox code receives the result that execute returns. Return only what the model may see from execute, or pass the tool to generateText as a direct tool.`)}if(n===void 0&&[void 0,``].includes(process.env.LOGFIRE_API_KEY))throw Error("Agent sandboxes require a Logfire API key with the `project:execute_agent_sandboxes` scope. Set the LOGFIRE_API_KEY environment variable, or pass `sandboxes` to codeMode().");if(!(r>0))throw RangeError(`idleTimeout must be a positive number of milliseconds or Infinity, not ${String(r)}.`);this.limits=_(e.limits),this.osPolicy={...Rt,...e.osPolicy},this.slots=new Pt(this.limits.concurrentToolCalls),this.idleTimeout=r;let i=it(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:le(i.typeDefinitions,i.functions,ce(this.osPolicy)),inputSchema:(0,d.jsonSchema)({type:`object`,properties:{code:{type:`string`,description:`The Python code to execute in the sandbox.`},restart:{type:`boolean`,description:`Set to true to reset REPL state. When false (default), state is preserved between calls.`}},required:[`code`],additionalProperties:!1},{validate:e=>{let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&(t.restart===void 0||typeof t.restart==`boolean`)?{success:!0,value:{code:t.code,restart:t.restart}}:{success:!1,error:/* @__PURE__ */ TypeError("run_code takes a string `code` and an optional boolean `restart`.")}}}),execute:async(e,t)=>{let n=await this.enqueue(e,t);return n instanceof St?n:{result:n}},toModelOutput:({output:e})=>{if(e instanceof St)throw e.error;if(typeof e==`object`&&e&&Object.keys(e).length===1&&`sandboxFailure`in e&&e.sandboxFailure===!0)return{type:`text`,value:`Agent Sandboxes infrastructure failed. This call did not complete; a developer must fix the sandbox before a new run.`};let t=typeof e==`object`&&e&&!Array.isArray(e)&&Reflect.ownKeys(e).length===1&&Object.hasOwn(e,`result`)?e.result:e;return typeof t==`string`?{type:`text`,value:t}:{type:`json`,value:t}}})}}async close(){return this.closing??=this.shutDown(),this.closing}async closeWhenDone(e){return Promise.resolve(e.finishReason).then(async()=>this.close(),async()=>this.close())}async[Symbol.asyncDispose](){return this.close()}async shutDown(){this.clearIdleTimer(),this.current?.stop(`closed`),await this.queue,await this.releaseSession();let e=this.options.sandboxes===void 0?this.poolPromise:void 0;this.poolPromise=void 0,e!==void 0&&await(await e).close()}async enqueue(e,t){let n=this.queue.then(async()=>this.run(e,t));return this.queue=n.catch(()=>void 0),n}closedError(){return/* @__PURE__ */ Error(`Code mode is closed, so this code did not run.`)}stoppedError(e,t){if(e.stopped===`deadline`)return/* @__PURE__ */ Error(`The code ran longer than its ${It(this.limits)}-second time limit, counting time spent waiting on tools, and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and make the code do less work per call.`+e.startedCalls());let n=e.stopped===`aborted`?`The agent run was aborted`:`Code mode was closed`;return t?/* @__PURE__ */ Error(`${n} while this code ran, so tool calls it had not started were stopped.${e.startedCalls()}`):e.stopped===`aborted`?/* @__PURE__ */ Error(`${n}, so this code did not run.`):this.closedError()}async run({code:e,restart:t},n){if(this.closing!==void 0)throw this.closedError();if(this.failure!==void 0)return this.failure;n.abortSignal?.throwIfAborted();let r=X(e);if(r>this.limits.codeBytes)throw Error(`The code is ${String(r)} bytes, over the ${String(this.limits.codeBytes)}-byte limit for one snippet. Send less code per call; variables and functions from earlier calls are still defined.`);let i=new Lt(n.toolCallId,this.limits);this.current=i;let a=()=>{i.stop(`aborted`)};n.abortSignal?.addEventListener(`abort`,a,{once:!0}),this.clearIdleTimer();let o=this.expired;this.expired=!1;try{return t===!0&&await this.releaseSession(),await this.feed(e,i,n)}catch(e){throw o&&e instanceof Error?/* @__PURE__ */ Error(`${e.message}\n\nThe sandbox session had no run_code call for ${String(this.idleTimeout/1e3)} seconds and was replaced, so variables, imports and definitions from earlier calls are gone.`):e}finally{i.stop(`finished`),n.abortSignal?.removeEventListener(`abort`,a),this.current=void 0,this.startIdleTimer()}}async failSandbox(e){this.failure=new St(e);try{await this.options.onError?.({error:e})}catch{return this.failure}return this.failure}async feed(e,t,n,r=!1){let i;try{i=await this.session(t.signal)}catch(e){if(t.stopped!==void 0)throw this.stoppedError(t,!1);return this.failSandbox(e)}if(t.stopped!==void 0)throw t.stopped===`deadline`&&await this.releaseSession(),this.stoppedError(t,!1);let a,o,s,c=!1,l=!1;r||t.start();let d=this.options.typeCheck===`off`||this.options.typeCheck!==`every-snippet`&&this.passedTypeCheck,f=i.feedRun(e,{externalLookup:this.externalLookup(t,n),printCallback:t.printed.write,os:this.osCallback(t),skipTypeCheck:d}).then(e=>({ok:!0,result:e}),e=>({ok:!1,error:e})),p=await Promise.race([f,Nt(t.signal)]);p===`stopped`?(l=!0,this.abandonSession(i,f)):p.ok?(a=p.result,c=!0,this.passedTypeCheck=!0):(o=p.error,s=wt(o),this.passedTypeCheck||=!(s instanceof u.MontyTypingError||s instanceof u.MontySyntaxError));let m=t.reason();if(m===`closed`||m===`aborted`)throw this.stoppedError(t,!0);if(m===`deadline`){l||await this.releaseSession();let e=s instanceof u.MontyRuntimeError?`Runtime error:\n${t.printed.prependTo(this.cut(s.display(`traceback`)))}\n\n`:``;throw Error(e+this.stoppedError(t,!0).message)}if(!c){if(s instanceof u.MontyShutdown&&!r&&t.callCount===0)return await this.releaseSession(),t.printed=new Ft(this.limits.outputBytes),this.feed(e,t,n,!0);t.stop(`finished`);let i=this.describeFailure(s,t);if((i===void 0||i.reset)&&await this.releaseSession(),i===void 0)return this.failSandbox(o);throw Error(i.message+(r?`\n\n${Ht}`:``),{cause:o})}let h=this.shapeResult(a,t,r);return r?{result:h,sessionReset:Ht}:h}shapeResult(e,t,n){let{outputBytes:r}=this.limits,i=/* @__PURE__ */ Error(`The result is more than ${String(r)} bytes of JSON, over the limit for what one snippet returns. The code ran and its variables are still defined, so return a smaller value from them, such as a summary or fewer fields.`+(n?`\n\n${Ht}`:``)),a;try{a=_t(gt(e,r))}catch(e){throw e instanceof ht?i:e}if(X(JSON.stringify(a??null))>r)throw i;let o=t.printed.output;return o===``?a??{}:a==null?{output:o}:{output:o,result:a}}cut(e){return vt(e,this.limits.outputBytes)}describeFailure(e,t){let{printed: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||Bt.some(e=>i.includes(e)))&&(r+=t.startedCalls());let a=Ut(e),o=Wt(e);a&&(r+=`\n\n${Vt}`),o&&(r+=`
22
39
 
23
- The code ran out of memory and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and keep less data in memory at once.`);let s=a||o;return e.exception.typeName===`RuntimeError`&&Lt.test(i)&&(r+=`
40
+ 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`&&zt.test(i)&&(r+=`
24
41
 
25
- 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&&e.timedOut||e instanceof u.MontyDisconnectError&&e.cause===`turn_timeout`)return{message:zt+t.startedCalls(),reset:!0};if(e instanceof u.MontyDisconnectError)return{message:(e.cause===`session_timeout`||e.cause===`idle_timeout`?`The sandbox session ended and its state is lost. Re-run any imports and recreate any state you need. `:`The sandbox session ended unexpectedly and its state was lost. Recreate any state you need. `)+`Check any tool calls already started before continuing, and do not replay completed side effects.`+t.startedCalls(),reset:!0};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}}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 ${Ft(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=Dt(Et(t,n,a.toolInputBytes),this.schemaArgNames.get(t));if(Y(JSON.stringify(c))>a.toolInputBytes)throw Z(`ValueError`,Ot(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}(): ${Tt(l.error)}`);let u=l===void 0?c:l.value,p=this.options.context,h=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?.(h)),r.signal);if(t!==void 0&&!t.success)throw Z(`ValueError`,`Invalid context for tool "${e}": ${Tt(t.error)}`);h=t===void 0?h:t.value}let g={toolName:e,inputPreview:X(u),status:`running`},_=await Q(m(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:h,tool:o}),r.signal);if(!_.approved){g.status=`denied`,r.calls.push(g);let t=_.reason===void 0?``:` ${_.reason}`;throw Z(`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 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:h,abortSignal:r.signal});b.running=e,e.then(y,y),n=await Q(e,r.signal)}catch(t){throw g.status=`failed`,r.stopped===void 0?this.replaceToolError(t,{toolName:e,toolCallId:s,input:u}):t}g.status=`returned`;let c;try{c=At(n)}catch(e){let n=e instanceof RangeError?`it is nested too deeply or contains itself`:St(e);throw g.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 g.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 g.outputPreview=X(d),d})}finally{b.running===void 0&&y()}}async execute(e,t,n){let r=e.execute,i=r(t,n);if(jt(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(e){this.sessionPromise??=this.checkout(e);try{return await this.sessionPromise}catch(e){throw this.sessionPromise=void 0,e}}async checkout(e){let t=this.options.typeCheck!==`off`;return c.context.with(this.traceContext,async()=>{e.throwIfAborted();let n=await this.pool();e.throwIfAborted();let r={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`}};try{return await n.checkout(r)}catch(t){let i=Ct(t);if(!(i instanceof u.MontyRefusedError)||i.statusCode===`UNAUTHENTICATED`||i.statusCode===`PERMISSION_DENIED`||![`caller_cap`,`capacity`,`worker_unavailable`].some(e=>e===i.cause))throw t;return await(0,p.setTimeout)(100,void 0,{signal:e}),e.throwIfAborted(),n.checkout(r)}})}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;
42
+ 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&&e.timedOut||e instanceof u.MontyDisconnectError&&e.cause===`turn_timeout`)return{message:Vt+t.startedCalls(),reset:!0};if(e instanceof u.MontyDisconnectError)return{message:(e.cause===`session_timeout`||e.cause===`idle_timeout`?`The sandbox session ended and its state is lost. Re-run any imports and recreate any state you need. `:`The sandbox session ended unexpectedly and its state was lost. Recreate any state you need. `)+`Check any tool calls already started before continuing, and do not replay completed side effects.`+t.startedCalls(),reset:!0};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}}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 Q(`TimeoutError`,`sleeping ${String(r)}s would exceed the ${It(this.limits)}s this code may run; ${i.toFixed(1)}s left`);return await $((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,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 s=`${r.id}__${String(r.callCount)}`,c=Ot(Dt(t,n,a.toolInputBytes),this.schemaArgNames.get(t));if(X(JSON.stringify(c))>a.toolInputBytes)throw Q(`ValueError`,kt(t,a.toolInputBytes));let l=await $(Promise.resolve((0,d.asSchema)(o.inputSchema).validate?.(c)),r.signal);if(l!==void 0&&!l.success)throw Q(`ValueError`,`Invalid arguments for ${t}(): ${Et(l.error)}`);let u=l===void 0?c:l.value,p=this.options.context,h=p!==void 0&&Object.hasOwn(p,e)?p[e]:void 0;if(o.contextSchema!==void 0){let t=await $(Promise.resolve((0,d.asSchema)(o.contextSchema).validate?.(h)),r.signal);if(t!==void 0&&!t.success)throw Q(`ValueError`,`Invalid context for tool "${e}": ${Et(t.error)}`);h=t===void 0?h:t.value}let g={toolName:e,inputPreview:Z(u),status:`running`},_=await $(m(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: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())},ee={};r.calls.push(g);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:h,abortSignal:r.signal});ee.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:s,input:u}):t}g.status=`returned`;let c;try{c=jt(n)}catch(e){let n=e instanceof RangeError?`it is nested too deeply or contains itself`:Ct(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(c);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 d=JSON.parse(c);return g.outputPreview=Z(d),d})}finally{ee.running===void 0&&y()}}async execute(e,t,n){let r=e.execute,i=r(t,n);if(Mt(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(e){this.sessionPromise??=this.checkout(e);try{return await this.sessionPromise}catch(e){throw this.sessionPromise=void 0,e}}async checkout(e){let t=this.options.typeCheck!==`off`;return c.context.with(this.traceContext,async()=>{e.throwIfAborted();let n=await this.pool();e.throwIfAborted();let r={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,...this.osPolicy.sleep===`system`?{maxTotalSleepSecs:this.limits.timeout/1e3}:{}},osPolicy:this.osPolicy};try{return await n.checkout(r)}catch(t){let i=wt(t);if(!(i instanceof u.MontyRefusedError)||i.statusCode===`UNAUTHENTICATED`||i.statusCode===`PERMISSION_DENIED`||![`caller_cap`,`capacity`,`worker_unavailable`].some(e=>e===i.cause))throw t;return await(0,p.setTimeout)(100,void 0,{signal:e}),e.throwIfAborted(),n.checkout(r)}})}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=xt;
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { MontySession, RemoteCheckoutOptions } from "@pydantic/monty";
1
+ import { MontySession, OsPolicy, RemoteCheckoutOptions } from "@pydantic/monty";
2
2
  import { StreamTextOnErrorCallback, Tool, ToolApprovalConfiguration, ToolApprovalStatus, ToolSet } from "ai";
3
3
  //#region src/approval.d.ts
4
4
  type AnyFunction = (...args: never[]) => unknown;
@@ -78,6 +78,15 @@ interface CodeModeOptions<TOOLS extends ToolSet, RUNTIME_CONTEXT = unknown> {
78
78
  /** Passed to `approval` functions; tool execution does not see generateText's `runtimeContext`. */
79
79
  runtimeContext?: RUNTIME_CONTEXT;
80
80
  limits?: CodeModeLimits;
81
+ /**
82
+ * Monty's clock, time zone, sleep and randomness settings, merged key by key over the default, which has no clock
83
+ * or randomness and waits for sleeps on the host (pydantic-ai's policy). For example, `{ datetime: 'system',
84
+ * randomStart: 'system' }` gives code the sandbox's clock and random seeding. The `run_code` description says
85
+ * whether code has a clock and whether sleeps wait. With `sleep: 'system'`, the sandbox waits instead of the host:
86
+ * each sleep stops at `sleepSystemMax` (10 seconds by default), and sleeps in one snippet that add up to more than
87
+ * `limits.timeout` raise `TimeoutError`.
88
+ */
89
+ osPolicy?: OsPolicy;
81
90
  /**
82
91
  * Which snippets Monty's type checker sees (default `'first-snippet'`, as pydantic-ai). Monty's checker rejects
83
92
  * some valid code, such as a None check on an indexed value, and a model can spend every step trying to satisfy
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { MontySession, RemoteCheckoutOptions } from "@pydantic/monty";
1
+ import { MontySession, OsPolicy, RemoteCheckoutOptions } from "@pydantic/monty";
2
2
  import { StreamTextOnErrorCallback, Tool, ToolApprovalConfiguration, ToolApprovalStatus, ToolSet } from "ai";
3
3
  //#region src/approval.d.ts
4
4
  type AnyFunction = (...args: never[]) => unknown;
@@ -78,6 +78,15 @@ interface CodeModeOptions<TOOLS extends ToolSet, RUNTIME_CONTEXT = unknown> {
78
78
  /** Passed to `approval` functions; tool execution does not see generateText's `runtimeContext`. */
79
79
  runtimeContext?: RUNTIME_CONTEXT;
80
80
  limits?: CodeModeLimits;
81
+ /**
82
+ * Monty's clock, time zone, sleep and randomness settings, merged key by key over the default, which has no clock
83
+ * or randomness and waits for sleeps on the host (pydantic-ai's policy). For example, `{ datetime: 'system',
84
+ * randomStart: 'system' }` gives code the sandbox's clock and random seeding. The `run_code` description says
85
+ * whether code has a clock and whether sleeps wait. With `sleep: 'system'`, the sandbox waits instead of the host:
86
+ * each sleep stops at `sleepSystemMax` (10 seconds by default), and sleeps in one snippet that add up to more than
87
+ * `limits.timeout` raise `TimeoutError`.
88
+ */
89
+ osPolicy?: OsPolicy;
81
90
  /**
82
91
  * Which snippets Monty's type checker sees (default `'first-snippet'`, as pydantic-ai). Monty's checker rejects
83
92
  * some valid code, such as a None check on an indexed value, and a model can spend every step trying to satisfy
package/dist/index.js CHANGED
@@ -1,25 +1,42 @@
1
1
  import{context as e}from"@opentelemetry/api";import{agentSandboxes as t}from"@pydantic/logfire-agent-sandboxes";import{MontyCrashedError as n,MontyDisconnectError as r,MontyError as i,MontyRefusedError as a,MontyRuntimeError as o,MontyShutdown as s,MontySyntaxError as c,MontyTypingError as l,NOT_HANDLED as u}from"@pydantic/monty";import{asSchema as d,jsonSchema as f,tool as p}from"ai";import*as ee from"logfire";import{setTimeout as m}from"node:timers/promises";async function h(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 g={timeout:3e4,toolCalls:100,concurrentToolCalls:8,outputBytes:64e3,codeBytes:1e5,toolInputBytes:1e6,toolOutputBytes:1e7,memory:268435456,suspensions:1e4},_=/* @__PURE__ */ new Set([`toolCalls`,`concurrentToolCalls`,`memory`,`suspensions`]);function v(e={}){let t={...g};for(let[n,r]of Object.entries(e)){if(!(n in g))throw TypeError(`Unknown code mode limit "${n}". The limits are: ${Object.keys(g).join(`, `)}.`);if(r!==void 0){if(!(typeof r==`number`&&r>0&&Number.isFinite(r)&&(!_.has(n)||Number.isSafeInteger(r)))){let e=_.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 te=/* @__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 ne(e){return te.has(e)}const re=/* @__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 ie(e){return re.has(e)}function y(e){return/^[\p{XID_Start}_]\p{XID_Continue}*$/u.test(e)}function b(e){return y(e)&&!ne(e)}function x(e){return e==null?`None`:typeof e==`boolean`?e?`True`:`False`:typeof e==`number`?ae(e):typeof e==`string`?se(e):Array.isArray(e)?`[${e.map(x).join(`, `)}]`:typeof e==`object`?`{${Object.entries(e).map(([e,t])=>`${se(e)}: ${x(t)}`).join(`, `)}}`:typeof e==`bigint`?e.toString():`None`}function ae(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 oe=/[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Cn}\p{Zl}\p{Zp}\p{Zs}]/u;function se(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!==` `&&oe.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 ce='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 le(e,t){if(t.length===0)return ce;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(`
2
+ `)n+=`\\n`;else if(r===`\r`)n+=`\\r`;else if(r!==` `&&oe.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}function ce(e){return`- **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. ${e}`}function le(e){return`- **No filesystem or environment**: \`pathlib.Path\` I/O and \`os.getenv\`/\`os.environ\` 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. \`datetime.datetime.now()\`, \`datetime.date.today()\`, and \`time.time()\` read the clock configured for this sandbox. ${e}`}function ue(e){let t=e.sleep===`zero`?"`time.sleep` and `asyncio.sleep` return at once without waiting.":"`time.sleep` and `asyncio.sleep` really wait.";return e.datetime===void 0||e.datetime===`call_host`?ce(t):le(t)}function de(e,t,n=ue({})){let r=`Write and run Python code in a sandboxed environment.
3
3
 
4
- `)+"\n```"),n.push("```python\n"+t.join(`
4
+ The sandbox uses Monty, a subset of Python. Key restrictions:
5
+ - **No third-party libraries**: only the standard library modules listed below can be used
6
+ - **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${n}\n- **No \`import *\`**: wildcard imports are not supported
5
7
 
6
- `)+"\n```"),`${ce}\n\n${n.join(`
8
+ State is preserved between calls (REPL-style). Set \`restart: true\` to reset state.
7
9
 
8
- `)}`}let S,C=/* @__PURE__ */ new Set;var w=class{kind=`simple`;name;constructor(e){this.name=e}toString(){return this.name}},ue=class{kind=`literal`;values;constructor(e){this.values=e}toString(){return`Literal[${this.values.map(x).join(`, `)}]`}},T=class{kind=`generic`;base;args;constructor(e,t){this.base=e,this.args=t}toString(){return`${this.base}[${this.args.map(String).join(`, `)}]`}},E=class{kind=`union`;members;constructor(e){this.members=e}toString(){return this.members.map(String).join(` | `)}};const de=` `;function fe(e){return e.replace(/[\\\0"]/gu,e=>e===`\\`?`\\\\`:e===`\0`?`\\x00`:`\\"`)}const D=`\\s\\x1c-\\x1f\\x85`,pe=RegExp(`^[${D}]+|[${D}]+$`,`gu`),me=/\r\n|[\n\r\v\f\x1c-\x1e\x85\u2028\u2029]/u,he=RegExp(`[${D}]+$`,`u`);function O(e){return e.replace(pe,``)}function ge(e){return e.replace(he,``)}function k(e){if(e===``)return[];let t=e.split(me);return t.at(-1)===``&&me.test(e.at(-1)??``)&&t.pop(),t}function A(e){return e!==void 0&&e!==``}function _e(e,t=``){let n=fe(O(e)),r=k(n);return r.length>1?[`${t}"""`,...r.map(e=>O(e)?`${t}${e}`:``),`${t}"""`]:[`${t}"""${n}"""`]}function ve(e){let t=e.replace(/[^a-zA-Z0-9_]/gu,`_`);return/^[0-9]/u.test(t)&&(t=`_${t}`),ne(t)&&(t=`${t}_`),t||`_`}function ye(e,t=``){return k(O(e).replace(/\0/gu,`\\x00`)).map(e=>ge(`${t}# ${e}`))}var be=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}: ${xe(this)}`];return A(this.description)&&e.push(..._e(this.description,` `)),e.join(`
9
- `)}};function xe(e){let t=String(e.type);return e.required?t:`NotRequired[${t}]`}function Se(e){let t=A(e.description)?ye(e.description,` `):[];return t.push(` ${x(e.name)}: ${xe(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(S===void 0||!S.conflicting.has(this.name))return this.name;let e=S.typeNames.get(this);if(e!==void 0)return e;let t=S.fallbackOwner;return A(t)?`${t}_${this.name}`:this.name}toString(){return this.displayName}renderDefinition(e,t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Map){return Ee({conflicting:t,typeNames:n,fallbackOwner:e},()=>this.renderDefinitionBody())}renderDefinitionBody(){if(![...this.fields.keys()].every(b))return this.renderFunctionalDefinition();let e=[`class ${this.displayName}(TypedDict):`];if(A(this.description)&&e.push(..._e(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)?ye(this.description):[];return e.push(`${this.displayName} = TypedDict(${x(this.displayName)}, {`),e.push(...[...this.fields.values()].map(Se)),e.push(`})`),e.join(`
12
- `)}structurallyEqual(e){return Ce(this,e,/* @__PURE__ */ new Map)}};function Ce(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||!we(i.type,e.type,n))return!1}return!0}function we(e,t,n){return e instanceof j&&t instanceof j?e.name===t.name&&Ce(e,t,n):e instanceof T&&t instanceof T?e.base===t.base&&Te(e.args,t.args,n):e instanceof E&&t instanceof E?Te(e.members,t.members,n):e.kind===t.kind&&String(e)===String(t)}function Te(e,t,n){return e.length===t.length&&e.every((e,r)=>{let i=t[r];return i!==void 0&&we(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 Ee({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(`${de}${e.name}: ${t}`),l.push(...n.map(e=>`${de}${de}${e}`)))}l.length>0&&c.push([`Args:`,...l].join(`
10
+ The 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:
11
+
12
+ \`\`\`python
13
+ result = some_expression
14
+ result
15
+ \`\`\`
16
+
17
+ Avoid \`print()\` for return values as it produces Python string representations, not structured data. Use \`print()\` only for supplementary logging or debug output.
18
+
19
+ Returns 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.`;if(t.length===0)return r;let i=["\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&&i.push("```python\n"+e.join(`
20
+
21
+ `)+"\n```"),i.push("```python\n"+t.join(`
22
+
23
+ `)+"\n```"),`${r}\n\n${i.join(`
24
+
25
+ `)}`}let S,C=/* @__PURE__ */ new Set;var w=class{kind=`simple`;name;constructor(e){this.name=e}toString(){return this.name}},fe=class{kind=`literal`;values;constructor(e){this.values=e}toString(){return`Literal[${this.values.map(x).join(`, `)}]`}},T=class{kind=`generic`;base;args;constructor(e,t){this.base=e,this.args=t}toString(){return`${this.base}[${this.args.map(String).join(`, `)}]`}},E=class{kind=`union`;members;constructor(e){this.members=e}toString(){return this.members.map(String).join(` | `)}};const D=` `;function pe(e){return e.replace(/[\\\0"]/gu,e=>e===`\\`?`\\\\`:e===`\0`?`\\x00`:`\\"`)}const me=`\\s\\x1c-\\x1f\\x85`,he=RegExp(`^[${me}]+|[${me}]+$`,`gu`),ge=/\r\n|[\n\r\v\f\x1c-\x1e\x85\u2028\u2029]/u,_e=RegExp(`[${me}]+$`,`u`);function O(e){return e.replace(he,``)}function ve(e){return e.replace(_e,``)}function k(e){if(e===``)return[];let t=e.split(ge);return t.at(-1)===``&&ge.test(e.at(-1)??``)&&t.pop(),t}function A(e){return e!==void 0&&e!==``}function j(e,t=``){let n=pe(O(e)),r=k(n);return r.length>1?[`${t}"""`,...r.map(e=>O(e)?`${t}${e}`:``),`${t}"""`]:[`${t}"""${n}"""`]}function ye(e){let t=e.replace(/[^a-zA-Z0-9_]/gu,`_`);return/^[0-9]/u.test(t)&&(t=`_${t}`),ne(t)&&(t=`${t}_`),t||`_`}function be(e,t=``){return k(O(e).replace(/\0/gu,`\\x00`)).map(e=>ve(`${t}# ${e}`))}var xe=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}: ${Se(this)}`];return A(this.description)&&e.push(...j(this.description,` `)),e.join(`
26
+ `)}};function Se(e){let t=String(e.type);return e.required?t:`NotRequired[${t}]`}function Ce(e){let t=A(e.description)?be(e.description,` `):[];return t.push(` ${x(e.name)}: ${Se(e)},`),t.join(`
27
+ `)}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(S===void 0||!S.conflicting.has(this.name))return this.name;let e=S.typeNames.get(this);if(e!==void 0)return e;let t=S.fallbackOwner;return A(t)?`${t}_${this.name}`:this.name}toString(){return this.displayName}renderDefinition(e,t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Map){return De({conflicting:t,typeNames:n,fallbackOwner:e},()=>this.renderDefinitionBody())}renderDefinitionBody(){if(![...this.fields.keys()].every(b))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(`
28
+ `)}renderFunctionalDefinition(){let e=A(this.description)?be(this.description):[];return e.push(`${this.displayName} = TypedDict(${x(this.displayName)}, {`),e.push(...[...this.fields.values()].map(Ce)),e.push(`})`),e.join(`
29
+ `)}structurallyEqual(e){return we(this,e,/* @__PURE__ */ new Map)}};function we(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||!Te(i.type,e.type,n))return!1}return!0}function Te(e,t,n){return e instanceof M&&t instanceof M?e.name===t.name&&we(e,t,n):e instanceof T&&t instanceof T?e.base===t.base&&Ee(e.args,t.args,n):e instanceof E&&t instanceof E?Ee(e.members,t.members,n):e.kind===t.kind&&String(e)===String(t)}function Ee(e,t,n){return e.length===t.length&&e.every((e,r)=>{let i=t[r];return i!==void 0&&Te(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 De({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(`${D}${e.name}: ${t}`),l.push(...n.map(e=>`${D}${D}${e}`)))}l.length>0&&c.push([`Args:`,...l].join(`
13
30
  `));let u=c.join(`
14
31
 
15
- `);return u!==``&&s.push(..._e(u,` `)),s.push(` ${e}`),s.join(`
16
- `)}static fromSchema(t,n,r){let i=Ae(n),a=/* @__PURE__ */ new Map;Pe(i,a,t);let o=Fe(n,i,a,t),s=P,c=/* @__PURE__ */ new Map;if(r!==void 0){let e=Ae(r);Pe(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)?(qe(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 Ee(e,t){let n=S;S=e;try{return t()}finally{S=n}}const P=new w(`Any`),F=new w(`None`),De=/* @__PURE__ */ new Map([[`string`,`str`],[`integer`,`int`],[`number`,`float`],[`boolean`,`bool`],[`null`,`None`]]);function Oe(e){return new w(De.get(e)??`Any`)}function ke(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(ke).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 Ae(e){let t=e.$defs;return z(t)?t:{}}function je(e){let t=e.properties;return z(t)?t:{}}function Me(e){let t=e.required;return new Set(Array.isArray(t)?t:[])}function Ne(e){return e.type===`object`&&`properties`in e}function Pe(e,t,n){for(let[r,i]of Object.entries(e)){let a=B(i);Ne(a)&&!t.has(r)&&H(r,a,e,t,n,r)}}function Fe(e,t,n,r){let i=Me(e),a=je(e),o=Ie(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,x(a.default),d)):i.has(e)?s.set(e,new M(f,u,void 0,d)):Le(a)?c.set(e,new M(f,u,`None`,d)):c.set(e,new M(f,new E([u,F]),`None`,d))}return new Map([...s,...c])}function Ie(e){let t=[...e],n=new Set(t.filter(b)),r=/* @__PURE__ */ new Map;for(let e of t){if(b(e)){r.set(e,e);continue}let t=ve(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 Le(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(Ne(a))H(e,a,t,n,r,i);else{if(C.has(e))return P;let o=C;C=/* @__PURE__ */ new Set([...o,e]);try{return V(a,t,n,r,i)}finally{C=o}}}return n.get(e)??new j(e)}if(`anyOf`in a)return Ve(a.anyOf,t,n,r,i);if(`oneOf`in a)return Ve(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 ue([a.const]):`enum`in a?new ue(a.enum):Re(a.type,a,t,n,r,i)}function Re(e,t,n,r,i,a){let o=De.get(e);if(o!==void 0)return new w(o);if(e===`array`){let e=t.items??{};return ze(e)?Array.isArray(e)?new T(`tuple`,e.map((e,t)=>V(e,n,r,i,`${a}.${String(t)}`))):new T(`list`,[V(e,n,r,i,`${a}Item`)]):new T(`list`,[P])}if(e===`object`){if(`properties`in t){let e=t.title,o=typeof e==`string`&&e!==``&&y(e)?e:L(i,a),s=Object.hasOwn(n,o)?B(n[o]):void 0;return s!==void 0&&Ne(s)&&!r.has(o)&&H(o,s,n,r,i,o),r.has(o)?Ge(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 T(`dict`,[new w(`str`),P]);if(z(e)){let t=V(e,n,r,i,`${a}Value`);return new T(`dict`,[new w(`str`),t])}}return new T(`dict`,[new w(`str`),P])}return Array.isArray(e)?Be(e,t,n,r,i,a):P}function ze(e){return Array.isArray(e)?e.length>0:z(e)?Object.keys(e).length>0:!!e}function Be(e,t,n,r,i,a){if(e.includes(`object`)&&`properties`in t){let o=Re(`object`,t,n,r,i,a);return e.includes(`null`)?new E([o,F]):o}let o=e.map(Oe),s=o.find(e=>String(e)!==`None`);if(o.length===2&&s!==void 0&&o.some(e=>String(e)===`None`))return new E([s,F]);let[c,...l]=o;return c===void 0?P:l.length>0?new E(o):c}function Ve(e,t,n,r,i){let a=e.map(B),o=He(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 E(u)}function He(e,t){let n=e.filter(e=>e.type===`object`&&`properties`in e&&!Ue(e)),r=/* @__PURE__ */ new Map;if(n.length<2)return r;let i=n.map(We),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 Ue(e){let t=e.title;return typeof t==`string`&&t!==``&&y(t)}function We(e){for(let t of Object.values(je(e))){let e=B(t).const;if(typeof e==`string`&&I(e)!==``)return e}}function Ge(e,t,n,r,i,a){let o=Ke(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=Ke(e,t,n,r,i,a);return o.fields=s.fields,o.description=s.description,o}function Ke(e,t,n,r,i,a){let o=Me(t),s=/* @__PURE__ */ new Map;for(let[e,c]of Object.entries(je(t))){let t=B(c),l=V(t,n,r,i,a?`${a}.${e}`:e),u=R(t.description);s.set(e,new be(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 T){let n=e.args.map(e=>U(e,t));n.some((t,n)=>t!==e.args[n])&&(e.args=n)}else if(e instanceof E){let n=e.members.map(e=>U(e,t));n.some((t,n)=>t!==e.members[n])&&(e.members=n)}return e}function qe(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 Je(e,t,n){let r=structuredClone(e),i=Ye(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=Qe(r.title,void 0,()=>L(t,n===`return`?`Return`:``)),o.add(c));let l=tt(r,i,n);for(let[e,n]of Object.entries(i))s(e,Qe(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 Ye(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])=>!$e.has(e)&&G(n,t)):!1}const Xe=/^__schema\d+$/u,Ze=/* @__PURE__ */ new Set([`asyncio`,`Any`,`TypedDict`,`NotRequired`,`Literal`,`str`,`int`,`float`,`bool`,`list`,`dict`,`tuple`]);function K(e){return b(e)&&!Ze.has(e)}function Qe(e,t,n){if(t!==void 0&&K(t)&&!Xe.test(t))return t;if(typeof e==`string`&&K(e))return e;if(t!==void 0&&!Xe.test(t)){let e=I(t);if(K(e))return e}return n()}const $e=/* @__PURE__ */ new Set([`default`,`const`,`enum`,`examples`]),et=/* @__PURE__ */ new Set([`properties`,`patternProperties`,`$defs`,`definitions`]);function tt(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=nt(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 nt(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(et.has(a)&&W(o))i[a]=Object.fromEntries(Object.entries(o).map(([e,i])=>[e,q(i,t,n,r)]));else if($e.has(a))i[a]=o;else if(a===`$ref`&&typeof o==`string`)i[a]=rt(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 rt(e,t,n,r){if(e===`#`&&r!==void 0)return`#/$defs/${r}`;let i=nt(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 it=`import asyncio
32
+ `);return u!==``&&s.push(...j(u,` `)),s.push(` ${e}`),s.join(`
33
+ `)}static fromSchema(t,n,r){let i=je(n),a=/* @__PURE__ */ new Map;Ne(i,a,t);let o=Pe(n,i,a,t),s=F,c=/* @__PURE__ */ new Map;if(r!==void 0){let e=je(r);Ne(e,c,t),s=W(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=K(s,u);for(let e of l)for(let t of e.fields.values())t.type=K(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)?(Ke(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 De(e,t){let n=S;S=e;try{return t()}finally{S=n}}const F=new w(`Any`),I=new w(`None`),Oe=/* @__PURE__ */ new Map([[`string`,`str`],[`integer`,`int`],[`number`,`float`],[`boolean`,`bool`],[`null`,`None`]]);function ke(e){return new w(Oe.get(e)??`Any`)}function Ae(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(Ae).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 je(e){let t=e.$defs;return B(t)?t:{}}function H(e){let t=e.properties;return B(t)?t:{}}function Me(e){let t=e.required;return new Set(Array.isArray(t)?t:[])}function U(e){return e.type===`object`&&`properties`in e}function Ne(e,t,n){for(let[r,i]of Object.entries(e)){let a=V(i);U(a)&&!t.has(r)&&G(r,a,e,t,n,r)}}function Pe(e,t,n,r){let i=Me(e),a=H(e),o=Fe(Object.keys(a)),s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Map;for(let[e,l]of Object.entries(a)){let a=V(l),u=W(a,t,n,r,e),d=z(a.description),f=o.get(e)??e;`default`in a?c.set(e,new N(f,u,x(a.default),d)):i.has(e)?s.set(e,new N(f,u,void 0,d)):Ie(a)?c.set(e,new N(f,u,`None`,d)):c.set(e,new N(f,new E([u,I]),`None`,d))}return new Map([...s,...c])}function Fe(e){let t=[...e],n=new Set(t.filter(b)),r=/* @__PURE__ */ new Map;for(let e of t){if(b(e)){r.set(e,e);continue}let t=ye(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 Ie(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 W(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(U(a))G(e,a,t,n,r,i);else{if(C.has(e))return F;let o=C;C=/* @__PURE__ */ new Set([...o,e]);try{return W(a,t,n,r,i)}finally{C=o}}}return n.get(e)??new M(e)}if(`anyOf`in a)return Be(a.anyOf,t,n,r,i);if(`oneOf`in a)return Be(a.oneOf,t,n,r,i);if(`allOf`in a){let e=a.allOf;return e.length===1?W(e[0],t,n,r,i):F}return`const`in a?new fe([a.const]):`enum`in a?new fe(a.enum):Le(a.type,a,t,n,r,i)}function Le(e,t,n,r,i,a){let o=Oe.get(e);if(o!==void 0)return new w(o);if(e===`array`){let e=t.items??{};return Re(e)?Array.isArray(e)?new T(`tuple`,e.map((e,t)=>W(e,n,r,i,`${a}.${String(t)}`))):new T(`list`,[W(e,n,r,i,`${a}Item`)]):new T(`list`,[F])}if(e===`object`){if(`properties`in t){let e=t.title,o=typeof e==`string`&&e!==``&&y(e)?e:R(i,a),s=Object.hasOwn(n,o)?V(n[o]):void 0;return s!==void 0&&U(s)&&!r.has(o)&&G(o,s,n,r,i,o),r.has(o)?We(o,t,n,r,i,a):G(o,t,n,r,i,a)}if(`additionalProperties`in t){let e=t.additionalProperties;if(e===!0)return new T(`dict`,[new w(`str`),F]);if(B(e)){let t=W(e,n,r,i,`${a}Value`);return new T(`dict`,[new w(`str`),t])}}return new T(`dict`,[new w(`str`),F])}return Array.isArray(e)?ze(e,t,n,r,i,a):F}function Re(e){return Array.isArray(e)?e.length>0:B(e)?Object.keys(e).length>0:!!e}function ze(e,t,n,r,i,a){if(e.includes(`object`)&&`properties`in t){let o=Le(`object`,t,n,r,i,a);return e.includes(`null`)?new E([o,I]):o}let o=e.map(ke),s=o.find(e=>String(e)!==`None`);if(o.length===2&&s!==void 0&&o.some(e=>String(e)===`None`))return new E([s,I]);let[c,...l]=o;return c===void 0?F:l.length>0?new E(o):c}function Be(e,t,n,r,i){let a=e.map(V),o=Ve(a,i),s=[],c=!1;for(let e of a)e.type===`null`?c=!0:s.push(W(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 E(u)}function Ve(e,t){let n=e.filter(e=>e.type===`object`&&`properties`in e&&!He(e)),r=/* @__PURE__ */ new Map;if(n.length<2)return r;let i=n.map(Ue),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 He(e){let t=e.title;return typeof t==`string`&&t!==``&&y(t)}function Ue(e){for(let t of Object.values(H(e))){let e=V(t).const;if(typeof e==`string`&&L(e)!==``)return e}}function We(e,t,n,r,i,a){let o=Ge(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 G(e,t,n,r,i,a){let o=new M(e);r.set(e,o);let s=Ge(e,t,n,r,i,a);return o.fields=s.fields,o.description=s.description,o}function Ge(e,t,n,r,i,a){let o=Me(t),s=/* @__PURE__ */ new Map;for(let[e,c]of Object.entries(H(t))){let t=V(c),l=W(t,n,r,i,a?`${a}.${e}`:e),u=z(t.description);s.set(e,new xe(e,l,o.has(e),u))}return new M(e,z(t.description),s)}function K(e,t){if(e instanceof M)return t.get(e)??e;if(e instanceof T){let n=e.args.map(e=>K(e,t));n.some((t,n)=>t!==e.args[n])&&(e.args=n)}else if(e instanceof E){let n=e.members.map(e=>K(e,t));n.some((t,n)=>t!==e.members[n])&&(e.members=n)}return e}function Ke(e,t,n){let r=/* @__PURE__ */ new Map([[t,n]]);for(let t of e.params.values())t.type=K(t.type,r);e.returnType=K(e.returnType,r);for(let t of e.referencedTypes)for(let e of t.fields.values())e.type=K(e.type,r)}function qe(e,t,n){let r=structuredClone(e),i=Je(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;Ye([r,...Object.values(i)],`#`)&&(c=Qe(r.title,void 0,()=>R(t,n===`return`?`Return`:``)),o.add(c));let l=tt(r,i,n);for(let[e,n]of Object.entries(i))s(e,Qe(q(n)?n.title:void 0,e,()=>R(t,l.get(e)??e)));let u=e=>Y(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 q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Je(e,t){let n={},r=[e.definitions,e.$defs];delete e.definitions,delete e.$defs;for(let e of r)if(q(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 Ye(e,t){return Array.isArray(e)?e.some(e=>Ye(e,t)):q(e)?e.$ref===t||Object.entries(e).some(([e,n])=>!$e.has(e)&&Ye(n,t)):!1}const Xe=/^__schema\d+$/u,Ze=/* @__PURE__ */ new Set([`asyncio`,`Any`,`TypedDict`,`NotRequired`,`Literal`,`str`,`int`,`float`,`bool`,`list`,`dict`,`tuple`]);function J(e){return b(e)&&!Ze.has(e)}function Qe(e,t,n){if(t!==void 0&&J(t)&&!Xe.test(t))return t;if(typeof e==`string`&&J(e))return e;if(t!==void 0&&!Xe.test(t)){let e=L(t);if(J(e))return e}return n()}const $e=/* @__PURE__ */ new Set([`default`,`const`,`enum`,`examples`]),et=/* @__PURE__ */ new Set([`properties`,`patternProperties`,`$defs`,`definitions`]);function tt(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(!q(e))return;let a=e.$ref;if(typeof a==`string`){let e=nt(a);e!==void 0&&Object.hasOwn(t,e)&&!r.has(e)&&(r.set(e,n),i(t[e],n))}let o=e.properties;if(q(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 nt(e){return/^#\/(?:definitions|\$defs)\/([^/]+)$/u.exec(e)?.[1]?.replace(/~1/gu,`/`).replace(/~0/gu,`~`)}function Y(e,t,n,r){if(Array.isArray(e))return e.map(e=>Y(e,t,n,r));if(!q(e))return e;let i={};for(let[a,o]of Object.entries(e))if(et.has(a)&&q(o))i[a]=Object.fromEntries(Object.entries(o).map(([e,i])=>[e,Y(i,t,n,r)]));else if($e.has(a))i[a]=o;else if(a===`$ref`&&typeof o==`string`)i[a]=rt(o,t,n,r);else if(a===`title`&&typeof o==`string`&&!J(o))continue;else i[a]=Y(o,t,n,r);return i}function rt(e,t,n,r){if(e===`#`&&r!==void 0)return`#/$defs/${r}`;let i=nt(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 it=`import asyncio
17
34
  from typing import Any, TypedDict, NotRequired, Literal`,at=new Set(it.split(`
18
- `).flatMap(e=>e.replace(/^(?:from \S+ )?import /u,``).split(`, `)));function ot(e){let{functions:t,toolNames:n}=st(e),r=/* @__PURE__ */ new Map;for(let e of t){let t=e.parametersSchema.properties,n=typeof t==`object`&&t&&!Array.isArray(t)?Object.keys(t):[],i=new Map([...Ie(n)].filter(([e,t])=>t!==e).map(([e,t])=>[t,e]));i.size>0&&r.set(e.name,i)}return{...ct(t),toolNames:n,schemaArgNames:r}}function st(e){let t=[],n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map;for(let[i,a]of Object.entries(e)){let e=lt(i);if(e===`run_code`)throw Error(`Tool "${i}" becomes the Python function "${e}", which code mode reserves for itself. Rename the tool.`);if(at.has(e))throw Error(`Tool "${i}" becomes the Python function "${e}", which the type-check stubs import, so the function would replace that import. Rename the tool.`);let o=r.get(e);if(o!==void 0)throw Error(`Tools "${o}" and "${i}" both become the Python function "${e}". Rename one of them.`);r.set(e,i),e!==i&&n.set(e,i);let s=a.outputSchema===void 0?void 0:ft(i,a);if(s===void 0&&ht(i,a),typeof a.description==`function`)throw Error(`Tool "${i}" has a description that depends on its context, which code mode cannot render yet`);t.push({name:e,description:a.description,parametersSchema:Je(ut(i,a),e,`parameters`),returnSchema:s===void 0?void 0:Je(s,e,`return`)})}return{functions:t,toolNames:n}}function ct(e){let t=e.map(e=>({f:e,sig:N.fromSchema(e.name,e.parametersSchema,e.returnSchema)})),n=t.map(({sig:e})=>e),r=N.getConflictingTypeNames(n),i=N.prefixedTypeNames(n,r),a=N.renderTypeDefinitions(n,r),o=e=>t.map(({f:t,sig:n})=>n.render(e,{name:t.name,description:t.description,isAsync:!0,conflictingTypeNames:r,typeNames:i}));return{typeDefinitions:a,functions:o(`...`),typeCheckStubs:[it,...a,...o(`raise NotImplementedError()`)].join(`
35
+ `).flatMap(e=>e.replace(/^(?:from \S+ )?import /u,``).split(`, `)));function ot(e){let{functions:t,toolNames:n}=st(e),r=/* @__PURE__ */ new Map;for(let e of t){let t=e.parametersSchema.properties,n=typeof t==`object`&&t&&!Array.isArray(t)?Object.keys(t):[],i=new Map([...Fe(n)].filter(([e,t])=>t!==e).map(([e,t])=>[t,e]));i.size>0&&r.set(e.name,i)}return{...ct(t),toolNames:n,schemaArgNames:r}}function st(e){let t=[],n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map;for(let[i,a]of Object.entries(e)){let e=lt(i);if(e===`run_code`)throw Error(`Tool "${i}" becomes the Python function "${e}", which code mode reserves for itself. Rename the tool.`);if(at.has(e))throw Error(`Tool "${i}" becomes the Python function "${e}", which the type-check stubs import, so the function would replace that import. Rename the tool.`);let o=r.get(e);if(o!==void 0)throw Error(`Tools "${o}" and "${i}" both become the Python function "${e}". Rename one of them.`);r.set(e,i),e!==i&&n.set(e,i);let s=a.outputSchema===void 0?void 0:ft(i,a);if(s===void 0&&gt(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:qe(ut(i,a),e,`parameters`),returnSchema:s===void 0?void 0:qe(s,e,`return`)})}return{functions:t,toolNames:n}}function ct(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:[it,...a,...o(`raise NotImplementedError()`)].join(`
19
36
 
20
- `)}}function lt(e){return ve(e)}function ut(e,t){return J(e,d(t.inputSchema).jsonSchema)}function dt(e){let t=(e?.[`~standard`])?.jsonSchema?.output;return typeof t==`function`?t:void 0}function ft(e,t){let n=dt(t.outputSchema);return n===void 0?J(e,d(t.outputSchema).jsonSchema):J(e,n({target:`draft-07`}))}function pt(e){return typeof e.then==`function`}function J(e,t){if(pt(t))throw Promise.resolve(t).catch(()=>void 0),Error(`Tool "${e}" has a schema that converts to JSON Schema asynchronously, which code mode does not support`);return t}const mt=/* @__PURE__ */ new WeakSet;function ht(e,t){mt.has(t)||(mt.add(t),console.warn(`Tool "${e}" has no outputSchema, so code mode shows its return type as Any. Add an outputSchema so that the model knows the shape of its result.`))}var Y=class extends Error{maxBytes;constructor(e){super(`The value is more than ${String(e)} bytes of JSON.`),this.maxBytes=e}};function gt(e,t){let n=t,r=e=>{if(n-=e,n<0)throw new Y(t)},i=e=>{r(2);let t={};for(let[n,i]of e){let e=String(n);r(X(e)+4),Object.defineProperty(t,e,{value:a(i),enumerable:!0,writable:!0,configurable:!0})}return t},a=e=>{if(e instanceof Map)return i(e);if(e instanceof Set||Array.isArray(e)){r(2);let t=[];for(let n of e)r(1),t.push(a(n));return t}if(typeof e==`bigint`){let t=e.toString();return r(t.length),Number.isSafeInteger(Number(e))?Number(e):t}return e instanceof Uint8Array?(r(e.length+2),Buffer.from(e).toString(`latin1`)):typeof e==`string`?(r(X(e)+2),e):typeof e==`object`&&e?i(Object.entries(e)):(r(typeof e==`number`?String(e).length:5),e)};return a(e)}function _t(e){return typeof e==`number`&&!Number.isFinite(e)?Number.isNaN(e)?`nan`:e>0?`inf`:`-inf`:Array.isArray(e)?e.map(_t):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,_t(t)])):e}function vt(e,t){let n=X(e);if(n<=t)return e;let r=Buffer.from(e),i=Math.floor(t/2),a=r.subarray(0,i).toString().replace(/\uFFFD$/u,``),o=r.subarray(n-i).toString().replace(/^\uFFFD/u,``);return`${a}\n... (${String(n-2*i)} of ${String(n)} bytes cut) ...\n${o}`}function X(e){return Buffer.byteLength(e,`utf8`)}function yt(e,t,n){return e>t?` ... (${String(e)} ${n} total)`:``}function Z(e,t=!1){if(typeof e==`string`)return x(e.slice(0,120))+yt(e.length,120,`chars`);if(Array.isArray(e))return t?`[${String(e.length)} items]`:`[${e.slice(0,5).map(e=>Z(e,!0)).join(`, `)}]`+yt(e.length,5,`items`);if(typeof e==`object`&&e){let n=Object.entries(e);return t?`{${String(n.length)} items}`:`{${n.slice(0,5).map(([e,t])=>`${Z(e,!0)}: ${Z(t,!0)}`).join(`, `)}}`+yt(n.length,5,`items`)}return e==null||typeof e==`boolean`||typeof e==`number`?x(e):`<object>`}function bt(e){let t=[],n=0;for(let r of e){let i=r.status===`returned`?`returned ${r.outputPreview??`None`}`:r.status===`denied`?`was denied and did not run`:`did not finish, so it may have applied a partial change`,a=`- ${r.toolName}(${r.inputPreview}) ${i}`;if(n+a.length>2e3){t.push(`- ... and ${String(e.length-t.length)} more not shown`);break}t.push(a),n+=a.length}let r=String(e.length);return`${r} nested tool calls started before execution stopped:\n`+t.join(`
21
- `)+`\nAccount for all ${r} before retrying; repeating a call repeats whatever it already did.`}function xt(e){return new Wt(e)}var St=class{sandboxFailure=!0;#e;constructor(e){this.#e=e}get error(){return this.#e}};function Q(e,t){let n=Error(t);return n.name=e,n}function Ct(e){return e instanceof Error?e.message:String(e)}function wt(e){let t=e;for(let e=0;e<8&&t instanceof Error;e+=1){if(t instanceof i)return t;t=t.cause}}const Tt=2e3;function Et(e){let t=Ct(e);return t.length>Tt?`${t.slice(0,Tt)} ... (${String(t.length)} chars total)`:t}function Dt(e,t,n){let r=t.at(-1),i=typeof r==`object`&&!!r&&Object.getPrototypeOf(r)===null;if(t.length>+!!i)throw Q(`TypeError`,`${e}() does not accept positional arguments; use keyword arguments`);if(!i)return{};try{return gt(r,n)}catch(t){throw t instanceof Y?Q(`ValueError`,kt(e,n)):t}}function Ot(e,t){return t===void 0?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[t.get(e)??e,n]))}function kt(e,t){return`The arguments to ${e}() are more than ${String(t)} bytes of JSON, over the limit for one call.`}function At(){let e=/* @__PURE__ */ new Map;return(t,n)=>{if(!(n instanceof Map||n instanceof Set))return n;let r=e.get(n);return r===void 0&&(r=n instanceof Map?Object.fromEntries([...n].map(([e,t])=>[String(e),t])):[...n],e.set(n,r)),r}}function jt(e){let t=JSON.stringify(e??null,At());if(t===void 0)throw TypeError(`the result, a ${typeof e==`object`?`value whose toJSON() returns undefined`:typeof e}, has no JSON form`);return t}function Mt(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e}async function $(e,t){if(t.aborted)throw e.catch(()=>void 0),t.reason;return new Promise((n,r)=>{let i=()=>{r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})})}async function Nt(e){return e.aborted?`stopped`:new Promise(t=>{e.addEventListener(`abort`,()=>{t(`stopped`)},{once:!0})})}var Pt=class{free;waiting=[];constructor(e){this.free=e}async acquire(e){if(e.throwIfAborted(),this.free>0){--this.free;return}let t=()=>void 0,n=new Promise(e=>{t=e});this.waiting.push(t);try{await $(n,e)}catch(e){let n=this.waiting.indexOf(t);throw n===-1?this.release():this.waiting.splice(n,1),e}}release(){let e=this.waiting.shift();e===void 0?this.free+=1:e()}},Ft=class{text=``;bytes=0;truncated=!1;maxBytes;constructor(e){this.maxBytes=e}write=(e,t)=>{if(this.truncated)return;let n=X(t);if(this.bytes+n<=this.maxBytes){this.text+=t,this.bytes+=n;return}this.text+=Buffer.from(t).subarray(0,this.maxBytes-this.bytes).toString().replace(/�$/u,``),this.truncated=!0};get output(){return this.truncated?`${this.text}\n[printed output cut at ${String(this.maxBytes)} bytes]\n`:this.text}prependTo(e){let t=this.output.replace(/\n+$/u,``);return t===``?e:`[stdout before error]\n${t}\n[/stdout before error]\n${e}`}};function It(e){return String(e.timeout/1e3)}var Lt=class{calls=[];printed;deadline=1/0;callCount=0;budgetExhausted=!1;stopped;controller=new AbortController;timer;id;limits;constructor(e,t){this.id=e,this.limits=t,this.printed=new Ft(t.outputBytes)}start(){this.deadline=Date.now()+this.limits.timeout,this.timer=setTimeout(()=>{this.stop(`deadline`)},this.limits.timeout)}get signal(){return this.controller.signal}stop(e){if(clearTimeout(this.timer),this.stopped!==void 0)return;this.stopped=e;let t=e===`deadline`?`the code passed its ${It(this.limits)}-second time limit`:e===`aborted`?`the agent run was aborted`:e===`closed`?`code mode was closed`:`the code had already finished`;this.controller.abort(Q(`TimeoutError`,`Stopped because ${t}.`))}reason(){return this.stopped}startedCalls(){return this.calls.length===0?``:`\n\n${bt(this.calls)}`}};const Rt=/^suspension limit [0-9]+ exceeded$/u,zt=[`time limit exceeded`,`memory limit exceeded`,`suspension limit `],Bt=`The code ran longer than its time limit and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and make the code do less work per call.`,Vt=`The sandbox session was replaced. Variables, imports and definitions from earlier calls are gone. Recreate any state you need, but do not replay completed side effects.`;function Ht(e){return e.traceback().length===0&&e.display(`msg`).includes(`time limit exceeded`)}function Ut(e){return e.exception.typeName===`MemoryError`&&e.display(`msg`).startsWith(`memory limit exceeded`)}var Wt=class{tools;limits;idleTimeout;pythonNames;schemaArgNames;typeCheckStubs;queue=Promise.resolve();poolPromise;sessionPromise;passedTypeCheck=!1;expired=!1;idleTimer;current;closing;failure;options;traceContext;slots;constructor(t){this.options=t,this.traceContext=e.active();let{tools:n,sandboxes:r,idleTimeout:i=3e5}=t;for(let[e,t]of Object.entries(n)){if(typeof t.execute!=`function`)throw Error(`Tool "${e}" has no execute function, so sandbox code cannot call it. Pass it to generateText as a direct tool instead.`);if(t.needsApproval!==void 0)throw Error(`Tool "${e}" sets needsApproval, which code mode cannot enforce. Use the approval option of codeMode() instead.`);if(t.toModelOutput!==void 0)throw Error(`Tool "${e}" sets toModelOutput, which code mode cannot apply: sandbox code receives the result that execute returns. Return only what the model may see from execute, or pass the tool to generateText as a direct tool.`)}if(r===void 0&&[void 0,``].includes(process.env.LOGFIRE_API_KEY))throw Error("Agent sandboxes require a Logfire API key with the `project:execute_agent_sandboxes` scope. Set the LOGFIRE_API_KEY environment variable, or pass `sandboxes` to codeMode().");if(!(i>0))throw RangeError(`idleTimeout must be a positive number of milliseconds or Infinity, not ${String(i)}.`);this.limits=v(t.limits),this.slots=new Pt(this.limits.concurrentToolCalls),this.idleTimeout=i;let a=ot(n);this.typeCheckStubs=a.typeCheckStubs,this.schemaArgNames=a.schemaArgNames,this.pythonNames=new Map(Object.keys(n).map(e=>[e,e]));for(let[e,t]of a.toolNames)this.pythonNames.set(t,e);for(let[e,t]of this.pythonNames)if(ie(t))throw Error(`Tool "${e}" becomes the Python function "${t}", which is a Python builtin, so sandbox code would call the builtin instead. Rename the tool.`);this.tools={run_code:p({description:le(a.typeDefinitions,a.functions),inputSchema:f({type:`object`,properties:{code:{type:`string`,description:`The Python code to execute in the sandbox.`},restart:{type:`boolean`,description:`Set to true to reset REPL state. When false (default), state is preserved between calls.`}},required:[`code`],additionalProperties:!1},{validate:e=>{let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&(t.restart===void 0||typeof t.restart==`boolean`)?{success:!0,value:{code:t.code,restart:t.restart}}:{success:!1,error:/* @__PURE__ */ TypeError("run_code takes a string `code` and an optional boolean `restart`.")}}}),execute:async(e,t)=>{let n=await this.enqueue(e,t);return n instanceof St?n:{result:n}},toModelOutput:({output:e})=>{if(e instanceof St)throw e.error;if(typeof e==`object`&&e&&Object.keys(e).length===1&&`sandboxFailure`in e&&e.sandboxFailure===!0)return{type:`text`,value:`Agent Sandboxes infrastructure failed. This call did not complete; a developer must fix the sandbox before a new run.`};let t=typeof e==`object`&&e&&!Array.isArray(e)&&Reflect.ownKeys(e).length===1&&Object.hasOwn(e,`result`)?e.result:e;return typeof t==`string`?{type:`text`,value:t}:{type:`json`,value:t}}})}}async close(){return this.closing??=this.shutDown(),this.closing}async closeWhenDone(e){return Promise.resolve(e.finishReason).then(async()=>this.close(),async()=>this.close())}async[Symbol.asyncDispose](){return this.close()}async shutDown(){this.clearIdleTimer(),this.current?.stop(`closed`),await this.queue,await this.releaseSession();let e=this.options.sandboxes===void 0?this.poolPromise:void 0;this.poolPromise=void 0,e!==void 0&&await(await e).close()}async enqueue(e,t){let n=this.queue.then(async()=>this.run(e,t));return this.queue=n.catch(()=>void 0),n}closedError(){return/* @__PURE__ */ Error(`Code mode is closed, so this code did not run.`)}stoppedError(e,t){if(e.stopped===`deadline`)return/* @__PURE__ */ Error(`The code ran longer than its ${It(this.limits)}-second time limit, counting time spent waiting on tools, and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and make the code do less work per call.`+e.startedCalls());let n=e.stopped===`aborted`?`The agent run was aborted`:`Code mode was closed`;return t?/* @__PURE__ */ Error(`${n} while this code ran, so tool calls it had not started were stopped.${e.startedCalls()}`):e.stopped===`aborted`?/* @__PURE__ */ Error(`${n}, so this code did not run.`):this.closedError()}async run({code:e,restart:t},n){if(this.closing!==void 0)throw this.closedError();if(this.failure!==void 0)return this.failure;n.abortSignal?.throwIfAborted();let r=X(e);if(r>this.limits.codeBytes)throw Error(`The code is ${String(r)} bytes, over the ${String(this.limits.codeBytes)}-byte limit for one snippet. Send less code per call; variables and functions from earlier calls are still defined.`);let i=new Lt(n.toolCallId,this.limits);this.current=i;let a=()=>{i.stop(`aborted`)};n.abortSignal?.addEventListener(`abort`,a,{once:!0}),this.clearIdleTimer();let o=this.expired;this.expired=!1;try{return t===!0&&await this.releaseSession(),await this.feed(e,i,n)}catch(e){throw o&&e instanceof Error?/* @__PURE__ */ Error(`${e.message}\n\nThe sandbox session had no run_code call for ${String(this.idleTimeout/1e3)} seconds and was replaced, so variables, imports and definitions from earlier calls are gone.`):e}finally{i.stop(`finished`),n.abortSignal?.removeEventListener(`abort`,a),this.current=void 0,this.startIdleTimer()}}async failSandbox(e){this.failure=new St(e);try{await this.options.onError?.({error:e})}catch{return this.failure}return this.failure}async feed(e,t,n,r=!1){let i;try{i=await this.session(t.signal)}catch(e){if(t.stopped!==void 0)throw this.stoppedError(t,!1);return this.failSandbox(e)}if(t.stopped!==void 0)throw t.stopped===`deadline`&&await this.releaseSession(),this.stoppedError(t,!1);let a,u,d,f=!1,p=!1;r||t.start();let ee=this.options.typeCheck===`off`||this.options.typeCheck!==`every-snippet`&&this.passedTypeCheck,m=i.feedRun(e,{externalLookup:this.externalLookup(t,n),printCallback:t.printed.write,os:this.osCallback(t),skipTypeCheck:ee}).then(e=>({ok:!0,result:e}),e=>({ok:!1,error:e})),h=await Promise.race([m,Nt(t.signal)]);h===`stopped`?(p=!0,this.abandonSession(i,m)):h.ok?(a=h.result,f=!0,this.passedTypeCheck=!0):(u=h.error,d=wt(u),this.passedTypeCheck||=!(d instanceof l||d instanceof c));let g=t.reason();if(g===`closed`||g===`aborted`)throw this.stoppedError(t,!0);if(g===`deadline`){p||await this.releaseSession();let e=d instanceof o?`Runtime error:\n${t.printed.prependTo(this.cut(d.display(`traceback`)))}\n\n`:``;throw Error(e+this.stoppedError(t,!0).message)}if(!f){if(d instanceof s&&!r&&t.callCount===0)return await this.releaseSession(),t.printed=new Ft(this.limits.outputBytes),this.feed(e,t,n,!0);t.stop(`finished`);let i=this.describeFailure(d,t);if((i===void 0||i.reset)&&await this.releaseSession(),i===void 0)return this.failSandbox(u);throw Error(i.message+(r?`\n\n${Vt}`:``),{cause:u})}let _=this.shapeResult(a,t,r);return r?{result:_,sessionReset:Vt}:_}shapeResult(e,t,n){let{outputBytes:r}=this.limits,i=/* @__PURE__ */ Error(`The result is more than ${String(r)} bytes of JSON, over the limit for what one snippet returns. The code ran and its variables are still defined, so return a smaller value from them, such as a summary or fewer fields.`+(n?`\n\n${Vt}`:``)),a;try{a=_t(gt(e,r))}catch(e){throw e instanceof Y?i:e}if(X(JSON.stringify(a??null))>r)throw i;let o=t.printed.output;return o===``?a??{}:a==null?{output:o}:{output:o,result:a}}cut(e){return vt(e,this.limits.outputBytes)}describeFailure(e,t){let{printed:i}=t;if(e instanceof c)return{message:`Syntax error in code:\n${i.prependTo(this.cut(e.display(`traceback`)))}`,reset:!1};if(e instanceof l)return{message:`Type error in code:\n${i.prependTo(this.cut(e.display()))}`,reset:!1};if(e instanceof o){let n=`Runtime error:\n${i.prependTo(this.cut(e.display(`traceback`)))}`,r=e.display(`msg`);(t.budgetExhausted||zt.some(e=>r.includes(e)))&&(n+=t.startedCalls());let a=Ht(e),o=Ut(e);a&&(n+=`\n\n${Bt}`),o&&(n+=`
37
+ `)}}function lt(e){return ye(e)}function ut(e,t){return mt(e,d(t.inputSchema).jsonSchema)}function dt(e){let t=(e?.[`~standard`])?.jsonSchema?.output;return typeof t==`function`?t:void 0}function ft(e,t){let n=dt(t.outputSchema);return n===void 0?mt(e,d(t.outputSchema).jsonSchema):mt(e,n({target:`draft-07`}))}function pt(e){return typeof e.then==`function`}function mt(e,t){if(pt(t))throw Promise.resolve(t).catch(()=>void 0),Error(`Tool "${e}" has a schema that converts to JSON Schema asynchronously, which code mode does not support`);return t}const ht=/* @__PURE__ */ new WeakSet;function gt(e,t){ht.has(t)||(ht.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 _t=class extends Error{maxBytes;constructor(e){super(`The value is more than ${String(e)} bytes of JSON.`),this.maxBytes=e}};function vt(e,t){let n=t,r=e=>{if(n-=e,n<0)throw new _t(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 yt(e){return typeof e==`number`&&!Number.isFinite(e)?Number.isNaN(e)?`nan`:e>0?`inf`:`-inf`:Array.isArray(e)?e.map(yt):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,yt(t)])):e}function bt(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 xt(e,t,n){return e>t?` ... (${String(e)} ${n} total)`:``}function Z(e,t=!1){if(typeof e==`string`)return x(e.slice(0,120))+xt(e.length,120,`chars`);if(Array.isArray(e))return t?`[${String(e.length)} items]`:`[${e.slice(0,5).map(e=>Z(e,!0)).join(`, `)}]`+xt(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(`, `)}}`+xt(n.length,5,`items`)}return e==null||typeof e==`boolean`||typeof e==`number`?x(e):`<object>`}function St(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(`
38
+ `)+`\nAccount for all ${r} before retrying; repeating a call repeats whatever it already did.`}function Ct(e){return new qt(e)}var wt=class{sandboxFailure=!0;#e;constructor(e){this.#e=e}get error(){return this.#e}};function Q(e,t){let n=Error(t);return n.name=e,n}function Tt(e){return e instanceof Error?e.message:String(e)}function Et(e){let t=e;for(let e=0;e<8&&t instanceof Error;e+=1){if(t instanceof i)return t;t=t.cause}}const Dt=2e3;function Ot(e){let t=Tt(e);return t.length>Dt?`${t.slice(0,Dt)} ... (${String(t.length)} chars total)`:t}function kt(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 vt(r,n)}catch(t){throw t instanceof _t?Q(`ValueError`,jt(e,n)):t}}function At(e,t){return t===void 0?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[t.get(e)??e,n]))}function jt(e,t){return`The arguments to ${e}() are more than ${String(t)} bytes of JSON, over the limit for one call.`}function Mt(){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 Nt(e){let t=JSON.stringify(e??null,Mt());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 Pt(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 Ft(e){return e.aborted?`stopped`:new Promise(t=>{e.addEventListener(`abort`,()=>{t(`stopped`)},{once:!0})})}var It=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()}},Lt=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 Rt(e){return String(e.timeout/1e3)}var zt=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 Lt(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 ${Rt(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${St(this.calls)}`}};const Bt={datetime:`call_host`,sleep:`call_host`,randomStart:`call_host`},Vt=/^suspension limit [0-9]+ exceeded$/u,Ht=[`time limit exceeded`,`memory limit exceeded`,`suspension limit `],Ut=`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.`,Wt=`The sandbox session was replaced. Variables, imports and definitions from earlier calls are gone. Recreate any state you need, but do not replay completed side effects.`;function Gt(e){return e.traceback().length===0&&e.display(`msg`).includes(`time limit exceeded`)}function Kt(e){return e.exception.typeName===`MemoryError`&&e.display(`msg`).startsWith(`memory limit exceeded`)}var qt=class{tools;limits;idleTimeout;pythonNames;schemaArgNames;typeCheckStubs;osPolicy;queue=Promise.resolve();poolPromise;sessionPromise;passedTypeCheck=!1;expired=!1;idleTimer;current;closing;failure;options;traceContext;slots;constructor(t){this.options=t,this.traceContext=e.active();let{tools:n,sandboxes:r,idleTimeout:i=3e5}=t;for(let[e,t]of Object.entries(n)){if(typeof t.execute!=`function`)throw Error(`Tool "${e}" has no execute function, so sandbox code cannot call it. Pass it to generateText as a direct tool instead.`);if(t.needsApproval!==void 0)throw Error(`Tool "${e}" sets needsApproval, which code mode cannot enforce. Use the approval option of codeMode() instead.`);if(t.toModelOutput!==void 0)throw Error(`Tool "${e}" sets toModelOutput, which code mode cannot apply: sandbox code receives the result that execute returns. Return only what the model may see from execute, or pass the tool to generateText as a direct tool.`)}if(r===void 0&&[void 0,``].includes(process.env.LOGFIRE_API_KEY))throw Error("Agent sandboxes require a Logfire API key with the `project:execute_agent_sandboxes` scope. Set the LOGFIRE_API_KEY environment variable, or pass `sandboxes` to codeMode().");if(!(i>0))throw RangeError(`idleTimeout must be a positive number of milliseconds or Infinity, not ${String(i)}.`);this.limits=v(t.limits),this.osPolicy={...Bt,...t.osPolicy},this.slots=new It(this.limits.concurrentToolCalls),this.idleTimeout=i;let a=ot(n);this.typeCheckStubs=a.typeCheckStubs,this.schemaArgNames=a.schemaArgNames,this.pythonNames=new Map(Object.keys(n).map(e=>[e,e]));for(let[e,t]of a.toolNames)this.pythonNames.set(t,e);for(let[e,t]of this.pythonNames)if(ie(t))throw Error(`Tool "${e}" becomes the Python function "${t}", which is a Python builtin, so sandbox code would call the builtin instead. Rename the tool.`);this.tools={run_code:p({description:de(a.typeDefinitions,a.functions,ue(this.osPolicy)),inputSchema:f({type:`object`,properties:{code:{type:`string`,description:`The Python code to execute in the sandbox.`},restart:{type:`boolean`,description:`Set to true to reset REPL state. When false (default), state is preserved between calls.`}},required:[`code`],additionalProperties:!1},{validate:e=>{let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&(t.restart===void 0||typeof t.restart==`boolean`)?{success:!0,value:{code:t.code,restart:t.restart}}:{success:!1,error:/* @__PURE__ */ TypeError("run_code takes a string `code` and an optional boolean `restart`.")}}}),execute:async(e,t)=>{let n=await this.enqueue(e,t);return n instanceof wt?n:{result:n}},toModelOutput:({output:e})=>{if(e instanceof wt)throw e.error;if(typeof e==`object`&&e&&Object.keys(e).length===1&&`sandboxFailure`in e&&e.sandboxFailure===!0)return{type:`text`,value:`Agent Sandboxes infrastructure failed. This call did not complete; a developer must fix the sandbox before a new run.`};let t=typeof e==`object`&&e&&!Array.isArray(e)&&Reflect.ownKeys(e).length===1&&Object.hasOwn(e,`result`)?e.result:e;return typeof t==`string`?{type:`text`,value:t}:{type:`json`,value:t}}})}}async close(){return this.closing??=this.shutDown(),this.closing}async closeWhenDone(e){return Promise.resolve(e.finishReason).then(async()=>this.close(),async()=>this.close())}async[Symbol.asyncDispose](){return this.close()}async shutDown(){this.clearIdleTimer(),this.current?.stop(`closed`),await this.queue,await this.releaseSession();let e=this.options.sandboxes===void 0?this.poolPromise:void 0;this.poolPromise=void 0,e!==void 0&&await(await e).close()}async enqueue(e,t){let n=this.queue.then(async()=>this.run(e,t));return this.queue=n.catch(()=>void 0),n}closedError(){return/* @__PURE__ */ Error(`Code mode is closed, so this code did not run.`)}stoppedError(e,t){if(e.stopped===`deadline`)return/* @__PURE__ */ Error(`The code ran longer than its ${Rt(this.limits)}-second time limit, counting time spent waiting on tools, and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and make the code do less work per call.`+e.startedCalls());let n=e.stopped===`aborted`?`The agent run was aborted`:`Code mode was closed`;return t?/* @__PURE__ */ Error(`${n} while this code ran, so tool calls it had not started were stopped.${e.startedCalls()}`):e.stopped===`aborted`?/* @__PURE__ */ Error(`${n}, so this code did not run.`):this.closedError()}async run({code:e,restart:t},n){if(this.closing!==void 0)throw this.closedError();if(this.failure!==void 0)return this.failure;n.abortSignal?.throwIfAborted();let r=X(e);if(r>this.limits.codeBytes)throw Error(`The code is ${String(r)} bytes, over the ${String(this.limits.codeBytes)}-byte limit for one snippet. Send less code per call; variables and functions from earlier calls are still defined.`);let i=new zt(n.toolCallId,this.limits);this.current=i;let a=()=>{i.stop(`aborted`)};n.abortSignal?.addEventListener(`abort`,a,{once:!0}),this.clearIdleTimer();let o=this.expired;this.expired=!1;try{return t===!0&&await this.releaseSession(),await this.feed(e,i,n)}catch(e){throw o&&e instanceof Error?/* @__PURE__ */ Error(`${e.message}\n\nThe sandbox session had no run_code call for ${String(this.idleTimeout/1e3)} seconds and was replaced, so variables, imports and definitions from earlier calls are gone.`):e}finally{i.stop(`finished`),n.abortSignal?.removeEventListener(`abort`,a),this.current=void 0,this.startIdleTimer()}}async failSandbox(e){this.failure=new wt(e);try{await this.options.onError?.({error:e})}catch{return this.failure}return this.failure}async feed(e,t,n,r=!1){let i;try{i=await this.session(t.signal)}catch(e){if(t.stopped!==void 0)throw this.stoppedError(t,!1);return this.failSandbox(e)}if(t.stopped!==void 0)throw t.stopped===`deadline`&&await this.releaseSession(),this.stoppedError(t,!1);let a,u,d,f=!1,p=!1;r||t.start();let ee=this.options.typeCheck===`off`||this.options.typeCheck!==`every-snippet`&&this.passedTypeCheck,m=i.feedRun(e,{externalLookup:this.externalLookup(t,n),printCallback:t.printed.write,os:this.osCallback(t),skipTypeCheck:ee}).then(e=>({ok:!0,result:e}),e=>({ok:!1,error:e})),h=await Promise.race([m,Ft(t.signal)]);h===`stopped`?(p=!0,this.abandonSession(i,m)):h.ok?(a=h.result,f=!0,this.passedTypeCheck=!0):(u=h.error,d=Et(u),this.passedTypeCheck||=!(d instanceof l||d instanceof c));let g=t.reason();if(g===`closed`||g===`aborted`)throw this.stoppedError(t,!0);if(g===`deadline`){p||await this.releaseSession();let e=d instanceof o?`Runtime error:\n${t.printed.prependTo(this.cut(d.display(`traceback`)))}\n\n`:``;throw Error(e+this.stoppedError(t,!0).message)}if(!f){if(d instanceof s&&!r&&t.callCount===0)return await this.releaseSession(),t.printed=new Lt(this.limits.outputBytes),this.feed(e,t,n,!0);t.stop(`finished`);let i=this.describeFailure(d,t);if((i===void 0||i.reset)&&await this.releaseSession(),i===void 0)return this.failSandbox(u);throw Error(i.message+(r?`\n\n${Wt}`:``),{cause:u})}let _=this.shapeResult(a,t,r);return r?{result:_,sessionReset:Wt}:_}shapeResult(e,t,n){let{outputBytes:r}=this.limits,i=/* @__PURE__ */ Error(`The result is more than ${String(r)} bytes of JSON, over the limit for what one snippet returns. The code ran and its variables are still defined, so return a smaller value from them, such as a summary or fewer fields.`+(n?`\n\n${Wt}`:``)),a;try{a=yt(vt(e,r))}catch(e){throw e instanceof _t?i:e}if(X(JSON.stringify(a??null))>r)throw i;let o=t.printed.output;return o===``?a??{}:a==null?{output:o}:{output:o,result:a}}cut(e){return bt(e,this.limits.outputBytes)}describeFailure(e,t){let{printed:i}=t;if(e instanceof c)return{message:`Syntax error in code:\n${i.prependTo(this.cut(e.display(`traceback`)))}`,reset:!1};if(e instanceof l)return{message:`Type error in code:\n${i.prependTo(this.cut(e.display()))}`,reset:!1};if(e instanceof o){let n=`Runtime error:\n${i.prependTo(this.cut(e.display(`traceback`)))}`,r=e.display(`msg`);(t.budgetExhausted||Ht.some(e=>r.includes(e)))&&(n+=t.startedCalls());let a=Gt(e),o=Kt(e);a&&(n+=`\n\n${Ut}`),o&&(n+=`
22
39
 
23
- The code ran out of memory and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and keep less data in memory at once.`);let s=a||o;return e.exception.typeName===`RuntimeError`&&Rt.test(r)&&(n+=`
40
+ 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`&&Vt.test(r)&&(n+=`
24
41
 
25
- 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&&e.timedOut||e instanceof r&&e.cause===`turn_timeout`)return{message:Bt+t.startedCalls(),reset:!0};if(e instanceof r)return{message:(e.cause===`session_timeout`||e.cause===`idle_timeout`?`The sandbox session ended and its state is lost. Re-run any imports and recreate any state you need. `:`The sandbox session ended unexpectedly and its state was lost. Recreate any state you need. `)+`Check any tool calls already started before continuing, and do not replay completed side effects.`+t.startedCalls(),reset:!0};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}}osCallback(e){return async(t,n)=>{if(t!==`time.sleep`&&t!==`asyncio.sleep`)return u;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 ${It(this.limits)}s this code may run; ${i.toFixed(1)}s left`);return await $(m(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 s=`${r.id}__${String(r.callCount)}`,c=Ot(Dt(t,n,a.toolInputBytes),this.schemaArgNames.get(t));if(X(JSON.stringify(c))>a.toolInputBytes)throw Q(`ValueError`,kt(t,a.toolInputBytes));let l=await $(Promise.resolve(d(o.inputSchema).validate?.(c)),r.signal);if(l!==void 0&&!l.success)throw Q(`ValueError`,`Invalid arguments for ${t}(): ${Et(l.error)}`);let u=l===void 0?c:l.value,f=this.options.context,p=f!==void 0&&Object.hasOwn(f,e)?f[e]:void 0;if(o.contextSchema!==void 0){let t=await $(Promise.resolve(d(o.contextSchema).validate?.(p)),r.signal);if(t!==void 0&&!t.success)throw Q(`ValueError`,`Invalid context for tool "${e}": ${Et(t.error)}`);p=t===void 0?p:t.value}let m={toolName:e,inputPreview:Z(u),status:`running`},g=await $(h(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:p,tool:o}),r.signal);if(!g.approved){m.status=`denied`,r.calls.push(m);let t=g.reason===void 0?``:` ${g.reason}`;throw Q(`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())},te={};r.calls.push(m);try{return await ee.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:p,abortSignal:r.signal});te.running=e,e.then(v,v),n=await $(e,r.signal)}catch(t){throw m.status=`failed`,r.stopped===void 0?this.replaceToolError(t,{toolName:e,toolCallId:s,input:u}):t}m.status=`returned`;let c;try{c=jt(n)}catch(e){let n=e instanceof RangeError?`it is nested too deeply or contains itself`:Ct(e);throw m.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(c);if(l>a.toolOutputBytes)throw m.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 d=JSON.parse(c);return m.outputPreview=Z(d),d})}finally{te.running===void 0&&v()}}async execute(e,t,n){let r=e.execute,i=r(t,n);if(Mt(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(e){this.sessionPromise??=this.checkout(e);try{return await this.sessionPromise}catch(e){throw this.sessionPromise=void 0,e}}async checkout(t){let n=this.options.typeCheck!==`off`;return e.with(this.traceContext,async()=>{t.throwIfAborted();let e=await this.pool();t.throwIfAborted();let r={ephemeral:!0,scriptName:`run_code.py`,typeCheck:n,...n?{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`}};try{return await e.checkout(r)}catch(n){let i=wt(n);if(!(i instanceof a)||i.statusCode===`UNAUTHENTICATED`||i.statusCode===`PERMISSION_DENIED`||![`caller_cap`,`capacity`,`worker_unavailable`].some(e=>e===i.cause))throw n;return await m(100,void 0,{signal:t}),t.throwIfAborted(),e.checkout(r)}})}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{xt as codeMode};
42
+ 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&&e.timedOut||e instanceof r&&e.cause===`turn_timeout`)return{message:Ut+t.startedCalls(),reset:!0};if(e instanceof r)return{message:(e.cause===`session_timeout`||e.cause===`idle_timeout`?`The sandbox session ended and its state is lost. Re-run any imports and recreate any state you need. `:`The sandbox session ended unexpectedly and its state was lost. Recreate any state you need. `)+`Check any tool calls already started before continuing, and do not replay completed side effects.`+t.startedCalls(),reset:!0};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}}osCallback(e){return async(t,n)=>{if(t!==`time.sleep`&&t!==`asyncio.sleep`)return u;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 ${Rt(this.limits)}s this code may run; ${i.toFixed(1)}s left`);return await $(m(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 s=`${r.id}__${String(r.callCount)}`,c=At(kt(t,n,a.toolInputBytes),this.schemaArgNames.get(t));if(X(JSON.stringify(c))>a.toolInputBytes)throw Q(`ValueError`,jt(t,a.toolInputBytes));let l=await $(Promise.resolve(d(o.inputSchema).validate?.(c)),r.signal);if(l!==void 0&&!l.success)throw Q(`ValueError`,`Invalid arguments for ${t}(): ${Ot(l.error)}`);let u=l===void 0?c:l.value,f=this.options.context,p=f!==void 0&&Object.hasOwn(f,e)?f[e]:void 0;if(o.contextSchema!==void 0){let t=await $(Promise.resolve(d(o.contextSchema).validate?.(p)),r.signal);if(t!==void 0&&!t.success)throw Q(`ValueError`,`Invalid context for tool "${e}": ${Ot(t.error)}`);p=t===void 0?p:t.value}let m={toolName:e,inputPreview:Z(u),status:`running`},g=await $(h(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:p,tool:o}),r.signal);if(!g.approved){m.status=`denied`,r.calls.push(m);let t=g.reason===void 0?``:` ${g.reason}`;throw Q(`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())},te={};r.calls.push(m);try{return await ee.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:p,abortSignal:r.signal});te.running=e,e.then(v,v),n=await $(e,r.signal)}catch(t){throw m.status=`failed`,r.stopped===void 0?this.replaceToolError(t,{toolName:e,toolCallId:s,input:u}):t}m.status=`returned`;let c;try{c=Nt(n)}catch(e){let n=e instanceof RangeError?`it is nested too deeply or contains itself`:Tt(e);throw m.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(c);if(l>a.toolOutputBytes)throw m.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 d=JSON.parse(c);return m.outputPreview=Z(d),d})}finally{te.running===void 0&&v()}}async execute(e,t,n){let r=e.execute,i=r(t,n);if(Pt(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(e){this.sessionPromise??=this.checkout(e);try{return await this.sessionPromise}catch(e){throw this.sessionPromise=void 0,e}}async checkout(t){let n=this.options.typeCheck!==`off`;return e.with(this.traceContext,async()=>{t.throwIfAborted();let e=await this.pool();t.throwIfAborted();let r={ephemeral:!0,scriptName:`run_code.py`,typeCheck:n,...n?{typeCheckStubs:this.typeCheckStubs}:{},limits:{maxFeedDurationSecs:this.limits.timeout/1e3,maxMemory:this.limits.memory,maxSuspensions:this.limits.suspensions,...this.osPolicy.sleep===`system`?{maxTotalSleepSecs:this.limits.timeout/1e3}:{}},osPolicy:this.osPolicy};try{return await e.checkout(r)}catch(n){let i=Et(n);if(!(i instanceof a)||i.statusCode===`UNAUTHENTICATED`||i.statusCode===`PERMISSION_DENIED`||![`caller_cap`,`capacity`,`worker_unavailable`].some(e=>e===i.cause))throw n;return await m(100,void 0,{signal:t}),t.throwIfAborted(),e.checkout(r)}})}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{Ct as codeMode};
package/package.json CHANGED
@@ -25,7 +25,7 @@
25
25
  "code-mode",
26
26
  "python"
27
27
  ],
28
- "version": "0.1.5",
28
+ "version": "0.2.1",
29
29
  "type": "module",
30
30
  "main": "./dist/index.cjs",
31
31
  "module": "./dist/index.js",
@@ -43,8 +43,8 @@
43
43
  }
44
44
  },
45
45
  "dependencies": {
46
- "@pydantic/logfire-agent-sandboxes": "0.2.3",
47
- "logfire": "0.26.1"
46
+ "@pydantic/logfire-agent-sandboxes": "0.2.4",
47
+ "logfire": "0.26.2"
48
48
  },
49
49
  "peerDependencies": {
50
50
  "@opentelemetry/api": ">=1.9.1 <1.10.0",