@lunora/agent 1.0.0-alpha.2 → 1.0.0-alpha.200

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.
Files changed (95) hide show
  1. package/dist/channels.d.mts +52 -33
  2. package/dist/channels.d.ts +52 -33
  3. package/dist/channels.mjs +1 -181
  4. package/dist/component.d.mts +97 -70
  5. package/dist/component.d.ts +97 -70
  6. package/dist/component.mjs +2 -407
  7. package/dist/inbound.d.mts +24 -22
  8. package/dist/inbound.d.ts +24 -22
  9. package/dist/inbound.mjs +1 -32
  10. package/dist/index.d.mts +576 -497
  11. package/dist/index.d.ts +576 -497
  12. package/dist/index.mjs +1 -18
  13. package/dist/naming.d.mts +18 -22
  14. package/dist/naming.d.ts +18 -22
  15. package/dist/naming.mjs +1 -8
  16. package/dist/packem_shared/AGENT_MODULE-M4D1EejI.mjs +1 -0
  17. package/dist/packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-wjR1QXHX-BHqkRjkN.mjs +1 -0
  18. package/dist/packem_shared/VoiceSessionDO-CB_yuzWV.mjs +1 -0
  19. package/dist/packem_shared/adaptMcpResult-CVlq-_TO.mjs +2 -0
  20. package/dist/packem_shared/agent-ai-CxEYOyOu.mjs +1 -0
  21. package/dist/packem_shared/agent-loop-DyJWnyiT.mjs +3 -0
  22. package/dist/packem_shared/agentAsTool-1Gwq45M3.mjs +1 -0
  23. package/dist/packem_shared/braintrustTelemetry-Byne8uPK.mjs +1 -0
  24. package/dist/packem_shared/branch-marker-boZ00zmk.mjs +1 -0
  25. package/dist/packem_shared/buildModelMessages-Y4tGo1T9.mjs +5 -0
  26. package/dist/packem_shared/codeTool-BQb-K3my.mjs +1 -0
  27. package/dist/packem_shared/collectAgenticMemoryTools-BeMWT2qt.mjs +1 -0
  28. package/dist/packem_shared/combineTelemetry-DgE9W9G8.mjs +1 -0
  29. package/dist/packem_shared/common-CJSjtsfv.mjs +1 -0
  30. package/dist/packem_shared/compileAgentWorkflow-C287O2ux.mjs +1 -0
  31. package/dist/packem_shared/component-shared-G8ngerkU.mjs +1 -0
  32. package/dist/packem_shared/consoleTelemetry-BZY3Y-Ly.mjs +1 -0
  33. package/dist/packem_shared/createAgentContext-BxDMNWNG.mjs +1 -0
  34. package/dist/packem_shared/createAgentGenerate-EEFNvpS5.mjs +3 -0
  35. package/dist/packem_shared/defineAgent-CjxGfOg7.mjs +3 -0
  36. package/dist/packem_shared/defineSkill-DGGvDWNq.mjs +1 -0
  37. package/dist/packem_shared/fnv1a-BNN96GYb.mjs +1 -0
  38. package/dist/packem_shared/functionTool-D3CP4f8-.mjs +1 -0
  39. package/dist/packem_shared/in-flight-calls-GH1A_1P3.mjs +1 -0
  40. package/dist/packem_shared/jsCodeTool-BLOvjXGF.mjs +18 -0
  41. package/dist/packem_shared/normalizeEntityName-k3fjicAG.mjs +2 -0
  42. package/dist/packem_shared/otlpTelemetry-ByqrB-72.mjs +1 -0
  43. package/dist/packem_shared/positive-integer-ztHqqpBk.mjs +1 -0
  44. package/dist/packem_shared/runAgentLoop-BIjYgCLE.mjs +1 -0
  45. package/dist/packem_shared/runVoiceTurn-CtKjHnfU.mjs +1 -0
  46. package/dist/packem_shared/sandbox-budgets-DDvj4Orr.mjs +1 -0
  47. package/dist/packem_shared/sandboxComponent-Du0yENEO.mjs +7 -0
  48. package/dist/packem_shared/sentryTelemetry-BHeydiAB.mjs +1 -0
  49. package/dist/packem_shared/tool-output-Cmk3JWMG.mjs +1 -0
  50. package/dist/packem_shared/types.d-CbYtFBw9.d.mts +1376 -0
  51. package/dist/packem_shared/types.d-CbYtFBw9.d.ts +1376 -0
  52. package/dist/packem_shared/voice-turn-DZNbOsWB.mjs +1 -0
  53. package/dist/packem_shared/webSearchTool-BptEsfd9.mjs +1 -0
  54. package/dist/packem_shared/workflow-binding-Dm9hBzx_.mjs +1 -0
  55. package/dist/reply.d.mts +40 -0
  56. package/dist/reply.d.ts +40 -0
  57. package/dist/reply.mjs +1 -0
  58. package/dist/sandbox.d.mts +269 -124
  59. package/dist/sandbox.d.ts +269 -124
  60. package/dist/sandbox.mjs +1 -109
  61. package/dist/skill-markdown.d.mts +36 -0
  62. package/dist/skill-markdown.d.ts +36 -0
  63. package/dist/skill-markdown.mjs +1 -0
  64. package/dist/telemetry/index.d.mts +314 -114
  65. package/dist/telemetry/index.d.ts +314 -114
  66. package/dist/telemetry/index.mjs +1 -4
  67. package/package.json +18 -9
  68. package/dist/packem_shared/AGENT_MODULE-Dnt_-AAT.mjs +0 -24
  69. package/dist/packem_shared/VoiceSessionDO-DLoXsHGF.mjs +0 -297
  70. package/dist/packem_shared/adaptMcpResult-wtNMvLoP.mjs +0 -65
  71. package/dist/packem_shared/agentAsTool-Dt8NlU6k.mjs +0 -94
  72. package/dist/packem_shared/base64-BVwtgRJV.mjs +0 -18
  73. package/dist/packem_shared/braintrustTelemetry-wuGDErob.mjs +0 -47
  74. package/dist/packem_shared/buildModelMessages-BWFigaoo.mjs +0 -69
  75. package/dist/packem_shared/codeTool-CjgJOC9t.mjs +0 -122
  76. package/dist/packem_shared/collectAgenticMemoryTools-QrzpV-WX.mjs +0 -97
  77. package/dist/packem_shared/combineTelemetry-DCyaaWAI.mjs +0 -43
  78. package/dist/packem_shared/common-DAeFCot5.mjs +0 -61
  79. package/dist/packem_shared/compileAgentWorkflow-BxJjHgtD.mjs +0 -55
  80. package/dist/packem_shared/consoleTelemetry-z2MiP1jt.mjs +0 -93
  81. package/dist/packem_shared/createAgentContext-4xJGXNR4.mjs +0 -50
  82. package/dist/packem_shared/createAgentGenerate-BQv9YJ01.mjs +0 -192
  83. package/dist/packem_shared/createDispatchRunner-DSbp_dph-ZHTtxy3f.mjs +0 -69
  84. package/dist/packem_shared/defineAgent-D6maSbVc.mjs +0 -148
  85. package/dist/packem_shared/defineSkill-Ctf_S-rz.mjs +0 -22
  86. package/dist/packem_shared/functionTool-D6lCa2jB.mjs +0 -20
  87. package/dist/packem_shared/graph-component-aoUwO-f0.mjs +0 -216
  88. package/dist/packem_shared/memory-D4FPcBsX.mjs +0 -12
  89. package/dist/packem_shared/normalizeEntityName-CyEEWFkR.mjs +0 -3
  90. package/dist/packem_shared/runAgentLoop-Dhg4ZNvw.mjs +0 -493
  91. package/dist/packem_shared/runVoiceTurn-LnqLvCRR.mjs +0 -211
  92. package/dist/packem_shared/sandboxComponent-DR3pTwBL.mjs +0 -194
  93. package/dist/packem_shared/sentryTelemetry-CgqFJyLO.mjs +0 -36
  94. package/dist/packem_shared/types.d-BhJFTvz_.d.mts +0 -1114
  95. package/dist/packem_shared/types.d-BhJFTvz_.d.ts +0 -1114
@@ -0,0 +1 @@
1
+ import{c as z}from"./agent-loop-DyJWnyiT.mjs";import{buildModelMessages as G}from"./buildModelMessages-Y4tGo1T9.mjs";import{toFunctionReference as A}from"./AGENT_MODULE-M4D1EejI.mjs";const ot=t=>{let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e)},P=t=>{const e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.codePointAt(r)??0;return n},C=t=>{const e=t.replaceAll("-","+").replaceAll("_","/"),n=e+"=".repeat((4-e.length%4)%4);return P(n)},D=new TextDecoder;new TextEncoder;const N="=",Q=t=>{if(t)try{const e=t[0]==="{"?t:D.decode(C(t)),n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}},ct=t=>{if(t){if(!t.startsWith(N))return t;try{return D.decode(C(t.slice(N.length)))}catch{return}}},dt=t=>{const e=Number(t);return Number.isFinite(e)&&e>0?e:void 0},ut=t=>typeof t=="number"&&Date.now()>=t,yt=t=>{try{t.send(JSON.stringify({code:"TOKEN_EXPIRED",error:{code:"TOKEN_EXPIRED",message:"authentication token expired"},message:"authentication token expired",type:"error"})),t.close?.(4001,"token_expired")}catch{}},Y=16e3,Z=1,tt=16,M=/[.!?]\s/u,et=/\s/u,nt=async function*(t){if(t instanceof Uint8Array){yield t;return}if(t instanceof ReadableStream){const e=t.getReader();try{for(;;){const{done:n,value:r}=await e.read();if(n)break;yield r}}finally{e.releaseLock()}return}yield*t},ft=(t,e=Y,n=Z,r=tt)=>{const i=n*r/8,l=e*i,m=new ArrayBuffer(44+t.byteLength),s=new DataView(m),u=(p,b)=>{for(let d=0;d<b.length;d+=1)s.setUint8(p+d,b.codePointAt(d)??0)};u(0,"RIFF"),s.setUint32(4,36+t.byteLength,!0),u(8,"WAVE"),u(12,"fmt "),s.setUint32(16,16,!0),s.setUint16(20,1,!0),s.setUint16(22,n,!0),s.setUint32(24,e,!0),s.setUint32(28,l,!0),s.setUint16(32,i,!0),s.setUint16(34,r,!0),u(36,"data"),s.setUint32(40,t.byteLength,!0);const a=new Uint8Array(m);return a.set(t,44),a},rt=t=>{const e=[];let n=t,r=M.exec(n);for(;r;){let i=r.index+1;for(;i<n.length&&et.test(n[i]??"");)i+=1;const l=n.slice(0,i).trim();l.length>0&&e.push(l),n=n.slice(i),r=M.exec(n)}return{rest:n,sentences:e}},lt=async t=>{const{agent:e,compact:n,connectionId:r,env:i,exportName:l,owner:m,paths:s,pcm:u,run:a,send:p,sendAudio:b,signal:d,streamGenerate:H,synthesize:L,text:B,threadKey:o,transcribe:F,turn:U,waitForDrain:O}=t,h=()=>d.aborted,v=A(s.appendMessage),$=A(s.ensureThread),K=A(s.listMessages),x=A(s.patchThread);await a($,{agent:l,key:o,...e.initialState===void 0?{}:{initialState:e.initialState},...m===void 0?{}:{owner:m}});try{const y=(B??(u?await F(u):"")).trim();if(y.length===0)return await a(x,{key:o,status:"idle"}),{assistantText:"",interrupted:!1,userText:""};p({text:y,type:"user_transcript"}),await a(v,{content:y,messageKey:`voice:${r}:${String(U)}:user`,role:"user",threadKey:o}),await a(x,{key:o,status:"running"});const _=typeof e.instructions=="function"?e.instructions({env:i,input:y,threadKey:o}):e.instructions,j=await a(K,{key:o}),{history:W,summary:I}=await z({agent:e,compact:n,env:i},j),V=G({history:W,..._===void 0?{}:{instructions:_},...I===void 0?{}:{summary:I}});let g="",E="",k=Promise.resolve();const X=async c=>{if(h()||c.length===0)return;let w=!1;try{for await(const f of nt(await L(c,d))){if(h()||(await O?.(),h()))break;b(f),w=!0}}catch(f){p({message:f instanceof Error?f.message:String(f),type:"error"})}w&&(E=E.length>0?`${E} ${c}`:c)},R=c=>{k=k.then(async()=>X(c))},J=await H({messages:V,signal:d},c=>{if(h())return;p({text:c,type:"assistant_delta"}),g+=c;const{rest:w,sentences:f}=rt(g);g=w;for(const q of f)R(q)});!h()&&g.trim().length>0&&R(g.trim()),g="",await k;const S=h(),T=S?E:J.text;return await a(v,{content:T,messageKey:`voice:${r}:${String(U)}:assistant`,role:"assistant",threadKey:o}),await a(x,{key:o,status:"idle"}),p(S?{type:"interrupted"}:{text:T,type:"assistant_done"}),{assistantText:T,interrupted:S,userText:y}}catch(y){throw await a(x,{key:o,status:"idle"}),y}},pt=t=>Q(t),ht=t=>{if(typeof t=="object"&&t!==null&&"text"in t){const{text:e}=t;return typeof e=="string"?e:""}return""},gt=t=>{if(t instanceof Uint8Array||t instanceof ReadableStream)return t;if(t instanceof Response&&t.body)return t.body;if(typeof t=="object"&&t!==null&&"audio"in t){const{audio:e}=t;if(typeof e=="string")return P(e);if(e instanceof ReadableStream||e instanceof Uint8Array)return e}return new Uint8Array(0)};export{dt as a,yt as b,ft as c,ct as d,ht as e,gt as f,nt as g,ut as i,pt as p,lt as r,ot as t};
@@ -0,0 +1 @@
1
+ import{LunoraError as c}from"@lunora/errors";import{jsonSchema as h}from"ai";import{r as u}from"./agent-ai-CxEYOyOu.mjs";const l=5,d="Search the web for current information. Returns up to a handful of results, each with a url, a title and (when the provider has one) a description. Use it for facts that may have changed after your training data, then cite the urls you relied on.",m=h({properties:{query:{description:"The search query, 1–1024 characters.",maxLength:1024,minLength:1,type:"string"}},required:["query"],type:"object"}),E=new Set(["BAD_REQUEST","INTERNAL","NOT_IMPLEMENTED"]),T=(t={})=>{const{description:a=d,limit:o=l,...n}=t;return{description:a,execute:async(s,i)=>{const r=u(i.env);if(!r)return"Web search is unavailable: this Worker has no `AI` binding. Answer from what you already know, and say that you could not search.";try{return(await r.websearch(s.query,{...n,limit:o})).items}catch(e){if(e instanceof c&&E.has(e.code))return`Web search failed: ${e.message}`;throw e}},inputSchema:m,isLunoraAgentTool:!0}};export{T as webSearchTool};
@@ -0,0 +1 @@
1
+ const l=(e,r,o)=>e?.[o]??r?.[o],f=(e,r,o,t)=>{const n=l(e,r,o);if(!(typeof n!="object"||n===null))return t.every(i=>typeof n[i]=="function")?n:void 0};export{f as r};
@@ -0,0 +1,40 @@
1
+ import { Mailer } from '@lunora/mail';
2
+ import { InboundEmail } from '@lunora/mail/inbound';
3
+ import { a as AgentReplyRef } from "./packem_shared/types.d-CbYtFBw9.mjs";
4
+ import 'ai';
5
+ /** The email arm of {@link AgentReplyRef}, narrowed for the helpers below. */
6
+ type EmailReplyRef = Extract<AgentReplyRef, {
7
+ channel: "email";
8
+ }>;
9
+ /**
10
+ * Capture a reply reference from an already-parsed inbound email — call it in
11
+ * an `onEmail` mapper and put the result on the run's `replyRef`.
12
+ *
13
+ * Returns `undefined` when the message carries no `Message-ID`: there is
14
+ * nothing to thread a reply against, and an unthreaded reply lands as a new
15
+ * conversation in the recipient's client, which is worse than not replying.
16
+ */
17
+ declare const captureEmailReplyRef: (email: InboundEmail) => EmailReplyRef | undefined;
18
+ /** RFC 5322 threading: append the replied-to id to any existing `References` chain. */
19
+ declare const buildReferences: (replyRef: EmailReplyRef) => string;
20
+ /** Subject + body of a reply. */
21
+ interface ReplyBody {
22
+ subject: string;
23
+ text: string;
24
+ }
25
+ /**
26
+ * Send a threaded reply through the app's own `@lunora/mail` mailer.
27
+ *
28
+ * The mailer is a parameter rather than something this module constructs: the
29
+ * app already configures one (API key or `send_email` binding), and passing it
30
+ * in keeps this module free of any runtime dependency on `@lunora/mail`.
31
+ *
32
+ * The reply goes to the original sender, from the mailer's configured default.
33
+ * An app running several aliases that wants the reply to come from whichever
34
+ * mailbox received the message passes `from: replyRef.to[0]` itself — a
35
+ * decision only the app can make.
36
+ */
37
+ declare const replyToEmail: (mailer: Mailer, replyRef: EmailReplyRef, body: ReplyBody) => Promise<{
38
+ id: string;
39
+ }>;
40
+ export { type EmailReplyRef, ReplyBody, buildReferences, captureEmailReplyRef, replyToEmail };
@@ -0,0 +1,40 @@
1
+ import { Mailer } from '@lunora/mail';
2
+ import { InboundEmail } from '@lunora/mail/inbound';
3
+ import { a as AgentReplyRef } from "./packem_shared/types.d-CbYtFBw9.js";
4
+ import 'ai';
5
+ /** The email arm of {@link AgentReplyRef}, narrowed for the helpers below. */
6
+ type EmailReplyRef = Extract<AgentReplyRef, {
7
+ channel: "email";
8
+ }>;
9
+ /**
10
+ * Capture a reply reference from an already-parsed inbound email — call it in
11
+ * an `onEmail` mapper and put the result on the run's `replyRef`.
12
+ *
13
+ * Returns `undefined` when the message carries no `Message-ID`: there is
14
+ * nothing to thread a reply against, and an unthreaded reply lands as a new
15
+ * conversation in the recipient's client, which is worse than not replying.
16
+ */
17
+ declare const captureEmailReplyRef: (email: InboundEmail) => EmailReplyRef | undefined;
18
+ /** RFC 5322 threading: append the replied-to id to any existing `References` chain. */
19
+ declare const buildReferences: (replyRef: EmailReplyRef) => string;
20
+ /** Subject + body of a reply. */
21
+ interface ReplyBody {
22
+ subject: string;
23
+ text: string;
24
+ }
25
+ /**
26
+ * Send a threaded reply through the app's own `@lunora/mail` mailer.
27
+ *
28
+ * The mailer is a parameter rather than something this module constructs: the
29
+ * app already configures one (API key or `send_email` binding), and passing it
30
+ * in keeps this module free of any runtime dependency on `@lunora/mail`.
31
+ *
32
+ * The reply goes to the original sender, from the mailer's configured default.
33
+ * An app running several aliases that wants the reply to come from whichever
34
+ * mailbox received the message passes `from: replyRef.to[0]` itself — a
35
+ * decision only the app can make.
36
+ */
37
+ declare const replyToEmail: (mailer: Mailer, replyRef: EmailReplyRef, body: ReplyBody) => Promise<{
38
+ id: string;
39
+ }>;
40
+ export { type EmailReplyRef, ReplyBody, buildReferences, captureEmailReplyRef, replyToEmail };
package/dist/reply.mjs ADDED
@@ -0,0 +1 @@
1
+ const t=e=>{if(e.messageId!==void 0)return{channel:"email",from:e.from,messageId:e.messageId,to:e.to,...e.references===void 0?{}:{references:e.references}}},n=e=>e.references===void 0?e.messageId:`${e.references} ${e.messageId}`,c=async(e,s,r)=>e.send({headers:{"In-Reply-To":s.messageId,References:n(s)},subject:r.subject,text:r.text,to:s.from});export{n as buildReferences,t as captureEmailReplyRef,c as replyToEmail};
@@ -1,11 +1,77 @@
1
- import { a as AgentToolContext, b as AgentToolDefinition } from "./packem_shared/types.d-BhJFTvz_.mjs";
1
+ import { c as AgentToolDefinition, d as AgentToolContext } from "./packem_shared/types.d-CbYtFBw9.mjs";
2
2
  import '@lunora/mail/inbound';
3
3
  import 'ai';
4
4
  /**
5
- * The model-provided input to a {@link browserTool} call — a discriminated
6
- * union on `op` so one tool exposes every headless-browser capability.
7
- * @experimental
8
- */
5
+ * The model-provided input to a {@link jsCodeTool} call.
6
+ * @experimental
7
+ */
8
+ interface JsCodeToolInput {
9
+ /** The body of an `async` function. Its `return` value is the result. */
10
+ code: string;
11
+ }
12
+ /**
13
+ * What a {@link jsCodeTool} call resolves to. `error` is set instead of `value`
14
+ * when the script threw, did not parse, returned something that is not JSON,
15
+ * or ran out of time.
16
+ * @experimental
17
+ */
18
+ interface JsCodeToolResult {
19
+ error?: string;
20
+ /** `console.*` output, one entry per call, at most {@link MAX_LOG_ENTRIES}. */
21
+ logs: string[];
22
+ value?: unknown;
23
+ }
24
+ /** Options for {@link jsCodeTool}. */
25
+ interface JsCodeToolOptions {
26
+ /** CPU budget per run, enforced by the loader. Default 1000 ms. */
27
+ cpuMs?: number;
28
+ /** Tool description shown to the model. */
29
+ description?: string;
30
+ }
31
+ /**
32
+ * A batteries-included agent tool that runs model-written JavaScript in a
33
+ * Worker Loader isolate — Cloudflare's Dynamic Workers, which celld implements
34
+ * too. The script gets no network (`globalOutbound: null`), no bindings, no
35
+ * tools and a CPU budget, so it is for computation: arithmetic, parsing,
36
+ * reshaping data the model already has. It returns the script's JSON result
37
+ * and its `console` output. A failure comes back as a result with `error` set,
38
+ * not a throw, so the durable step does not retry a script that will fail the
39
+ * same way again.
40
+ *
41
+ * Importing the tool makes codegen provision the `worker_loaders` binding
42
+ * (`LOADER`) and refuse a target whose matrix rates `workerLoaders`
43
+ * `unsupported`.
44
+ *
45
+ * ```ts
46
+ * import { defineAgent, jsCodeTool } from "@lunora/agent";
47
+ *
48
+ * export const analyst = defineAgent({
49
+ * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
50
+ * tools: { js: jsCodeTool() },
51
+ * });
52
+ * ```
53
+ * @experimental
54
+ */
55
+ declare const jsCodeTool: (options?: JsCodeToolOptions) => AgentToolDefinition<JsCodeToolInput, JsCodeToolResult>;
56
+ /**
57
+ * What a byte-returning browser op resolves to. The render is written to R2 and
58
+ * its key comes back — never the bytes, which would be truncated to the model's
59
+ * output cap and billed for nothing.
60
+ * @experimental
61
+ */
62
+ interface BrowserRenderResult {
63
+ /** Size of the stored object. */
64
+ bytes: number;
65
+ /** The absolute R2 key the render was written to. */
66
+ key: string;
67
+ /** The render's content type, e.g. `image/jpeg`. */
68
+ mediaType: string;
69
+ }
70
+ /**
71
+ * The model-provided input to a {@link browserTool} call — a discriminated
72
+ * union on `op` so one tool exposes every headless-browser capability.
73
+ * @experimental
74
+ */
9
75
  type BrowserToolInput = {
10
76
  fullPage?: boolean;
11
77
  op: "screenshot";
@@ -23,12 +89,12 @@ type BrowserToolInput = {
23
89
  url: string;
24
90
  };
25
91
  /**
26
- * The model-provided input to a {@link containerTool} call — a discriminated
27
- * union on `op`. `fetch` sends an HTTP request to the container; `exec` asks it
28
- * to run a command (routed as a POST to `/exec`, since the container surface
29
- * exposes no first-class exec RPC — the container app must serve that route).
30
- * @experimental
31
- */
92
+ * The model-provided input to a {@link containerTool} call — a discriminated
93
+ * union on `op`. `fetch` sends an HTTP request to the container; `exec` asks it
94
+ * to run a command (delegated to `ctx.containers.<name>.exec`, the first-class
95
+ * exec contract in `@lunora/container`; the container app serves its route).
96
+ * @experimental
97
+ */
32
98
  type ContainerToolInput = {
33
99
  args?: string[];
34
100
  command?: string;
@@ -40,28 +106,47 @@ type ContainerToolInput = {
40
106
  path: string;
41
107
  };
42
108
  /**
43
- * Author-supplied config for `browserTool`.
44
- * @experimental
45
- */
109
+ * Author-supplied config for `browserTool`.
110
+ * @experimental
111
+ */
46
112
  interface BrowserToolOptions {
113
+ /**
114
+ * R2 binding name the byte-returning ops (`screenshot`, `pdf`) write their
115
+ * render to. REQUIRED for those two: a render is billed, and a tool result
116
+ * is capped at `MAX_TOOL_OUTPUT_CHARS`, so base64 bytes inline would be
117
+ * truncated mid-string and unusable by the model — paid for and thrown
118
+ * away. With a bucket the op returns `{ bytes, key, mediaType }` and the
119
+ * app serves or post-processes the object by key. `content`/`scrape`
120
+ * return text and need no bucket; without one, a `screenshot`/`pdf` call is
121
+ * refused as a tool result (never dispatched) so nothing is billed.
122
+ */
123
+ bucket?: string;
47
124
  /** Override the model-facing description (what the tool does). */
48
125
  description?: string;
49
126
  /**
50
- * Gate a call behind a human approval. Defaults to **unattended** (no gate),
51
- * matching the AI SDK. `browserTool` fetches a model-chosen `url` with no
52
- * allowlist, so it is an SSRF surface: a prompt-injected model can point it at
53
- * an internal/link-local address and read the response back into context. Pass
54
- * a boolean or a predicate to gate it (evaluated from replay-stable input, so
55
- * keep it deterministic).
56
- */
127
+ * Gate a call behind a human approval. Defaults to **unattended** (no gate),
128
+ * matching the AI SDK. `browserTool` fetches a model-chosen `url` with no
129
+ * allowlist, so it is an SSRF surface: a prompt-injected model can point it at
130
+ * an internal/link-local address and read the response back into context. Pass
131
+ * a boolean or a predicate to gate it (evaluated from replay-stable input, so
132
+ * keep it deterministic).
133
+ */
57
134
  needsApproval?: ((input: BrowserToolInput) => boolean) | boolean;
135
+ /**
136
+ * Key prefix inside {@link BrowserToolOptions.bucket} that renders are
137
+ * written under, isolating them from the rest of the bucket. Default: the
138
+ * bucket root. Each render lands at `<root>/<threadKey>/<toolCallId>.<ext>`
139
+ * — derived only from replay-stable identifiers, so a retried step
140
+ * overwrites its own object rather than accumulating one per attempt.
141
+ */
142
+ root?: string;
58
143
  }
59
144
  /**
60
- * The model-provided input to a {@link fsTool} call — a discriminated union on
61
- * `op` over an R2-backed virtual filesystem. Paths are relative to the tool's
62
- * pinned `root`; a `..` that escapes the root is rejected server-side.
63
- * @experimental
64
- */
145
+ * The model-provided input to a {@link fsTool} call — a discriminated union on
146
+ * `op` over an R2-backed virtual filesystem. Paths are relative to the tool's
147
+ * pinned `root`; a `..` that escapes the root is rejected server-side.
148
+ * @experimental
149
+ */
65
150
  type FsToolInput = {
66
151
  op: "ls";
67
152
  path?: string;
@@ -80,121 +165,181 @@ type FsToolInput = {
80
165
  path: string;
81
166
  };
82
167
  /**
83
- * Author-supplied config for `fsTool`.
84
- * @experimental
85
- */
168
+ * Author-supplied config for `fsTool`.
169
+ * @experimental
170
+ */
86
171
  interface FsToolOptions {
87
172
  /** Override the model-facing description (what the tool does). */
88
173
  description?: string;
89
174
  /**
90
- * Gate a call behind a human approval. Defaults to gating the WRITING ops
91
- * (`write`, `rm`) — a prompt-injected model shouldn't silently overwrite or
92
- * delete the sandbox — while `ls`/`read`/`stat` run unattended. Pass a boolean
93
- * or a predicate (evaluated from replay-stable input, so keep it deterministic).
94
- */
175
+ * Gate a call behind a human approval. Defaults to gating the WRITING ops
176
+ * (`write`, `rm`) — a prompt-injected model shouldn't silently overwrite or
177
+ * delete the sandbox — while `ls`/`read`/`stat` run unattended. Pass a boolean
178
+ * or a predicate (evaluated from replay-stable input, so keep it deterministic).
179
+ */
95
180
  needsApproval?: ((input: FsToolInput) => boolean) | boolean;
96
181
  /**
97
- * The key prefix every path is scoped under, isolating this tool's files from
98
- * the rest of the bucket. Either a fixed string (e.g. `"agents/support"`) or a
99
- * function of the tool context — return `` `agents/${ctx.threadKey}` `` (or an
100
- * owner-derived prefix) to give each run/user its OWN namespace in a
101
- * multi-tenant agent. Default: the bucket root (shared — set a root for
102
- * multi-tenant use). The server rejects any `..` that would escape it.
103
- */
182
+ * The key prefix every path is scoped under, isolating this tool's files from
183
+ * the rest of the bucket. Either a fixed string (e.g. `"agents/support"`) or a
184
+ * function of the tool context — return `` `agents/${ctx.threadKey}` `` (or an
185
+ * owner-derived prefix) to give each run/user its OWN namespace in a
186
+ * multi-tenant agent. Default: the bucket root (shared — set a root for
187
+ * multi-tenant use). The server rejects any `..` that would escape it.
188
+ */
104
189
  root?: ((context: AgentToolContext) => string) | string;
105
190
  }
106
191
  /**
107
- * Author-supplied config for `containerTool`.
108
- * @experimental
109
- */
192
+ * Author-supplied config for `containerFsTool`.
193
+ * @experimental
194
+ */
195
+ interface ContainerFsToolOptions {
196
+ /** Override the model-facing description (what the tool does). */
197
+ description?: string;
198
+ /**
199
+ * Gate a call behind a human approval. Defaults to gating the writing ops
200
+ * (`write`, `rm`), as `fsTool` does. Pass a boolean or a predicate
201
+ * (evaluated from replay-stable input, so keep it deterministic).
202
+ */
203
+ needsApproval?: ((input: FsToolInput) => boolean) | boolean;
204
+ /**
205
+ * The absolute directory inside the container every path is scoped under.
206
+ * Default `"/workspace"`. The dispatcher rejects any `..` that would escape it.
207
+ */
208
+ root?: string;
209
+ }
210
+ /**
211
+ * Author-supplied config for `containerTool`.
212
+ * @experimental
213
+ */
110
214
  interface ContainerToolOptions {
111
215
  /** Override the model-facing description (what the tool does). */
112
216
  description?: string;
113
217
  /**
114
- * Gate a call behind a human approval. Defaults to gating any command
115
- * execution: an `exec`, AND a `fetch` whose path resolves to the privileged
116
- * `/exec` route (both reach the same command-execution path in the container,
117
- * so gating on the `op` name alone would let a `fetch` to `/exec` run a
118
- * command unattended). A plain `fetch` to any other route runs unattended.
119
- * Pass a boolean or your own predicate to change that. Evaluated from
120
- * replay-stable input, so keep it deterministic.
121
- */
218
+ * Gate a call behind a human approval. Defaults to gating any command
219
+ * execution — an `exec` — plus any `fetch` using a non-idempotent method
220
+ * (POST/PUT/PATCH/DELETE), so a prompt-injected model cannot reach some
221
+ * other mutating route unattended. A read-only `fetch` runs unattended. The
222
+ * exec route itself needs no special case: `@lunora/container` reserves
223
+ * `/__lunora/*` and refuses a `fetch` into it. Pass a boolean or your own
224
+ * predicate to change that. Evaluated from replay-stable input, so keep it
225
+ * deterministic.
226
+ */
122
227
  needsApproval?: ((input: ContainerToolInput) => boolean) | boolean;
123
228
  }
124
229
  /**
125
- * A batteries-included agent tool that drives Cloudflare Browser Rendering. One
126
- * tool exposes every browser op (screenshot / pdf / content / scrape); the model
127
- * picks via `op`. The call dispatches to the auto-registered `sandbox:invoke`
128
- * action — which runs on an action ctx carrying `ctx.browser`. Importing the tool
129
- * makes codegen register the dispatcher and provision the `BROWSER` binding; like
130
- * any `ctx.browser` user, the app still supplies a `config.browser` thunk
131
- * (`createBrowser({ binding: env.BROWSER, launch })` with the optional
132
- * `@cloudflare/playwright` `launch` peer) to `createShardDO()` — codegen never
133
- * injects that peer, so the browser op throws a directed error until it is wired.
134
- *
135
- * Security: the model chooses the `url` with no allowlist, so this is an SSRF
136
- * surface — pass `opts.needsApproval` to gate calls a prompt-injected model
137
- * could aim at internal/link-local endpoints.
138
- *
139
- * ```ts
140
- * import { browserTool, defineAgent } from "@lunora/agent/sandbox";
141
- *
142
- * export const researcher = defineAgent({
143
- * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
144
- * tools: { browser: browserTool() },
145
- * });
146
- * ```
147
- * @experimental
148
- */
149
- declare const browserTool: (options?: BrowserToolOptions) => AgentToolDefinition<BrowserToolInput, string>;
230
+ * A batteries-included agent tool that drives Cloudflare Browser Rendering. One
231
+ * tool exposes every browser op (screenshot / pdf / content / scrape); the model
232
+ * picks via `op`. The call dispatches to the auto-registered `sandbox:invoke`
233
+ * action — which runs on an action ctx carrying `ctx.browser`. Importing the tool
234
+ * makes codegen register the dispatcher and provision the `BROWSER` binding; like
235
+ * any `ctx.browser` user, the app still supplies a `config.browser` thunk
236
+ * (`createBrowser({ binding: env.BROWSER, launch })` with the optional
237
+ * `@cloudflare/playwright` `launch` peer) to `createShardDO()` — codegen never
238
+ * injects that peer, so the browser op throws a directed error until it is wired.
239
+ *
240
+ * `content`/`scrape` return text. `screenshot`/`pdf` write the render to
241
+ * `opts.bucket` and return `{ bytes, key, mediaType }` — never the bytes
242
+ * themselves, which a 4000-char tool-output cap would truncate into something
243
+ * unusable after paying for the render. Without a bucket those two ops are
244
+ * refused as a tool result and never dispatched.
245
+ *
246
+ * Security: the model chooses the `url` with no allowlist, so this is an SSRF
247
+ * surface — pass `opts.needsApproval` to gate calls a prompt-injected model
248
+ * could aim at internal/link-local endpoints.
249
+ *
250
+ * ```ts
251
+ * import { browserTool, defineAgent } from "@lunora/agent/sandbox";
252
+ *
253
+ * export const researcher = defineAgent({
254
+ * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
255
+ * tools: { browser: browserTool({ bucket: "SANDBOX_BUCKET", root: "renders" }) },
256
+ * });
257
+ * ```
258
+ * @experimental
259
+ */
260
+ declare const browserTool: (options?: BrowserToolOptions) => AgentToolDefinition<BrowserToolInput, BrowserRenderResult | string>;
150
261
  /**
151
- * A batteries-included agent tool that talks to a declared Cloudflare
152
- * Container. `name` is the `ctx.containers.&lt;name>` key (the `lunora/containers.ts`
153
- * export). One tool exposes `fetch` (HTTP request) and `exec` (run a command);
154
- * the model picks via `op`. The call dispatches to the auto-registered
155
- * `sandbox:invoke` action, which carries `ctx.containers`.
156
- *
157
- * By default a `fetch` runs unattended while command execution is gated behind a
158
- * human approval — an `exec`, AND a `fetch` whose path resolves to the privileged
159
- * `/exec` route (both reach the same command-execution path in the container, so
160
- * gating on the `op` name alone would let a `fetch` to `/exec` run a command
161
- * unattended). Note a `fetch` can still reach any *other* container route
162
- * unattended, so scope the container's routes accordingly. Pass
163
- * `opts.needsApproval` to widen or disable the gate.
164
- *
165
- * ```ts
166
- * import { containerTool, defineAgent } from "@lunora/agent/sandbox";
167
- *
168
- * export const ops = defineAgent({
169
- * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
170
- * tools: { sandbox: containerTool("sandbox") },
171
- * });
172
- * ```
173
- * @experimental
174
- */
262
+ * A batteries-included agent tool that talks to a declared Cloudflare
263
+ * Container. `name` is the `ctx.containers.<name>` key (the `lunora/containers.ts`
264
+ * export). One tool exposes `fetch` (HTTP request) and `exec` (run a command);
265
+ * the model picks via `op`. The call dispatches to the auto-registered
266
+ * `sandbox:invoke` action, which carries `ctx.containers`.
267
+ *
268
+ * Every call is addressed to ONE instance per thread (`ctx.containers.<name>
269
+ * .get(threadKey)`), not a random pool member, so a multi-step session shares a
270
+ * filesystem — size the container's `maxInstances` for the number of live
271
+ * threads. See `sandbox-budgets.ts` for the time budgets and the re-execution
272
+ * ceiling that remains.
273
+ *
274
+ * By default a read-only (GET/HEAD/OPTIONS, or method-omitted) `fetch` runs
275
+ * unattended while everything else is gated behind a human approval — an
276
+ * `exec`; a `fetch` whose path resolves to the privileged exec route (both
277
+ * reach the same command-execution path in the container, so gating on the
278
+ * `op` name alone would let a `fetch` to it run a command unattended);
279
+ * and a `fetch` using a non-idempotent method (POST/PUT/PATCH/DELETE) to ANY
280
+ * route, since a prompt-injected model could otherwise mutate container state
281
+ * through some other privileged route just by avoiding the literal exec
282
+ * path. A `fetch` can still reach any *other read* route unattended, so scope
283
+ * the container's GET routes accordingly. Pass `opts.needsApproval` to widen
284
+ * or disable the gate.
285
+ *
286
+ * ```ts
287
+ * import { containerTool, defineAgent } from "@lunora/agent/sandbox";
288
+ *
289
+ * export const ops = defineAgent({
290
+ * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
291
+ * tools: { sandbox: containerTool("sandbox") },
292
+ * });
293
+ * ```
294
+ * @experimental
295
+ */
175
296
  declare const containerTool: (name: string, options?: ContainerToolOptions) => AgentToolDefinition<ContainerToolInput, string>;
176
297
  /**
177
- * A batteries-included agent tool exposing a persistent, R2-backed virtual
178
- * filesystem. `bucket` is the R2 binding name; every path is scoped under the
179
- * pinned `opts.root` (a `..` that would escape it is rejected). One tool exposes
180
- * `ls`/`read`/`write`/`rm`/`stat`; the model picks via `op`. The call dispatches
181
- * to the auto-registered `sandbox:invoke` action, which reads the bucket from
182
- * `ctx.env`. workerd has no real shell — this is object-store-backed file I/O.
183
- *
184
- * By default the writing ops (`write`/`rm`) pause for a human approval while
185
- * reads run unattended; pass `opts.needsApproval` to change that. Importing the
186
- * tool registers the dispatcher; the app must declare the `r2_bucket` binding in
187
- * `wrangler.jsonc` (the fs op throws a directed error until it is wired).
188
- *
189
- * ```ts
190
- * import { defineAgent, fsTool } from "@lunora/agent/sandbox";
191
- *
192
- * export const coder = defineAgent({
193
- * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
194
- * tools: { fs: fsTool("SANDBOX_BUCKET", { root: "agents/coder" }) },
195
- * });
196
- * ```
197
- * @experimental
198
- */
298
+ * A batteries-included agent tool exposing a persistent, R2-backed virtual
299
+ * filesystem. `bucket` is the R2 binding name; every path is scoped under the
300
+ * pinned `opts.root` (a `..` that would escape it is rejected). One tool exposes
301
+ * `ls`/`read`/`write`/`rm`/`stat`; the model picks via `op`. The call dispatches
302
+ * to the auto-registered `sandbox:invoke` action, which reads the bucket from
303
+ * `ctx.env`. workerd has no real shell — this is object-store-backed file I/O.
304
+ *
305
+ * By default the writing ops (`write`/`rm`) pause for a human approval while
306
+ * reads run unattended; pass `opts.needsApproval` to change that. Importing the
307
+ * tool registers the dispatcher; the app must declare the `r2_bucket` binding in
308
+ * `wrangler.jsonc` (the fs op throws a directed error until it is wired).
309
+ *
310
+ * ```ts
311
+ * import { defineAgent, fsTool } from "@lunora/agent/sandbox";
312
+ *
313
+ * export const coder = defineAgent({
314
+ * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
315
+ * tools: { fs: fsTool("SANDBOX_BUCKET", { root: "agents/coder" }) },
316
+ * });
317
+ * ```
318
+ * @experimental
319
+ */
199
320
  declare const fsTool: (bucket: string, options?: FsToolOptions) => AgentToolDefinition<FsToolInput>;
200
- export { type BrowserToolInput, type BrowserToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, browserTool, containerTool, fsTool };
321
+ /**
322
+ * A batteries-included agent tool for files on a container's OWN disk —
323
+ * `name` is the `ctx.containers.<name>` key of a `defineContainer({ sandbox:
324
+ * true })` container. Same `ls`/`read`/`write`/`rm`/`stat` ops and the same
325
+ * default approval gate as {@link fsTool}, but backed by the container's
326
+ * filesystem (through `@cloudflare/sandbox`'s `Files`) instead of R2, and
327
+ * addressed to the same per-thread instance {@link containerTool} uses. So a
328
+ * file the model writes here is the file its next `exec` sees, which is not
329
+ * true of `fsTool`.
330
+ *
331
+ * Every path is scoped under `opts.root` (default `/workspace`); a `..` that
332
+ * would escape it is rejected. A `write` creates missing parent directories.
333
+ *
334
+ * ```ts
335
+ * import { containerFsTool, containerTool, defineAgent } from "@lunora/agent/sandbox";
336
+ *
337
+ * export const coder = defineAgent({
338
+ * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
339
+ * tools: { files: containerFsTool("sandbox"), shell: containerTool("sandbox") },
340
+ * });
341
+ * ```
342
+ * @experimental
343
+ */
344
+ declare const containerFsTool: (name: string, options?: ContainerFsToolOptions) => AgentToolDefinition<FsToolInput>;
345
+ export { type BrowserRenderResult, type BrowserToolInput, type BrowserToolOptions, type ContainerFsToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, type JsCodeToolInput, type JsCodeToolOptions, type JsCodeToolResult, browserTool, containerFsTool, containerTool, fsTool, jsCodeTool };