@lunora/agent 1.0.0-alpha.41 → 1.0.0-alpha.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/channels.d.mts +2 -2
- package/dist/channels.d.ts +2 -2
- package/dist/component.mjs +2 -2
- package/dist/inbound.d.mts +1 -1
- package/dist/inbound.d.ts +1 -1
- package/dist/index.d.mts +2 -15
- package/dist/index.d.ts +2 -15
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/VoiceSessionDO-DNXzVGVf.mjs +1 -0
- package/dist/packem_shared/{compileAgentWorkflow-Bzd8oR9X.mjs → compileAgentWorkflow-BW627hb5.mjs} +1 -1
- package/dist/packem_shared/component-shared-BVjAbtUu.mjs +1 -0
- package/dist/packem_shared/consoleTelemetry-C_85CaZ7.mjs +1 -0
- package/dist/packem_shared/createAgentGenerate-BS1vasdV.mjs +3 -0
- package/dist/packem_shared/normalizeEntityName-DrEDaSSz.mjs +2 -0
- package/dist/packem_shared/runAgentLoop-nuk5NsAn.mjs +3 -0
- package/dist/packem_shared/{types.d-B6v0Hgi5.d.mts → types.d-PMYeuDE7.d.mts} +7 -1
- package/dist/packem_shared/{types.d-B6v0Hgi5.d.ts → types.d-PMYeuDE7.d.ts} +7 -1
- package/dist/sandbox.d.mts +1 -1
- package/dist/sandbox.d.ts +1 -1
- package/dist/skill-markdown.d.mts +36 -0
- package/dist/skill-markdown.d.ts +36 -0
- package/dist/skill-markdown.mjs +1 -0
- package/dist/telemetry/index.mjs +1 -1
- package/package.json +13 -8
- package/dist/packem_shared/VoiceSessionDO-bNlFmRop.mjs +0 -1
- package/dist/packem_shared/consoleTelemetry-CaoI-NGg.mjs +0 -1
- package/dist/packem_shared/createAgentGenerate-D96dEdYw.mjs +0 -3
- package/dist/packem_shared/graph-component-B2YmC2eL.mjs +0 -2
- package/dist/packem_shared/normalizeEntityName-BQpyssvL.mjs +0 -1
- package/dist/packem_shared/runAgentLoop-BHjAmXGh.mjs +0 -3
package/dist/channels.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AgentDefinition } from "./packem_shared/types.d-
|
|
2
|
-
export type { I as InboundChannelEvent } from "./packem_shared/types.d-
|
|
1
|
+
import { A as AgentDefinition } from "./packem_shared/types.d-PMYeuDE7.mjs";
|
|
2
|
+
export type { I as InboundChannelEvent } from "./packem_shared/types.d-PMYeuDE7.mjs";
|
|
3
3
|
import '@lunora/mail/inbound';
|
|
4
4
|
import 'ai';
|
|
5
5
|
/**
|
package/dist/channels.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AgentDefinition } from "./packem_shared/types.d-
|
|
2
|
-
export type { I as InboundChannelEvent } from "./packem_shared/types.d-
|
|
1
|
+
import { A as AgentDefinition } from "./packem_shared/types.d-PMYeuDE7.js";
|
|
2
|
+
export type { I as InboundChannelEvent } from "./packem_shared/types.d-PMYeuDE7.js";
|
|
3
3
|
import '@lunora/mail/inbound';
|
|
4
4
|
import 'ai';
|
|
5
5
|
/**
|
package/dist/component.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{LunoraError as w}from"@lunora/errors";import{defineTable as x,initLunora as $,defineSchemaExtension as j}from"@lunora/server";import{v as e}from"@lunora/values";import{i as b,o as k,
|
|
2
|
-
`)}});return{agentEpisodeRecall:b(
|
|
1
|
+
import{LunoraError as w}from"@lunora/errors";import{defineTable as x,initLunora as $,defineSchemaExtension as j}from"@lunora/server";import{v as e}from"@lunora/values";import{i as b,o as k,s as O}from"./packem_shared/component-shared-BVjAbtUu.mjs";import{graphTables as S,graphComponent as F}from"./packem_shared/normalizeEntityName-DrEDaSSz.mjs";import{normalizeEntityName as re}from"./packem_shared/normalizeEntityName-DrEDaSSz.mjs";import{sandboxComponent as oe}from"./packem_shared/sandboxComponent-CKDGyK4Y.mjs";const I="agent_episodes",L=5,U=20,B=500,N=200,G=/\s+/gu,z=c=>c===void 0||!Number.isFinite(c)?L:Math.min(U,Math.max(1,Math.trunc(c))),P={episodes:x({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:H,query:J}=$.dataModel().create(),Q=()=>{const c=H.input({createdAt:e.optional(e.number()),messageKey:e.string(),owner:e.string(),summary:e.string(),threadKey:e.optional(e.string())}).mutation(async({args:s,ctx:u})=>{const l=s.summary.replaceAll(G," ").trim().slice(0,B);if(l.length===0)return{recorded:!1};if(await u.db.query(I).withIndex("byOwnerMessageKey",p=>p.eq("owner",s.owner).eq("messageKey",s.messageKey)).first())return{recorded:!1};await u.db.insert(I,{createdAt:s.createdAt??Date.now(),messageKey:s.messageKey,owner:s.owner,summary:l,...s.threadKey===void 0?{}:{threadKey:s.threadKey}});const g=await u.db.query(I).withIndex("byOwnerCreatedAt",p=>p.eq("owner",s.owner)).order("asc").take(N+1);for(const p of g.slice(0,Math.max(0,g.length-N)))await u.db.delete(p._id);return{recorded:!0}}),f=J.input({limit:e.optional(e.number()),owner:e.string()}).query(async({args:s,ctx:u})=>{const l=await u.db.query(I).withIndex("byOwnerCreatedAt",g=>g.eq("owner",s.owner)).order("desc").take(z(s.limit));return l.length===0?{context:""}:{context:l.toReversed().map(g=>`- ${g.summary}`).join(`
|
|
2
|
+
`)}});return{agentEpisodeRecall:b(f),agentEpisodeUpsert:b(c)}},T="threads",R="messages",d=`${k}_${T}`,K=`${k}_${R}`,V=j(k,{tables:{[R]:x({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(),[T]:x({agent:e.string(),createdAt:e.number(),error:e.optional(e.string()),instanceId:e.optional(e.string()),key:e.string(),messageCount:e.number(),owner:e.optional(e.string()),state:e.optional(e.any()),status:e.union(e.literal("idle"),e.literal("running"),e.literal("error"),e.literal("cancelled"),e.literal("awaiting_input")),title:e.optional(e.string()),updatedAt:e.number(),usage:e.optional(e.object({inputTokens:e.optional(e.number()),outputTokens:e.optional(e.number()),totalTokens:e.optional(e.number())}))}).index("byKey",["key"],{unique:!0}).index("byAgent",["agent"]).index("byInstance",["instanceId"]).public(),...S,...P}}),{mutation:m,query:q}=$.dataModel().create(),te=()=>{const c=m.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:a})=>{const r=Date.now(),n=await a.db.query(d).withIndex("byKey",i=>i.eq("key",t.key)).first();if(n){if(n.owner!==t.owner&&t.owner!==void 0)throw new Error(`@lunora/agent: thread "${t.key}" belongs to another owner`);const i=n.instanceId;if((n.status==="running"||n.status==="awaiting_input")&&i!==void 0&&(t.instanceId===void 0||t.instanceId!==i)){const o=t.onConcurrentRun??"reject";if(o!=="replace")throw new w("CONFLICT",`@lunora/agent: thread "${t.key}" already has a run in flight (instance "${i}") — onConcurrentRun="${o}"`);return await a.db.patch(n._id,{error:void 0,status:"running",updatedAt:r,...t.instanceId===void 0?{}:{instanceId:t.instanceId}}),{created:!1,priorInstanceId:i,replaced:!0}}return await a.db.patch(n._id,{error:void 0,status:"running",updatedAt:r,...t.instanceId===void 0?{}:{instanceId:t.instanceId}}),{created:!1}}return await a.db.insert(d,{agent:t.agent,createdAt:r,key:t.key,messageCount:0,status:"running",updatedAt:r,...O({instanceId:t.instanceId,owner:t.owner,state:t.initialState,title:t.title})}),{created:!0}}),f=m.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:a})=>{const r=await a.db.query(K).withIndex("byMessageKey",y=>y.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();if(r)return{seq:r.seq};const n=await a.db.query(d).withIndex("byKey",y=>y.eq("key",t.threadKey)).first();if(!n)throw new Error(`@lunora/agent: cannot append to unknown thread "${t.threadKey}" — run agentEnsureThread first`);const i=n.messageCount,o=Date.now();return await a.db.insert(K,{content:t.content,createdAt:o,messageKey:t.messageKey,role:t.role,seq:i,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 a.db.patch(n._id,{messageCount:i+1,updatedAt:o}),{seq:i}}),s=m.input({error:e.optional(e.string()),instanceId:e.optional(e.string()),key:e.optional(e.string()),status:e.optional(e.union(e.literal("idle"),e.literal("running"),e.literal("error"),e.literal("cancelled"),e.literal("awaiting_input"))),title:e.optional(e.string()),usage:e.optional(e.object({inputTokens:e.optional(e.number()),outputTokens:e.optional(e.number()),totalTokens:e.optional(e.number())}))}).mutation(async({args:t,ctx:a})=>{const{instanceId:r,key:n}=t;let i;n!==void 0?i=await a.db.query(d).withIndex("byKey",o=>o.eq("key",n)).first():r!==void 0&&(i=await a.db.query(d).withIndex("byInstance",o=>o.eq("instanceId",r)).first()),i&&await a.db.patch(i._id,{updatedAt:Date.now(),...t.error===void 0?{}:{error:t.error},...t.status===void 0?{}:{status:t.status},...t.title===void 0?{}:{title:t.title},...t.usage===void 0?{}:{usage:t.usage}})}),u=m.input({key:e.string(),state:e.any()}).mutation(async({args:t,ctx:a})=>{const r=await a.db.query(d).withIndex("byKey",n=>n.eq("key",t.key)).first();r&&await a.db.patch(r._id,{state:t.state,updatedAt:Date.now()})}),l=(t,a)=>{if(!t)return;const{owner:r}=t;if(!(r!==void 0&&r!==(a.userId??void 0)))return t},g=q.input({key:e.string()}).query(async({args:t,ctx:a})=>{const r=await a.db.query(d).withIndex("byKey",n=>n.eq("key",t.key)).first();return l(r,a.auth)}),p=q.input({key:e.string()}).query(async({args:t,ctx:a})=>{const r=await a.db.query(d).withIndex("byKey",n=>n.eq("key",t.key)).first();return l(r,a.auth)?.state}),_=q.input({key:e.string(),limit:e.optional(e.number())}).query(async({args:t,ctx:a})=>{const r=await a.db.query(d).withIndex("byKey",n=>n.eq("key",t.key)).first();return l(r,a.auth)===void 0?[]:t.limit!==void 0?(await a.db.query(K).withIndex("byThread",n=>n.eq("threadKey",t.key)).order("desc").take(t.limit)).toReversed():a.db.query(K).withIndex("byThread",n=>n.eq("threadKey",t.key)).collect()}),D=m.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:a})=>{const r=await a.db.query(d).withIndex("byKey",h=>h.eq("key",t.threadKey)).first(),n=l(r,a.auth);if(n===void 0)throw new w("FORBIDDEN",`@lunora/agent: not allowed to resolve approvals on thread "${t.threadKey}"`);if(n.instanceId!==t.instanceId)throw new w("FORBIDDEN",`@lunora/agent: instance "${t.instanceId}" does not own thread "${t.threadKey}"`);const i=n.agent,{agents:o}=a,y=o?.[i];if(typeof y?.sendEvent!="function")throw new w("INTERNAL",`@lunora/agent: no ctx.agents["${i}"] 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}}),M=m.input({agent:e.string(),input:e.string(),threadKey:e.string(),title:e.optional(e.string())}).mutation(async({args:t,ctx:a})=>{const{agents:r}=a,n=r?.[t.agent];if(typeof n?.run!="function")throw new w("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(n.publicRun!==!0)throw new w("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 i=a.auth.userId??void 0,o=await a.db.query(d).withIndex("byKey",h=>h.eq("key",t.threadKey)).first();if(o){const h=o.status,E=o.instanceId,v=o.owner;if((h==="running"||h==="awaiting_input")&&E!==void 0&&(v===void 0||v===i))return{id:E,threadKey:t.threadKey};if(v!==i&&i!==void 0)throw new w("FORBIDDEN",`@lunora/agent: thread "${t.threadKey}" belongs to another owner`)}const{id:y}=await n.run({input:t.input,threadKey:t.threadKey,...i===void 0?{}:{owner:i},...t.title===void 0?{}:{title:t.title}});return{id:y,threadKey:t.threadKey}}),C=F(),A=Q();return{extension:V,functions:{agentAppendMessage:b(f),agentEnsureThread:b(c),agentEpisodeRecall:A.agentEpisodeRecall,agentEpisodeUpsert:A.agentEpisodeUpsert,agentGraphTraverse:C.agentGraphTraverse,agentGraphUpsert:C.agentGraphUpsert,agentMessages:_,agentPatchThread:b(s),agentResolveApproval:D,agentRun:M,agentSetState:b(u),agentState:p,agentThread:g}}};export{te as agentComponent,V as agentExtension,re as normalizeEntityName,oe as sandboxComponent};
|
package/dist/inbound.d.mts
CHANGED
package/dist/inbound.d.ts
CHANGED
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AgentDefinition,
|
|
2
|
-
export type {
|
|
1
|
+
import { A as AgentDefinition, d as AgentCompact, e as AgentEpisodeExtract, f as AgentGraphExtract, g as AgentGenerate, h as AgentTokenSink, i as AgentRunInput, j as AgentFunctionPaths, k as AgentRunFunction, l as AgentStepLike, m as AgentStreamGenerate, n as AgentRunResult, o as AgentMessageRow, p as AgentConfig, c as SkillDefinition, q as AnyAgentTool, r as AgentAsToolOptions, s as AgentSubToolInput, b as AgentToolDefinition, t as AgentBindingSpec, u as AgentHandle, v as AgentToolConfig, w as AgentFunctionReference, x as AgentModelInput, y as SkillConfig } from "./packem_shared/types.d-PMYeuDE7.mjs";
|
|
2
|
+
export type { z as AgentApprovalContext, B as AgentEmailMapper, C as AgentEmailRun, D as AgentGenerateOptions, E as AgentGenerateResult, F as AgentInstructionsContext, G as AgentLiveEvent, H as AgentMemoryOptions, J as AgentMemorySource, K as AgentMessageStatus, L as AgentOnStepFinish, M as AgentPrepareStep, N as AgentPrepareStepInput, O as AgentPrepareStepResult, P as AgentProgressEvent, Q as AgentRunHandle, R as AgentStepFinishInfo, T as AgentStepInfo, U as AgentThreadStatus, V as AgentTokenDelta, W as AgentToolCall, a as AgentToolContext, X as AgentUsage, Y as AgentVoiceConfig, Z as AgentWorkflowBindingLike, _ as AgentWorkflowInstanceLike } from "./packem_shared/types.d-PMYeuDE7.mjs";
|
|
3
3
|
export { type AgentComponent, agentComponent, agentExtension } from "./component.mjs";
|
|
4
4
|
import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
|
|
5
5
|
export { agentBindingName, agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.mjs";
|
|
@@ -793,19 +793,6 @@ declare class VoiceSessionDO {
|
|
|
793
793
|
private synthesizeWithSignal;
|
|
794
794
|
/** Abort an in-flight turn and free a socket's transient buffers. */
|
|
795
795
|
private cleanupSocket;
|
|
796
|
-
/**
|
|
797
|
-
* Whether `attachment` carries a credential whose expiry (stamped at
|
|
798
|
-
* upgrade) is now past. Delegates to the shared boundary check
|
|
799
|
-
* `@lunora/do`'s `ShardDO` uses for the same decision, so the two DOs can
|
|
800
|
-
* never disagree about it.
|
|
801
|
-
*/
|
|
802
|
-
private isSocketExpired;
|
|
803
|
-
/**
|
|
804
|
-
* Drop an expired-credential socket via the shared `TOKEN_EXPIRED`/`4001`
|
|
805
|
-
* helper `@lunora/do`'s `ShardDO` also calls, so both DOs send the
|
|
806
|
-
* client-facing wire shape from one place.
|
|
807
|
-
*/
|
|
808
|
-
private dropExpiredSocket;
|
|
809
796
|
/** Send a JSON control frame, swallowing a closed-socket error (never throw from a handler). */
|
|
810
797
|
private send;
|
|
811
798
|
/** Send a binary audio frame, swallowing a closed-socket error. */
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AgentDefinition,
|
|
2
|
-
export type {
|
|
1
|
+
import { A as AgentDefinition, d as AgentCompact, e as AgentEpisodeExtract, f as AgentGraphExtract, g as AgentGenerate, h as AgentTokenSink, i as AgentRunInput, j as AgentFunctionPaths, k as AgentRunFunction, l as AgentStepLike, m as AgentStreamGenerate, n as AgentRunResult, o as AgentMessageRow, p as AgentConfig, c as SkillDefinition, q as AnyAgentTool, r as AgentAsToolOptions, s as AgentSubToolInput, b as AgentToolDefinition, t as AgentBindingSpec, u as AgentHandle, v as AgentToolConfig, w as AgentFunctionReference, x as AgentModelInput, y as SkillConfig } from "./packem_shared/types.d-PMYeuDE7.js";
|
|
2
|
+
export type { z as AgentApprovalContext, B as AgentEmailMapper, C as AgentEmailRun, D as AgentGenerateOptions, E as AgentGenerateResult, F as AgentInstructionsContext, G as AgentLiveEvent, H as AgentMemoryOptions, J as AgentMemorySource, K as AgentMessageStatus, L as AgentOnStepFinish, M as AgentPrepareStep, N as AgentPrepareStepInput, O as AgentPrepareStepResult, P as AgentProgressEvent, Q as AgentRunHandle, R as AgentStepFinishInfo, T as AgentStepInfo, U as AgentThreadStatus, V as AgentTokenDelta, W as AgentToolCall, a as AgentToolContext, X as AgentUsage, Y as AgentVoiceConfig, Z as AgentWorkflowBindingLike, _ as AgentWorkflowInstanceLike } from "./packem_shared/types.d-PMYeuDE7.js";
|
|
3
3
|
export { type AgentComponent, agentComponent, agentExtension } from "./component.js";
|
|
4
4
|
import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
|
|
5
5
|
export { agentBindingName, agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.js";
|
|
@@ -793,19 +793,6 @@ declare class VoiceSessionDO {
|
|
|
793
793
|
private synthesizeWithSignal;
|
|
794
794
|
/** Abort an in-flight turn and free a socket's transient buffers. */
|
|
795
795
|
private cleanupSocket;
|
|
796
|
-
/**
|
|
797
|
-
* Whether `attachment` carries a credential whose expiry (stamped at
|
|
798
|
-
* upgrade) is now past. Delegates to the shared boundary check
|
|
799
|
-
* `@lunora/do`'s `ShardDO` uses for the same decision, so the two DOs can
|
|
800
|
-
* never disagree about it.
|
|
801
|
-
*/
|
|
802
|
-
private isSocketExpired;
|
|
803
|
-
/**
|
|
804
|
-
* Drop an expired-credential socket via the shared `TOKEN_EXPIRED`/`4001`
|
|
805
|
-
* helper `@lunora/do`'s `ShardDO` also calls, so both DOs send the
|
|
806
|
-
* client-facing wire shape from one place.
|
|
807
|
-
*/
|
|
808
|
-
private dropExpiredSocket;
|
|
809
796
|
/** Send a JSON control frame, swallowing a closed-socket error (never throw from a handler). */
|
|
810
797
|
private send;
|
|
811
798
|
/** Send a binary audio frame, swallowing a closed-socket error. */
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{runAgentLoop as t,splitForCompaction as r}from"./packem_shared/runAgentLoop-
|
|
1
|
+
import{runAgentLoop as t,splitForCompaction as r}from"./packem_shared/runAgentLoop-nuk5NsAn.mjs";import{collectAgenticMemoryTools as a,toSearchResults as i}from"./packem_shared/collectAgenticMemoryTools-DBcP8dUa.mjs";import{agentAsTool as l}from"./packem_shared/agentAsTool-gH17BQ8M.mjs";import{codeTool as p}from"./packem_shared/codeTool-DYJVy-bH.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as A}from"./packem_shared/createAgentContext-D1cXHQO2.mjs";import{defineAgent as d,defineAgentTool as u,isAgentDefinition as N}from"./packem_shared/defineAgent-D0VIzlhu.mjs";import{functionTool as D}from"./packem_shared/functionTool-CWHhkYqd.mjs";import{createAgentGenerate as M,createEpisodeExtract as O,createGraphExtract as _,createStreamGenerate as C,resolveAgentModel as G}from"./packem_shared/createAgentGenerate-BS1vasdV.mjs";import{adaptMcpResult as F,mcpTools as L}from"./packem_shared/adaptMcpResult-18G7zpFo.mjs";import{buildModelMessages as k}from"./packem_shared/buildModelMessages-Dm2wVNQy.mjs";import{agentBindingName as R,agentClassName as V,agentDefaultName as b,voiceBindingName as h,voiceClassName as w}from"./naming.mjs";import{AGENT_MODULE as I,DEFAULT_AGENT_FUNCTION_PATHS as P,SANDBOX_INVOKE_PATH as X,SANDBOX_MODULE as y,toFunctionReference as K}from"./packem_shared/AGENT_MODULE-BXx-tSCe.mjs";import{browserTool as W,containerTool as j,fsTool as q}from"./sandbox.mjs";import{defineSkill as J,isSkillDefinition as Y}from"./packem_shared/defineSkill-DfJxCwfZ.mjs";import{default as $}from"./packem_shared/VoiceSessionDO-DNXzVGVf.mjs";import{Q as oe}from"./packem_shared/voice-turn-DzRKyf-x.mjs";import{default as re}from"./packem_shared/compileAgentWorkflow-BW627hb5.mjs";export{I as AGENT_MODULE,P as DEFAULT_AGENT_FUNCTION_PATHS,X as SANDBOX_INVOKE_PATH,y as SANDBOX_MODULE,$ as VoiceSessionDO,F as adaptMcpResult,l as agentAsTool,R as agentBindingName,V as agentClassName,c as agentComponent,b as agentDefaultName,x as agentExtension,W as browserTool,k as buildModelMessages,p as codeTool,a as collectAgenticMemoryTools,re as compileAgentWorkflow,j as containerTool,A as createAgentContext,M as createAgentGenerate,O as createEpisodeExtract,_ as createGraphExtract,C as createStreamGenerate,d as defineAgent,u as defineAgentTool,J as defineSkill,q as fsTool,D as functionTool,N as isAgentDefinition,Y as isSkillDefinition,L as mcpTools,G as resolveAgentModel,t as runAgentLoop,oe as runVoiceTurn,r as splitForCompaction,K as toFunctionReference,i as toSearchResults,h as voiceBindingName,w as voiceClassName};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createAi as g}from"@lunora/ai";import{A as y}from"./createDispatchRunner-EYOnoElU-CpVpdTXn.mjs";import{a as m}from"./base64-B_qZ_Tyh.mjs";import{X as w,l as b,g as v,p as u,E as l,Y as A,Z as S,e as x,Q as I,P as k}from"./voice-turn-DzRKyf-x.mjs";import{createStreamGenerate as M}from"./createAgentGenerate-BS1vasdV.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as B,toFunctionReference as f}from"./AGENT_MODULE-BXx-tSCe.mjs";const U="@cf/openai/whisper-large-v3-turbo",z="@cf/deepgram/aura-1",F=8*1024*1024,N=256*1024,p=15,T=5e3;class L{agent;ai;env;exportName;paths;streamGenerate;sttModel;ttsModel;audioBuffers=new Map;bufferedBytes=new Map;controllers=new Map;state;constructor(t,e,s,n){this.state=t,this.env=e,this.agent=s,this.exportName=n,this.paths=B,this.ai=g({binding:e.AI,env:e}),this.streamGenerate=M(s,e),this.sttModel=s.voice?.stt??U,this.ttsModel=s.voice?.tts??z}fetch(t){if(t.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{status:426});const e=new URL(t.url).searchParams.get("threadKey");if(!e)return new Response("Missing threadKey",{status:400});const s=globalThis.WebSocketPair,n=new s,i=n[0],r=n[1];this.state.acceptWebSocket(r);const c=crypto.randomUUID(),o=w(t.headers.get("x-lunora-identity")),d=b(t.headers.get("x-lunora-userid")),a=v(t.headers.get("x-lunora-identity-exp"));if(u(a))return l(r),new Response(null,{status:101,webSocket:i});r.serializeAttachment?.({connectionId:c,threadKey:e,turn:0,...a===void 0?{}:{expiresAt:a},...o===void 0?{}:{identity:o},...d===void 0?{}:{userId:d}}),this.send(r,{audioFormat:this.agent.voice?.audioFormat??"mp3",type:"ready"});const h=this.agent.voice?.greeting;return h&&h.length>0&&this.state.waitUntil?.(this.speakGreeting(r,c,e,d,o,h)),new Response(null,{status:101,webSocket:i})}async webSocketMessage(t,e){const s=t.deserializeAttachment?.();if(s){if(u(s.expiresAt)){l(t);return}try{if(typeof e=="string"){await this.handleControl(t,s,e);return}this.bufferAudio(s.connectionId,new Uint8Array(e),t)}catch(n){this.send(t,{message:n instanceof Error?n.message:String(n),type:"error"})}}}webSocketClose(t){this.cleanupSocket(t)}webSocketError(t){this.cleanupSocket(t)}resolveRun(t,e){const s=t===void 0&&e===void 0?void 0:{...e===void 0?{}:{claims:e},...t===void 0?{}:{userId:t}};return y({env:this.env,label:"@lunora/agent voice",...s===void 0?{}:{identity:s}})}async transcribe(t){const e=A(t);return S(await this.ai.run(this.sttModel,{audio:m(e)}))}async synthesize(t,e){const s=this.agent.voice?.speaker;return x(await this.ai.run(this.ttsModel,{text:t,...s===void 0?{}:{speaker:s}},e===void 0?void 0:{signal:e}))}async handleControl(t,e,s){let n;try{n=JSON.parse(s)}catch{return}if(n.type==="interrupt"){this.controllers.get(e.connectionId)?.abort();return}if(this.controllers.has(e.connectionId)){this.send(t,{message:"a turn is already in progress — send an interrupt before the next utterance",type:"error"});return}if(n.type==="commit"){const i=this.drainAudio(e.connectionId);await this.runTurn(t,e,{pcm:i});return}await this.runTurn(t,e,{text:n.text})}bufferAudio(t,e,s){const n=(this.bufferedBytes.get(t)??0)+e.byteLength;if(n>F){this.audioBuffers.delete(t),this.bufferedBytes.delete(t),this.send(s,{message:"utterance exceeded the maximum buffer — send a commit sooner",type:"error"});return}const i=this.audioBuffers.get(t)??[];i.push(e),this.audioBuffers.set(t,i),this.bufferedBytes.set(t,n)}drainAudio(t){const e=this.audioBuffers.get(t)??[];this.audioBuffers.delete(t),this.bufferedBytes.delete(t);const s=e.reduce((r,c)=>r+c.byteLength,0),n=new Uint8Array(s);let i=0;for(const r of e)n.set(r,i),i+=r.byteLength;return n}async runTurn(t,e,s){const n=new AbortController;this.controllers.set(e.connectionId,n);try{await I({agent:this.agent,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:n.signal,streamGenerate:this.streamGenerate,synthesize:async(i,r)=>this.synthesizeWithSignal(i,r),threadKey:e.threadKey,transcribe:async i=>this.transcribe(i),turn:e.turn,waitForDrain:async()=>this.waitForSocketDrain(t),...e.userId===void 0?{}:{owner:e.userId},...s.pcm===void 0?{}:{pcm:s.pcm},...s.text===void 0?{}:{text:s.text}})}finally{this.controllers.get(e.connectionId)===n&&this.controllers.delete(e.connectionId),t.serializeAttachment?.({...e,turn:e.turn+1})}}async speakGreeting(t,e,s,n,i,r){const c=this.resolveRun(n,i),o=new AbortController,d=()=>o.signal.aborted;this.controllers.set(e,o);try{await c(f(this.paths.ensureThread),{agent:this.exportName,key:s,...this.agent.initialState===void 0?{}:{initialState:this.agent.initialState},...n===void 0?{}:{owner:n}});for await(const a of k(await this.synthesizeWithSignal(r,o.signal))){if(d()||(await this.waitForSocketDrain(t),d()))break;this.sendAudio(t,a)}d()||(await c(f(this.paths.appendMessage),{content:r,messageKey:"voice:greeting:assistant",role:"assistant",threadKey:s}),this.send(t,{text:r,type:"assistant_done"}))}catch(a){this.send(t,{message:a instanceof Error?a.message:String(a),type:"error"})}finally{this.controllers.get(e)===o&&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))}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 s=0;for(;typeof e.bufferedAmount=="number"&&e.bufferedAmount>N&&s<T;)await new Promise(n=>{setTimeout(n,p)}),s+=p}}export{L as default};
|
package/dist/packem_shared/{compileAgentWorkflow-Bzd8oR9X.mjs → compileAgentWorkflow-BW627hb5.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineWorkflow as m}from"@lunora/workflow";import{runAgentLoop as i}from"./runAgentLoop-
|
|
1
|
+
import{defineWorkflow as m}from"@lunora/workflow";import{runAgentLoop as i}from"./runAgentLoop-nuk5NsAn.mjs";import{createStreamGenerate as p,createAgentGenerate as c,createEpisodeExtract as l,createGraphExtract as d,createCompact as f}from"./createAgentGenerate-BS1vasdV.mjs";import{agentDefaultName as u}from"../naming.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as v}from"./AGENT_MODULE-BXx-tSCe.mjs";import{A as E}from"./createDispatchRunner-EYOnoElU-CpVpdTXn.mjs";import{otlpTelemetry as N}from"./otlpTelemetry-DcW9mOLV.mjs";const T=(t,r,a)=>r===void 0?t:E({env:a,identity:{userId:r},label:"@lunora/agent"}),y=(t,r,a)=>{const e=r.LUNORA_OTLP_ENDPOINT;if(typeof e!="string"||e===""||t.telemetry?.isEnabled===!1)return t;const n=typeof r.LUNORA_OTLP_TOKEN=="string"?r.LUNORA_OTLP_TOKEN:void 0,o=[t.telemetry?.integrations].flat().filter(s=>s!==void 0);return{...t,telemetry:{...t.telemetry,integrations:[...o,N({conversationId:a,endpoint:e,token:n})],isEnabled:!0}}},G=(t,r,a)=>m({handler:async e=>{const n=y(t,e.env,e.params.threadKey);return i({agent:n,compact:f(),env:e.env,exportName:r,extractGraph:d(),extractEpisode:l(),generate:c(n,e.env),instanceId:e.event.instanceId,params:e.params,paths:a?.paths??v,run:T(e.run,e.params.owner,e.env),step:e.step,streamGenerate:p(n,e.env)})},name:t.name??u(r)});export{G as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o="agent",r=t=>({...t,visibility:"internal"}),s=t=>{const e={};for(const[n,i]of Object.entries(t))i!==void 0&&(e[n]=i);return e};export{r as i,o,s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as g,d as c,s as l,c as f,a as I,r as o,b as m}from"./common-Dck97z3Y.mjs";const b=(a,r,d)=>{globalThis.console[a](r,d)},x=(a={})=>{const{functionId:r,logger:d=b,recordInputs:u=!1,recordOutputs:i=!1}=a,p=r===void 0?"":`[${r}] `,t=(e,n,s)=>{d(e,`${p}${n}`,s)};return{onAbort:e=>{t("warn","agent operation aborted",{callId:o(e,"callId"),reason:o(e,"reason")})},onEnd:e=>{t("info","agent operation completed",{callId:o(e,"callId"),finishReason:o(e,"finishReason"),operationId:o(e,"operationId"),usage:l(o(e,"usage"))})},onError:e=>{t("error","agent operation errored",{error:c(e)})},onLanguageModelCallEnd:e=>{const n={callId:o(e,"callId"),finishReason:o(e,"finishReason"),modelId:o(e,"modelId"),provider:o(e,"provider"),usage:l(o(e,"usage"))};i&&(n.text=f(o(e,"content"))),t("info","language model call ended",n)},onStart:e=>{t("info","agent operation started",{callId:o(e,"callId"),modelId:o(e,"modelId"),operationId:o(e,"operationId"),provider:o(e,"provider")})},onStepEnd:e=>{t("info","agent step ended",{finishReason:o(e,"finishReason"),stepNumber:o(e,"stepNumber"),usage:l(o(e,"usage"))})},onStepStart:e=>{t("info","agent step started",{stepNumber:o(e,"stepNumber")})},onToolExecutionEnd:e=>{const n=I(e),s={success:n.success,tool:n.name,toolExecutionMs:n.toolExecutionMs};n.success||(s.error=c(n.error)),i&&n.success&&(s.output=n.output),t(n.success?"info":"warn","tool execution ended",s)},onToolExecutionStart:e=>{const n={tool:m(e)};u&&(n.input=g(e)),t("info","tool execution started",n)}}};export{x as consoleTelemetry};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{createAi as w}from"@lunora/ai";import{LunoraError as x}from"@lunora/errors";import{jsonSchema as T,generateText as d,Output as g,streamText as j,tool as k}from"ai";const y=e=>{if(!e)return;const t={};for(const o of["inputTokens","outputTokens","totalTokens"]){const n=e[o];n!==void 0&&(t[o]=n)}return Object.keys(t).length>0?t:void 0},f=e=>e.map(t=>({id:t.toolCallId,input:t.input,name:t.toolName})),m=(e,t)=>{if(typeof e=="function")return e(t);if(typeof e=="string"){const o=t.AI;if(!o)throw new x("INTERNAL",`@lunora/agent: the agent model "${e}" is a Workers AI id but there is no \`AI\` binding on the workflow env — declare the ai binding in wrangler.jsonc`);return w({binding:o,env:t}).model(e)}return e},v=(e,t)=>{const o=m(e.model,t),n={};for(const[i,a]of Object.entries(e.tools??{}))n[i]=k({description:a.description,inputSchema:a.inputSchema});const s=e.output===void 0?void 0:g.object({schema:e.output}),r={...e.temperature===void 0?{}:{temperature:e.temperature},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens},...e.telemetry===void 0?{}:{telemetry:e.telemetry},...e.repairToolCall===void 0?{}:{experimental_repairToolCall:e.repairToolCall}};return{defaultModel:o,output:s,staticSettings:r,tools:n}},b=(e,{activeTools:t,messages:o,model:n,signal:s,toolChoice:r})=>{const{defaultModel:i,output:a,staticSettings:h,tools:l}=e,c=t===void 0?l:Object.fromEntries(Object.entries(l).filter(([p])=>t.includes(p)));return{messages:o,model:n??i,...h,...Object.keys(c).length>0?{tools:c}:{},...r===void 0?{}:{toolChoice:r},...a===void 0?{}:{output:a},...s===void 0?{}:{abortSignal:s}}},N=(e,t)=>{const o=v(e,t);return async n=>{const s=await d(b(o,n)),r=y(s.usage);return{text:s.text,toolCalls:f(s.toolCalls),...r===void 0?{}:{usage:r},...o.output===void 0?{}:{output:s.output}}}},$=(e,t)=>{const o=v(e,t);return async(n,s)=>{const r=j(b(o,n));let i="";try{for await(const u of r.textStream)i+=u,s(u)}catch(u){if(n.signal?.aborted)return{text:i,toolCalls:[]};throw u}const[a,h,l,c]=await Promise.all([r.text,r.toolCalls,r.usage,o.output===void 0?Promise.resolve(void 0):r.output]),p=y(l);return{text:a,toolCalls:f(h),...p===void 0?{}:{usage:p},...o.output===void 0?{}:{output:c}}}},C=T({additionalProperties:!1,properties:{entities:{description:"The distinct entities (people, orgs, places, things, concepts) named in the exchange.",items:{additionalProperties:!1,properties:{name:{description:"The entity's canonical name.",type:"string"},type:{description:"An optional coarse type, e.g. person, org, place, product.",type:"string"}},required:["name"],type:"object"},type:"array"},relations:{description:"The directed relationships between the entities, as (src)-[label]->(dst) triples.",items:{additionalProperties:!1,properties:{confidence:{description:"Confidence in the relation, 0..1.",type:"number"},dst:{description:"The destination entity name (must appear in `entities`).",type:"string"},label:{description:"The relationship, a short snake_case verb phrase, e.g. works_at.",type:"string"},src:{description:"The source entity name (must appear in `entities`).",type:"string"}},required:["src","dst","label"],type:"object"},type:"array"}},required:["entities","relations"],type:"object"}),O=(e,t)=>["Extract a knowledge graph of the durable facts stated in the following exchange.","Return the distinct entities and the directed relationships between them.","Only include facts actually stated — do not invent entities or relations. Prefer few, high-signal triples.","",`User: ${e}`,"",`Assistant: ${t}`].join(`
|
|
2
|
+
`),q=()=>async({assistantText:e,env:t,model:o,userInput:n})=>{const{output:s}=await d({model:m(o,t),output:g.object({schema:C}),prompt:O(n,e)});return s},A=(e,t)=>["Summarize the following exchange as ONE concise past-tense sentence for a long-term memory log.","Capture what the user wanted and what was done or decided — a durable fact worth recalling in a later conversation.","No preamble and no quotes: return only the sentence.","",`User: ${e}`,"",`Assistant: ${t}`].join(`
|
|
3
|
+
`),G=()=>async({assistantText:e,env:t,model:o,userInput:n})=>{const{text:s}=await d({model:m(o,t),prompt:A(n,e)});return{summary:s.trim()}},S="You are compacting an ongoing conversation. Summarize the messages so far into a concise brief that preserves decisions made, facts established, open questions, and current task state — everything the assistant needs to continue coherently. Write it as notes for the assistant, not a reply to the user. No preamble.",M=()=>async({env:e,messages:t,model:o})=>{const{text:n}=await d({messages:t,model:m(o,e),system:S});return n.trim()};export{N as createAgentGenerate,M as createCompact,G as createEpisodeExtract,q as createGraphExtract,$ as createStreamGenerate,m as resolveAgentModel};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{defineTable as f,initLunora as C}from"@lunora/server";import{v as e}from"@lunora/values";import{o as A,i as x,s as S}from"./component-shared-BVjAbtUu.mjs";const O="entities",K="edges",N=`${A}_${O}`,g=`${A}_${K}`,J={[O]:f({createdAt:e.number(),firstMessageKey:e.optional(e.string()),name:e.string(),owner:e.string(),type:e.optional(e.string()),updatedAt:e.number(),weight:e.optional(e.number())}).index("byOwnerName",["owner","name"],{unique:!0}).index("byOwnerUpdatedAt",["owner","updatedAt"]).public(),[K]:f({createdAt:e.number(),dstName:e.string(),label:e.string(),messageKey:e.string(),owner:e.string(),srcName:e.string(),updatedAt:e.number(),weight:e.optional(e.number())}).index("byOwnerSrc",["owner","srcName"]).index("byOwnerDst",["owner","dstName"]).index("byTriple",["owner","srcName","label","dstName"],{unique:!0}).public()},q=64,$=2,v=4,I=8,T=32,L=500,M=/\s+/gu,_=/[^\p{L}\p{N}]+/u,b=t=>t.trim().replaceAll(M," ").toLowerCase(),j=t=>t.toLowerCase().split(_).filter(n=>n.length>=2),D=t=>({dstName:t.dstName,label:t.label,srcName:t.srcName,weight:t.weight??1}),U=(t,n)=>n.weight-t.weight||t.label.localeCompare(n.label)||t.srcName.localeCompare(n.srcName)||t.dstName.localeCompare(n.dstName),k=(t,n)=>n.some(a=>t.includes(a)||a.includes(t)),z=t=>t.map(n=>`- ${n.srcName} —[${n.label}]→ ${n.dstName}`).toSorted((n,a)=>n.localeCompare(a)).join(`
|
|
2
|
+
`),G=t=>`${t.srcName}\0${t.label}\0${t.dstName}`,P=(t,n,a,r)=>{const s=G(t);r.collectedKeys.has(s)||(r.collectedKeys.add(s),r.collected.push(t));const l=t.srcName===n?t.dstName:t.srcName;!r.seen.has(l)&&r.seen.size<a.maxNodes&&(r.seen.add(l),r.next.push(l))},B=async(t,n,a)=>{const r={collected:[],collectedKeys:new Set,next:[],seen:new Set(n)};let s=n.slice(0,a.maxNodes);for(let l=0;l<a.depth&&s.length>0;l+=1){r.next=[];for(const u of s){const o=(await t(u)).toSorted(U).slice(0,a.fanOut);for(const m of o)P(m,u,a,r)}s=r.next}return r.collected},{mutation:E,query:F}=C.dataModel().create(),Q=()=>{const t=E.input({entities:e.array(e.object({name:e.string(),type:e.optional(e.string())})),messageKey:e.string(),owner:e.string(),relations:e.array(e.object({confidence:e.optional(e.number()),dst:e.string(),label:e.string(),src:e.string()}))}).mutation(async({args:a,ctx:r})=>{const s=Date.now(),l=async(d,i)=>{const c=b(d);if(c.length===0)return;const w=await r.db.query(N).withIndex("byOwnerName",p=>p.eq("owner",a.owner).eq("name",c)).first();return w?(i!==void 0&&w.type===void 0&&await r.db.patch(w._id,{type:i,updatedAt:s}),c):(await r.db.insert(N,{createdAt:s,name:c,owner:a.owner,updatedAt:s,weight:1,...S({firstMessageKey:a.messageKey,type:i})}),c)},u=async d=>{const i=b(d.src),c=b(d.dst),w=b(d.label);if(i.length===0||c.length===0||w.length===0||i===c)return!1;await l(i),await l(c);const p=d.confidence??1,y=await r.db.query(g).withIndex("byTriple",h=>h.eq("owner",a.owner).eq("srcName",i).eq("label",w).eq("dstName",c)).first();if(y){const h=y.weight??1;await r.db.patch(y._id,{updatedAt:s,weight:Math.max(h,p)})}else await r.db.insert(g,{createdAt:s,dstName:c,label:w,messageKey:a.messageKey,owner:a.owner,srcName:i,updatedAt:s,weight:p});return!0};let o=0;for(const d of a.entities.slice(0,q))await l(d.name,d.type)!==void 0&&(o+=1);let m=0;for(const d of a.relations.slice(0,q))await u(d)&&(m+=1);return{entities:o,relations:m}}),n=F.input({depth:e.optional(e.number()),fanOut:e.optional(e.number()),maxNodes:e.optional(e.number()),maxSeeds:e.optional(e.number()),owner:e.string(),query:e.string()}).query(async({args:a,ctx:r})=>{const s=j(a.query);if(s.length===0)return{context:""};const l=(await r.db.query(N).withIndex("byOwnerUpdatedAt",o=>o.eq("owner",a.owner)).order("desc").take(L)).filter(o=>k(o.name,s)).toSorted((o,m)=>(m.weight??1)-(o.weight??1)||o.name.localeCompare(m.name)).slice(0,a.maxSeeds??v).map(o=>o.name);if(l.length===0)return{context:""};const u=await B(async o=>{const[m,d]=await Promise.all([r.db.query(g).withIndex("byOwnerSrc",i=>i.eq("owner",a.owner).eq("srcName",o)).collect(),r.db.query(g).withIndex("byOwnerDst",i=>i.eq("owner",a.owner).eq("dstName",o)).collect()]);return[...m,...d].map(i=>D(i))},l,{depth:a.depth??$,fanOut:a.fanOut??I,maxNodes:a.maxNodes??T});return{context:z(u)}});return{agentGraphTraverse:x(n),agentGraphUpsert:x(t)}};export{Q as graphComponent,J as graphTables,b as normalizeEntityName};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{s as q}from"./component-shared-BVjAbtUu.mjs";import{resolveAgentModel as L}from"./createAgentGenerate-BS1vasdV.mjs";import{i as _,c as C,t as J,n as Q}from"./memory-DNRyyp1b.mjs";import{buildModelMessages as E}from"./buildModelMessages-Dm2wVNQy.mjs";import{agentBindingName as V}from"../naming.mjs";import{toFunctionReference as v}from"./AGENT_MODULE-BXx-tSCe.mjs";const W=8,b=e=>e===void 0?"null":JSON.stringify(e),X=e=>e===void 0?[]:[e].flat(),Y=async(e,t)=>(await Promise.all(e.map(async o=>o({steps:t})))).some(Boolean),Z=(e,t)=>{if(t===void 0)return e;if(e===void 0)return{...t};const o={};for(const a of["inputTokens","outputTokens","totalTokens"])(e[a]!==void 0||t[a]!==void 0)&&(o[a]=(e[a]??0)+(t[a]??0));return o},z=async(e,t,o,a,r)=>{const{needsApproval:n}=e;return n===void 0||n===!1?!1:n===!0?!0:o.do(a,async()=>n(t,r))},H=async(e,t)=>{const{instanceId:o,patchThread:a,persist:r,step:n}=e;await r({content:`Awaiting approval to run tool "${t.name}".`,messageKey:`${o}:approval:${t.id}`,role:"tool",status:"awaiting_approval",toolCallId:t.id,toolName:t.name}),await a({status:"awaiting_input"});const i=await n.waitForEvent(`approval:${t.id}`,{type:`agent-approval:${t.id}`});return await a({status:"running"}),{decision:i.payload.decision,...i.payload.note===void 0?{}:{note:i.payload.note}}},tt=async(e,t)=>{const{env:o,getState:a,instanceId:r,onTokenDelta:n,persist:i,run:d,setState:c,step:p,threadKey:s,tools:u}=e,l=`tool:${t.name}:${t.id}`,m=u[t.name],h=`${r}:tool:${t.id}`;if(!m){await i({content:`Error: unknown tool "${t.name}"`,messageKey:h,role:"tool",stepName:l,toolCallId:t.id,toolName:t.name});return}const f=T=>{n?.({data:T,kind:"progress",threadKey:s,toolCallId:t.id})},$={env:o,getState:a,idempotencyKey:l,reportProgress:f,run:d,setState:c,threadKey:s,toolCallId:t.id},g={env:o,getState:a,idempotencyKey:l,reportProgress:f,run:d,threadKey:s,toolCallId:t.id},K=`tool:approval-gate:${t.id}`;let x;if(await z(m,t.input,p,K,g)){const{decision:T,note:S}=await H(e,t);if(T==="reject"){const M=S===void 0?"":` Reason: ${S}`;await i({content:`Tool "${t.name}" was rejected by the user and not run.${M}`,messageKey:h,role:"tool",status:"rejected",stepName:l,toolCallId:t.id,toolName:t.name});return}x="approved"}const w=await p.do(l,()=>Promise.resolve(m.execute(t.input,$)));await i({content:typeof w=="string"?w:b(w),messageKey:h,role:"tool",stepName:l,...x===void 0?{}:{status:x},toolCallId:t.id,toolName:t.name})},et=(e,t,o)=>{if(!t)return e;let{messages:a}=e;return t.messages!==void 0&&(a=t.messages),t.system!==void 0&&(a=[{content:t.system,role:"system"},...a]),{activeTools:t.activeTools??e.activeTools,messages:a,model:t.model===void 0?e.model:L(t.model,o),toolChoice:t.toolChoice??e.toolChoice}},at=(e,t)=>{if(t===void 0||e.length<=t.maxMessages)return;const o=Math.max(1,t.keepRecent??Math.ceil(t.maxMessages/2));if(e.length<=o)return;let a=e.length-o;for(;a>0&&e[a]?.role==="tool";)a-=1;if(!(a<=0))return{older:e.slice(0,a),recent:e.slice(a)}},ot=async(e,t)=>{const{agent:o,compact:a,env:r}=e,n=at(t,o.compaction);if(n===void 0||a===void 0)return{history:t,summary:void 0};try{const i=await a({env:r,messages:E({history:n.older}),model:o.compaction?.model??o.model});return i.length>0?{history:n.recent,summary:i}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},st=async(e,t,o)=>{const{agent:a,env:r,generate:n,instructions:i,listMessages:d,memoryContext:c,onTokenDelta:p,run:s,step:u,streamGenerate:l,threadKey:m}=e;return u.do(`llm:turn:${String(t)}`,async()=>{const h=await s(d,{key:m}),{history:f,summary:$}=await ot(e,h);let g={activeTools:a.activeTools,messages:E({history:f,instructions:i,memoryContext:c,summary:$}),model:void 0,toolChoice:a.toolChoice};a.prepareStep&&(g=et(g,await a.prepareStep({messages:g.messages,stepNumber:t,steps:o}),r));const K={messages:g.messages,...g.activeTools===void 0?{}:{activeTools:g.activeTools},...g.model===void 0?{}:{model:g.model},...g.toolChoice===void 0?{}:{toolChoice:g.toolChoice}};return l&&p?l(K,x=>{p({text:x,threadKey:m,turn:t})}):n(K)})},A=async(e,t)=>{const{agent:o,step:a}=e;o.onStepFinish&&await a.do(`agent:step-finish:${String(t.turn)}`,async()=>(await o.onStepFinish?.(t),!0))},nt=e=>({text:e.text,toolCalls:e.toolCalls.map(t=>({input:t.input,toolCallId:t.id,toolName:t.name})),...e.usage===void 0?{}:{usage:e.usage}}),R=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},rt=e=>q({depth:e?.depth,fanOut:e?.fanOut,maxNodes:e?.maxNodes,maxSeeds:e?.maxSeeds}),it=async(e,t,o,a)=>{if(e.source===void 0)return;const r=v(e.source),{topK:n}=e,i=C("memory:retrieve",e.key),d=await o.do(i,async()=>a(r,{query:t,...n===void 0?{}:{topK:n}}));return R(d)},lt=async(e,t,o,a,r,n)=>{if(o===void 0)return;const i=C("memory:traverse",e.key),d=await r.do(i,async()=>n(a,{owner:o,query:t,...rt(e.graph)}));return R(d)},dt=async(e,t,o,a,r)=>{if(t===void 0)return;const n=C("memory:recall",e.key),i={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},d=await a.do(n,async()=>r(o,i));return R(d)},ct=async(e,t)=>e.kind==="episodic"?dt(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?lt(e,t.input,t.owner,t.graphTraverse,t.step,t.run):it(e,t.input,t.step,t.run),ut=e=>{const t=e.findIndex(o=>o.kind==="episodic");return e.filter((o,a)=>o.kind!=="episodic"||a===t)},pt=async(e,t,o,a,r,n)=>{const i=ut(Q(e));if(i.length===0)return;const d=v(a.graphTraverse),c=v(a.episodeRecall),p=[];for(const s of i){const u=await ct(s,{episodeRecall:c,graphTraverse:d,input:t,owner:o,run:n,step:r});u!==void 0&&p.push(u)}return p.length>0?p.join(`
|
|
2
|
+
|
|
3
|
+
`):void 0},mt=async e=>{const{agent:t,env:o,extractGraph:a,finalText:r,input:n,instanceId:i,owner:d,paths:c,run:p,step:s}=e;if(a===void 0||d===void 0||r===void 0||r.length===0)return;const u=_(t);if(u!==void 0)try{const l={assistantText:r,env:o,model:u.graph?.extractionModel??t.model,userInput:n},m=await s.do(C("memory:extract",u.key),async()=>a(l));await p(v(c.graphUpsert),{...m,messageKey:`${i}:${C("extract",u.key)}`,owner:d})}catch{}},yt=async e=>{const{agent:t,env:o,extractEpisode:a,finalText:r,input:n,instanceId:i,owner:d,paths:c,run:p,step:s,threadKey:u}=e;if(a===void 0||d===void 0||r===void 0||r.length===0)return;const l=J(t);if(l!==void 0)try{const m={assistantText:r,env:o,model:l.episodic?.extractionModel??t.model,userInput:n},{summary:h}=await s.do(C("memory:episode",l.key),async()=>a(m));await p(v(c.episodeUpsert),{messageKey:`${i}:${C("episode",l.key)}`,owner:d,summary:h,threadKey:u})}catch{}},gt=async(e,t,o)=>{const a=e[V(t)];if(!(!a||typeof a.get!="function"))try{await(await a.get(o)).terminate()}catch{}},vt=async(e,t,o,a,r)=>{const{instanceId:n,persist:i}=e,d=o.usage===void 0?{}:{usage:o.usage};if(o.toolCalls.length===0){const c=o.output!==void 0&&o.text.length===0?b(o.output):o.text;return await i({content:c,messageKey:`${n}:assistant:${String(t)}`,role:"assistant"}),await A(e,{text:o.text,toolCalls:[],turn:t,...d}),{final:{stopped:"final",text:o.text,turns:t+1,...o.output===void 0?{}:{output:o.output}}}}await i({content:o.text,messageKey:`${n}:assistant:${String(t)}`,role:"assistant",toolCalls:o.toolCalls});for(const c of o.toolCalls)await tt(e,c);if(await A(e,{text:o.text,toolCalls:o.toolCalls,turn:t,...d}),a.push(nt(o)),r.length>0&&await Y(r,a))return"stopCondition"},ht=async(e,t,o,a)=>{const r=[];let n,i=!1,d=0;for(let c=0;c<t;c+=1){const p=await st(e,c,r);a.value=Z(a.value,p.usage),d=c+1;const s=await vt(e,c,p,r,o);if(s==="stopCondition"){i=!0;break}if(s!==void 0){n=s.final;break}}return{final:n,stoppedByCondition:i,turnsRun:d}},$t=async e=>{const{agent:t,compact:o,env:a,exportName:r,extractEpisode:n,extractGraph:i,generate:d,instanceId:c,onTokenDelta:p,params:s,paths:u,run:l,step:m,streamGenerate:h}=e,f=t.maxTurns??W,$=X(t.stopWhen),g=v(u.appendMessage),K=v(u.ensureThread),x=v(u.listMessages),w=v(u.patchThread),T=v(u.setState),S=v(u.state),M=async y=>{await l(g,{threadKey:s.threadKey,...y})},F=async y=>{await l(w,{key:s.threadKey,...y})},G=async()=>await l(S,{key:s.threadKey}),j=async y=>{await l(T,{key:s.threadKey,state:y})},N=await l(K,{agent:r,instanceId:c,key:s.threadKey,...t.initialState===void 0?{}:{initialState:t.initialState},...t.onConcurrentRun===void 0?{}:{onConcurrentRun:t.onConcurrentRun},...s.owner===void 0?{}:{owner:s.owner},...s.title===void 0?{}:{title:s.title}});N?.replaced&&N.priorInstanceId!==void 0&&await gt(a,r,N.priorInstanceId),await M({content:s.input,messageKey:`${c}:user`,role:"user"});const B=await pt(t,s.input,s.owner,u,m,l),D=typeof t.instructions=="function"?t.instructions({env:a,input:s.input,threadKey:s.threadKey}):t.instructions,P={agent:t,compact:o,env:a,generate:d,getState:G,instanceId:c,instructions:D,listMessages:x,memoryContext:B,onTokenDelta:p,patchThread:F,persist:M,run:l,setState:j,step:m,streamGenerate:h,threadKey:s.threadKey,tools:t.tools??{}},I={value:void 0};try{const{final:y,stoppedByCondition:O,turnsRun:U}=await ht(P,f,$,I),k=I.value===void 0?{}:{usage:I.value};return await mt({agent:t,env:a,extractGraph:i,finalText:y?.text,input:s.input,instanceId:c,owner:s.owner,paths:u,run:l,step:m}),await yt({agent:t,env:a,extractEpisode:n,finalText:y?.text,input:s.input,instanceId:c,owner:s.owner,paths:u,run:l,step:m,threadKey:s.threadKey}),y?(await l(w,{key:s.threadKey,status:"idle",...k}),{...y,...k}):O?(await l(w,{key:s.threadKey,status:"idle",...k}),{stopped:"stopCondition",turns:U,...k}):(await l(w,{error:`agent stopped: maxTurns (${String(f)}) reached`,key:s.threadKey,status:"error",...k}),{stopped:"maxTurns",turns:f,...k})}catch(y){throw await l(w,{error:y instanceof Error?y.message:String(y),key:s.threadKey,status:"error",...I.value===void 0?{}:{usage:I.value}}),y}};export{$t as runAgentLoop,at as splitForCompaction};
|
|
@@ -335,6 +335,12 @@ interface SkillConfig {
|
|
|
335
335
|
*/
|
|
336
336
|
tools?: Record<string, AnyAgentTool>;
|
|
337
337
|
}
|
|
338
|
+
/**
|
|
339
|
+
* The code-side parts of a markdown-authored skill — everything `SKILL.md`
|
|
340
|
+
* cannot carry. `name` and `instructions` come from the file itself.
|
|
341
|
+
* @experimental
|
|
342
|
+
*/
|
|
343
|
+
type SkillMarkdownExtras = Omit<SkillConfig, "instructions" | "name">;
|
|
338
344
|
/**
|
|
339
345
|
* A `defineSkill` result — config plus the brand the agent merge checks.
|
|
340
346
|
* @experimental
|
|
@@ -1128,4 +1134,4 @@ interface AgentHandle {
|
|
|
1128
1134
|
/** Read a run's workflow status by instance id. */
|
|
1129
1135
|
status: (id: string) => Promise<unknown>;
|
|
1130
1136
|
}
|
|
1131
|
-
export { AgentDefinition as A,
|
|
1137
|
+
export { AgentDefinition as A, AgentEmailMapper as B, AgentEmailRun as C, AgentGenerateOptions as D, AgentGenerateResult as E, AgentInstructionsContext as F, AgentLiveEvent as G, AgentMemoryOptions as H, InboundChannelEvent as I, AgentMemorySource as J, AgentMessageStatus as K, AgentOnStepFinish as L, AgentPrepareStep as M, AgentPrepareStepInput as N, AgentPrepareStepResult as O, AgentProgressEvent as P, AgentRunHandle as Q, AgentStepFinishInfo as R, SkillMarkdownExtras as S, AgentStepInfo as T, AgentThreadStatus as U, AgentTokenDelta as V, AgentToolCall as W, AgentUsage as X, AgentVoiceConfig as Y, AgentWorkflowBindingLike as Z, AgentWorkflowInstanceLike as _, AgentToolContext as a, AgentToolDefinition as b, SkillDefinition as c, AgentCompact as d, AgentEpisodeExtract as e, AgentGraphExtract as f, AgentGenerate as g, AgentTokenSink as h, AgentRunInput as i, AgentFunctionPaths as j, AgentRunFunction as k, AgentStepLike as l, AgentStreamGenerate as m, AgentRunResult as n, AgentMessageRow as o, AgentConfig as p, AnyAgentTool as q, AgentAsToolOptions as r, AgentSubToolInput as s, AgentBindingSpec as t, AgentHandle as u, AgentToolConfig as v, AgentFunctionReference as w, AgentModelInput as x, SkillConfig as y, AgentApprovalContext as z };
|
|
@@ -335,6 +335,12 @@ interface SkillConfig {
|
|
|
335
335
|
*/
|
|
336
336
|
tools?: Record<string, AnyAgentTool>;
|
|
337
337
|
}
|
|
338
|
+
/**
|
|
339
|
+
* The code-side parts of a markdown-authored skill — everything `SKILL.md`
|
|
340
|
+
* cannot carry. `name` and `instructions` come from the file itself.
|
|
341
|
+
* @experimental
|
|
342
|
+
*/
|
|
343
|
+
type SkillMarkdownExtras = Omit<SkillConfig, "instructions" | "name">;
|
|
338
344
|
/**
|
|
339
345
|
* A `defineSkill` result — config plus the brand the agent merge checks.
|
|
340
346
|
* @experimental
|
|
@@ -1128,4 +1134,4 @@ interface AgentHandle {
|
|
|
1128
1134
|
/** Read a run's workflow status by instance id. */
|
|
1129
1135
|
status: (id: string) => Promise<unknown>;
|
|
1130
1136
|
}
|
|
1131
|
-
export { AgentDefinition as A,
|
|
1137
|
+
export { AgentDefinition as A, AgentEmailMapper as B, AgentEmailRun as C, AgentGenerateOptions as D, AgentGenerateResult as E, AgentInstructionsContext as F, AgentLiveEvent as G, AgentMemoryOptions as H, InboundChannelEvent as I, AgentMemorySource as J, AgentMessageStatus as K, AgentOnStepFinish as L, AgentPrepareStep as M, AgentPrepareStepInput as N, AgentPrepareStepResult as O, AgentProgressEvent as P, AgentRunHandle as Q, AgentStepFinishInfo as R, SkillMarkdownExtras as S, AgentStepInfo as T, AgentThreadStatus as U, AgentTokenDelta as V, AgentToolCall as W, AgentUsage as X, AgentVoiceConfig as Y, AgentWorkflowBindingLike as Z, AgentWorkflowInstanceLike as _, AgentToolContext as a, AgentToolDefinition as b, SkillDefinition as c, AgentCompact as d, AgentEpisodeExtract as e, AgentGraphExtract as f, AgentGenerate as g, AgentTokenSink as h, AgentRunInput as i, AgentFunctionPaths as j, AgentRunFunction as k, AgentStepLike as l, AgentStreamGenerate as m, AgentRunResult as n, AgentMessageRow as o, AgentConfig as p, AnyAgentTool as q, AgentAsToolOptions as r, AgentSubToolInput as s, AgentBindingSpec as t, AgentHandle as u, AgentToolConfig as v, AgentFunctionReference as w, AgentModelInput as x, SkillConfig as y, AgentApprovalContext as z };
|
package/dist/sandbox.d.mts
CHANGED
package/dist/sandbox.d.ts
CHANGED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { S as SkillMarkdownExtras, c as SkillDefinition } from "./packem_shared/types.d-PMYeuDE7.mjs";
|
|
2
|
+
import '@lunora/mail/inbound';
|
|
3
|
+
import 'ai';
|
|
4
|
+
/**
|
|
5
|
+
* Declare a skill whose prose lives in a markdown file.
|
|
6
|
+
*
|
|
7
|
+
* ```ts
|
|
8
|
+
* import triage from "./skills/triage/SKILL.md?raw";
|
|
9
|
+
* import { functionTool } from "@lunora/agent";
|
|
10
|
+
* import { skillFromMarkdown } from "@lunora/agent/skill-markdown";
|
|
11
|
+
*
|
|
12
|
+
* export const triageSkill = skillFromMarkdown(triage, {
|
|
13
|
+
* tools: { searchCode: functionTool(api.code.search, { ... }) },
|
|
14
|
+
* });
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* ```md
|
|
18
|
+
* ---
|
|
19
|
+
* name: triage
|
|
20
|
+
* ---
|
|
21
|
+
* Reproduce the report before proposing a cause. Cite the failing test.
|
|
22
|
+
* ```
|
|
23
|
+
*
|
|
24
|
+
* The split is the point: the instructions are the part a non-author reads,
|
|
25
|
+
* reviews and copies between projects, so they belong in a file that is legible
|
|
26
|
+
* on its own — and the `name` travels WITH that file, so a skill can move
|
|
27
|
+
* without a matching TypeScript wrapper. Tools and `knowledge` stay in code,
|
|
28
|
+
* because they are code.
|
|
29
|
+
*
|
|
30
|
+
* Getting the markdown here is the caller's job (`?raw` under Vite, a build-time
|
|
31
|
+
* import elsewhere) — a Worker has no filesystem to read it from at runtime, so
|
|
32
|
+
* this takes the string rather than a path.
|
|
33
|
+
* @experimental
|
|
34
|
+
*/
|
|
35
|
+
declare const skillFromMarkdown: (markdown: string, extras?: SkillMarkdownExtras) => SkillDefinition;
|
|
36
|
+
export { type SkillMarkdownExtras, skillFromMarkdown };
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { S as SkillMarkdownExtras, c as SkillDefinition } from "./packem_shared/types.d-PMYeuDE7.js";
|
|
2
|
+
import '@lunora/mail/inbound';
|
|
3
|
+
import 'ai';
|
|
4
|
+
/**
|
|
5
|
+
* Declare a skill whose prose lives in a markdown file.
|
|
6
|
+
*
|
|
7
|
+
* ```ts
|
|
8
|
+
* import triage from "./skills/triage/SKILL.md?raw";
|
|
9
|
+
* import { functionTool } from "@lunora/agent";
|
|
10
|
+
* import { skillFromMarkdown } from "@lunora/agent/skill-markdown";
|
|
11
|
+
*
|
|
12
|
+
* export const triageSkill = skillFromMarkdown(triage, {
|
|
13
|
+
* tools: { searchCode: functionTool(api.code.search, { ... }) },
|
|
14
|
+
* });
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* ```md
|
|
18
|
+
* ---
|
|
19
|
+
* name: triage
|
|
20
|
+
* ---
|
|
21
|
+
* Reproduce the report before proposing a cause. Cite the failing test.
|
|
22
|
+
* ```
|
|
23
|
+
*
|
|
24
|
+
* The split is the point: the instructions are the part a non-author reads,
|
|
25
|
+
* reviews and copies between projects, so they belong in a file that is legible
|
|
26
|
+
* on its own — and the `name` travels WITH that file, so a skill can move
|
|
27
|
+
* without a matching TypeScript wrapper. Tools and `knowledge` stay in code,
|
|
28
|
+
* because they are code.
|
|
29
|
+
*
|
|
30
|
+
* Getting the markdown here is the caller's job (`?raw` under Vite, a build-time
|
|
31
|
+
* import elsewhere) — a Worker has no filesystem to read it from at runtime, so
|
|
32
|
+
* this takes the string rather than a path.
|
|
33
|
+
* @experimental
|
|
34
|
+
*/
|
|
35
|
+
declare const skillFromMarkdown: (markdown: string, extras?: SkillMarkdownExtras) => SkillDefinition;
|
|
36
|
+
export { type SkillMarkdownExtras, skillFromMarkdown };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as o}from"@lunora/errors";import{parse as s}from"yaml";import{defineSkill as l}from"./packem_shared/defineSkill-DfJxCwfZ.mjs";const m=/^\uFEFF?[ \t]*---[ \t]*\r?\n/u,d=/^---[ \t]*$/mu,h=n=>{const r=m.exec(n);if(!r)return{body:n.trim(),data:{}};const t=n.slice(r[0].length),e=d.exec(t);if(!e)throw new o("INTERNAL","@lunora/agent: the skill markdown opens with `---` but never closes the frontmatter block. Add a closing `---` on its own line.");let a;try{a=s(t.slice(0,e.index))}catch(i){throw new o("INTERNAL",`@lunora/agent: the skill markdown has invalid YAML frontmatter — ${i instanceof Error?i.message:String(i)}`)}return{body:t.slice(e.index+e[0].length).trim(),data:typeof a=="object"&&a!==null?a:{}}},c=(n,r={})=>{if(typeof n!="string")throw new o("INTERNAL",`@lunora/agent: skillFromMarkdown expects the markdown SOURCE as a string, got ${typeof n}`);const{body:t,data:e}=h(n);if(e.name!==void 0&&typeof e.name!="string")throw new o("INTERNAL",`@lunora/agent: the skill markdown's \`name\` must be a string, got ${Array.isArray(e.name)?"array":typeof e.name}. Quote it if the value looks like a number or a boolean (\`name: "2fa"\`).`);if(typeof e.name!="string")throw new o("INTERNAL","@lunora/agent: skillFromMarkdown found no `name` in the markdown frontmatter. Open the file with a `---` line, put `name: <identifier>` on its own line, and close it with `---`. Other keys are parsed and ignored — only `name` is read here.");if(t==="")throw new o("INTERNAL",`@lunora/agent: the skill markdown for "${e.name}" has no body — the instructions below the closing \`---\` are what the skill contributes.`);return l({...r,instructions:t,name:e.name})};export{c as skillFromMarkdown};
|
package/dist/telemetry/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{braintrustTelemetry as o}from"../packem_shared/braintrustTelemetry-CnOI5WAw.mjs";import{combineTelemetry as m}from"../packem_shared/combineTelemetry-oLCV_EPV.mjs";import{consoleTelemetry as p}from"../packem_shared/consoleTelemetry-
|
|
1
|
+
import{braintrustTelemetry as o}from"../packem_shared/braintrustTelemetry-CnOI5WAw.mjs";import{combineTelemetry as m}from"../packem_shared/combineTelemetry-oLCV_EPV.mjs";import{consoleTelemetry as p}from"../packem_shared/consoleTelemetry-C_85CaZ7.mjs";import{otlpTelemetry as f}from"../packem_shared/otlpTelemetry-DcW9mOLV.mjs";import{sentryTelemetry as T}from"../packem_shared/sentryTelemetry-Dr2aPuvl.mjs";export{o as braintrustTelemetry,m as combineTelemetry,p as consoleTelemetry,f as otlpTelemetry,T as sentryTelemetry};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/agent",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.43",
|
|
4
4
|
"description": "Durable AI agents for Lunora: defineAgent compiles a replay-safe tool-loop onto Cloudflare Workflows, with DO SQLite threads and live message subscriptions",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agent",
|
|
@@ -62,6 +62,10 @@
|
|
|
62
62
|
"types": "./dist/naming.d.ts",
|
|
63
63
|
"import": "./dist/naming.mjs"
|
|
64
64
|
},
|
|
65
|
+
"./skill-markdown": {
|
|
66
|
+
"types": "./dist/skill-markdown.d.ts",
|
|
67
|
+
"import": "./dist/skill-markdown.mjs"
|
|
68
|
+
},
|
|
65
69
|
"./sandbox": {
|
|
66
70
|
"types": "./dist/sandbox.d.ts",
|
|
67
71
|
"import": "./dist/sandbox.mjs"
|
|
@@ -76,14 +80,15 @@
|
|
|
76
80
|
"access": "public"
|
|
77
81
|
},
|
|
78
82
|
"dependencies": {
|
|
79
|
-
"@lunora/ai": "1.0.0-alpha.
|
|
80
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
81
|
-
"@lunora/mail": "1.0.0-alpha.
|
|
82
|
-
"@lunora/server": "1.0.0-alpha.
|
|
83
|
-
"@lunora/values": "1.0.0-alpha.
|
|
84
|
-
"@lunora/workflow": "1.0.0-alpha.
|
|
83
|
+
"@lunora/ai": "1.0.0-alpha.49",
|
|
84
|
+
"@lunora/errors": "1.0.0-alpha.15",
|
|
85
|
+
"@lunora/mail": "1.0.0-alpha.42",
|
|
86
|
+
"@lunora/server": "1.0.0-alpha.63",
|
|
87
|
+
"@lunora/values": "1.0.0-alpha.20",
|
|
88
|
+
"@lunora/workflow": "1.0.0-alpha.22",
|
|
85
89
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
86
|
-
"ai": "7.0.37"
|
|
90
|
+
"ai": "7.0.37",
|
|
91
|
+
"yaml": "^2.9.0"
|
|
87
92
|
},
|
|
88
93
|
"engines": {
|
|
89
94
|
"node": "^22.15.0 || >=24.11.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{createAi as g}from"@lunora/ai";import{A as y}from"./createDispatchRunner-EYOnoElU-CpVpdTXn.mjs";import{a as m}from"./base64-B_qZ_Tyh.mjs";import{X as w,l as b,g as v,p as u,E as l,Y as S,Z as x,e as A,Q as k,P as I}from"./voice-turn-DzRKyf-x.mjs";import{createStreamGenerate as M}from"./createAgentGenerate-D96dEdYw.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as B,toFunctionReference as p}from"./AGENT_MODULE-BXx-tSCe.mjs";const E="@cf/openai/whisper-large-v3-turbo",U="@cf/deepgram/aura-1",z=8*1024*1024,F=256*1024,f=15,N=5e3;class L{agent;ai;env;exportName;paths;streamGenerate;sttModel;ttsModel;audioBuffers=new Map;bufferedBytes=new Map;controllers=new Map;state;constructor(t,e,s,n){this.state=t,this.env=e,this.agent=s,this.exportName=n,this.paths=B,this.ai=g({binding:e.AI,env:e}),this.streamGenerate=M(s,e),this.sttModel=s.voice?.stt??E,this.ttsModel=s.voice?.tts??U}fetch(t){if(t.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{status:426});const e=new URL(t.url).searchParams.get("threadKey");if(!e)return new Response("Missing threadKey",{status:400});const s=globalThis.WebSocketPair,n=new s,i=n[0],r=n[1];this.state.acceptWebSocket(r);const c=crypto.randomUUID(),a=w(t.headers.get("x-lunora-identity")),d=b(t.headers.get("x-lunora-userid")),o=v(t.headers.get("x-lunora-identity-exp"));if(u(o))return l(r),new Response(null,{status:101,webSocket:i});r.serializeAttachment?.({connectionId:c,threadKey:e,turn:0,...o===void 0?{}:{expiresAt:o},...a===void 0?{}:{identity:a},...d===void 0?{}:{userId:d}}),this.send(r,{audioFormat:this.agent.voice?.audioFormat??"mp3",type:"ready"});const h=this.agent.voice?.greeting;return h&&h.length>0&&this.state.waitUntil?.(this.speakGreeting(r,c,e,d,a,h)),new Response(null,{status:101,webSocket:i})}async webSocketMessage(t,e){const s=t.deserializeAttachment?.();if(s){if(this.isSocketExpired(s)){this.dropExpiredSocket(t);return}try{if(typeof e=="string"){await this.handleControl(t,s,e);return}this.bufferAudio(s.connectionId,new Uint8Array(e),t)}catch(n){this.send(t,{message:n instanceof Error?n.message:String(n),type:"error"})}}}webSocketClose(t){this.cleanupSocket(t)}webSocketError(t){this.cleanupSocket(t)}resolveRun(t,e){const s=t===void 0&&e===void 0?void 0:{...e===void 0?{}:{claims:e},...t===void 0?{}:{userId:t}};return y({env:this.env,label:"@lunora/agent voice",...s===void 0?{}:{identity:s}})}async transcribe(t){const e=S(t);return x(await this.ai.run(this.sttModel,{audio:m(e)}))}async synthesize(t,e){const s=this.agent.voice?.speaker;return A(await this.ai.run(this.ttsModel,{text:t,...s===void 0?{}:{speaker:s}},e===void 0?void 0:{signal:e}))}async handleControl(t,e,s){let n;try{n=JSON.parse(s)}catch{return}if(n.type==="interrupt"){this.controllers.get(e.connectionId)?.abort();return}if(this.controllers.has(e.connectionId)){this.send(t,{message:"a turn is already in progress — send an interrupt before the next utterance",type:"error"});return}if(n.type==="commit"){const i=this.drainAudio(e.connectionId);await this.runTurn(t,e,{pcm:i});return}await this.runTurn(t,e,{text:n.text})}bufferAudio(t,e,s){const n=(this.bufferedBytes.get(t)??0)+e.byteLength;if(n>z){this.audioBuffers.delete(t),this.bufferedBytes.delete(t),this.send(s,{message:"utterance exceeded the maximum buffer — send a commit sooner",type:"error"});return}const i=this.audioBuffers.get(t)??[];i.push(e),this.audioBuffers.set(t,i),this.bufferedBytes.set(t,n)}drainAudio(t){const e=this.audioBuffers.get(t)??[];this.audioBuffers.delete(t),this.bufferedBytes.delete(t);const s=e.reduce((r,c)=>r+c.byteLength,0),n=new Uint8Array(s);let i=0;for(const r of e)n.set(r,i),i+=r.byteLength;return n}async runTurn(t,e,s){const n=new AbortController;this.controllers.set(e.connectionId,n);try{await k({agent:this.agent,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:n.signal,streamGenerate:this.streamGenerate,synthesize:async(i,r)=>this.synthesizeWithSignal(i,r),threadKey:e.threadKey,transcribe:async i=>this.transcribe(i),turn:e.turn,waitForDrain:async()=>this.waitForSocketDrain(t),...e.userId===void 0?{}:{owner:e.userId},...s.pcm===void 0?{}:{pcm:s.pcm},...s.text===void 0?{}:{text:s.text}})}finally{this.controllers.get(e.connectionId)===n&&this.controllers.delete(e.connectionId),t.serializeAttachment?.({...e,turn:e.turn+1})}}async speakGreeting(t,e,s,n,i,r){const c=this.resolveRun(n,i),a=new AbortController,d=()=>a.signal.aborted;this.controllers.set(e,a);try{await c(p(this.paths.ensureThread),{agent:this.exportName,key:s,...this.agent.initialState===void 0?{}:{initialState:this.agent.initialState},...n===void 0?{}:{owner:n}});for await(const o of I(await this.synthesizeWithSignal(r,a.signal))){if(d()||(await this.waitForSocketDrain(t),d()))break;this.sendAudio(t,o)}d()||(await c(p(this.paths.appendMessage),{content:r,messageKey:"voice:greeting:assistant",role:"assistant",threadKey:s}),this.send(t,{text:r,type:"assistant_done"}))}catch(o){this.send(t,{message:o instanceof Error?o.message:String(o),type:"error"})}finally{this.controllers.get(e)===a&&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))}isSocketExpired(t){return u(t.expiresAt)}dropExpiredSocket(t){l(t)}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 s=0;for(;typeof e.bufferedAmount=="number"&&e.bufferedAmount>F&&s<N;)await new Promise(n=>{setTimeout(n,f)}),s+=f}}export{L as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as f,d as u,s as l,c as g,a as I,r as o,b as m}from"./common-Dck97z3Y.mjs";const b=(i,r,s)=>{const a=globalThis.console;i==="error"?a.error(r,s):i==="warn"?a.warn(r,s):a.info(r,s)},x=(i={})=>{const{functionId:r,logger:s=b,recordInputs:a=!1,recordOutputs:c=!1}=i,p=r===void 0?"":`[${r}] `,t=(e,n,d)=>{s(e,`${p}${n}`,d)};return{onAbort:e=>{t("warn","agent operation aborted",{callId:o(e,"callId"),reason:o(e,"reason")})},onEnd:e=>{t("info","agent operation completed",{callId:o(e,"callId"),finishReason:o(e,"finishReason"),operationId:o(e,"operationId"),usage:l(o(e,"usage"))})},onError:e=>{t("error","agent operation errored",{error:u(e)})},onLanguageModelCallEnd:e=>{const n={callId:o(e,"callId"),finishReason:o(e,"finishReason"),modelId:o(e,"modelId"),provider:o(e,"provider"),usage:l(o(e,"usage"))};c&&(n.text=g(o(e,"content"))),t("info","language model call ended",n)},onStart:e=>{t("info","agent operation started",{callId:o(e,"callId"),modelId:o(e,"modelId"),operationId:o(e,"operationId"),provider:o(e,"provider")})},onStepEnd:e=>{t("info","agent step ended",{finishReason:o(e,"finishReason"),stepNumber:o(e,"stepNumber"),usage:l(o(e,"usage"))})},onStepStart:e=>{t("info","agent step started",{stepNumber:o(e,"stepNumber")})},onToolExecutionEnd:e=>{const n=I(e),d={success:n.success,tool:n.name,toolExecutionMs:n.toolExecutionMs};n.success||(d.error=u(n.error)),c&&n.success&&(d.output=n.output),t(n.success?"info":"warn","tool execution ended",d)},onToolExecutionStart:e=>{const n={tool:m(e)};a&&(n.input=f(e)),t("info","tool execution started",n)}}};export{x as consoleTelemetry};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{createAi as T}from"@lunora/ai";import{LunoraError as w}from"@lunora/errors";import{jsonSchema as x,generateText as d,streamText as k,Output as g,tool as j}from"ai";const y=t=>{if(!t)return;const e={};return t.inputTokens!==void 0&&(e.inputTokens=t.inputTokens),t.outputTokens!==void 0&&(e.outputTokens=t.outputTokens),t.totalTokens!==void 0&&(e.totalTokens=t.totalTokens),Object.keys(e).length>0?e:void 0},f=t=>t.map(e=>({id:e.toolCallId,input:e.input,name:e.toolName})),m=(t,e)=>{if(typeof t=="function")return t(e);if(typeof t=="string"){const o=e.AI;if(!o)throw new w("INTERNAL",`@lunora/agent: the agent model "${t}" is a Workers AI id but there is no \`AI\` binding on the workflow env — declare the ai binding in wrangler.jsonc`);return T({binding:o,env:e}).model(t)}return t},v=(t,e)=>{const o=m(t.model,e),n={};for(const[i,a]of Object.entries(t.tools??{}))n[i]=j({description:a.description,inputSchema:a.inputSchema});const s=t.output===void 0?void 0:g.object({schema:t.output}),r={...t.temperature===void 0?{}:{temperature:t.temperature},...t.maxOutputTokens===void 0?{}:{maxOutputTokens:t.maxOutputTokens},...t.telemetry===void 0?{}:{telemetry:t.telemetry},...t.repairToolCall===void 0?{}:{experimental_repairToolCall:t.repairToolCall}};return{defaultModel:o,output:s,staticSettings:r,tools:n}},b=(t,{activeTools:e,messages:o,model:n,signal:s,toolChoice:r})=>{const{defaultModel:i,output:a,staticSettings:h,tools:l}=t,c=e===void 0?l:Object.fromEntries(Object.entries(l).filter(([p])=>e.includes(p)));return{messages:o,model:n??i,...h,...Object.keys(c).length>0?{tools:c}:{},...r===void 0?{}:{toolChoice:r},...a===void 0?{}:{output:a},...s===void 0?{}:{abortSignal:s}}},N=(t,e)=>{const o=v(t,e);return async n=>{const s=await d(b(o,n)),r=y(s.usage);return{text:s.text,toolCalls:f(s.toolCalls),...r===void 0?{}:{usage:r},...o.output===void 0?{}:{output:s.output}}}},$=(t,e)=>{const o=v(t,e);return async(n,s)=>{const r=k(b(o,n));let i="";try{for await(const u of r.textStream)i+=u,s(u)}catch(u){if(n.signal?.aborted)return{text:i,toolCalls:[]};throw u}const[a,h,l,c]=await Promise.all([r.text,r.toolCalls,r.usage,o.output===void 0?Promise.resolve(void 0):r.output]),p=y(l);return{text:a,toolCalls:f(h),...p===void 0?{}:{usage:p},...o.output===void 0?{}:{output:c}}}},C=x({additionalProperties:!1,properties:{entities:{description:"The distinct entities (people, orgs, places, things, concepts) named in the exchange.",items:{additionalProperties:!1,properties:{name:{description:"The entity's canonical name.",type:"string"},type:{description:"An optional coarse type, e.g. person, org, place, product.",type:"string"}},required:["name"],type:"object"},type:"array"},relations:{description:"The directed relationships between the entities, as (src)-[label]->(dst) triples.",items:{additionalProperties:!1,properties:{confidence:{description:"Confidence in the relation, 0..1.",type:"number"},dst:{description:"The destination entity name (must appear in `entities`).",type:"string"},label:{description:"The relationship, a short snake_case verb phrase, e.g. works_at.",type:"string"},src:{description:"The source entity name (must appear in `entities`).",type:"string"}},required:["src","dst","label"],type:"object"},type:"array"}},required:["entities","relations"],type:"object"}),O=(t,e)=>["Extract a knowledge graph of the durable facts stated in the following exchange.","Return the distinct entities and the directed relationships between them.","Only include facts actually stated — do not invent entities or relations. Prefer few, high-signal triples.","",`User: ${t}`,"",`Assistant: ${e}`].join(`
|
|
2
|
-
`),q=()=>async({assistantText:t,env:e,model:o,userInput:n})=>{const{output:s}=await d({model:m(o,e),output:g.object({schema:C}),prompt:O(n,t)});return s},A=(t,e)=>["Summarize the following exchange as ONE concise past-tense sentence for a long-term memory log.","Capture what the user wanted and what was done or decided — a durable fact worth recalling in a later conversation.","No preamble and no quotes: return only the sentence.","",`User: ${t}`,"",`Assistant: ${e}`].join(`
|
|
3
|
-
`),G=()=>async({assistantText:t,env:e,model:o,userInput:n})=>{const{text:s}=await d({model:m(o,e),prompt:A(n,t)});return{summary:s.trim()}},S="You are compacting an ongoing conversation. Summarize the messages so far into a concise brief that preserves decisions made, facts established, open questions, and current task state — everything the assistant needs to continue coherently. Write it as notes for the assistant, not a reply to the user. No preamble.",M=()=>async({env:t,messages:e,model:o})=>{const{text:n}=await d({messages:e,model:m(o,t),system:S});return n.trim()};export{N as createAgentGenerate,M as createCompact,G as createEpisodeExtract,q as createGraphExtract,$ as createStreamGenerate,m as resolveAgentModel};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{defineTable as f,initLunora as v}from"@lunora/server";import{v as e}from"@lunora/values";const A="agent",x=t=>({...t,visibility:"internal"}),S=t=>{const n={};for(const[a,r]of Object.entries(t))r!==void 0&&(n[a]=r);return n},O="entities",K="edges",N=`${A}_${O}`,g=`${A}_${K}`,E={[O]:f({createdAt:e.number(),firstMessageKey:e.optional(e.string()),name:e.string(),owner:e.string(),type:e.optional(e.string()),updatedAt:e.number(),weight:e.optional(e.number())}).index("byOwnerName",["owner","name"],{unique:!0}).index("byOwnerUpdatedAt",["owner","updatedAt"]).public(),[K]:f({createdAt:e.number(),dstName:e.string(),label:e.string(),messageKey:e.string(),owner:e.string(),srcName:e.string(),updatedAt:e.number(),weight:e.optional(e.number())}).index("byOwnerSrc",["owner","srcName"]).index("byOwnerDst",["owner","dstName"]).index("byTriple",["owner","srcName","label","dstName"],{unique:!0}).public()},q=64,C=2,$=4,I=8,j=32,L=500,M=/\s+/gu,T=/[^\p{L}\p{N}]+/u,b=t=>t.trim().replaceAll(M," ").toLowerCase(),_=t=>t.toLowerCase().split(T).filter(n=>n.length>=2),D=t=>({dstName:t.dstName,label:t.label,srcName:t.srcName,weight:t.weight??1}),U=(t,n)=>n.weight-t.weight||t.label.localeCompare(n.label)||t.srcName.localeCompare(n.srcName)||t.dstName.localeCompare(n.dstName),k=(t,n)=>n.some(a=>t.includes(a)||a.includes(t)),G=t=>t.map(n=>`- ${n.srcName} —[${n.label}]→ ${n.dstName}`).toSorted((n,a)=>n.localeCompare(a)).join(`
|
|
2
|
-
`),P=t=>`${t.srcName}\0${t.label}\0${t.dstName}`,z=(t,n,a,r)=>{const s=P(t);r.collectedKeys.has(s)||(r.collectedKeys.add(s),r.collected.push(t));const l=t.srcName===n?t.dstName:t.srcName;!r.seen.has(l)&&r.seen.size<a.maxNodes&&(r.seen.add(l),r.next.push(l))},B=async(t,n,a)=>{const r={collected:[],collectedKeys:new Set,next:[],seen:new Set(n)};let s=n.slice(0,a.maxNodes);for(let l=0;l<a.depth&&s.length>0;l+=1){r.next=[];for(const u of s){const o=(await t(u)).toSorted(U).slice(0,a.fanOut);for(const m of o)z(m,u,a,r)}s=r.next}return r.collected},{mutation:F,query:H}=v.dataModel().create(),J=()=>{const t=F.input({entities:e.array(e.object({name:e.string(),type:e.optional(e.string())})),messageKey:e.string(),owner:e.string(),relations:e.array(e.object({confidence:e.optional(e.number()),dst:e.string(),label:e.string(),src:e.string()}))}).mutation(async({args:a,ctx:r})=>{const s=Date.now(),l=async(c,i)=>{const d=b(c);if(d.length===0)return;const w=await r.db.query(N).withIndex("byOwnerName",p=>p.eq("owner",a.owner).eq("name",d)).first();return w?(i!==void 0&&w.type===void 0&&await r.db.patch(w._id,{type:i,updatedAt:s}),d):(await r.db.insert(N,{createdAt:s,name:d,owner:a.owner,updatedAt:s,weight:1,...S({firstMessageKey:a.messageKey,type:i})}),d)},u=async c=>{const i=b(c.src),d=b(c.dst),w=b(c.label);if(i.length===0||d.length===0||w.length===0||i===d)return!1;await l(i),await l(d);const p=c.confidence??1,y=await r.db.query(g).withIndex("byTriple",h=>h.eq("owner",a.owner).eq("srcName",i).eq("label",w).eq("dstName",d)).first();if(y){const h=y.weight??1;await r.db.patch(y._id,{updatedAt:s,weight:Math.max(h,p)})}else await r.db.insert(g,{createdAt:s,dstName:d,label:w,messageKey:a.messageKey,owner:a.owner,srcName:i,updatedAt:s,weight:p});return!0};let o=0;for(const c of a.entities.slice(0,q))await l(c.name,c.type)!==void 0&&(o+=1);let m=0;for(const c of a.relations.slice(0,q))await u(c)&&(m+=1);return{entities:o,relations:m}}),n=H.input({depth:e.optional(e.number()),fanOut:e.optional(e.number()),maxNodes:e.optional(e.number()),maxSeeds:e.optional(e.number()),owner:e.string(),query:e.string()}).query(async({args:a,ctx:r})=>{const s=_(a.query);if(s.length===0)return{context:""};const l=(await r.db.query(N).withIndex("byOwnerUpdatedAt",o=>o.eq("owner",a.owner)).order("desc").take(L)).filter(o=>k(o.name,s)).toSorted((o,m)=>(m.weight??1)-(o.weight??1)||o.name.localeCompare(m.name)).slice(0,a.maxSeeds??$).map(o=>o.name);if(l.length===0)return{context:""};const u=await B(async o=>{const[m,c]=await Promise.all([r.db.query(g).withIndex("byOwnerSrc",i=>i.eq("owner",a.owner).eq("srcName",o)).collect(),r.db.query(g).withIndex("byOwnerDst",i=>i.eq("owner",a.owner).eq("dstName",o)).collect()]);return[...m,...c].map(i=>D(i))},l,{depth:a.depth??C,fanOut:a.fanOut??I,maxNodes:a.maxNodes??j});return{context:G(u)}});return{agentGraphTraverse:x(n),agentGraphUpsert:x(t)}};export{x as i,J as j,A as o,b as p,E as q,S as s};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"@lunora/server";import"@lunora/values";import{j as m,q as t,p as e}from"./graph-component-B2YmC2eL.mjs";export{m as graphComponent,t as graphTables,e as normalizeEntityName};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{resolveAgentModel as q}from"./createAgentGenerate-D96dEdYw.mjs";import{i as L,c as T,t as J,n as Q}from"./memory-DNRyyp1b.mjs";import{buildModelMessages as G}from"./buildModelMessages-Dm2wVNQy.mjs";import{agentBindingName as V}from"../naming.mjs";import{toFunctionReference as g}from"./AGENT_MODULE-BXx-tSCe.mjs";const W=8,b=e=>e===void 0?"null":JSON.stringify(e),X=e=>e===void 0?[]:Array.isArray(e)?e:[e],Y=async(e,t)=>(await Promise.all(e.map(async a=>a({steps:t})))).some(Boolean),A=(e,t)=>e===void 0&&t===void 0?void 0:(e??0)+(t??0),Z=(e,t)=>{if(t===void 0)return e;if(e===void 0)return{...t};const a={},o=A(e.inputTokens,t.inputTokens),r=A(e.outputTokens,t.outputTokens),n=A(e.totalTokens,t.totalTokens);return o!==void 0&&(a.inputTokens=o),r!==void 0&&(a.outputTokens=r),n!==void 0&&(a.totalTokens=n),a},z=async(e,t,a,o,r)=>{const{needsApproval:n}=e;return n===void 0||n===!1?!1:n===!0?!0:a.do(o,async()=>n(t,r))},H=async(e,t)=>{const{instanceId:a,patchThread:o,persist:r,step:n}=e;await r({content:`Awaiting approval to run tool "${t.name}".`,messageKey:`${a}:approval:${t.id}`,role:"tool",status:"awaiting_approval",toolCallId:t.id,toolName:t.name}),await o({status:"awaiting_input"});const i=await n.waitForEvent(`approval:${t.id}`,{type:`agent-approval:${t.id}`});return await o({status:"running"}),{decision:i.payload.decision,...i.payload.note===void 0?{}:{note:i.payload.note}}},tt=async(e,t)=>{const{env:a,getState:o,instanceId:r,onTokenDelta:n,persist:i,run:l,setState:c,step:p,threadKey:s,tools:u}=e,d=`tool:${t.name}:${t.id}`,m=u[t.name],h=`${r}:tool:${t.id}`;if(!m){await i({content:`Error: unknown tool "${t.name}"`,messageKey:h,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name});return}const f=$=>{n?.({data:$,kind:"progress",threadKey:s,toolCallId:t.id})},K={env:a,getState:o,idempotencyKey:d,reportProgress:f,run:l,setState:c,threadKey:s,toolCallId:t.id},v={env:a,getState:o,idempotencyKey:d,reportProgress:f,run:l,threadKey:s,toolCallId:t.id},C=`tool:approval-gate:${t.id}`;let x;if(await z(m,t.input,p,C,v)){const{decision:$,note:I}=await H(e,t);if($==="reject"){const N=I===void 0?"":` Reason: ${I}`;await i({content:`Tool "${t.name}" was rejected by the user and not run.${N}`,messageKey:h,role:"tool",status:"rejected",stepName:d,toolCallId:t.id,toolName:t.name});return}x="approved"}const w=await p.do(d,()=>Promise.resolve(m.execute(t.input,K)));await i({content:typeof w=="string"?w:b(w),messageKey:h,role:"tool",stepName:d,...x===void 0?{}:{status:x},toolCallId:t.id,toolName:t.name})},et=(e,t,a)=>{if(!t)return e;let{messages:o}=e;return t.messages!==void 0&&(o=t.messages),t.system!==void 0&&(o=[{content:t.system,role:"system"},...o]),{activeTools:t.activeTools??e.activeTools,messages:o,model:t.model===void 0?e.model:q(t.model,a),toolChoice:t.toolChoice??e.toolChoice}},at=(e,t)=>{if(t===void 0||e.length<=t.maxMessages)return;const a=Math.max(1,t.keepRecent??Math.ceil(t.maxMessages/2));if(e.length<=a)return;let o=e.length-a;for(;o>0&&e[o]?.role==="tool";)o-=1;if(!(o<=0))return{older:e.slice(0,o),recent:e.slice(o)}},ot=async(e,t)=>{const{agent:a,compact:o,env:r}=e,n=at(t,a.compaction);if(n===void 0||o===void 0)return{history:t,summary:void 0};try{const i=await o({env:r,messages:G({history:n.older}),model:a.compaction?.model??a.model});return i.length>0?{history:n.recent,summary:i}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},st=async(e,t,a)=>{const{agent:o,env:r,generate:n,instructions:i,listMessages:l,memoryContext:c,onTokenDelta:p,run:s,step:u,streamGenerate:d,threadKey:m}=e;return u.do(`llm:turn:${String(t)}`,async()=>{const h=await s(l,{key:m}),{history:f,summary:K}=await ot(e,h);let v={activeTools:o.activeTools,messages:G({history:f,instructions:i,memoryContext:c,summary:K}),model:void 0,toolChoice:o.toolChoice};o.prepareStep&&(v=et(v,await o.prepareStep({messages:v.messages,stepNumber:t,steps:a}),r));const C={messages:v.messages,...v.activeTools===void 0?{}:{activeTools:v.activeTools},...v.model===void 0?{}:{model:v.model},...v.toolChoice===void 0?{}:{toolChoice:v.toolChoice}};return d&&p?d(C,x=>{p({text:x,threadKey:m,turn:t})}):n(C)})},E=async(e,t)=>{const{agent:a,step:o}=e;a.onStepFinish&&await o.do(`agent:step-finish:${String(t.turn)}`,async()=>(await a.onStepFinish?.(t),!0))},nt=e=>({text:e.text,toolCalls:e.toolCalls.map(t=>({input:t.input,toolCallId:t.id,toolName:t.name})),...e.usage===void 0?{}:{usage:e.usage}}),R=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},rt=e=>{const t={};return e?.depth!==void 0&&(t.depth=e.depth),e?.fanOut!==void 0&&(t.fanOut=e.fanOut),e?.maxNodes!==void 0&&(t.maxNodes=e.maxNodes),e?.maxSeeds!==void 0&&(t.maxSeeds=e.maxSeeds),t},it=async(e,t,a,o)=>{if(e.source===void 0)return;const r=g(e.source),{topK:n}=e,i=T("memory:retrieve",e.key),l=await a.do(i,async()=>o(r,{query:t,...n===void 0?{}:{topK:n}}));return R(l)},dt=async(e,t,a,o,r,n)=>{if(a===void 0)return;const i=T("memory:traverse",e.key),l=await r.do(i,async()=>n(o,{owner:a,query:t,...rt(e.graph)}));return R(l)},lt=async(e,t,a,o,r)=>{if(t===void 0)return;const n=T("memory:recall",e.key),i={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},l=await o.do(n,async()=>r(a,i));return R(l)},ct=async(e,t)=>e.kind==="episodic"?lt(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?dt(e,t.input,t.owner,t.graphTraverse,t.step,t.run):it(e,t.input,t.step,t.run),ut=e=>{let t=!1;return e.filter(a=>a.kind!=="episodic"?!0:t?!1:(t=!0,!0))},pt=async(e,t,a,o,r,n)=>{const i=ut(Q(e));if(i.length===0)return;const l=g(o.graphTraverse),c=g(o.episodeRecall),p=[];for(const s of i){const u=await ct(s,{episodeRecall:c,graphTraverse:l,input:t,owner:a,run:n,step:r});u!==void 0&&p.push(u)}return p.length>0?p.join(`
|
|
2
|
-
|
|
3
|
-
`):void 0},mt=async e=>{const{agent:t,env:a,extractGraph:o,finalText:r,input:n,instanceId:i,owner:l,paths:c,run:p,step:s}=e;if(o===void 0||l===void 0||r===void 0||r.length===0)return;const u=L(t);if(u!==void 0)try{const d={assistantText:r,env:a,model:u.graph?.extractionModel??t.model,userInput:n},m=await s.do(T("memory:extract",u.key),async()=>o(d));await p(g(c.graphUpsert),{...m,messageKey:`${i}:${T("extract",u.key)}`,owner:l})}catch{}},yt=async e=>{const{agent:t,env:a,extractEpisode:o,finalText:r,input:n,instanceId:i,owner:l,paths:c,run:p,step:s,threadKey:u}=e;if(o===void 0||l===void 0||r===void 0||r.length===0)return;const d=J(t);if(d!==void 0)try{const m={assistantText:r,env:a,model:d.episodic?.extractionModel??t.model,userInput:n},{summary:h}=await s.do(T("memory:episode",d.key),async()=>o(m));await p(g(c.episodeUpsert),{messageKey:`${i}:${T("episode",d.key)}`,owner:l,summary:h,threadKey:u})}catch{}},vt=async(e,t,a)=>{const o=e[V(t)];if(!(!o||typeof o.get!="function"))try{await(await o.get(a)).terminate()}catch{}},gt=async(e,t,a,o,r)=>{const{instanceId:n,persist:i}=e,l=a.usage===void 0?{}:{usage:a.usage};if(a.toolCalls.length===0){const c=a.output!==void 0&&a.text.length===0?b(a.output):a.text;return await i({content:c,messageKey:`${n}:assistant:${String(t)}`,role:"assistant"}),await E(e,{text:a.text,toolCalls:[],turn:t,...l}),{final:{stopped:"final",text:a.text,turns:t+1,...a.output===void 0?{}:{output:a.output}}}}await i({content:a.text,messageKey:`${n}:assistant:${String(t)}`,role:"assistant",toolCalls:a.toolCalls});for(const c of a.toolCalls)await tt(e,c);if(await E(e,{text:a.text,toolCalls:a.toolCalls,turn:t,...l}),o.push(nt(a)),r.length>0&&await Y(r,o))return"stopCondition"},ht=async(e,t,a,o)=>{const r=[];let n,i=!1,l=0;for(let c=0;c<t;c+=1){const p=await st(e,c,r);o.value=Z(o.value,p.usage),l=c+1;const s=await gt(e,c,p,r,a);if(s==="stopCondition"){i=!0;break}if(s!==void 0){n=s.final;break}}return{final:n,stoppedByCondition:i,turnsRun:l}},kt=async e=>{const{agent:t,compact:a,env:o,exportName:r,extractEpisode:n,extractGraph:i,generate:l,instanceId:c,onTokenDelta:p,params:s,paths:u,run:d,step:m,streamGenerate:h}=e,f=t.maxTurns??W,K=X(t.stopWhen),v=g(u.appendMessage),C=g(u.ensureThread),x=g(u.listMessages),w=g(u.patchThread),$=g(u.setState),I=g(u.state),N=async y=>{await d(v,{threadKey:s.threadKey,...y})},F=async y=>{await d(w,{key:s.threadKey,...y})},j=async()=>await d(I,{key:s.threadKey}),B=async y=>{await d($,{key:s.threadKey,state:y})},M=await d(C,{agent:r,instanceId:c,key:s.threadKey,...t.initialState===void 0?{}:{initialState:t.initialState},...t.onConcurrentRun===void 0?{}:{onConcurrentRun:t.onConcurrentRun},...s.owner===void 0?{}:{owner:s.owner},...s.title===void 0?{}:{title:s.title}});M?.replaced&&M.priorInstanceId!==void 0&&await vt(o,r,M.priorInstanceId),await N({content:s.input,messageKey:`${c}:user`,role:"user"});const D=await pt(t,s.input,s.owner,u,m,d),O=typeof t.instructions=="function"?t.instructions({env:o,input:s.input,threadKey:s.threadKey}):t.instructions,P={agent:t,compact:a,env:o,generate:l,getState:j,instanceId:c,instructions:O,listMessages:x,memoryContext:D,onTokenDelta:p,patchThread:F,persist:N,run:d,setState:B,step:m,streamGenerate:h,threadKey:s.threadKey,tools:t.tools??{}},S={value:void 0};try{const{final:y,stoppedByCondition:U,turnsRun:_}=await ht(P,f,K,S),k=S.value===void 0?{}:{usage:S.value};return await mt({agent:t,env:o,extractGraph:i,finalText:y?.text,input:s.input,instanceId:c,owner:s.owner,paths:u,run:d,step:m}),await yt({agent:t,env:o,extractEpisode:n,finalText:y?.text,input:s.input,instanceId:c,owner:s.owner,paths:u,run:d,step:m,threadKey:s.threadKey}),y?(await d(w,{key:s.threadKey,status:"idle",...k}),{...y,...k}):U?(await d(w,{key:s.threadKey,status:"idle",...k}),{stopped:"stopCondition",turns:_,...k}):(await d(w,{error:`agent stopped: maxTurns (${String(f)}) reached`,key:s.threadKey,status:"error",...k}),{stopped:"maxTurns",turns:f,...k})}catch(y){throw await d(w,{error:y instanceof Error?y.message:String(y),key:s.threadKey,status:"error",...S.value===void 0?{}:{usage:S.value}}),y}};export{kt as runAgentLoop,at as splitForCompaction};
|