@pydantic/logfire-ai-sdk-code-mode 0.1.2 → 0.1.3
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/README.md +3 -0
- package/dist/index.cjs +15 -18
- package/dist/index.d.cts +10 -2
- package/dist/index.d.ts +10 -2
- package/dist/index.js +16 -19
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -43,3 +43,6 @@ call in that run.
|
|
|
43
43
|
|
|
44
44
|
See the [Agent Sandboxes docs](https://github.com/pydantic/logfire-js/blob/main/docs/agent-sandboxes.md#use-with-the-vercel-ai-sdk)
|
|
45
45
|
for streaming, approval, tool context, limits, and error handling.
|
|
46
|
+
|
|
47
|
+
Agent Sandboxes setup and checkout errors end the run instead of reaching the model.
|
|
48
|
+
Use `codeMode`'s `onError` handler for developer-side reporting, and handle thrown errors or rejected streams.
|
package/dist/index.cjs
CHANGED
|
@@ -1,28 +1,25 @@
|
|
|
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
|
|
2
|
-
`)n+=`\\n`;else if(r===`\r`)n+=`\\r`;else if(r!==` `&&
|
|
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(`
|
|
3
3
|
|
|
4
4
|
`)+"\n```"),n.push("```python\n"+t.join(`
|
|
5
5
|
|
|
6
|
-
`)+"\n```"),`${
|
|
6
|
+
`)+"\n```"),`${ie}\n\n${n.join(`
|
|
7
7
|
|
|
8
|
-
`)}`}let
|
|
9
|
-
`)}};function
|
|
10
|
-
`)}var
|
|
11
|
-
`)}renderFunctionalDefinition(){let e=A(this.description)?
|
|
12
|
-
`)}structurallyEqual(e){return
|
|
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(`
|
|
13
13
|
`));let u=c.join(`
|
|
14
14
|
|
|
15
|
-
`);return u!==``&&s.push(...
|
|
16
|
-
`)}static fromSchema(t,n,r){let i=
|
|
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
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:
|
|
18
|
+
`).flatMap(e=>e.replace(/^(?:from \S+ )?import /u,``).split(`, `)));function rt(e){let{functions:t,toolNames:n}=it(e),r=/* @__PURE__ */ new Map;for(let e of t){let t=e.parametersSchema.properties,n=typeof t==`object`&&t&&!Array.isArray(t)?Object.keys(t):[],i=new Map([...Me(n)].filter(([e,t])=>t!==e).map(([e,t])=>[t,e]));i.size>0&&r.set(e.name,i)}return{...at(t),toolNames:n,schemaArgNames:r}}function it(e){let t=[],n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map;for(let[i,a]of Object.entries(e)){let e=ot(i);if(e===`run_code`)throw Error(`Tool "${i}" becomes the Python function "${e}", which code mode reserves for itself. Rename the tool.`);if(nt.has(e))throw Error(`Tool "${i}" becomes the Python function "${e}", which the type-check stubs import, so the function would replace that import. Rename the tool.`);let o=r.get(e);if(o!==void 0)throw Error(`Tools "${o}" and "${i}" both become the Python function "${e}". Rename one of them.`);r.set(e,i),e!==i&&n.set(e,i);let s=a.outputSchema===void 0?void 0:lt(i,a);if(s===void 0&&pt(i,a),typeof a.description==`function`)throw Error(`Tool "${i}" has a description that depends on its context, which code mode cannot render yet`);t.push({name:e,description:a.description,parametersSchema:We(st(i,a),e,`parameters`),returnSchema:s===void 0?void 0:We(s,e,`return`)})}return{functions:t,toolNames:n}}function at(e){let t=e.map(e=>({f:e,sig:N.fromSchema(e.name,e.parametersSchema,e.returnSchema)})),n=t.map(({sig:e})=>e),r=N.getConflictingTypeNames(n),i=N.prefixedTypeNames(n,r),a=N.renderTypeDefinitions(n,r),o=e=>t.map(({f:t,sig:n})=>n.render(e,{name:t.name,description:t.description,isAsync:!0,conflictingTypeNames:r,typeNames:i}));return{typeDefinitions:a,functions:o(`...`),typeCheckStubs:[tt,...a,...o(`raise NotImplementedError()`)].join(`
|
|
19
19
|
|
|
20
|
-
`)}}function ot(e){return
|
|
21
|
-
`)+`\nAccount for all ${r} before retrying; repeating a call repeats whatever it already did.`}function bt(e){return new Rt(e)}function Z(e,t){let n=Error(t);return n.name=e,n}function xt(e){return e instanceof Error?e.message:String(e)}const St=2e3;function Ct(e){let t=xt(e);return t.length>St?`${t.slice(0,St)} ... (${String(t.length)} chars total)`:t}function wt(e,t,n){let r=t.at(-1),i=typeof r==`object`&&!!r&&Object.getPrototypeOf(r)===null;if(t.length>+!!i)throw Z(`TypeError`,`${e}() does not accept positional arguments; use keyword arguments`);if(!i)return{};try{return ht(r,n)}catch(t){throw t instanceof mt?Z(`ValueError`,Et(e,n)):t}}function Tt(e,t){return t===void 0?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[t.get(e)??e,n]))}function Et(e,t){return`The arguments to ${e}() are more than ${String(t)} bytes of JSON, over the limit for one call.`}function Dt(){let e=/* @__PURE__ */ new Map;return(t,n)=>{if(!(n instanceof Map||n instanceof Set))return n;let r=e.get(n);return r===void 0&&(r=n instanceof Map?Object.fromEntries([...n].map(([e,t])=>[String(e),t])):[...n],e.set(n,r)),r}}function Ot(e){let t=JSON.stringify(e??null,Dt());if(t===void 0)throw TypeError(`the result, a ${typeof e==`object`?`value whose toJSON() returns undefined`:typeof e}, has no JSON form`);return t}function kt(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e}async function Q(e,t){if(t.aborted)throw e.catch(()=>void 0),t.reason;return new Promise((n,r)=>{let i=()=>{r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})})}async function At(e){return e.aborted?`stopped`:new Promise(t=>{e.addEventListener(`abort`,()=>{t(`stopped`)},{once:!0})})}var jt=class{free;waiting=[];constructor(e){this.free=e}async acquire(e){if(e.throwIfAborted(),this.free>0){--this.free;return}let t=()=>void 0,n=new Promise(e=>{t=e});this.waiting.push(t);try{await Q(n,e)}catch(e){let n=this.waiting.indexOf(t);throw n===-1?this.release():this.waiting.splice(n,1),e}}release(){let e=this.waiting.shift();e===void 0?this.free+=1:e()}},Mt=class{text=``;bytes=0;truncated=!1;maxBytes;constructor(e){this.maxBytes=e}write=(e,t)=>{if(this.truncated)return;let n=Y(t);if(this.bytes+n<=this.maxBytes){this.text+=t,this.bytes+=n;return}this.text+=Buffer.from(t).subarray(0,this.maxBytes-this.bytes).toString().replace(/�$/u,``),this.truncated=!0};get output(){return this.truncated?`${this.text}\n[printed output cut at ${String(this.maxBytes)} bytes]\n`:this.text}prependTo(e){let t=this.output.replace(/\n+$/u,``);return t===``?e:`[stdout before error]\n${t}\n[/stdout before error]\n${e}`}};function $(e){return String(e.timeout/1e3)}var Nt=class{calls=[];printed;deadline=1/0;callCount=0;budgetExhausted=!1;stopped;controller=new AbortController;timer;id;limits;constructor(e,t){this.id=e,this.limits=t,this.printed=new Mt(t.outputBytes)}start(){this.deadline=Date.now()+this.limits.timeout,this.timer=setTimeout(()=>{this.stop(`deadline`)},this.limits.timeout)}get signal(){return this.controller.signal}stop(e){if(clearTimeout(this.timer),this.stopped!==void 0)return;this.stopped=e;let t=e===`deadline`?`the code passed its ${$(this.limits)}-second time limit`:e===`aborted`?`the agent run was aborted`:e===`closed`?`code mode was closed`:`the code had already finished`;this.controller.abort(Z(`TimeoutError`,`Stopped because ${t}.`))}reason(){return this.stopped}startedCalls(){return this.calls.length===0?``:`\n\n${yt(this.calls)}`}};const Pt=/^suspension limit [0-9]+ exceeded$/u,Ft=[`time limit exceeded`,`memory limit exceeded`,`suspension limit `];function It(e){return e.traceback().length===0&&e.display(`msg`).includes(`time limit exceeded`)}function Lt(e){return e.exception.typeName===`MemoryError`&&e.display(`msg`).startsWith(`memory limit exceeded`)}var Rt=class{tools;limits;idleTimeout;pythonNames;schemaArgNames;typeCheckStubs;queue=Promise.resolve();poolPromise;sessionPromise;passedTypeCheck=!1;expired=!1;idleTimer;current;closing;options;traceContext;slots;constructor(e){this.options=e,this.traceContext=c.context.active();let{tools:t,sandboxes:n,idleTimeout:r=3e5}=e;for(let[e,n]of Object.entries(t)){if(typeof n.execute!=`function`)throw Error(`Tool "${e}" has no execute function, so sandbox code cannot call it. Pass it to generateText as a direct tool instead.`);if(n.needsApproval!==void 0)throw Error(`Tool "${e}" sets needsApproval, which code mode cannot enforce. Use the approval option of codeMode() instead.`);if(n.toModelOutput!==void 0)throw Error(`Tool "${e}" sets toModelOutput, which code mode cannot apply: sandbox code receives the result that execute returns. Return only what the model may see from execute, or pass the tool to generateText as a direct tool.`)}if(n===void 0&&[void 0,``].includes(process.env.LOGFIRE_API_KEY))throw Error("Agent sandboxes require a Logfire API key with the `project:execute_agent_sandboxes` scope. Set the LOGFIRE_API_KEY environment variable, or pass `sandboxes` to codeMode().");if(!(r>0))throw RangeError(`idleTimeout must be a positive number of milliseconds or Infinity, not ${String(r)}.`);this.limits=g(e.limits),this.slots=new jt(this.limits.concurrentToolCalls),this.idleTimeout=r;let i=rt(t);this.typeCheckStubs=i.typeCheckStubs,this.schemaArgNames=i.schemaArgNames,this.pythonNames=new Map(Object.keys(t).map(e=>[e,e]));for(let[e,t]of i.toolNames)this.pythonNames.set(t,e);for(let[e,t]of this.pythonNames)if(te(t))throw Error(`Tool "${e}" becomes the Python function "${t}", which is a Python builtin, so sandbox code would call the builtin instead. Rename the tool.`);this.tools={run_code:(0,d.tool)({description:oe(i.typeDefinitions,i.functions),inputSchema:(0,d.jsonSchema)({type:`object`,properties:{code:{type:`string`,description:`The Python code to execute in the sandbox.`},restart:{type:`boolean`,description:`Set to true to reset REPL state. When false (default), state is preserved between calls.`}},required:[`code`],additionalProperties:!1},{validate:e=>{let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&(t.restart===void 0||typeof t.restart==`boolean`)?{success:!0,value:{code:t.code,restart:t.restart}}:{success:!1,error:/* @__PURE__ */ TypeError("run_code takes a string `code` and an optional boolean `restart`.")}}}),execute:async(e,t)=>this.enqueue(e,t)})}}async close(){return this.closing??=this.shutDown(),this.closing}async closeWhenDone(e){return Promise.resolve(e.finishReason).then(async()=>this.close(),async()=>this.close())}async[Symbol.asyncDispose](){return this.close()}async shutDown(){this.clearIdleTimer(),this.current?.stop(`closed`),await this.queue,await this.releaseSession();let e=this.options.sandboxes===void 0?this.poolPromise:void 0;this.poolPromise=void 0,e!==void 0&&await(await e).close()}async enqueue(e,t){let n=this.queue.then(async()=>this.run(e,t));return this.queue=n.catch(()=>void 0),n}closedError(){return/* @__PURE__ */ Error(`Code mode is closed, so this code did not run.`)}stoppedError(e,t){let n=e.stopped===`aborted`?`The agent run was aborted`:`Code mode was closed`;return t?/* @__PURE__ */ Error(`${n} while this code ran, so tool calls it had not started were stopped.${e.startedCalls()}`):e.stopped===`aborted`?/* @__PURE__ */ Error(`${n}, so this code did not run.`):this.closedError()}async run({code:e,restart:t},n){if(this.closing!==void 0)throw this.closedError();n.abortSignal?.throwIfAborted();let r=Y(e);if(r>this.limits.codeBytes)throw Error(`The code is ${String(r)} bytes, over the ${String(this.limits.codeBytes)}-byte limit for one snippet. Send less code per call; variables and functions from earlier calls are still defined.`);let i=new Nt(n.toolCallId,this.limits);this.current=i;let a=()=>{i.stop(`aborted`)};n.abortSignal?.addEventListener(`abort`,a,{once:!0}),this.clearIdleTimer();let o=this.expired;this.expired=!1;try{return t===!0&&await this.releaseSession(),await this.feed(e,i,n)}catch(e){throw o&&e instanceof Error?/* @__PURE__ */ Error(`${e.message}\n\nThe sandbox session had no run_code call for ${String(this.idleTimeout/1e3)} seconds and was replaced, so variables, imports and definitions from earlier calls are gone.`):e}finally{i.stop(`finished`),n.abortSignal?.removeEventListener(`abort`,a),this.current=void 0,this.startIdleTimer()}}async feed(e,t,n){let r;try{r=await this.session()}catch(e){throw t.stopped===void 0?Error(this.describeFailure(e,t).message,{cause:e}):this.stoppedError(t,!1)}if(t.stopped!==void 0)throw this.stoppedError(t,!1);let i,a,o=!1,s=!1;t.start();let c=this.options.typeCheck===`off`||this.options.typeCheck!==`every-snippet`&&this.passedTypeCheck,l=r.feedRun(e,{externalLookup:this.externalLookup(t,n),printCallback:t.printed.write,os:this.osCallback(t),skipTypeCheck:c}).then(e=>({ok:!0,result:e}),e=>({ok:!1,error:e})),d=await Promise.race([l,At(t.signal)]);d===`stopped`?(s=!0,this.abandonSession(r,l)):d.ok?(i=d.result,o=!0,this.passedTypeCheck=!0):(a=d.error,this.passedTypeCheck||=!(a instanceof u.MontyTypingError||a instanceof u.MontySyntaxError));let f=t.reason();if(f===`closed`||f===`aborted`)throw this.stoppedError(t,!0);if(f===`deadline`){s||await this.releaseSession();let e=a instanceof u.MontyRuntimeError?`Runtime error:\n${t.printed.prependTo(this.cut(a.display(`traceback`)))}\n\n`:``;throw Error(`${e}The code ran longer than its ${$(this.limits)}-second time limit, counting time spent waiting on tools, and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and make the code do less work per call.`+t.startedCalls())}if(!o){let e=this.describeFailure(a,t);throw e.reset&&await this.releaseSession(),Error(e.message,{cause:a})}return this.shapeResult(i,t)}shapeResult(e,t){let{outputBytes:n}=this.limits,r=/* @__PURE__ */ Error(`The result is more than ${String(n)} bytes of JSON, over the limit for what one snippet returns. The code ran and its variables are still defined, so return a smaller value from them, such as a summary or fewer fields.`),i;try{i=gt(ht(e,n))}catch(e){throw e instanceof mt?r:e}if(Y(JSON.stringify(i??null))>n)throw r;let a=t.printed.output;return a===``?i??{}:i==null?{output:a}:{output:a,result:i}}cut(e){return _t(e,this.limits.outputBytes)}describeFailure(e,t){let{printed:n}=t;if(e instanceof u.MontySyntaxError)return{message:`Syntax error in code:\n${n.prependTo(this.cut(e.display(`traceback`)))}`,reset:!1};if(e instanceof u.MontyTypingError)return{message:`Type error in code:\n${n.prependTo(this.cut(e.display()))}`,reset:!1};if(e instanceof u.MontyRuntimeError){let r=`Runtime error:\n${n.prependTo(this.cut(e.display(`traceback`)))}`,i=e.display(`msg`);(t.budgetExhausted||Ft.some(e=>i.includes(e)))&&(r+=t.startedCalls());let a=It(e),o=Lt(e);a&&(r+=`
|
|
20
|
+
`)}}function ot(e){return ge(e)}function st(e,t){return dt(e,(0,d.asSchema)(t.inputSchema).jsonSchema)}function ct(e){let t=(e?.[`~standard`])?.jsonSchema?.output;return typeof t==`function`?t:void 0}function lt(e,t){let n=ct(t.outputSchema);return n===void 0?dt(e,(0,d.asSchema)(t.outputSchema).jsonSchema):dt(e,n({target:`draft-07`}))}function ut(e){return typeof e.then==`function`}function dt(e,t){if(ut(t))throw Promise.resolve(t).catch(()=>void 0),Error(`Tool "${e}" has a schema that converts to JSON Schema asynchronously, which code mode does not support`);return t}const ft=/* @__PURE__ */ new WeakSet;function pt(e,t){ft.has(t)||(ft.add(t),console.warn(`Tool "${e}" has no outputSchema, so code mode shows its return type as Any. Add an outputSchema so that the model knows the shape of its result.`))}var mt=class extends Error{maxBytes;constructor(e){super(`The value is more than ${String(e)} bytes of JSON.`),this.maxBytes=e}};function ht(e,t){let n=t,r=e=>{if(n-=e,n<0)throw new mt(t)},i=e=>{r(2);let t={};for(let[n,i]of e){let e=String(n);r(Y(e)+4),Object.defineProperty(t,e,{value:a(i),enumerable:!0,writable:!0,configurable:!0})}return t},a=e=>{if(e instanceof Map)return i(e);if(e instanceof Set||Array.isArray(e)){r(2);let t=[];for(let n of e)r(1),t.push(a(n));return t}if(typeof e==`bigint`){let t=e.toString();return r(t.length),Number.isSafeInteger(Number(e))?Number(e):t}return e instanceof Uint8Array?(r(e.length+2),Buffer.from(e).toString(`latin1`)):typeof e==`string`?(r(Y(e)+2),e):typeof e==`object`&&e?i(Object.entries(e)):(r(typeof e==`number`?String(e).length:5),e)};return a(e)}function gt(e){return typeof e==`number`&&!Number.isFinite(e)?Number.isNaN(e)?`nan`:e>0?`inf`:`-inf`:Array.isArray(e)?e.map(gt):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,gt(t)])):e}function _t(e,t){let n=Y(e);if(n<=t)return e;let r=Buffer.from(e),i=Math.floor(t/2),a=r.subarray(0,i).toString().replace(/\uFFFD$/u,``),o=r.subarray(n-i).toString().replace(/^\uFFFD/u,``);return`${a}\n... (${String(n-2*i)} of ${String(n)} bytes cut) ...\n${o}`}function Y(e){return Buffer.byteLength(e,`utf8`)}function vt(e,t,n){return e>t?` ... (${String(e)} ${n} total)`:``}function X(e,t=!1){if(typeof e==`string`)return C(e.slice(0,120))+vt(e.length,120,`chars`);if(Array.isArray(e))return t?`[${String(e.length)} items]`:`[${e.slice(0,5).map(e=>X(e,!0)).join(`, `)}]`+vt(e.length,5,`items`);if(typeof e==`object`&&e){let n=Object.entries(e);return t?`{${String(n.length)} items}`:`{${n.slice(0,5).map(([e,t])=>`${X(e,!0)}: ${X(t,!0)}`).join(`, `)}}`+vt(n.length,5,`items`)}return e==null||typeof e==`boolean`||typeof e==`number`?C(e):`<object>`}function yt(e){let t=[],n=0;for(let r of e){let i=r.status===`returned`?`returned ${r.outputPreview??`None`}`:r.status===`denied`?`was denied and did not run`:`did not finish, so it may have applied a partial change`,a=`- ${r.toolName}(${r.inputPreview}) ${i}`;if(n+a.length>2e3){t.push(`- ... and ${String(e.length-t.length)} more not shown`);break}t.push(a),n+=a.length}let r=String(e.length);return`${r} nested tool calls started before execution stopped:\n`+t.join(`
|
|
21
|
+
`)+`\nAccount for all ${r} before retrying; repeating a call repeats whatever it already did.`}function bt(e){return new Ht(e)}var xt=class{sandboxFailure=!0;#e;constructor(e){this.#e=e}get error(){return this.#e}};function Z(e,t){let n=Error(t);return n.name=e,n}function St(e){return e instanceof Error?e.message:String(e)}function Ct(e){let t=e;for(let e=0;e<8&&t instanceof Error;e+=1){if(t instanceof u.MontyError)return t;t=t.cause}}const wt=2e3;function Tt(e){let t=St(e);return t.length>wt?`${t.slice(0,wt)} ... (${String(t.length)} chars total)`:t}function Et(e,t,n){let r=t.at(-1),i=typeof r==`object`&&!!r&&Object.getPrototypeOf(r)===null;if(t.length>+!!i)throw Z(`TypeError`,`${e}() does not accept positional arguments; use keyword arguments`);if(!i)return{};try{return ht(r,n)}catch(t){throw t instanceof mt?Z(`ValueError`,Ot(e,n)):t}}function Dt(e,t){return t===void 0?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[t.get(e)??e,n]))}function Ot(e,t){return`The arguments to ${e}() are more than ${String(t)} bytes of JSON, over the limit for one call.`}function kt(){let e=/* @__PURE__ */ new Map;return(t,n)=>{if(!(n instanceof Map||n instanceof Set))return n;let r=e.get(n);return r===void 0&&(r=n instanceof Map?Object.fromEntries([...n].map(([e,t])=>[String(e),t])):[...n],e.set(n,r)),r}}function At(e){let t=JSON.stringify(e??null,kt());if(t===void 0)throw TypeError(`the result, a ${typeof e==`object`?`value whose toJSON() returns undefined`:typeof e}, has no JSON form`);return t}function jt(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e}async function Q(e,t){if(t.aborted)throw e.catch(()=>void 0),t.reason;return new Promise((n,r)=>{let i=()=>{r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})})}async function Mt(e){return e.aborted?`stopped`:new Promise(t=>{e.addEventListener(`abort`,()=>{t(`stopped`)},{once:!0})})}var Nt=class{free;waiting=[];constructor(e){this.free=e}async acquire(e){if(e.throwIfAborted(),this.free>0){--this.free;return}let t=()=>void 0,n=new Promise(e=>{t=e});this.waiting.push(t);try{await Q(n,e)}catch(e){let n=this.waiting.indexOf(t);throw n===-1?this.release():this.waiting.splice(n,1),e}}release(){let e=this.waiting.shift();e===void 0?this.free+=1:e()}},Pt=class{text=``;bytes=0;truncated=!1;maxBytes;constructor(e){this.maxBytes=e}write=(e,t)=>{if(this.truncated)return;let n=Y(t);if(this.bytes+n<=this.maxBytes){this.text+=t,this.bytes+=n;return}this.text+=Buffer.from(t).subarray(0,this.maxBytes-this.bytes).toString().replace(/�$/u,``),this.truncated=!0};get output(){return this.truncated?`${this.text}\n[printed output cut at ${String(this.maxBytes)} bytes]\n`:this.text}prependTo(e){let t=this.output.replace(/\n+$/u,``);return t===``?e:`[stdout before error]\n${t}\n[/stdout before error]\n${e}`}};function Ft(e){return String(e.timeout/1e3)}var It=class{calls=[];printed;deadline=1/0;callCount=0;budgetExhausted=!1;stopped;controller=new AbortController;timer;id;limits;constructor(e,t){this.id=e,this.limits=t,this.printed=new Pt(t.outputBytes)}start(){this.deadline=Date.now()+this.limits.timeout,this.timer=setTimeout(()=>{this.stop(`deadline`)},this.limits.timeout)}get signal(){return this.controller.signal}stop(e){if(clearTimeout(this.timer),this.stopped!==void 0)return;this.stopped=e;let t=e===`deadline`?`the code passed its ${Ft(this.limits)}-second time limit`:e===`aborted`?`the agent run was aborted`:e===`closed`?`code mode was closed`:`the code had already finished`;this.controller.abort(Z(`TimeoutError`,`Stopped because ${t}.`))}reason(){return this.stopped}startedCalls(){return this.calls.length===0?``:`\n\n${yt(this.calls)}`}};const Lt=/^suspension limit [0-9]+ exceeded$/u,Rt=[`time limit exceeded`,`memory limit exceeded`,`suspension limit `],zt=`The code ran longer than its time limit and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and make the code do less work per call.`,$=`The sandbox session was replaced. Variables, imports and definitions from earlier calls are gone. Recreate any state you need, but do not replay completed side effects.`;function Bt(e){return e.traceback().length===0&&e.display(`msg`).includes(`time limit exceeded`)}function Vt(e){return e.exception.typeName===`MemoryError`&&e.display(`msg`).startsWith(`memory limit exceeded`)}var Ht=class{tools;limits;idleTimeout;pythonNames;schemaArgNames;typeCheckStubs;queue=Promise.resolve();poolPromise;sessionPromise;passedTypeCheck=!1;expired=!1;idleTimer;current;closing;failure;options;traceContext;slots;constructor(e){this.options=e,this.traceContext=c.context.active();let{tools:t,sandboxes:n,idleTimeout:r=3e5}=e;for(let[e,n]of Object.entries(t)){if(typeof n.execute!=`function`)throw Error(`Tool "${e}" has no execute function, so sandbox code cannot call it. Pass it to generateText as a direct tool instead.`);if(n.needsApproval!==void 0)throw Error(`Tool "${e}" sets needsApproval, which code mode cannot enforce. Use the approval option of codeMode() instead.`);if(n.toModelOutput!==void 0)throw Error(`Tool "${e}" sets toModelOutput, which code mode cannot apply: sandbox code receives the result that execute returns. Return only what the model may see from execute, or pass the tool to generateText as a direct tool.`)}if(n===void 0&&[void 0,``].includes(process.env.LOGFIRE_API_KEY))throw Error("Agent sandboxes require a Logfire API key with the `project:execute_agent_sandboxes` scope. Set the LOGFIRE_API_KEY environment variable, or pass `sandboxes` to codeMode().");if(!(r>0))throw RangeError(`idleTimeout must be a positive number of milliseconds or Infinity, not ${String(r)}.`);this.limits=_(e.limits),this.slots=new Nt(this.limits.concurrentToolCalls),this.idleTimeout=r;let i=rt(t);this.typeCheckStubs=i.typeCheckStubs,this.schemaArgNames=i.schemaArgNames,this.pythonNames=new Map(Object.keys(t).map(e=>[e,e]));for(let[e,t]of i.toolNames)this.pythonNames.set(t,e);for(let[e,t]of this.pythonNames)if(ee(t))throw Error(`Tool "${e}" becomes the Python function "${t}", which is a Python builtin, so sandbox code would call the builtin instead. Rename the tool.`);this.tools={run_code:(0,d.tool)({description:ae(i.typeDefinitions,i.functions),inputSchema:(0,d.jsonSchema)({type:`object`,properties:{code:{type:`string`,description:`The Python code to execute in the sandbox.`},restart:{type:`boolean`,description:`Set to true to reset REPL state. When false (default), state is preserved between calls.`}},required:[`code`],additionalProperties:!1},{validate:e=>{let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&(t.restart===void 0||typeof t.restart==`boolean`)?{success:!0,value:{code:t.code,restart:t.restart}}:{success:!1,error:/* @__PURE__ */ TypeError("run_code takes a string `code` and an optional boolean `restart`.")}}}),execute:async(e,t)=>{let n=await this.enqueue(e,t);return n instanceof xt?n:{result:n}},toModelOutput:({output:e})=>{if(e instanceof xt)throw e.error;if(typeof e==`object`&&e&&Object.keys(e).length===1&&`sandboxFailure`in e&&e.sandboxFailure===!0)return{type:`text`,value:`Agent Sandboxes infrastructure failed. This call did not complete; a developer must fix the sandbox before a new run.`};let{result:t}=e;return typeof t==`string`?{type:`text`,value:t}:{type:`json`,value:t}}})}}async close(){return this.closing??=this.shutDown(),this.closing}async closeWhenDone(e){return Promise.resolve(e.finishReason).then(async()=>this.close(),async()=>this.close())}async[Symbol.asyncDispose](){return this.close()}async shutDown(){this.clearIdleTimer(),this.current?.stop(`closed`),await this.queue,await this.releaseSession();let e=this.options.sandboxes===void 0?this.poolPromise:void 0;this.poolPromise=void 0,e!==void 0&&await(await e).close()}async enqueue(e,t){let n=this.queue.then(async()=>this.run(e,t));return this.queue=n.catch(()=>void 0),n}closedError(){return/* @__PURE__ */ Error(`Code mode is closed, so this code did not run.`)}stoppedError(e,t){if(e.stopped===`deadline`)return/* @__PURE__ */ Error(`The code ran longer than its ${Ft(this.limits)}-second time limit, counting time spent waiting on tools, and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and make the code do less work per call.`+e.startedCalls());let n=e.stopped===`aborted`?`The agent run was aborted`:`Code mode was closed`;return t?/* @__PURE__ */ Error(`${n} while this code ran, so tool calls it had not started were stopped.${e.startedCalls()}`):e.stopped===`aborted`?/* @__PURE__ */ Error(`${n}, so this code did not run.`):this.closedError()}async run({code:e,restart:t},n){if(this.closing!==void 0)throw this.closedError();if(this.failure!==void 0)return this.failure;n.abortSignal?.throwIfAborted();let r=Y(e);if(r>this.limits.codeBytes)throw Error(`The code is ${String(r)} bytes, over the ${String(this.limits.codeBytes)}-byte limit for one snippet. Send less code per call; variables and functions from earlier calls are still defined.`);let i=new It(n.toolCallId,this.limits);this.current=i;let a=()=>{i.stop(`aborted`)};n.abortSignal?.addEventListener(`abort`,a,{once:!0}),this.clearIdleTimer();let o=this.expired;this.expired=!1;try{return t===!0&&await this.releaseSession(),await this.feed(e,i,n)}catch(e){throw o&&e instanceof Error?/* @__PURE__ */ Error(`${e.message}\n\nThe sandbox session had no run_code call for ${String(this.idleTimeout/1e3)} seconds and was replaced, so variables, imports and definitions from earlier calls are gone.`):e}finally{i.stop(`finished`),n.abortSignal?.removeEventListener(`abort`,a),this.current=void 0,this.startIdleTimer()}}async failSandbox(e){this.failure=new xt(e);try{await this.options.onError?.({error:e})}catch{return this.failure}return this.failure}async feed(e,t,n,r=!1){let i;try{i=await this.session(t.signal)}catch(e){if(t.stopped!==void 0)throw this.stoppedError(t,!1);return this.failSandbox(e)}if(t.stopped!==void 0)throw t.stopped===`deadline`&&await this.releaseSession(),this.stoppedError(t,!1);let a,o,s,c=!1,l=!1;r||t.start();let d=this.options.typeCheck===`off`||this.options.typeCheck!==`every-snippet`&&this.passedTypeCheck,f=i.feedRun(e,{externalLookup:this.externalLookup(t,n),printCallback:t.printed.write,os:this.osCallback(t),skipTypeCheck:d}).then(e=>({ok:!0,result:e}),e=>({ok:!1,error:e})),p=await Promise.race([f,Mt(t.signal)]);p===`stopped`?(l=!0,this.abandonSession(i,f)):p.ok?(a=p.result,c=!0,this.passedTypeCheck=!0):(o=p.error,s=Ct(o),this.passedTypeCheck||=!(s instanceof u.MontyTypingError||s instanceof u.MontySyntaxError));let m=t.reason();if(m===`closed`||m===`aborted`)throw this.stoppedError(t,!0);if(m===`deadline`){l||await this.releaseSession();let e=s instanceof u.MontyRuntimeError?`Runtime error:\n${t.printed.prependTo(this.cut(s.display(`traceback`)))}\n\n`:``;throw Error(e+this.stoppedError(t,!0).message)}if(!c){if(s instanceof u.MontyShutdown&&!r&&t.callCount===0)return await this.releaseSession(),t.printed=new Pt(this.limits.outputBytes),this.feed(e,t,n,!0);t.stop(`finished`);let i=this.describeFailure(s,t);if((i===void 0||i.reset)&&await this.releaseSession(),i===void 0)return this.failSandbox(o);throw Error(i.message+(r?`\n\n${$}`:``),{cause:o})}let h=this.shapeResult(a,t,r);return r?{result:h,sessionReset:$}:h}shapeResult(e,t,n){let{outputBytes:r}=this.limits,i=/* @__PURE__ */ Error(`The result is more than ${String(r)} bytes of JSON, over the limit for what one snippet returns. The code ran and its variables are still defined, so return a smaller value from them, such as a summary or fewer fields.`+(n?`\n\n${$}`:``)),a;try{a=gt(ht(e,r))}catch(e){throw e instanceof mt?i:e}if(Y(JSON.stringify(a??null))>r)throw i;let o=t.printed.output;return o===``?a??{}:a==null?{output:o}:{output:o,result:a}}cut(e){return _t(e,this.limits.outputBytes)}describeFailure(e,t){let{printed:n}=t;if(e instanceof u.MontySyntaxError)return{message:`Syntax error in code:\n${n.prependTo(this.cut(e.display(`traceback`)))}`,reset:!1};if(e instanceof u.MontyTypingError)return{message:`Type error in code:\n${n.prependTo(this.cut(e.display()))}`,reset:!1};if(e instanceof u.MontyRuntimeError){let r=`Runtime error:\n${n.prependTo(this.cut(e.display(`traceback`)))}`,i=e.display(`msg`);(t.budgetExhausted||Rt.some(e=>i.includes(e)))&&(r+=t.startedCalls());let a=Bt(e),o=Vt(e);a&&(r+=`\n\n${zt}`),o&&(r+=`
|
|
22
22
|
|
|
23
|
-
The code ran
|
|
23
|
+
The code ran out of memory and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and keep less data in memory at once.`);let s=a||o;return e.exception.typeName===`RuntimeError`&&Lt.test(i)&&(r+=`
|
|
24
24
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
If this reports the sandbox session's suspension limit, its cumulative host-interaction budget is exhausted. Further tool calls, OS callbacks, name lookups and future resolutions need a fresh session; revising the snippet does not replenish this budget. Pure Python using existing state may still work. Pass \`restart: true\` to start a fresh session; that discards all REPL variables, imports and definitions. Check the calls already started before continuing, and do not replay completed side effects.`),{message:r,reset:s}}if(e instanceof u.MontyCrashedError)return{message:`The code crashed the sandbox worker and the session was reset. Revise the code and try again.${t.startedCalls()}`,reset:!0};let r=e instanceof Error?`${e.name}: ${e.message}`:String(e);return{message:`Code execution failed and the session was reset. Re-run any imports, recreate any state you need, and try again.
|
|
28
|
-
${n.prependTo(this.cut(r))}${t.startedCalls()}`,reset:!0}}osCallback(e){return async(t,n)=>{if(t!==`time.sleep`&&t!==`asyncio.sleep`)return u.NOT_HANDLED;let r=Number(n[0]),i=Math.max(0,(e.deadline-Date.now())/1e3);if(e.stopped!==void 0||r>i)throw Z(`TimeoutError`,`sleeping ${String(r)}s would exceed the ${$(this.limits)}s this code may run; ${i.toFixed(1)}s left`);return await Q((0,p.setTimeout)(r*1e3,void 0,{ref:!1}),e.signal),null}}externalLookup(e,t){return Object.fromEntries(Object.keys(this.options.tools).map(n=>{let r=this.pythonNames.get(n)??n;return[r,async(...i)=>this.callTool(n,r,i,e,t)]}))}async callTool(e,t,n,r,i){let{limits:a}=this,o=this.options.tools[e];if(r.stopped!==void 0)throw r.signal.reason;if(r.callCount>=a.toolCalls)throw r.budgetExhausted=!0,Z(`RuntimeError`,`Code mode allows ${String(a.toolCalls)} nested tool calls per \`run_code\` call and this snippet asked for more. Call fewer tools, for example by filtering the inputs first, or split the work across several \`run_code\` calls.`);r.callCount+=1;let s=`${r.id}__${String(r.callCount)}`,c=Tt(wt(t,n,a.toolInputBytes),this.schemaArgNames.get(t));if(Y(JSON.stringify(c))>a.toolInputBytes)throw Z(`ValueError`,Et(t,a.toolInputBytes));let l=await Q(Promise.resolve((0,d.asSchema)(o.inputSchema).validate?.(c)),r.signal);if(l!==void 0&&!l.success)throw Z(`ValueError`,`Invalid arguments for ${t}(): ${Ct(l.error)}`);let u=l===void 0?c:l.value,p=this.options.context,m=p!==void 0&&Object.hasOwn(p,e)?p[e]:void 0;if(o.contextSchema!==void 0){let t=await Q(Promise.resolve((0,d.asSchema)(o.contextSchema).validate?.(m)),r.signal);if(t!==void 0&&!t.success)throw Z(`ValueError`,`Invalid context for tool "${e}": ${Ct(t.error)}`);m=t===void 0?m:t.value}let h={toolName:e,inputPreview:X(u),status:`running`},g=await Q(ee(this.options.approval,{tools:this.options.tools,toolsContext:this.options.context??{},runtimeContext:this.options.runtimeContext},{toolName:e,toolCallId:s,input:u,messages:i.messages,toolContext:m,tool:o}),r.signal);if(!g.approved){h.status=`denied`,r.calls.push(h);let t=g.reason===void 0?``:` ${g.reason}`;throw Z(`RuntimeError`,g.needsUser?`Tool '${e}' needs a person to approve it, and code mode cannot ask for approval from inside the sandbox.${t}`:`Tool '${e}' call denied:${t===``?` denied by the approval policy`:t}`)}await this.slots.acquire(r.signal);let _=!1,v=()=>{_||(_=!0,this.slots.release())},y={};r.calls.push(h);try{return await f.span(`run_code called {tool_name}`,{tool_name:e,tool_call_id:s,arguments:u},{},async()=>{let n;try{r.signal.throwIfAborted();let e=this.execute(o,u,{...i,toolCallId:s,context:m,abortSignal:r.signal});y.running=e,e.then(v,v),n=await Q(e,r.signal)}catch(t){throw h.status=`failed`,r.stopped===void 0?this.replaceToolError(t,{toolName:e,toolCallId:s,input:u}):t}h.status=`returned`;let c;try{c=Ot(n)}catch(e){let n=e instanceof RangeError?`it is nested too deeply or contains itself`:xt(e);throw h.outputPreview=`<not JSON>`,Z(`ValueError`,`${t}() returned a value that cannot be sent to the sandbox as JSON: ${n}. The call ran, so do not repeat it to get the same result.`)}let l=Y(c);if(l>a.toolOutputBytes)throw h.outputPreview=`<${String(l)} bytes, over the limit>`,Z(`ValueError`,`${t}() returned ${String(l)} bytes of JSON, over the ${String(a.toolOutputBytes)}-byte limit for one call. The call ran, so do not repeat it to get the same result.`);let d=JSON.parse(c);return h.outputPreview=X(d),d})}finally{y.running===void 0&&v()}}async execute(e,t,n){let r=e.execute,i=r(t,n);if(kt(i)){let e;for await(let t of i)e=t;return e}return await i}replaceToolError(e,t){let n=this.options.onToolError?.(e,t);return n instanceof Error?n:typeof n==`string`?Error(n):e instanceof Error?e:Error(String(e))}async pool(){let{sandboxes:e}=this.options;this.poolPromise??=e===void 0?(0,l.agentSandboxes)({requestTimeout:this.limits.timeout/1e3+10}):Promise.resolve(e);try{return await this.poolPromise}catch(e){throw this.poolPromise=void 0,e}}async session(){this.sessionPromise??=this.checkout();try{return await this.sessionPromise}catch(e){throw this.sessionPromise=void 0,e}}async checkout(){let e=this.options.typeCheck!==`off`;return c.context.with(this.traceContext,async()=>(await this.pool()).checkout({ephemeral:!0,scriptName:`run_code.py`,typeCheck:e,...e?{typeCheckStubs:this.typeCheckStubs}:{},limits:{maxFeedDurationSecs:this.limits.timeout/1e3,maxMemory:this.limits.memory,maxSuspensions:this.limits.suspensions},osPolicy:{datetime:`call_host`,sleep:`call_host`,randomStart:`call_host`}}))}abandonSession(e,t){this.sessionPromise=void 0,this.passedTypeCheck=!1,t.then(async()=>e.close()).catch(()=>void 0)}async releaseSession(){let e=this.sessionPromise;if(this.sessionPromise=void 0,this.passedTypeCheck=!1,e!==void 0)try{await(await e).close()}catch{}}startIdleTimer(){this.closing===void 0&&this.sessionPromise!==void 0&&Number.isFinite(this.idleTimeout)&&(this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.current===void 0&&this.closing===void 0&&(this.expired=!0,this.releaseSession().catch(()=>void 0))},Math.min(this.idleTimeout,2**31-1)),this.idleTimer.unref())}clearIdleTimer(){clearTimeout(this.idleTimer),this.idleTimer=void 0}};exports.codeMode=bt;
|
|
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;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { MontySession, RemoteCheckoutOptions } from "@pydantic/monty";
|
|
2
|
-
import { Tool, ToolApprovalConfiguration, ToolApprovalStatus, ToolSet } from "ai";
|
|
2
|
+
import { StreamTextOnErrorCallback, Tool, ToolApprovalConfiguration, ToolApprovalStatus, ToolSet } from "ai";
|
|
3
3
|
//#region src/approval.d.ts
|
|
4
4
|
type AnyFunction = (...args: never[]) => unknown;
|
|
5
5
|
/** The AI SDK's statuses without `'user-approval'`: nothing in the sandbox can wait for a person. */
|
|
@@ -94,15 +94,22 @@ interface CodeModeOptions<TOOLS extends ToolSet, RUNTIME_CONTEXT = unknown> {
|
|
|
94
94
|
* Replaces the error the sandbox, the model and the trace see when a tool throws. Return a string or an error to
|
|
95
95
|
* replace it, or `undefined` to keep it. Messages pass through unchanged by default, as in pydantic-ai. A result
|
|
96
96
|
* that has no JSON form, such as a bigint or a cycle, is not a tool error, so this is not called for it.
|
|
97
|
+
* Sandbox configuration and infrastructure failures end the agent run instead and do not call this hook.
|
|
97
98
|
*/
|
|
98
99
|
onToolError?: (error: unknown, call: ToolErrorCall) => Error | string | undefined;
|
|
100
|
+
/**
|
|
101
|
+
* Reports the original Agent Sandboxes infrastructure error once, including on UI routes where the AI SDK does
|
|
102
|
+
* not call its own error handler. Uses the AI SDK's `{ error }` event shape so one handler can be passed to both.
|
|
103
|
+
* The handler is awaited; its exceptions cannot replace the original error.
|
|
104
|
+
*/
|
|
105
|
+
onError?: StreamTextOnErrorCallback;
|
|
99
106
|
}
|
|
100
107
|
interface RunCodeInput {
|
|
101
108
|
code: string;
|
|
102
109
|
restart?: boolean | undefined;
|
|
103
110
|
}
|
|
104
111
|
interface CodeMode extends AsyncDisposable {
|
|
105
|
-
/** `{ run_code }`, to spread into generateText's or streamText's `tools`. */
|
|
112
|
+
/** `{ run_code }`, to spread into generateText's or streamText's `tools`. Successful outputs use `{ result: value }`; the output hook unwraps them for the model. */
|
|
106
113
|
readonly tools: {
|
|
107
114
|
run_code: Tool<RunCodeInput, unknown>;
|
|
108
115
|
};
|
|
@@ -127,6 +134,7 @@ interface CodeMode extends AsyncDisposable {
|
|
|
127
134
|
* ```
|
|
128
135
|
*
|
|
129
136
|
* With `streamText`, use `closeWhenDone(result)` instead, because the block exits before the stream is read.
|
|
137
|
+
* Sandbox setup and checkout failures end the run with the original error; unexpected disconnects become retryable model tool errors.
|
|
130
138
|
*/
|
|
131
139
|
export declare function codeMode<TOOLS extends ToolSet, RUNTIME_CONTEXT = unknown>(options: CodeModeOptions<TOOLS, RUNTIME_CONTEXT>): CodeMode;
|
|
132
140
|
//#endregion
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { MontySession, RemoteCheckoutOptions } from "@pydantic/monty";
|
|
2
|
-
import { Tool, ToolApprovalConfiguration, ToolApprovalStatus, ToolSet } from "ai";
|
|
2
|
+
import { StreamTextOnErrorCallback, Tool, ToolApprovalConfiguration, ToolApprovalStatus, ToolSet } from "ai";
|
|
3
3
|
//#region src/approval.d.ts
|
|
4
4
|
type AnyFunction = (...args: never[]) => unknown;
|
|
5
5
|
/** The AI SDK's statuses without `'user-approval'`: nothing in the sandbox can wait for a person. */
|
|
@@ -94,15 +94,22 @@ interface CodeModeOptions<TOOLS extends ToolSet, RUNTIME_CONTEXT = unknown> {
|
|
|
94
94
|
* Replaces the error the sandbox, the model and the trace see when a tool throws. Return a string or an error to
|
|
95
95
|
* replace it, or `undefined` to keep it. Messages pass through unchanged by default, as in pydantic-ai. A result
|
|
96
96
|
* that has no JSON form, such as a bigint or a cycle, is not a tool error, so this is not called for it.
|
|
97
|
+
* Sandbox configuration and infrastructure failures end the agent run instead and do not call this hook.
|
|
97
98
|
*/
|
|
98
99
|
onToolError?: (error: unknown, call: ToolErrorCall) => Error | string | undefined;
|
|
100
|
+
/**
|
|
101
|
+
* Reports the original Agent Sandboxes infrastructure error once, including on UI routes where the AI SDK does
|
|
102
|
+
* not call its own error handler. Uses the AI SDK's `{ error }` event shape so one handler can be passed to both.
|
|
103
|
+
* The handler is awaited; its exceptions cannot replace the original error.
|
|
104
|
+
*/
|
|
105
|
+
onError?: StreamTextOnErrorCallback;
|
|
99
106
|
}
|
|
100
107
|
interface RunCodeInput {
|
|
101
108
|
code: string;
|
|
102
109
|
restart?: boolean | undefined;
|
|
103
110
|
}
|
|
104
111
|
interface CodeMode extends AsyncDisposable {
|
|
105
|
-
/** `{ run_code }`, to spread into generateText's or streamText's `tools`. */
|
|
112
|
+
/** `{ run_code }`, to spread into generateText's or streamText's `tools`. Successful outputs use `{ result: value }`; the output hook unwraps them for the model. */
|
|
106
113
|
readonly tools: {
|
|
107
114
|
run_code: Tool<RunCodeInput, unknown>;
|
|
108
115
|
};
|
|
@@ -127,6 +134,7 @@ interface CodeMode extends AsyncDisposable {
|
|
|
127
134
|
* ```
|
|
128
135
|
*
|
|
129
136
|
* With `streamText`, use `closeWhenDone(result)` instead, because the block exits before the stream is read.
|
|
137
|
+
* Sandbox setup and checkout failures end the run with the original error; unexpected disconnects become retryable model tool errors.
|
|
130
138
|
*/
|
|
131
139
|
export declare function codeMode<TOOLS extends ToolSet, RUNTIME_CONTEXT = unknown>(options: CodeModeOptions<TOOLS, RUNTIME_CONTEXT>): CodeMode;
|
|
132
140
|
//#endregion
|
package/dist/index.js
CHANGED
|
@@ -1,28 +1,25 @@
|
|
|
1
|
-
import{context as e}from"@opentelemetry/api";import{agentSandboxes as t}from"@pydantic/logfire-agent-sandboxes";import{MontyCrashedError as n,
|
|
2
|
-
`)n+=`\\n`;else if(r===`\r`)n+=`\\r`;else if(r!==` `&&
|
|
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(`
|
|
3
3
|
|
|
4
4
|
`)+"\n```"),n.push("```python\n"+t.join(`
|
|
5
5
|
|
|
6
|
-
`)+"\n```"),`${
|
|
6
|
+
`)+"\n```"),`${ce}\n\n${n.join(`
|
|
7
7
|
|
|
8
|
-
`)}`}let C
|
|
9
|
-
`)}};function
|
|
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(
|
|
11
|
-
`)}renderFunctionalDefinition(){let e=A(this.description)?
|
|
12
|
-
`)}structurallyEqual(e){return
|
|
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(`
|
|
13
13
|
`));let u=c.join(`
|
|
14
14
|
|
|
15
|
-
`);return u!==``&&s.push(...
|
|
16
|
-
`)}static fromSchema(t,n,r){let i=
|
|
17
|
-
from typing import Any, TypedDict, NotRequired, Literal`,
|
|
18
|
-
`).flatMap(e=>e.replace(/^(?:from \S+ )?import /u,``).split(`, `)));function
|
|
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
|
|
17
|
+
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(`
|
|
19
19
|
|
|
20
|
-
`)}}function
|
|
21
|
-
`)+`\nAccount for all ${r} before retrying; repeating a call repeats whatever it already did.`}function _t(e){return new It(e)}function Q(e,t){let n=Error(t);return n.name=e,n}function vt(e){return e instanceof Error?e.message:String(e)}const yt=2e3;function bt(e){let t=vt(e);return t.length>yt?`${t.slice(0,yt)} ... (${String(t.length)} chars total)`:t}function xt(e,t,n){let r=t.at(-1),i=typeof r==`object`&&!!r&&Object.getPrototypeOf(r)===null;if(t.length>+!!i)throw Q(`TypeError`,`${e}() does not accept positional arguments; use keyword arguments`);if(!i)return{};try{return ft(r,n)}catch(t){throw t instanceof Y?Q(`ValueError`,Ct(e,n)):t}}function St(e,t){return t===void 0?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[t.get(e)??e,n]))}function Ct(e,t){return`The arguments to ${e}() are more than ${String(t)} bytes of JSON, over the limit for one call.`}function wt(){let e=/* @__PURE__ */ new Map;return(t,n)=>{if(!(n instanceof Map||n instanceof Set))return n;let r=e.get(n);return r===void 0&&(r=n instanceof Map?Object.fromEntries([...n].map(([e,t])=>[String(e),t])):[...n],e.set(n,r)),r}}function Tt(e){let t=JSON.stringify(e??null,wt());if(t===void 0)throw TypeError(`the result, a ${typeof e==`object`?`value whose toJSON() returns undefined`:typeof e}, has no JSON form`);return t}function Et(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e}async function $(e,t){if(t.aborted)throw e.catch(()=>void 0),t.reason;return new Promise((n,r)=>{let i=()=>{r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})})}async function Dt(e){return e.aborted?`stopped`:new Promise(t=>{e.addEventListener(`abort`,()=>{t(`stopped`)},{once:!0})})}var Ot=class{free;waiting=[];constructor(e){this.free=e}async acquire(e){if(e.throwIfAborted(),this.free>0){--this.free;return}let t=()=>void 0,n=new Promise(e=>{t=e});this.waiting.push(t);try{await $(n,e)}catch(e){let n=this.waiting.indexOf(t);throw n===-1?this.release():this.waiting.splice(n,1),e}}release(){let e=this.waiting.shift();e===void 0?this.free+=1:e()}},kt=class{text=``;bytes=0;truncated=!1;maxBytes;constructor(e){this.maxBytes=e}write=(e,t)=>{if(this.truncated)return;let n=X(t);if(this.bytes+n<=this.maxBytes){this.text+=t,this.bytes+=n;return}this.text+=Buffer.from(t).subarray(0,this.maxBytes-this.bytes).toString().replace(/�$/u,``),this.truncated=!0};get output(){return this.truncated?`${this.text}\n[printed output cut at ${String(this.maxBytes)} bytes]\n`:this.text}prependTo(e){let t=this.output.replace(/\n+$/u,``);return t===``?e:`[stdout before error]\n${t}\n[/stdout before error]\n${e}`}};function At(e){return String(e.timeout/1e3)}var jt=class{calls=[];printed;deadline=1/0;callCount=0;budgetExhausted=!1;stopped;controller=new AbortController;timer;id;limits;constructor(e,t){this.id=e,this.limits=t,this.printed=new kt(t.outputBytes)}start(){this.deadline=Date.now()+this.limits.timeout,this.timer=setTimeout(()=>{this.stop(`deadline`)},this.limits.timeout)}get signal(){return this.controller.signal}stop(e){if(clearTimeout(this.timer),this.stopped!==void 0)return;this.stopped=e;let t=e===`deadline`?`the code passed its ${At(this.limits)}-second time limit`:e===`aborted`?`the agent run was aborted`:e===`closed`?`code mode was closed`:`the code had already finished`;this.controller.abort(Q(`TimeoutError`,`Stopped because ${t}.`))}reason(){return this.stopped}startedCalls(){return this.calls.length===0?``:`\n\n${gt(this.calls)}`}};const Mt=/^suspension limit [0-9]+ exceeded$/u,Nt=[`time limit exceeded`,`memory limit exceeded`,`suspension limit `];function Pt(e){return e.traceback().length===0&&e.display(`msg`).includes(`time limit exceeded`)}function Ft(e){return e.exception.typeName===`MemoryError`&&e.display(`msg`).startsWith(`memory limit exceeded`)}var It=class{tools;limits;idleTimeout;pythonNames;schemaArgNames;typeCheckStubs;queue=Promise.resolve();poolPromise;sessionPromise;passedTypeCheck=!1;expired=!1;idleTimer;current;closing;options;traceContext;slots;constructor(t){this.options=t,this.traceContext=e.active();let{tools:n,sandboxes:r,idleTimeout:i=3e5}=t;for(let[e,t]of Object.entries(n)){if(typeof t.execute!=`function`)throw Error(`Tool "${e}" has no execute function, so sandbox code cannot call it. Pass it to generateText as a direct tool instead.`);if(t.needsApproval!==void 0)throw Error(`Tool "${e}" sets needsApproval, which code mode cannot enforce. Use the approval option of codeMode() instead.`);if(t.toModelOutput!==void 0)throw Error(`Tool "${e}" sets toModelOutput, which code mode cannot apply: sandbox code receives the result that execute returns. Return only what the model may see from execute, or pass the tool to generateText as a direct tool.`)}if(r===void 0&&[void 0,``].includes(process.env.LOGFIRE_API_KEY))throw Error("Agent sandboxes require a Logfire API key with the `project:execute_agent_sandboxes` scope. Set the LOGFIRE_API_KEY environment variable, or pass `sandboxes` to codeMode().");if(!(i>0))throw RangeError(`idleTimeout must be a positive number of milliseconds or Infinity, not ${String(i)}.`);this.limits=h(t.limits),this.slots=new Ot(this.limits.concurrentToolCalls),this.idleTimeout=i;let a=nt(n);this.typeCheckStubs=a.typeCheckStubs,this.schemaArgNames=a.schemaArgNames,this.pythonNames=new Map(Object.keys(n).map(e=>[e,e]));for(let[e,t]of a.toolNames)this.pythonNames.set(t,e);for(let[e,t]of this.pythonNames)if(y(t))throw Error(`Tool "${e}" becomes the Python function "${t}", which is a Python builtin, so sandbox code would call the builtin instead. Rename the tool.`);this.tools={run_code:l({description:ie(a.typeDefinitions,a.functions),inputSchema:c({type:`object`,properties:{code:{type:`string`,description:`The Python code to execute in the sandbox.`},restart:{type:`boolean`,description:`Set to true to reset REPL state. When false (default), state is preserved between calls.`}},required:[`code`],additionalProperties:!1},{validate:e=>{let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&(t.restart===void 0||typeof t.restart==`boolean`)?{success:!0,value:{code:t.code,restart:t.restart}}:{success:!1,error:/* @__PURE__ */ TypeError("run_code takes a string `code` and an optional boolean `restart`.")}}}),execute:async(e,t)=>this.enqueue(e,t)})}}async close(){return this.closing??=this.shutDown(),this.closing}async closeWhenDone(e){return Promise.resolve(e.finishReason).then(async()=>this.close(),async()=>this.close())}async[Symbol.asyncDispose](){return this.close()}async shutDown(){this.clearIdleTimer(),this.current?.stop(`closed`),await this.queue,await this.releaseSession();let e=this.options.sandboxes===void 0?this.poolPromise:void 0;this.poolPromise=void 0,e!==void 0&&await(await e).close()}async enqueue(e,t){let n=this.queue.then(async()=>this.run(e,t));return this.queue=n.catch(()=>void 0),n}closedError(){return/* @__PURE__ */ Error(`Code mode is closed, so this code did not run.`)}stoppedError(e,t){let n=e.stopped===`aborted`?`The agent run was aborted`:`Code mode was closed`;return t?/* @__PURE__ */ Error(`${n} while this code ran, so tool calls it had not started were stopped.${e.startedCalls()}`):e.stopped===`aborted`?/* @__PURE__ */ Error(`${n}, so this code did not run.`):this.closedError()}async run({code:e,restart:t},n){if(this.closing!==void 0)throw this.closedError();n.abortSignal?.throwIfAborted();let r=X(e);if(r>this.limits.codeBytes)throw Error(`The code is ${String(r)} bytes, over the ${String(this.limits.codeBytes)}-byte limit for one snippet. Send less code per call; variables and functions from earlier calls are still defined.`);let i=new jt(n.toolCallId,this.limits);this.current=i;let a=()=>{i.stop(`aborted`)};n.abortSignal?.addEventListener(`abort`,a,{once:!0}),this.clearIdleTimer();let o=this.expired;this.expired=!1;try{return t===!0&&await this.releaseSession(),await this.feed(e,i,n)}catch(e){throw o&&e instanceof Error?/* @__PURE__ */ Error(`${e.message}\n\nThe sandbox session had no run_code call for ${String(this.idleTimeout/1e3)} seconds and was replaced, so variables, imports and definitions from earlier calls are gone.`):e}finally{i.stop(`finished`),n.abortSignal?.removeEventListener(`abort`,a),this.current=void 0,this.startIdleTimer()}}async feed(e,t,n){let o;try{o=await this.session()}catch(e){throw t.stopped===void 0?Error(this.describeFailure(e,t).message,{cause:e}):this.stoppedError(t,!1)}if(t.stopped!==void 0)throw this.stoppedError(t,!1);let s,c,l=!1,u=!1;t.start();let d=this.options.typeCheck===`off`||this.options.typeCheck!==`every-snippet`&&this.passedTypeCheck,f=o.feedRun(e,{externalLookup:this.externalLookup(t,n),printCallback:t.printed.write,os:this.osCallback(t),skipTypeCheck:d}).then(e=>({ok:!0,result:e}),e=>({ok:!1,error:e})),p=await Promise.race([f,Dt(t.signal)]);p===`stopped`?(u=!0,this.abandonSession(o,f)):p.ok?(s=p.result,l=!0,this.passedTypeCheck=!0):(c=p.error,this.passedTypeCheck||=!(c instanceof a||c instanceof i));let m=t.reason();if(m===`closed`||m===`aborted`)throw this.stoppedError(t,!0);if(m===`deadline`){u||await this.releaseSession();let e=c instanceof r?`Runtime error:\n${t.printed.prependTo(this.cut(c.display(`traceback`)))}\n\n`:``;throw Error(`${e}The code ran longer than its ${At(this.limits)}-second time limit, counting time spent waiting on tools, and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and make the code do less work per call.`+t.startedCalls())}if(!l){let e=this.describeFailure(c,t);throw e.reset&&await this.releaseSession(),Error(e.message,{cause:c})}return this.shapeResult(s,t)}shapeResult(e,t){let{outputBytes:n}=this.limits,r=/* @__PURE__ */ Error(`The result is more than ${String(n)} bytes of JSON, over the limit for what one snippet returns. The code ran and its variables are still defined, so return a smaller value from them, such as a summary or fewer fields.`),i;try{i=pt(ft(e,n))}catch(e){throw e instanceof Y?r:e}if(X(JSON.stringify(i??null))>n)throw r;let a=t.printed.output;return a===``?i??{}:i==null?{output:a}:{output:a,result:i}}cut(e){return mt(e,this.limits.outputBytes)}describeFailure(e,t){let{printed:o}=t;if(e instanceof i)return{message:`Syntax error in code:\n${o.prependTo(this.cut(e.display(`traceback`)))}`,reset:!1};if(e instanceof a)return{message:`Type error in code:\n${o.prependTo(this.cut(e.display()))}`,reset:!1};if(e instanceof r){let n=`Runtime error:\n${o.prependTo(this.cut(e.display(`traceback`)))}`,r=e.display(`msg`);(t.budgetExhausted||Nt.some(e=>r.includes(e)))&&(n+=t.startedCalls());let i=Pt(e),a=Ft(e);i&&(n+=`
|
|
20
|
+
`)}}function lt(e){return ve(e)}function ut(e,t){return J(e,d(t.inputSchema).jsonSchema)}function dt(e){let t=(e?.[`~standard`])?.jsonSchema?.output;return typeof t==`function`?t:void 0}function ft(e,t){let n=dt(t.outputSchema);return n===void 0?J(e,d(t.outputSchema).jsonSchema):J(e,n({target:`draft-07`}))}function pt(e){return typeof e.then==`function`}function J(e,t){if(pt(t))throw Promise.resolve(t).catch(()=>void 0),Error(`Tool "${e}" has a schema that converts to JSON Schema asynchronously, which code mode does not support`);return t}const mt=/* @__PURE__ */ new WeakSet;function ht(e,t){mt.has(t)||(mt.add(t),console.warn(`Tool "${e}" has no outputSchema, so code mode shows its return type as Any. Add an outputSchema so that the model knows the shape of its result.`))}var Y=class extends Error{maxBytes;constructor(e){super(`The value is more than ${String(e)} bytes of JSON.`),this.maxBytes=e}};function gt(e,t){let n=t,r=e=>{if(n-=e,n<0)throw new Y(t)},i=e=>{r(2);let t={};for(let[n,i]of e){let e=String(n);r(X(e)+4),Object.defineProperty(t,e,{value:a(i),enumerable:!0,writable:!0,configurable:!0})}return t},a=e=>{if(e instanceof Map)return i(e);if(e instanceof Set||Array.isArray(e)){r(2);let t=[];for(let n of e)r(1),t.push(a(n));return t}if(typeof e==`bigint`){let t=e.toString();return r(t.length),Number.isSafeInteger(Number(e))?Number(e):t}return e instanceof Uint8Array?(r(e.length+2),Buffer.from(e).toString(`latin1`)):typeof e==`string`?(r(X(e)+2),e):typeof e==`object`&&e?i(Object.entries(e)):(r(typeof e==`number`?String(e).length:5),e)};return a(e)}function _t(e){return typeof e==`number`&&!Number.isFinite(e)?Number.isNaN(e)?`nan`:e>0?`inf`:`-inf`:Array.isArray(e)?e.map(_t):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,_t(t)])):e}function vt(e,t){let n=X(e);if(n<=t)return e;let r=Buffer.from(e),i=Math.floor(t/2),a=r.subarray(0,i).toString().replace(/\uFFFD$/u,``),o=r.subarray(n-i).toString().replace(/^\uFFFD/u,``);return`${a}\n... (${String(n-2*i)} of ${String(n)} bytes cut) ...\n${o}`}function X(e){return Buffer.byteLength(e,`utf8`)}function yt(e,t,n){return e>t?` ... (${String(e)} ${n} total)`:``}function Z(e,t=!1){if(typeof e==`string`)return x(e.slice(0,120))+yt(e.length,120,`chars`);if(Array.isArray(e))return t?`[${String(e.length)} items]`:`[${e.slice(0,5).map(e=>Z(e,!0)).join(`, `)}]`+yt(e.length,5,`items`);if(typeof e==`object`&&e){let n=Object.entries(e);return t?`{${String(n.length)} items}`:`{${n.slice(0,5).map(([e,t])=>`${Z(e,!0)}: ${Z(t,!0)}`).join(`, `)}}`+yt(n.length,5,`items`)}return e==null||typeof e==`boolean`||typeof e==`number`?x(e):`<object>`}function bt(e){let t=[],n=0;for(let r of e){let i=r.status===`returned`?`returned ${r.outputPreview??`None`}`:r.status===`denied`?`was denied and did not run`:`did not finish, so it may have applied a partial change`,a=`- ${r.toolName}(${r.inputPreview}) ${i}`;if(n+a.length>2e3){t.push(`- ... and ${String(e.length-t.length)} more not shown`);break}t.push(a),n+=a.length}let r=String(e.length);return`${r} nested tool calls started before execution stopped:\n`+t.join(`
|
|
21
|
+
`)+`\nAccount for all ${r} before retrying; repeating a call repeats whatever it already did.`}function xt(e){return new Wt(e)}var St=class{sandboxFailure=!0;#e;constructor(e){this.#e=e}get error(){return this.#e}};function Q(e,t){let n=Error(t);return n.name=e,n}function Ct(e){return e instanceof Error?e.message:String(e)}function wt(e){let t=e;for(let e=0;e<8&&t instanceof Error;e+=1){if(t instanceof i)return t;t=t.cause}}const Tt=2e3;function Et(e){let t=Ct(e);return t.length>Tt?`${t.slice(0,Tt)} ... (${String(t.length)} chars total)`:t}function Dt(e,t,n){let r=t.at(-1),i=typeof r==`object`&&!!r&&Object.getPrototypeOf(r)===null;if(t.length>+!!i)throw Q(`TypeError`,`${e}() does not accept positional arguments; use keyword arguments`);if(!i)return{};try{return gt(r,n)}catch(t){throw t instanceof Y?Q(`ValueError`,kt(e,n)):t}}function Ot(e,t){return t===void 0?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[t.get(e)??e,n]))}function kt(e,t){return`The arguments to ${e}() are more than ${String(t)} bytes of JSON, over the limit for one call.`}function At(){let e=/* @__PURE__ */ new Map;return(t,n)=>{if(!(n instanceof Map||n instanceof Set))return n;let r=e.get(n);return r===void 0&&(r=n instanceof Map?Object.fromEntries([...n].map(([e,t])=>[String(e),t])):[...n],e.set(n,r)),r}}function jt(e){let t=JSON.stringify(e??null,At());if(t===void 0)throw TypeError(`the result, a ${typeof e==`object`?`value whose toJSON() returns undefined`:typeof e}, has no JSON form`);return t}function Mt(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e}async function $(e,t){if(t.aborted)throw e.catch(()=>void 0),t.reason;return new Promise((n,r)=>{let i=()=>{r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})})}async function Nt(e){return e.aborted?`stopped`:new Promise(t=>{e.addEventListener(`abort`,()=>{t(`stopped`)},{once:!0})})}var Pt=class{free;waiting=[];constructor(e){this.free=e}async acquire(e){if(e.throwIfAborted(),this.free>0){--this.free;return}let t=()=>void 0,n=new Promise(e=>{t=e});this.waiting.push(t);try{await $(n,e)}catch(e){let n=this.waiting.indexOf(t);throw n===-1?this.release():this.waiting.splice(n,1),e}}release(){let e=this.waiting.shift();e===void 0?this.free+=1:e()}},Ft=class{text=``;bytes=0;truncated=!1;maxBytes;constructor(e){this.maxBytes=e}write=(e,t)=>{if(this.truncated)return;let n=X(t);if(this.bytes+n<=this.maxBytes){this.text+=t,this.bytes+=n;return}this.text+=Buffer.from(t).subarray(0,this.maxBytes-this.bytes).toString().replace(/�$/u,``),this.truncated=!0};get output(){return this.truncated?`${this.text}\n[printed output cut at ${String(this.maxBytes)} bytes]\n`:this.text}prependTo(e){let t=this.output.replace(/\n+$/u,``);return t===``?e:`[stdout before error]\n${t}\n[/stdout before error]\n${e}`}};function It(e){return String(e.timeout/1e3)}var Lt=class{calls=[];printed;deadline=1/0;callCount=0;budgetExhausted=!1;stopped;controller=new AbortController;timer;id;limits;constructor(e,t){this.id=e,this.limits=t,this.printed=new Ft(t.outputBytes)}start(){this.deadline=Date.now()+this.limits.timeout,this.timer=setTimeout(()=>{this.stop(`deadline`)},this.limits.timeout)}get signal(){return this.controller.signal}stop(e){if(clearTimeout(this.timer),this.stopped!==void 0)return;this.stopped=e;let t=e===`deadline`?`the code passed its ${It(this.limits)}-second time limit`:e===`aborted`?`the agent run was aborted`:e===`closed`?`code mode was closed`:`the code had already finished`;this.controller.abort(Q(`TimeoutError`,`Stopped because ${t}.`))}reason(){return this.stopped}startedCalls(){return this.calls.length===0?``:`\n\n${bt(this.calls)}`}};const Rt=/^suspension limit [0-9]+ exceeded$/u,zt=[`time limit exceeded`,`memory limit exceeded`,`suspension limit `],Bt=`The code ran longer than its time limit and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and make the code do less work per call.`,Vt=`The sandbox session was replaced. Variables, imports and definitions from earlier calls are gone. Recreate any state you need, but do not replay completed side effects.`;function Ht(e){return e.traceback().length===0&&e.display(`msg`).includes(`time limit exceeded`)}function Ut(e){return e.exception.typeName===`MemoryError`&&e.display(`msg`).startsWith(`memory limit exceeded`)}var Wt=class{tools;limits;idleTimeout;pythonNames;schemaArgNames;typeCheckStubs;queue=Promise.resolve();poolPromise;sessionPromise;passedTypeCheck=!1;expired=!1;idleTimer;current;closing;failure;options;traceContext;slots;constructor(t){this.options=t,this.traceContext=e.active();let{tools:n,sandboxes:r,idleTimeout:i=3e5}=t;for(let[e,t]of Object.entries(n)){if(typeof t.execute!=`function`)throw Error(`Tool "${e}" has no execute function, so sandbox code cannot call it. Pass it to generateText as a direct tool instead.`);if(t.needsApproval!==void 0)throw Error(`Tool "${e}" sets needsApproval, which code mode cannot enforce. Use the approval option of codeMode() instead.`);if(t.toModelOutput!==void 0)throw Error(`Tool "${e}" sets toModelOutput, which code mode cannot apply: sandbox code receives the result that execute returns. Return only what the model may see from execute, or pass the tool to generateText as a direct tool.`)}if(r===void 0&&[void 0,``].includes(process.env.LOGFIRE_API_KEY))throw Error("Agent sandboxes require a Logfire API key with the `project:execute_agent_sandboxes` scope. Set the LOGFIRE_API_KEY environment variable, or pass `sandboxes` to codeMode().");if(!(i>0))throw RangeError(`idleTimeout must be a positive number of milliseconds or Infinity, not ${String(i)}.`);this.limits=v(t.limits),this.slots=new Pt(this.limits.concurrentToolCalls),this.idleTimeout=i;let a=ot(n);this.typeCheckStubs=a.typeCheckStubs,this.schemaArgNames=a.schemaArgNames,this.pythonNames=new Map(Object.keys(n).map(e=>[e,e]));for(let[e,t]of a.toolNames)this.pythonNames.set(t,e);for(let[e,t]of this.pythonNames)if(ie(t))throw Error(`Tool "${e}" becomes the Python function "${t}", which is a Python builtin, so sandbox code would call the builtin instead. Rename the tool.`);this.tools={run_code:p({description:le(a.typeDefinitions,a.functions),inputSchema:f({type:`object`,properties:{code:{type:`string`,description:`The Python code to execute in the sandbox.`},restart:{type:`boolean`,description:`Set to true to reset REPL state. When false (default), state is preserved between calls.`}},required:[`code`],additionalProperties:!1},{validate:e=>{let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&(t.restart===void 0||typeof t.restart==`boolean`)?{success:!0,value:{code:t.code,restart:t.restart}}:{success:!1,error:/* @__PURE__ */ TypeError("run_code takes a string `code` and an optional boolean `restart`.")}}}),execute:async(e,t)=>{let n=await this.enqueue(e,t);return n instanceof St?n:{result:n}},toModelOutput:({output:e})=>{if(e instanceof St)throw e.error;if(typeof e==`object`&&e&&Object.keys(e).length===1&&`sandboxFailure`in e&&e.sandboxFailure===!0)return{type:`text`,value:`Agent Sandboxes infrastructure failed. This call did not complete; a developer must fix the sandbox before a new run.`};let{result:t}=e;return typeof t==`string`?{type:`text`,value:t}:{type:`json`,value:t}}})}}async close(){return this.closing??=this.shutDown(),this.closing}async closeWhenDone(e){return Promise.resolve(e.finishReason).then(async()=>this.close(),async()=>this.close())}async[Symbol.asyncDispose](){return this.close()}async shutDown(){this.clearIdleTimer(),this.current?.stop(`closed`),await this.queue,await this.releaseSession();let e=this.options.sandboxes===void 0?this.poolPromise:void 0;this.poolPromise=void 0,e!==void 0&&await(await e).close()}async enqueue(e,t){let n=this.queue.then(async()=>this.run(e,t));return this.queue=n.catch(()=>void 0),n}closedError(){return/* @__PURE__ */ Error(`Code mode is closed, so this code did not run.`)}stoppedError(e,t){if(e.stopped===`deadline`)return/* @__PURE__ */ Error(`The code ran longer than its ${It(this.limits)}-second time limit, counting time spent waiting on tools, and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and make the code do less work per call.`+e.startedCalls());let n=e.stopped===`aborted`?`The agent run was aborted`:`Code mode was closed`;return t?/* @__PURE__ */ Error(`${n} while this code ran, so tool calls it had not started were stopped.${e.startedCalls()}`):e.stopped===`aborted`?/* @__PURE__ */ Error(`${n}, so this code did not run.`):this.closedError()}async run({code:e,restart:t},n){if(this.closing!==void 0)throw this.closedError();if(this.failure!==void 0)return this.failure;n.abortSignal?.throwIfAborted();let r=X(e);if(r>this.limits.codeBytes)throw Error(`The code is ${String(r)} bytes, over the ${String(this.limits.codeBytes)}-byte limit for one snippet. Send less code per call; variables and functions from earlier calls are still defined.`);let i=new Lt(n.toolCallId,this.limits);this.current=i;let a=()=>{i.stop(`aborted`)};n.abortSignal?.addEventListener(`abort`,a,{once:!0}),this.clearIdleTimer();let o=this.expired;this.expired=!1;try{return t===!0&&await this.releaseSession(),await this.feed(e,i,n)}catch(e){throw o&&e instanceof Error?/* @__PURE__ */ Error(`${e.message}\n\nThe sandbox session had no run_code call for ${String(this.idleTimeout/1e3)} seconds and was replaced, so variables, imports and definitions from earlier calls are gone.`):e}finally{i.stop(`finished`),n.abortSignal?.removeEventListener(`abort`,a),this.current=void 0,this.startIdleTimer()}}async failSandbox(e){this.failure=new St(e);try{await this.options.onError?.({error:e})}catch{return this.failure}return this.failure}async feed(e,t,n,r=!1){let i;try{i=await this.session(t.signal)}catch(e){if(t.stopped!==void 0)throw this.stoppedError(t,!1);return this.failSandbox(e)}if(t.stopped!==void 0)throw t.stopped===`deadline`&&await this.releaseSession(),this.stoppedError(t,!1);let a,u,d,f=!1,p=!1;r||t.start();let ee=this.options.typeCheck===`off`||this.options.typeCheck!==`every-snippet`&&this.passedTypeCheck,m=i.feedRun(e,{externalLookup:this.externalLookup(t,n),printCallback:t.printed.write,os:this.osCallback(t),skipTypeCheck:ee}).then(e=>({ok:!0,result:e}),e=>({ok:!1,error:e})),h=await Promise.race([m,Nt(t.signal)]);h===`stopped`?(p=!0,this.abandonSession(i,m)):h.ok?(a=h.result,f=!0,this.passedTypeCheck=!0):(u=h.error,d=wt(u),this.passedTypeCheck||=!(d instanceof l||d instanceof c));let g=t.reason();if(g===`closed`||g===`aborted`)throw this.stoppedError(t,!0);if(g===`deadline`){p||await this.releaseSession();let e=d instanceof o?`Runtime error:\n${t.printed.prependTo(this.cut(d.display(`traceback`)))}\n\n`:``;throw Error(e+this.stoppedError(t,!0).message)}if(!f){if(d instanceof s&&!r&&t.callCount===0)return await this.releaseSession(),t.printed=new Ft(this.limits.outputBytes),this.feed(e,t,n,!0);t.stop(`finished`);let i=this.describeFailure(d,t);if((i===void 0||i.reset)&&await this.releaseSession(),i===void 0)return this.failSandbox(u);throw Error(i.message+(r?`\n\n${Vt}`:``),{cause:u})}let _=this.shapeResult(a,t,r);return r?{result:_,sessionReset:Vt}:_}shapeResult(e,t,n){let{outputBytes:r}=this.limits,i=/* @__PURE__ */ Error(`The result is more than ${String(r)} bytes of JSON, over the limit for what one snippet returns. The code ran and its variables are still defined, so return a smaller value from them, such as a summary or fewer fields.`+(n?`\n\n${Vt}`:``)),a;try{a=_t(gt(e,r))}catch(e){throw e instanceof Y?i:e}if(X(JSON.stringify(a??null))>r)throw i;let o=t.printed.output;return o===``?a??{}:a==null?{output:o}:{output:o,result:a}}cut(e){return vt(e,this.limits.outputBytes)}describeFailure(e,t){let{printed:i}=t;if(e instanceof c)return{message:`Syntax error in code:\n${i.prependTo(this.cut(e.display(`traceback`)))}`,reset:!1};if(e instanceof l)return{message:`Type error in code:\n${i.prependTo(this.cut(e.display()))}`,reset:!1};if(e instanceof o){let n=`Runtime error:\n${i.prependTo(this.cut(e.display(`traceback`)))}`,r=e.display(`msg`);(t.budgetExhausted||zt.some(e=>r.includes(e)))&&(n+=t.startedCalls());let a=Ht(e),o=Ut(e);a&&(n+=`\n\n${Bt}`),o&&(n+=`
|
|
22
22
|
|
|
23
|
-
The code ran
|
|
23
|
+
The code ran out of memory and was stopped, so the session was reset. Re-run any imports, recreate any state you need, and keep less data in memory at once.`);let s=a||o;return e.exception.typeName===`RuntimeError`&&Rt.test(r)&&(n+=`
|
|
24
24
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
If this reports the sandbox session's suspension limit, its cumulative host-interaction budget is exhausted. Further tool calls, OS callbacks, name lookups and future resolutions need a fresh session; revising the snippet does not replenish this budget. Pure Python using existing state may still work. Pass \`restart: true\` to start a fresh session; that discards all REPL variables, imports and definitions. Check the calls already started before continuing, and do not replay completed side effects.`),{message:n,reset:s}}if(e instanceof n)return{message:`The code crashed the sandbox worker and the session was reset. Revise the code and try again.${t.startedCalls()}`,reset:!0};let s=e instanceof Error?`${e.name}: ${e.message}`:String(e);return{message:`Code execution failed and the session was reset. Re-run any imports, recreate any state you need, and try again.
|
|
28
|
-
${o.prependTo(this.cut(s))}${t.startedCalls()}`,reset:!0}}osCallback(e){return async(t,n)=>{if(t!==`time.sleep`&&t!==`asyncio.sleep`)return o;let r=Number(n[0]),i=Math.max(0,(e.deadline-Date.now())/1e3);if(e.stopped!==void 0||r>i)throw Q(`TimeoutError`,`sleeping ${String(r)}s would exceed the ${At(this.limits)}s this code may run; ${i.toFixed(1)}s left`);return await $(d(r*1e3,void 0,{ref:!1}),e.signal),null}}externalLookup(e,t){return Object.fromEntries(Object.keys(this.options.tools).map(n=>{let r=this.pythonNames.get(n)??n;return[r,async(...i)=>this.callTool(n,r,i,e,t)]}))}async callTool(e,t,n,r,i){let{limits:a}=this,o=this.options.tools[e];if(r.stopped!==void 0)throw r.signal.reason;if(r.callCount>=a.toolCalls)throw r.budgetExhausted=!0,Q(`RuntimeError`,`Code mode allows ${String(a.toolCalls)} nested tool calls per \`run_code\` call and this snippet asked for more. Call fewer tools, for example by filtering the inputs first, or split the work across several \`run_code\` calls.`);r.callCount+=1;let c=`${r.id}__${String(r.callCount)}`,l=St(xt(t,n,a.toolInputBytes),this.schemaArgNames.get(t));if(X(JSON.stringify(l))>a.toolInputBytes)throw Q(`ValueError`,Ct(t,a.toolInputBytes));let d=await $(Promise.resolve(s(o.inputSchema).validate?.(l)),r.signal);if(d!==void 0&&!d.success)throw Q(`ValueError`,`Invalid arguments for ${t}(): ${bt(d.error)}`);let p=d===void 0?l:d.value,m=this.options.context,h=m!==void 0&&Object.hasOwn(m,e)?m[e]:void 0;if(o.contextSchema!==void 0){let t=await $(Promise.resolve(s(o.contextSchema).validate?.(h)),r.signal);if(t!==void 0&&!t.success)throw Q(`ValueError`,`Invalid context for tool "${e}": ${bt(t.error)}`);h=t===void 0?h:t.value}let g={toolName:e,inputPreview:Z(p),status:`running`},_=await $(f(this.options.approval,{tools:this.options.tools,toolsContext:this.options.context??{},runtimeContext:this.options.runtimeContext},{toolName:e,toolCallId:c,input:p,messages:i.messages,toolContext:h,tool:o}),r.signal);if(!_.approved){g.status=`denied`,r.calls.push(g);let t=_.reason===void 0?``:` ${_.reason}`;throw Q(`RuntimeError`,_.needsUser?`Tool '${e}' needs a person to approve it, and code mode cannot ask for approval from inside the sandbox.${t}`:`Tool '${e}' call denied:${t===``?` denied by the approval policy`:t}`)}await this.slots.acquire(r.signal);let v=!1,y=()=>{v||(v=!0,this.slots.release())},b={};r.calls.push(g);try{return await u.span(`run_code called {tool_name}`,{tool_name:e,tool_call_id:c,arguments:p},{},async()=>{let n;try{r.signal.throwIfAborted();let e=this.execute(o,p,{...i,toolCallId:c,context:h,abortSignal:r.signal});b.running=e,e.then(y,y),n=await $(e,r.signal)}catch(t){throw g.status=`failed`,r.stopped===void 0?this.replaceToolError(t,{toolName:e,toolCallId:c,input:p}):t}g.status=`returned`;let s;try{s=Tt(n)}catch(e){let n=e instanceof RangeError?`it is nested too deeply or contains itself`:vt(e);throw g.outputPreview=`<not JSON>`,Q(`ValueError`,`${t}() returned a value that cannot be sent to the sandbox as JSON: ${n}. The call ran, so do not repeat it to get the same result.`)}let l=X(s);if(l>a.toolOutputBytes)throw g.outputPreview=`<${String(l)} bytes, over the limit>`,Q(`ValueError`,`${t}() returned ${String(l)} bytes of JSON, over the ${String(a.toolOutputBytes)}-byte limit for one call. The call ran, so do not repeat it to get the same result.`);let u=JSON.parse(s);return g.outputPreview=Z(u),u})}finally{b.running===void 0&&y()}}async execute(e,t,n){let r=e.execute,i=r(t,n);if(Et(i)){let e;for await(let t of i)e=t;return e}return await i}replaceToolError(e,t){let n=this.options.onToolError?.(e,t);return n instanceof Error?n:typeof n==`string`?Error(n):e instanceof Error?e:Error(String(e))}async pool(){let{sandboxes:e}=this.options;this.poolPromise??=e===void 0?t({requestTimeout:this.limits.timeout/1e3+10}):Promise.resolve(e);try{return await this.poolPromise}catch(e){throw this.poolPromise=void 0,e}}async session(){this.sessionPromise??=this.checkout();try{return await this.sessionPromise}catch(e){throw this.sessionPromise=void 0,e}}async checkout(){let t=this.options.typeCheck!==`off`;return e.with(this.traceContext,async()=>(await this.pool()).checkout({ephemeral:!0,scriptName:`run_code.py`,typeCheck:t,...t?{typeCheckStubs:this.typeCheckStubs}:{},limits:{maxFeedDurationSecs:this.limits.timeout/1e3,maxMemory:this.limits.memory,maxSuspensions:this.limits.suspensions},osPolicy:{datetime:`call_host`,sleep:`call_host`,randomStart:`call_host`}}))}abandonSession(e,t){this.sessionPromise=void 0,this.passedTypeCheck=!1,t.then(async()=>e.close()).catch(()=>void 0)}async releaseSession(){let e=this.sessionPromise;if(this.sessionPromise=void 0,this.passedTypeCheck=!1,e!==void 0)try{await(await e).close()}catch{}}startIdleTimer(){this.closing===void 0&&this.sessionPromise!==void 0&&Number.isFinite(this.idleTimeout)&&(this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.current===void 0&&this.closing===void 0&&(this.expired=!0,this.releaseSession().catch(()=>void 0))},Math.min(this.idleTimeout,2**31-1)),this.idleTimer.unref())}clearIdleTimer(){clearTimeout(this.idleTimer),this.idleTimer=void 0}};export{_t as codeMode};
|
|
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};
|