@lunora/agent 1.0.0-alpha.5 → 1.0.0-alpha.50
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/channels.mjs +1 -181
- package/dist/component.mjs +2 -418
- package/dist/inbound.d.mts +1 -1
- package/dist/inbound.d.ts +1 -1
- package/dist/inbound.mjs +1 -32
- package/dist/index.d.mts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.mjs +1 -18
- package/dist/naming.mjs +1 -8
- package/dist/packem_shared/AGENT_MODULE-BXx-tSCe.mjs +1 -0
- package/dist/packem_shared/VoiceSessionDO-DNXzVGVf.mjs +1 -0
- package/dist/packem_shared/adaptMcpResult-18G7zpFo.mjs +2 -0
- package/dist/packem_shared/agentAsTool-gH17BQ8M.mjs +1 -0
- package/dist/packem_shared/base64-B_qZ_Tyh.mjs +1 -0
- package/dist/packem_shared/braintrustTelemetry-CnOI5WAw.mjs +1 -0
- package/dist/packem_shared/branch-marker-DELZqEOQ.mjs +1 -0
- package/dist/packem_shared/buildModelMessages-Dm2wVNQy.mjs +5 -0
- package/dist/packem_shared/codeTool-DYJVy-bH.mjs +1 -0
- package/dist/packem_shared/collectAgenticMemoryTools-DBcP8dUa.mjs +1 -0
- package/dist/packem_shared/combineTelemetry-oLCV_EPV.mjs +1 -0
- package/dist/packem_shared/common-Dck97z3Y.mjs +1 -0
- package/dist/packem_shared/compileAgentWorkflow-BW627hb5.mjs +1 -0
- package/dist/packem_shared/component-shared-BVjAbtUu.mjs +1 -0
- package/dist/packem_shared/consoleTelemetry-C_85CaZ7.mjs +1 -0
- package/dist/packem_shared/createAgentContext-D1cXHQO2.mjs +1 -0
- package/dist/packem_shared/createAgentGenerate-BS1vasdV.mjs +3 -0
- package/dist/packem_shared/createDispatchRunner-EYOnoElU-CpVpdTXn.mjs +1 -0
- package/dist/packem_shared/defineAgent-D0VIzlhu.mjs +3 -0
- package/dist/packem_shared/defineSkill-DfJxCwfZ.mjs +1 -0
- package/dist/packem_shared/functionTool-CWHhkYqd.mjs +1 -0
- package/dist/packem_shared/memory-DNRyyp1b.mjs +1 -0
- package/dist/packem_shared/normalizeEntityName-DrEDaSSz.mjs +2 -0
- package/dist/packem_shared/otlpTelemetry-DcW9mOLV.mjs +1 -0
- package/dist/packem_shared/runAgentLoop-nuk5NsAn.mjs +3 -0
- package/dist/packem_shared/runVoiceTurn-DhN9Asnn.mjs +1 -0
- package/dist/packem_shared/sandboxComponent-CKDGyK4Y.mjs +1 -0
- package/dist/packem_shared/sentryTelemetry-Dr2aPuvl.mjs +1 -0
- package/dist/packem_shared/{types.d-boAM2Yi1.d.mts → types.d-PMYeuDE7.d.mts} +40 -17
- package/dist/packem_shared/{types.d-boAM2Yi1.d.ts → types.d-PMYeuDE7.d.ts} +40 -17
- package/dist/packem_shared/voice-turn-DzRKyf-x.mjs +1 -0
- package/dist/sandbox.d.mts +2 -2
- package/dist/sandbox.d.ts +2 -2
- package/dist/sandbox.mjs +1 -113
- 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.d.mts +82 -1
- package/dist/telemetry/index.d.ts +82 -1
- package/dist/telemetry/index.mjs +1 -4
- package/package.json +13 -8
- package/dist/packem_shared/AGENT_MODULE-Dnt_-AAT.mjs +0 -24
- package/dist/packem_shared/VoiceSessionDO-DLoXsHGF.mjs +0 -297
- package/dist/packem_shared/adaptMcpResult-wtNMvLoP.mjs +0 -65
- package/dist/packem_shared/agentAsTool-CUHlWsmt.mjs +0 -98
- package/dist/packem_shared/base64-BVwtgRJV.mjs +0 -18
- package/dist/packem_shared/braintrustTelemetry-wuGDErob.mjs +0 -47
- package/dist/packem_shared/buildModelMessages-BWFigaoo.mjs +0 -69
- package/dist/packem_shared/codeTool-CjgJOC9t.mjs +0 -122
- package/dist/packem_shared/collectAgenticMemoryTools-QrzpV-WX.mjs +0 -97
- package/dist/packem_shared/combineTelemetry-DCyaaWAI.mjs +0 -43
- package/dist/packem_shared/common-DAeFCot5.mjs +0 -61
- package/dist/packem_shared/compileAgentWorkflow-DX90058f.mjs +0 -55
- package/dist/packem_shared/consoleTelemetry-z2MiP1jt.mjs +0 -93
- package/dist/packem_shared/createAgentContext-4xJGXNR4.mjs +0 -50
- package/dist/packem_shared/createAgentGenerate-BQv9YJ01.mjs +0 -192
- package/dist/packem_shared/createDispatchRunner-DSbp_dph-ZHTtxy3f.mjs +0 -69
- package/dist/packem_shared/defineAgent-DAwAZC9P.mjs +0 -148
- package/dist/packem_shared/defineSkill-Ctf_S-rz.mjs +0 -22
- package/dist/packem_shared/functionTool-D6lCa2jB.mjs +0 -20
- package/dist/packem_shared/graph-component-Bbaxxymp.mjs +0 -217
- package/dist/packem_shared/memory-D4FPcBsX.mjs +0 -12
- package/dist/packem_shared/normalizeEntityName-BouctxLC.mjs +0 -3
- package/dist/packem_shared/runAgentLoop-B3Q2o-Uz.mjs +0 -493
- package/dist/packem_shared/runVoiceTurn-LnqLvCRR.mjs +0 -211
- package/dist/packem_shared/sandboxComponent-DR3pTwBL.mjs +0 -194
- package/dist/packem_shared/sentryTelemetry-CgqFJyLO.mjs +0 -36
package/dist/inbound.mjs
CHANGED
|
@@ -1,32 +1 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { createInboundEmailHandler, parseInboundEmail } from '@lunora/mail/inbound';
|
|
3
|
-
|
|
4
|
-
const dispatchAgentEmail = (targets) => {
|
|
5
|
-
const handler = createInboundEmailHandler({
|
|
6
|
-
dispatch: async (email, context) => {
|
|
7
|
-
for (const target of targets) {
|
|
8
|
-
const mapper = target.agent.onEmail;
|
|
9
|
-
if (!mapper) {
|
|
10
|
-
continue;
|
|
11
|
-
}
|
|
12
|
-
const run = await mapper(email);
|
|
13
|
-
if (run === null || run === void 0) {
|
|
14
|
-
continue;
|
|
15
|
-
}
|
|
16
|
-
const binding = context.env[target.binding];
|
|
17
|
-
if (!binding || typeof binding.create !== "function") {
|
|
18
|
-
throw new LunoraError(
|
|
19
|
-
"INTERNAL",
|
|
20
|
-
`@lunora/agent: no Workflow binding "${target.binding}" on env for an inbound agent — run codegen/dev so wrangler.jsonc declares it`
|
|
21
|
-
);
|
|
22
|
-
}
|
|
23
|
-
await binding.create({ params: run });
|
|
24
|
-
return;
|
|
25
|
-
}
|
|
26
|
-
},
|
|
27
|
-
parse: parseInboundEmail
|
|
28
|
-
});
|
|
29
|
-
return async (message, env, context) => handler(message, env, context);
|
|
30
|
-
};
|
|
31
|
-
|
|
32
|
-
export { dispatchAgentEmail };
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import{createInboundEmailHandler as u,parseInboundEmail as d}from"@lunora/mail/inbound";import{h as f,B as l}from"./packem_shared/branch-marker-DELZqEOQ.mjs";const E=c=>{const s=u({dispatch:async(o,a)=>{for(const n of c){const t=n.agent.onEmail;if(!t)continue;const r=await t(o);if(r==null)continue;const e=a.env[n.binding];if(!e||typeof e.create!="function")throw new i("INTERNAL",`@lunora/agent: no Workflow binding "${n.binding}" on env for an inbound agent — run codegen/dev so wrangler.jsonc declares it`);if(f(r))throw new i("BAD_REQUEST",`@lunora/agent: inbound run params ${l}`);await e.create({params:r});return}},parse:d});return async(o,a,n)=>s(o,a,n)};export{E as dispatchAgentEmail};
|
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";
|
|
@@ -183,7 +183,7 @@ declare const agentAsTool: (options: AgentAsToolOptions) => AgentToolDefinition<
|
|
|
183
183
|
interface ToolScriptStep {
|
|
184
184
|
/** A stable name later steps reference the output by. */
|
|
185
185
|
id: string;
|
|
186
|
-
/** The tool's input; values may embed `{ "$from": "
|
|
186
|
+
/** The tool's input; values may embed `{ "$from": "<stepId>", "$path": "a.b" }` refs. */
|
|
187
187
|
input?: Record<string, unknown>;
|
|
188
188
|
/** The tool to call — one of the tools handed to {@link codeTool}. */
|
|
189
189
|
tool: string;
|
|
@@ -808,15 +808,15 @@ declare class VoiceSessionDO {
|
|
|
808
808
|
}
|
|
809
809
|
/**
|
|
810
810
|
* Compile a `defineAgent` definition into the workflow the generated
|
|
811
|
-
*
|
|
811
|
+
* `<Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
|
|
812
812
|
*
|
|
813
813
|
* ```ts
|
|
814
814
|
* import LunoraWorkflow from "@lunora/workflow/do";
|
|
815
815
|
* import { compileAgentWorkflow } from "@lunora/agent";
|
|
816
816
|
* import { support } from "../agents.js";
|
|
817
817
|
*
|
|
818
|
-
* export class SupportAgentWorkflow extends LunoraWorkflow
|
|
819
|
-
* public constructor(ctx: ConstructorParameters
|
|
818
|
+
* export class SupportAgentWorkflow extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
|
|
819
|
+
* public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
|
|
820
820
|
* super(ctx, env, compileAgentWorkflow(support, "support"), "support");
|
|
821
821
|
* }
|
|
822
822
|
* }
|
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";
|
|
@@ -183,7 +183,7 @@ declare const agentAsTool: (options: AgentAsToolOptions) => AgentToolDefinition<
|
|
|
183
183
|
interface ToolScriptStep {
|
|
184
184
|
/** A stable name later steps reference the output by. */
|
|
185
185
|
id: string;
|
|
186
|
-
/** The tool's input; values may embed `{ "$from": "
|
|
186
|
+
/** The tool's input; values may embed `{ "$from": "<stepId>", "$path": "a.b" }` refs. */
|
|
187
187
|
input?: Record<string, unknown>;
|
|
188
188
|
/** The tool to call — one of the tools handed to {@link codeTool}. */
|
|
189
189
|
tool: string;
|
|
@@ -808,15 +808,15 @@ declare class VoiceSessionDO {
|
|
|
808
808
|
}
|
|
809
809
|
/**
|
|
810
810
|
* Compile a `defineAgent` definition into the workflow the generated
|
|
811
|
-
*
|
|
811
|
+
* `<Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
|
|
812
812
|
*
|
|
813
813
|
* ```ts
|
|
814
814
|
* import LunoraWorkflow from "@lunora/workflow/do";
|
|
815
815
|
* import { compileAgentWorkflow } from "@lunora/agent";
|
|
816
816
|
* import { support } from "../agents.js";
|
|
817
817
|
*
|
|
818
|
-
* export class SupportAgentWorkflow extends LunoraWorkflow
|
|
819
|
-
* public constructor(ctx: ConstructorParameters
|
|
818
|
+
* export class SupportAgentWorkflow extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
|
|
819
|
+
* public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
|
|
820
820
|
* super(ctx, env, compileAgentWorkflow(support, "support"), "support");
|
|
821
821
|
* }
|
|
822
822
|
* }
|
package/dist/index.mjs
CHANGED
|
@@ -1,18 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export { collectAgenticMemoryTools, toSearchResults } from './packem_shared/collectAgenticMemoryTools-QrzpV-WX.mjs';
|
|
3
|
-
export { agentAsTool } from './packem_shared/agentAsTool-CUHlWsmt.mjs';
|
|
4
|
-
export { codeTool } from './packem_shared/codeTool-CjgJOC9t.mjs';
|
|
5
|
-
export { agentComponent, agentExtension } from './component.mjs';
|
|
6
|
-
export { default as createAgentContext } from './packem_shared/createAgentContext-4xJGXNR4.mjs';
|
|
7
|
-
export { defineAgent, defineAgentTool, isAgentDefinition } from './packem_shared/defineAgent-DAwAZC9P.mjs';
|
|
8
|
-
export { functionTool } from './packem_shared/functionTool-D6lCa2jB.mjs';
|
|
9
|
-
export { createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, resolveAgentModel } from './packem_shared/createAgentGenerate-BQv9YJ01.mjs';
|
|
10
|
-
export { adaptMcpResult, mcpTools } from './packem_shared/adaptMcpResult-wtNMvLoP.mjs';
|
|
11
|
-
export { buildModelMessages } from './packem_shared/buildModelMessages-BWFigaoo.mjs';
|
|
12
|
-
export { agentBindingName, agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from './naming.mjs';
|
|
13
|
-
export { AGENT_MODULE, DEFAULT_AGENT_FUNCTION_PATHS, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, toFunctionReference } from './packem_shared/AGENT_MODULE-Dnt_-AAT.mjs';
|
|
14
|
-
export { browserTool, containerTool, fsTool } from './sandbox.mjs';
|
|
15
|
-
export { defineSkill, isSkillDefinition } from './packem_shared/defineSkill-Ctf_S-rz.mjs';
|
|
16
|
-
export { default as VoiceSessionDO } from './packem_shared/VoiceSessionDO-DLoXsHGF.mjs';
|
|
17
|
-
export { runVoiceTurn } from './packem_shared/runVoiceTurn-LnqLvCRR.mjs';
|
|
18
|
-
export { default as compileAgentWorkflow } from './packem_shared/compileAgentWorkflow-DX90058f.mjs';
|
|
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};
|
package/dist/naming.mjs
CHANGED
|
@@ -1,8 +1 @@
|
|
|
1
|
-
const
|
|
2
|
-
const agentClassName = (exportName) => `${exportName.charAt(0).toUpperCase()}${exportName.slice(1)}AgentWorkflow`;
|
|
3
|
-
const agentBindingName = (exportName) => `AGENT_${exportName.replaceAll(CAMEL_BOUNDARY, "$1_$2").toUpperCase()}`;
|
|
4
|
-
const agentDefaultName = (exportName) => `agent-${exportName.replaceAll(CAMEL_BOUNDARY, "$1-$2").toLowerCase()}`;
|
|
5
|
-
const voiceClassName = (exportName) => `${exportName.charAt(0).toUpperCase()}${exportName.slice(1)}VoiceDO`;
|
|
6
|
-
const voiceBindingName = (exportName) => `VOICE_${exportName.replaceAll(CAMEL_BOUNDARY, "$1_$2").toUpperCase()}`;
|
|
7
|
-
|
|
8
|
-
export { agentBindingName, agentClassName, agentDefaultName, voiceBindingName, voiceClassName };
|
|
1
|
+
const a=/([a-z0-9])([A-Z])/gu,s=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}AgentWorkflow`,t=e=>`AGENT_${e.replaceAll(a,"$1_$2").toUpperCase()}`,l=e=>`agent-${e.replaceAll(a,"$1-$2").toLowerCase()}`,o=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}VoiceDO`,r=e=>`VOICE_${e.replaceAll(a,"$1_$2").toUpperCase()}`;export{t as agentBindingName,s as agentClassName,l as agentDefaultName,r as voiceBindingName,o as voiceClassName};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e="agents",t="sandbox",s=`${t}:invoke`,n={appendMessage:`${e}:agentAppendMessage`,ensureThread:`${e}:agentEnsureThread`,episodeRecall:`${e}:agentEpisodeRecall`,episodeUpsert:`${e}:agentEpisodeUpsert`,graphTraverse:`${e}:agentGraphTraverse`,graphUpsert:`${e}:agentGraphUpsert`,listMessages:`${e}:agentMessages`,patchThread:`${e}:agentPatchThread`,run:`${e}:agentRun`,setState:`${e}:agentSetState`,state:`${e}:agentState`},r=a=>typeof a=="string"?{__lunoraRef:a}:a;export{e as AGENT_MODULE,n as DEFAULT_AGENT_FUNCTION_PATHS,s as SANDBOX_INVOKE_PATH,t as SANDBOX_MODULE,r as toFunctionReference};
|
|
@@ -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};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import{jsonSchema as s}from"ai";const c=t=>{if(t.structuredContent!==void 0)return t.structuredContent;const e=(t.content??[]).filter(o=>o.type==="text"&&typeof o.text=="string").map(o=>o.text).join(`
|
|
2
|
+
`);return t.isError===!0?`MCP tool error: ${e.length>0?e:"unknown error"}`:e.length>0?e:t.content},l=(t,e)=>({description:e.description??`MCP tool "${e.name}".`,execute:async o=>c(await t.callTool({arguments:o,name:e.name})),inputSchema:s(e.inputSchema),isLunoraAgentTool:!0}),u=async t=>{if(t.command!==void 0)throw new i("INTERNAL","@lunora/agent: mcpTools `command` (stdio transport) cannot run in the Workers runtime — pass a `url` for an HTTP/SSE MCP server, or inject a connected `client`");if(t.url===void 0)throw new i("INTERNAL","@lunora/agent: mcpTools requires a `url` (an HTTP/SSE MCP server) or an injected `client`");const e=new URL(t.url),{Client:o}=await import("@modelcontextprotocol/sdk/client/index.js");let r;if(t.transport==="sse"){const{SSEClientTransport:a}=await import("@modelcontextprotocol/sdk/client/sse.js");r=new a(e)}else{const{StreamableHTTPClientTransport:a}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");r=new a(e)}const n=new o({name:t.name??"lunora-agent",version:t.version??"0.0.0"});return await n.connect(r),n},w=async t=>{const e=t.client??await u(t),{tools:o}=await e.listTools(),r={};for(const n of o)t.only!==void 0&&!t.only.includes(n.name)||(r[`${t.prefix??""}${n.name}`]=l(e,n));return r};export{c as adaptMcpResult,w as mcpTools};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as p}from"@lunora/errors";import{jsonSchema as T}from"ai";import{isDuplicateInstanceError as $}from"../channels.mjs";import{agentBindingName as N}from"../naming.mjs";import{toFunctionReference as b,DEFAULT_AGENT_FUNCTION_PATHS as E}from"./AGENT_MODULE-BXx-tSCe.mjs";const A=new Set(["complete","errored","terminated"]),I=120,S=500,L=e=>e!==null&&typeof e=="object"&&typeof e.status=="string"?e.status:"unknown",k=async e=>{await new Promise(t=>{setTimeout(t,e)})},C=async(e,t,n,u)=>{for(let a=0;a<t;a+=1){const i=L(await e.status());if(A.has(i))return i;await u(n)}return"timeout"},R=e=>{for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.role==="assistant"&&(n.toolCalls===void 0||n.toolCalls.length===0))return n.content}return""},j=e=>{if(typeof e.name!="string"||e.name.length===0)throw new p("INTERNAL","@lunora/agent: agent.asTool requires a `name` (the child agent's export name, selecting its AGENT_* binding)");if(typeof e.description!="string"||e.description.length===0)throw new p("INTERNAL","@lunora/agent: agent.asTool requires a non-empty `description` (the parent model decides from it)");const{name:t}=e,n=N(t),u=e.maxPolls??I,a=e.pollIntervalMs??S,i=e.wait??k,m=b(E.listMessages),f=async(w,r)=>{const o=r.env[n];if(!o||typeof o.create!="function"||typeof o.get!="function")throw new p("INTERNAL",`@lunora/agent: agent.asTool("${t}") found no Workflow binding "${n}" on env — declare the "${t}" agent so codegen wires its binding`);const d=`${r.threadKey}::sub::${t}::${r.toolCallId}`,g=`sub-${t}-${r.toolCallId}`,h={input:w.prompt,threadKey:d};let c;try{const l=await o.create({id:g,params:h});c=await o.get(l.id)}catch(l){if(!$(l))throw l;c=await o.get(g)}const s=await C(c,u,a,i);if(s==="errored"||s==="terminated")return`Sub-agent "${t}" ${s} before producing an answer.`;if(s==="timeout")return`Sub-agent "${t}" did not finish within the allotted time.`;const y=await r.run(m,{key:d});return R(y)};return{description:e.description,execute:f,inputSchema:T({properties:{prompt:{description:"The task or question to delegate to the sub-agent.",type:"string"}},required:["prompt"],type:"object"}),isLunoraAgentTool:!0}};export{j as agentAsTool};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o=e=>{let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)},l=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n+=1)r[n]=t.codePointAt(n)??0;return r},a=e=>{const t=e.replaceAll("-","+").replaceAll("_","/"),r=t+"=".repeat((4-t.length%4)%4);return l(r)};export{o as a,l as o,a as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as g,t as p,r as l}from"./common-Dck97z3Y.mjs";const d=(o,a)=>typeof o=="string"&&o.length>0?o:a,i=o=>{const{functionId:a,logger:n,recordInputs:u=!1,recordOutputs:c=!1}=o;return{executeLanguageModelCall:e=>n.traced(async t=>{u&&t.log({input:l(e,"messages"),model:l(e,"modelId")});const r=await e.execute();return c&&t.log({output:r}),r},{name:d(a,"language_model_call"),type:"llm"}),executeTool:e=>{const t=l(l(e,"toolCall"),"toolName");return n.traced(async r=>{u&&r.log({input:p(e),tool:t});const s=await e.execute();return c&&r.log({output:s}),s},{name:d(t,"execute_tool"),type:"tool"})},onError:e=>{n.traced(t=>{t.log({error:g(e)})},{name:"error",type:"error"})}}};export{i as braintrustTelemetry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r="__lunoraBranch",e=a=>typeof a=="object"&&a!==null&&Object.hasOwn(a,r),o=`may not contain the reserved workflow branch-marker key ("${r}")`;export{o as B,e as h};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
const n=t=>t.toolCalls===void 0||t.toolCalls.length===0?{content:t.content,role:"assistant"}:{content:[...t.content.length>0?[{text:t.content,type:"text"}]:[],...t.toolCalls.map(o=>({input:o.input,toolCallId:o.id,toolName:o.name,type:"tool-call"}))],role:"assistant"},s=t=>({content:[{output:{type:"text",value:t.content},toolCallId:t.toolCallId??"",toolName:t.toolName??"",type:"tool-result"}],role:"tool"}),l=t=>{const o=[];t.instructions!==void 0&&t.instructions.length>0&&o.push({content:t.instructions,role:"system"}),t.memoryContext!==void 0&&t.memoryContext.length>0&&o.push({content:`Relevant context retrieved for this conversation:
|
|
2
|
+
|
|
3
|
+
${t.memoryContext}`,role:"system"}),t.summary!==void 0&&t.summary.length>0&&o.push({content:`Summary of the earlier conversation:
|
|
4
|
+
|
|
5
|
+
${t.summary}`,role:"system"});for(const e of t.history)if(e.status!=="awaiting_approval")switch(e.role){case"assistant":{o.push(n(e));break}case"system":{o.push({content:e.content,role:"system"});break}case"tool":{o.push(s(e));break}case"user":{o.push({content:e.content,role:"user"});break}}return o};export{l as buildModelMessages};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as a}from"@lunora/errors";import{jsonSchema as h}from"ai";const $=16,f=4e3,A=e=>{if(e===void 0)return e;const o=typeof e=="string"?e:JSON.stringify(e);return o.length<=f?e:`${o.slice(0,f)}… [truncated]`},b=(e,o)=>{let t=e;for(const s of o.split(".")){if(t===null||typeof t!="object"||!Object.hasOwn(t,s))return;t=t[s]}return t},l=(e,o)=>{if(Array.isArray(e))return e.map(r=>l(r,o));if(e===null||typeof e!="object")return e;const t=e;if(typeof t.$from=="string"){const r=t.$from;if(!(r in o))throw new a("BAD_REQUEST",`@lunora/agent: code step references unknown result "${r}" (define it in an earlier step)`);return typeof t.$path=="string"?b(o[r],t.$path):o[r]}const s={};for(const[r,i]of Object.entries(t))s[r]=l(i,o);return s},v=async(e,o,t,s)=>{const r=Array.isArray(e.steps)?e.steps.slice(0,s):[],i={},p=[],c=new Set;for(const n of r){if(c.has(n.id))throw new a("BAD_REQUEST",`@lunora/agent: duplicate code step id "${n.id}" — each step id must be unique (later steps reference an output by id via $from)`);c.add(n.id)}for(const n of r){const d=o[n.tool];if(!d)throw new a("BAD_REQUEST",`@lunora/agent: code step calls unknown tool "${n.tool}" (available: ${Object.keys(o).join(", ")})`);const y=l(n.input??{},i),m={...t,idempotencyKey:`${t.idempotencyKey}:${n.id}`,toolCallId:`${t.toolCallId}:${n.id}`},u=await d.execute(y,m);i[n.id]=u,p.push({id:n.id,output:A(u)})}return{final:p.at(-1)?.output,results:p}},w=e=>`Compose MULTIPLE tool calls in one turn as a script, instead of one call per turn. Provide \`steps\`: an ordered array of \`{ id, tool, input }\`. A later step's \`input\` may reference an earlier step's output with \`{ "$from": "<stepId>", "$path": "optional.dot.path" }\`. Available tools: ${Object.entries(e).map(([o,t])=>`"${o}" — ${t.description}`).join("; ")}.`,g=h({properties:{steps:{description:"Ordered tool calls; a later input may reference an earlier output via { $from, $path }.",items:{additionalProperties:!1,properties:{id:{description:"A name later steps reference this output by.",type:"string"},input:{additionalProperties:!0,description:"The tool input (may embed $from refs).",type:"object"},tool:{description:"The tool to call.",type:"string"}},required:["id","tool"],type:"object"},type:"array"}},required:["steps"],type:"object"}),E=(e,o={})=>{const t=e;if(!t||typeof t!="object"||Object.keys(t).length===0)throw new a("INTERNAL","@lunora/agent: codeTool requires a non-empty map of tools to compose");for(const[r,i]of Object.entries(t))if(i.needsApproval!==void 0&&i.needsApproval!==!1)throw new a("INTERNAL",`@lunora/agent: codeTool cannot compose "${r}" — it has a \`needsApproval\` gate a code-mode script can't pause for. Expose it as a normal top-level tool, or gate the whole script via codeTool's \`needsApproval\`.`);const s=o.maxSteps??$;return{description:o.description??w(e),execute:(r,i)=>v(r,e,i,s),inputSchema:g,isLunoraAgentTool:!0,...o.needsApproval===void 0?{}:{needsApproval:o.needsApproval}}};export{E as codeTool,l as resolveReferences,v as runToolScript};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{jsonSchema as u}from"ai";import{toFunctionReference as d}from"./AGENT_MODULE-BXx-tSCe.mjs";const y=240,h=50,m=(t,i)=>t.length<=i?t:`${t.slice(0,i)}…`,l=t=>{if(!(t===void 0||!Number.isFinite(t)))return Math.min(h,Math.max(1,Math.trunc(t)))},f=(t,i)=>{const r=t??{},s=Array.isArray(r.chunks)?r.chunks:[],e=Array.isArray(r.sources)?r.sources:[];return{results:s.map(o=>({id:typeof o.id=="string"?o.id:"",score:typeof o.score=="number"?o.score:0,snippet:m(typeof o.text=="string"?o.text:"",i),sourceId:typeof o.sourceId=="string"?o.sourceId:""})),sources:e}},g=u({additionalProperties:!1,properties:{query:{description:"Natural-language search query.",type:"string"},topK:{description:"Maximum number of hits to return.",type:"number"}},required:["query"],type:"object"}),k=u({additionalProperties:!1,properties:{id:{description:"The `id` of a hit returned by the search tool.",type:"string"}},required:["id"],type:"object"}),x=(t,i,r)=>{const s=d(i),e=Math.max(1,t.snippetChars??y),o=t.topK;return{description:`Search long-term memory for passages relevant to a query. Returns ranked { id, sourceId, score, snippet } hits — call again with a refined query to dig deeper.${r===void 0?"":` Use \`${r}\` with a hit's \`id\` to fetch its full text.`}`,execute:async(n,a)=>{const c=l(n.topK)??o,p=await a.run(s,{query:n.query,...c===void 0?{}:{topK:c}});return f(p,e)},inputSchema:g,isLunoraAgentTool:!0}},q=t=>{const i=d(t);return{description:"Fetch the full text of a memory document by the `id` from a search hit.",execute:(r,s)=>s.run(i,{id:r.id}),inputSchema:k,isLunoraAgentTool:!0}},A=(t,i)=>{const r=[];t.memory&&r.push({key:"default",...t.memory});for(const e of i)e.knowledge&&r.push({key:e.name,...e.knowledge});const s={};for(const e of r){if(e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic"||e.source===void 0)continue;const o=e.key==="default"?"searchMemory":`search_${e.key}`,n=e.key==="default"?"readMemory":`read_${e.key}`,a=e.read!==void 0;s[o]=x(e,e.source,a?n:void 0),a&&(s[n]=q(e.read))}return s};export{A as collectAgenticMemoryTools,f as toSearchResults};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=e=>async n=>{await Promise.allSettled(e.map(async a=>a?.(n)))},r=e=>{const n=e.filter(a=>typeof a=="function");return a=>{let o=a.execute;for(const p of n.toReversed()){const l=o;o=()=>p({...a,execute:l})}return o()}},d=(...e)=>({executeLanguageModelCall:r(e.map(n=>n.executeLanguageModelCall)),executeTool:r(e.map(n=>n.executeTool)),onAbort:t(e.map(n=>n.onAbort)),onEmbedEnd:t(e.map(n=>n.onEmbedEnd)),onEmbedStart:t(e.map(n=>n.onEmbedStart)),onEnd:t(e.map(n=>n.onEnd)),onError:t(e.map(n=>n.onError)),onLanguageModelCallEnd:t(e.map(n=>n.onLanguageModelCallEnd)),onLanguageModelCallStart:t(e.map(n=>n.onLanguageModelCallStart)),onObjectStepEnd:t(e.map(n=>n.onObjectStepEnd)),onObjectStepStart:t(e.map(n=>n.onObjectStepStart)),onRerankEnd:t(e.map(n=>n.onRerankEnd)),onRerankStart:t(e.map(n=>n.onRerankStart)),onStart:t(e.map(n=>n.onStart)),onStepEnd:t(e.map(n=>n.onStepEnd)),onStepFinish:t(e.map(n=>n.onStepFinish)),onStepStart:t(e.map(n=>n.onStepStart)),onToolExecutionEnd:t(e.map(n=>n.onToolExecutionEnd)),onToolExecutionStart:t(e.map(n=>n.onToolExecutionStart))});export{d as combineTelemetry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=(o,e)=>{if(!(o===null||typeof o!="object"))return o[e]},y=o=>{const e={};for(const r of["inputTokens","outputTokens","totalTokens"]){const s=t(o,r);typeof s=="number"&&(e[r]=s)}return Object.keys(e).length>0?e:void 0},m=o=>{const e=t(t(o,"providerMetadata"),"gateway"),r=t(t(o,"response"),"headers"),s=d=>{const g=t(r,"get"),f=typeof g=="function"?g.call(r,d):t(r,d);return typeof f=="string"&&f.length>0?f:void 0},n={},c=t(e,"cost");typeof c=="number"&&Number.isFinite(c)&&(n.cost=c);const i=t(e,"cached"),a=t(e,"cacheStatus"),l=typeof a=="string"?a:s("cf-aig-cache-status");typeof i=="boolean"?n.cached=i:typeof l=="string"&&(n.cached=l.toUpperCase()==="HIT");const u=t(e,"logId")??t(e,"log_id"),p=typeof u=="string"&&u.length>0?u:s("cf-aig-log-id");return typeof p=="string"&&p.length>0&&(n.logId=p),Object.keys(n).length>0?n:void 0},b=o=>{const e=t(o,"toolCall"),r=t(e,"toolName"),s=typeof r=="string"?r:void 0,n=t(o,"toolOutput"),c=t(n,"type"),i=t(o,"success"),a=typeof i=="boolean"?i:c!=="tool-error",l=t(o,"toolExecutionMs");return{error:a?void 0:t(n,"error")??t(o,"error"),name:s,output:a?t(n,"output"):void 0,success:a,toolExecutionMs:typeof l=="number"?l:void 0}},h=o=>{const e=t(t(o,"toolCall"),"toolName");return typeof e=="string"?e:void 0},v=o=>t(t(o,"toolCall"),"input"),T=o=>{if(!Array.isArray(o))return;let e="";for(const r of o)if(t(r,"type")==="text"){const s=t(r,"text");typeof s=="string"&&(e+=s)}return e.length>0?e:void 0},x=o=>o instanceof Error?{message:o.message,name:o.name}:o;export{b as a,h as b,T as c,x as d,m as e,t as r,y as s,v as t};
|
|
@@ -0,0 +1 @@
|
|
|
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 @@
|
|
|
1
|
+
import{A as f}from"./createDispatchRunner-EYOnoElU-CpVpdTXn.mjs";import{LunoraError as i}from"@lunora/errors";import{h as g,B as l}from"./branch-marker-DELZqEOQ.mjs";import{toFunctionReference as p,DEFAULT_AGENT_FUNCTION_PATHS as w}from"./AGENT_MODULE-BXx-tSCe.mjs";const h=(r,c,s)=>{const o={},u=p(w.patchThread),d=()=>s??f({env:r,label:"@lunora/agent"});for(const t of c){const a=()=>{const n=r[t.binding];if(!n||typeof n.create!="function"||typeof n.get!="function")throw new i("INTERNAL",`@lunora/agent: no Workflow binding "${t.binding}" on env for agent "${t.exportName}" — run codegen/dev so wrangler.jsonc declares it`);return n};o[t.exportName]={cancel:async n=>{await(await a().get(n)).terminate();try{await d()(u,{instanceId:n,status:"cancelled"})}catch{}},publicRun:t.publicRun===!0,run:async(n,e)=>{if(g(n))throw new i("BAD_REQUEST",`@lunora/agent: run input ${l}`);return{id:(await a().create({...e?.id===void 0?{}:{id:e.id},params:n})).id}},sendEvent:async(n,e)=>{await(await a().get(n)).sendEvent(e)},status:async n=>(await a().get(n)).status()}}return o};export{h as default};
|
|
@@ -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 @@
|
|
|
1
|
+
import{LunoraError as a}from"@lunora/errors";const g=t=>{let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e)},p=t=>g(t).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"");new TextDecoder;const y=new TextEncoder,f="=",w=t=>{for(let e=0;e<t.length;e+=1)if(t.charCodeAt(e)>255)return!1;return!0},$=t=>p(y.encode(JSON.stringify(t))),b=t=>!t.startsWith(f)&&w(t)?t:`${f}${p(y.encode(t))}`,m="/_lunora/scheduler/dispatch",I=t=>{let e=t.length;for(;e>0&&t[e-1]==="/";)e-=1;return t.slice(0,e)},A=(t,e,n)=>{try{const r=JSON.parse(n)?.error;if(typeof r=="object"&&r!==null&&typeof r.code=="string"){const{code:s,data:c,message:i}=r;return new a(s,typeof i=="string"?i:void 0,{data:c,status:e})}}catch{}return new a("INTERNAL",`${t}: function dispatch failed (${String(e)}): ${n}`,{status:e})},R=t=>{const{label:e}=t,n=globalThis.fetch,r=t.fetchImpl??(typeof n=="function"?n.bind(globalThis):void 0);return async(s,c,i={})=>{if(typeof r!="function")throw new TypeError(`${e}: no fetch implementation available — pass fetchImpl or run on a platform with global fetch`);const l=t.env.LUNORA_ORIGIN_URL;if(typeof l!="string"||l.length===0)throw new a("INTERNAL",`${e}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const u=t.env.LUNORA_ADMIN_TOKEN;if(typeof u!="string"||u.length===0)throw new a("INTERNAL",`${e}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const N=`${I(l)}${m}`,h={authorization:`Bearer ${u}`,"content-type":"application/json"};t.identity?.userId!==void 0&&(h["x-lunora-userid"]=b(t.identity.userId)),t.identity?.claims!==void 0&&(h["x-lunora-identity"]=$(t.identity.claims));const o=await r(N,{body:JSON.stringify({args:c??{},functionPath:s.__lunoraRef,shardKey:i.shardKey}),headers:h,method:"POST"});if(!o.ok)throw A(e,o.status,await o.text());const d=await o.text();if(d.length!==0)try{return JSON.parse(d)}catch{throw new a("INTERNAL",`${e}: function dispatch returned a non-JSON body (${String(o.status)}): ${d}`,{status:o.status})}}};export{R as A};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{LunoraError as s}from"@lunora/errors";import{collectAgenticMemoryTools as f}from"./collectAgenticMemoryTools-DBcP8dUa.mjs";import{agentAsTool as d}from"./agentAsTool-gH17BQ8M.mjs";import{r as m}from"./memory-DNRyyp1b.mjs";import{SKILL_NAME_PATTERN as h,RESERVED_SKILL_NAME as c}from"./defineSkill-DfJxCwfZ.mjs";const w=/^[a-zA-Z][\w-]*$/u,p=(e,r)=>{const o={...e.tools};for(const n of r)for(const[t,a]of Object.entries(n.tools??{})){if(Object.hasOwn(o,t))throw new s("INTERNAL",`@lunora/agent: skill "${n.name}" tool "${t}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);o[t]=a}return o},y=(e,r)=>{const o=[];for(const n of[e.instructions,...r.map(t=>t.instructions)])n&&o.push(n);return o.length<=1?o[0]:n=>o.map(t=>typeof t=="function"?t(n):t).filter(t=>t.length>0).join(`
|
|
2
|
+
|
|
3
|
+
`)},N=(e,r)=>{const o=[];e.memory&&m(e.memory)&&o.push({key:"default",...e.memory});for(const n of r)n.knowledge&&m(n.knowledge)&&o.push({key:n.name,...n.knowledge});return o},T=e=>{const r=new Set;for(const o of e){if(typeof o.name!="string"||!h.test(o.name))throw new s("INTERNAL",`@lunora/agent: skill \`name\` must be a valid identifier (letters, digits, _ or -, starting with a letter), got ${JSON.stringify(o.name)}`);if(o.name===c)throw new s("INTERNAL",`@lunora/agent: skill name "${c}" is reserved (it keys the agent's own \`memory\` source / the \`memory:retrieve\` step) — choose another name`);if(r.has(o.name))throw new s("INTERNAL",`@lunora/agent: skill name "${o.name}" is used by more than one skill — rename one (a skill name keys its knowledge memory source, which must be unique)`);r.add(o.name)}},A=(e,r)=>{if(e===void 0)return;const o=Object.keys(r).filter(n=>!e.includes(n));if(o.length>0)throw new s("INTERNAL",`@lunora/agent: \`activeTools\` omits the agentic-memory tool(s) ${o.map(n=>`"${n}"`).join(", ")} — the model could never call them; add them to \`activeTools\` (or drop \`activeTools\` to expose every tool)`)},k=(e,r)=>{const o=(n,t)=>{if(n&&n.kind!=="graph"&&n.kind!=="episodic"&&n.source===void 0)throw new s("INTERNAL",`@lunora/agent: ${t} requires a \`source\` action unless \`kind: "graph"\` or \`kind: "episodic"\``)};o(e.memory,"`memory`");for(const n of r)o(n.knowledge,`skill "${n.name}" \`knowledge\``)},$=e=>{const r=e.model;if(r==null||typeof r=="string"&&r.length===0)throw new s("INTERNAL","@lunora/agent: defineAgent requires a `model` (a Workers AI id, an AI SDK LanguageModel, or an (env) => model thunk)");if(e.maxTurns!==void 0&&(!Number.isInteger(e.maxTurns)||e.maxTurns<1))throw new s("INTERNAL","@lunora/agent: `maxTurns` must be a positive integer");const o=e.skills??[];T(o),k(e,o);const n=p(e,o),t=f(e,o);for(const[i,g]of Object.entries(t)){if(Object.hasOwn(n,i))throw new s("INTERNAL",`@lunora/agent: agentic-memory tool "${i}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);n[i]=g}const a=Object.keys(t).length>0;A(e.activeTools,t);for(const i of Object.keys(n))if(!w.test(i))throw new s("INTERNAL",`@lunora/agent: tool name "${i}" is not a valid identifier (letters, digits, _ or -, starting with a letter)`);const l=N(e,o),u=y(e,o);return{...e,asTool:d,isLunoraAgent:!0,...o.some(i=>!!i.instructions)?{instructions:u}:{},...l.length>0?{memorySources:l}:{},...o.length>0||a?{tools:n}:{}}},b=e=>typeof e=="object"&&e!==null&&e.isLunoraAgent===!0,j=e=>{if(typeof e.execute!="function")throw new s("INTERNAL","@lunora/agent: defineAgentTool requires an `execute` function");if(typeof e.description!="string"||e.description.length===0)throw new s("INTERNAL","@lunora/agent: defineAgentTool requires a non-empty `description` (the model decides from it)");return{...e,isLunoraAgentTool:!0}};export{$ as defineAgent,j as defineAgentTool,b as isAgentDefinition};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as t}from"@lunora/errors";const r=/^[a-zA-Z][\w-]*$/u,i="default",a=e=>{if(typeof e.name!="string"||!r.test(e.name))throw new t("INTERNAL",`@lunora/agent: defineSkill requires a \`name\` that is a valid identifier (letters, digits, _ or -, starting with a letter), got ${JSON.stringify(e.name)}`);if(e.name===i)throw new t("INTERNAL",`@lunora/agent: skill name "${i}" is reserved (it keys the agent's own \`memory\` source / the historic \`memory:retrieve\` step) — choose another name`);return{...e,isLunoraSkill:!0}},o=e=>typeof e=="object"&&e!==null&&e.isLunoraSkill===!0;export{i as RESERVED_SKILL_NAME,r as SKILL_NAME_PATTERN,a as defineSkill,o as isSkillDefinition};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as e}from"@lunora/errors";import{toFunctionReference as c}from"./AGENT_MODULE-BXx-tSCe.mjs";const s=(n,o)=>{if(typeof o.description!="string"||o.description.length===0)throw new e("INTERNAL","@lunora/agent: functionTool requires a non-empty `description` (the model decides from it)");if(o.inputSchema===void 0)throw new e("INTERNAL","@lunora/agent: functionTool requires an `inputSchema` (a zod schema or `jsonSchema(...)`)");const t=c(n);return{description:o.description,execute:(r,i)=>i.run(t,r),inputSchema:o.inputSchema,isLunoraAgentTool:!0}};export{s as functionTool};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o=i=>i.kind==="graph"||i.kind==="episodic"||i.mode!=="agentic",m=i=>i.memorySources?i.memorySources:i.memory&&o(i.memory)?[{key:"default",...i.memory}]:[],r=i=>m(i).find(d=>d.kind==="graph"),n=i=>m(i).find(d=>d.kind==="episodic"),e=(i,d)=>d==="default"?i:`${i}:${d}`;export{e as c,r as i,m as n,o as r,n as t};
|
|
@@ -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 @@
|
|
|
1
|
+
import{s as U,r as d,e as V,c as j,t as A,b as z}from"./common-Dck97z3Y.mjs";const I=e=>`${String(Math.round(e))}000000`,w=e=>{const t=new Uint8Array(e);crypto.getRandomValues(t);let o="";for(const n of t)o+=n.toString(16).padStart(2,"0");return o},x=(e,t)=>typeof t=="boolean"?{key:e,value:{boolValue:t}}:typeof t=="number"?Number.isFinite(t)?Number.isSafeInteger(t)?{key:e,value:{intValue:String(t)}}:{key:e,value:{doubleValue:t}}:{key:e,value:{stringValue:String(t)}}:{key:e,value:{stringValue:t}},C=(e,t,o)=>{const n={},c=new Map,m=(u,g)=>{const h=u.toLowerCase(),b=c.get(h);b===void 0?(c.set(h,u),n[u]=g):n[b]=g};for(const[u,g]of Object.entries(e))m(u,g);for(const[u,g]of Object.entries(t??{}))m(u,g);return o!==void 0&&o.length>0&&m("authorization",`Bearer ${o}`),n},D=e=>Array.isArray(e)?e:[e],M=(e,t)=>{const o={"service.name":e};for(const[n,c]of Object.entries({}))o[n]=c;return Object.entries(o).map(([n,c])=>x(n,c))},F=(e,t,o,n)=>({resourceSpans:[{resource:{attributes:M(o)},scopeSpans:[{scope:{name:t},spans:D(e)}]}]}),a=(e,t,o)=>{if(o!=null){if(typeof o=="boolean"||typeof o=="number"||typeof o=="string"){e.push(x(t,o));return}e.push(x(t,JSON.stringify(o)))}},T=(e,t)=>{(async()=>{let o;try{o=await e}catch(n){t(!1,n instanceof Error?n.message:String(n),void 0);return}t(!0,void 0,o)})().catch(()=>{})},L=e=>{const{conversationId:t,endpoint:o,headers:n,recordInputs:c=!1,recordOutputs:m=!1,token:u,traceId:g,waitUntil:h}=e,b=e.serviceName??"lunora";let v=o;for(;v.endsWith("/");)v=v.slice(0,-1);const N=`${v}/v1/traces`,$=C({"content-type":"application/json"},n,u),O=(r,f,l,p,y)=>{const _={attributes:y,endTimeUnixNano:I(Date.now()),kind:1,name:r,spanId:w(8),startTimeUnixNano:I(f),status:l?{code:1}:{code:2,message:p??""},traceId:g??w(16)};try{const i=fetch(N,{body:JSON.stringify(F(_,"@lunora/agent",b)),headers:$,method:"POST"}).catch(()=>{});h?.(i)}catch{}};return{executeLanguageModelCall:r=>{const f=Date.now(),l=d(r,"modelId"),p=r.execute();return T(p,(y,_,i)=>{const s=[];a(s,"gen_ai.operation.name","chat"),a(s,"gen_ai.request.model",l),a(s,"gen_ai.system",d(r,"provider")),a(s,"gen_ai.conversation.id",t);const k=U(d(i,"usage"));k&&(a(s,"gen_ai.usage.input_tokens",k.inputTokens),a(s,"gen_ai.usage.output_tokens",k.outputTokens),a(s,"gen_ai.usage.total_tokens",k.totalTokens));const S=V(i);S&&(a(s,"gen_ai.usage.cost",S.cost),a(s,"gen_ai.response.cached",S.cached),a(s,"cf.aig.log_id",S.logId)),c&&a(s,"gen_ai.prompt",d(r,"messages")),m&&a(s,"gen_ai.completion",j(d(i,"content"))),O(typeof l=="string"?`chat ${l}`:"language_model_call",f,y,_,s)}),p},executeTool:r=>{const f=Date.now(),l=z(r),p=r.execute();return T(p,(y,_)=>{const i=[];a(i,"gen_ai.operation.name","execute_tool"),a(i,"gen_ai.tool.name",l),a(i,"gen_ai.tool.call.id",d(r,"toolCallId")),c&&a(i,"gen_ai.tool.input",A(r)),O(typeof l=="string"?`execute_tool ${l}`:"execute_tool",f,y,_,i)}),p}}};export{L as otlpTelemetry};
|
|
@@ -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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./base64-B_qZ_Tyh.mjs";import{X as s,Y as i,e as p,Z as n,Q as m,P as d}from"./voice-turn-DzRKyf-x.mjs";import"./buildModelMessages-Dm2wVNQy.mjs";import"./AGENT_MODULE-BXx-tSCe.mjs";export{s as parseIdentity,i as pcmToWav,p as readSynthesisAudio,n as readTranscriptionText,m as runVoiceTurn,d as toByteIterable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{initLunora as h}from"@lunora/server";import{v as n}from"@lunora/values";import{a as d}from"./base64-B_qZ_Tyh.mjs";const{internalAction:w}=h.dataModel().create(),b=()=>globalThis.document?.documentElement?.outerHTML??"",u=1e6,m=20,y=new TextEncoder,x=async(o,t)=>{const e=t.url??"";switch(t.op){case"content":return o.content(e);case"pdf":return{data:d(await o.pdf(e)),encoding:"base64",mediaType:"application/pdf"};case"scrape":return o.scrape(e,b);case"screenshot":{const r=await o.screenshot(e,{...t.fullPage===void 0?{}:{fullPage:t.fullPage},...t.type===void 0?{}:{type:t.type}});return{data:d(r),encoding:"base64",mediaType:t.type==="jpeg"?"image/jpeg":"image/png"}}default:throw new c("INTERNAL",`@lunora/agent: sandbox browser op "${t.op}" is not supported`)}},T=async(o,t)=>{const e=o.any();if(t.op==="exec")return(await e.fetch("/exec",{body:JSON.stringify({args:t.args??[],command:t.command??""}),headers:{"content-type":"application/json"},method:"POST"})).text();if(t.op==="fetch")return(await e.fetch(t.path??"/",{...t.body===void 0?{}:{body:t.body},method:t.method??"GET"})).text();throw new c("INTERNAL",`@lunora/agent: sandbox container op "${t.op}" is not supported`)},g=o=>{let t=0,e=o.length;for(;t<e&&o[t]==="/";)t+=1;for(;e>t&&o[e-1]==="/";)e-=1;return o.slice(t,e)},E=(o,t)=>{const e=g(o),r=[];for(const a of t.split("/"))if(!(a===""||a===".")){if(a===".."){if(r.length===0)throw new c("BAD_REQUEST","@lunora/agent: fs path escapes the sandbox root");r.pop();continue}r.push(a)}const i=r.join("/");return e&&i?`${e}/${i}`:e||i},N=async(o,t,e)=>{const r=t.length>0?`${t}/`:"",i=e.length>0?e.length+1:0,a=[];let s;for(let l=0;l<m;l+=1){const p=await o.list({prefix:r,...s===void 0?{}:{cursor:s}});for(const f of p.objects)a.push(f.key.slice(i));if(!p.truncated||p.cursor===void 0)return{entries:a,truncated:!1};s=p.cursor}return{entries:a,truncated:!0}},$=async(o,t,e)=>{const r=g(t),i=E(t,e.path??"");switch(e.op){case"ls":{const{entries:a,truncated:s}=await N(o,i,r);return s?{entries:a,truncated:!0}:{entries:a}}case"read":{const a=await o.head(i);if(a&&a.size>u)throw new c("BAD_REQUEST",`@lunora/agent: fs read: "${e.path??""}" is ${String(a.size)} bytes (max ${String(u)})`);const s=await o.get(i);if(!s)throw new c("NOT_FOUND",`@lunora/agent: fs read: no file at "${e.path??""}"`);return s.text()}case"rm":return await o.delete(i),{path:e.path??"",removed:!0};case"stat":{const a=await o.head(i);return a?{exists:!0,size:a.size}:{exists:!1}}case"write":{const a=e.content??"",s=y.encode(a).length;if(s>u)throw new c("BAD_REQUEST",`@lunora/agent: fs write: ${String(s)} bytes exceeds the max (${String(u)})`);return await o.put(i,a),{bytes:s,path:e.path??"",wrote:!0}}default:throw new c("INTERNAL",`@lunora/agent: sandbox fs op "${e.op}" is not supported`)}},S=()=>({invoke:w.input({args:n.optional(n.array(n.string())),body:n.optional(n.string()),bucket:n.optional(n.string()),command:n.optional(n.string()),content:n.optional(n.string()),fullPage:n.optional(n.boolean()),kind:n.union(n.literal("browser"),n.literal("container"),n.literal("fs")),method:n.optional(n.string()),name:n.optional(n.string()),op:n.string(),path:n.optional(n.string()),root:n.optional(n.string()),selector:n.optional(n.string()),type:n.optional(n.string()),url:n.optional(n.string())}).action(async({args:o,ctx:t})=>{const e=t,r=o;if(r.kind==="browser"){if(!e.browser)throw new c("INTERNAL","@lunora/agent: sandbox browser op needs `ctx.browser` — install @lunora/browser and run codegen");return x(e.browser,r)}if(r.kind==="fs"){const s=e.env?.[r.bucket??""];if(!s||typeof s.get!="function")throw new c("INTERNAL",`@lunora/agent: sandbox fs op found no R2 bucket "${r.bucket??""}" on env — declare the r2_bucket binding in wrangler.jsonc and run codegen`);return $(s,r.root??"",r)}const i=r.name??"",a=e.containers?.[i];if(!a)throw new c("INTERNAL",`@lunora/agent: sandbox container op found no ctx.containers["${i}"] — declare the container in lunora/containers.ts and run codegen`);return T(a,r)})});export{E as resolveFsKey,$ as runFsOp,S as sandboxComponent};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as u,r as t}from"./common-Dck97z3Y.mjs";const r=(o,n)=>typeof o=="string"&&o.length>0?o:n,c=o=>{const{functionId:n,recordInputs:i=!1,Sentry:l}=o;return{executeLanguageModelCall:e=>{const a={"gen_ai.operation.name":r(n,"language_model_call"),"gen_ai.request.model":t(e,"modelId"),"gen_ai.system":t(e,"provider")};return i&&(a["gen_ai.prompt"]=t(e,"messages")),l.startSpan({attributes:a,name:r(n,"language_model_call"),op:"gen_ai.generate"},()=>e.execute())},executeTool:e=>{const a=t(t(e,"toolCall"),"toolName"),s={"gen_ai.operation.name":"execute_tool","gen_ai.tool.call.id":t(e,"toolCallId"),"gen_ai.tool.name":a};return i&&(s["gen_ai.tool.input"]=u(e)),l.startSpan({attributes:s,name:`execute_tool ${r(a,"tool")}`,op:"gen_ai.execute_tool"},()=>e.execute())},onError:e=>{l.captureException(e)}}};export{c as sentryTelemetry};
|
|
@@ -23,7 +23,7 @@ interface AgentStepLike {
|
|
|
23
23
|
/**
|
|
24
24
|
* Durably hibernate until an external event of `type` arrives, then return
|
|
25
25
|
* its payload. Used for human-in-the-loop approvals: a run pauses on
|
|
26
|
-
* `approval
|
|
26
|
+
* `approval:<toolCallId>` until a client resolves it. Like `do`, a resolved
|
|
27
27
|
* wait is memoized — a replay returns the recorded decision without pausing
|
|
28
28
|
* again. Signature mirrors `@lunora/workflow`'s `WorkflowStepLike`.
|
|
29
29
|
*/
|
|
@@ -42,7 +42,7 @@ interface AgentStepLike {
|
|
|
42
42
|
* `idempotencyKey`.
|
|
43
43
|
*
|
|
44
44
|
* The `idempotencyKey` is the deterministic durable-step name
|
|
45
|
-
* (`tool
|
|
45
|
+
* (`tool:<name>:<toolCallId>`). A COMPLETED tool step is never re-run on a
|
|
46
46
|
* workflow replay (native step memoization) — but a step that FAILS mid-body
|
|
47
47
|
* is retried at-least-once, so a side-effecting tool (charge a card, send a
|
|
48
48
|
* mail) must dedupe on this key itself.
|
|
@@ -107,6 +107,17 @@ interface AgentToolContext {
|
|
|
107
107
|
/** The provider-issued tool-call id. */
|
|
108
108
|
toolCallId: string;
|
|
109
109
|
}
|
|
110
|
+
/**
|
|
111
|
+
* The READ-ONLY view of {@link AgentToolContext} handed to a `needsApproval`
|
|
112
|
+
* gate function — every field except `setState`. A gate that mutates thread
|
|
113
|
+
* state is a side effect inside a decision predicate, which this type makes a
|
|
114
|
+
* compile-time error rather than a documented-but-unenforced rule: `getState`
|
|
115
|
+
* and `run` stay available (reads are legitimate gate inputs, and the
|
|
116
|
+
* function form is resolved inside its own durable step, so they are
|
|
117
|
+
* replay-safe there too).
|
|
118
|
+
* @experimental
|
|
119
|
+
*/
|
|
120
|
+
type AgentApprovalContext = Omit<AgentToolContext, "setState">;
|
|
110
121
|
/**
|
|
111
122
|
* An agent tool. Unlike a raw AI SDK tool, `execute` is NOT handed to the
|
|
112
123
|
* model call — the loop runs it itself inside a named durable step so a
|
|
@@ -127,17 +138,23 @@ interface AgentToolDefinition<Input = unknown, Output = unknown> {
|
|
|
127
138
|
* Gate the tool behind a human approval (mirrors the AI SDK's
|
|
128
139
|
* `needsApproval`). When it resolves truthy the durable run PAUSES — the
|
|
129
140
|
* thread moves to `"awaiting_input"` and the workflow hibernates on
|
|
130
|
-
* `approval
|
|
141
|
+
* `approval:<toolCallId>` — until a client calls `agents:agentResolveApproval`.
|
|
131
142
|
* On approve the tool runs exactly as normal; on reject it is skipped and a
|
|
132
143
|
* tool result explaining the rejection is persisted so the next turn recovers.
|
|
133
144
|
* A boolean gates statically; a function gates per input. Default: `false`
|
|
134
|
-
* (unchanged behavior).
|
|
135
|
-
*
|
|
136
|
-
*
|
|
137
|
-
*
|
|
138
|
-
*
|
|
145
|
+
* (unchanged behavior).
|
|
146
|
+
*
|
|
147
|
+
* The boolean/`undefined` forms are compile-time constants re-derived
|
|
148
|
+
* identically on every replay — no durable step. The FUNCTION form runs
|
|
149
|
+
* inside its OWN durable step (`tool:approval-gate:<toolCallId>`, distinct
|
|
150
|
+
* from the tool's own step), so it now runs exactly once per call, not once
|
|
151
|
+
* per replay. It must still be otherwise pure: deterministic given its
|
|
152
|
+
* inputs (no `Date.now()`/`Math.random()`) and free of side effects — the
|
|
153
|
+
* context it receives is {@link AgentApprovalContext}, which has no
|
|
154
|
+
* `setState`; state writes belong only in `execute`, inside the tool's own
|
|
155
|
+
* memoized step.
|
|
139
156
|
*/
|
|
140
|
-
needsApproval?: ((input: Input, context:
|
|
157
|
+
needsApproval?: ((input: Input, context: AgentApprovalContext) => boolean | Promise<boolean>) | boolean;
|
|
141
158
|
}
|
|
142
159
|
/**
|
|
143
160
|
* Author-supplied tool config (see {@link AgentToolDefinition}).
|
|
@@ -252,7 +269,7 @@ interface AgentMemoryOptions {
|
|
|
252
269
|
* (`key: "default"`) from {@link AgentConfig.memory}, then one per skill that
|
|
253
270
|
* carries `knowledge` (keyed by the skill's name). The key names the durable
|
|
254
271
|
* step — the default source keeps the historic `"memory:retrieve"`, a skill
|
|
255
|
-
* source uses `"memory:retrieve
|
|
272
|
+
* source uses `"memory:retrieve:<key>"` — so replay stays deterministic.
|
|
256
273
|
* @experimental
|
|
257
274
|
*/
|
|
258
275
|
interface AgentMemorySource extends AgentMemoryOptions {
|
|
@@ -308,7 +325,7 @@ interface SkillConfig {
|
|
|
308
325
|
knowledge?: AgentMemoryOptions;
|
|
309
326
|
/**
|
|
310
327
|
* The skill's identifier — namespaces this skill's `knowledge` memory source
|
|
311
|
-
* (the durable step `memory:retrieve
|
|
328
|
+
* (the durable step `memory:retrieve:<name>`). Must be identifier-shaped.
|
|
312
329
|
*/
|
|
313
330
|
name: string;
|
|
314
331
|
/**
|
|
@@ -318,6 +335,12 @@ interface SkillConfig {
|
|
|
318
335
|
*/
|
|
319
336
|
tools?: Record<string, AnyAgentTool>;
|
|
320
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">;
|
|
321
344
|
/**
|
|
322
345
|
* A `defineSkill` result — config plus the brand the agent merge checks.
|
|
323
346
|
* @experimental
|
|
@@ -358,7 +381,7 @@ interface AgentStepFinishInfo {
|
|
|
358
381
|
}
|
|
359
382
|
/**
|
|
360
383
|
* Called after each LLM turn with that turn's text, tool calls, and usage. Runs
|
|
361
|
-
* inside a named durable step (`agent:step-finish
|
|
384
|
+
* inside a named durable step (`agent:step-finish:<turn>`) so it fires exactly
|
|
362
385
|
* once per turn even across a workflow replay.
|
|
363
386
|
* @experimental
|
|
364
387
|
*/
|
|
@@ -530,7 +553,7 @@ interface AgentConfig {
|
|
|
530
553
|
model: AgentModelInput;
|
|
531
554
|
/**
|
|
532
555
|
* Optional override for the deployed workflow name (`wrangler.jsonc`
|
|
533
|
-
* `workflows[].name`). Defaults to `agent
|
|
556
|
+
* `workflows[].name`). Defaults to `agent-<kebab-cased export name>`. Does
|
|
534
557
|
* NOT change the binding name, which is always derived from the export
|
|
535
558
|
* name (`support` → `AGENT_SUPPORT`).
|
|
536
559
|
*/
|
|
@@ -577,7 +600,7 @@ interface AgentConfig {
|
|
|
577
600
|
* Opt this agent into being STARTED over the public RPC boundary — i.e. via
|
|
578
601
|
* the auto-registered `agents:agentRun` mutation an HTTP-only client (e.g.
|
|
579
602
|
* the `@lunora/mcp` server) calls. Default `false`: an agent is startable
|
|
580
|
-
* only from server-side app code (`ctx.agents
|
|
603
|
+
* only from server-side app code (`ctx.agents.<name>.run(...)`), so declaring
|
|
581
604
|
* an agent does NOT expose it to arbitrary RPC callers. Fail-closed — the run
|
|
582
605
|
* mutation refuses an agent that has not opted in, regardless of any MCP-side
|
|
583
606
|
* `allowAgents` configuration. A started thread is still owner-scoped to
|
|
@@ -688,7 +711,7 @@ interface AgentAsToolOptions {
|
|
|
688
711
|
/** Cap on child-run status polls before giving up. Default 120. */
|
|
689
712
|
maxPolls?: number;
|
|
690
713
|
/**
|
|
691
|
-
* The child agent's export name — selects its `AGENT_
|
|
714
|
+
* The child agent's export name — selects its `AGENT_<NAME>` Workflow
|
|
692
715
|
* binding (e.g. `"researcher"` → `AGENT_RESEARCHER`). The model-facing tool
|
|
693
716
|
* name is the KEY assigned in the parent's `tools` map, not this.
|
|
694
717
|
*/
|
|
@@ -1078,7 +1101,7 @@ interface AgentRunHandle {
|
|
|
1078
1101
|
id: string;
|
|
1079
1102
|
}
|
|
1080
1103
|
/**
|
|
1081
|
-
* The `ctx.agents
|
|
1104
|
+
* The `ctx.agents.<name>` producer handle.
|
|
1082
1105
|
* @experimental
|
|
1083
1106
|
*/
|
|
1084
1107
|
interface AgentHandle {
|
|
@@ -1111,4 +1134,4 @@ interface AgentHandle {
|
|
|
1111
1134
|
/** Read a run's workflow status by instance id. */
|
|
1112
1135
|
status: (id: string) => Promise<unknown>;
|
|
1113
1136
|
}
|
|
1114
|
-
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 };
|