@lunora/agent 1.0.0-alpha.232 → 1.0.0-alpha.234

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 (56) hide show
  1. package/dist/channels.d.mts +2 -2
  2. package/dist/channels.d.ts +2 -2
  3. package/dist/component.d.mts +13 -1
  4. package/dist/component.d.ts +13 -1
  5. package/dist/component.mjs +2 -2
  6. package/dist/inbound.d.mts +1 -1
  7. package/dist/inbound.d.ts +1 -1
  8. package/dist/index.d.mts +98 -4
  9. package/dist/index.d.ts +98 -4
  10. package/dist/index.mjs +1 -1
  11. package/dist/packem_shared/AGENT_MODULE-CYBmT9SD.mjs +1 -0
  12. package/dist/packem_shared/SecretUnavailableError-BCp40Leh.mjs +1 -0
  13. package/dist/packem_shared/{VoiceSessionDO-D7O6Fclt.mjs → VoiceSessionDO-vGQ5RM-f.mjs} +1 -1
  14. package/dist/packem_shared/agent-loop-Cn7CA8n-.mjs +3 -0
  15. package/dist/packem_shared/{agentAsTool-BJi-uU4s.mjs → agentAsTool-CA7Sha2i.mjs} +1 -1
  16. package/dist/packem_shared/braintrustTelemetry-Ck09dC4G.mjs +1 -0
  17. package/dist/packem_shared/{buildModelMessages-Y4tGo1T9.mjs → buildModelMessages-BH7FXfkd.mjs} +2 -2
  18. package/dist/packem_shared/{codeTool-dpJANTDc.mjs → codeTool-Hm_Af6t4.mjs} +1 -1
  19. package/dist/packem_shared/{collectAgenticMemoryTools-D07XhGKr.mjs → collectAgenticMemoryTools-BWdIhOfY.mjs} +1 -1
  20. package/dist/packem_shared/common-DBc9y7Np.mjs +1 -0
  21. package/dist/packem_shared/{compileAgentWorkflow-KtkWJyHR.mjs → compileAgentWorkflow-D_GZWBJx.mjs} +1 -1
  22. package/dist/packem_shared/component-shared-DdXFbng-.mjs +1 -0
  23. package/dist/packem_shared/{consoleTelemetry-BZY3Y-Ly.mjs → consoleTelemetry-Cl-WQEsZ.mjs} +1 -1
  24. package/dist/packem_shared/{createAgentContext-Wlc1ZgWa.mjs → createAgentContext-BwEzrHXM.mjs} +1 -1
  25. package/dist/packem_shared/createAgentGenerate-C6mp2LqI.mjs +3 -0
  26. package/dist/packem_shared/{defineAgent-DrI8Hw7B.mjs → defineAgent-DGAOwO_s.mjs} +1 -1
  27. package/dist/packem_shared/{functionTool-Baqdn0OK.mjs → functionTool-C95ns65V.mjs} +1 -1
  28. package/dist/packem_shared/{in-flight-calls-GH1A_1P3.mjs → in-flight-calls-C9QGq8uH.mjs} +1 -1
  29. package/dist/packem_shared/{normalizeEntityName-k3fjicAG.mjs → normalizeEntityName-CmalZhT_.mjs} +1 -1
  30. package/dist/packem_shared/otlpTelemetry-CiSI9HE_.mjs +1 -0
  31. package/dist/packem_shared/runAgentLoop-CmRZ-o4N.mjs +1 -0
  32. package/dist/packem_shared/{runVoiceTurn-DdQVm4Kv.mjs → runVoiceTurn-CPEwDqxk.mjs} +1 -1
  33. package/dist/packem_shared/sentryTelemetry-B1BuLxxj.mjs +1 -0
  34. package/dist/packem_shared/{types.d-DqYbp4ye.d.mts → types.d-vAmttAsE.d.mts} +55 -6
  35. package/dist/packem_shared/{types.d-DqYbp4ye.d.ts → types.d-vAmttAsE.d.ts} +55 -6
  36. package/dist/packem_shared/voice-turn-CnyPkynX.mjs +1 -0
  37. package/dist/packem_shared/wrapUntrusted-BuHBC6sV.mjs +2 -0
  38. package/dist/reply.d.mts +1 -1
  39. package/dist/reply.d.ts +1 -1
  40. package/dist/sandbox.d.mts +1 -1
  41. package/dist/sandbox.d.ts +1 -1
  42. package/dist/sandbox.mjs +1 -1
  43. package/dist/skill-markdown.d.mts +1 -1
  44. package/dist/skill-markdown.d.ts +1 -1
  45. package/dist/telemetry/index.mjs +1 -1
  46. package/package.json +7 -6
  47. package/dist/packem_shared/AGENT_MODULE-B6FqQC80.mjs +0 -1
  48. package/dist/packem_shared/agent-loop-DzzRTrgP.mjs +0 -3
  49. package/dist/packem_shared/braintrustTelemetry-Byne8uPK.mjs +0 -1
  50. package/dist/packem_shared/common-CJSjtsfv.mjs +0 -1
  51. package/dist/packem_shared/component-shared-G8ngerkU.mjs +0 -1
  52. package/dist/packem_shared/createAgentGenerate-D9DbEj9I.mjs +0 -3
  53. package/dist/packem_shared/otlpTelemetry-DC5n77sQ.mjs +0 -1
  54. package/dist/packem_shared/runAgentLoop-COwgPdOl.mjs +0 -1
  55. package/dist/packem_shared/sentryTelemetry-BHeydiAB.mjs +0 -1
  56. package/dist/packem_shared/voice-turn-CzFz5tWG.mjs +0 -1
@@ -1,5 +1,5 @@
1
- import { A as AgentDefinition } from "./packem_shared/types.d-DqYbp4ye.mjs";
2
- export type { I as InboundChannelEvent } from "./packem_shared/types.d-DqYbp4ye.mjs";
1
+ import { A as AgentDefinition } from "./packem_shared/types.d-vAmttAsE.mjs";
2
+ export type { I as InboundChannelEvent } from "./packem_shared/types.d-vAmttAsE.mjs";
3
3
  import '@lunora/mail/inbound';
4
4
  import 'ai';
5
5
  /**
@@ -1,5 +1,5 @@
1
- import { A as AgentDefinition } from "./packem_shared/types.d-DqYbp4ye.js";
2
- export type { I as InboundChannelEvent } from "./packem_shared/types.d-DqYbp4ye.js";
1
+ import { A as AgentDefinition } from "./packem_shared/types.d-vAmttAsE.js";
2
+ export type { I as InboundChannelEvent } from "./packem_shared/types.d-vAmttAsE.js";
3
3
  import '@lunora/mail/inbound';
4
4
  import 'ai';
5
5
  /**
@@ -83,6 +83,8 @@ declare const sandboxComponent: () => SandboxComponent;
83
83
  declare const THREADS_BARE_TABLE = "threads";
84
84
  declare const MESSAGES_BARE_TABLE = "messages";
85
85
  declare const RUN_QUEUE_BARE_TABLE = "run_queue";
86
+ declare const GRANTS_BARE_TABLE = "approval_grants";
87
+ declare const REQUESTS_BARE_TABLE = "secret_requests";
86
88
  /**
87
89
  * The agent thread tables, shipped as a schema extension so an app merges
88
90
  * them with one call and they can never collide with app tables:
@@ -99,7 +101,7 @@ declare const RUN_QUEUE_BARE_TABLE = "run_queue";
99
101
  * message is a no-op instead of a duplicate.
100
102
  * @experimental
101
103
  */
102
- declare const agentExtension: SchemaExtension<Record<keyof typeof episodeTables | keyof typeof graphTables | typeof MESSAGES_BARE_TABLE | typeof RUN_QUEUE_BARE_TABLE | typeof THREADS_BARE_TABLE, TableDefinition>, typeof AGENT_EXTENSION_KEY>;
104
+ declare const agentExtension: SchemaExtension<Record<keyof typeof episodeTables | keyof typeof graphTables | typeof GRANTS_BARE_TABLE | typeof MESSAGES_BARE_TABLE | typeof REQUESTS_BARE_TABLE | typeof RUN_QUEUE_BARE_TABLE | typeof THREADS_BARE_TABLE, TableDefinition>, typeof AGENT_EXTENSION_KEY>;
103
105
  /**
104
106
  * `AgentComponent` is part of the experimental `@lunora/agent` API and may change without a major version bump.
105
107
  * @experimental
@@ -108,8 +110,12 @@ interface AgentComponent {
108
110
  extension: SchemaExtension;
109
111
  functions: {
110
112
  agentAppendMessage: AgentRegisteredFunction;
113
+ agentApprovalGranted: AgentRegisteredFunction;
114
+ agentApprovalGrants: AgentRegisteredFunction;
111
115
  agentCompleteRun: AgentRegisteredFunction;
116
+ agentDeclineSecret: AgentRegisteredFunction;
112
117
  agentDeleteMessage: AgentRegisteredFunction;
118
+ agentDiscardSecret: AgentRegisteredFunction;
113
119
  agentEnsureThread: AgentRegisteredFunction;
114
120
  agentEpisodeRecall: AgentRegisteredFunction;
115
121
  agentEpisodeUpsert: AgentRegisteredFunction;
@@ -117,11 +123,17 @@ interface AgentComponent {
117
123
  agentGraphUpsert: AgentRegisteredFunction;
118
124
  agentHistory: AgentRegisteredFunction;
119
125
  agentMessages: AgentRegisteredFunction;
126
+ agentOpenSecretRequest: AgentRegisteredFunction;
120
127
  agentPatchThread: AgentRegisteredFunction;
121
128
  agentResolveApproval: AgentRegisteredFunction;
129
+ agentRevokeApprovalGrant: AgentRegisteredFunction;
122
130
  agentRun: AgentRegisteredFunction;
131
+ agentSecretRequests: AgentRegisteredFunction;
123
132
  agentSetState: AgentRegisteredFunction;
133
+ agentSettleSecretRequest: AgentRegisteredFunction;
124
134
  agentState: AgentRegisteredFunction;
135
+ agentSupplySecret: AgentRegisteredFunction;
136
+ agentTakeSecret: AgentRegisteredFunction;
125
137
  agentThread: AgentRegisteredFunction;
126
138
  };
127
139
  }
@@ -83,6 +83,8 @@ declare const sandboxComponent: () => SandboxComponent;
83
83
  declare const THREADS_BARE_TABLE = "threads";
84
84
  declare const MESSAGES_BARE_TABLE = "messages";
85
85
  declare const RUN_QUEUE_BARE_TABLE = "run_queue";
86
+ declare const GRANTS_BARE_TABLE = "approval_grants";
87
+ declare const REQUESTS_BARE_TABLE = "secret_requests";
86
88
  /**
87
89
  * The agent thread tables, shipped as a schema extension so an app merges
88
90
  * them with one call and they can never collide with app tables:
@@ -99,7 +101,7 @@ declare const RUN_QUEUE_BARE_TABLE = "run_queue";
99
101
  * message is a no-op instead of a duplicate.
100
102
  * @experimental
101
103
  */
102
- declare const agentExtension: SchemaExtension<Record<keyof typeof episodeTables | keyof typeof graphTables | typeof MESSAGES_BARE_TABLE | typeof RUN_QUEUE_BARE_TABLE | typeof THREADS_BARE_TABLE, TableDefinition>, typeof AGENT_EXTENSION_KEY>;
104
+ declare const agentExtension: SchemaExtension<Record<keyof typeof episodeTables | keyof typeof graphTables | typeof GRANTS_BARE_TABLE | typeof MESSAGES_BARE_TABLE | typeof REQUESTS_BARE_TABLE | typeof RUN_QUEUE_BARE_TABLE | typeof THREADS_BARE_TABLE, TableDefinition>, typeof AGENT_EXTENSION_KEY>;
103
105
  /**
104
106
  * `AgentComponent` is part of the experimental `@lunora/agent` API and may change without a major version bump.
105
107
  * @experimental
@@ -108,8 +110,12 @@ interface AgentComponent {
108
110
  extension: SchemaExtension;
109
111
  functions: {
110
112
  agentAppendMessage: AgentRegisteredFunction;
113
+ agentApprovalGranted: AgentRegisteredFunction;
114
+ agentApprovalGrants: AgentRegisteredFunction;
111
115
  agentCompleteRun: AgentRegisteredFunction;
116
+ agentDeclineSecret: AgentRegisteredFunction;
112
117
  agentDeleteMessage: AgentRegisteredFunction;
118
+ agentDiscardSecret: AgentRegisteredFunction;
113
119
  agentEnsureThread: AgentRegisteredFunction;
114
120
  agentEpisodeRecall: AgentRegisteredFunction;
115
121
  agentEpisodeUpsert: AgentRegisteredFunction;
@@ -117,11 +123,17 @@ interface AgentComponent {
117
123
  agentGraphUpsert: AgentRegisteredFunction;
118
124
  agentHistory: AgentRegisteredFunction;
119
125
  agentMessages: AgentRegisteredFunction;
126
+ agentOpenSecretRequest: AgentRegisteredFunction;
120
127
  agentPatchThread: AgentRegisteredFunction;
121
128
  agentResolveApproval: AgentRegisteredFunction;
129
+ agentRevokeApprovalGrant: AgentRegisteredFunction;
122
130
  agentRun: AgentRegisteredFunction;
131
+ agentSecretRequests: AgentRegisteredFunction;
123
132
  agentSetState: AgentRegisteredFunction;
133
+ agentSettleSecretRequest: AgentRegisteredFunction;
124
134
  agentState: AgentRegisteredFunction;
135
+ agentSupplySecret: AgentRegisteredFunction;
136
+ agentTakeSecret: AgentRegisteredFunction;
125
137
  agentThread: AgentRegisteredFunction;
126
138
  };
127
139
  }
@@ -1,2 +1,2 @@
1
- import{LunoraError as g}from"@lunora/errors";import{defineTable as _,initLunora as $,defineSchemaExtension as H}from"@lunora/server";import{v as e}from"@lunora/values";import{a as b,A as C,d as X,b as Q}from"./packem_shared/component-shared-G8ngerkU.mjs";import{graphTables as W,graphComponent as Y}from"./packem_shared/normalizeEntityName-k3fjicAG.mjs";import{normalizeEntityName as be}from"./packem_shared/normalizeEntityName-k3fjicAG.mjs";import{sandboxComponent as fe}from"./packem_shared/sandboxComponent-Du0yENEO.mjs";const k="agent_episodes",z=5,V=20,J=500,D=200,Z=/\s+/gu,ee=s=>s===void 0||!Number.isFinite(s)?z:Math.min(V,Math.max(1,Math.trunc(s))),te={episodes:_({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:ne,query:ie}=$.dataModel().create(),ae=()=>{const s=ne.input({createdAt:e.optional(e.number()),messageKey:e.string(),owner:e.string(),summary:e.string(),threadKey:e.optional(e.string())}).mutation(async({args:d,ctx:l})=>{const m=d.summary.replaceAll(Z," ").trim().slice(0,J);if(m.length===0)return{recorded:!1};if(await l.db.query(k).withIndex("byOwnerMessageKey",c=>c.eq("owner",d.owner).eq("messageKey",d.messageKey)).first())return{recorded:!1};await l.db.insert(k,{createdAt:d.createdAt??Date.now(),messageKey:d.messageKey,owner:d.owner,summary:m,...d.threadKey===void 0?{}:{threadKey:d.threadKey}});const q=await l.db.query(k).withIndex("byOwnerCreatedAt",c=>c.eq("owner",d.owner)).order("asc").take(D+1);for(const c of q.slice(0,Math.max(0,q.length-D)))await l.db.delete(c._id);return{recorded:!0}}),r=ie.input({limit:e.optional(e.number()),owner:e.string()}).query(async({args:d,ctx:l})=>{const m=await l.db.query(k).withIndex("byOwnerCreatedAt",I=>I.eq("owner",d.owner)).order("desc").take(ee(d.limit));return m.length===0?{context:""}:{context:m.toReversed().map(I=>`- ${I.summary}`).join(`
2
- `)}});return{agentEpisodeRecall:b(r),agentEpisodeUpsert:b(s)}},O="threads",L="messages",U="run_queue",p=`${C}_${O}`,E=`${C}_${L}`,v=`${C}_${U}`,M=5,oe=780*60*1e3,re=H(C,{tables:{[L]:_({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(),[O]:_({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")),summary:e.optional(e.string()),summaryConfig:e.optional(e.string()),summaryRebuiltSeq:e.optional(e.number()),summaryThroughSeq:e.optional(e.number()),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(),[U]:_({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(),...W,...te}}),{mutation:f,query:T}=$.dataModel().create(),se=async(s,r,d)=>{if(r.instanceId===void 0)throw new g("CONFLICT",`@lunora/agent: thread "${r.key}" already has a run in flight (instance "${r.priorInstanceId}") — cannot queue a dispatch with no instance id`);const{instanceId:l}=r,m=await s.query(v).withIndex("byThreadInstance",c=>c.eq("threadKey",r.key).eq("instanceId",l)).first();if(m)return{outcome:"queued",position:m.position};const I=await s.query(v).withIndex("byThread",c=>c.eq("threadKey",r.key)).collect();if(I.length>=M)throw new g("CONFLICT",`@lunora/agent: thread "${r.key}" run queue is full (depth ${String(M)}) — rejecting instance "${l}"`);const q=(I.at(-1)?.position??-1)+1;return await s.insert(v,{agent:r.agent,enqueuedAt:d,instanceId:l,position:q,threadKey:r.key}),{outcome:"queued",position:q}},de=async(s,r,d)=>{if(r.policy==="queue")return se(s,{agent:r.agent,instanceId:r.instanceId,key:r.key,priorInstanceId:r.priorInstanceId},d);if(r.policy!=="replace")throw new g("CONFLICT",`@lunora/agent: thread "${r.key}" already has a run in flight (instance "${r.priorInstanceId}") — onConcurrentRun="${r.policy}"`);return await s.patch(r.existingId,{error:null,status:"running",updatedAt:d,...r.instanceId===void 0?{}:{completedInstanceId:null,instanceId:r.instanceId}}),{outcome:"replaced",priorInstanceId:r.priorInstanceId}},ue=(s,r,d)=>{const l=s.instanceId;if(l===void 0||r===l||s.status!=="running"&&s.status!=="awaiting_input")return;const m=typeof s.updatedAt=="number"?s.updatedAt:0,I=s.status==="awaiting_input"?Q:oe;return d-m>I?void 0:l},he=()=>{const s=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",o=>o.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 o=ue(i,t.instanceId,a);return o!==void 0?de(n.db,{agent:t.agent,existingId:i._id,instanceId:t.instanceId,key:t.key,policy:t.onConcurrentRun??"reject",priorInstanceId:o},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,...X({instanceId:t.instanceId,owner:t.owner,state:t.initialState,title:t.title})}),{outcome:"created"}}),r=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 o=i.messageCount,u=Date.now();return await n.db.insert(E,{content:t.content,createdAt:u,messageKey:t.messageKey,role:t.role,seq:o,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:o+1,updatedAt:u}),{seq:o}}),d=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)}),l=f.input({error:e.optional(e.string()),ifInstanceId: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"))),summary:e.optional(e.string()),summaryConfig:e.optional(e.string()),summaryRebuiltSeq:e.optional(e.number()),summaryThroughSeq:e.optional(e.number()),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 o;i!==void 0?o=await n.db.query(p).withIndex("byKey",u=>u.eq("key",i)).first():a!==void 0&&(o=await n.db.query(p).withIndex("byInstance",u=>u.eq("instanceId",a)).first()),!(!o||t.ifInstanceId!==void 0&&o.instanceId!==t.ifInstanceId)&&await n.db.patch(o._id,{updatedAt:Date.now(),...t.error===void 0?{}:{error:t.error},...t.status===void 0?{}:{status:t.status},...t.summary===void 0?{}:{summary:t.summary},...t.summaryConfig===void 0?{}:{summaryConfig:t.summaryConfig},...t.summaryRebuiltSeq===void 0?{}:{summaryRebuiltSeq:t.summaryRebuiltSeq},...t.summaryThroughSeq===void 0?{}:{summaryThroughSeq:t.summaryThroughSeq},...t.title===void 0?{}:{title:t.title},...t.usage===void 0?{}:{usage:t.usage}})}),m=T.input({configKey:e.optional(e.string()),key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",A=>A.eq("key",t.key)).first(),i=a?.summary,o=a?.summaryThroughSeq,u=a?.summaryRebuiltSeq,y=a?.summaryConfig,h=typeof i=="string"&&i.length>0&&typeof o=="number",w=t.configKey===void 0||y===t.configKey,K=typeof u!="number"||typeof o=="number"&&o>=2*u+1,x=h&&w&&!K,R=await n.db.query(E).withIndex("byThread",A=>x?A.eq("threadKey",t.key).gt("seq",o):A.eq("threadKey",t.key)).collect();return x?{messages:R,summary:i}:h?{fallback:{summary:i,throughSeq:o},messages:R}:{messages:R}}),I=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",w=>w.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 w=await n.db.query(v).withIndex("byThreadInstance",K=>K.eq("threadKey",t.key).eq("instanceId",t.instanceId)).first();return w&&await n.db.delete(w._id),{}}const y=(i.completedInstanceId===t.instanceId?[]:await n.db.query(v).withIndex("byThread",w=>w.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 h=y.instanceId;return await n.db.delete(y._id),await n.db.patch(i._id,{completedInstanceId:t.instanceId,instanceId:h,status:"running",updatedAt:a,...t.error===void 0?{}:{error:t.error},...t.usage===void 0?{}:{usage:t.usage}}),{dequeued:h}}),q=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()})}),c=(t,n)=>{if(!t)return;const{owner:a}=t;if(!(a!==void 0&&a!==(n.userId??void 0)))return t},B=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 c(a,n.auth)}),j=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 c(a,n.auth)?.state}),P=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 c(a,n.auth)===void 0?[]:t.limit!==void 0?(await n.db.query(E).withIndex("byThread",o=>o.eq("threadKey",t.key)).order("desc").take(t.limit)).toReversed():n.db.query(E).withIndex("byThread",i=>i.eq("threadKey",t.key)).collect()}),F=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",h=>h.eq("key",t.threadKey)).first(),i=c(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 o=i.agent,{agents:u}=n,y=u?.[o];if(typeof y?.sendEvent!="function")throw new g("INTERNAL",`@lunora/agent: no ctx.agents["${o}"] 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}}),G=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 o=n.auth.userId??void 0,u=await n.db.query(p).withIndex("byKey",h=>h.eq("key",t.threadKey)).first();if(u){const h=u.status,w=u.instanceId,K=u.owner;if((h==="running"||h==="awaiting_input")&&w!==void 0&&(K===void 0||K===o))return{id:w,threadKey:t.threadKey};if(K!==o)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,...o===void 0?{}:{owner:o},...t.title===void 0?{}:{title:t.title}});return{id:y,threadKey:t.threadKey}}),S=Y(),N=ae();return{extension:re,functions:{agentAppendMessage:b(r),agentCompleteRun:b(I),agentEnsureThread:b(s),agentEpisodeRecall:N.agentEpisodeRecall,agentEpisodeUpsert:N.agentEpisodeUpsert,agentGraphTraverse:S.agentGraphTraverse,agentGraphUpsert:S.agentGraphUpsert,agentHistory:b(m),agentMessages:P,agentDeleteMessage:b(d),agentPatchThread:b(l),agentResolveApproval:F,agentRun:G,agentSetState:b(q),agentState:j,agentThread:B}}};export{he as agentComponent,re as agentExtension,be as normalizeEntityName,fe as sandboxComponent};
1
+ import{LunoraError as h}from"@lunora/errors";import{SecretValueTooLargeError as pe}from"@lunora/platform";import{defineTable as E,initLunora as W,defineSchemaExtension as he}from"@lunora/server";import{v as e}from"@lunora/values";import{a as K,A as _,d as me,b as we,c as Ie,S as be}from"./packem_shared/component-shared-DdXFbng-.mjs";import{graphTables as ge,graphComponent as fe}from"./packem_shared/normalizeEntityName-CmalZhT_.mjs";import{normalizeEntityName as Xe}from"./packem_shared/normalizeEntityName-CmalZhT_.mjs";import{sandboxComponent as Ye}from"./packem_shared/sandboxComponent-Du0yENEO.mjs";const x="agent_episodes",qe=5,Ke=20,ve=500,G=200,Ae=/\s+/gu,Te=s=>s===void 0||!Number.isFinite(s)?qe:Math.min(Ke,Math.max(1,Math.trunc(s))),Ce={episodes:E({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:Ee,query:_e}=W.dataModel().create(),ke=()=>{const s=Ee.input({createdAt:e.optional(e.number()),messageKey:e.string(),owner:e.string(),summary:e.string(),threadKey:e.optional(e.string())}).mutation(async({args:d,ctx:l})=>{const c=d.summary.replaceAll(Ae," ").trim().slice(0,ve);if(c.length===0)return{recorded:!1};if(await l.db.query(x).withIndex("byOwnerMessageKey",y=>y.eq("owner",d.owner).eq("messageKey",d.messageKey)).first())return{recorded:!1};await l.db.insert(x,{createdAt:d.createdAt??Date.now(),messageKey:d.messageKey,owner:d.owner,summary:c,...d.threadKey===void 0?{}:{threadKey:d.threadKey}});const g=await l.db.query(x).withIndex("byOwnerCreatedAt",y=>y.eq("owner",d.owner)).order("asc").take(G+1);for(const y of g.slice(0,Math.max(0,g.length-G)))await l.db.delete(y._id);return{recorded:!0}}),o=_e.input({limit:e.optional(e.number()),owner:e.string()}).query(async({args:d,ctx:l})=>{const c=await l.db.query(x).withIndex("byOwnerCreatedAt",p=>p.eq("owner",d.owner)).order("desc").take(Te(d.limit));return c.length===0?{context:""}:{context:c.toReversed().map(p=>`- ${p.summary}`).join(`
2
+ `)}});return{agentEpisodeRecall:K(o),agentEpisodeUpsert:K(s)}},X="threads",V="messages",Y="run_queue",z="approval_grants",J="secret_requests",w=`${_}_${X}`,A=`${_}_${V}`,R=`${_}_${Y}`,$=`${_}_${z}`,O=`${_}_${J}`,P=5,B=e.object({cacheReadTokens:e.optional(e.number()),cacheWriteTokens:e.optional(e.number()),inputTokens:e.optional(e.number()),outputTokens:e.optional(e.number()),reasoningTokens:e.optional(e.number()),status:e.optional(e.union(e.literal("complete"),e.literal("partial"),e.literal("unavailable"))),totalTokens:e.optional(e.number())}),Se=780*60*1e3,Ne=he(_,{tables:{[V]:E({approvalScope:e.optional(e.literal("thread")),content:e.string(),createdAt:e.number(),expiresAt:e.optional(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("awaiting_secret"),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(),[X]:E({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")),summary:e.optional(e.string()),summaryConfig:e.optional(e.string()),summaryRebuiltSeq:e.optional(e.number()),summaryThroughSeq:e.optional(e.number()),title:e.optional(e.string()),updatedAt:e.number(),usage:e.optional(B)}).index("byKey",["key"],{unique:!0}).index("byAgent",["agent"]).index("byInstance",["instanceId"]).public(),[Y]:E({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(),[z]:E({createdAt:e.number(),threadKey:e.string(),toolName:e.string()}).index("byThreadTool",["threadKey","toolName"],{unique:!0}).public(),[J]:E({consumerTool:e.string(),createdAt:e.number(),expiresAt:e.number(),instanceId:e.string(),ref:e.optional(e.string().nullable()),label:e.optional(e.string().nullable()),status:e.union(e.literal("pending"),e.literal("supplied"),e.literal("declined"),e.literal("expired"),e.literal("consumed")),threadKey:e.string(),toolCallId:e.string(),callId:e.optional(e.string()),toolName:e.string(),updatedAt:e.number()}).index("byThreadCall",["threadKey","toolCallId"],{unique:!0}).index("byThreadCallId",["threadKey","callId"]).public(),...ge,...Ce}}),{mutation:q,query:C}=W.dataModel().create(),Re=async(s,o,d,l)=>{const c=await s.query(A).withIndex("byMessageKey",k=>k.eq("threadKey",o).eq("messageKey",`${d}:approval:${l}`)).first();if(c?.status!=="awaiting_approval")throw new h("CONFLICT",`@lunora/agent: no pending approval for tool call "${l}" to grant for thread "${o}"`);const{expiresAt:p}=c;if(typeof p!="number")throw new h("CONFLICT",`@lunora/agent: the approval for tool call "${l}" on thread "${o}" has no recorded deadline, so it cannot be granted for the thread`);if(Date.now()>=p)throw new h("CONFLICT",`@lunora/agent: the approval for tool call "${l}" on thread "${o}" has timed out`);const g=c.toolName;await s.query($).withIndex("byThreadTool",k=>k.eq("threadKey",o).eq("toolName",g)).first()||await s.insert($,{createdAt:Date.now(),threadKey:o,toolName:g})},$e=async(s,o,d,l)=>(await s.query(A).withIndex("byMessageKey",p=>p.eq("threadKey",o).eq("messageKey",`${d}:approval:${l}`)).first())?.status==="awaiting_approval",xe=async(s,o,d,l)=>{const c=await s.query(A).withIndex("byMessageKey",p=>p.eq("threadKey",o).eq("messageKey",`${d}:approval:${l}`)).first();c?.status==="awaiting_approval"&&await s.delete(c._id)},M=s=>{const{agentSecrets:o}=s;if(o===void 0)throw new h("NOT_IMPLEMENTED","@lunora/agent: no secret store is wired on this deployment. Codegen wires one only when a source in lunora/ value-imports requestSecretTool from @lunora/agent (directly, through a namespace import, or through a relative barrel that re-exports it); add that import, or this target cannot hold a human-supplied secret value");return o},D=(s,o,d)=>{const l=o.userId??void 0;if(s===null||l===void 0||s.owner!==l)throw new h("FORBIDDEN",`@lunora/agent: only the thread's owner can ${d}`);return s},j=async(s,o,d)=>{const{instanceId:l,key:c}=o,p=typeof l=="string"?await s.query(A).withIndex("byMessageKey",g=>g.eq("threadKey",c).eq("messageKey",`${l}:secret:${d}`)).first():void 0;if(p?.status!=="awaiting_secret")throw new h("CONFLICT",`@lunora/agent: no pending secret request for tool call "${d}" on thread "${c}"`);return p},N=async(s,o,d)=>await s.query(O).withIndex("byThreadCall",c=>c.eq("threadKey",o).eq("toolCallId",d)).first()??void 0,H=async(s,o,d,l,c)=>{const g=(await s.query(O).withIndex("byThreadCallId",y=>y.eq("threadKey",o).eq("callId",l)).collect()).filter(y=>y.status==="pending"&&y.instanceId===d&&c<y.expiresAt);if(g.length!==1)throw new h("CONFLICT",`@lunora/agent: no pending secret request for tool call "${l}" on thread "${o}"`);return g[0]},De=(s,o)=>Math.max(Ie,s+be-o),L=async(s,o,d,l)=>{const c=await N(s,o,d);if(c?.status!=="pending"||l>=c.expiresAt)throw new h("CONFLICT",`@lunora/agent: no open secret request for tool call "${d}" on thread "${o}"`);return c},Q=(s,o)=>{const{instanceId:d}=o,{agents:l}=s,c=l?.[o.agent];if(typeof d!="string"||typeof c?.sendEvent!="function")throw new h("INTERNAL",`@lunora/agent: no ctx.agents["${String(o.agent)}"] producer to deliver the secret — run codegen/dev`);return{instanceId:d,sendEvent:c.sendEvent}},Oe=async(s,o,d)=>{if(o.instanceId===void 0)throw new h("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:l}=o,c=await s.query(R).withIndex("byThreadInstance",y=>y.eq("threadKey",o.key).eq("instanceId",l)).first();if(c)return{outcome:"queued",position:c.position};const p=await s.query(R).withIndex("byThread",y=>y.eq("threadKey",o.key)).collect();if(p.length>=P)throw new h("CONFLICT",`@lunora/agent: thread "${o.key}" run queue is full (depth ${String(P)}) — rejecting instance "${l}"`);const g=(p.at(-1)?.position??-1)+1;return await s.insert(R,{agent:o.agent,enqueuedAt:d,instanceId:l,position:g,threadKey:o.key}),{outcome:"queued",position:g}},Me=async(s,o,d)=>{if(o.policy==="queue")return Oe(s,{agent:o.agent,instanceId:o.instanceId,key:o.key,priorInstanceId:o.priorInstanceId},d);if(o.policy!=="replace")throw new h("CONFLICT",`@lunora/agent: thread "${o.key}" already has a run in flight (instance "${o.priorInstanceId}") — onConcurrentRun="${o.policy}"`);return await s.patch(o.existingId,{error:null,status:"running",updatedAt:d,...o.instanceId===void 0?{}:{completedInstanceId:null,instanceId:o.instanceId}}),{outcome:"replaced",priorInstanceId:o.priorInstanceId}},Le=(s,o,d)=>{const l=s.instanceId;if(l===void 0||o===l||s.status!=="running"&&s.status!=="awaiting_input")return;const c=typeof s.updatedAt=="number"?s.updatedAt:0,p=s.status==="awaiting_input"?we:Se;return d-c>p?void 0:l},He=()=>{const s=q.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(w).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=Le(i,t.instanceId,a);return r!==void 0?Me(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(w,{agent:t.agent,createdAt:a,key:t.key,messageCount:0,status:"running",updatedAt:a,...me({instanceId:t.instanceId,owner:t.owner,state:t.initialState,title:t.title})}),{outcome:"created"}}),o=q.input({approvalScope:e.optional(e.literal("thread")),content:e.string(),expiresAt:e.optional(e.number()),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("awaiting_secret"),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(A).withIndex("byMessageKey",m=>m.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();if(a)return{seq:a.seq};const i=await n.db.query(w).withIndex("byKey",m=>m.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,u=Date.now();return await n.db.insert(A,{content:t.content,createdAt:u,messageKey:t.messageKey,role:t.role,seq:r,threadKey:t.threadKey,...t.approvalScope===void 0?{}:{approvalScope:t.approvalScope},...t.expiresAt===void 0?{}:{expiresAt:t.expiresAt},...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:u}),{seq:r}}),d=q.input({messageKey:e.string(),threadKey:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(A).withIndex("byMessageKey",i=>i.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();a&&await n.db.delete(a._id)}),l=q.input({error:e.optional(e.string()),ifInstanceId: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"))),summary:e.optional(e.string()),summaryConfig:e.optional(e.string()),summaryRebuiltSeq:e.optional(e.number()),summaryThroughSeq:e.optional(e.number()),title:e.optional(e.string()),usage:e.optional(B)}).mutation(async({args:t,ctx:n})=>{const{instanceId:a,key:i}=t;let r;i!==void 0?r=await n.db.query(w).withIndex("byKey",u=>u.eq("key",i)).first():a!==void 0&&(r=await n.db.query(w).withIndex("byInstance",u=>u.eq("instanceId",a)).first()),!(!r||t.ifInstanceId!==void 0&&r.instanceId!==t.ifInstanceId)&&await n.db.patch(r._id,{updatedAt:Date.now(),...t.error===void 0?{}:{error:t.error},...t.status===void 0?{}:{status:t.status},...t.summary===void 0?{}:{summary:t.summary},...t.summaryConfig===void 0?{}:{summaryConfig:t.summaryConfig},...t.summaryRebuiltSeq===void 0?{}:{summaryRebuiltSeq:t.summaryRebuiltSeq},...t.summaryThroughSeq===void 0?{}:{summaryThroughSeq:t.summaryThroughSeq},...t.title===void 0?{}:{title:t.title},...t.usage===void 0?{}:{usage:t.usage}})}),c=C.input({configKey:e.optional(e.string()),key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(w).withIndex("byKey",b=>b.eq("key",t.key)).first(),i=a?.summary,r=a?.summaryThroughSeq,u=a?.summaryRebuiltSeq,m=a?.summaryConfig,I=typeof i=="string"&&i.length>0&&typeof r=="number",f=t.configKey===void 0||m===t.configKey,v=typeof u!="number"||typeof r=="number"&&r>=2*u+1,S=I&&f&&!v,T=await n.db.query(A).withIndex("byThread",b=>S?b.eq("threadKey",t.key).gt("seq",r):b.eq("threadKey",t.key)).collect();return S?{messages:T,summary:i}:I?{fallback:{summary:i,throughSeq:r},messages:T}:{messages:T}}),p=q.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(B)}).mutation(async({args:t,ctx:n})=>{const a=Date.now(),i=await n.db.query(w).withIndex("byKey",f=>f.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 f=await n.db.query(R).withIndex("byThreadInstance",v=>v.eq("threadKey",t.key).eq("instanceId",t.instanceId)).first();return f&&await n.db.delete(f._id),{}}const m=(i.completedInstanceId===t.instanceId?[]:await n.db.query(R).withIndex("byThread",f=>f.eq("threadKey",t.key)).collect())[0];if(!m)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 I=m.instanceId;return await n.db.delete(m._id),await n.db.patch(i._id,{completedInstanceId:t.instanceId,instanceId:I,status:"running",updatedAt:a,...t.error===void 0?{}:{error:t.error},...t.usage===void 0?{}:{usage:t.usage}}),{dequeued:I}}),g=q.input({key:e.string(),state:e.any()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(w).withIndex("byKey",i=>i.eq("key",t.key)).first();a&&await n.db.patch(a._id,{state:t.state,updatedAt:Date.now()})}),y=(t,n)=>{if(!t)return;const{owner:a}=t;if(!(a!==void 0&&a!==(n.userId??void 0)))return t},k=C.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(w).withIndex("byKey",i=>i.eq("key",t.key)).first();return y(a,n.auth)}),Z=C.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(w).withIndex("byKey",i=>i.eq("key",t.key)).first();return y(a,n.auth)?.state}),ee=C.input({key:e.string(),limit:e.optional(e.number())}).query(async({args:t,ctx:n})=>{const a=await n.db.query(w).withIndex("byKey",i=>i.eq("key",t.key)).first();return y(a,n.auth)===void 0?[]:t.limit!==void 0?(await n.db.query(A).withIndex("byThread",r=>r.eq("threadKey",t.key)).order("desc").take(t.limit)).toReversed():n.db.query(A).withIndex("byThread",i=>i.eq("threadKey",t.key)).collect()}),te=q.input({decision:e.union(e.literal("approve"),e.literal("approve_for_thread"),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(w).withIndex("byKey",I=>I.eq("key",t.threadKey)).first(),i=y(a,n.auth);if(i===void 0)throw new h("FORBIDDEN",`@lunora/agent: not allowed to resolve approvals on thread "${t.threadKey}"`);if(i.instanceId!==t.instanceId)throw new h("FORBIDDEN",`@lunora/agent: instance "${t.instanceId}" does not own thread "${t.threadKey}"`);const r=i.agent,{agents:u}=n,m=u?.[r];if(typeof m?.sendEvent!="function")throw new h("INTERNAL",`@lunora/agent: no ctx.agents["${r}"] producer to resolve the approval — run codegen/dev so the agent binding is wired`);if(!await $e(n.db,t.threadKey,t.instanceId,t.toolCallId))throw new h("CONFLICT",`@lunora/agent: no pending approval for tool call "${t.toolCallId}" on thread "${t.threadKey}" to decide`);return t.decision==="approve_for_thread"&&(D(a,n.auth,"grant a lasting approval for a tool"),await Re(n.db,t.threadKey,t.instanceId,t.toolCallId)),await xe(n.db,t.threadKey,t.instanceId,t.toolCallId),await m.sendEvent(t.instanceId,{payload:{decision:t.decision==="reject"?"reject":"approve",toolCallId:t.toolCallId,...t.decision==="approve_for_thread"?{scope:"thread"}:{},...t.note===void 0?{}:{note:t.note}},type:`agent-approval:${t.toolCallId}`}),{resolved:!0}}),ne=q.input({secret:e.sensitive(e.string()),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=D(await n.db.query(w).withIndex("byKey",b=>b.eq("key",t.threadKey)).first(),n.auth,"supply or decline a secret on it"),i=M(n),u=(await H(n.db,t.threadKey,a.instanceId,t.toolCallId,Date.now())).toolCallId,m=await j(n.db,a,u),I=Q(n,a),f=a.instanceId,v=b=>{if(b.instanceId!==f)throw new h("CONFLICT",`@lunora/agent: tool call "${t.toolCallId}" on thread "${t.threadKey}" was reopened by a newer run while its secret was being stored`)},S=await L(n.db,t.threadKey,u,Date.now());v(S);let T;try{T=await i.put(t.secret,{scope:t.threadKey,ttlMs:De(S.expiresAt,Date.now())})}catch(b){throw b instanceof pe?new h("PAYLOAD_TOO_LARGE",b.message):b}try{const b=await L(n.db,t.threadKey,u,Date.now());v(b),await n.db.patch(b._id,{ref:T,status:"supplied",updatedAt:Date.now()}),await n.db.delete(m._id)}catch(b){throw await i.discard(T).catch(()=>{}),b}try{await I.sendEvent(I.instanceId,{payload:{},type:`agent-secret:${u}`})}catch{}return{resolved:!0}}),ae=q.input({threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=D(await n.db.query(w).withIndex("byKey",f=>f.eq("key",t.threadKey)).first(),n.auth,"supply or decline a secret on it"),r=(await H(n.db,t.threadKey,a.instanceId,t.toolCallId,Date.now())).toolCallId,u=await j(n.db,a,r),m=Q(n,a),I=await L(n.db,t.threadKey,r,Date.now());await n.db.patch(I._id,{status:"declined",updatedAt:Date.now()}),await n.db.delete(u._id);try{await m.sendEvent(m.instanceId,{payload:{},type:`agent-secret:${r}`})}catch{}return{resolved:!0}}),ie=K(q.input({consumerTool:e.string(),expiresAt:e.number(),instanceId:e.string(),callId:e.optional(e.string()),label:e.optional(e.string()),threadKey:e.string(),toolCallId:e.string(),toolName:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await N(n.db,t.threadKey,t.toolCallId),i=Date.now();if(a===void 0){await n.db.insert(O,{consumerTool:t.consumerTool,createdAt:i,expiresAt:t.expiresAt,instanceId:t.instanceId,label:t.label??null,status:"pending",callId:t.callId??t.toolCallId,threadKey:t.threadKey,toolCallId:t.toolCallId,toolName:t.toolName,updatedAt:i});return}if(a.instanceId!==t.instanceId){if(typeof a.ref=="string"){const{agentSecrets:r}=n;await r?.discard(a.ref)}await n.db.patch(a._id,{consumerTool:t.consumerTool,createdAt:i,expiresAt:t.expiresAt,label:t.label??null,ref:null,callId:t.callId??t.toolCallId,instanceId:t.instanceId,status:"pending",toolName:t.toolName,updatedAt:i})}})),oe=K(q.input({instanceId:e.string(),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await N(n.db,t.threadKey,t.toolCallId);if(a?.instanceId!==t.instanceId)return{status:"expired"};const{status:i}=a;return i==="pending"?(await n.db.patch(a._id,{status:"expired",updatedAt:Date.now()}),{status:"expired"}):i==="supplied"||i==="consumed"?{status:"supplied"}:{status:i==="declined"?"declined":"expired"}})),re=K(q.input({claimant:e.string(),consumerCallId:e.string(),instanceId:e.string(),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await N(n.db,t.threadKey,t.toolCallId);if(!(a?.instanceId!==t.instanceId||a.status!=="supplied"&&a.status!=="consumed")&&!(typeof a.ref!="string"||t.claimant!==`tool:${a.consumerTool}:${t.consumerCallId}`))return M(n).take(a.ref,{claimant:t.claimant,scope:t.threadKey})})),se=K(q.input({instanceId:e.string(),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await N(n.db,t.threadKey,t.toolCallId);a?.instanceId===t.instanceId&&(typeof a.ref=="string"&&await M(n).discard(a.ref),a.status==="supplied"&&await n.db.patch(a._id,{status:"consumed",updatedAt:Date.now()}))})),de=C.input({threadKey:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(w).withIndex("byKey",u=>u.eq("key",t.threadKey)).first();D(a,n.auth,"list its secret requests");const i=await n.db.query(O).withIndex("byThreadCall",u=>u.eq("threadKey",t.threadKey)).collect(),r=Date.now();return i.map(u=>({createdAt:u.createdAt,expiresAt:u.expiresAt,...typeof u.label=="string"?{label:u.label}:{},status:u.status==="pending"&&r>=u.expiresAt?"expired":u.status,toolCallId:u.callId??u.toolCallId,toolName:u.toolName}))}),le=K(C.input({key:e.string(),toolName:e.string()}).query(async({args:t,ctx:n})=>await n.db.query($).withIndex("byThreadTool",i=>i.eq("threadKey",t.key).eq("toolName",t.toolName)).first()!==null)),ue=C.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(w).withIndex("byKey",r=>r.eq("key",t.key)).first();return y(a,n.auth)===void 0?[]:(await n.db.query($).withIndex("byThreadTool",r=>r.eq("threadKey",t.key)).collect()).map(r=>({createdAt:r.createdAt,toolName:r.toolName}))}),ce=q.input({threadKey:e.string(),toolName:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(w).withIndex("byKey",r=>r.eq("key",t.threadKey)).first();if(y(a,n.auth)===void 0)throw new h("FORBIDDEN",`@lunora/agent: not allowed to revoke approvals on thread "${t.threadKey}"`);const i=await n.db.query($).withIndex("byThreadTool",r=>r.eq("threadKey",t.threadKey).eq("toolName",t.toolName)).first();return i?(await n.db.delete(i._id),{revoked:!0}):{revoked:!1}}),ye=q.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 h("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 h("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,u=await n.db.query(w).withIndex("byKey",I=>I.eq("key",t.threadKey)).first();if(u){const I=u.status,f=u.instanceId,v=u.owner;if((I==="running"||I==="awaiting_input")&&f!==void 0&&(v===void 0||v===r))return{id:f,threadKey:t.threadKey};if(v!==r)throw new h("FORBIDDEN",`@lunora/agent: thread "${t.threadKey}" belongs to another owner`)}const{id:m}=await i.run({input:t.input,threadKey:t.threadKey,...r===void 0?{}:{owner:r},...t.title===void 0?{}:{title:t.title}});return{id:m,threadKey:t.threadKey}}),F=fe(),U=ke();return{extension:Ne,functions:{agentApprovalGranted:le,agentApprovalGrants:ue,agentAppendMessage:K(o),agentCompleteRun:K(p),agentEnsureThread:K(s),agentEpisodeRecall:U.agentEpisodeRecall,agentEpisodeUpsert:U.agentEpisodeUpsert,agentGraphTraverse:F.agentGraphTraverse,agentGraphUpsert:F.agentGraphUpsert,agentHistory:K(c),agentMessages:ee,agentDeleteMessage:K(d),agentPatchThread:K(l),agentResolveApproval:te,agentRevokeApprovalGrant:ce,agentRun:ye,agentSetState:K(g),agentState:Z,agentSupplySecret:ne,agentTakeSecret:re,agentThread:k,agentDeclineSecret:ae,agentDiscardSecret:se,agentOpenSecretRequest:ie,agentSecretRequests:de,agentSettleSecretRequest:oe}}};export{He as agentComponent,Ne as agentExtension,Xe as normalizeEntityName,Ye as sandboxComponent};
@@ -1,4 +1,4 @@
1
- import { A as AgentDefinition } from "./packem_shared/types.d-DqYbp4ye.mjs";
1
+ import { A as AgentDefinition } from "./packem_shared/types.d-vAmttAsE.mjs";
2
2
  import '@lunora/mail/inbound';
3
3
  import 'ai';
4
4
  /**
package/dist/inbound.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as AgentDefinition } from "./packem_shared/types.d-DqYbp4ye.js";
1
+ import { A as AgentDefinition } from "./packem_shared/types.d-vAmttAsE.js";
2
2
  import '@lunora/mail/inbound';
3
3
  import 'ai';
4
4
  /**
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as AgentDefinition, e as AgentCompact, f as AgentEpisodeExtract, g as AgentGraphExtract, h as AgentGenerate, i as AgentTokenSink, j as AgentRunInput, k as AgentFunctionPaths, l as AgentRunFunction, m as AgentStepLike, n as AgentStreamGenerate, o as AgentRunResult, p as AgentMessageRow, q as AgentConfig, b as SkillDefinition, r as AnyAgentTool, s as AgentAsToolOptions, t as AgentSubToolInput, c as AgentToolDefinition, u as AgentBindingSpec, v as AgentHandle, w as AgentToolConfig, x as AgentFunctionReference, y as AgentModelInput, z as SkillConfig } from "./packem_shared/types.d-DqYbp4ye.mjs";
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-DqYbp4ye.mjs";
1
+ import { A as AgentDefinition, e as AgentCompact, f as AgentEpisodeExtract, g as AgentGraphExtract, h as AgentGenerate, i as AgentTokenSink, j as AgentRunInput, k as AgentFunctionPaths, l as AgentRunFunction, m as AgentStepLike, n as AgentStreamGenerate, o as AgentRunResult, p as AgentMessageRow, q as AgentConfig, b as SkillDefinition, r as AnyAgentTool, s as AgentAsToolOptions, t as AgentSubToolInput, c as AgentToolDefinition, u as AgentBindingSpec, v as AgentHandle, w as AgentToolConfig, x as AgentFunctionReference, y as AgentModelInput, d as AgentToolContext, z as SkillConfig } from "./packem_shared/types.d-vAmttAsE.mjs";
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, $ as AgentUsage, a0 as AgentVoiceConfig, a1 as AgentWorkflowBindingLike, a2 as AgentWorkflowInstanceLike, a3 as EnsureThreadOutcome } from "./packem_shared/types.d-vAmttAsE.mjs";
3
3
  export { type AgentComponent, agentComponent, agentExtension } from "./component.mjs";
4
4
  import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
5
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";
@@ -592,6 +592,82 @@ declare const DEFAULT_AGENT_FUNCTION_PATHS: AgentFunctionPaths;
592
592
  * @experimental
593
593
  */
594
594
  declare const toFunctionReference: (source: AgentFunctionReference | string) => AgentFunctionReference;
595
+ /** The model's input to {@link requestSecretTool}: what the secret is for, shown to the person asked. */
596
+ interface SecretRequestInput {
597
+ label: string;
598
+ }
599
+ /**
600
+ * Thrown by {@link withSecret} when the value is no longer takeable. The loop
601
+ * records it as a deterministic tool failure, so the model can recover rather
602
+ * than the durable step retrying a read that can never succeed.
603
+ */
604
+ declare class SecretUnavailableError extends Error {
605
+ readonly code = "SECRET_UNAVAILABLE";
606
+ constructor();
607
+ }
608
+ /**
609
+ * An agent tool that asks the human for a secret value (an API key, a token) and
610
+ * hands the model only an opaque `{ secretRef }` in return. The loop pauses the
611
+ * run until the owner supplies the value through `agents:agentSupplySecret`, or
612
+ * declines through `agents:agentDeclineSecret`. `execute` is never called: the
613
+ * loop resolves this tool itself.
614
+ *
615
+ * `consumer` names the one tool allowed to read the value. The model can pass the
616
+ * `secretRef` to any tool, but only the declared consumer's {@link withSecret} call
617
+ * takes it, so a prompt-injected model cannot route the value elsewhere.
618
+ *
619
+ * Codegen wires the secret store when a source in `lunora/` value-imports this tool
620
+ * from `@lunora/agent`: by a named import, a namespace import that reads it, or a
621
+ * relative barrel that re-exports it. Without that wiring the supply mutation refuses,
622
+ * and the refusal names the missing import. Requires a host that rates `secretValues`
623
+ * as supported.
624
+ *
625
+ * ```ts
626
+ * import { defineAgent, requestSecretTool } from "@lunora/agent";
627
+ *
628
+ * export const billing = defineAgent({
629
+ * tools: {
630
+ * requestApiKey: requestSecretTool({
631
+ * consumer: "chargeCard",
632
+ * description: "Ask the user for their payment-provider API key.",
633
+ * }),
634
+ * chargeCard: functionTool({ ... }), // reads the value with withSecret
635
+ * },
636
+ * });
637
+ * ```
638
+ *
639
+ * The value transits the supply mutation's arguments, which are marked
640
+ * `v.sensitive`: the request log masks them. The run's history records only the
641
+ * request id.
642
+ * @experimental
643
+ */
644
+ declare const requestSecretTool: (options: {
645
+ consumer: string;
646
+ description: string;
647
+ }) => AgentToolDefinition<SecretRequestInput, {
648
+ secretRef: string;
649
+ }>;
650
+ /**
651
+ * Read a human-supplied secret inside the tool that the request declared as its
652
+ * `consumer`, hand it to `use`, and return only what `use` returns. The value never
653
+ * leaves the callback: it is not a step output, not a tool result and not a message.
654
+ * The read is its own durable step named for this call, so a retry of the same step
655
+ * re-takes the value (the claimant is this step's name), while a different call
656
+ * cannot.
657
+ *
658
+ * Call it from inside a tool's `execute`. The discard runs as a separate durable step
659
+ * only after the take succeeded and `use` returned, so a call that is refused (the
660
+ * wrong tool, another thread, an expired request) cannot burn a value the declared
661
+ * consumer still needs. If `use` keeps failing, the value stays until its TTL expires,
662
+ * which is the backstop for a crash between the take and the discard. `use` must not
663
+ * return or log the value. A result that carries it is refused (the call fails with
664
+ * `LunoraError`) rather than journalled. An error that carries it is redacted before
665
+ * it propagates, so the step's retry, the failure the loop records and telemetry never
666
+ * see the value; `traceToolExecution` records the tool's input and output.
667
+ * @throws {SecretUnavailableError} when the request is unknown, not supplied, declared for another consumer, or from another thread
668
+ * @experimental
669
+ */
670
+ declare const withSecret: <Result>(context: AgentToolContext, secretRef: string, use: (secret: string) => Promise<Result> | Result) => Promise<Result>;
595
671
  /**
596
672
  * Declare a reusable skill: a bundle of expertise — an instruction fragment,
597
673
  * tools, and retrieval `knowledge` — an agent composes in via
@@ -628,12 +704,28 @@ declare const defineSkill: (config: SkillConfig) => SkillDefinition;
628
704
  * @experimental
629
705
  */
630
706
  declare const isSkillDefinition: (value: unknown) => value is SkillDefinition;
707
+ /**
708
+ * Wrap untrusted text for inclusion in a prompt. The text sits between a tag
709
+ * whose id is random per call, so payload text cannot forge the closing tag (it
710
+ * cannot know the id), and any `<` or `>` in it is escaped so it cannot form a
711
+ * tag at all. A mention or cashtag (`@`, `$`) not glued to a word, and a slash
712
+ * command `/` at the start of a token, get a zero-width space after them. Given a header map, the headers are rendered
713
+ * above the body with credential-like values redacted. A one-line note after the
714
+ * block tells the model the enclosed data is not to be followed as instructions.
715
+ *
716
+ * Use it on the text a mapper hands the model, e.g. `input: wrapUntrusted(email.text ?? "")`.
717
+ * @experimental
718
+ */
719
+ declare const wrapUntrusted: (value: string, headers?: Headers | Readonly<Record<string, string>>) => string;
631
720
  /**
632
721
  * A control frame the server sends the client as a JSON text message (audio
633
722
  * rides separate binary frames). `ready` announces the negotiated codec on
634
723
  * connect; `user_transcript` carries the STT result; `assistant_delta` streams
635
724
  * the live LLM text; `assistant_done` is the final turn text; `interrupted`
636
- * acks a barge-in; `error` reports a non-fatal turn failure.
725
+ * acks a barge-in; `assistant_discarded` says the turn failed, so the deltas
726
+ * already streamed for it are not an answer; `error` reports a failure. An
727
+ * `error` alone does not end a turn: a speech-synthesis failure reports one and
728
+ * the turn still completes.
637
729
  * @experimental
638
730
  */
639
731
  type VoiceServerFrame = {
@@ -651,6 +743,8 @@ type VoiceServerFrame = {
651
743
  } | {
652
744
  text: string;
653
745
  type: "user_transcript";
746
+ } | {
747
+ type: "assistant_discarded";
654
748
  } | {
655
749
  type: "interrupted";
656
750
  };
@@ -924,4 +1018,4 @@ declare const webSearchTool: (options?: WebSearchToolOptions) => AgentToolDefini
924
1018
  declare const compileAgentWorkflow: (agent: AgentDefinition, exportName: string, options?: {
925
1019
  paths?: AgentFunctionPaths;
926
1020
  }) => WorkflowDefinition<AgentRunInput, AgentRunResult>;
927
- export { AGENT_MODULE, type AgentAsToolOptions, type AgentBindingSpec, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentGenerate, type AgentHandle, type AgentLoopOptions, type AgentMemoryReadInput, type AgentMemorySearchHit, type AgentMemorySearchInput, type AgentMemorySearchResult, type AgentMessageRow, type AgentModelInput, type AgentRunFunction, type AgentRunInput, type AgentRunResult, type AgentStepLike, type AgentStreamGenerate, type AgentSubToolInput, type AgentTokenSink, type AgentToolConfig, type AgentToolDefinition, type AnyAgentTool, type CodeToolOptions, DEFAULT_AGENT_FUNCTION_PATHS, type FunctionToolOptions, type McpCallResult, type McpClientLike, type McpContentPart, type McpToolInfo, type McpToolsOptions, type RunVoiceTurnOptions, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, type SkillConfig, type SkillDefinition, type ToolScript, type ToolScriptResult, type ToolScriptStep, type VoiceAudioSource, type VoiceClientFrame, type VoiceSend, type VoiceSendAudio, type VoiceServerFrame, VoiceSessionDO, type VoiceSynthesize, type VoiceTranscribe, type VoiceTurnResult, type WebSearchToolInput, type WebSearchToolOptions, adaptMcpResult, agentAsTool, buildModelMessages, codeTool, collectAgenticMemoryTools, compileAgentWorkflow, createAgentContext, createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, mcpTools, resolveAgentModel, runAgentLoop, runVoiceTurn, splitForCompaction, toFunctionReference, toSearchResults, webSearchTool };
1021
+ export { AGENT_MODULE, type AgentAsToolOptions, type AgentBindingSpec, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentGenerate, type AgentHandle, type AgentLoopOptions, type AgentMemoryReadInput, type AgentMemorySearchHit, type AgentMemorySearchInput, type AgentMemorySearchResult, type AgentMessageRow, type AgentModelInput, type AgentRunFunction, type AgentRunInput, type AgentRunResult, type AgentStepLike, type AgentStreamGenerate, type AgentSubToolInput, type AgentTokenSink, type AgentToolConfig, type AgentToolContext, type AgentToolDefinition, type AnyAgentTool, type CodeToolOptions, DEFAULT_AGENT_FUNCTION_PATHS, type FunctionToolOptions, type McpCallResult, type McpClientLike, type McpContentPart, type McpToolInfo, type McpToolsOptions, type RunVoiceTurnOptions, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, type SecretRequestInput, SecretUnavailableError, type SkillConfig, type SkillDefinition, type ToolScript, type ToolScriptResult, type ToolScriptStep, type VoiceAudioSource, type VoiceClientFrame, type VoiceSend, type VoiceSendAudio, type VoiceServerFrame, VoiceSessionDO, type VoiceSynthesize, type VoiceTranscribe, type VoiceTurnResult, type WebSearchToolInput, type WebSearchToolOptions, adaptMcpResult, agentAsTool, buildModelMessages, codeTool, collectAgenticMemoryTools, compileAgentWorkflow, createAgentContext, createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, mcpTools, requestSecretTool, resolveAgentModel, runAgentLoop, runVoiceTurn, splitForCompaction, toFunctionReference, toSearchResults, webSearchTool, withSecret, wrapUntrusted };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as AgentDefinition, e as AgentCompact, f as AgentEpisodeExtract, g as AgentGraphExtract, h as AgentGenerate, i as AgentTokenSink, j as AgentRunInput, k as AgentFunctionPaths, l as AgentRunFunction, m as AgentStepLike, n as AgentStreamGenerate, o as AgentRunResult, p as AgentMessageRow, q as AgentConfig, b as SkillDefinition, r as AnyAgentTool, s as AgentAsToolOptions, t as AgentSubToolInput, c as AgentToolDefinition, u as AgentBindingSpec, v as AgentHandle, w as AgentToolConfig, x as AgentFunctionReference, y as AgentModelInput, z as SkillConfig } from "./packem_shared/types.d-DqYbp4ye.js";
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-DqYbp4ye.js";
1
+ import { A as AgentDefinition, e as AgentCompact, f as AgentEpisodeExtract, g as AgentGraphExtract, h as AgentGenerate, i as AgentTokenSink, j as AgentRunInput, k as AgentFunctionPaths, l as AgentRunFunction, m as AgentStepLike, n as AgentStreamGenerate, o as AgentRunResult, p as AgentMessageRow, q as AgentConfig, b as SkillDefinition, r as AnyAgentTool, s as AgentAsToolOptions, t as AgentSubToolInput, c as AgentToolDefinition, u as AgentBindingSpec, v as AgentHandle, w as AgentToolConfig, x as AgentFunctionReference, y as AgentModelInput, d as AgentToolContext, z as SkillConfig } from "./packem_shared/types.d-vAmttAsE.js";
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, $ as AgentUsage, a0 as AgentVoiceConfig, a1 as AgentWorkflowBindingLike, a2 as AgentWorkflowInstanceLike, a3 as EnsureThreadOutcome } from "./packem_shared/types.d-vAmttAsE.js";
3
3
  export { type AgentComponent, agentComponent, agentExtension } from "./component.js";
4
4
  import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
5
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";
@@ -592,6 +592,82 @@ declare const DEFAULT_AGENT_FUNCTION_PATHS: AgentFunctionPaths;
592
592
  * @experimental
593
593
  */
594
594
  declare const toFunctionReference: (source: AgentFunctionReference | string) => AgentFunctionReference;
595
+ /** The model's input to {@link requestSecretTool}: what the secret is for, shown to the person asked. */
596
+ interface SecretRequestInput {
597
+ label: string;
598
+ }
599
+ /**
600
+ * Thrown by {@link withSecret} when the value is no longer takeable. The loop
601
+ * records it as a deterministic tool failure, so the model can recover rather
602
+ * than the durable step retrying a read that can never succeed.
603
+ */
604
+ declare class SecretUnavailableError extends Error {
605
+ readonly code = "SECRET_UNAVAILABLE";
606
+ constructor();
607
+ }
608
+ /**
609
+ * An agent tool that asks the human for a secret value (an API key, a token) and
610
+ * hands the model only an opaque `{ secretRef }` in return. The loop pauses the
611
+ * run until the owner supplies the value through `agents:agentSupplySecret`, or
612
+ * declines through `agents:agentDeclineSecret`. `execute` is never called: the
613
+ * loop resolves this tool itself.
614
+ *
615
+ * `consumer` names the one tool allowed to read the value. The model can pass the
616
+ * `secretRef` to any tool, but only the declared consumer's {@link withSecret} call
617
+ * takes it, so a prompt-injected model cannot route the value elsewhere.
618
+ *
619
+ * Codegen wires the secret store when a source in `lunora/` value-imports this tool
620
+ * from `@lunora/agent`: by a named import, a namespace import that reads it, or a
621
+ * relative barrel that re-exports it. Without that wiring the supply mutation refuses,
622
+ * and the refusal names the missing import. Requires a host that rates `secretValues`
623
+ * as supported.
624
+ *
625
+ * ```ts
626
+ * import { defineAgent, requestSecretTool } from "@lunora/agent";
627
+ *
628
+ * export const billing = defineAgent({
629
+ * tools: {
630
+ * requestApiKey: requestSecretTool({
631
+ * consumer: "chargeCard",
632
+ * description: "Ask the user for their payment-provider API key.",
633
+ * }),
634
+ * chargeCard: functionTool({ ... }), // reads the value with withSecret
635
+ * },
636
+ * });
637
+ * ```
638
+ *
639
+ * The value transits the supply mutation's arguments, which are marked
640
+ * `v.sensitive`: the request log masks them. The run's history records only the
641
+ * request id.
642
+ * @experimental
643
+ */
644
+ declare const requestSecretTool: (options: {
645
+ consumer: string;
646
+ description: string;
647
+ }) => AgentToolDefinition<SecretRequestInput, {
648
+ secretRef: string;
649
+ }>;
650
+ /**
651
+ * Read a human-supplied secret inside the tool that the request declared as its
652
+ * `consumer`, hand it to `use`, and return only what `use` returns. The value never
653
+ * leaves the callback: it is not a step output, not a tool result and not a message.
654
+ * The read is its own durable step named for this call, so a retry of the same step
655
+ * re-takes the value (the claimant is this step's name), while a different call
656
+ * cannot.
657
+ *
658
+ * Call it from inside a tool's `execute`. The discard runs as a separate durable step
659
+ * only after the take succeeded and `use` returned, so a call that is refused (the
660
+ * wrong tool, another thread, an expired request) cannot burn a value the declared
661
+ * consumer still needs. If `use` keeps failing, the value stays until its TTL expires,
662
+ * which is the backstop for a crash between the take and the discard. `use` must not
663
+ * return or log the value. A result that carries it is refused (the call fails with
664
+ * `LunoraError`) rather than journalled. An error that carries it is redacted before
665
+ * it propagates, so the step's retry, the failure the loop records and telemetry never
666
+ * see the value; `traceToolExecution` records the tool's input and output.
667
+ * @throws {SecretUnavailableError} when the request is unknown, not supplied, declared for another consumer, or from another thread
668
+ * @experimental
669
+ */
670
+ declare const withSecret: <Result>(context: AgentToolContext, secretRef: string, use: (secret: string) => Promise<Result> | Result) => Promise<Result>;
595
671
  /**
596
672
  * Declare a reusable skill: a bundle of expertise — an instruction fragment,
597
673
  * tools, and retrieval `knowledge` — an agent composes in via
@@ -628,12 +704,28 @@ declare const defineSkill: (config: SkillConfig) => SkillDefinition;
628
704
  * @experimental
629
705
  */
630
706
  declare const isSkillDefinition: (value: unknown) => value is SkillDefinition;
707
+ /**
708
+ * Wrap untrusted text for inclusion in a prompt. The text sits between a tag
709
+ * whose id is random per call, so payload text cannot forge the closing tag (it
710
+ * cannot know the id), and any `<` or `>` in it is escaped so it cannot form a
711
+ * tag at all. A mention or cashtag (`@`, `$`) not glued to a word, and a slash
712
+ * command `/` at the start of a token, get a zero-width space after them. Given a header map, the headers are rendered
713
+ * above the body with credential-like values redacted. A one-line note after the
714
+ * block tells the model the enclosed data is not to be followed as instructions.
715
+ *
716
+ * Use it on the text a mapper hands the model, e.g. `input: wrapUntrusted(email.text ?? "")`.
717
+ * @experimental
718
+ */
719
+ declare const wrapUntrusted: (value: string, headers?: Headers | Readonly<Record<string, string>>) => string;
631
720
  /**
632
721
  * A control frame the server sends the client as a JSON text message (audio
633
722
  * rides separate binary frames). `ready` announces the negotiated codec on
634
723
  * connect; `user_transcript` carries the STT result; `assistant_delta` streams
635
724
  * the live LLM text; `assistant_done` is the final turn text; `interrupted`
636
- * acks a barge-in; `error` reports a non-fatal turn failure.
725
+ * acks a barge-in; `assistant_discarded` says the turn failed, so the deltas
726
+ * already streamed for it are not an answer; `error` reports a failure. An
727
+ * `error` alone does not end a turn: a speech-synthesis failure reports one and
728
+ * the turn still completes.
637
729
  * @experimental
638
730
  */
639
731
  type VoiceServerFrame = {
@@ -651,6 +743,8 @@ type VoiceServerFrame = {
651
743
  } | {
652
744
  text: string;
653
745
  type: "user_transcript";
746
+ } | {
747
+ type: "assistant_discarded";
654
748
  } | {
655
749
  type: "interrupted";
656
750
  };
@@ -924,4 +1018,4 @@ declare const webSearchTool: (options?: WebSearchToolOptions) => AgentToolDefini
924
1018
  declare const compileAgentWorkflow: (agent: AgentDefinition, exportName: string, options?: {
925
1019
  paths?: AgentFunctionPaths;
926
1020
  }) => WorkflowDefinition<AgentRunInput, AgentRunResult>;
927
- export { AGENT_MODULE, type AgentAsToolOptions, type AgentBindingSpec, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentGenerate, type AgentHandle, type AgentLoopOptions, type AgentMemoryReadInput, type AgentMemorySearchHit, type AgentMemorySearchInput, type AgentMemorySearchResult, type AgentMessageRow, type AgentModelInput, type AgentRunFunction, type AgentRunInput, type AgentRunResult, type AgentStepLike, type AgentStreamGenerate, type AgentSubToolInput, type AgentTokenSink, type AgentToolConfig, type AgentToolDefinition, type AnyAgentTool, type CodeToolOptions, DEFAULT_AGENT_FUNCTION_PATHS, type FunctionToolOptions, type McpCallResult, type McpClientLike, type McpContentPart, type McpToolInfo, type McpToolsOptions, type RunVoiceTurnOptions, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, type SkillConfig, type SkillDefinition, type ToolScript, type ToolScriptResult, type ToolScriptStep, type VoiceAudioSource, type VoiceClientFrame, type VoiceSend, type VoiceSendAudio, type VoiceServerFrame, VoiceSessionDO, type VoiceSynthesize, type VoiceTranscribe, type VoiceTurnResult, type WebSearchToolInput, type WebSearchToolOptions, adaptMcpResult, agentAsTool, buildModelMessages, codeTool, collectAgenticMemoryTools, compileAgentWorkflow, createAgentContext, createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, mcpTools, resolveAgentModel, runAgentLoop, runVoiceTurn, splitForCompaction, toFunctionReference, toSearchResults, webSearchTool };
1021
+ export { AGENT_MODULE, type AgentAsToolOptions, type AgentBindingSpec, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentGenerate, type AgentHandle, type AgentLoopOptions, type AgentMemoryReadInput, type AgentMemorySearchHit, type AgentMemorySearchInput, type AgentMemorySearchResult, type AgentMessageRow, type AgentModelInput, type AgentRunFunction, type AgentRunInput, type AgentRunResult, type AgentStepLike, type AgentStreamGenerate, type AgentSubToolInput, type AgentTokenSink, type AgentToolConfig, type AgentToolContext, type AgentToolDefinition, type AnyAgentTool, type CodeToolOptions, DEFAULT_AGENT_FUNCTION_PATHS, type FunctionToolOptions, type McpCallResult, type McpClientLike, type McpContentPart, type McpToolInfo, type McpToolsOptions, type RunVoiceTurnOptions, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, type SecretRequestInput, SecretUnavailableError, type SkillConfig, type SkillDefinition, type ToolScript, type ToolScriptResult, type ToolScriptStep, type VoiceAudioSource, type VoiceClientFrame, type VoiceSend, type VoiceSendAudio, type VoiceServerFrame, VoiceSessionDO, type VoiceSynthesize, type VoiceTranscribe, type VoiceTurnResult, type WebSearchToolInput, type WebSearchToolOptions, adaptMcpResult, agentAsTool, buildModelMessages, codeTool, collectAgenticMemoryTools, compileAgentWorkflow, createAgentContext, createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, mcpTools, requestSecretTool, resolveAgentModel, runAgentLoop, runVoiceTurn, splitForCompaction, toFunctionReference, toSearchResults, webSearchTool, withSecret, wrapUntrusted };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{r as t,s as r}from"./packem_shared/agent-loop-DzzRTrgP.mjs";import{collectAgenticMemoryTools as a,toSearchResults as f}from"./packem_shared/collectAgenticMemoryTools-D07XhGKr.mjs";import{agentAsTool as s}from"./packem_shared/agentAsTool-BJi-uU4s.mjs";import{codeTool as m}from"./packem_shared/codeTool-dpJANTDc.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as A}from"./packem_shared/createAgentContext-Wlc1ZgWa.mjs";import{defineAgent as d,defineAgentTool as u,isAgentDefinition as N}from"./packem_shared/defineAgent-DrI8Hw7B.mjs";import{functionTool as D}from"./packem_shared/functionTool-Baqdn0OK.mjs";import{createAgentGenerate as C,createEpisodeExtract as M,createGraphExtract as O,createStreamGenerate as _,resolveAgentModel as F}from"./packem_shared/createAgentGenerate-D9DbEj9I.mjs";import{jsCodeTool as L}from"./packem_shared/jsCodeTool-CIlCK1bG.mjs";import{adaptMcpResult as b,mcpTools as h}from"./packem_shared/adaptMcpResult-DFF_g58r.mjs";import{buildModelMessages as v}from"./packem_shared/buildModelMessages-Y4tGo1T9.mjs";import{agentClassName as B,agentDefaultName as R,voiceBindingName as V,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-B6FqQC80.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-D7O6Fclt.mjs";import{r as re}from"./packem_shared/voice-turn-CzFz5tWG.mjs";import{webSearchTool as ae}from"./packem_shared/webSearchTool-BobmV4cD.mjs";import{default as le}from"./packem_shared/compileAgentWorkflow-KtkWJyHR.mjs";export{P as AGENT_MODULE,X as DEFAULT_AGENT_FUNCTION_PATHS,j as SANDBOX_INVOKE_PATH,y as SANDBOX_MODULE,oe as VoiceSessionDO,b as adaptMcpResult,s as agentAsTool,B as agentClassName,c as agentComponent,R as agentDefaultName,x as agentExtension,q as browserTool,v as buildModelMessages,m as codeTool,a as collectAgenticMemoryTools,le 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,h as mcpTools,F as resolveAgentModel,t as runAgentLoop,re as runVoiceTurn,r as splitForCompaction,K as toFunctionReference,f as toSearchResults,V as voiceBindingName,H as voiceClassName,ae as webSearchTool};
1
+ import{r,s as t}from"./packem_shared/agent-loop-Cn7CA8n-.mjs";import{collectAgenticMemoryTools as n,toSearchResults as l}from"./packem_shared/collectAgenticMemoryTools-BWdIhOfY.mjs";import{agentAsTool as s}from"./packem_shared/agentAsTool-CA7Sha2i.mjs";import{codeTool as p}from"./packem_shared/codeTool-Hm_Af6t4.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as A}from"./packem_shared/createAgentContext-BwEzrHXM.mjs";import{defineAgent as g,defineAgentTool as u,isAgentDefinition as S}from"./packem_shared/defineAgent-DGAOwO_s.mjs";import{functionTool as N}from"./packem_shared/functionTool-C95ns65V.mjs";import{createAgentGenerate as C,createEpisodeExtract as M,createGraphExtract as O,createStreamGenerate as _,resolveAgentModel as U}from"./packem_shared/createAgentGenerate-C6mp2LqI.mjs";import{jsCodeTool as F}from"./packem_shared/jsCodeTool-CIlCK1bG.mjs";import{adaptMcpResult as b,mcpTools as h}from"./packem_shared/adaptMcpResult-DFF_g58r.mjs";import{buildModelMessages as L}from"./packem_shared/buildModelMessages-BH7FXfkd.mjs";import{agentClassName as B,agentDefaultName as R,voiceBindingName as V,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 q,toFunctionReference as y}from"./packem_shared/AGENT_MODULE-CYBmT9SD.mjs";import{browserTool as W,containerFsTool as z,containerTool as J,fsTool as Q}from"./sandbox.mjs";import{SecretUnavailableError as Z,requestSecretTool as $,withSecret as ee}from"./packem_shared/SecretUnavailableError-BCp40Leh.mjs";import{defineSkill as re,isSkillDefinition as te}from"./packem_shared/defineSkill-DGGvDWNq.mjs";import{default as ne}from"./packem_shared/wrapUntrusted-BuHBC6sV.mjs";import{default as fe}from"./packem_shared/VoiceSessionDO-vGQ5RM-f.mjs";import{r as ie}from"./packem_shared/voice-turn-CnyPkynX.mjs";import{webSearchTool as me}from"./packem_shared/webSearchTool-BobmV4cD.mjs";import{default as xe}from"./packem_shared/compileAgentWorkflow-D_GZWBJx.mjs";export{P as AGENT_MODULE,X as DEFAULT_AGENT_FUNCTION_PATHS,j as SANDBOX_INVOKE_PATH,q as SANDBOX_MODULE,Z as SecretUnavailableError,fe as VoiceSessionDO,b as adaptMcpResult,s as agentAsTool,B as agentClassName,c as agentComponent,R as agentDefaultName,x as agentExtension,W as browserTool,L as buildModelMessages,p as codeTool,n as collectAgenticMemoryTools,xe as compileAgentWorkflow,z as containerFsTool,J as containerTool,A as createAgentContext,C as createAgentGenerate,M as createEpisodeExtract,O as createGraphExtract,_ as createStreamGenerate,g as defineAgent,u as defineAgentTool,re as defineSkill,Q as fsTool,N as functionTool,S as isAgentDefinition,te as isSkillDefinition,F as jsCodeTool,h as mcpTools,$ as requestSecretTool,U as resolveAgentModel,r as runAgentLoop,ie as runVoiceTurn,t as splitForCompaction,y as toFunctionReference,l as toSearchResults,V as voiceBindingName,H as voiceClassName,me as webSearchTool,ee as withSecret,ne as wrapUntrusted};
@@ -0,0 +1 @@
1
+ const e="agents",a="sandbox",n=`${a}:invoke`,s={appendMessage:`${e}:agentAppendMessage`,approvalGranted:`${e}:agentApprovalGranted`,completeRun:`${e}:agentCompleteRun`,deleteMessage:`${e}:agentDeleteMessage`,ensureThread:`${e}:agentEnsureThread`,episodeRecall:`${e}:agentEpisodeRecall`,episodeUpsert:`${e}:agentEpisodeUpsert`,graphTraverse:`${e}:agentGraphTraverse`,graphUpsert:`${e}:agentGraphUpsert`,history:`${e}:agentHistory`,listMessages:`${e}:agentMessages`,patchThread:`${e}:agentPatchThread`,run:`${e}:agentRun`,setState:`${e}:agentSetState`,state:`${e}:agentState`,takeSecret:`${e}:agentTakeSecret`,discardSecret:`${e}:agentDiscardSecret`,openSecretRequest:`${e}:agentOpenSecretRequest`,settleSecretRequest:`${e}:agentSettleSecretRequest`},r=t=>typeof t=="string"?{__lunoraRef:t}:t;export{e as AGENT_MODULE,s as DEFAULT_AGENT_FUNCTION_PATHS,n as SANDBOX_INVOKE_PATH,a as SANDBOX_MODULE,r as toFunctionReference};
@@ -0,0 +1 @@
1
+ import{jsonSchema as y}from"@ai-sdk/provider-utils";import{LunoraError as s}from"@lunora/errors";import{toFunctionReference as l,DEFAULT_AGENT_FUNCTION_PATHS as d}from"./AGENT_MODULE-CYBmT9SD.mjs";const p=200,N=e=>{const t=typeof e=="object"&&e!==null?e.label:void 0;if(!(typeof t!="string"||t.trim().length===0))return[...t.trim()].slice(0,p).join("")};class g extends Error{code="SECRET_UNAVAILABLE";constructor(){super("the secret is no longer available: it expired, was already used by another tool call, or was never supplied"),this.name="SecretUnavailableError"}}const T=e=>{if(typeof e.description!="string"||e.description.length===0)throw new s("INTERNAL","@lunora/agent: requestSecretTool requires a non-empty `description` (the model decides from it)");if(typeof e.consumer!="string"||e.consumer.length===0)throw new s("INTERNAL","@lunora/agent: requestSecretTool requires a non-empty `consumer`: the name of the one tool allowed to read the value");return{description:e.description,execute:()=>{throw new s("INTERNAL","@lunora/agent: requestSecretTool is resolved by the loop and must never be executed")},inputSchema:y({properties:{label:{description:"What the secret is for, shown to the person asked.",type:"string"}},required:["label"],type:"object"}),isLunoraAgentTool:!0,secretRequest:{consumer:e.consumer}}},w=(e,t)=>t instanceof Error?{...Object.fromEntries(Object.entries(t)),message:t.message,name:t.name,stack:t.stack}:t,f=e=>{const t=new TextEncoder().encode(e),n=Array.from(t,r=>String.fromCodePoint(r)).join(""),a=btoa(n),o=Array.from(t,r=>r.toString(16).padStart(2,"0")).join("");return[...new Set([a,a.replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),encodeURIComponent(e),o,JSON.stringify(e).slice(1,-1),e])]},h=(e,t)=>{if(t.length===0||e===void 0||typeof e=="function"||typeof e=="symbol")return!1;let n;try{n=JSON.stringify(e,w)}catch{return!1}return f(t).some(a=>n.includes(a))},E="[redacted]",u="@lunora/agent: withSecret's callback threw a value that is withheld, in case it carries the secret",c=(e,t)=>{if(t.length===0)return e;let n=e;for(const a of f(t).toSorted((o,r)=>r.length-o.length))n=n.split(a).join(E);return n},m=(e,t,n=new Set)=>{if(!(e instanceof Error))return new s("INTERNAL",u);if(n.has(e))return e;n.add(e);try{e.message=c(e.message,t),typeof e.stack=="string"&&(e.stack=c(e.stack,t));const a=e;for(const o of Object.getOwnPropertyNames(e)){if(o==="message"||o==="stack")continue;const r=a[o];if(r instanceof Error){const i=m(r,t,n);i!==r&&(a[o]=i)}else h(r,t)&&(a[o]=JSON.parse(c(JSON.stringify(r),t)))}}catch{return new s("INTERNAL",u)}return e},I=async(e,t,n)=>{const a=await e.step.do(`secret:consume:${e.idempotencyKey}:${t}`,async()=>{const o=await e.run(l(d.takeSecret),{claimant:e.idempotencyKey,consumerCallId:e.toolCallId,instanceId:e.instanceId,threadKey:e.threadKey,toolCallId:t});if(typeof o!="string")return{unavailable:!0};let r;try{r=await n(o)}catch(i){throw m(i,o)}return h(r,o)?{leaked:!0}:{result:r}});if("unavailable"in a)throw new g;if(await e.step.do(`secret:discard:${e.idempotencyKey}:${t}`,async()=>{await e.run(l(d.discardSecret),{instanceId:e.instanceId,threadKey:e.threadKey,toolCallId:t})}),"leaked"in a)throw new s("INTERNAL","@lunora/agent: withSecret's callback returned the secret, so its result was not recorded");return a.result};export{g as SecretUnavailableError,T as requestSecretTool,N as secretLabelOf,I as withSecret};
@@ -1 +1 @@
1
- import{createAi as A}from"@lunora/ai/create";import{n as b}from"./DEFAULT_DISPATCH_TIMEOUT_MS-mg6qrlU6-CT5Q5dbp.mjs";import{p as x,d as T,a as _,i as p,b as y,c as v,e as E,t as k,f as M,r as w,g as C}from"./voice-turn-CzFz5tWG.mjs";import{r as I}from"./agent-ai-CP87uSoZ.mjs";import{createStreamGenerate as R,createCompact as L}from"./createAgentGenerate-D9DbEj9I.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as N,toFunctionReference as m}from"./AGENT_MODULE-B6FqQC80.mjs";const O="@cf/openai/whisper-large-v3-turbo",U="@cf/deepgram/aura-1",B=8*1024*1024,F=100,f=4e3,g=f*4+1024,D=4002,z=4003,W=4004,G=256*1024,S=15,X=5e3,K=h=>{if(h===null||typeof h!="object")return!1;const{text:t,type:e}=h;return e==="commit"||e==="interrupt"||e==="text"&&typeof t=="string"};class j{agent;ai;env;exportName;paths;streamGenerate;sttModel;ttsModel;maxSessionTurns;audioBuffers=new Map;bufferedBytes=new Map;controllers=new Map;state;constructor(t,e,r,s){this.state=t,this.env=e,this.agent=r,this.exportName=s,this.paths=N,this.ai=I(e)??A({env:e}),this.streamGenerate=R(r,e),this.sttModel=r.voice?.stt??O,this.ttsModel=r.voice?.tts??U,this.maxSessionTurns=r.voice?.maxTurns??F}fetch(t){if(t.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{status:426});const r=new URL(t.url).searchParams.get("threadKey");if(!r)return new Response("Missing threadKey",{status:400});const s=globalThis.WebSocketPair,i=new s,n=i[0],o=i[1];this.state.acceptWebSocket(o);const c=crypto.randomUUID(),d=x(t.headers.get("x-lunora-identity")),a=T(t.headers.get("x-lunora-userid")),u=_(t.headers.get("x-lunora-identity-exp"));if(p(u))return y(o),new Response(null,{status:101,webSocket:n});o.serializeAttachment?.({connectionId:c,threadKey:r,turn:0,...u===void 0?{}:{expiresAt:u},...d===void 0?{}:{identity:d},...a===void 0?{}:{userId:a}}),this.send(o,{audioFormat:this.agent.voice?.audioFormat??"mp3",type:"ready"});const l=this.agent.voice?.greeting;return l&&l.length>0&&this.state.waitUntil?.(this.speakGreeting(o,c,r,a,d,l)),new Response(null,{status:101,webSocket:n})}async webSocketMessage(t,e){const r=t.deserializeAttachment?.();if(r){if(p(r.expiresAt)){y(t);return}try{if(typeof e=="string"){await this.handleControl(t,r,e);return}this.bufferAudio(r.connectionId,new Uint8Array(e),t)}catch(s){this.send(t,{message:s instanceof Error?s.message:String(s),type:"error"})}}}webSocketClose(t){this.cleanupSocket(t)}webSocketError(t){this.cleanupSocket(t)}resolveRun(t,e){const r=t===void 0&&e===void 0?void 0:{...e===void 0?{}:{claims:e},...t===void 0?{}:{userId:t}};return b({env:this.env,label:"@lunora/agent voice",...r===void 0?{}:{identity:r}})}async transcribe(t){const e=v(t);return E(await this.ai.run(this.sttModel,{audio:k(e)}))}async synthesize(t,e){const r=this.agent.voice?.speaker;return M(await this.ai.run(this.ttsModel,{text:t,...r===void 0?{}:{speaker:r}},e===void 0?void 0:{signal:e}))}async handleControl(t,e,r){if(r.length>g){this.send(t,{message:`control frame exceeds the maximum of ${String(g)} characters`,type:"error"}),this.closeSocket(t,W,"control_frame_limit");return}let s;try{s=JSON.parse(r)}catch{return}if(!K(s)){this.send(t,{message:'unsupported control frame — expected { type: "text", text }, { type: "commit" } or { type: "interrupt" }',type:"error"});return}const i=s;if(i.type==="interrupt"){this.controllers.get(e.connectionId)?.abort();return}if(i.type==="text"&&i.text.length>f){this.send(t,{message:`text frame exceeds the maximum of ${String(f)} characters`,type:"error"});return}if(e.turn>=this.maxSessionTurns){this.send(t,{message:`voice session reached its ${String(this.maxSessionTurns)}-turn limit — reconnect to continue`,type:"error"}),this.closeSocket(t,D,"turn_limit");return}if(this.controllers.has(e.connectionId)){i.type==="commit"&&this.drainAudio(e.connectionId),this.send(t,{message:"a turn is already in progress — send an interrupt before the next utterance",type:"error"});return}if(i.type==="commit"){const n=this.drainAudio(e.connectionId);await this.runTurn(t,e,{pcm:n});return}await this.runTurn(t,e,{text:i.text})}bufferAudio(t,e,r){const s=(this.bufferedBytes.get(t)??0)+e.byteLength;if(s>B){this.audioBuffers.delete(t),this.bufferedBytes.delete(t),this.send(r,{message:"utterance exceeded the maximum buffer — send a commit sooner",type:"error"}),this.closeSocket(r,z,"utterance_too_large");return}const i=this.audioBuffers.get(t)??[];i.push(e),this.audioBuffers.set(t,i),this.bufferedBytes.set(t,s)}drainAudio(t){const e=this.audioBuffers.get(t)??[];this.audioBuffers.delete(t),this.bufferedBytes.delete(t);const r=e.reduce((n,o)=>n+o.byteLength,0),s=new Uint8Array(r);let i=0;for(const n of e)s.set(n,i),i+=n.byteLength;return s}async runTurn(t,e,r){const s=new AbortController;this.controllers.set(e.connectionId,s);try{await w({agent:this.agent,compact:L(),connectionId:e.connectionId,env:this.env,exportName:this.exportName,paths:this.paths,run:this.resolveRun(e.userId,e.identity),send:i=>{this.send(t,i)},sendAudio:i=>{this.sendAudio(t,i)},signal:s.signal,streamGenerate:this.streamGenerate,synthesize:async(i,n)=>this.synthesizeWithSignal(i,n),threadKey:e.threadKey,transcribe:async i=>this.transcribe(i),turn:e.turn,waitForDrain:async()=>this.waitForSocketDrain(t),...e.userId===void 0?{}:{owner:e.userId},...r.pcm===void 0?{}:{pcm:r.pcm},...r.text===void 0?{}:{text:r.text}})}finally{this.controllers.get(e.connectionId)===s&&this.controllers.delete(e.connectionId),t.serializeAttachment?.({...e,turn:e.turn+1})}}async speakGreeting(t,e,r,s,i,n){const o=this.resolveRun(s,i),c=new AbortController,d=()=>c.signal.aborted;this.controllers.set(e,c);try{if((await o(m(this.paths.ensureThread),{agent:this.exportName,key:r,...this.agent.initialState===void 0?{}:{initialState:this.agent.initialState},...s===void 0?{}:{owner:s}}))?.outcome!=="created")return;for await(const u of C(await this.synthesizeWithSignal(n,c.signal))){if(d()||(await this.waitForSocketDrain(t),d()))break;this.sendAudio(t,u)}d()||(await o(m(this.paths.appendMessage),{content:n,messageKey:"voice:greeting:assistant",role:"assistant",threadKey:r}),this.send(t,{text:n,type:"assistant_done"}))}catch(a){this.send(t,{message:a instanceof Error?a.message:String(a),type:"error"})}finally{this.controllers.get(e)===c&&this.controllers.delete(e)}}async synthesizeWithSignal(t,e){return e.aborted?new Uint8Array(0):this.synthesize(t,e)}cleanupSocket(t){const e=t.deserializeAttachment?.();e&&(this.controllers.get(e.connectionId)?.abort(),this.controllers.delete(e.connectionId),this.audioBuffers.delete(e.connectionId),this.bufferedBytes.delete(e.connectionId))}closeSocket(t,e,r){try{t.close?.(e,r)}catch{}}send(t,e){try{t.send(JSON.stringify(e))}catch{}}sendAudio(t,e){try{t.send(e)}catch{}}async waitForSocketDrain(t){const e=t;let r=0;for(;typeof e.bufferedAmount=="number"&&e.bufferedAmount>G&&r<X;)await new Promise(s=>{setTimeout(s,S)}),r+=S}}export{j as default};
1
+ import{createAi as A}from"@lunora/ai/create";import{n as b}from"./DEFAULT_DISPATCH_TIMEOUT_MS-mg6qrlU6-CT5Q5dbp.mjs";import{p as x,d as T,a as _,i as p,b as y,c as v,e as E,t as k,f as M,r as w,g as C}from"./voice-turn-CnyPkynX.mjs";import{r as I}from"./agent-ai-CP87uSoZ.mjs";import{createStreamGenerate as R,createCompact as L}from"./createAgentGenerate-C6mp2LqI.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as N,toFunctionReference as m}from"./AGENT_MODULE-CYBmT9SD.mjs";const O="@cf/openai/whisper-large-v3-turbo",U="@cf/deepgram/aura-1",B=8*1024*1024,F=100,f=4e3,g=f*4+1024,D=4002,z=4003,W=4004,G=256*1024,S=15,X=5e3,K=h=>{if(h===null||typeof h!="object")return!1;const{text:t,type:e}=h;return e==="commit"||e==="interrupt"||e==="text"&&typeof t=="string"};class j{agent;ai;env;exportName;paths;streamGenerate;sttModel;ttsModel;maxSessionTurns;audioBuffers=new Map;bufferedBytes=new Map;controllers=new Map;state;constructor(t,e,r,s){this.state=t,this.env=e,this.agent=r,this.exportName=s,this.paths=N,this.ai=I(e)??A({env:e}),this.streamGenerate=R(r,e),this.sttModel=r.voice?.stt??O,this.ttsModel=r.voice?.tts??U,this.maxSessionTurns=r.voice?.maxTurns??F}fetch(t){if(t.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{status:426});const r=new URL(t.url).searchParams.get("threadKey");if(!r)return new Response("Missing threadKey",{status:400});const s=globalThis.WebSocketPair,i=new s,n=i[0],o=i[1];this.state.acceptWebSocket(o);const c=crypto.randomUUID(),d=x(t.headers.get("x-lunora-identity")),a=T(t.headers.get("x-lunora-userid")),u=_(t.headers.get("x-lunora-identity-exp"));if(p(u))return y(o),new Response(null,{status:101,webSocket:n});o.serializeAttachment?.({connectionId:c,threadKey:r,turn:0,...u===void 0?{}:{expiresAt:u},...d===void 0?{}:{identity:d},...a===void 0?{}:{userId:a}}),this.send(o,{audioFormat:this.agent.voice?.audioFormat??"mp3",type:"ready"});const l=this.agent.voice?.greeting;return l&&l.length>0&&this.state.waitUntil?.(this.speakGreeting(o,c,r,a,d,l)),new Response(null,{status:101,webSocket:n})}async webSocketMessage(t,e){const r=t.deserializeAttachment?.();if(r){if(p(r.expiresAt)){y(t);return}try{if(typeof e=="string"){await this.handleControl(t,r,e);return}this.bufferAudio(r.connectionId,new Uint8Array(e),t)}catch(s){this.send(t,{message:s instanceof Error?s.message:String(s),type:"error"})}}}webSocketClose(t){this.cleanupSocket(t)}webSocketError(t){this.cleanupSocket(t)}resolveRun(t,e){const r=t===void 0&&e===void 0?void 0:{...e===void 0?{}:{claims:e},...t===void 0?{}:{userId:t}};return b({env:this.env,label:"@lunora/agent voice",...r===void 0?{}:{identity:r}})}async transcribe(t){const e=v(t);return E(await this.ai.run(this.sttModel,{audio:k(e)}))}async synthesize(t,e){const r=this.agent.voice?.speaker;return M(await this.ai.run(this.ttsModel,{text:t,...r===void 0?{}:{speaker:r}},e===void 0?void 0:{signal:e}))}async handleControl(t,e,r){if(r.length>g){this.send(t,{message:`control frame exceeds the maximum of ${String(g)} characters`,type:"error"}),this.closeSocket(t,W,"control_frame_limit");return}let s;try{s=JSON.parse(r)}catch{return}if(!K(s)){this.send(t,{message:'unsupported control frame — expected { type: "text", text }, { type: "commit" } or { type: "interrupt" }',type:"error"});return}const i=s;if(i.type==="interrupt"){this.controllers.get(e.connectionId)?.abort();return}if(i.type==="text"&&i.text.length>f){this.send(t,{message:`text frame exceeds the maximum of ${String(f)} characters`,type:"error"});return}if(e.turn>=this.maxSessionTurns){this.send(t,{message:`voice session reached its ${String(this.maxSessionTurns)}-turn limit — reconnect to continue`,type:"error"}),this.closeSocket(t,D,"turn_limit");return}if(this.controllers.has(e.connectionId)){i.type==="commit"&&this.drainAudio(e.connectionId),this.send(t,{message:"a turn is already in progress — send an interrupt before the next utterance",type:"error"});return}if(i.type==="commit"){const n=this.drainAudio(e.connectionId);await this.runTurn(t,e,{pcm:n});return}await this.runTurn(t,e,{text:i.text})}bufferAudio(t,e,r){const s=(this.bufferedBytes.get(t)??0)+e.byteLength;if(s>B){this.audioBuffers.delete(t),this.bufferedBytes.delete(t),this.send(r,{message:"utterance exceeded the maximum buffer — send a commit sooner",type:"error"}),this.closeSocket(r,z,"utterance_too_large");return}const i=this.audioBuffers.get(t)??[];i.push(e),this.audioBuffers.set(t,i),this.bufferedBytes.set(t,s)}drainAudio(t){const e=this.audioBuffers.get(t)??[];this.audioBuffers.delete(t),this.bufferedBytes.delete(t);const r=e.reduce((n,o)=>n+o.byteLength,0),s=new Uint8Array(r);let i=0;for(const n of e)s.set(n,i),i+=n.byteLength;return s}async runTurn(t,e,r){const s=new AbortController;this.controllers.set(e.connectionId,s);try{await w({agent:this.agent,compact:L(),connectionId:e.connectionId,env:this.env,exportName:this.exportName,paths:this.paths,run:this.resolveRun(e.userId,e.identity),send:i=>{this.send(t,i)},sendAudio:i=>{this.sendAudio(t,i)},signal:s.signal,streamGenerate:this.streamGenerate,synthesize:async(i,n)=>this.synthesizeWithSignal(i,n),threadKey:e.threadKey,transcribe:async i=>this.transcribe(i),turn:e.turn,waitForDrain:async()=>this.waitForSocketDrain(t),...e.userId===void 0?{}:{owner:e.userId},...r.pcm===void 0?{}:{pcm:r.pcm},...r.text===void 0?{}:{text:r.text}})}finally{this.controllers.get(e.connectionId)===s&&this.controllers.delete(e.connectionId),t.serializeAttachment?.({...e,turn:e.turn+1})}}async speakGreeting(t,e,r,s,i,n){const o=this.resolveRun(s,i),c=new AbortController,d=()=>c.signal.aborted;this.controllers.set(e,c);try{if((await o(m(this.paths.ensureThread),{agent:this.exportName,key:r,...this.agent.initialState===void 0?{}:{initialState:this.agent.initialState},...s===void 0?{}:{owner:s}}))?.outcome!=="created")return;for await(const u of C(await this.synthesizeWithSignal(n,c.signal))){if(d()||(await this.waitForSocketDrain(t),d()))break;this.sendAudio(t,u)}d()||(await o(m(this.paths.appendMessage),{content:n,messageKey:"voice:greeting:assistant",role:"assistant",threadKey:r}),this.send(t,{text:n,type:"assistant_done"}))}catch(a){this.send(t,{message:a instanceof Error?a.message:String(a),type:"error"})}finally{this.controllers.get(e)===c&&this.controllers.delete(e)}}async synthesizeWithSignal(t,e){return e.aborted?new Uint8Array(0):this.synthesize(t,e)}cleanupSocket(t){const e=t.deserializeAttachment?.();e&&(this.controllers.get(e.connectionId)?.abort(),this.controllers.delete(e.connectionId),this.audioBuffers.delete(e.connectionId),this.bufferedBytes.delete(e.connectionId))}closeSocket(t,e,r){try{t.close?.(e,r)}catch{}}send(t,e){try{t.send(JSON.stringify(e))}catch{}}sendAudio(t,e){try{t.send(e)}catch{}}async waitForSocketDrain(t){const e=t;let r=0;for(;typeof e.bufferedAmount=="number"&&e.bufferedAmount>G&&r<X;)await new Promise(s=>{setTimeout(s,S)}),r+=S}}export{j as default};