@lunora/agent 1.0.0-alpha.160 → 1.0.0-alpha.161

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.
@@ -1,2 +1,2 @@
1
- import{LunoraError as g}from"@lunora/errors";import{defineTable as k,initLunora as D,defineSchemaExtension as j}from"@lunora/server";import{v as e}from"@lunora/values";import{a as q,A as _,d as P,b as F}from"./packem_shared/component-shared-G8ngerkU.mjs";import{graphTables as G,graphComponent as H}from"./packem_shared/normalizeEntityName-k3fjicAG.mjs";import{normalizeEntityName as he}from"./packem_shared/normalizeEntityName-k3fjicAG.mjs";import{sandboxComponent as we}from"./packem_shared/sandboxComponent-CKX-iNXC.mjs";const v="agent_episodes",X=5,Q=20,W=500,N=200,Y=/\s+/gu,z=d=>d===void 0||!Number.isFinite(d)?X:Math.min(Q,Math.max(1,Math.trunc(d))),V={episodes:k({createdAt:e.number(),messageKey:e.string(),owner:e.string(),summary:e.string(),threadKey:e.optional(e.string())}).index("byOwnerCreatedAt",["owner","createdAt"]).index("byOwnerMessageKey",["owner","messageKey"],{unique:!0}).public()},{mutation:J,query:Z}=D.dataModel().create(),ee=()=>{const d=J.input({createdAt:e.optional(e.number()),messageKey:e.string(),owner:e.string(),summary:e.string(),threadKey:e.optional(e.string())}).mutation(async({args:s,ctx:u})=>{const c=s.summary.replaceAll(Y," ").trim().slice(0,W);if(c.length===0)return{recorded:!1};if(await u.db.query(v).withIndex("byOwnerMessageKey",I=>I.eq("owner",s.owner).eq("messageKey",s.messageKey)).first())return{recorded:!1};await u.db.insert(v,{createdAt:s.createdAt??Date.now(),messageKey:s.messageKey,owner:s.owner,summary:c,...s.threadKey===void 0?{}:{threadKey:s.threadKey}});const w=await u.db.query(v).withIndex("byOwnerCreatedAt",I=>I.eq("owner",s.owner)).order("asc").take(N+1);for(const I of w.slice(0,Math.max(0,w.length-N)))await u.db.delete(I._id);return{recorded:!0}}),o=Z.input({limit:e.optional(e.number()),owner:e.string()}).query(async({args:s,ctx:u})=>{const c=await u.db.query(v).withIndex("byOwnerCreatedAt",h=>h.eq("owner",s.owner)).order("desc").take(z(s.limit));return c.length===0?{context:""}:{context:c.toReversed().map(h=>`- ${h.summary}`).join(`
1
+ import{LunoraError as g}from"@lunora/errors";import{defineTable as k,initLunora as D,defineSchemaExtension as j}from"@lunora/server";import{v as e}from"@lunora/values";import{a as q,A as _,d as P,b as F}from"./packem_shared/component-shared-G8ngerkU.mjs";import{graphTables as G,graphComponent as H}from"./packem_shared/normalizeEntityName-k3fjicAG.mjs";import{normalizeEntityName as he}from"./packem_shared/normalizeEntityName-k3fjicAG.mjs";import{sandboxComponent as we}from"./packem_shared/sandboxComponent-Du0yENEO.mjs";const v="agent_episodes",X=5,Q=20,W=500,N=200,Y=/\s+/gu,z=d=>d===void 0||!Number.isFinite(d)?X:Math.min(Q,Math.max(1,Math.trunc(d))),V={episodes:k({createdAt:e.number(),messageKey:e.string(),owner:e.string(),summary:e.string(),threadKey:e.optional(e.string())}).index("byOwnerCreatedAt",["owner","createdAt"]).index("byOwnerMessageKey",["owner","messageKey"],{unique:!0}).public()},{mutation:J,query:Z}=D.dataModel().create(),ee=()=>{const d=J.input({createdAt:e.optional(e.number()),messageKey:e.string(),owner:e.string(),summary:e.string(),threadKey:e.optional(e.string())}).mutation(async({args:s,ctx:u})=>{const c=s.summary.replaceAll(Y," ").trim().slice(0,W);if(c.length===0)return{recorded:!1};if(await u.db.query(v).withIndex("byOwnerMessageKey",I=>I.eq("owner",s.owner).eq("messageKey",s.messageKey)).first())return{recorded:!1};await u.db.insert(v,{createdAt:s.createdAt??Date.now(),messageKey:s.messageKey,owner:s.owner,summary:c,...s.threadKey===void 0?{}:{threadKey:s.threadKey}});const w=await u.db.query(v).withIndex("byOwnerCreatedAt",I=>I.eq("owner",s.owner)).order("asc").take(N+1);for(const I of w.slice(0,Math.max(0,w.length-N)))await u.db.delete(I._id);return{recorded:!0}}),o=Z.input({limit:e.optional(e.number()),owner:e.string()}).query(async({args:s,ctx:u})=>{const c=await u.db.query(v).withIndex("byOwnerCreatedAt",h=>h.eq("owner",s.owner)).order("desc").take(z(s.limit));return c.length===0?{context:""}:{context:c.toReversed().map(h=>`- ${h.summary}`).join(`
2
2
  `)}});return{agentEpisodeRecall:q(o),agentEpisodeUpsert:q(d)}},S="threads",$="messages",M="run_queue",p=`${_}_${S}`,E=`${_}_${$}`,A=`${_}_${M}`,x=5,te=780*60*1e3,ne=j(_,{tables:{[$]:k({content:e.string(),createdAt:e.number(),messageKey:e.string(),role:e.union(e.literal("user"),e.literal("assistant"),e.literal("tool"),e.literal("system")),seq:e.number(),status:e.optional(e.union(e.literal("awaiting_approval"),e.literal("approved"),e.literal("rejected"))),stepName:e.optional(e.string()),threadKey:e.string(),toolCallId:e.optional(e.string()),toolCalls:e.optional(e.array(e.object({id:e.string(),input:e.any(),name:e.string()}))),toolName:e.optional(e.string())}).index("byThread",["threadKey","seq"]).index("byMessageKey",["threadKey","messageKey"],{unique:!0}).public(),[S]:k({agent:e.string(),createdAt:e.number(),error:e.optional(e.string().nullable()),completedInstanceId:e.optional(e.string().nullable()),instanceId:e.optional(e.string()),key:e.string(),messageCount:e.number(),owner:e.optional(e.string()),state:e.optional(e.any()),status:e.union(e.literal("idle"),e.literal("running"),e.literal("error"),e.literal("cancelled"),e.literal("awaiting_input")),title:e.optional(e.string()),updatedAt:e.number(),usage:e.optional(e.object({inputTokens:e.optional(e.number()),outputTokens:e.optional(e.number()),totalTokens:e.optional(e.number())}))}).index("byKey",["key"],{unique:!0}).index("byAgent",["agent"]).index("byInstance",["instanceId"]).public(),[M]:k({agent:e.string(),enqueuedAt:e.number(),instanceId:e.string(),position:e.number(),threadKey:e.string()}).index("byThread",["threadKey","position"]).index("byThreadInstance",["threadKey","instanceId"],{unique:!0}).public(),...G,...V}}),{mutation:f,query:T}=D.dataModel().create(),ie=async(d,o,s)=>{if(o.instanceId===void 0)throw new g("CONFLICT",`@lunora/agent: thread "${o.key}" already has a run in flight (instance "${o.priorInstanceId}") — cannot queue a dispatch with no instance id`);const{instanceId:u}=o,c=await d.query(A).withIndex("byThreadInstance",I=>I.eq("threadKey",o.key).eq("instanceId",u)).first();if(c)return{outcome:"queued",position:c.position};const h=await d.query(A).withIndex("byThread",I=>I.eq("threadKey",o.key)).collect();if(h.length>=x)throw new g("CONFLICT",`@lunora/agent: thread "${o.key}" run queue is full (depth ${String(x)}) — rejecting instance "${u}"`);const w=(h.at(-1)?.position??-1)+1;return await d.insert(A,{agent:o.agent,enqueuedAt:s,instanceId:u,position:w,threadKey:o.key}),{outcome:"queued",position:w}},ae=async(d,o,s)=>{if(o.policy==="queue")return ie(d,{agent:o.agent,instanceId:o.instanceId,key:o.key,priorInstanceId:o.priorInstanceId},s);if(o.policy!=="replace")throw new g("CONFLICT",`@lunora/agent: thread "${o.key}" already has a run in flight (instance "${o.priorInstanceId}") — onConcurrentRun="${o.policy}"`);return await d.patch(o.existingId,{error:null,status:"running",updatedAt:s,...o.instanceId===void 0?{}:{completedInstanceId:null,instanceId:o.instanceId}}),{outcome:"replaced",priorInstanceId:o.priorInstanceId}},oe=(d,o,s)=>{const u=d.instanceId;if(u===void 0||o===u||d.status!=="running"&&d.status!=="awaiting_input")return;const c=typeof d.updatedAt=="number"?d.updatedAt:0,h=d.status==="awaiting_input"?F:te;return s-c>h?void 0:u},ce=()=>{const d=f.input({agent:e.string(),initialState:e.optional(e.any()),instanceId:e.optional(e.string()),key:e.string(),onConcurrentRun:e.optional(e.union(e.literal("reject"),e.literal("queue"),e.literal("replace"))),owner:e.optional(e.string()),title:e.optional(e.string())}).mutation(async({args:t,ctx:n})=>{const a=Date.now(),i=await n.db.query(p).withIndex("byKey",r=>r.eq("key",t.key)).first();if(i){if(i.owner!==t.owner)throw new Error(`@lunora/agent: thread "${t.key}" belongs to another owner`);if(t.instanceId!==void 0&&i.completedInstanceId===t.instanceId)return{outcome:"completed"};const r=oe(i,t.instanceId,a);return r!==void 0?ae(n.db,{agent:t.agent,existingId:i._id,instanceId:t.instanceId,key:t.key,policy:t.onConcurrentRun??"reject",priorInstanceId:r},a):(await n.db.patch(i._id,{error:null,status:"running",updatedAt:a,...t.instanceId===void 0?{}:{completedInstanceId:null,instanceId:t.instanceId}}),{outcome:"continued"})}return await n.db.insert(p,{agent:t.agent,createdAt:a,key:t.key,messageCount:0,status:"running",updatedAt:a,...P({instanceId:t.instanceId,owner:t.owner,state:t.initialState,title:t.title})}),{outcome:"created"}}),o=f.input({content:e.string(),messageKey:e.string(),role:e.union(e.literal("user"),e.literal("assistant"),e.literal("tool"),e.literal("system")),status:e.optional(e.union(e.literal("awaiting_approval"),e.literal("approved"),e.literal("rejected"))),stepName:e.optional(e.string()),threadKey:e.string(),toolCallId:e.optional(e.string()),toolCalls:e.optional(e.array(e.object({id:e.string(),input:e.any(),name:e.string()}))),toolName:e.optional(e.string())}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(E).withIndex("byMessageKey",y=>y.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();if(a)return{seq:a.seq};const i=await n.db.query(p).withIndex("byKey",y=>y.eq("key",t.threadKey)).first();if(!i)throw new Error(`@lunora/agent: cannot append to unknown thread "${t.threadKey}" — run agentEnsureThread first`);const r=i.messageCount,l=Date.now();return await n.db.insert(E,{content:t.content,createdAt:l,messageKey:t.messageKey,role:t.role,seq:r,threadKey:t.threadKey,...t.status===void 0?{}:{status:t.status},...t.stepName===void 0?{}:{stepName:t.stepName},...t.toolCallId===void 0?{}:{toolCallId:t.toolCallId},...t.toolCalls===void 0?{}:{toolCalls:t.toolCalls},...t.toolName===void 0?{}:{toolName:t.toolName}}),await n.db.patch(i._id,{messageCount:r+1,updatedAt:l}),{seq:r}}),s=f.input({messageKey:e.string(),threadKey:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(E).withIndex("byMessageKey",i=>i.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();a&&await n.db.delete(a._id)}),u=f.input({error:e.optional(e.string()),instanceId:e.optional(e.string()),key:e.optional(e.string()),status:e.optional(e.union(e.literal("idle"),e.literal("running"),e.literal("error"),e.literal("cancelled"),e.literal("awaiting_input"))),title:e.optional(e.string()),usage:e.optional(e.object({inputTokens:e.optional(e.number()),outputTokens:e.optional(e.number()),totalTokens:e.optional(e.number())}))}).mutation(async({args:t,ctx:n})=>{const{instanceId:a,key:i}=t;let r;i!==void 0?r=await n.db.query(p).withIndex("byKey",l=>l.eq("key",i)).first():a!==void 0&&(r=await n.db.query(p).withIndex("byInstance",l=>l.eq("instanceId",a)).first()),r&&await n.db.patch(r._id,{updatedAt:Date.now(),...t.error===void 0?{}:{error:t.error},...t.status===void 0?{}:{status:t.status},...t.title===void 0?{}:{title:t.title},...t.usage===void 0?{}:{usage:t.usage}})}),c=f.input({error:e.optional(e.string()),instanceId:e.string(),key:e.string(),status:e.union(e.literal("idle"),e.literal("error"),e.literal("cancelled")),usage:e.optional(e.object({inputTokens:e.optional(e.number()),outputTokens:e.optional(e.number()),totalTokens:e.optional(e.number())}))}).mutation(async({args:t,ctx:n})=>{const a=Date.now(),i=await n.db.query(p).withIndex("byKey",b=>b.eq("key",t.key)).first();if(i?.instanceId!==t.instanceId){if(i?.completedInstanceId===t.instanceId&&i.status==="running"&&typeof i.instanceId=="string")return{dequeued:i.instanceId};const b=await n.db.query(A).withIndex("byThreadInstance",K=>K.eq("threadKey",t.key).eq("instanceId",t.instanceId)).first();return b&&await n.db.delete(b._id),{}}const y=(i.completedInstanceId===t.instanceId?[]:await n.db.query(A).withIndex("byThread",b=>b.eq("threadKey",t.key)).collect())[0];if(!y)return await n.db.patch(i._id,{completedInstanceId:t.instanceId,status:t.status,updatedAt:a,...t.error===void 0?{}:{error:t.error},...t.usage===void 0?{}:{usage:t.usage}}),{};const m=y.instanceId;return await n.db.delete(y._id),await n.db.patch(i._id,{completedInstanceId:t.instanceId,instanceId:m,status:"running",updatedAt:a,...t.error===void 0?{}:{error:t.error},...t.usage===void 0?{}:{usage:t.usage}}),{dequeued:m}}),h=f.input({key:e.string(),state:e.any()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",i=>i.eq("key",t.key)).first();a&&await n.db.patch(a._id,{state:t.state,updatedAt:Date.now()})}),w=(t,n)=>{if(!t)return;const{owner:a}=t;if(!(a!==void 0&&a!==(n.userId??void 0)))return t},I=T.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",i=>i.eq("key",t.key)).first();return w(a,n.auth)}),O=T.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",i=>i.eq("key",t.key)).first();return w(a,n.auth)?.state}),L=T.input({key:e.string(),limit:e.optional(e.number())}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",i=>i.eq("key",t.key)).first();return w(a,n.auth)===void 0?[]:t.limit!==void 0?(await n.db.query(E).withIndex("byThread",r=>r.eq("threadKey",t.key)).order("desc").take(t.limit)).toReversed():n.db.query(E).withIndex("byThread",i=>i.eq("threadKey",t.key)).collect()}),U=f.input({decision:e.union(e.literal("approve"),e.literal("reject")),instanceId:e.string(),note:e.optional(e.string()),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",m=>m.eq("key",t.threadKey)).first(),i=w(a,n.auth);if(i===void 0)throw new g("FORBIDDEN",`@lunora/agent: not allowed to resolve approvals on thread "${t.threadKey}"`);if(i.instanceId!==t.instanceId)throw new g("FORBIDDEN",`@lunora/agent: instance "${t.instanceId}" does not own thread "${t.threadKey}"`);const r=i.agent,{agents:l}=n,y=l?.[r];if(typeof y?.sendEvent!="function")throw new g("INTERNAL",`@lunora/agent: no ctx.agents["${r}"] producer to resolve the approval — run codegen/dev so the agent binding is wired`);return await y.sendEvent(t.instanceId,{payload:{decision:t.decision,toolCallId:t.toolCallId,...t.note===void 0?{}:{note:t.note}},type:`agent-approval:${t.toolCallId}`}),{resolved:!0}}),B=f.input({agent:e.string(),input:e.string(),threadKey:e.string(),title:e.optional(e.string())}).mutation(async({args:t,ctx:n})=>{const{agents:a}=n,i=a?.[t.agent];if(typeof i?.run!="function")throw new g("INTERNAL",`@lunora/agent: no ctx.agents["${t.agent}"] producer to start a run — run codegen/dev so the agent binding is wired, and check the agent name`);if(i.publicRun!==!0)throw new g("FORBIDDEN",`@lunora/agent: agent "${t.agent}" is not enabled for public runs — set defineAgent({ publicRun: true }) to allow an external client (e.g. the @lunora/mcp server) to start it`);const r=n.auth.userId??void 0,l=await n.db.query(p).withIndex("byKey",m=>m.eq("key",t.threadKey)).first();if(l){const m=l.status,b=l.instanceId,K=l.owner;if((m==="running"||m==="awaiting_input")&&b!==void 0&&(K===void 0||K===r))return{id:b,threadKey:t.threadKey};if(K!==r)throw new g("FORBIDDEN",`@lunora/agent: thread "${t.threadKey}" belongs to another owner`)}const{id:y}=await i.run({input:t.input,threadKey:t.threadKey,...r===void 0?{}:{owner:r},...t.title===void 0?{}:{title:t.title}});return{id:y,threadKey:t.threadKey}}),C=H(),R=ee();return{extension:ne,functions:{agentAppendMessage:q(o),agentCompleteRun:q(c),agentEnsureThread:q(d),agentEpisodeRecall:R.agentEpisodeRecall,agentEpisodeUpsert:R.agentEpisodeUpsert,agentGraphTraverse:C.agentGraphTraverse,agentGraphUpsert:C.agentGraphUpsert,agentMessages:L,agentDeleteMessage:q(s),agentPatchThread:q(u),agentResolveApproval:U,agentRun:B,agentSetState:q(h),agentState:O,agentThread:I}}};export{ce as agentComponent,ne as agentExtension,he as normalizeEntityName,we as sandboxComponent};
package/dist/index.d.mts CHANGED
@@ -2,7 +2,7 @@ import { A as AgentDefinition, e as AgentCompact, f as AgentEpisodeExtract, g as
2
2
  export type { B as AgentApprovalContext, C as AgentEmailMapper, D as AgentEmailRun, E as AgentGenerateOptions, F as AgentGenerateResult, G as AgentInstructionsContext, H as AgentLiveEvent, J as AgentMemoryOptions, K as AgentMemorySource, L as AgentMessageStatus, M as AgentOnReply, N as AgentOnStepFinish, O as AgentPrepareStep, P as AgentPrepareStepInput, Q as AgentPrepareStepResult, R as AgentProgressEvent, T as AgentReplyInfo, a as AgentReplyRef, U as AgentRunHandle, V as AgentRunOptions, W as AgentStepFinishInfo, X as AgentStepInfo, Y as AgentThreadStatus, Z as AgentTokenDelta, _ as AgentToolCall, d as AgentToolContext, $ as AgentUsage, a0 as AgentVoiceConfig, a1 as AgentWorkflowBindingLike, a2 as AgentWorkflowInstanceLike, a3 as EnsureThreadOutcome } from "./packem_shared/types.d-CbYtFBw9.mjs";
3
3
  export { type AgentComponent, agentComponent, agentExtension } from "./component.mjs";
4
4
  import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
5
- export { type BrowserRenderResult, type BrowserToolInput, type BrowserToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, type JsCodeToolInput, type JsCodeToolOptions, type JsCodeToolResult, browserTool, containerTool, fsTool, jsCodeTool } from "./sandbox.mjs";
5
+ 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 } from "./sandbox.mjs";
6
6
  export { agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.mjs";
7
7
  import { createAi } from '@lunora/ai';
8
8
  import { WorkflowDefinition } from '@lunora/workflow';
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ import { A as AgentDefinition, e as AgentCompact, f as AgentEpisodeExtract, g as
2
2
  export type { B as AgentApprovalContext, C as AgentEmailMapper, D as AgentEmailRun, E as AgentGenerateOptions, F as AgentGenerateResult, G as AgentInstructionsContext, H as AgentLiveEvent, J as AgentMemoryOptions, K as AgentMemorySource, L as AgentMessageStatus, M as AgentOnReply, N as AgentOnStepFinish, O as AgentPrepareStep, P as AgentPrepareStepInput, Q as AgentPrepareStepResult, R as AgentProgressEvent, T as AgentReplyInfo, a as AgentReplyRef, U as AgentRunHandle, V as AgentRunOptions, W as AgentStepFinishInfo, X as AgentStepInfo, Y as AgentThreadStatus, Z as AgentTokenDelta, _ as AgentToolCall, d as AgentToolContext, $ as AgentUsage, a0 as AgentVoiceConfig, a1 as AgentWorkflowBindingLike, a2 as AgentWorkflowInstanceLike, a3 as EnsureThreadOutcome } from "./packem_shared/types.d-CbYtFBw9.js";
3
3
  export { type AgentComponent, agentComponent, agentExtension } from "./component.js";
4
4
  import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
5
- export { type BrowserRenderResult, type BrowserToolInput, type BrowserToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, type JsCodeToolInput, type JsCodeToolOptions, type JsCodeToolResult, browserTool, containerTool, fsTool, jsCodeTool } from "./sandbox.js";
5
+ 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 } from "./sandbox.js";
6
6
  export { agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.js";
7
7
  import { createAi } from '@lunora/ai';
8
8
  import { WorkflowDefinition } from '@lunora/workflow';
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{r as t,s as r}from"./packem_shared/agent-loop-CQUKMFWA.mjs";import{collectAgenticMemoryTools as a,toSearchResults as f}from"./packem_shared/collectAgenticMemoryTools-BeMWT2qt.mjs";import{agentAsTool as s}from"./packem_shared/agentAsTool-1Gwq45M3.mjs";import{codeTool as m}from"./packem_shared/codeTool-BQb-K3my.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as T}from"./packem_shared/createAgentContext-D3mf7LEU.mjs";import{defineAgent as d,defineAgentTool as u,isAgentDefinition as N}from"./packem_shared/defineAgent-CK3CpiOr.mjs";import{functionTool as D}from"./packem_shared/functionTool-D3CP4f8-.mjs";import{createAgentGenerate as C,createEpisodeExtract as M,createGraphExtract as O,createStreamGenerate as _,resolveAgentModel as G}from"./packem_shared/createAgentGenerate-BOILDUZj.mjs";import{jsCodeTool as L}from"./packem_shared/jsCodeTool-BLOvjXGF.mjs";import{adaptMcpResult as k,mcpTools as v}from"./packem_shared/adaptMcpResult-CVlq-_TO.mjs";import{buildModelMessages as R}from"./packem_shared/buildModelMessages-Y4tGo1T9.mjs";import{agentClassName as b,agentDefaultName as h,voiceBindingName as w,voiceClassName as H}from"./naming.mjs";import{AGENT_MODULE as P,DEFAULT_AGENT_FUNCTION_PATHS as X,SANDBOX_INVOKE_PATH as j,SANDBOX_MODULE as y,toFunctionReference as K}from"./packem_shared/AGENT_MODULE-M4D1EejI.mjs";import{browserTool as q,containerTool as z,fsTool as J}from"./sandbox.mjs";import{defineSkill as Y,isSkillDefinition as Z}from"./packem_shared/defineSkill-DGGvDWNq.mjs";import{default as ee}from"./packem_shared/VoiceSessionDO-Dc09ClZz.mjs";import{r as te}from"./packem_shared/voice-turn-BiDZeZwp.mjs";import{default as ne}from"./packem_shared/compileAgentWorkflow-Dijgn4Cz.mjs";export{P as AGENT_MODULE,X as DEFAULT_AGENT_FUNCTION_PATHS,j as SANDBOX_INVOKE_PATH,y as SANDBOX_MODULE,ee as VoiceSessionDO,k as adaptMcpResult,s as agentAsTool,b as agentClassName,c as agentComponent,h as agentDefaultName,x as agentExtension,q as browserTool,R as buildModelMessages,m as codeTool,a as collectAgenticMemoryTools,ne as compileAgentWorkflow,z as containerTool,T as createAgentContext,C as createAgentGenerate,M as createEpisodeExtract,O as createGraphExtract,_ as createStreamGenerate,d as defineAgent,u as defineAgentTool,Y as defineSkill,J as fsTool,D as functionTool,N as isAgentDefinition,Z as isSkillDefinition,L as jsCodeTool,v as mcpTools,G as resolveAgentModel,t as runAgentLoop,te as runVoiceTurn,r as splitForCompaction,K as toFunctionReference,f as toSearchResults,w as voiceBindingName,H as voiceClassName};
1
+ import{r as t,s as r}from"./packem_shared/agent-loop-CQUKMFWA.mjs";import{collectAgenticMemoryTools as a,toSearchResults as f}from"./packem_shared/collectAgenticMemoryTools-BeMWT2qt.mjs";import{agentAsTool as s}from"./packem_shared/agentAsTool-1Gwq45M3.mjs";import{codeTool as m}from"./packem_shared/codeTool-BQb-K3my.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as A}from"./packem_shared/createAgentContext-D3mf7LEU.mjs";import{defineAgent as d,defineAgentTool as u,isAgentDefinition as N}from"./packem_shared/defineAgent-CK3CpiOr.mjs";import{functionTool as D}from"./packem_shared/functionTool-D3CP4f8-.mjs";import{createAgentGenerate as C,createEpisodeExtract as M,createGraphExtract as O,createStreamGenerate as _,resolveAgentModel as F}from"./packem_shared/createAgentGenerate-BOILDUZj.mjs";import{jsCodeTool as L}from"./packem_shared/jsCodeTool-BLOvjXGF.mjs";import{adaptMcpResult as k,mcpTools as v}from"./packem_shared/adaptMcpResult-CVlq-_TO.mjs";import{buildModelMessages as R}from"./packem_shared/buildModelMessages-Y4tGo1T9.mjs";import{agentClassName as b,agentDefaultName as h,voiceBindingName as w,voiceClassName as H}from"./naming.mjs";import{AGENT_MODULE as P,DEFAULT_AGENT_FUNCTION_PATHS as X,SANDBOX_INVOKE_PATH as j,SANDBOX_MODULE as y,toFunctionReference as K}from"./packem_shared/AGENT_MODULE-M4D1EejI.mjs";import{browserTool as q,containerFsTool as z,containerTool as J,fsTool as Q}from"./sandbox.mjs";import{defineSkill as Z,isSkillDefinition as $}from"./packem_shared/defineSkill-DGGvDWNq.mjs";import{default as oe}from"./packem_shared/VoiceSessionDO-Dc09ClZz.mjs";import{r as re}from"./packem_shared/voice-turn-BiDZeZwp.mjs";import{default as ae}from"./packem_shared/compileAgentWorkflow-Dijgn4Cz.mjs";export{P as AGENT_MODULE,X as DEFAULT_AGENT_FUNCTION_PATHS,j as SANDBOX_INVOKE_PATH,y as SANDBOX_MODULE,oe as VoiceSessionDO,k as adaptMcpResult,s as agentAsTool,b as agentClassName,c as agentComponent,h as agentDefaultName,x as agentExtension,q as browserTool,R as buildModelMessages,m as codeTool,a as collectAgenticMemoryTools,ae as compileAgentWorkflow,z as containerFsTool,J as containerTool,A as createAgentContext,C as createAgentGenerate,M as createEpisodeExtract,O as createGraphExtract,_ as createStreamGenerate,d as defineAgent,u as defineAgentTool,Z as defineSkill,Q as fsTool,D as functionTool,N as isAgentDefinition,$ as isSkillDefinition,L as jsCodeTool,v as mcpTools,F as resolveAgentModel,t as runAgentLoop,re as runVoiceTurn,r as splitForCompaction,K as toFunctionReference,f as toSearchResults,w as voiceBindingName,H as voiceClassName};
@@ -0,0 +1,7 @@
1
+ import{LunoraError as c,isLunoraError as $}from"@lunora/errors";import{initLunora as N}from"@lunora/server";import{v as s}from"@lunora/values";import{b as v,c as A,d as _}from"./sandbox-budgets-DDvj4Orr.mjs";const y=async(o,t,n)=>{if(o===null)return{overflowed:!1,text:""};const r=o.getReader(),e=new TextDecoder,a=()=>{r.cancel().catch(()=>{})};n?.addEventListener("abort",a);let i="",l=0,p=!1;try{for(;n?.aborted!==!0;){const{done:h,value:u}=await r.read();if(h)break;if(l+u.byteLength>t){p=!0,i+=e.decode(u.subarray(0,t-l),{stream:!0});break}l+=u.byteLength,i+=e.decode(u,{stream:!0})}i+=e.decode()}finally{n?.removeEventListener("abort",a),r.cancel().catch(()=>{})}if(n?.aborted===!0)throw n.reason;return{overflowed:p,text:i}},{internalAction:R}=N.dataModel().create(),L=()=>globalThis.document?.documentElement?.outerHTML??"",d=1e6,w=1e6,O=20,E=new TextEncoder,B=o=>{const t=[`exit code: ${String(o.code)}`];return o.stdout.length>0&&t.push(`stdout:
2
+ ${o.stdout}`),o.stderr.length>0&&t.push(`stderr:
3
+ ${o.stderr}`),t.join(`
4
+
5
+ `)},D=async(o,t)=>{const n=AbortSignal.timeout(_);try{const r=await o.fetch(t.path??"/",{...t.body===void 0?{}:{body:t.body},method:t.method??"GET",signal:n}),e=await y(r.body,w,n);return e.overflowed?`${e.text}
6
+
7
+ [truncated at ${String(w)} bytes]`:e.text}catch(r){return`fetch failed: ${r instanceof Error?r.message:String(r)}`}},x=(o,t)=>{if(t.instance===void 0||t.instance.length===0)throw new c("BAD_REQUEST","@lunora/agent: sandbox container op arrived with no `instance` — the tool pins the thread's own container");return o.get(t.instance)},k=async(o,t)=>{const n=x(o,t);if(t.op==="exec")try{return B(await n.exec(t.command??"",{args:t.args??[],timeoutMs:A}))}catch(r){return`exec failed: ${r instanceof Error?r.message:String(r)}`}if(t.op==="fetch")return await D(n,t);throw new c("INTERNAL",`@lunora/agent: sandbox container op "${t.op}" is not supported`)},S=(o,t)=>new c("INTERNAL",`@lunora/agent: sandbox ${o} op found no R2 bucket "${t}" on env — declare the r2_bucket binding in wrangler.jsonc and run codegen`),g=(o,t)=>{const n=o.env?.[t.bucket??""];return n&&typeof n.get=="function"?n:void 0},b=(o,t)=>{if(!o)throw S("browser",t.bucket??"");return o},T=o=>{let t=0,n=o.length;for(;t<n&&o[t]==="/";)t+=1;for(;n>t&&o[n-1]==="/";)n-=1;return o.slice(t,n)},f=(o,t)=>{const n=T(o),r=[];for(const a of t.split("/"))if(!(a===""||a===".")){if(a===".."){if(r.length===0)throw new c("BAD_REQUEST","@lunora/agent: fs path escapes the sandbox root");r.pop();continue}r.push(a)}const e=r.join("/");return n&&e?`${n}/${e}`:n||e},F=async(o,t,n)=>{const r=t.length>0?`${t}/`:"",e=n.length>0?n.length+1:0,a=[];let i;for(let l=0;l<O;l+=1){const p=await o.list({prefix:r,...i===void 0?{}:{cursor:i}});for(const h of p.objects)a.push(h.key.slice(e));if(!p.truncated||p.cursor===void 0)return{entries:a,truncated:!1};i=p.cursor}return{entries:a,truncated:!0}},m=async(o,t,n,r,e)=>{const a=f(t,n);return await o.put(a,r),{bytes:r.byteLength,key:a,mediaType:e}},I=async(o,t,n)=>{const r=t.url??"",e={timeoutMs:v};switch(t.op){case"content":return o.content(r,e);case"pdf":return m(b(n,t),t.root??"",t.path??"",await o.pdf(r,e),"application/pdf");case"scrape":return o.scrape(r,L,e);case"screenshot":{const a=b(n,t),i=await o.screenshot(r,{...e,...t.fullPage===void 0?{}:{fullPage:t.fullPage},...t.type===void 0?{}:{type:t.type}});return m(a,t.root??"",t.path??"",i,t.type==="jpeg"?"image/jpeg":"image/png")}default:throw new c("INTERNAL",`@lunora/agent: sandbox browser op "${t.op}" is not supported`)}},M=async(o,t,n)=>{const r=T(t),e=f(t,n.path??"");switch(n.op){case"ls":{const{entries:a,truncated:i}=await F(o,e,r);return i?{entries:a,truncated:!0}:{entries:a}}case"read":{const a=await o.head(e);if(a&&a.size>d)throw new c("BAD_REQUEST",`@lunora/agent: fs read: "${n.path??""}" is ${String(a.size)} bytes (max ${String(d)})`);const i=await o.get(e);if(!i)throw new c("NOT_FOUND",`@lunora/agent: fs read: no file at "${n.path??""}"`);return i.text()}case"rm":return await o.delete(e),{path:n.path??"",removed:!0};case"stat":{const a=await o.head(e);return a?{exists:!0,size:a.size}:{exists:!1}}case"write":{const a=n.content??"",i=E.encode(a).length;if(i>d)throw new c("BAD_REQUEST",`@lunora/agent: fs write: ${String(i)} bytes exceeds the max (${String(d)})`);return await o.put(e,a),{bytes:i,path:n.path??"",wrote:!0}}default:throw new c("INTERNAL",`@lunora/agent: sandbox fs op "${n.op}" is not supported`)}},U=o=>o.slice(0,o.lastIndexOf("/"))||"/",C=async(o,t)=>{const{files:n}=x(o,t);if(n===void 0)throw new c("INTERNAL","@lunora/agent: containerFsTool needs ctx.containers.<name>.get(id).files — update @lunora/container");const r=`/${f(t.root??"/",t.path??"")}`;switch(t.op){case"ls":return{entries:(await n.readDirectory(r)).map(a=>a.type==="directory"?`${a.name}/`:a.name)};case"read":{const{size:e}=await n.stat(r);if(Number(e)>d)throw new c("BAD_REQUEST",`@lunora/agent: fs read: "${t.path??""}" is ${String(e)} bytes (max ${String(d)})`);const a=await n.readFile(r),i=await y(a.body,d);if(i.overflowed)throw new c("BAD_REQUEST",`@lunora/agent: fs read: "${t.path??""}" exceeds ${String(d)} bytes`);return i.text}case"rm":return await n.remove(r,{force:!0}),{path:t.path??"",removed:!0};case"stat":try{const{size:e,type:a}=await n.stat(r);return{exists:!0,size:Number(e),type:a}}catch(e){if($(e)&&e.code==="NOT_FOUND")return{exists:!1};throw e}case"write":{const e=t.content??"",a=E.encode(e).length;if(a>d)throw new c("BAD_REQUEST",`@lunora/agent: fs write: ${String(a)} bytes exceeds the max (${String(d)})`);return await n.mkdir(U(r),{recursive:!0}),await n.writeFile(r,e),{bytes:a,path:t.path??"",wrote:!0}}default:throw new c("INTERNAL",`@lunora/agent: sandbox fs op "${t.op}" is not supported`)}},P=()=>({invoke:R.input({args:s.optional(s.array(s.string())),body:s.optional(s.string()),bucket:s.optional(s.string()),command:s.optional(s.string()),content:s.optional(s.string()),fullPage:s.optional(s.boolean()),instance:s.optional(s.string()),kind:s.union(s.literal("browser"),s.literal("container"),s.literal("containerFs"),s.literal("fs")),method:s.optional(s.string()),name:s.optional(s.string()),op:s.string(),path:s.optional(s.string()),root:s.optional(s.string()),selector:s.optional(s.string()),type:s.optional(s.string()),url:s.optional(s.string())}).action(async({args:t,ctx:n})=>{const r=n,e=t;if(e.kind==="browser"){if(!r.browser)throw new c("INTERNAL","@lunora/agent: sandbox browser op needs `ctx.browser` — install @lunora/browser and run codegen");return I(r.browser,e,g(r,e))}if(e.kind==="fs"){const l=g(r,e);if(!l)throw S("fs",e.bucket??"");return M(l,e.root??"",e)}const a=e.name??"",i=r.containers?.[a];if(!i)throw new c("INTERNAL",`@lunora/agent: sandbox container op found no ctx.containers["${a}"] — declare the container in lunora/containers.ts and run codegen`);return e.kind==="containerFs"?C(i,e):k(i,e)})});export{f as resolveFsKey,C as runContainerFsOp,M as runFsOp,P as sandboxComponent};
@@ -188,6 +188,25 @@ interface FsToolOptions {
188
188
  */
189
189
  root?: ((context: AgentToolContext) => string) | string;
190
190
  }
191
+ /**
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
+ }
191
210
  /**
192
211
  * Author-supplied config for `containerTool`.
193
212
  * @experimental
@@ -299,4 +318,28 @@ declare const containerTool: (name: string, options?: ContainerToolOptions) => A
299
318
  * @experimental
300
319
  */
301
320
  declare const fsTool: (bucket: string, options?: FsToolOptions) => AgentToolDefinition<FsToolInput>;
302
- export { type BrowserRenderResult, type BrowserToolInput, type BrowserToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, type JsCodeToolInput, type JsCodeToolOptions, type JsCodeToolResult, browserTool, containerTool, fsTool, jsCodeTool };
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 };
package/dist/sandbox.d.ts CHANGED
@@ -188,6 +188,25 @@ interface FsToolOptions {
188
188
  */
189
189
  root?: ((context: AgentToolContext) => string) | string;
190
190
  }
191
+ /**
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
+ }
191
210
  /**
192
211
  * Author-supplied config for `containerTool`.
193
212
  * @experimental
@@ -299,4 +318,28 @@ declare const containerTool: (name: string, options?: ContainerToolOptions) => A
299
318
  * @experimental
300
319
  */
301
320
  declare const fsTool: (bucket: string, options?: FsToolOptions) => AgentToolDefinition<FsToolInput>;
302
- export { type BrowserRenderResult, type BrowserToolInput, type BrowserToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, type JsCodeToolInput, type JsCodeToolOptions, type JsCodeToolResult, browserTool, containerTool, fsTool, jsCodeTool };
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 };
package/dist/sandbox.mjs CHANGED
@@ -1 +1 @@
1
- import{LunoraError as a}from"@lunora/errors";import{jsonSchema as s}from"ai";import{toFunctionReference as h,SANDBOX_INVOKE_PATH as u}from"./packem_shared/AGENT_MODULE-M4D1EejI.mjs";import{S as l,a as T}from"./packem_shared/sandbox-budgets-DDvj4Orr.mjs";import{jsCodeTool as k}from"./packem_shared/jsCodeTool-BLOvjXGF.mjs";const i=h(u),f=e=>{if(e.op==="pdf")return"pdf";if(e.op==="screenshot")return e.type==="jpeg"?"jpeg":"png"},m=new Set(["bucket","path","root"]),g='Drive a headless browser: screenshot a page, render it to PDF, read its HTML content, or scrape it. Set `op` to "screenshot" | "pdf" | "content" | "scrape" and pass the target `url`.',E='Talk to a sandboxed container: `fetch` an HTTP path on it, or `exec` a command inside it. Set `op` to "fetch" (with `path`) or "exec" (with `command`).',y='Read and write files in a persistent sandbox filesystem. Set `op` to "ls" (list a directory), "read", "write" (with `content`), "rm", or "stat", and pass `path`.',S=e=>e.op==="write"||e.op==="rm",A=s({properties:{content:{description:"write: the file contents.",type:"string"},op:{description:"The filesystem operation to run.",enum:["ls","read","write","rm","stat"],type:"string"},path:{description:"The file or directory path, relative to the sandbox root.",type:"string"}},required:["op"],type:"object"}),O=s({properties:{fullPage:{description:"screenshot: capture the full scrollable page rather than just the viewport.",type:"boolean"},op:{description:"The browser operation to run.",enum:["screenshot","scrape","pdf","content"],type:"string"},selector:{description:"scrape: optional CSS selector hint to narrow the extraction.",type:"string"},type:{description:"screenshot: image encoding (default png).",enum:["png","jpeg"],type:"string"},url:{description:"The URL to operate on.",type:"string"}},required:["op","url"],type:"object"}),_=new Set(["DELETE","PATCH","POST","PUT"]),b=e=>e.op==="exec"||_.has((e.method??"GET").toUpperCase()),w=s({properties:{args:{description:"exec: command arguments.",items:{type:"string"},type:"array"},body:{description:"fetch: request body.",type:"string"},command:{description:"exec: the command to run.",type:"string"},method:{description:"fetch: HTTP method (default GET).",type:"string"},op:{description:"The container operation to run.",enum:["fetch","exec"],type:"string"},path:{description:"fetch: request path on the container (e.g. /health).",type:"string"}},required:["op"],type:"object"}),v=(e={})=>{const t=e.bucket!==void 0&&e.bucket.length>0?e.bucket:void 0;return{description:e.description??g,execute:async(n,o)=>{const r=f(n);if(r!==void 0&&t===void 0)return`Cannot run a "${n.op}": this browser tool has no \`bucket\` configured, so the render has nowhere to go. Use "content" or "scrape" for page text, or ask the operator to pass \`browserTool({ bucket })\`.`;const c=r===void 0?{}:{bucket:t,path:`${o.threadKey}/${o.toolCallId}.${r}`,...e.root===void 0?{}:{root:e.root}},p=Object.fromEntries(Object.entries(n).filter(([d])=>!m.has(d)));return await o.run(i,{...p,...c,kind:"browser"},{timeoutMs:l})},inputSchema:O,isLunoraAgentTool:!0,...e.needsApproval===void 0?{}:{needsApproval:e.needsApproval}}},C=(e,t={})=>{if(typeof e!="string"||e.length===0)throw new a("INTERNAL","@lunora/agent: containerTool requires a container `name` (the ctx.containers.<name> key from lunora/containers.ts)");const n=t.needsApproval??b;return{description:t.description??E,execute:(o,r)=>r.run(i,{...o,instance:r.threadKey,kind:"container",name:e},{timeoutMs:T}),inputSchema:w,isLunoraAgentTool:!0,needsApproval:n}},x=(e,t={})=>{if(typeof e!="string"||e.length===0)throw new a("INTERNAL","@lunora/agent: fsTool requires an R2 `bucket` binding name (the r2_bucket declared in wrangler.jsonc)");return{description:t.description??y,execute:(n,o)=>{const r=typeof t.root=="function"?t.root(o):t.root??"";return o.run(i,{...n,bucket:e,kind:"fs",root:r})},inputSchema:A,isLunoraAgentTool:!0,needsApproval:t.needsApproval??S}};export{v as browserTool,C as containerTool,x as fsTool,k as jsCodeTool};
1
+ import{LunoraError as s}from"@lunora/errors";import{jsonSchema as a}from"ai";import{toFunctionReference as T,SANDBOX_INVOKE_PATH as m}from"./packem_shared/AGENT_MODULE-M4D1EejI.mjs";import{S as g,a as c}from"./packem_shared/sandbox-budgets-DDvj4Orr.mjs";import{jsCodeTool as j}from"./packem_shared/jsCodeTool-BLOvjXGF.mjs";const i=T(m),f=e=>{if(e.op==="pdf")return"pdf";if(e.op==="screenshot")return e.type==="jpeg"?"jpeg":"png"},E=new Set(["bucket","path","root"]),S='Drive a headless browser: screenshot a page, render it to PDF, read its HTML content, or scrape it. Set `op` to "screenshot" | "pdf" | "content" | "scrape" and pass the target `url`.',y='Talk to a sandboxed container: `fetch` an HTTP path on it, or `exec` a command inside it. Set `op` to "fetch" (with `path`) or "exec" (with `command`).',A='Read and write files in a persistent sandbox filesystem. Set `op` to "ls" (list a directory), "read", "write" (with `content`), "rm", or "stat", and pass `path`.',w='Read and write files on the sandboxed container\'s own disk — the same disk its commands run against. Set `op` to "ls" (list a directory), "read", "write" (with `content`), "rm", or "stat", and pass `path`.',_="/workspace",p=e=>e.op==="write"||e.op==="rm",d=a({properties:{content:{description:"write: the file contents.",type:"string"},op:{description:"The filesystem operation to run.",enum:["ls","read","write","rm","stat"],type:"string"},path:{description:"The file or directory path, relative to the sandbox root.",type:"string"}},required:["op"],type:"object"}),N=a({properties:{fullPage:{description:"screenshot: capture the full scrollable page rather than just the viewport.",type:"boolean"},op:{description:"The browser operation to run.",enum:["screenshot","scrape","pdf","content"],type:"string"},selector:{description:"scrape: optional CSS selector hint to narrow the extraction.",type:"string"},type:{description:"screenshot: image encoding (default png).",enum:["png","jpeg"],type:"string"},url:{description:"The URL to operate on.",type:"string"}},required:["op","url"],type:"object"}),O=new Set(["DELETE","PATCH","POST","PUT"]),b=e=>e.op==="exec"||O.has((e.method??"GET").toUpperCase()),R=a({properties:{args:{description:"exec: command arguments.",items:{type:"string"},type:"array"},body:{description:"fetch: request body.",type:"string"},command:{description:"exec: the command to run.",type:"string"},method:{description:"fetch: HTTP method (default GET).",type:"string"},op:{description:"The container operation to run.",enum:["fetch","exec"],type:"string"},path:{description:"fetch: request path on the container (e.g. /health).",type:"string"}},required:["op"],type:"object"}),L=(e={})=>{const t=e.bucket!==void 0&&e.bucket.length>0?e.bucket:void 0;return{description:e.description??S,execute:async(o,n)=>{const r=f(o);if(r!==void 0&&t===void 0)return`Cannot run a "${o.op}": this browser tool has no \`bucket\` configured, so the render has nowhere to go. Use "content" or "scrape" for page text, or ask the operator to pass \`browserTool({ bucket })\`.`;const h=r===void 0?{}:{bucket:t,path:`${n.threadKey}/${n.toolCallId}.${r}`,...e.root===void 0?{}:{root:e.root}},u=Object.fromEntries(Object.entries(o).filter(([l])=>!E.has(l)));return await n.run(i,{...u,...h,kind:"browser"},{timeoutMs:g})},inputSchema:N,isLunoraAgentTool:!0,...e.needsApproval===void 0?{}:{needsApproval:e.needsApproval}}},k=(e,t={})=>{if(typeof e!="string"||e.length===0)throw new s("INTERNAL","@lunora/agent: containerTool requires a container `name` (the ctx.containers.<name> key from lunora/containers.ts)");const o=t.needsApproval??b;return{description:t.description??y,execute:(n,r)=>r.run(i,{...n,instance:r.threadKey,kind:"container",name:e},{timeoutMs:c}),inputSchema:R,isLunoraAgentTool:!0,needsApproval:o}},x=(e,t={})=>{if(typeof e!="string"||e.length===0)throw new s("INTERNAL","@lunora/agent: fsTool requires an R2 `bucket` binding name (the r2_bucket declared in wrangler.jsonc)");return{description:t.description??A,execute:(o,n)=>{const r=typeof t.root=="function"?t.root(n):t.root??"";return n.run(i,{...o,bucket:e,kind:"fs",root:r})},inputSchema:d,isLunoraAgentTool:!0,needsApproval:t.needsApproval??p}},F=(e,t={})=>{if(typeof e!="string"||e.length===0)throw new s("INTERNAL","@lunora/agent: containerFsTool requires a container `name` (the ctx.containers.<name> key from lunora/containers.ts)");const o=t.root??_;if(!o.startsWith("/"))throw new s("INTERNAL",`@lunora/agent: containerFsTool \`root\` must be an absolute path inside the container (got "${o}")`);return{description:t.description??w,execute:(n,r)=>r.run(i,{...n,instance:r.threadKey,kind:"containerFs",name:e,root:o},{timeoutMs:c}),inputSchema:d,isLunoraAgentTool:!0,needsApproval:t.needsApproval??p}};export{L as browserTool,F as containerFsTool,k as containerTool,x as fsTool,j as jsCodeTool};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/agent",
3
- "version": "1.0.0-alpha.160",
3
+ "version": "1.0.0-alpha.161",
4
4
  "description": "Durable AI agents for Lunora: defineAgent compiles a replay-safe tool-loop onto Cloudflare Workflows, with DO SQLite threads and live message subscriptions",
5
5
  "keywords": [
6
6
  "agent",
@@ -87,7 +87,7 @@
87
87
  "@lunora/ai": "1.0.0-alpha.105",
88
88
  "@lunora/errors": "1.0.0-alpha.48",
89
89
  "@lunora/mail": "1.0.0-alpha.94",
90
- "@lunora/server": "1.0.0-alpha.167",
90
+ "@lunora/server": "1.0.0-alpha.168",
91
91
  "@lunora/values": "1.0.0-alpha.58",
92
92
  "@lunora/workflow": "1.0.0-alpha.69",
93
93
  "@modelcontextprotocol/sdk": "^1.30.0",
@@ -1,7 +0,0 @@
1
- import{LunoraError as i}from"@lunora/errors";import{initLunora as x}from"@lunora/server";import{v as a}from"@lunora/values";import{b as T,c as S,d as _}from"./sandbox-budgets-DDvj4Orr.mjs";const v=async(e,t,n)=>{if(e===null)return{overflowed:!1,text:""};const r=e.getReader(),o=new TextDecoder,s=()=>{r.cancel().catch(()=>{})};n?.addEventListener("abort",s);let c="",d=0,l=!1;try{for(;n?.aborted!==!0;){const{done:h,value:p}=await r.read();if(h)break;if(d+p.byteLength>t){l=!0,c+=o.decode(p.subarray(0,t-d),{stream:!0});break}d+=p.byteLength,c+=o.decode(p,{stream:!0})}c+=o.decode()}finally{n?.removeEventListener("abort",s),r.cancel().catch(()=>{})}if(n?.aborted===!0)throw n.reason;return{overflowed:l,text:c}},{internalAction:A}=x.dataModel().create(),N=()=>globalThis.document?.documentElement?.outerHTML??"",u=1e6,g=1e6,$=20,R=new TextEncoder,L=e=>{const t=[`exit code: ${String(e.code)}`];return e.stdout.length>0&&t.push(`stdout:
2
- ${e.stdout}`),e.stderr.length>0&&t.push(`stderr:
3
- ${e.stderr}`),t.join(`
4
-
5
- `)},B=async(e,t)=>{const n=AbortSignal.timeout(_);try{const r=await e.fetch(t.path??"/",{...t.body===void 0?{}:{body:t.body},method:t.method??"GET",signal:n}),o=await v(r.body,g,n);return o.overflowed?`${o.text}
6
-
7
- [truncated at ${String(g)} bytes]`:o.text}catch(r){return`fetch failed: ${r instanceof Error?r.message:String(r)}`}},O=async(e,t)=>{if(t.instance===void 0||t.instance.length===0)throw new i("BAD_REQUEST","@lunora/agent: sandbox container op arrived with no `instance` — the tool pins the thread's own container");const n=e.get(t.instance);if(t.op==="exec")try{return L(await n.exec(t.command??"",{args:t.args??[],timeoutMs:S}))}catch(r){return`exec failed: ${r instanceof Error?r.message:String(r)}`}if(t.op==="fetch")return await B(n,t);throw new i("INTERNAL",`@lunora/agent: sandbox container op "${t.op}" is not supported`)},m=(e,t)=>new i("INTERNAL",`@lunora/agent: sandbox ${e} op found no R2 bucket "${t}" on env — declare the r2_bucket binding in wrangler.jsonc and run codegen`),f=(e,t)=>{const n=e.env?.[t.bucket??""];return n&&typeof n.get=="function"?n:void 0},w=(e,t)=>{if(!e)throw m("browser",t.bucket??"");return e},E=e=>{let t=0,n=e.length;for(;t<n&&e[t]==="/";)t+=1;for(;n>t&&e[n-1]==="/";)n-=1;return e.slice(t,n)},y=(e,t)=>{const n=E(e),r=[];for(const s of t.split("/"))if(!(s===""||s===".")){if(s===".."){if(r.length===0)throw new i("BAD_REQUEST","@lunora/agent: fs path escapes the sandbox root");r.pop();continue}r.push(s)}const o=r.join("/");return n&&o?`${n}/${o}`:n||o},k=async(e,t,n)=>{const r=t.length>0?`${t}/`:"",o=n.length>0?n.length+1:0,s=[];let c;for(let d=0;d<$;d+=1){const l=await e.list({prefix:r,...c===void 0?{}:{cursor:c}});for(const h of l.objects)s.push(h.key.slice(o));if(!l.truncated||l.cursor===void 0)return{entries:s,truncated:!1};c=l.cursor}return{entries:s,truncated:!0}},b=async(e,t,n,r,o)=>{const s=y(t,n);return await e.put(s,r),{bytes:r.byteLength,key:s,mediaType:o}},M=async(e,t,n)=>{const r=t.url??"",o={timeoutMs:T};switch(t.op){case"content":return e.content(r,o);case"pdf":return b(w(n,t),t.root??"",t.path??"",await e.pdf(r,o),"application/pdf");case"scrape":return e.scrape(r,N,o);case"screenshot":{const s=w(n,t),c=await e.screenshot(r,{...o,...t.fullPage===void 0?{}:{fullPage:t.fullPage},...t.type===void 0?{}:{type:t.type}});return b(s,t.root??"",t.path??"",c,t.type==="jpeg"?"image/jpeg":"image/png")}default:throw new i("INTERNAL",`@lunora/agent: sandbox browser op "${t.op}" is not supported`)}},I=async(e,t,n)=>{const r=E(t),o=y(t,n.path??"");switch(n.op){case"ls":{const{entries:s,truncated:c}=await k(e,o,r);return c?{entries:s,truncated:!0}:{entries:s}}case"read":{const s=await e.head(o);if(s&&s.size>u)throw new i("BAD_REQUEST",`@lunora/agent: fs read: "${n.path??""}" is ${String(s.size)} bytes (max ${String(u)})`);const c=await e.get(o);if(!c)throw new i("NOT_FOUND",`@lunora/agent: fs read: no file at "${n.path??""}"`);return c.text()}case"rm":return await e.delete(o),{path:n.path??"",removed:!0};case"stat":{const s=await e.head(o);return s?{exists:!0,size:s.size}:{exists:!1}}case"write":{const s=n.content??"",c=R.encode(s).length;if(c>u)throw new i("BAD_REQUEST",`@lunora/agent: fs write: ${String(c)} bytes exceeds the max (${String(u)})`);return await e.put(o,s),{bytes:c,path:n.path??"",wrote:!0}}default:throw new i("INTERNAL",`@lunora/agent: sandbox fs op "${n.op}" is not supported`)}},U=()=>({invoke:A.input({args:a.optional(a.array(a.string())),body:a.optional(a.string()),bucket:a.optional(a.string()),command:a.optional(a.string()),content:a.optional(a.string()),fullPage:a.optional(a.boolean()),instance:a.optional(a.string()),kind:a.union(a.literal("browser"),a.literal("container"),a.literal("fs")),method:a.optional(a.string()),name:a.optional(a.string()),op:a.string(),path:a.optional(a.string()),root:a.optional(a.string()),selector:a.optional(a.string()),type:a.optional(a.string()),url:a.optional(a.string())}).action(async({args:t,ctx:n})=>{const r=n,o=t;if(o.kind==="browser"){if(!r.browser)throw new i("INTERNAL","@lunora/agent: sandbox browser op needs `ctx.browser` — install @lunora/browser and run codegen");return M(r.browser,o,f(r,o))}if(o.kind==="fs"){const d=f(r,o);if(!d)throw m("fs",o.bucket??"");return I(d,o.root??"",o)}const s=o.name??"",c=r.containers?.[s];if(!c)throw new i("INTERNAL",`@lunora/agent: sandbox container op found no ctx.containers["${s}"] — declare the container in lunora/containers.ts and run codegen`);return O(c,o)})});export{y as resolveFsKey,I as runFsOp,U as sandboxComponent};